khtmlview.cpp

00001 /* This file is part of the KDE project
00002  *
00003  * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
00004  *                     1999 Lars Knoll <knoll@kde.org>
00005  *                     1999 Antti Koivisto <koivisto@kde.org>
00006  *                     2000-2004 Dirk Mueller <mueller@kde.org>
00007  *                     2003 Leo Savernik <l.savernik@aon.at>
00008  *                     2003-2004 Apple Computer, Inc.
00009  *
00010  * This library is free software; you can redistribute it and/or
00011  * modify it under the terms of the GNU Library General Public
00012  * License as published by the Free Software Foundation; either
00013  * version 2 of the License, or (at your option) any later version.
00014  *
00015  * This library is distributed in the hope that it will be useful,
00016  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00017  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00018  * Library General Public License for more details.
00019  *
00020  * You should have received a copy of the GNU Library General Public License
00021  * along with this library; see the file COPYING.LIB.  If not, write to
00022  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00023  * Boston, MA 02110-1301, USA.
00024  */
00025 
00026 
00027 #include "khtmlview.moc"
00028 
00029 #include "khtmlview.h"
00030 
00031 #include "khtml_part.h"
00032 #include "khtml_events.h"
00033 
00034 #include "html/html_documentimpl.h"
00035 #include "html/html_inlineimpl.h"
00036 #include "html/html_formimpl.h"
00037 #include "rendering/render_arena.h"
00038 #include "rendering/render_canvas.h"
00039 #include "rendering/render_frames.h"
00040 #include "rendering/render_replaced.h"
00041 #include "rendering/render_layer.h"
00042 #include "rendering/render_line.h"
00043 #include "rendering/render_table.h"
00044 // removeme
00045 #define protected public
00046 #include "rendering/render_text.h"
00047 #undef protected
00048 #include "xml/dom2_eventsimpl.h"
00049 #include "css/cssstyleselector.h"
00050 #include "css/csshelper.h"
00051 #include "misc/htmlhashes.h"
00052 #include "misc/helper.h"
00053 #include "misc/loader.h"
00054 #include "khtml_settings.h"
00055 #include "khtml_printsettings.h"
00056 
00057 #include "khtmlpart_p.h"
00058 
00059 #ifndef KHTML_NO_CARET
00060 #include "khtml_caret_p.h"
00061 #include "xml/dom2_rangeimpl.h"
00062 #endif
00063 
00064 #include <kapplication.h>
00065 #include <kcursor.h>
00066 #include <kdebug.h>
00067 #include <kdialogbase.h>
00068 #include <kiconloader.h>
00069 #include <kimageio.h>
00070 #include <klocale.h>
00071 #include <knotifyclient.h>
00072 #include <kprinter.h>
00073 #include <ksimpleconfig.h>
00074 #include <kstandarddirs.h>
00075 #include <kstdaccel.h>
00076 #include <kstringhandler.h>
00077 #include <kurldrag.h>
00078 
00079 #include <qbitmap.h>
00080 #include <qlabel.h>
00081 #include <qobjectlist.h>
00082 #include <qpaintdevicemetrics.h>
00083 #include <qpainter.h>
00084 #include <qptrdict.h>
00085 #include <qtooltip.h>
00086 #include <qstring.h>
00087 #include <qstylesheet.h>
00088 #include <qtimer.h>
00089 #include <qvaluevector.h>
00090 
00091 //#define DEBUG_NO_PAINT_BUFFER
00092 
00093 //#define DEBUG_FLICKER
00094 
00095 //#define DEBUG_PIXEL
00096 
00097 #ifdef Q_WS_X11
00098 #include <X11/Xlib.h>
00099 #include <fixx11h.h>
00100 #endif
00101 
00102 #define PAINT_BUFFER_HEIGHT 128
00103 
00104 #if 0
00105 namespace khtml {
00106     void dumpLineBoxes(RenderFlow *flow);
00107 }
00108 #endif
00109 
00110 using namespace DOM;
00111 using namespace khtml;
00112 class KHTMLToolTip;
00113 
00114 
00115 #ifndef QT_NO_TOOLTIP
00116 
00117 class KHTMLToolTip : public QToolTip
00118 {
00119 public:
00120     KHTMLToolTip(KHTMLView *view,  KHTMLViewPrivate* vp) : QToolTip(view->viewport())
00121     {
00122         m_view = view;
00123         m_viewprivate = vp;
00124     };
00125 
00126 protected:
00127     virtual void maybeTip(const QPoint &);
00128 
00129 private:
00130     KHTMLView *m_view;
00131     KHTMLViewPrivate* m_viewprivate;
00132 };
00133 
00134 #endif
00135 
00136 class KHTMLViewPrivate {
00137     friend class KHTMLToolTip;
00138 public:
00139 
00140     enum PseudoFocusNodes {
00141     PFNone,
00142     PFTop,
00143     PFBottom
00144     };
00145 
00146     enum CompletedState {
00147         CSNone = 0,
00148         CSFull,
00149         CSActionPending
00150     };
00151 
00152     KHTMLViewPrivate()
00153         : underMouse( 0 ), underMouseNonShared( 0 ), visibleWidgets( 107 )
00154 #ifndef NO_SMOOTH_SCROLL_HACK
00155           , dx(0), dy(0), ddx(0), ddy(0), rdx(0), rdy(0), scrolling(false)
00156 #endif
00157     {
00158 #ifndef KHTML_NO_CARET
00159     m_caretViewContext = 0;
00160     m_editorContext = 0;
00161 #endif // KHTML_NO_CARET
00162         postponed_autorepeat = NULL;
00163         reset();
00164         vmode = QScrollView::Auto;
00165     hmode = QScrollView::Auto;
00166         tp=0;
00167         paintBuffer=0;
00168         vertPaintBuffer=0;
00169         formCompletions=0;
00170         prevScrollbarVisible = true;
00171     tooltip = 0;
00172         possibleTripleClick = false;
00173         emitCompletedAfterRepaint = CSNone;
00174     cursor_icon_widget = NULL;
00175         m_mouseScrollTimer = 0;
00176         m_mouseScrollIndicator = 0;
00177     }
00178     ~KHTMLViewPrivate()
00179     {
00180         delete formCompletions;
00181         delete tp; tp = 0;
00182         delete paintBuffer; paintBuffer =0;
00183         delete vertPaintBuffer;
00184         delete postponed_autorepeat;
00185         if (underMouse)
00186         underMouse->deref();
00187         if (underMouseNonShared)
00188         underMouseNonShared->deref();
00189     delete tooltip;
00190 #ifndef KHTML_NO_CARET
00191     delete m_caretViewContext;
00192     delete m_editorContext;
00193 #endif // KHTML_NO_CARET
00194         delete cursor_icon_widget;
00195         delete m_mouseScrollTimer;
00196         delete m_mouseScrollIndicator;
00197     }
00198     void reset()
00199     {
00200         if (underMouse)
00201         underMouse->deref();
00202     underMouse = 0;
00203         if (underMouseNonShared)
00204         underMouseNonShared->deref();
00205     underMouseNonShared = 0;
00206         linkPressed = false;
00207         useSlowRepaints = false;
00208     tabMovePending = false;
00209     lastTabbingDirection = true;
00210     pseudoFocusNode = PFNone;
00211 #ifndef KHTML_NO_SCROLLBARS
00212         //We don't turn off the toolbars here
00213     //since if the user turns them
00214     //off, then chances are they want them turned
00215     //off always - even after a reset.
00216 #else
00217         vmode = QScrollView::AlwaysOff;
00218         hmode = QScrollView::AlwaysOff;
00219 #endif
00220 #ifdef DEBUG_PIXEL
00221         timer.start();
00222         pixelbooth = 0;
00223         repaintbooth = 0;
00224 #endif
00225         scrollBarMoved = false;
00226         contentsMoving = false;
00227         ignoreWheelEvents = false;
00228     borderX = 30;
00229     borderY = 30;
00230         paged = false;
00231     clickX = -1;
00232     clickY = -1;
00233         prevMouseX = -1;
00234         prevMouseY = -1;
00235     clickCount = 0;
00236     isDoubleClick = false;
00237     scrollingSelf = false;
00238         delete postponed_autorepeat;
00239         postponed_autorepeat = NULL;
00240     layoutTimerId = 0;
00241         repaintTimerId = 0;
00242         scrollTimerId = 0;
00243         scrollSuspended = false;
00244         scrollSuspendPreActivate = false;
00245         complete = false;
00246         firstRelayout = true;
00247         needsFullRepaint = true;
00248         dirtyLayout = false;
00249         layoutSchedulingEnabled = true;
00250         painting = false;
00251         updateRegion = QRegion();
00252         m_dialogsAllowed = true;
00253 #ifndef KHTML_NO_CARET
00254         if (m_caretViewContext) {
00255           m_caretViewContext->caretMoved = false;
00256       m_caretViewContext->keyReleasePending = false;
00257         }/*end if*/
00258 #endif // KHTML_NO_CARET
00259 #ifndef KHTML_NO_TYPE_AHEAD_FIND
00260         typeAheadActivated = false;
00261 #endif // KHTML_NO_TYPE_AHEAD_FIND
00262     accessKeysActivated = false;
00263     accessKeysPreActivate = false;
00264 
00265         // We ref/deref to ensure defaultHTMLSettings is available
00266         KHTMLFactory::ref();
00267         accessKeysEnabled = KHTMLFactory::defaultHTMLSettings()->accessKeysEnabled();
00268         KHTMLFactory::deref();
00269 
00270         emitCompletedAfterRepaint = CSNone;
00271     }
00272     void newScrollTimer(QWidget *view, int tid)
00273     {
00274         //kdDebug(6000) << "newScrollTimer timer " << tid << endl;
00275         view->killTimer(scrollTimerId);
00276         scrollTimerId = tid;
00277         scrollSuspended = false;
00278     }
00279     enum ScrollDirection { ScrollLeft, ScrollRight, ScrollUp, ScrollDown };
00280 
00281     void adjustScroller(QWidget *view, ScrollDirection direction, ScrollDirection oppositedir)
00282     {
00283         static const struct { int msec, pixels; } timings [] = {
00284             {320,1}, {224,1}, {160,1}, {112,1}, {80,1}, {56,1}, {40,1},
00285             {28,1}, {20,1}, {20,2}, {20,3}, {20,4}, {20,6}, {20,8}, {0,0}
00286         };
00287         if (!scrollTimerId ||
00288             (static_cast<int>(scrollDirection) != direction &&
00289              (static_cast<int>(scrollDirection) != oppositedir || scrollSuspended))) {
00290             scrollTiming = 6;
00291             scrollBy = timings[scrollTiming].pixels;
00292             scrollDirection = direction;
00293             newScrollTimer(view, view->startTimer(timings[scrollTiming].msec));
00294         } else if (scrollDirection == direction &&
00295                    timings[scrollTiming+1].msec && !scrollSuspended) {
00296             scrollBy = timings[++scrollTiming].pixels;
00297             newScrollTimer(view, view->startTimer(timings[scrollTiming].msec));
00298         } else if (scrollDirection == oppositedir) {
00299             if (scrollTiming) {
00300                 scrollBy = timings[--scrollTiming].pixels;
00301                 newScrollTimer(view, view->startTimer(timings[scrollTiming].msec));
00302             }
00303         }
00304         scrollSuspended = false;
00305     }
00306 
00307 #ifndef KHTML_NO_CARET
00308 
00311     CaretViewContext *caretViewContext() {
00312       if (!m_caretViewContext) m_caretViewContext = new CaretViewContext();
00313       return m_caretViewContext;
00314     }
00318     EditorContext *editorContext() {
00319       if (!m_editorContext) m_editorContext = new EditorContext();
00320       return m_editorContext;
00321     }
00322 #endif // KHTML_NO_CARET
00323 
00324 #ifdef DEBUG_PIXEL
00325     QTime timer;
00326     unsigned int pixelbooth;
00327     unsigned int repaintbooth;
00328 #endif
00329 
00330     QPainter *tp;
00331     QPixmap  *paintBuffer;
00332     QPixmap  *vertPaintBuffer;
00333     NodeImpl *underMouse;
00334     NodeImpl *underMouseNonShared;
00335 
00336     bool tabMovePending:1;
00337     bool lastTabbingDirection:1;
00338     PseudoFocusNodes pseudoFocusNode:2;
00339     bool scrollBarMoved:1;
00340     bool contentsMoving:1;
00341 
00342     QScrollView::ScrollBarMode vmode;
00343     QScrollView::ScrollBarMode hmode;
00344     bool prevScrollbarVisible:1;
00345     bool linkPressed:1;
00346     bool useSlowRepaints:1;
00347     bool ignoreWheelEvents:1;
00348 
00349     int borderX, borderY;
00350     KSimpleConfig *formCompletions;
00351 
00352     bool paged;
00353 
00354     int clickX, clickY, clickCount;
00355     bool isDoubleClick;
00356 
00357     int prevMouseX, prevMouseY;
00358     bool scrollingSelf;
00359     int layoutTimerId;
00360     QKeyEvent* postponed_autorepeat;
00361 
00362     int repaintTimerId;
00363     int scrollTimerId;
00364     int scrollTiming;
00365     int scrollBy;
00366     ScrollDirection scrollDirection     :2;
00367     bool scrollSuspended            :1;
00368     bool scrollSuspendPreActivate       :1;
00369     bool complete               :1;
00370     bool firstRelayout              :1;
00371     bool layoutSchedulingEnabled        :1;
00372     bool needsFullRepaint           :1;
00373     bool painting               :1;
00374     bool possibleTripleClick            :1;
00375     bool dirtyLayout                           :1;
00376     bool m_dialogsAllowed           :1;
00377     QRegion updateRegion;
00378     KHTMLToolTip *tooltip;
00379     QPtrDict<QWidget> visibleWidgets;
00380 #ifndef KHTML_NO_CARET
00381     CaretViewContext *m_caretViewContext;
00382     EditorContext *m_editorContext;
00383 #endif // KHTML_NO_CARET
00384 #ifndef KHTML_NO_TYPE_AHEAD_FIND
00385     QString findString;
00386     QTimer timer;
00387     bool findLinksOnly;
00388     bool typeAheadActivated;
00389 #endif // KHTML_NO_TYPE_AHEAD_FIND
00390     bool accessKeysEnabled;
00391     bool accessKeysActivated;
00392     bool accessKeysPreActivate;
00393     CompletedState emitCompletedAfterRepaint;
00394 
00395     QWidget* cursor_icon_widget;
00396 
00397     // scrolling activated by MMB
00398     short m_mouseScroll_byX;
00399     short m_mouseScroll_byY;
00400     QTimer *m_mouseScrollTimer;
00401     QWidget *m_mouseScrollIndicator;
00402 #ifndef NO_SMOOTH_SCROLL_HACK
00403     QTimer timer2;
00404     int dx;
00405     int dy;
00406     // Step size * 16 and residual to avoid huge difference between 1px/step and 2px/step
00407     int ddx;
00408     int ddy;
00409     int rdx;
00410     int rdy;
00411     bool scrolling;
00412 #endif
00413 
00414 };
00415 
00416 #ifndef QT_NO_TOOLTIP
00417 
00427 static bool findImageMapRect(HTMLImageElementImpl *img, const QPoint &scrollOfs,
00428             const QPoint &p, QRect &r, QString &s)
00429 {
00430     HTMLMapElementImpl* map;
00431     if (img && img->getDocument()->isHTMLDocument() &&
00432         (map = static_cast<HTMLDocumentImpl*>(img->getDocument())->getMap(img->imageMap()))) {
00433         RenderObject::NodeInfo info(true, false);
00434         RenderObject *rend = img->renderer();
00435         int ax, ay;
00436         if (!rend || !rend->absolutePosition(ax, ay))
00437             return false;
00438         // we're a client side image map
00439         bool inside = map->mapMouseEvent(p.x() - ax + scrollOfs.x(),
00440                 p.y() - ay + scrollOfs.y(), rend->contentWidth(),
00441                 rend->contentHeight(), info);
00442         if (inside && info.URLElement()) {
00443             HTMLAreaElementImpl *area = static_cast<HTMLAreaElementImpl *>(info.URLElement());
00444             Q_ASSERT(area->id() == ID_AREA);
00445             s = area->getAttribute(ATTR_TITLE).string();
00446             QRegion reg = area->cachedRegion();
00447             if (!s.isEmpty() && !reg.isEmpty()) {
00448                 r = reg.boundingRect();
00449                 r.moveBy(ax, ay);
00450                 return true;
00451             }
00452         }
00453     }
00454     return false;
00455 }
00456 
00457 void KHTMLToolTip::maybeTip(const QPoint& p)
00458 {
00459     DOM::NodeImpl *node = m_viewprivate->underMouseNonShared;
00460     QRect region;
00461     while ( node ) {
00462         if ( node->isElementNode() ) {
00463             DOM::ElementImpl *e = static_cast<DOM::ElementImpl*>( node );
00464             QRect r;
00465             QString s;
00466             bool found = false;
00467             // for images, check if it is part of a client-side image map,
00468             // and query the <area>s' title attributes, too
00469             if (e->id() == ID_IMG && !e->getAttribute( ATTR_USEMAP ).isEmpty()) {
00470                 found = findImageMapRect(static_cast<HTMLImageElementImpl *>(e),
00471                             m_view->viewportToContents(QPoint(0, 0)), p, r, s);
00472             }
00473             if (!found) {
00474                 s = e->getAttribute( ATTR_TITLE ).string();
00475                 r = node->getRect();
00476             }
00477             region |= QRect( m_view->contentsToViewport( r.topLeft() ), r.size() );
00478             if ( !s.isEmpty() ) {
00479                 tip( region, QStyleSheet::convertFromPlainText( s, QStyleSheetItem::WhiteSpaceNormal ) );
00480                 break;
00481             }
00482         }
00483         node = node->parentNode();
00484     }
00485 }
00486 #endif
00487 
00488 KHTMLView::KHTMLView( KHTMLPart *part, QWidget *parent, const char *name)
00489     : QScrollView( parent, name, WResizeNoErase | WRepaintNoErase )
00490 {
00491     m_medium = "screen";
00492 
00493     m_part = part;
00494     d = new KHTMLViewPrivate;
00495     QScrollView::setVScrollBarMode(d->vmode);
00496     QScrollView::setHScrollBarMode(d->hmode);
00497     connect(kapp, SIGNAL(kdisplayPaletteChanged()), this, SLOT(slotPaletteChanged()));
00498     connect(this, SIGNAL(contentsMoving(int, int)), this, SLOT(slotScrollBarMoved()));
00499 
00500     // initialize QScrollView
00501     enableClipper(true);
00502     // hack to get unclipped painting on the viewport.
00503     static_cast<KHTMLView *>(static_cast<QWidget *>(viewport()))->setWFlags(WPaintUnclipped);
00504 
00505     setResizePolicy(Manual);
00506     viewport()->setMouseTracking(true);
00507     viewport()->setBackgroundMode(NoBackground);
00508 
00509     KImageIO::registerFormats();
00510 
00511 #ifndef QT_NO_TOOLTIP
00512     d->tooltip = new KHTMLToolTip( this, d );
00513 #endif
00514 
00515 #ifndef KHTML_NO_TYPE_AHEAD_FIND
00516     connect(&d->timer, SIGNAL(timeout()), this, SLOT(findTimeout()));
00517 #endif // KHTML_NO_TYPE_AHEAD_FIND
00518 
00519     init();
00520 
00521     viewport()->show();
00522 #ifndef NO_SMOOTH_SCROLL_HACK
00523 #define timer timer2
00524     connect(&d->timer, SIGNAL(timeout()), this, SLOT(scrollTick()));
00525 #undef timer
00526 #endif
00527 
00528 }
00529 
00530 KHTMLView::~KHTMLView()
00531 {
00532     closeChildDialogs();
00533     if (m_part)
00534     {
00535         //WABA: Is this Ok? Do I need to deref it as well?
00536         //Does this need to be done somewhere else?
00537         DOM::DocumentImpl *doc = m_part->xmlDocImpl();
00538         if (doc)
00539             doc->detach();
00540     }
00541     delete d; d = 0;
00542 }
00543 
00544 void KHTMLView::init()
00545 {
00546     if(!d->paintBuffer) d->paintBuffer = new QPixmap(PAINT_BUFFER_HEIGHT, PAINT_BUFFER_HEIGHT);
00547     if(!d->vertPaintBuffer)
00548         d->vertPaintBuffer = new QPixmap(10, PAINT_BUFFER_HEIGHT);
00549     if(!d->tp) d->tp = new QPainter();
00550 
00551     setFocusPolicy(QWidget::StrongFocus);
00552     viewport()->setFocusProxy(this);
00553 
00554     _marginWidth = -1; // undefined
00555     _marginHeight = -1;
00556     _width = 0;
00557     _height = 0;
00558 
00559     installEventFilter(this);
00560 
00561     setAcceptDrops(true);
00562     QSize s = viewportSize(4095, 4095);
00563     resizeContents(s.width(), s.height());
00564 }
00565 
00566 void KHTMLView::clear()
00567 {
00568     // work around QScrollview's unbelievable bugginess
00569     setStaticBackground(true);
00570 #ifndef KHTML_NO_CARET
00571     if (!m_part->isCaretMode() && !m_part->isEditable()) caretOff();
00572 #endif
00573 
00574 #ifndef KHTML_NO_TYPE_AHEAD_FIND
00575     if( d->typeAheadActivated )
00576         findTimeout();
00577 #endif
00578     if (d->accessKeysEnabled && d->accessKeysActivated)
00579         accessKeysTimeout();
00580     viewport()->unsetCursor();
00581     if ( d->cursor_icon_widget )
00582         d->cursor_icon_widget->hide();
00583     d->reset();
00584     killTimers();
00585     emit cleared();
00586 
00587     QScrollView::setHScrollBarMode(d->hmode);
00588     QScrollView::setVScrollBarMode(d->vmode);
00589     verticalScrollBar()->setEnabled( false );
00590     horizontalScrollBar()->setEnabled( false );
00591 }
00592 
00593 void KHTMLView::hideEvent(QHideEvent* e)
00594 {
00595     QScrollView::hideEvent(e);
00596     if ( m_part && m_part->xmlDocImpl() )
00597         m_part->xmlDocImpl()->docLoader()->pauseAnimations();
00598 }
00599 
00600 void KHTMLView::showEvent(QShowEvent* e)
00601 {
00602     QScrollView::showEvent(e);
00603     if ( m_part && m_part->xmlDocImpl() )
00604         m_part->xmlDocImpl()->docLoader()->resumeAnimations();
00605 }
00606 
00607 void KHTMLView::resizeEvent (QResizeEvent* e)
00608 {
00609     int dw = e->oldSize().width() - e->size().width();
00610     int dh = e->oldSize().height() - e->size().height();
00611 
00612     // if we are shrinking the view, don't allow the content to overflow
00613     // before the layout occurs - we don't know if we need scrollbars yet
00614     dw = dw>0 ? kMax(0, contentsWidth()-dw) : contentsWidth();
00615     dh = dh>0 ? kMax(0, contentsHeight()-dh) : contentsHeight();
00616 
00617     resizeContents(dw, dh);
00618 
00619     QScrollView::resizeEvent(e);
00620 
00621     if ( m_part && m_part->xmlDocImpl() )
00622         m_part->xmlDocImpl()->dispatchWindowEvent( EventImpl::RESIZE_EVENT, false, false );
00623 }
00624 
00625 void KHTMLView::viewportResizeEvent (QResizeEvent* e)
00626 {
00627     QScrollView::viewportResizeEvent(e);
00628 
00629     //int w = visibleWidth();
00630     //int h = visibleHeight();
00631 
00632     if (d->layoutSchedulingEnabled)
00633         layout();
00634 #ifndef KHTML_NO_CARET
00635     else {
00636         hideCaret();
00637         recalcAndStoreCaretPos();
00638     showCaret();
00639     }/*end if*/
00640 #endif
00641 
00642     KApplication::sendPostedEvents(viewport(), QEvent::Paint);
00643 }
00644 
00645 // this is to get rid of a compiler virtual overload mismatch warning. do not remove
00646 void KHTMLView::drawContents( QPainter*)
00647 {
00648 }
00649 
00650 void KHTMLView::drawContents( QPainter *p, int ex, int ey, int ew, int eh )
00651 {
00652 #ifdef DEBUG_PIXEL
00653 
00654     if ( d->timer.elapsed() > 5000 ) {
00655         qDebug( "drawed %d pixels in %d repaints the last %d milliseconds",
00656                 d->pixelbooth, d->repaintbooth,  d->timer.elapsed() );
00657         d->timer.restart();
00658         d->pixelbooth = 0;
00659         d->repaintbooth = 0;
00660     }
00661     d->pixelbooth += ew*eh;
00662     d->repaintbooth++;
00663 #endif
00664 
00665     //kdDebug( 6000 ) << "drawContents this="<< this <<" x=" << ex << ",y=" << ey << ",w=" << ew << ",h=" << eh << endl;
00666     if(!m_part || !m_part->xmlDocImpl() || !m_part->xmlDocImpl()->renderer()) {
00667         p->fillRect(ex, ey, ew, eh, palette().active().brush(QColorGroup::Base));
00668         return;
00669     } else if ( d->complete && static_cast<RenderCanvas*>(m_part->xmlDocImpl()->renderer())->needsLayout() ) {
00670         // an external update request happens while we have a layout scheduled
00671         unscheduleRelayout();
00672         layout();
00673     }
00674 
00675     if (d->painting) {
00676         kdDebug( 6000 ) << "WARNING: drawContents reentered! " << endl;
00677         return;
00678     }
00679     d->painting = true;
00680 
00681     QPoint pt = contentsToViewport(QPoint(ex, ey));
00682     QRegion cr = QRect(pt.x(), pt.y(), ew, eh);
00683 
00684     // kdDebug(6000) << "clip rect: " << QRect(pt.x(), pt.y(), ew, eh) << endl;
00685     for (QPtrDictIterator<QWidget> it(d->visibleWidgets); it.current(); ++it) {
00686     QWidget *w = it.current();
00687     RenderWidget* rw = static_cast<RenderWidget*>( it.currentKey() );
00688     if (w && rw && !rw->isKHTMLWidget()) {
00689             int x, y;
00690             rw->absolutePosition(x, y);
00691             contentsToViewport(x, y, x, y);
00692             int pbx = rw->borderLeft()+rw->paddingLeft();
00693             int pby = rw->borderTop()+rw->paddingTop();
00694             QRect g = QRect(x+pbx, y+pby,
00695                             rw->width()-pbx-rw->borderRight()-rw->paddingRight(),
00696                             rw->height()-pby-rw->borderBottom()-rw->paddingBottom());
00697             if ( !rw->isFrame() && ((g.top() > pt.y()+eh) || (g.bottom() <= pt.y()) ||
00698                                     (g.right() <= pt.x()) || (g.left() > pt.x()+ew) ))
00699                 continue;
00700             RenderLayer* rl = rw->needsMask() ? rw->enclosingStackingContext() : 0;
00701             QRegion mask = rl ? rl->getMask() : QRegion();
00702             if (!mask.isNull()) {
00703                 QPoint o(0,0);
00704                 o = contentsToViewport(o);
00705                 mask.translate(o.x(),o.y());
00706                 mask = mask.intersect( QRect(g.x(),g.y(),g.width(),g.height()) );
00707                 cr -= mask;
00708             } else {
00709                 cr -= g;
00710             }
00711         }
00712     }
00713 
00714 #if 0
00715     // this is commonly the case with framesets. we still do
00716     // want to paint them, otherwise the widgets don't get placed.
00717     if (cr.isEmpty()) {
00718         d->painting = false;
00719     return;
00720     }
00721 #endif
00722 
00723 #ifndef DEBUG_NO_PAINT_BUFFER
00724     p->setClipRegion(cr);
00725 
00726     if (eh > PAINT_BUFFER_HEIGHT && ew <= 10) {
00727         if ( d->vertPaintBuffer->height() < visibleHeight() )
00728             d->vertPaintBuffer->resize(10, visibleHeight());
00729         d->tp->begin(d->vertPaintBuffer);
00730         d->tp->translate(-ex, -ey);
00731         d->tp->fillRect(ex, ey, ew, eh, palette().active().brush(QColorGroup::Base));
00732         m_part->xmlDocImpl()->renderer()->layer()->paint(d->tp, QRect(ex, ey, ew, eh));
00733         d->tp->end();
00734     p->drawPixmap(ex, ey, *d->vertPaintBuffer, 0, 0, ew, eh);
00735     }
00736     else {
00737         if ( d->paintBuffer->width() < visibleWidth() )
00738             d->paintBuffer->resize(visibleWidth(),PAINT_BUFFER_HEIGHT);
00739 
00740         int py=0;
00741         while (py < eh) {
00742             int ph = eh-py < PAINT_BUFFER_HEIGHT ? eh-py : PAINT_BUFFER_HEIGHT;
00743             d->tp->begin(d->paintBuffer);
00744             d->tp->translate(-ex, -ey-py);
00745             d->tp->fillRect(ex, ey+py, ew, ph, palette().active().brush(QColorGroup::Base));
00746             m_part->xmlDocImpl()->renderer()->layer()->paint(d->tp, QRect(ex, ey+py, ew, ph));
00747             d->tp->end();
00748 
00749         p->drawPixmap(ex, ey+py, *d->paintBuffer, 0, 0, ew, ph);
00750             py += PAINT_BUFFER_HEIGHT;
00751         }
00752     }
00753 #else // !DEBUG_NO_PAINT_BUFFER
00754 static int cnt=0;
00755     ex = contentsX(); ey = contentsY();
00756     ew = visibleWidth(); eh = visibleHeight();
00757     QRect pr(ex,ey,ew,eh);
00758     kdDebug() << "[" << ++cnt << "]" << " clip region: " << pr << endl;
00759 //  p->setClipRegion(QRect(0,0,ew,eh));
00760 //        p->translate(-ex, -ey);
00761         p->fillRect(ex, ey, ew, eh, palette().active().brush(QColorGroup::Base));
00762         m_part->xmlDocImpl()->renderer()->layer()->paint(p, pr);
00763 #endif // DEBUG_NO_PAINT_BUFFER
00764 
00765 #ifndef KHTML_NO_CARET
00766     if (d->m_caretViewContext && d->m_caretViewContext->visible) {
00767         QRect pos(d->m_caretViewContext->x, d->m_caretViewContext->y,
00768         d->m_caretViewContext->width, d->m_caretViewContext->height);
00769         if (pos.intersects(QRect(ex, ey, ew, eh))) {
00770             p->setRasterOp(XorROP);
00771         p->setPen(white);
00772         if (pos.width() == 1)
00773               p->drawLine(pos.topLeft(), pos.bottomRight());
00774         else {
00775           p->fillRect(pos, white);
00776         }/*end if*/
00777     }/*end if*/
00778     }/*end if*/
00779 #endif // KHTML_NO_CARET
00780 
00781 //    p->setPen(QPen(magenta,0,DashDotDotLine));
00782 //    p->drawRect(dbg_paint_rect);
00783 
00784     khtml::DrawContentsEvent event( p, ex, ey, ew, eh );
00785     QApplication::sendEvent( m_part, &event );
00786 
00787     if (d->scrollingSelf || d->contentsMoving || cr.contains(viewport()->mapFromGlobal(QCursor::pos()))) {
00788         QMouseEvent *tempEvent = new QMouseEvent( QEvent::MouseMove, viewport()->mapFromGlobal( QCursor::pos() ), Qt::NoButton, Qt::NoButton );
00789         viewportMouseMoveEvent( tempEvent );
00790         delete tempEvent;
00791     }
00792 
00793     d->painting = false;
00794 }
00795 
00796 void KHTMLView::setMarginWidth(int w)
00797 {
00798     // make it update the rendering area when set
00799     _marginWidth = w;
00800 }
00801 
00802 void KHTMLView::setMarginHeight(int h)
00803 {
00804     // make it update the rendering area when set
00805     _marginHeight = h;
00806 }
00807 
00808 void KHTMLView::layout()
00809 {
00810     if( m_part && m_part->xmlDocImpl() ) {
00811         DOM::DocumentImpl *document = m_part->xmlDocImpl();
00812 
00813         khtml::RenderCanvas* canvas = static_cast<khtml::RenderCanvas *>(document->renderer());
00814         if ( !canvas ) return;
00815 
00816         d->layoutSchedulingEnabled=false;
00817 
00818         // the reference object for the overflow property on canvas
00819         RenderObject * ref = 0;
00820         RenderObject* root = document->documentElement() ? document->documentElement()->renderer() : 0;
00821 
00822         if (document->isHTMLDocument()) {
00823              NodeImpl *body = static_cast<HTMLDocumentImpl*>(document)->body();
00824              if(body && body->renderer() && body->id() == ID_FRAMESET) {
00825                  QScrollView::setVScrollBarMode(AlwaysOff);
00826                  QScrollView::setHScrollBarMode(AlwaysOff);
00827                  body->renderer()->setNeedsLayout(true);
00828 //                  if (d->tooltip) {
00829 //                      delete d->tooltip;
00830 //                      d->tooltip = 0;
00831 //                  }
00832              }
00833              else {
00834                  if (!d->tooltip)
00835                      d->tooltip = new KHTMLToolTip( this, d );
00836                  // only apply body's overflow to canvas if root as a visible overflow
00837                  if (root)
00838                      ref = (!body || root->style()->hidesOverflow()) ? root : body->renderer();
00839              }
00840         } else {
00841             ref = root;
00842         }
00843 
00844         if (ref) {
00845             if( ref->style()->overflowX() == OHIDDEN )
00846                 if (d->hmode == Auto) QScrollView::setHScrollBarMode(AlwaysOff);
00847             else
00848                 if (QScrollView::hScrollBarMode() == AlwaysOff) QScrollView::setHScrollBarMode(d->hmode);
00849             if ( ref->style()->overflowY() == OHIDDEN )
00850                 if (d->vmode == Auto) QScrollView::setVScrollBarMode(AlwaysOff);
00851             else
00852                 if (QScrollView::vScrollBarMode() == AlwaysOff) QScrollView::setVScrollBarMode(d->vmode);
00853         }
00854         d->needsFullRepaint = d->firstRelayout;
00855         if (_height !=  visibleHeight() || _width != visibleWidth()) {;
00856             d->needsFullRepaint = true;
00857             _height = visibleHeight();
00858             _width = visibleWidth();
00859         }
00860         //QTime qt;
00861         //qt.start();
00862         canvas->layout();
00863 
00864         emit finishedLayout();
00865         if (d->firstRelayout) {
00866             // make sure firstRelayout is set to false now in case this layout
00867             // wasn't scheduled
00868             d->firstRelayout = false;
00869             verticalScrollBar()->setEnabled( true );
00870             horizontalScrollBar()->setEnabled( true );
00871         }
00872 #if 0
00873     ElementImpl *listitem = m_part->xmlDocImpl()->getElementById("__test_element__");
00874     if (listitem) kdDebug(6000) << "after layout, before repaint" << endl;
00875     if (listitem) dumpLineBoxes(static_cast<RenderFlow *>(listitem->renderer()));
00876 #endif
00877 #ifndef KHTML_NO_CARET
00878         hideCaret();
00879         if ((m_part->isCaretMode() || m_part->isEditable())
00880             && !d->complete && d->m_caretViewContext
00881                 && !d->m_caretViewContext->caretMoved) {
00882             initCaret();
00883         } else {
00884         recalcAndStoreCaretPos();
00885         showCaret();
00886         }/*end if*/
00887 #endif
00888         if (d->accessKeysEnabled && d->accessKeysActivated) {
00889             emit hideAccessKeys();
00890             displayAccessKeys();
00891         }
00892         //kdDebug( 6000 ) << "TIME: layout() dt=" << qt.elapsed() << endl;
00893     }
00894     else
00895        _width = visibleWidth();
00896 
00897     killTimer(d->layoutTimerId);
00898     d->layoutTimerId = 0;
00899     d->layoutSchedulingEnabled=true;
00900 }
00901 
00902 void KHTMLView::closeChildDialogs()
00903 {
00904     QObjectList *dlgs = queryList("QDialog");
00905     for (QObject *dlg = dlgs->first(); dlg; dlg = dlgs->next())
00906     {
00907         KDialogBase* dlgbase = dynamic_cast<KDialogBase *>( dlg );
00908         if ( dlgbase ) {
00909             if ( dlgbase->testWFlags( WShowModal ) ) {
00910                 kdDebug(6000) << "closeChildDialogs: closing dialog " << dlgbase << endl;
00911                 // close() ends up calling QButton::animateClick, which isn't immediate
00912                 // we need something the exits the event loop immediately (#49068)
00913                 dlgbase->cancel();
00914             }
00915         }
00916         else
00917         {
00918             kdWarning() << "closeChildDialogs: not a KDialogBase! Don't use QDialogs in KDE! " << static_cast<QWidget*>(dlg) << endl;
00919             static_cast<QWidget*>(dlg)->hide();
00920         }
00921     }
00922     delete dlgs;
00923     d->m_dialogsAllowed = false;
00924 }
00925 
00926 bool KHTMLView::dialogsAllowed() {
00927     bool allowed = d->m_dialogsAllowed;
00928     KHTMLPart* p = m_part->parentPart();
00929     if (p && p->view())
00930         allowed &= p->view()->dialogsAllowed();
00931     return allowed;
00932 }
00933 
00934 void KHTMLView::closeEvent( QCloseEvent* ev )
00935 {
00936     closeChildDialogs();
00937     QScrollView::closeEvent( ev );
00938 }
00939 
00940 //
00941 // Event Handling
00942 //
00944 
00945 void KHTMLView::viewportMousePressEvent( QMouseEvent *_mouse )
00946 {
00947     if (!m_part->xmlDocImpl()) return;
00948     if (d->possibleTripleClick && ( _mouse->button() & MouseButtonMask ) == LeftButton)
00949     {
00950         viewportMouseDoubleClickEvent( _mouse ); // it handles triple clicks too
00951         return;
00952     }
00953 
00954     int xm, ym;
00955     viewportToContents(_mouse->x(), _mouse->y(), xm, ym);
00956     //kdDebug( 6000 ) << "mousePressEvent: viewport=("<<_mouse->x()<<"/"<<_mouse->y()<<"), contents=(" << xm << "/" << ym << ")\n";
00957 
00958     d->isDoubleClick = false;
00959 
00960     DOM::NodeImpl::MouseEvent mev( _mouse->stateAfter(), DOM::NodeImpl::MousePress );
00961     m_part->xmlDocImpl()->prepareMouseEvent( false, xm, ym, &mev );
00962 
00963     //kdDebug(6000) << "innerNode="<<mev.innerNode.nodeName().string()<<endl;
00964 
00965     if ( (_mouse->button() == MidButton) &&
00966           !m_part->d->m_bOpenMiddleClick && !d->m_mouseScrollTimer &&
00967           mev.url.isNull() && (mev.innerNode.elementId() != ID_INPUT) ) {
00968         QPoint point = mapFromGlobal( _mouse->globalPos() );
00969 
00970         d->m_mouseScroll_byX = 0;
00971         d->m_mouseScroll_byY = 0;
00972 
00973         d->m_mouseScrollTimer = new QTimer( this );
00974         connect( d->m_mouseScrollTimer, SIGNAL(timeout()), this, SLOT(slotMouseScrollTimer()) );
00975 
00976         if ( !d->m_mouseScrollIndicator ) {
00977             QPixmap pixmap, icon;
00978             pixmap.resize( 48, 48 );
00979             pixmap.fill( QColor( qRgba( 127, 127, 127, 127 ) ) );
00980 
00981             QPainter p( &pixmap );
00982             icon = KGlobal::iconLoader()->loadIcon( "1uparrow", KIcon::Small );
00983             p.drawPixmap( 16, 0, icon );
00984             icon = KGlobal::iconLoader()->loadIcon( "1leftarrow", KIcon::Small );
00985             p.drawPixmap( 0, 16, icon );
00986             icon = KGlobal::iconLoader()->loadIcon( "1downarrow", KIcon::Small );
00987             p.drawPixmap( 16, 32,icon  );
00988             icon = KGlobal::iconLoader()->loadIcon( "1rightarrow", KIcon::Small );
00989             p.drawPixmap( 32, 16, icon );
00990             p.drawEllipse( 23, 23, 2, 2 );
00991 
00992             d->m_mouseScrollIndicator = new QWidget( this, 0 );
00993             d->m_mouseScrollIndicator->setFixedSize( 48, 48 );
00994             d->m_mouseScrollIndicator->setPaletteBackgroundPixmap( pixmap );
00995         }
00996         d->m_mouseScrollIndicator->move( point.x()-24, point.y()-24 );
00997 
00998         bool hasHorBar = visibleWidth() < contentsWidth();
00999         bool hasVerBar = visibleHeight() < contentsHeight();
01000 
01001         KConfig *config = KGlobal::config();
01002         KConfigGroupSaver saver( config, "HTML Settings" );
01003         if ( config->readBoolEntry( "ShowMouseScrollIndicator", true ) ) {
01004             d->m_mouseScrollIndicator->show();
01005             d->m_mouseScrollIndicator->unsetCursor();
01006 
01007             QBitmap mask = d->m_mouseScrollIndicator->paletteBackgroundPixmap()->createHeuristicMask( true );
01008 
01009         if ( hasHorBar && !hasVerBar ) {
01010                 QBitmap bm( 16, 16, true );
01011                 bitBlt( &mask, 16,  0, &bm, 0, 0, -1, -1 );
01012                 bitBlt( &mask, 16, 32, &bm, 0, 0, -1, -1 );
01013                 d->m_mouseScrollIndicator->setCursor( KCursor::SizeHorCursor );
01014             }
01015             else if ( !hasHorBar && hasVerBar ) {
01016                 QBitmap bm( 16, 16, true );
01017                 bitBlt( &mask,  0, 16, &bm, 0, 0, -1, -1 );
01018                 bitBlt( &mask, 32, 16, &bm, 0, 0, -1, -1 );
01019                 d->m_mouseScrollIndicator->setCursor( KCursor::SizeVerCursor );
01020             }
01021             else
01022                 d->m_mouseScrollIndicator->setCursor( KCursor::SizeAllCursor );
01023 
01024             d->m_mouseScrollIndicator->setMask( mask );
01025         }
01026         else {
01027             if ( hasHorBar && !hasVerBar )
01028                 viewport()->setCursor( KCursor::SizeHorCursor );
01029             else if ( !hasHorBar && hasVerBar )
01030                 viewport()->setCursor( KCursor::SizeVerCursor );
01031             else
01032                 viewport()->setCursor( KCursor::SizeAllCursor );
01033         }
01034 
01035         return;
01036     }
01037     else if ( d->m_mouseScrollTimer ) {
01038         delete d->m_mouseScrollTimer;
01039         d->m_mouseScrollTimer = 0;
01040 
01041         if ( d->m_mouseScrollIndicator )
01042             d->m_mouseScrollIndicator->hide();
01043     }
01044 
01045     d->clickCount = 1;
01046     d->clickX = xm;
01047     d->clickY = ym;
01048 
01049     bool swallowEvent = dispatchMouseEvent(EventImpl::MOUSEDOWN_EVENT,mev.innerNode.handle(),mev.innerNonSharedNode.handle(),true,
01050                                            d->clickCount,_mouse,true,DOM::NodeImpl::MousePress);
01051 
01052     khtml::RenderObject* r = mev.innerNode.handle() ? mev.innerNode.handle()->renderer() : 0;
01053     if (r && r->isWidget())
01054     _mouse->ignore();
01055 
01056     if (!swallowEvent) {
01057     emit m_part->nodeActivated(mev.innerNode);
01058 
01059     khtml::MousePressEvent event( _mouse, xm, ym, mev.url, mev.target, mev.innerNode );
01060         QApplication::sendEvent( m_part, &event );
01061         // we might be deleted after this
01062     }
01063 }
01064 
01065 void KHTMLView::viewportMouseDoubleClickEvent( QMouseEvent *_mouse )
01066 {
01067     if(!m_part->xmlDocImpl()) return;
01068 
01069     int xm, ym;
01070     viewportToContents(_mouse->x(), _mouse->y(), xm, ym);
01071 
01072     kdDebug( 6000 ) << "mouseDblClickEvent: x=" << xm << ", y=" << ym << endl;
01073 
01074     d->isDoubleClick = true;
01075 
01076     DOM::NodeImpl::MouseEvent mev( _mouse->stateAfter(), DOM::NodeImpl::MouseDblClick );
01077     m_part->xmlDocImpl()->prepareMouseEvent( false, xm, ym, &mev );
01078 
01079     // We do the same thing as viewportMousePressEvent() here, since the DOM does not treat
01080     // single and double-click events as separate (only the detail, i.e. number of clicks differs)
01081     if (d->clickCount > 0 &&
01082         QPoint(d->clickX-xm,d->clickY-ym).manhattanLength() <= QApplication::startDragDistance())
01083     d->clickCount++;
01084     else { // shouldn't happen, if Qt has the same criterias for double clicks.
01085     d->clickCount = 1;
01086     d->clickX = xm;
01087     d->clickY = ym;
01088     }
01089     bool swallowEvent = dispatchMouseEvent(EventImpl::MOUSEDOWN_EVENT,mev.innerNode.handle(),mev.innerNonSharedNode.handle(),true,
01090                                            d->clickCount,_mouse,true,DOM::NodeImpl::MouseDblClick);
01091 
01092     khtml::RenderObject* r = mev.innerNode.handle() ? mev.innerNode.handle()->renderer() : 0;
01093     if (r && r->isWidget())
01094     _mouse->ignore();
01095 
01096     if (!swallowEvent) {
01097     khtml::MouseDoubleClickEvent event( _mouse, xm, ym, mev.url, mev.target, mev.innerNode, d->clickCount );
01098     QApplication::sendEvent( m_part, &event );
01099     }
01100 
01101     d->possibleTripleClick=true;
01102     QTimer::singleShot(QApplication::doubleClickInterval(),this,SLOT(tripleClickTimeout()));
01103 }
01104 
01105 void KHTMLView::tripleClickTimeout()
01106 {
01107     d->possibleTripleClick = false;
01108     d->clickCount = 0;
01109 }
01110 
01111 static inline void forwardPeripheralEvent(khtml::RenderWidget* r, QMouseEvent* me, int x, int y)
01112 {
01113     int absx = 0;
01114     int absy = 0;
01115     r->absolutePosition(absx, absy);
01116     QPoint p(x-absx, y-absy);
01117     QMouseEvent fw(me->type(), p, me->button(), me->state());
01118     QWidget* w = r->widget();
01119     QScrollView* sc = ::qt_cast<QScrollView*>(w);
01120     if (sc && !::qt_cast<QListBox*>(w))
01121         static_cast<khtml::RenderWidget::ScrollViewEventPropagator*>(sc)->sendEvent(&fw);
01122     else if(w)
01123         static_cast<khtml::RenderWidget::EventPropagator*>(w)->sendEvent(&fw);
01124 }
01125 
01126 
01127 static bool targetOpensNewWindow(KHTMLPart *part, QString target)
01128 {
01129     if (!target.isEmpty() && (target.lower() != "_top") &&
01130        (target.lower() != "_self") && (target.lower() != "_parent")) {
01131         if (target.lower() == "_blank")
01132             return true;
01133         else {
01134             while (part->parentPart())
01135                 part = part->parentPart();
01136             if (!part->frameExists(target))
01137                 return true;
01138         }
01139     }
01140     return false;
01141 }
01142 
01143 void KHTMLView::viewportMouseMoveEvent( QMouseEvent * _mouse )
01144 {
01145     if ( d->m_mouseScrollTimer ) {
01146         QPoint point = mapFromGlobal( _mouse->globalPos() );
01147 
01148         int deltaX = point.x() - d->m_mouseScrollIndicator->x() - 24;
01149         int deltaY = point.y() - d->m_mouseScrollIndicator->y() - 24;
01150 
01151         (deltaX > 0) ? d->m_mouseScroll_byX = 1 : d->m_mouseScroll_byX = -1;
01152         (deltaY > 0) ? d->m_mouseScroll_byY = 1 : d->m_mouseScroll_byY = -1;
01153 
01154         double adX = QABS(deltaX)/30.0;
01155         double adY = QABS(deltaY)/30.0;
01156 
01157         d->m_mouseScroll_byX = kMax(kMin(d->m_mouseScroll_byX * int(adX*adX), SHRT_MAX), SHRT_MIN);
01158         d->m_mouseScroll_byY = kMax(kMin(d->m_mouseScroll_byY * int(adY*adY), SHRT_MAX), SHRT_MIN);
01159 
01160         if (d->m_mouseScroll_byX == 0 && d->m_mouseScroll_byY == 0) {
01161             d->m_mouseScrollTimer->stop();
01162         }
01163         else if (!d->m_mouseScrollTimer->isActive()) {
01164             d->m_mouseScrollTimer->changeInterval( 20 );
01165         }
01166     }
01167 
01168     if(!m_part->xmlDocImpl()) return;
01169 
01170     int xm, ym;
01171     viewportToContents(_mouse->x(), _mouse->y(), xm, ym);
01172 
01173     DOM::NodeImpl::MouseEvent mev( _mouse->stateAfter(), DOM::NodeImpl::MouseMove );
01174     // Do not modify :hover/:active state while mouse is pressed.
01175     m_part->xmlDocImpl()->prepareMouseEvent( _mouse->state() & Qt::MouseButtonMask /*readonly ?*/, xm, ym, &mev );
01176 
01177 //     kdDebug(6000) << "mouse move: " << _mouse->pos()
01178 //        << " button " << _mouse->button()
01179 //        << " state " << _mouse->state() << endl;
01180 
01181     bool swallowEvent = dispatchMouseEvent(EventImpl::MOUSEMOVE_EVENT,mev.innerNode.handle(),mev.innerNonSharedNode.handle(),false,
01182                                            0,_mouse,true,DOM::NodeImpl::MouseMove);
01183 
01184     if (d->clickCount > 0 &&
01185         QPoint(d->clickX-xm,d->clickY-ym).manhattanLength() > QApplication::startDragDistance()) {
01186     d->clickCount = 0;  // moving the mouse outside the threshold invalidates the click
01187     }
01188 
01189     // execute the scheduled script. This is to make sure the mouseover events come after the mouseout events
01190     m_part->executeScheduledScript();
01191 
01192     DOM::NodeImpl* fn = m_part->xmlDocImpl()->focusNode();
01193     if (fn && fn != mev.innerNode.handle() &&
01194         fn->renderer() && fn->renderer()->isWidget()) {
01195         forwardPeripheralEvent(static_cast<khtml::RenderWidget*>(fn->renderer()), _mouse, xm, ym);
01196     }
01197 
01198     khtml::RenderObject* r = mev.innerNode.handle() ? mev.innerNode.handle()->renderer() : 0;
01199     khtml::RenderStyle* style = (r && r->style()) ? r->style() : 0;
01200     QCursor c;
01201     bool mailtoCursor = false;
01202     bool newWindowCursor = false;
01203     switch ( style ? style->cursor() : CURSOR_AUTO) {
01204     case CURSOR_AUTO:
01205         if ( r && r->isText() )
01206             c = KCursor::ibeamCursor();
01207         if ( mev.url.length() && m_part->settings()->changeCursor() ) {
01208             c = m_part->urlCursor();
01209         if (mev.url.string().startsWith("mailto:") && mev.url.string().find('@')>0)
01210                 mailtoCursor = true;
01211             else
01212                 newWindowCursor = targetOpensNewWindow( m_part, mev.target.string() );
01213         }
01214 
01215         if (r && r->isFrameSet() && !static_cast<RenderFrameSet*>(r)->noResize())
01216             c = QCursor(static_cast<RenderFrameSet*>(r)->cursorShape());
01217 
01218         break;
01219     case CURSOR_CROSS:
01220         c = KCursor::crossCursor();
01221         break;
01222     case CURSOR_POINTER:
01223         c = m_part->urlCursor();
01224     if (mev.url.string().startsWith("mailto:") && mev.url.string().find('@')>0)
01225             mailtoCursor = true;
01226         else
01227             newWindowCursor = targetOpensNewWindow( m_part, mev.target.string() );
01228         break;
01229     case CURSOR_PROGRESS:
01230         c = KCursor::workingCursor();
01231         break;
01232     case CURSOR_MOVE:
01233         c = KCursor::sizeAllCursor();
01234         break;
01235     case CURSOR_E_RESIZE:
01236     case CURSOR_W_RESIZE:
01237         c = KCursor::sizeHorCursor();
01238         break;
01239     case CURSOR_N_RESIZE:
01240     case CURSOR_S_RESIZE:
01241         c = KCursor::sizeVerCursor();
01242         break;
01243     case CURSOR_NE_RESIZE:
01244     case CURSOR_SW_RESIZE:
01245         c = KCursor::sizeBDiagCursor();
01246         break;
01247     case CURSOR_NW_RESIZE:
01248     case CURSOR_SE_RESIZE:
01249         c = KCursor::sizeFDiagCursor();
01250         break;
01251     case CURSOR_TEXT:
01252         c = KCursor::ibeamCursor();
01253         break;
01254     case CURSOR_WAIT:
01255         c = KCursor::waitCursor();
01256         break;
01257     case CURSOR_HELP:
01258         c = KCursor::whatsThisCursor();
01259         break;
01260     case CURSOR_DEFAULT:
01261         break;
01262     }
01263 
01264     if ( viewport()->cursor().handle() != c.handle() ) {
01265         if( c.handle() == KCursor::arrowCursor().handle()) {
01266             for (KHTMLPart* p = m_part; p; p = p->parentPart())
01267                 p->view()->viewport()->unsetCursor();
01268         }
01269         else {
01270             viewport()->setCursor( c );
01271         }
01272     }
01273 
01274     if ( ( mailtoCursor || newWindowCursor ) && isVisible() && hasFocus() ) {
01275 #ifdef Q_WS_X11
01276         if( !d->cursor_icon_widget ) {
01277             QPixmap icon_pixmap = KGlobal::iconLoader()->loadIcon( mailtoCursor ? "mail_generic" : "window_new", KIcon::Small, 0, KIcon::DefaultState, 0, true );
01278             d->cursor_icon_widget = new QWidget( NULL, NULL, WX11BypassWM );
01279             XSetWindowAttributes attr;
01280             attr.save_under = True;
01281             XChangeWindowAttributes( qt_xdisplay(), d->cursor_icon_widget->winId(), CWSaveUnder, &attr );
01282             d->cursor_icon_widget->resize( icon_pixmap.width(), icon_pixmap.height());
01283             if( icon_pixmap.mask() )
01284                 d->cursor_icon_widget->setMask( *icon_pixmap.mask());
01285             else
01286                 d->cursor_icon_widget->clearMask();
01287             d->cursor_icon_widget->setBackgroundPixmap( icon_pixmap );
01288             d->cursor_icon_widget->erase();
01289         }
01290         QPoint c_pos = QCursor::pos();
01291         d->cursor_icon_widget->move( c_pos.x() + 15, c_pos.y() + 15 );
01292         XRaiseWindow( qt_xdisplay(), d->cursor_icon_widget->winId());
01293         QApplication::flushX();
01294         d->cursor_icon_widget->show();
01295 #endif
01296     }
01297     else if ( d->cursor_icon_widget )
01298         d->cursor_icon_widget->hide();
01299 
01300     if (r && r->isWidget()) {
01301     _mouse->ignore();
01302     }
01303 
01304 
01305     d->prevMouseX = xm;
01306     d->prevMouseY = ym;
01307 
01308     if (!swallowEvent) {
01309         khtml::MouseMoveEvent event( _mouse, xm, ym, mev.url, mev.target, mev.innerNode );
01310         QApplication::sendEvent( m_part, &event );
01311     }
01312 }
01313 
01314 void KHTMLView::viewportMouseReleaseEvent( QMouseEvent * _mouse )
01315 {
01316     bool swallowEvent = false;
01317     int xm, ym;
01318     viewportToContents(_mouse->x(), _mouse->y(), xm, ym);
01319     DOM::NodeImpl::MouseEvent mev( _mouse->stateAfter(), DOM::NodeImpl::MouseRelease );
01320 
01321     if ( m_part->xmlDocImpl() )
01322     {
01323         m_part->xmlDocImpl()->prepareMouseEvent( false, xm, ym, &mev );
01324 
01325         swallowEvent = dispatchMouseEvent(EventImpl::MOUSEUP_EVENT,mev.innerNode.handle(),mev.innerNonSharedNode.handle(),true,
01326                                           d->clickCount,_mouse,false,DOM::NodeImpl::MouseRelease);
01327 
01328         if (d->clickCount > 0 &&
01329             QPoint(d->clickX-xm,d->clickY-ym).manhattanLength() <= QApplication::startDragDistance()) {
01330             QMouseEvent me(d->isDoubleClick ? QEvent::MouseButtonDblClick : QEvent::MouseButtonRelease,
01331                            _mouse->pos(), _mouse->button(), _mouse->state());
01332             dispatchMouseEvent(EventImpl::CLICK_EVENT, mev.innerNode.handle(),mev.innerNonSharedNode.handle(),true,
01333                                d->clickCount, &me, true, DOM::NodeImpl::MouseRelease);
01334         }
01335 
01336         DOM::NodeImpl* fn = m_part->xmlDocImpl()->focusNode();
01337         if (fn && fn != mev.innerNode.handle() &&
01338             fn->renderer() && fn->renderer()->isWidget() &&
01339             _mouse->button() != MidButton) {
01340             forwardPeripheralEvent(static_cast<khtml::RenderWidget*>(fn->renderer()), _mouse, xm, ym);
01341         }
01342 
01343         khtml::RenderObject* r = mev.innerNode.handle() ? mev.innerNode.handle()->renderer() : 0;
01344         if (r && r->isWidget())
01345             _mouse->ignore();
01346     }
01347 
01348     if (!swallowEvent) {
01349     khtml::MouseReleaseEvent event( _mouse, xm, ym, mev.url, mev.target, mev.innerNode );
01350     QApplication::sendEvent( m_part, &event );
01351     }
01352 }
01353 
01354 // returns true if event should be swallowed
01355 bool KHTMLView::dispatchKeyEvent( QKeyEvent *_ke )
01356 {
01357     if (!m_part->xmlDocImpl())
01358         return false;
01359     // Pressing and releasing a key should generate keydown, keypress and keyup events
01360     // Holding it down should generated keydown, keypress (repeatedly) and keyup events
01361     // The problem here is that Qt generates two autorepeat events (keyrelease+keypress)
01362     // for autorepeating, while DOM wants only one autorepeat event (keypress), so one
01363     // of the Qt events shouldn't be passed to DOM, but it should be still filtered
01364     // out if DOM would filter the autorepeat event. Additional problem is that Qt keyrelease
01365     // events don't have text() set (Qt bug?), so DOM often would ignore the keypress event
01366     // if it was created using Qt keyrelease, but Qt autorepeat keyrelease comes
01367     // before Qt autorepeat keypress (i.e. problem whether to filter it out or not).
01368     // The solution is to filter out and postpone the Qt autorepeat keyrelease until
01369     // the following Qt keypress event comes. If DOM accepts the DOM keypress event,
01370     // the postponed event will be simply discarded. If not, it will be passed to keyPressEvent()
01371     // again, and here it will be ignored.
01372     //
01373     //  Qt:      Press      | Release(autorepeat) Press(autorepeat) etc. |   Release
01374     //  DOM:   Down + Press |      (nothing)           Press             |     Up
01375 
01376     // It's also possible to get only Releases. E.g. the release of alt-tab,
01377     // or when the keypresses get captured by an accel.
01378 
01379     if( _ke == d->postponed_autorepeat ) // replayed event
01380     {
01381         return false;
01382     }
01383 
01384     if( _ke->type() == QEvent::KeyPress )
01385     {
01386         if( !_ke->isAutoRepeat())
01387         {
01388             bool ret = dispatchKeyEventHelper( _ke, false ); // keydown
01389             // don't send keypress even if keydown was blocked, like IE (and unlike Mozilla)
01390             if( !ret && dispatchKeyEventHelper( _ke, true )) // keypress
01391                 ret = true;
01392             return ret;
01393         }
01394         else // autorepeat
01395         {
01396             bool ret = dispatchKeyEventHelper( _ke, true ); // keypress
01397             if( !ret && d->postponed_autorepeat )
01398                 keyPressEvent( d->postponed_autorepeat );
01399             delete d->postponed_autorepeat;
01400             d->postponed_autorepeat = NULL;
01401             return ret;
01402         }
01403     }
01404     else // QEvent::KeyRelease
01405     {
01406         // Discard postponed "autorepeat key-release" events that didn't see
01407         // a keypress after them (e.g. due to QAccel)
01408         if ( d->postponed_autorepeat ) {
01409             delete d->postponed_autorepeat;
01410             d->postponed_autorepeat = 0;
01411         }
01412 
01413         if( !_ke->isAutoRepeat()) {
01414             return dispatchKeyEventHelper( _ke, false ); // keyup
01415         }
01416         else
01417         {
01418             d->postponed_autorepeat = new QKeyEvent( _ke->type(), _ke->key(), _ke->ascii(), _ke->state(),
01419                 _ke->text(), _ke->isAutoRepeat(), _ke->count());
01420             if( _ke->isAccepted())
01421                 d->postponed_autorepeat->accept();
01422             else
01423                 d->postponed_autorepeat->ignore();
01424             return true;
01425         }
01426     }
01427 }
01428 
01429 // returns true if event should be swallowed
01430 bool KHTMLView::dispatchKeyEventHelper( QKeyEvent *_ke, bool keypress )
01431 {
01432     DOM::NodeImpl* keyNode = m_part->xmlDocImpl()->focusNode();
01433     if (keyNode) {
01434         return keyNode->dispatchKeyEvent(_ke, keypress);
01435     } else { // no focused node, send to document
01436         return m_part->xmlDocImpl()->dispatchKeyEvent(_ke, keypress);
01437     }
01438 }
01439 
01440 void KHTMLView::keyPressEvent( QKeyEvent *_ke )
01441 {
01442 #ifndef KHTML_NO_TYPE_AHEAD_FIND
01443     if(d->typeAheadActivated)
01444     {
01445         // type-ahead find aka find-as-you-type
01446         if(_ke->key() == Key_BackSpace)
01447         {
01448             d->findString = d->findString.left(d->findString.length() - 1);
01449 
01450             if(!d->findString.isEmpty())
01451             {
01452                 findAhead(false);
01453             }
01454             else
01455             {
01456                 findTimeout();
01457             }
01458 
01459             d->timer.start(3000, true);
01460             _ke->accept();
01461             return;
01462         }
01463         else if(_ke->key() == Key_Escape)
01464         {
01465             findTimeout();
01466 
01467             _ke->accept();
01468             return;
01469         }
01470         else if(_ke->key() == Key_Space || !_ke->text().stripWhiteSpace().isEmpty())
01471         {
01472             d->findString += _ke->text();
01473 
01474             findAhead(true);
01475 
01476             d->timer.start(3000, true);
01477             _ke->accept();
01478             return;
01479         }
01480     }
01481 #endif // KHTML_NO_TYPE_AHEAD_FIND
01482 
01483 #ifndef KHTML_NO_CARET
01484     if (m_part->isEditable() || m_part->isCaretMode()
01485         || (m_part->xmlDocImpl() && m_part->xmlDocImpl()->focusNode()
01486         && m_part->xmlDocImpl()->focusNode()->contentEditable())) {
01487       d->caretViewContext()->keyReleasePending = true;
01488       caretKeyPressEvent(_ke);
01489       return;
01490     }
01491 #endif // KHTML_NO_CARET
01492 
01493     // If CTRL was hit, be prepared for access keys
01494     if (d->accessKeysEnabled && _ke->key() == Key_Control && _ke->state()==0 && !d->accessKeysActivated)
01495     {
01496         d->accessKeysPreActivate=true;
01497         _ke->accept();
01498         return;
01499     }
01500 
01501     if (_ke->key() == Key_Shift && _ke->state()==0)
01502         d->scrollSuspendPreActivate=true;
01503 
01504     // accesskey handling needs to be done before dispatching, otherwise e.g. lineedits
01505     // may eat the event
01506 
01507     if (d->accessKeysEnabled && d->accessKeysActivated)
01508     {
01509         int state = ( _ke->state() & ( ShiftButton | ControlButton | AltButton | MetaButton ));
01510         if ( state==0 || state==ShiftButton) {
01511     if (_ke->key() != Key_Shift) accessKeysTimeout();
01512         handleAccessKey( _ke );
01513         _ke->accept();
01514         return;
01515         }
01516     accessKeysTimeout();
01517     }
01518 
01519     if ( dispatchKeyEvent( _ke )) {
01520         // If either keydown or keypress was accepted by a widget, or canceled by JS, stop here.
01521         _ke->accept();
01522         return;
01523     }
01524 
01525     int offs = (clipper()->height() < 30) ? clipper()->height() : 30;
01526     if (_ke->state() & Qt::ShiftButton)
01527       switch(_ke->key())
01528         {
01529         case Key_Space:
01530             scrollBy( 0, -clipper()->height() + offs );
01531             if(d->scrollSuspended)
01532                 d->newScrollTimer(this, 0);
01533             break;
01534 
01535         case Key_Down:
01536         case Key_J:
01537             d->adjustScroller(this, KHTMLViewPrivate::ScrollDown, KHTMLViewPrivate::ScrollUp);
01538             break;
01539 
01540         case Key_Up:
01541         case Key_K:
01542             d->adjustScroller(this, KHTMLViewPrivate::ScrollUp, KHTMLViewPrivate::ScrollDown);
01543             break;
01544 
01545         case Key_Left:
01546         case Key_H:
01547             d->adjustScroller(this, KHTMLViewPrivate::ScrollLeft, KHTMLViewPrivate::ScrollRight);
01548             break;
01549 
01550         case Key_Right:
01551         case Key_L:
01552             d->adjustScroller(this, KHTMLViewPrivate::ScrollRight, KHTMLViewPrivate::ScrollLeft);
01553             break;
01554         }
01555     else
01556         switch ( _ke->key() )
01557         {
01558         case Key_Down:
01559         case Key_J:
01560             if (!d->scrollTimerId || d->scrollSuspended)
01561                 scrollBy( 0, 10 );
01562             if (d->scrollTimerId)
01563                 d->newScrollTimer(this, 0);
01564             break;
01565 
01566         case Key_Space:
01567         case Key_Next:
01568             scrollBy( 0, clipper()->height() - offs );
01569             if(d->scrollSuspended)
01570                 d->newScrollTimer(this, 0);
01571             break;
01572 
01573         case Key_Up:
01574         case Key_K:
01575             if (!d->scrollTimerId || d->scrollSuspended)
01576                 scrollBy( 0, -10 );
01577             if (d->scrollTimerId)
01578                 d->newScrollTimer(this, 0);
01579             break;
01580 
01581         case Key_Prior:
01582             scrollBy( 0, -clipper()->height() + offs );
01583             if(d->scrollSuspended)
01584                 d->newScrollTimer(this, 0);
01585             break;
01586         case Key_Right:
01587         case Key_L:
01588             if (!d->scrollTimerId || d->scrollSuspended)
01589                 scrollBy( 10, 0 );
01590             if (d->scrollTimerId)
01591                 d->newScrollTimer(this, 0);
01592             break;
01593         case Key_Left:
01594         case Key_H:
01595             if (!d->scrollTimerId || d->scrollSuspended)
01596                 scrollBy( -10, 0 );
01597             if (d->scrollTimerId)
01598                 d->newScrollTimer(this, 0);
01599             break;
01600         case Key_Enter:
01601         case Key_Return:
01602         // ### FIXME:
01603         // or even better to HTMLAnchorElementImpl::event()
01604             if (m_part->xmlDocImpl()) {
01605         NodeImpl *n = m_part->xmlDocImpl()->focusNode();
01606         if (n)
01607             n->setActive();
01608         }
01609             break;
01610         case Key_Home:
01611             setContentsPos( 0, 0 );
01612             if(d->scrollSuspended)
01613                 d->newScrollTimer(this, 0);
01614             break;
01615         case Key_End:
01616             setContentsPos( 0, contentsHeight() - visibleHeight() );
01617             if(d->scrollSuspended)
01618                 d->newScrollTimer(this, 0);
01619             break;
01620         case Key_Shift:
01621             // what are you doing here?
01622         _ke->ignore();
01623             return;
01624         default:
01625             if (d->scrollTimerId)
01626                 d->newScrollTimer(this, 0);
01627         _ke->ignore();
01628             return;
01629         }
01630 
01631     _ke->accept();
01632 }
01633 
01634 void KHTMLView::findTimeout()
01635 {
01636 #ifndef KHTML_NO_TYPE_AHEAD_FIND
01637     d->typeAheadActivated = false;
01638     d->findString = "";
01639     m_part->setStatusBarText(i18n("Find stopped."), KHTMLPart::BarDefaultText);
01640     m_part->enableFindAheadActions( true );
01641 #endif // KHTML_NO_TYPE_AHEAD_FIND
01642 }
01643 
01644 #ifndef KHTML_NO_TYPE_AHEAD_FIND
01645 void KHTMLView::startFindAhead( bool linksOnly )
01646 {
01647     if( linksOnly )
01648     {
01649         d->findLinksOnly = true;
01650         m_part->setStatusBarText(i18n("Starting -- find links as you type"),
01651                                  KHTMLPart::BarDefaultText);
01652     }
01653     else
01654     {
01655         d->findLinksOnly = false;
01656         m_part->setStatusBarText(i18n("Starting -- find text as you type"),
01657                                  KHTMLPart::BarDefaultText);
01658     }
01659 
01660     m_part->findTextBegin();
01661     d->typeAheadActivated = true;
01662         // disable, so that the shortcut ( / or ' by default ) doesn't interfere
01663     m_part->enableFindAheadActions( false );
01664     d->timer.start(3000, true);
01665 }
01666 
01667 void KHTMLView::findAhead(bool increase)
01668 {
01669     QString status;
01670 
01671     if(d->findLinksOnly)
01672     {
01673         m_part->findText(d->findString, KHTMLPart::FindNoPopups |
01674                          KHTMLPart::FindLinksOnly, this);
01675         if(m_part->findTextNext())
01676         {
01677             status = i18n("Link found: \"%1\".");
01678         }
01679         else
01680         {
01681             if(increase) KNotifyClient::beep();
01682             status = i18n("Link not found: \"%1\".");
01683         }
01684     }
01685     else
01686     {
01687         m_part->findText(d->findString, KHTMLPart::FindNoPopups, this);
01688         if(m_part->findTextNext())
01689         {
01690             status = i18n("Text found: \"%1\".");
01691         }
01692         else
01693         {
01694             if(increase) KNotifyClient::beep();
01695             status = i18n("Text not found: \"%1\".");
01696         }
01697     }
01698 
01699     m_part->setStatusBarText(status.arg(d->findString.lower()),
01700                              KHTMLPart::BarDefaultText);
01701 }
01702 
01703 void KHTMLView::updateFindAheadTimeout()
01704 {
01705     if( d->typeAheadActivated )
01706         d->timer.start( 3000, true );
01707 }
01708 
01709 #endif // KHTML_NO_TYPE_AHEAD_FIND
01710 
01711 void KHTMLView::keyReleaseEvent(QKeyEvent *_ke)
01712 {
01713 #ifndef KHTML_NO_TYPE_AHEAD_FIND
01714     if(d->typeAheadActivated) {
01715         _ke->accept();
01716         return;
01717     }
01718 #endif
01719     if (d->m_caretViewContext && d->m_caretViewContext->keyReleasePending) {
01720         //caretKeyReleaseEvent(_ke);
01721     d->m_caretViewContext->keyReleasePending = false;
01722     return;
01723     }
01724 
01725     if( d->scrollSuspendPreActivate && _ke->key() != Key_Shift )
01726         d->scrollSuspendPreActivate = false;
01727     if( _ke->key() == Key_Shift && d->scrollSuspendPreActivate && _ke->state() == Qt::ShiftButton
01728         && !(KApplication::keyboardMouseState() & Qt::ShiftButton))
01729     {
01730         if (d->scrollTimerId)
01731         {
01732             d->scrollSuspended = !d->scrollSuspended;
01733 #ifndef NO_SMOOTH_SCROLL_HACK
01734             if( d->scrollSuspended )
01735                 stopScrolling();
01736 #endif
01737         }
01738     }
01739 
01740     if (d->accessKeysEnabled)
01741     {
01742         if (d->accessKeysPreActivate && _ke->key() != Key_Control)
01743             d->accessKeysPreActivate=false;
01744         if (d->accessKeysPreActivate && _ke->state() == Qt::ControlButton && !(KApplication::keyboardMouseState() & Qt::ControlButton))
01745         {
01746         displayAccessKeys();
01747         m_part->setStatusBarText(i18n("Access Keys activated"),KHTMLPart::BarOverrideText);
01748         d->accessKeysActivated = true;
01749         d->accessKeysPreActivate = false;
01750             _ke->accept();
01751             return;
01752         }
01753     else if (d->accessKeysActivated)
01754         {
01755             accessKeysTimeout();
01756             _ke->accept();
01757             return;
01758         }
01759     }
01760 
01761     // Send keyup event
01762     if ( dispatchKeyEvent( _ke ) )
01763     {
01764         _ke->accept();
01765         return;
01766     }
01767 
01768     QScrollView::keyReleaseEvent(_ke);
01769 }
01770 
01771 void KHTMLView::contentsContextMenuEvent ( QContextMenuEvent * /*ce*/ )
01772 {
01773 // ### what kind of c*** is that ?
01774 #if 0
01775     if (!m_part->xmlDocImpl()) return;
01776     int xm = _ce->x();
01777     int ym = _ce->y();
01778 
01779     DOM::NodeImpl::MouseEvent mev( _ce->state(), DOM::NodeImpl::MouseMove ); // ### not a mouse event!
01780     m_part->xmlDocImpl()->prepareMouseEvent( xm, ym, &mev );
01781 
01782     NodeImpl *targetNode = mev.innerNode.handle();
01783     if (targetNode && targetNode->renderer() && targetNode->renderer()->isWidget()) {
01784         int absx = 0;
01785         int absy = 0;
01786         targetNode->renderer()->absolutePosition(absx,absy);
01787         QPoint pos(xm-absx,ym-absy);
01788 
01789         QWidget *w = static_cast<RenderWidget*>(targetNode->renderer())->widget();
01790         QContextMenuEvent cme(_ce->reason(),pos,_ce->globalPos(),_ce->state());
01791         setIgnoreEvents(true);
01792         QApplication::sendEvent(w,&cme);
01793         setIgnoreEvents(false);
01794     }
01795 #endif
01796 }
01797 
01798 bool KHTMLView::focusNextPrevChild( bool next )
01799 {
01800     // Now try to find the next child
01801     if (m_part->xmlDocImpl() && focusNextPrevNode(next))
01802     {
01803     if (m_part->xmlDocImpl()->focusNode())
01804         kdDebug() << "focusNode.name: "
01805               << m_part->xmlDocImpl()->focusNode()->nodeName().string() << endl;
01806     return true; // focus node found
01807     }
01808 
01809     // If we get here, pass tabbing control up to the next/previous child in our parent
01810     d->pseudoFocusNode = KHTMLViewPrivate::PFNone;
01811     if (m_part->parentPart() && m_part->parentPart()->view())
01812         return m_part->parentPart()->view()->focusNextPrevChild(next);
01813 
01814     return QWidget::focusNextPrevChild(next);
01815 }
01816 
01817 void KHTMLView::doAutoScroll()
01818 {
01819     QPoint pos = QCursor::pos();
01820     pos = viewport()->mapFromGlobal( pos );
01821 
01822     int xm, ym;
01823     viewportToContents(pos.x(), pos.y(), xm, ym);
01824 
01825     pos = QPoint(pos.x() - viewport()->x(), pos.y() - viewport()->y());
01826     if ( (pos.y() < 0) || (pos.y() > visibleHeight()) ||
01827          (pos.x() < 0) || (pos.x() > visibleWidth()) )
01828     {
01829         ensureVisible( xm, ym, 0, 5 );
01830 
01831 #ifndef KHTML_NO_SELECTION
01832         // extend the selection while scrolling
01833     DOM::Node innerNode;
01834     if (m_part->isExtendingSelection()) {
01835             RenderObject::NodeInfo renderInfo(true/*readonly*/, false/*active*/);
01836             m_part->xmlDocImpl()->renderer()->layer()
01837                 ->nodeAtPoint(renderInfo, xm, ym);
01838             innerNode = renderInfo.innerNode();
01839     }/*end if*/
01840 
01841         if (innerNode.handle() && innerNode.handle()->renderer()) {
01842             int absX, absY;
01843             innerNode.handle()->renderer()->absolutePosition(absX, absY);
01844 
01845             m_part->extendSelectionTo(xm, ym, absX, absY, innerNode);
01846         }/*end if*/
01847 #endif // KHTML_NO_SELECTION
01848     }
01849 }
01850 
01851 
01852 class HackWidget : public QWidget
01853 {
01854  public:
01855     inline void setNoErase() { setWFlags(getWFlags()|WRepaintNoErase); }
01856 };
01857 
01858 bool KHTMLView::eventFilter(QObject *o, QEvent *e)
01859 {
01860     if ( e->type() == QEvent::AccelOverride ) {
01861     QKeyEvent* ke = (QKeyEvent*) e;
01862 //kdDebug(6200) << "QEvent::AccelOverride" << endl;
01863     if (m_part->isEditable() || m_part->isCaretMode()
01864         || (m_part->xmlDocImpl() && m_part->xmlDocImpl()->focusNode()
01865         && m_part->xmlDocImpl()->focusNode()->contentEditable())) {
01866 //kdDebug(6200) << "editable/navigable" << endl;
01867         if ( (ke->state() & ControlButton) || (ke->state() & ShiftButton) ) {
01868         switch ( ke->key() ) {
01869         case Key_Left:
01870         case Key_Right:
01871         case Key_Up:
01872         case Key_Down:
01873         case Key_Home:
01874         case Key_End:
01875             ke->accept();
01876 //kdDebug(6200) << "eaten" << endl;
01877             return true;
01878         default:
01879             break;
01880         }
01881         }
01882     }
01883     }
01884 
01885     if ( e->type() == QEvent::Leave ) {
01886       if ( d->cursor_icon_widget )
01887         d->cursor_icon_widget->hide();
01888       m_part->resetHoverText();
01889     }
01890 
01891     QWidget *view = viewport();
01892 
01893     if (o == view) {
01894     // we need to install an event filter on all children of the viewport to
01895     // be able to get correct stacking of children within the document.
01896     if(e->type() == QEvent::ChildInserted) {
01897         QObject *c = static_cast<QChildEvent *>(e)->child();
01898         if (c->isWidgetType()) {
01899         QWidget *w = static_cast<QWidget *>(c);
01900         // don't install the event filter on toplevels
01901         if (w->parentWidget(true) == view) {
01902             if (!strcmp(w->name(), "__khtml")) {
01903             w->installEventFilter(this);
01904             w->unsetCursor();
01905             if (!::qt_cast<QFrame*>(w))
01906                 w->setBackgroundMode( QWidget::NoBackground );
01907             static_cast<HackWidget *>(w)->setNoErase();
01908             if (w->children()) {
01909                 QObjectListIterator it(*w->children());
01910                 for (; it.current(); ++it) {
01911                 QWidget *widget = ::qt_cast<QWidget *>(it.current());
01912                 if (widget && !widget->isTopLevel()) {
01913                     if (!::qt_cast<QFrame*>(w))
01914                         widget->setBackgroundMode( QWidget::NoBackground );
01915                     static_cast<HackWidget *>(widget)->setNoErase();
01916                     widget->installEventFilter(this);
01917                 }
01918                 }
01919             }
01920             }
01921         }
01922         }
01923     }
01924     } else if (o->isWidgetType()) {
01925     QWidget *v = static_cast<QWidget *>(o);
01926         QWidget *c = v;
01927     while (v && v != view) {
01928             c = v;
01929         v = v->parentWidget(true);
01930     }
01931 
01932     if (v && !strcmp(c->name(), "__khtml")) {
01933         bool block = false;
01934         QWidget *w = static_cast<QWidget *>(o);
01935         switch(e->type()) {
01936         case QEvent::Paint:
01937         if (!allowWidgetPaintEvents) {
01938             // eat the event. Like this we can control exactly when the widget
01939             // get's repainted.
01940             block = true;
01941             int x = 0, y = 0;
01942             QWidget *v = w;
01943             while (v && v != view) {
01944             x += v->x();
01945             y += v->y();
01946             v = v->parentWidget();
01947             }
01948             viewportToContents( x, y, x, y );
01949             QPaintEvent *pe = static_cast<QPaintEvent *>(e);
01950             bool asap = !d->contentsMoving && ::qt_cast<QScrollView *>(c);
01951 
01952             // QScrollView needs fast repaints
01953             if ( asap && !d->painting && m_part->xmlDocImpl() && m_part->xmlDocImpl()->renderer() &&
01954                  !static_cast<khtml::RenderCanvas *>(m_part->xmlDocImpl()->renderer())->needsLayout() ) {
01955                 repaintContents(x + pe->rect().x(), y + pe->rect().y(),
01956                                             pe->rect().width(), pe->rect().height(), true);
01957                     } else {
01958                 scheduleRepaint(x + pe->rect().x(), y + pe->rect().y(),
01959                     pe->rect().width(), pe->rect().height(), asap);
01960                     }
01961         }
01962         break;
01963         case QEvent::MouseMove:
01964         case QEvent::MouseButtonPress:
01965         case QEvent::MouseButtonRelease:
01966         case QEvent::MouseButtonDblClick: {
01967         if ( (w->parentWidget() == view || ::qt_cast<QScrollView*>(c)) && !::qt_cast<QScrollBar *>(w)) {
01968             QMouseEvent *me = static_cast<QMouseEvent *>(e);
01969             QPoint pt = w->mapTo( view, me->pos());
01970             QMouseEvent me2(me->type(), pt, me->button(), me->state());
01971 
01972             if (e->type() == QEvent::MouseMove)
01973             viewportMouseMoveEvent(&me2);
01974             else if(e->type() == QEvent::MouseButtonPress)
01975             viewportMousePressEvent(&me2);
01976             else if(e->type() == QEvent::MouseButtonRelease)
01977             viewportMouseReleaseEvent(&me2);
01978             else
01979             viewportMouseDoubleClickEvent(&me2);
01980             block = true;
01981                 }
01982         break;
01983         }
01984         case QEvent::KeyPress:
01985         case QEvent::KeyRelease:
01986         if (w->parentWidget() == view && !::qt_cast<QScrollBar *>(w)) {
01987             QKeyEvent *ke = static_cast<QKeyEvent *>(e);
01988             if (e->type() == QEvent::KeyPress)
01989             keyPressEvent(ke);
01990             else
01991             keyReleaseEvent(ke);
01992             block = true;
01993         }
01994         default:
01995         break;
01996         }
01997         if (block) {
01998         //qDebug("eating event");
01999         return true;
02000         }
02001     }
02002     }
02003 
02004 //    kdDebug(6000) <<"passing event on to sv event filter object=" << o->className() << " event=" << e->type() << endl;
02005     return QScrollView::eventFilter(o, e);
02006 }
02007 
02008 
02009 DOM::NodeImpl *KHTMLView::nodeUnderMouse() const
02010 {
02011     return d->underMouse;
02012 }
02013 
02014 DOM::NodeImpl *KHTMLView::nonSharedNodeUnderMouse() const
02015 {
02016     return d->underMouseNonShared;
02017 }
02018 
02019 bool KHTMLView::scrollTo(const QRect &bounds)
02020 {
02021     d->scrollingSelf = true; // so scroll events get ignored
02022 
02023     int x, y, xe, ye;
02024     x = bounds.left();
02025     y = bounds.top();
02026     xe = bounds.right();
02027     ye = bounds.bottom();
02028 
02029     //kdDebug(6000)<<"scrolling coords: x="<<x<<" y="<<y<<" width="<<xe-x<<" height="<<ye-y<<endl;
02030 
02031     int deltax;
02032     int deltay;
02033 
02034     int curHeight = visibleHeight();
02035     int curWidth = visibleWidth();
02036 
02037     if (ye-y>curHeight-d->borderY)
02038     ye  = y + curHeight - d->borderY;
02039 
02040     if (xe-x>curWidth-d->borderX)
02041     xe = x + curWidth - d->borderX;
02042 
02043     // is xpos of target left of the view's border?
02044     if (x < contentsX() + d->borderX )
02045             deltax = x - contentsX() - d->borderX;
02046     // is xpos of target right of the view's right border?
02047     else if (xe + d->borderX > contentsX() + curWidth)
02048             deltax = xe + d->borderX - ( contentsX() + curWidth );
02049     else
02050         deltax = 0;
02051 
02052     // is ypos of target above upper border?
02053     if (y < contentsY() + d->borderY)
02054             deltay = y - contentsY() - d->borderY;
02055     // is ypos of target below lower border?
02056     else if (ye + d->borderY > contentsY() + curHeight)
02057             deltay = ye + d->borderY - ( contentsY() + curHeight );
02058     else
02059         deltay = 0;
02060 
02061     int maxx = curWidth-d->borderX;
02062     int maxy = curHeight-d->borderY;
02063 
02064     int scrollX,scrollY;
02065 
02066     scrollX = deltax > 0 ? (deltax > maxx ? maxx : deltax) : deltax == 0 ? 0 : (deltax>-maxx ? deltax : -maxx);
02067     scrollY = deltay > 0 ? (deltay > maxy ? maxy : deltay) : deltay == 0 ? 0 : (deltay>-maxy ? deltay : -maxy);
02068 
02069     if (contentsX() + scrollX < 0)
02070     scrollX = -contentsX();
02071     else if (contentsWidth() - visibleWidth() - contentsX() < scrollX)
02072     scrollX = contentsWidth() - visibleWidth() - contentsX();
02073 
02074     if (contentsY() + scrollY < 0)
02075     scrollY = -contentsY();
02076     else if (contentsHeight() - visibleHeight() - contentsY() < scrollY)
02077     scrollY = contentsHeight() - visibleHeight() - contentsY();
02078 
02079     scrollBy(scrollX, scrollY);
02080 
02081     d->scrollingSelf = false;
02082 
02083     if ( (abs(deltax)<=maxx) && (abs(deltay)<=maxy) )
02084     return true;
02085     else return false;
02086 
02087 }
02088 
02089 bool KHTMLView::focusNextPrevNode(bool next)
02090 {
02091     // Sets the focus node of the document to be the node after (or if
02092     // next is false, before) the current focus node.  Only nodes that
02093     // are selectable (i.e. for which isFocusable() returns true) are
02094     // taken into account, and the order used is that specified in the
02095     // HTML spec (see DocumentImpl::nextFocusNode() and
02096     // DocumentImpl::previousFocusNode() for details).
02097 
02098     DocumentImpl *doc = m_part->xmlDocImpl();
02099     NodeImpl *oldFocusNode = doc->focusNode();
02100 
02101     // See whether we're in the middle of detach. If so, we want to
02102     // clear focus... The document code will be careful to not
02103     // emit events in that case..
02104     if (oldFocusNode && oldFocusNode->renderer() &&
02105         !oldFocusNode->renderer()->parent()) {
02106         doc->setFocusNode(0);
02107         return true;
02108     }
02109 
02110 #if 1
02111     // If the user has scrolled the document, then instead of picking
02112     // the next focusable node in the document, use the first one that
02113     // is within the visible area (if possible).
02114     if (d->scrollBarMoved)
02115     {
02116     NodeImpl *toFocus;
02117     if (next)
02118         toFocus = doc->nextFocusNode(oldFocusNode);
02119     else
02120         toFocus = doc->previousFocusNode(oldFocusNode);
02121 
02122     if (!toFocus && oldFocusNode)
02123         if (next)
02124         toFocus = doc->nextFocusNode(NULL);
02125         else
02126         toFocus = doc->previousFocusNode(NULL);
02127 
02128     while (toFocus && toFocus != oldFocusNode)
02129     {
02130 
02131         QRect focusNodeRect = toFocus->getRect();
02132         if ((focusNodeRect.left() > contentsX()) && (focusNodeRect.right() < contentsX() + visibleWidth()) &&
02133         (focusNodeRect.top() > contentsY()) && (focusNodeRect.bottom() < contentsY() + visibleHeight())) {
02134         {
02135             QRect r = toFocus->getRect();
02136             ensureVisible( r.right(), r.bottom());
02137             ensureVisible( r.left(), r.top());
02138             d->scrollBarMoved = false;
02139             d->tabMovePending = false;
02140             d->lastTabbingDirection = next;
02141             d->pseudoFocusNode = KHTMLViewPrivate::PFNone;
02142             m_part->xmlDocImpl()->setFocusNode(toFocus);
02143             Node guard(toFocus);
02144             if (!toFocus->hasOneRef() )
02145             {
02146             emit m_part->nodeActivated(Node(toFocus));
02147             }
02148             return true;
02149         }
02150         }
02151         if (next)
02152         toFocus = doc->nextFocusNode(toFocus);
02153         else
02154         toFocus = doc->previousFocusNode(toFocus);
02155 
02156         if (!toFocus && oldFocusNode)
02157         if (next)
02158             toFocus = doc->nextFocusNode(NULL);
02159         else
02160             toFocus = doc->previousFocusNode(NULL);
02161     }
02162 
02163     d->scrollBarMoved = false;
02164     }
02165 #endif
02166 
02167     if (!oldFocusNode && d->pseudoFocusNode == KHTMLViewPrivate::PFNone)
02168     {
02169     ensureVisible(contentsX(), next?0:contentsHeight());
02170     d->scrollBarMoved = false;
02171     d->pseudoFocusNode = next?KHTMLViewPrivate::PFTop:KHTMLViewPrivate::PFBottom;
02172     return true;
02173     }
02174 
02175     NodeImpl *newFocusNode = NULL;
02176 
02177     if (d->tabMovePending && next != d->lastTabbingDirection)
02178     {
02179     //kdDebug ( 6000 ) << " tab move pending and tabbing direction changed!\n";
02180     newFocusNode = oldFocusNode;
02181     }
02182     else if (next)
02183     {
02184     if (oldFocusNode || d->pseudoFocusNode == KHTMLViewPrivate::PFTop )
02185         newFocusNode = doc->nextFocusNode(oldFocusNode);
02186     }
02187     else
02188     {
02189     if (oldFocusNode || d->pseudoFocusNode == KHTMLViewPrivate::PFBottom )
02190         newFocusNode = doc->previousFocusNode(oldFocusNode);
02191     }
02192 
02193     bool targetVisible = false;
02194     if (!newFocusNode)
02195     {
02196     if ( next )
02197     {
02198         targetVisible = scrollTo(QRect(contentsX()+visibleWidth()/2,contentsHeight()-d->borderY,0,0));
02199     }
02200     else
02201     {
02202         targetVisible = scrollTo(QRect(contentsX()+visibleWidth()/2,d->borderY,0,0));
02203     }
02204     }
02205     else
02206     {
02207 #ifndef KHTML_NO_CARET
02208         // if it's an editable element, activate the caret
02209         if (!m_part->isCaretMode() && !m_part->isEditable()
02210         && newFocusNode->contentEditable()) {
02211         d->caretViewContext();
02212         moveCaretTo(newFocusNode, 0L, true);
02213         } else {
02214         caretOff();
02215     }
02216 #endif // KHTML_NO_CARET
02217 
02218     targetVisible = scrollTo(newFocusNode->getRect());
02219     }
02220 
02221     if (targetVisible)
02222     {
02223     //kdDebug ( 6000 ) << " target reached.\n";
02224     d->tabMovePending = false;
02225 
02226     m_part->xmlDocImpl()->setFocusNode(newFocusNode);
02227     if (newFocusNode)
02228     {
02229         Node guard(newFocusNode);
02230         if (!newFocusNode->hasOneRef() )
02231         {
02232         emit m_part->nodeActivated(Node(newFocusNode));
02233         }
02234         return true;
02235     }
02236     else
02237     {
02238         d->pseudoFocusNode = next?KHTMLViewPrivate::PFBottom:KHTMLViewPrivate::PFTop;
02239         return false;
02240     }
02241     }
02242     else
02243     {
02244     if (!d->tabMovePending)
02245         d->lastTabbingDirection = next;
02246     d->tabMovePending = true;
02247     return true;
02248     }
02249 }
02250 
02251 void KHTMLView::displayAccessKeys()
02252 {
02253     QValueVector< QChar > taken;
02254     displayAccessKeys( NULL, this, taken, false );
02255     displayAccessKeys( NULL, this, taken, true );
02256 }
02257 
02258 void KHTMLView::displayAccessKeys( KHTMLView* caller, KHTMLView* origview, QValueVector< QChar >& taken, bool use_fallbacks )
02259 {
02260     QMap< ElementImpl*, QChar > fallbacks;
02261     if( use_fallbacks )
02262         fallbacks = buildFallbackAccessKeys();
02263     for( NodeImpl* n = m_part->xmlDocImpl(); n != NULL; n = n->traverseNextNode()) {
02264         if( n->isElementNode()) {
02265             ElementImpl* en = static_cast< ElementImpl* >( n );
02266             DOMString s = en->getAttribute( ATTR_ACCESSKEY );
02267             QString accesskey;
02268             if( s.length() == 1 ) {
02269                 QChar a = s.string()[ 0 ].upper();
02270                 if( qFind( taken.begin(), taken.end(), a ) == taken.end()) // !contains
02271                     accesskey = a;
02272             }
02273             if( accesskey.isNull() && fallbacks.contains( en )) {
02274                 QChar a = fallbacks[ en ].upper();
02275                 if( qFind( taken.begin(), taken.end(), a ) == taken.end()) // !contains
02276                     accesskey = QString( "<qt><i>" ) + a + "</i></qt>";
02277             }
02278             if( !accesskey.isNull()) {
02279             QRect rec=en->getRect();
02280             QLabel *lab=new QLabel(accesskey,viewport(),0,Qt::WDestructiveClose);
02281             connect( origview, SIGNAL(hideAccessKeys()), lab, SLOT(close()) );
02282             connect( this, SIGNAL(repaintAccessKeys()), lab, SLOT(repaint()));
02283             lab->setPalette(QToolTip::palette());
02284             lab->setLineWidth(2);
02285             lab->setFrameStyle(QFrame::Box | QFrame::Plain);
02286             lab->setMargin(3);
02287             lab->adjustSize();
02288             addChild(lab,
02289                     KMIN(rec.left()+rec.width()/2, contentsWidth() - lab->width()),
02290                     KMIN(rec.top()+rec.height()/2, contentsHeight() - lab->height()));
02291             showChild(lab);
02292                 taken.append( accesskey[ 0 ] );
02293         }
02294         }
02295     }
02296     if( use_fallbacks )
02297         return;
02298     QPtrList<KParts::ReadOnlyPart> frames = m_part->frames();
02299     for( QPtrListIterator<KParts::ReadOnlyPart> it( frames );
02300          it != NULL;
02301          ++it ) {
02302         if( !(*it)->inherits( "KHTMLPart" ))
02303             continue;
02304         KHTMLPart* part = static_cast< KHTMLPart* >( *it );
02305         if( part->view() && part->view() != caller )
02306             part->view()->displayAccessKeys( this, origview, taken, use_fallbacks );
02307     }
02308     // pass up to the parent
02309     if (m_part->parentPart() && m_part->parentPart()->view()
02310         && m_part->parentPart()->view() != caller)
02311         m_part->parentPart()->view()->displayAccessKeys( this, origview, taken, use_fallbacks );
02312 }
02313 
02314 
02315 
02316 void KHTMLView::accessKeysTimeout()
02317 {
02318 d->accessKeysActivated=false;
02319 d->accessKeysPreActivate = false;
02320 m_part->setStatusBarText(QString::null, KHTMLPart::BarOverrideText);
02321 emit hideAccessKeys();
02322 }
02323 
02324 // Handling of the HTML accesskey attribute.
02325 bool KHTMLView::handleAccessKey( const QKeyEvent* ev )
02326 {
02327 // Qt interprets the keyevent also with the modifiers, and ev->text() matches that,
02328 // but this code must act as if the modifiers weren't pressed
02329     QChar c;
02330     if( ev->key() >= Key_A && ev->key() <= Key_Z )
02331         c = 'A' + ev->key() - Key_A;
02332     else if( ev->key() >= Key_0 && ev->key() <= Key_9 )
02333         c = '0' + ev->key() - Key_0;
02334     else {
02335         // TODO fake XKeyEvent and XLookupString ?
02336         // This below seems to work e.g. for eacute though.
02337         if( ev->text().length() == 1 )
02338             c = ev->text()[ 0 ];
02339     }
02340     if( c.isNull())
02341         return false;
02342     return focusNodeWithAccessKey( c );
02343 }
02344 
02345 bool KHTMLView::focusNodeWithAccessKey( QChar c, KHTMLView* caller )
02346 {
02347     DocumentImpl *doc = m_part->xmlDocImpl();
02348     if( !doc )
02349         return false;
02350     ElementImpl* node = doc->findAccessKeyElement( c );
02351     if( !node ) {
02352         QPtrList<KParts::ReadOnlyPart> frames = m_part->frames();
02353         for( QPtrListIterator<KParts::ReadOnlyPart> it( frames );
02354              it != NULL;
02355              ++it ) {
02356             if( !(*it)->inherits( "KHTMLPart" ))
02357                 continue;
02358             KHTMLPart* part = static_cast< KHTMLPart* >( *it );
02359             if( part->view() && part->view() != caller
02360                 && part->view()->focusNodeWithAccessKey( c, this ))
02361                 return true;
02362         }
02363         // pass up to the parent
02364         if (m_part->parentPart() && m_part->parentPart()->view()
02365             && m_part->parentPart()->view() != caller
02366             && m_part->parentPart()->view()->focusNodeWithAccessKey( c, this ))
02367             return true;
02368         if( caller == NULL ) { // the active frame (where the accesskey was pressed)
02369             QMap< ElementImpl*, QChar > fallbacks = buildFallbackAccessKeys();
02370             for( QMap< ElementImpl*, QChar >::ConstIterator it = fallbacks.begin();
02371                  it != fallbacks.end();
02372                  ++it )
02373                 if( *it == c ) {
02374                     node = it.key();
02375                     break;
02376                 }
02377         }
02378         if( node == NULL )
02379             return false;
02380     }
02381 
02382     // Scroll the view as necessary to ensure that the new focus node is visible
02383 #ifndef KHTML_NO_CARET
02384     // if it's an editable element, activate the caret
02385     if (!m_part->isCaretMode() && !m_part->isEditable()
02386     && node->contentEditable()) {
02387         d->caretViewContext();
02388         moveCaretTo(node, 0L, true);
02389     } else {
02390         caretOff();
02391     }
02392 #endif // KHTML_NO_CARET
02393 
02394     QRect r = node->getRect();
02395     ensureVisible( r.right(), r.bottom());
02396     ensureVisible( r.left(), r.top());
02397 
02398     Node guard( node );
02399     if( node->isFocusable()) {
02400     if (node->id()==ID_LABEL) {
02401         // if Accesskey is a label, give focus to the label's referrer.
02402         node=static_cast<ElementImpl *>(static_cast< HTMLLabelElementImpl* >( node )->getFormElement());
02403         if (!node) return true;
02404             guard = node;
02405     }
02406         // Set focus node on the document
02407         QFocusEvent::setReason( QFocusEvent::Shortcut );
02408         m_part->xmlDocImpl()->setFocusNode(node);
02409         QFocusEvent::resetReason();
02410         if( node != NULL && node->hasOneRef()) // deleted, only held by guard
02411             return true;
02412         emit m_part->nodeActivated(Node(node));
02413         if( node != NULL && node->hasOneRef())
02414             return true;
02415     }
02416 
02417     switch( node->id()) {
02418         case ID_A:
02419             static_cast< HTMLAnchorElementImpl* >( node )->click();
02420           break;
02421         case ID_INPUT:
02422             static_cast< HTMLInputElementImpl* >( node )->click();
02423           break;
02424         case ID_BUTTON:
02425             static_cast< HTMLButtonElementImpl* >( node )->click();
02426           break;
02427         case ID_AREA:
02428             static_cast< HTMLAreaElementImpl* >( node )->click();
02429           break;
02430         case ID_TEXTAREA:
02431       break; // just focusing it is enough
02432         case ID_LEGEND:
02433             // TODO
02434           break;
02435     }
02436     return true;
02437 }
02438 
02439 static QString getElementText( NodeImpl* start, bool after )
02440 {
02441     QString ret;             // nextSibling(), to go after e.g. </select>
02442     for( NodeImpl* n = after ? start->nextSibling() : start->traversePreviousNode();
02443          n != NULL;
02444          n = after ? n->traverseNextNode() : n->traversePreviousNode()) {
02445         if( n->isTextNode()) {
02446             if( after )
02447                 ret += static_cast< TextImpl* >( n )->toString().string();
02448             else
02449                 ret.prepend( static_cast< TextImpl* >( n )->toString().string());
02450         } else {
02451             switch( n->id()) {
02452                 case ID_A:
02453                 case ID_FONT:
02454                 case ID_TT:
02455                 case ID_U:
02456                 case ID_B:
02457                 case ID_I:
02458                 case ID_S:
02459                 case ID_STRIKE:
02460                 case ID_BIG:
02461                 case ID_SMALL:
02462                 case ID_EM:
02463                 case ID_STRONG:
02464                 case ID_DFN:
02465                 case ID_CODE:
02466                 case ID_SAMP:
02467                 case ID_KBD:
02468                 case ID_VAR:
02469                 case ID_CITE:
02470                 case ID_ABBR:
02471                 case ID_ACRONYM:
02472                 case ID_SUB:
02473                 case ID_SUP:
02474                 case ID_SPAN:
02475                 case ID_NOBR:
02476                 case ID_WBR:
02477                     break;
02478                 case ID_TD:
02479                     if( ret.stripWhiteSpace().isEmpty())
02480                         break;
02481                     // fall through
02482                 default:
02483                     return ret.simplifyWhiteSpace();
02484             }
02485         }
02486     }
02487     return ret.simplifyWhiteSpace();
02488 }
02489 
02490 static QMap< NodeImpl*, QString > buildLabels( NodeImpl* start )
02491 {
02492     QMap< NodeImpl*, QString > ret;
02493     for( NodeImpl* n = start;
02494          n != NULL;
02495          n = n->traverseNextNode()) {
02496         if( n->id() == ID_LABEL ) {
02497             HTMLLabelElementImpl* label = static_cast< HTMLLabelElementImpl* >( n );
02498             NodeImpl* labelfor = label->getFormElement();
02499             if( labelfor )
02500                 ret[ labelfor ] = label->innerText().string().simplifyWhiteSpace();
02501         }
02502     }
02503     return ret;
02504 }
02505 
02506 namespace khtml {
02507 struct AccessKeyData {
02508     ElementImpl* element;
02509     QString text;
02510     QString url;
02511     int priority; // 10(highest) - 0(lowest)
02512 };
02513 }
02514 
02515 QMap< ElementImpl*, QChar > KHTMLView::buildFallbackAccessKeys() const
02516 {
02517     // build a list of all possible candidate elements that could use an accesskey
02518     QValueList< AccessKeyData > data;
02519     QMap< NodeImpl*, QString > labels = buildLabels( m_part->xmlDocImpl());
02520     for( NodeImpl* n = m_part->xmlDocImpl();
02521          n != NULL;
02522          n = n->traverseNextNode()) {
02523         if( n->isElementNode()) {
02524             ElementImpl* element = static_cast< ElementImpl* >( n );
02525             if( element->getAttribute( ATTR_ACCESSKEY ).length() == 1 )
02526                 continue; // has accesskey set, ignore
02527             if( element->renderer() == NULL )
02528                 continue; // not visible
02529             QString text;
02530             QString url;
02531             int priority = 0;
02532             bool ignore = false;
02533             bool text_after = false;
02534             bool text_before = false;
02535             switch( element->id()) {
02536                 case ID_A:
02537                     url = khtml::parseURL(element->getAttribute(ATTR_HREF)).string();
02538                     if( url.isEmpty()) // doesn't have href, it's only an anchor
02539                         continue;
02540                     text = static_cast< HTMLElementImpl* >( element )->innerText().string().simplifyWhiteSpace();
02541                     priority = 2;
02542                     break;
02543                 case ID_INPUT: {
02544                     HTMLInputElementImpl* in = static_cast< HTMLInputElementImpl* >( element );
02545                     switch( in->inputType()) {
02546                         case HTMLInputElementImpl::SUBMIT:
02547                             text = in->value().string();
02548                             if( text.isEmpty())
02549                                 text = i18n( "Submit" );
02550                             priority = 7;
02551                             break;
02552                         case HTMLInputElementImpl::IMAGE:
02553                             text = in->altText().string();
02554                             priority = 7;
02555                             break;
02556                         case HTMLInputElementImpl::BUTTON:
02557                             text = in->value().string();
02558                             priority = 5;
02559                             break;
02560                         case HTMLInputElementImpl::RESET:
02561                             text = in->value().string();
02562                             if( text.isEmpty())
02563                                 text = i18n( "Reset" );
02564                             priority = 5;
02565                             break;
02566                         case HTMLInputElementImpl::HIDDEN:
02567                             ignore = true;
02568                             break;
02569                         case HTMLInputElementImpl::CHECKBOX:
02570                         case HTMLInputElementImpl::RADIO:
02571                             text_after = true;
02572                             priority = 5;
02573                             break;
02574                         case HTMLInputElementImpl::TEXT:
02575                         case HTMLInputElementImpl::PASSWORD:
02576                         case HTMLInputElementImpl::FILE:
02577                             text_before = true;
02578                             priority = 5;
02579                             break;
02580                         default:
02581                             priority = 5;
02582                             break;
02583                     }
02584                     break;
02585                 }
02586                 case ID_BUTTON:
02587                     text = static_cast< HTMLElementImpl* >( element )->innerText().string().simplifyWhiteSpace();
02588                     switch( static_cast< HTMLButtonElementImpl* >( element )->buttonType()) {
02589                         case HTMLButtonElementImpl::SUBMIT:
02590                             if( text.isEmpty())
02591                                 text = i18n( "Submit" );
02592                             priority = 7;
02593                             break;
02594                         case HTMLButtonElementImpl::RESET:
02595                             if( text.isEmpty())
02596                                 text = i18n( "Reset" );
02597                             priority = 5;
02598                             break;
02599                         default:
02600                             priority = 5;
02601                             break;
02602                     break;
02603                     }
02604                 case ID_SELECT: // these don't have accesskey attribute, but quick access may be handy
02605                     text_before = true;
02606                     text_after = true;
02607                     priority = 5;
02608                     break;
02609                 case ID_FRAME:
02610                     ignore = true;
02611                     break;
02612                 default:
02613                     ignore = !element->isFocusable();
02614                     priority = 2;
02615                     break;
02616             }
02617             if( ignore )
02618                 continue;
02619             if( text.isNull() && labels.contains( element ))
02620                 text = labels[ element ];
02621             if( text.isNull() && text_before )
02622                 text = getElementText( element, false );
02623             if( text.isNull() && text_after )
02624                 text = getElementText( element, true );
02625             text = text.stripWhiteSpace();
02626             // increase priority of items which have explicitly specified accesskeys in the config
02627             QValueList< QPair< QString, QChar > > priorities
02628                 = m_part->settings()->fallbackAccessKeysAssignments();
02629             for( QValueList< QPair< QString, QChar > >::ConstIterator it = priorities.begin();
02630                  it != priorities.end();
02631                  ++it ) {
02632                 if( text == (*it).first )
02633                     priority = 10;
02634             }
02635             AccessKeyData tmp = { element, text, url, priority };
02636             data.append( tmp );
02637         }
02638     }
02639 
02640     QValueList< QChar > keys;
02641     for( char c = 'A'; c <= 'Z'; ++c )
02642         keys << c;
02643     for( char c = '0'; c <= '9'; ++c )
02644         keys << c;
02645     for( NodeImpl* n = m_part->xmlDocImpl();
02646          n != NULL;
02647          n = n->traverseNextNode()) {
02648         if( n->isElementNode()) {
02649             ElementImpl* en = static_cast< ElementImpl* >( n );
02650             DOMString s = en->getAttribute( ATTR_ACCESSKEY );
02651             if( s.length() == 1 ) {
02652                 QChar c = s.string()[ 0 ].upper();
02653                 keys.remove( c ); // remove manually assigned accesskeys
02654             }
02655         }
02656     }
02657 
02658     QMap< ElementImpl*, QChar > ret;
02659     for( int priority = 10;
02660          priority >= 0;
02661          --priority ) {
02662         for( QValueList< AccessKeyData >::Iterator it = data.begin();
02663              it != data.end();
02664              ) {
02665             if( (*it).priority != priority ) {
02666                 ++it;
02667                 continue;
02668             }
02669             if( keys.isEmpty())
02670                 break;
02671             QString text = (*it).text;
02672             QChar key;
02673             if( key.isNull() && !text.isEmpty()) {
02674                 QValueList< QPair< QString, QChar > > priorities
02675                     = m_part->settings()->fallbackAccessKeysAssignments();
02676                 for( QValueList< QPair< QString, QChar > >::ConstIterator it = priorities.begin();
02677                      it != priorities.end();
02678                      ++it )
02679                     if( text == (*it).first && keys.contains( (*it).second )) {
02680                         key = (*it).second;
02681                         break;
02682                     }
02683             }
02684             // try first to select the first character as the accesskey,
02685             // then first character of the following words,
02686             // and then simply the first free character
02687             if( key.isNull() && !text.isEmpty()) {
02688                 QStringList words = QStringList::split( ' ', text );
02689                 for( QStringList::ConstIterator it = words.begin();
02690                      it != words.end();
02691                      ++it ) {
02692                     if( keys.contains( (*it)[ 0 ].upper())) {
02693                         key = (*it)[ 0 ].upper();
02694                         break;
02695                     }
02696                 }
02697             }
02698             if( key.isNull() && !text.isEmpty()) {
02699                 for( unsigned int i = 0;
02700                      i < text.length();
02701                      ++i ) {
02702                     if( keys.contains( text[ i ].upper())) {
02703                         key = text[ i ].upper();
02704                         break;
02705                     }
02706                 }
02707             }
02708             if( key.isNull())
02709                 key = keys.front();
02710             ret[ (*it).element ] = key;
02711             keys.remove( key );
02712             QString url = (*it).url;
02713             it = data.remove( it );
02714             // assign the same accesskey also to other elements pointing to the same url
02715             if( !url.isEmpty() && !url.startsWith( "javascript:", false )) {
02716                 for( QValueList< AccessKeyData >::Iterator it2 = data.begin();
02717                      it2 != data.end();
02718                      ) {
02719                     if( (*it2).url == url ) {
02720                         ret[ (*it2).element ] = key;
02721                         if( it == it2 )
02722                             ++it;
02723                         it2 = data.remove( it2 );
02724                     } else
02725                         ++it2;
02726                 }
02727             }
02728         }
02729     }
02730     return ret;
02731 }
02732 
02733 void KHTMLView::setMediaType( const QString &medium )
02734 {
02735     m_medium = medium;
02736 }
02737 
02738 QString KHTMLView::mediaType() const
02739 {
02740     return m_medium;
02741 }
02742 
02743 bool KHTMLView::pagedMode() const
02744 {
02745     return d->paged;
02746 }
02747 
02748 void KHTMLView::setWidgetVisible(RenderWidget* w, bool vis)
02749 {
02750     if (vis) {
02751         d->visibleWidgets.replace(w, w->widget());
02752     }
02753     else
02754         d->visibleWidgets.remove(w);
02755 }
02756 
02757 bool KHTMLView::needsFullRepaint() const
02758 {
02759     return d->needsFullRepaint;
02760 }
02761 
02762 void KHTMLView::print()
02763 {
02764     print( false );
02765 }
02766 
02767 void KHTMLView::print(bool quick)
02768 {
02769     if(!m_part->xmlDocImpl()) return;
02770     khtml::RenderCanvas *root = static_cast<khtml::RenderCanvas *>(m_part->xmlDocImpl()->renderer());
02771     if(!root) return;
02772 
02773     KPrinter *printer = new KPrinter(true, QPrinter::ScreenResolution);
02774     printer->addDialogPage(new KHTMLPrintSettings());
02775     QString docname = m_part->xmlDocImpl()->URL().prettyURL();
02776     if ( !docname.isEmpty() )
02777         docname = KStringHandler::csqueeze(docname, 80);
02778     if(quick || printer->setup(this, i18n("Print %1").arg(docname))) {
02779         viewport()->setCursor( waitCursor ); // only viewport(), no QApplication::, otherwise we get the busy cursor in kdeprint's dialogs
02780         // set up KPrinter
02781         printer->setFullPage(false);
02782         printer->setCreator(QString("KDE %1.%2.%3 HTML Library").arg(KDE_VERSION_MAJOR).arg(KDE_VERSION_MINOR).arg(KDE_VERSION_RELEASE));
02783         printer->setDocName(docname);
02784 
02785         QPainter *p = new QPainter;
02786         p->begin( printer );
02787         khtml::setPrintPainter( p );
02788 
02789         m_part->xmlDocImpl()->setPaintDevice( printer );
02790         QString oldMediaType = mediaType();
02791         setMediaType( "print" );
02792         // We ignore margin settings for html and body when printing
02793         // and use the default margins from the print-system
02794         // (In Qt 3.0.x the default margins are hardcoded in Qt)
02795         m_part->xmlDocImpl()->setPrintStyleSheet( printer->option("app-khtml-printfriendly") == "true" ?
02796                                                   "* { background-image: none !important;"
02797                                                   "    background-color: white !important;"
02798                                                   "    color: black !important; }"
02799                           "body { margin: 0px !important; }"
02800                           "html { margin: 0px !important; }" :
02801                           "body { margin: 0px !important; }"
02802                           "html { margin: 0px !important; }"
02803                           );
02804 
02805         QPaintDeviceMetrics metrics( printer );
02806 
02807         kdDebug(6000) << "printing: physical page width = " << metrics.width()
02808                       << " height = " << metrics.height() << endl;
02809         root->setStaticMode(true);
02810         root->setPagedMode(true);
02811         root->setWidth(metrics.width());
02812 //         root->setHeight(metrics.height());
02813         root->setPageTop(0);
02814         root->setPageBottom(0);
02815         d->paged = true;
02816 
02817         m_part->xmlDocImpl()->styleSelector()->computeFontSizes(&metrics, 100);
02818         m_part->xmlDocImpl()->updateStyleSelector();
02819         root->setPrintImages( printer->option("app-khtml-printimages") == "true");
02820         root->makePageBreakAvoidBlocks();
02821 
02822         root->setNeedsLayoutAndMinMaxRecalc();
02823         root->layout();
02824         khtml::RenderWidget::flushWidgetResizes(); // make sure widgets have their final size
02825 
02826         // check sizes ask for action.. (scale or clip)
02827 
02828         bool printHeader = (printer->option("app-khtml-printheader") == "true");
02829 
02830         int headerHeight = 0;
02831         QFont headerFont("Sans Serif", 8);
02832 
02833         QString headerLeft = KGlobal::locale()->formatDate(QDate::currentDate(),true);
02834         QString headerMid = docname;
02835         QString headerRight;
02836 
02837         if (printHeader)
02838         {
02839            p->setFont(headerFont);
02840            headerHeight = (p->fontMetrics().lineSpacing() * 3) / 2;
02841         }
02842 
02843         // ok. now print the pages.
02844         kdDebug(6000) << "printing: html page width = " << root->docWidth()
02845                       << " height = " << root->docHeight() << endl;
02846         kdDebug(6000) << "printing: margins left = " << printer->margins().width()
02847                       << " top = " << printer->margins().height() << endl;
02848         kdDebug(6000) << "printing: paper width = " << metrics.width()
02849                       << " height = " << metrics.height() << endl;
02850         // if the width is too large to fit on the paper we just scale
02851         // the whole thing.
02852         int pageWidth = metrics.width();
02853         int pageHeight = metrics.height();
02854         p->setClipRect(0,0, pageWidth, pageHeight);
02855 
02856         pageHeight -= headerHeight;
02857 
02858         bool scalePage = false;
02859         double scale = 0.0;
02860 #ifndef QT_NO_TRANSFORMATIONS
02861         if(root->docWidth() > metrics.width()) {
02862             scalePage = true;
02863             scale = ((double) metrics.width())/((double) root->docWidth());
02864             pageHeight = (int) (pageHeight/scale);
02865             pageWidth = (int) (pageWidth/scale);
02866             headerHeight = (int) (headerHeight/scale);
02867         }
02868 #endif
02869         kdDebug(6000) << "printing: scaled html width = " << pageWidth
02870                       << " height = " << pageHeight << endl;
02871 
02872         root->setHeight(pageHeight);
02873         root->setPageBottom(pageHeight);
02874         root->setNeedsLayout(true);
02875         root->layoutIfNeeded();
02876 //         m_part->slotDebugRenderTree();
02877 
02878         // Squeeze header to make it it on the page.
02879         if (printHeader)
02880         {
02881             int available_width = metrics.width() - 10 -
02882                 2 * kMax(p->boundingRect(0, 0, metrics.width(), p->fontMetrics().lineSpacing(), Qt::AlignLeft, headerLeft).width(),
02883                          p->boundingRect(0, 0, metrics.width(), p->fontMetrics().lineSpacing(), Qt::AlignLeft, headerRight).width());
02884             if (available_width < 150)
02885                available_width = 150;
02886             int mid_width;
02887             int squeeze = 120;
02888             do {
02889                 headerMid = KStringHandler::csqueeze(docname, squeeze);
02890                 mid_width = p->boundingRect(0, 0, metrics.width(), p->fontMetrics().lineSpacing(), Qt::AlignLeft, headerMid).width();
02891                 squeeze -= 10;
02892             } while (mid_width > available_width);
02893         }
02894 
02895         int top = 0;
02896         int bottom = 0;
02897         int page = 1;
02898         while(top < root->docHeight()) {
02899             if(top > 0) printer->newPage();
02900             p->setClipRect(0, 0, pageWidth, headerHeight, QPainter::CoordDevice);
02901             if (printHeader)
02902             {
02903                 int dy = p->fontMetrics().lineSpacing();
02904                 p->setPen(Qt::black);
02905                 p->setFont(headerFont);
02906 
02907                 headerRight = QString("#%1").arg(page);
02908 
02909                 p->drawText(0, 0, metrics.width(), dy, Qt::AlignLeft, headerLeft);
02910                 p->drawText(0, 0, metrics.width(), dy, Qt::AlignHCenter, headerMid);
02911                 p->drawText(0, 0, metrics.width(), dy, Qt::AlignRight, headerRight);
02912             }
02913 
02914 
02915 #ifndef QT_NO_TRANSFORMATIONS
02916             if (scalePage)
02917                 p->scale(scale, scale);
02918 #endif
02919 
02920             p->setClipRect(0, headerHeight, pageWidth, pageHeight, QPainter::CoordDevice);
02921             p->translate(0, headerHeight-top);
02922 
02923             bottom = top+pageHeight;
02924 
02925             root->setPageTop(top);
02926             root->setPageBottom(bottom);
02927             root->setPageNumber(page);
02928 
02929             root->layer()->paint(p, QRect(0, top, pageWidth, pageHeight));
02930 //             m_part->xmlDocImpl()->renderer()->layer()->paint(p, QRect(0, top, pageWidth, pageHeight));
02931 //             root->repaint();
02932 //             p->flush();
02933             kdDebug(6000) << "printed: page " << page <<" bottom At = " << bottom << endl;
02934 
02935             top = bottom;
02936             p->resetXForm();
02937             page++;
02938         }
02939 
02940         p->end();
02941         delete p;
02942 
02943         // and now reset the layout to the usual one...
02944         root->setPagedMode(false);
02945         root->setStaticMode(false);
02946         d->paged = false;
02947         khtml::setPrintPainter( 0 );
02948         setMediaType( oldMediaType );
02949         m_part->xmlDocImpl()->setPaintDevice( this );
02950         m_part->xmlDocImpl()->styleSelector()->computeFontSizes(m_part->xmlDocImpl()->paintDeviceMetrics(), m_part->zoomFactor());
02951         m_part->xmlDocImpl()->updateStyleSelector();
02952         viewport()->unsetCursor();
02953     }
02954     delete printer;
02955 }
02956 
02957 void KHTMLView::slotPaletteChanged()
02958 {
02959     if(!m_part->xmlDocImpl()) return;
02960     DOM::DocumentImpl *document = m_part->xmlDocImpl();
02961     if (!document->isHTMLDocument()) return;
02962     khtml::RenderCanvas *root = static_cast<khtml::RenderCanvas *>(document->renderer());
02963     if(!root) return;
02964     root->style()->resetPalette();
02965     NodeImpl *body = static_cast<HTMLDocumentImpl*>(document)->body();
02966     if(!body) return;
02967     body->setChanged(true);
02968     body->recalcStyle( NodeImpl::Force );
02969 }
02970 
02971 void KHTMLView::paint(QPainter *p, const QRect &rc, int yOff, bool *more)
02972 {
02973     if(!m_part->xmlDocImpl()) return;
02974     khtml::RenderCanvas *root = static_cast<khtml::RenderCanvas *>(m_part->xmlDocImpl()->renderer());
02975     if(!root) return;
02976 
02977     m_part->xmlDocImpl()->setPaintDevice(p->device());
02978     root->setPagedMode(true);
02979     root->setStaticMode(true);
02980     root->setWidth(rc.width());
02981 
02982     p->save();
02983     p->setClipRect(rc);
02984     p->translate(rc.left(), rc.top());
02985     double scale = ((double) rc.width()/(double) root->docWidth());
02986     int height = (int) ((double) rc.height() / scale);
02987 #ifndef QT_NO_TRANSFORMATIONS
02988     p->scale(scale, scale);
02989 #endif
02990     root->setPageTop(yOff);
02991     root->setPageBottom(yOff+height);
02992 
02993     root->layer()->paint(p, QRect(0, yOff, root->docWidth(), height));
02994     if (more)
02995         *more = yOff + height < root->docHeight();
02996     p->restore();
02997 
02998     root->setPagedMode(false);
02999     root->setStaticMode(false);
03000     m_part->xmlDocImpl()->setPaintDevice( this );
03001 }
03002 
03003 
03004 void KHTMLView::useSlowRepaints()
03005 {
03006     d->useSlowRepaints = true;
03007     setStaticBackground(true);
03008 }
03009 
03010 
03011 void KHTMLView::setVScrollBarMode ( ScrollBarMode mode )
03012 {
03013 #ifndef KHTML_NO_SCROLLBARS
03014     d->vmode = mode;
03015     QScrollView::setVScrollBarMode(mode);
03016 #else
03017     Q_UNUSED( mode );
03018 #endif
03019 }
03020 
03021 void KHTMLView::setHScrollBarMode ( ScrollBarMode mode )
03022 {
03023 #ifndef KHTML_NO_SCROLLBARS
03024     d->hmode = mode;
03025     QScrollView::setHScrollBarMode(mode);
03026 #else
03027     Q_UNUSED( mode );
03028 #endif
03029 }
03030 
03031 void KHTMLView::restoreScrollBar()
03032 {
03033     int ow = visibleWidth();
03034     QScrollView::setVScrollBarMode(d->vmode);
03035     if (visibleWidth() != ow)
03036         layout();
03037     d->prevScrollbarVisible = verticalScrollBar()->isVisible();
03038 }
03039 
03040 QStringList KHTMLView::formCompletionItems(const QString &name) const
03041 {
03042     if (!m_part->settings()->isFormCompletionEnabled())
03043         return QStringList();
03044     if (!d->formCompletions)
03045         d->formCompletions = new KSimpleConfig(locateLocal("data", "khtml/formcompletions"));
03046     return d->formCompletions->readListEntry(name);
03047 }
03048 
03049 void KHTMLView::clearCompletionHistory(const QString& name)
03050 {
03051     if (!d->formCompletions)
03052     {
03053         d->formCompletions = new KSimpleConfig(locateLocal("data", "khtml/formcompletions"));
03054     }
03055     d->formCompletions->writeEntry(name, "");
03056     d->formCompletions->sync();
03057 }
03058 
03059 void KHTMLView::addFormCompletionItem(const QString &name, const QString &value)
03060 {
03061     if (!m_part->settings()->isFormCompletionEnabled())
03062         return;
03063     // don't store values that are all numbers or just numbers with
03064     // dashes or spaces as those are likely credit card numbers or
03065     // something similar
03066     bool cc_number(true);
03067     for (unsigned int i = 0; i < value.length(); ++i)
03068     {
03069       QChar c(value[i]);
03070       if (!c.isNumber() && c != '-' && !c.isSpace())
03071       {
03072         cc_number = false;
03073         break;
03074       }
03075     }
03076     if (cc_number)
03077       return;
03078     QStringList items = formCompletionItems(name);
03079     if (!items.contains(value))
03080         items.prepend(value);
03081     while ((int)items.count() > m_part->settings()->maxFormCompletionItems())
03082         items.remove(items.fromLast());
03083     d->formCompletions->writeEntry(name, items);
03084 }
03085 
03086 void KHTMLView::addNonPasswordStorableSite(const QString& host)
03087 {
03088     if (!d->formCompletions) {
03089         d->formCompletions = new KSimpleConfig(locateLocal("data", "khtml/formcompletions"));
03090     }
03091 
03092     d->formCompletions->setGroup("NonPasswordStorableSites");
03093     QStringList sites = d->formCompletions->readListEntry("Sites");
03094     sites.append(host);
03095     d->formCompletions->writeEntry("Sites", sites);
03096     d->formCompletions->sync();
03097     d->formCompletions->setGroup(QString::null);//reset
03098 }
03099 
03100 bool KHTMLView::nonPasswordStorableSite(const QString& host) const
03101 {
03102     if (!d->formCompletions) {
03103         d->formCompletions = new KSimpleConfig(locateLocal("data", "khtml/formcompletions"));
03104     }
03105     d->formCompletions->setGroup("NonPasswordStorableSites");
03106     QStringList sites =  d->formCompletions->readListEntry("Sites");
03107     d->formCompletions->setGroup(QString::null);//reset
03108 
03109     return (sites.find(host) != sites.end());
03110 }
03111 
03112 // returns true if event should be swallowed
03113 bool KHTMLView::dispatchMouseEvent(int eventId, DOM::NodeImpl *targetNode,
03114                    DOM::NodeImpl *targetNodeNonShared, bool cancelable,
03115                    int detail,QMouseEvent *_mouse, bool setUnder,
03116                    int mouseEventType)
03117 {
03118     // if the target node is a text node, dispatch on the parent node - rdar://4196646 (and #76948)
03119     if (targetNode && targetNode->isTextNode())
03120         targetNode = targetNode->parentNode();
03121 
03122     if (d->underMouse)
03123     d->underMouse->deref();
03124     d->underMouse = targetNode;
03125     if (d->underMouse)
03126     d->underMouse->ref();
03127 
03128     if (d->underMouseNonShared)
03129     d->underMouseNonShared->deref();
03130     d->underMouseNonShared = targetNodeNonShared;
03131     if (d->underMouseNonShared)
03132     d->underMouseNonShared->ref();
03133 
03134     int exceptioncode = 0;
03135     int pageX = 0;
03136     int pageY = 0;
03137     viewportToContents(_mouse->x(), _mouse->y(), pageX, pageY);
03138     int clientX = pageX - contentsX();
03139     int clientY = pageY - contentsY();
03140     int screenX = _mouse->globalX();
03141     int screenY = _mouse->globalY();
03142     int button = -1;
03143     switch (_mouse->button()) {
03144     case LeftButton:
03145         button = 0;
03146         break;
03147     case MidButton:
03148         button = 1;
03149         break;
03150     case RightButton:
03151         button = 2;
03152         break;
03153     default:
03154         break;
03155     }
03156     if (d->accessKeysEnabled && d->accessKeysPreActivate && button!=-1)
03157         d->accessKeysPreActivate=false;
03158 
03159     bool ctrlKey = (_mouse->state() & ControlButton);
03160     bool altKey = (_mouse->state() & AltButton);
03161     bool shiftKey = (_mouse->state() & ShiftButton);
03162     bool metaKey = (_mouse->state() & MetaButton);
03163 
03164     // mouseout/mouseover
03165     if (setUnder && (d->prevMouseX != pageX || d->prevMouseY != pageY)) {
03166 
03167         // ### this code sucks. we should save the oldUnder instead of calculating
03168         // it again. calculating is expensive! (Dirk)
03169         NodeImpl *oldUnder = 0;
03170     if (d->prevMouseX >= 0 && d->prevMouseY >= 0) {
03171         NodeImpl::MouseEvent mev( _mouse->stateAfter(), static_cast<NodeImpl::MouseEventType>(mouseEventType));
03172         m_part->xmlDocImpl()->prepareMouseEvent( true, d->prevMouseX, d->prevMouseY, &mev );
03173         oldUnder = mev.innerNode.handle();
03174 
03175             if (oldUnder && oldUnder->isTextNode())
03176                 oldUnder = oldUnder->parentNode();
03177     }
03178 //  qDebug("oldunder=%p (%s), target=%p (%s) x/y=%d/%d", oldUnder, oldUnder ? oldUnder->renderer()->renderName() : 0, targetNode,  targetNode ? targetNode->renderer()->renderName() : 0, _mouse->x(), _mouse->y());
03179     if (oldUnder != targetNode) {
03180         // send mouseout event to the old node
03181         if (oldUnder){
03182         oldUnder->ref();
03183         MouseEventImpl *me = new MouseEventImpl(EventImpl::MOUSEOUT_EVENT,
03184                             true,true,m_part->xmlDocImpl()->defaultView(),
03185                             0,screenX,screenY,clientX,clientY,pageX, pageY,
03186                             ctrlKey,altKey,shiftKey,metaKey,
03187                             button,targetNode);
03188         me->ref();
03189         oldUnder->dispatchEvent(me,exceptioncode,true);
03190         me->deref();
03191         }
03192 
03193         // send mouseover event to the new node
03194         if (targetNode) {
03195         MouseEventImpl *me = new MouseEventImpl(EventImpl::MOUSEOVER_EVENT,
03196                             true,true,m_part->xmlDocImpl()->defaultView(),
03197                             0,screenX,screenY,clientX,clientY,pageX, pageY,
03198                             ctrlKey,altKey,shiftKey,metaKey,
03199                             button,oldUnder);
03200 
03201         me->ref();
03202         targetNode->dispatchEvent(me,exceptioncode,true);
03203         me->deref();
03204         }
03205 
03206             if (oldUnder)
03207                 oldUnder->deref();
03208         }
03209     }
03210 
03211     bool swallowEvent = false;
03212 
03213     if (targetNode) {
03214         // send the actual event
03215         bool dblclick = ( eventId == EventImpl::CLICK_EVENT &&
03216                           _mouse->type() == QEvent::MouseButtonDblClick );
03217         MouseEventImpl *me = new MouseEventImpl(static_cast<EventImpl::EventId>(eventId),
03218                         true,cancelable,m_part->xmlDocImpl()->defaultView(),
03219                         detail,screenX,screenY,clientX,clientY,pageX, pageY,
03220                         ctrlKey,altKey,shiftKey,metaKey,
03221                         button,0, _mouse, dblclick );
03222         me->ref();
03223         targetNode->dispatchEvent(me,exceptioncode,true);
03224     bool defaultHandled = me->defaultHandled();
03225         if (defaultHandled || me->defaultPrevented())
03226             swallowEvent = true;
03227         me->deref();
03228 
03229         if (eventId == EventImpl::MOUSEDOWN_EVENT) {
03230             // Focus should be shifted on mouse down, not on a click.  -dwh
03231             // Blur current focus node when a link/button is clicked; this
03232             // is expected by some sites that rely on onChange handlers running
03233             // from form fields before the button click is processed.
03234             DOM::NodeImpl* nodeImpl = targetNode;
03235             for ( ; nodeImpl && !nodeImpl->isFocusable(); nodeImpl = nodeImpl->parentNode());
03236             if (nodeImpl && nodeImpl->isMouseFocusable())
03237                 m_part->xmlDocImpl()->setFocusNode(nodeImpl);
03238             else if (!nodeImpl || !nodeImpl->focused())
03239                 m_part->xmlDocImpl()->setFocusNode(0);
03240         }
03241     }
03242 
03243     return swallowEvent;
03244 }
03245 
03246 void KHTMLView::setIgnoreWheelEvents( bool e )
03247 {
03248     d->ignoreWheelEvents = e;
03249 }
03250 
03251 #ifndef QT_NO_WHEELEVENT
03252 
03253 void KHTMLView::viewportWheelEvent(QWheelEvent* e)
03254 {
03255     if (d->accessKeysEnabled && d->accessKeysPreActivate) d->accessKeysPreActivate=false;
03256 
03257     if ( ( e->state() & ControlButton) == ControlButton )
03258     {
03259         emit zoomView( - e->delta() );
03260         e->accept();
03261     }
03262     else if (d->firstRelayout)
03263     {
03264         e->accept();
03265     }
03266     else if( (   (e->orientation() == Vertical &&
03267                    ((d->ignoreWheelEvents && !verticalScrollBar()->isVisible())
03268                      || e->delta() > 0 && contentsY() <= 0
03269                      || e->delta() < 0 && contentsY() >= contentsHeight() - visibleHeight()))
03270               ||
03271                  (e->orientation() == Horizontal &&
03272                     ((d->ignoreWheelEvents && !horizontalScrollBar()->isVisible())
03273                      || e->delta() > 0 && contentsX() <=0
03274                      || e->delta() < 0 && contentsX() >= contentsWidth() - visibleWidth())))
03275             && m_part->parentPart())
03276     {
03277         if ( m_part->parentPart()->view() )
03278             m_part->parentPart()->view()->wheelEvent( e );
03279         e->ignore();
03280     }
03281     else
03282     {
03283         d->scrollBarMoved = true;
03284 #ifndef NO_SMOOTH_SCROLL_HACK
03285         scrollViewWheelEvent( e );
03286 #else
03287         QScrollView::viewportWheelEvent( e );
03288 #endif
03289     }
03290 
03291 }
03292 #endif
03293 
03294 void KHTMLView::dragEnterEvent( QDragEnterEvent* ev )
03295 {
03296     // Handle drops onto frames (#16820)
03297     // Drops on the main html part is handled by Konqueror (and shouldn't do anything
03298     // in e.g. kmail, so not handled here).
03299     if ( m_part->parentPart() )
03300     {
03301         QApplication::sendEvent(m_part->parentPart()->widget(), ev);
03302     return;
03303     }
03304     QScrollView::dragEnterEvent( ev );
03305 }
03306 
03307 void KHTMLView::dropEvent( QDropEvent *ev )
03308 {
03309     // Handle drops onto frames (#16820)
03310     // Drops on the main html part is handled by Konqueror (and shouldn't do anything
03311     // in e.g. kmail, so not handled here).
03312     if ( m_part->parentPart() )
03313     {
03314         QApplication::sendEvent(m_part->parentPart()->widget(), ev);
03315     return;
03316     }
03317     QScrollView::dropEvent( ev );
03318 }
03319 
03320 void KHTMLView::focusInEvent( QFocusEvent *e )
03321 {
03322 #ifndef KHTML_NO_TYPE_AHEAD_FIND
03323     m_part->enableFindAheadActions( true );
03324 #endif
03325     DOM::NodeImpl* fn = m_part->xmlDocImpl() ? m_part->xmlDocImpl()->focusNode() : 0;
03326     if (fn && fn->renderer() && fn->renderer()->isWidget() &&
03327         (e->reason() != QFocusEvent::Mouse) &&
03328         static_cast<khtml::RenderWidget*>(fn->renderer())->widget())
03329         static_cast<khtml::RenderWidget*>(fn->renderer())->widget()->setFocus();
03330 #ifndef KHTML_NO_CARET
03331     // Restart blink frequency timer if it has been killed, but only on
03332     // editable nodes
03333     if (d->m_caretViewContext &&
03334         d->m_caretViewContext->freqTimerId == -1 &&
03335         fn) {
03336         if (m_part->isCaretMode()
03337         || m_part->isEditable()
03338             || (fn && fn->renderer()
03339             && fn->renderer()->style()->userInput()
03340                 == UI_ENABLED)) {
03341             d->m_caretViewContext->freqTimerId = startTimer(500);
03342         d->m_caretViewContext->visible = true;
03343         }/*end if*/
03344     }/*end if*/
03345     showCaret();
03346 #endif // KHTML_NO_CARET
03347     QScrollView::focusInEvent( e );
03348 }
03349 
03350 void KHTMLView::focusOutEvent( QFocusEvent *e )
03351 {
03352     if(m_part) m_part->stopAutoScroll();
03353 
03354 #ifndef KHTML_NO_TYPE_AHEAD_FIND
03355     if(d->typeAheadActivated)
03356     {
03357         findTimeout();
03358     }
03359     m_part->enableFindAheadActions( false );
03360 #endif // KHTML_NO_TYPE_AHEAD_FIND
03361 
03362 #ifndef KHTML_NO_CARET
03363     if (d->m_caretViewContext) {
03364         switch (d->m_caretViewContext->displayNonFocused) {
03365     case KHTMLPart::CaretInvisible:
03366             hideCaret();
03367         break;
03368     case KHTMLPart::CaretVisible: {
03369         killTimer(d->m_caretViewContext->freqTimerId);
03370         d->m_caretViewContext->freqTimerId = -1;
03371             NodeImpl *caretNode = m_part->xmlDocImpl()->focusNode();
03372         if (!d->m_caretViewContext->visible && (m_part->isCaretMode()
03373         || m_part->isEditable()
03374             || (caretNode && caretNode->renderer()
03375             && caretNode->renderer()->style()->userInput()
03376                 == UI_ENABLED))) {
03377             d->m_caretViewContext->visible = true;
03378             showCaret(true);
03379         }/*end if*/
03380         break;
03381     }
03382     case KHTMLPart::CaretBlink:
03383         // simply leave as is
03384         break;
03385     }/*end switch*/
03386     }/*end if*/
03387 #endif // KHTML_NO_CARET
03388 
03389     if ( d->cursor_icon_widget )
03390         d->cursor_icon_widget->hide();
03391 
03392     QScrollView::focusOutEvent( e );
03393 }
03394 
03395 void KHTMLView::slotScrollBarMoved()
03396 {
03397     if ( !d->firstRelayout && !d->complete && m_part->xmlDocImpl() &&
03398           d->layoutSchedulingEnabled) {
03399         // contents scroll while we are not complete: we need to check our layout *now*
03400         khtml::RenderCanvas* root = static_cast<khtml::RenderCanvas *>( m_part->xmlDocImpl()->renderer() );
03401         if (root && root->needsLayout()) {
03402             unscheduleRelayout();
03403             layout();
03404         }
03405     }
03406     if (!d->scrollingSelf) {
03407         d->scrollBarMoved = true;
03408         d->contentsMoving = true;
03409         // ensure quick reset of contentsMoving flag
03410         scheduleRepaint(0, 0, 0, 0);
03411     }
03412 
03413     if (m_part->xmlDocImpl() && m_part->xmlDocImpl()->documentElement())
03414         m_part->xmlDocImpl()->documentElement()->dispatchHTMLEvent(EventImpl::SCROLL_EVENT, true, false);
03415 }
03416 
03417 void KHTMLView::timerEvent ( QTimerEvent *e )
03418 {
03419 //    kdDebug() << "timer event " << e->timerId() << endl;
03420     if ( e->timerId() == d->scrollTimerId ) {
03421         if( d->scrollSuspended )
03422             return;
03423         switch (d->scrollDirection) {
03424             case KHTMLViewPrivate::ScrollDown:
03425                 if (contentsY() + visibleHeight () >= contentsHeight())
03426                     d->newScrollTimer(this, 0);
03427                 else
03428                     scrollBy( 0, d->scrollBy );
03429                 break;
03430             case KHTMLViewPrivate::ScrollUp:
03431                 if (contentsY() <= 0)
03432                     d->newScrollTimer(this, 0);
03433                 else
03434                     scrollBy( 0, -d->scrollBy );
03435                 break;
03436             case KHTMLViewPrivate::ScrollRight:
03437                 if (contentsX() + visibleWidth () >= contentsWidth())
03438                     d->newScrollTimer(this, 0);
03439                 else
03440                     scrollBy( d->scrollBy, 0 );
03441                 break;
03442             case KHTMLViewPrivate::ScrollLeft:
03443                 if (contentsX() <= 0)
03444                     d->newScrollTimer(this, 0);
03445                 else
03446                     scrollBy( -d->scrollBy, 0 );
03447                 break;
03448         }
03449         return;
03450     }
03451     else if ( e->timerId() == d->layoutTimerId ) {
03452         d->dirtyLayout = true;
03453         layout();
03454         if (d->firstRelayout) {
03455             d->firstRelayout = false;
03456             verticalScrollBar()->setEnabled( true );
03457             horizontalScrollBar()->setEnabled( true );
03458         }
03459     }
03460 #ifndef KHTML_NO_CARET
03461     else if (d->m_caretViewContext
03462              && e->timerId() == d->m_caretViewContext->freqTimerId) {
03463         d->m_caretViewContext->visible = !d->m_caretViewContext->visible;
03464     if (d->m_caretViewContext->displayed) {
03465         updateContents(d->m_caretViewContext->x, d->m_caretViewContext->y,
03466             d->m_caretViewContext->width,
03467             d->m_caretViewContext->height);
03468     }/*end if*/
03469 //  if (d->m_caretViewContext->visible) cout << "|" << flush;
03470 //  else cout << "" << flush;
03471     return;
03472     }
03473 #endif
03474 
03475     d->contentsMoving = false;
03476     if( m_part->xmlDocImpl() ) {
03477     DOM::DocumentImpl *document = m_part->xmlDocImpl();
03478     khtml::RenderCanvas* root = static_cast<khtml::RenderCanvas *>(document->renderer());
03479 
03480     if ( root && root->needsLayout() ) {
03481         killTimer(d->repaintTimerId);
03482         d->repaintTimerId = 0;
03483         scheduleRelayout();
03484         return;
03485     }
03486     }
03487 
03488     setStaticBackground(d->useSlowRepaints);
03489 
03490 //        kdDebug() << "scheduled repaint "<< d->repaintTimerId  << endl;
03491     killTimer(d->repaintTimerId);
03492     d->repaintTimerId = 0;
03493 
03494     QRect updateRegion;
03495     QMemArray<QRect> rects = d->updateRegion.rects();
03496 
03497     d->updateRegion = QRegion();
03498 
03499     if ( rects.size() )
03500         updateRegion = rects[0];
03501 
03502     for ( unsigned i = 1; i < rects.size(); ++i ) {
03503         QRect newRegion = updateRegion.unite(rects[i]);
03504         if (2*newRegion.height() > 3*updateRegion.height() )
03505         {
03506             repaintContents( updateRegion );
03507             updateRegion = rects[i];
03508         }
03509         else
03510             updateRegion = newRegion;
03511     }
03512 
03513     if ( !updateRegion.isNull() )
03514         repaintContents( updateRegion );
03515 
03516     // As widgets can only be accurately positioned during painting, every layout might
03517     // dissociate a widget from its RenderWidget. E.g: if a RenderWidget was visible before layout, but the layout
03518     // pushed it out of the viewport, it will not be repainted, and consequently it's assocoated widget won't be repositioned!
03519     // Thus we need to check each supposedly 'visible' widget at the end of each layout, and remove it in case it's no more in sight.
03520 
03521     if (d->dirtyLayout && !d->visibleWidgets.isEmpty()) {
03522         QWidget* w;
03523         d->dirtyLayout = false;
03524 
03525         QRect visibleRect(contentsX(), contentsY(), visibleWidth(), visibleHeight());
03526         QPtrList<RenderWidget> toRemove;
03527         for (QPtrDictIterator<QWidget> it(d->visibleWidgets); it.current(); ++it) {
03528             int xp = 0, yp = 0;
03529             w = it.current();
03530             RenderWidget* rw = static_cast<RenderWidget*>( it.currentKey() );
03531             if (!rw->absolutePosition(xp, yp) ||
03532                 !visibleRect.intersects(QRect(xp, yp, w->width(), w->height())))
03533                 toRemove.append(rw);
03534         }
03535         for (RenderWidget* r = toRemove.first(); r; r = toRemove.next())
03536             if ( (w = d->visibleWidgets.take(r) ) )
03537                 addChild(w, 0, -500000);
03538     }
03539 
03540     emit repaintAccessKeys();
03541     if (d->emitCompletedAfterRepaint) {
03542         bool full = d->emitCompletedAfterRepaint == KHTMLViewPrivate::CSFull;
03543         d->emitCompletedAfterRepaint = KHTMLViewPrivate::CSNone;
03544         if ( full )
03545             emit m_part->completed();
03546         else
03547             emit m_part->completed(true);
03548     }
03549 }
03550 
03551 void KHTMLView::scheduleRelayout(khtml::RenderObject * /*clippedObj*/)
03552 {
03553     if (!d->layoutSchedulingEnabled || d->layoutTimerId)
03554         return;
03555 
03556     d->layoutTimerId = startTimer( m_part->xmlDocImpl() && m_part->xmlDocImpl()->parsing()
03557                              ? 1000 : 0 );
03558 }
03559 
03560 void KHTMLView::unscheduleRelayout()
03561 {
03562     if (!d->layoutTimerId)
03563         return;
03564 
03565     killTimer(d->layoutTimerId);
03566     d->layoutTimerId = 0;
03567 }
03568 
03569 void KHTMLView::unscheduleRepaint()
03570 {
03571     if (!d->repaintTimerId)
03572         return;
03573 
03574     killTimer(d->repaintTimerId);
03575     d->repaintTimerId = 0;
03576 }
03577 
03578 void KHTMLView::scheduleRepaint(int x, int y, int w, int h, bool asap)
03579 {
03580     bool parsing = !m_part->xmlDocImpl() || m_part->xmlDocImpl()->parsing();
03581 
03582 //     kdDebug() << "parsing " << parsing << endl;
03583 //     kdDebug() << "complete " << d->complete << endl;
03584 
03585     int time = parsing ? 300 : (!asap ? ( !d->complete ? 100 : 20 ) : 0);
03586 
03587 #ifdef DEBUG_FLICKER
03588     QPainter p;
03589     p.begin( viewport() );
03590 
03591     int vx, vy;
03592     contentsToViewport( x, y, vx, vy );
03593     p.fillRect( vx, vy, w, h, Qt::red );
03594     p.end();
03595 #endif
03596 
03597     d->updateRegion = d->updateRegion.unite(QRect(x,y,w,h));
03598 
03599     if (asap && !parsing)
03600         unscheduleRepaint();
03601 
03602     if ( !d->repaintTimerId )
03603         d->repaintTimerId = startTimer( time );
03604 
03605 //     kdDebug() << "starting timer " << time << endl;
03606 }
03607 
03608 void KHTMLView::complete( bool pendingAction )
03609 {
03610 //     kdDebug() << "KHTMLView::complete()" << endl;
03611 
03612     d->complete = true;
03613 
03614     // is there a relayout pending?
03615     if (d->layoutTimerId)
03616     {
03617 //         kdDebug() << "requesting relayout now" << endl;
03618         // do it now
03619         killTimer(d->layoutTimerId);
03620         d->layoutTimerId = startTimer( 0 );
03621         d->emitCompletedAfterRepaint = pendingAction ?
03622             KHTMLViewPrivate::CSActionPending : KHTMLViewPrivate::CSFull;
03623     }
03624 
03625     // is there a repaint pending?
03626     if (d->repaintTimerId)
03627     {
03628 //         kdDebug() << "requesting repaint now" << endl;
03629         // do it now
03630         killTimer(d->repaintTimerId);
03631         d->repaintTimerId = startTimer( 20 );
03632         d->emitCompletedAfterRepaint = pendingAction ?
03633             KHTMLViewPrivate::CSActionPending : KHTMLViewPrivate::CSFull;
03634     }
03635 
03636     if (!d->emitCompletedAfterRepaint)
03637     {
03638         if (!pendingAction)
03639         emit m_part->completed();
03640         else
03641             emit m_part->completed(true);
03642     }
03643 
03644 }
03645 
03646 void KHTMLView::slotMouseScrollTimer()
03647 {
03648     scrollBy( d->m_mouseScroll_byX, d->m_mouseScroll_byY );
03649 }
03650 
03651 #ifndef KHTML_NO_CARET
03652 
03653 // ### the dependencies on static functions are a nightmare. just be
03654 // hacky and include the implementation here. Clean me up, please.
03655 
03656 #include "khtml_caret.cpp"
03657 
03658 void KHTMLView::initCaret(bool keepSelection)
03659 {
03660 #if DEBUG_CARETMODE > 0
03661   kdDebug(6200) << "begin initCaret" << endl;
03662 #endif
03663   // save caretMoved state as moveCaretTo changes it
03664   if (m_part->xmlDocImpl()) {
03665 #if 0
03666     ElementImpl *listitem = m_part->xmlDocImpl()->getElementById("__test_element__");
03667     if (listitem) dumpLineBoxes(static_cast<RenderFlow *>(listitem->renderer()));
03668 #endif
03669     d->caretViewContext();
03670     bool cmoved = d->m_caretViewContext->caretMoved;
03671     if (m_part->d->caretNode().isNull()) {
03672       // set to document, position will be sanitized anyway
03673       m_part->d->caretNode() = m_part->document();
03674       m_part->d->caretOffset() = 0L;
03675       // This sanity check is necessary for the not so unlikely case that
03676       // setEditable or setCaretMode is called before any render objects have
03677       // been created.
03678       if (!m_part->d->caretNode().handle()->renderer()) return;
03679     }/*end if*/
03680 //    kdDebug(6200) << "d->m_selectionStart " << m_part->d->m_selectionStart.handle()
03681 //          << " d->m_selectionEnd " << m_part->d->m_selectionEnd.handle() << endl;
03682     // ### does not repaint the selection on keepSelection!=false
03683     moveCaretTo(m_part->d->caretNode().handle(), m_part->d->caretOffset(), !keepSelection);
03684 //    kdDebug(6200) << "d->m_selectionStart " << m_part->d->m_selectionStart.handle()
03685 //          << " d->m_selectionEnd " << m_part->d->m_selectionEnd.handle() << endl;
03686     d->m_caretViewContext->caretMoved = cmoved;
03687   }/*end if*/
03688 #if DEBUG_CARETMODE > 0
03689   kdDebug(6200) << "end initCaret" << endl;
03690 #endif
03691 }
03692 
03693 bool KHTMLView::caretOverrides() const
03694 {
03695     bool cm = m_part->isCaretMode();
03696     bool dm = m_part->isEditable();
03697     return cm && !dm ? false
03698         : (dm || m_part->d->caretNode().handle()->contentEditable())
03699       && d->editorContext()->override;
03700 }
03701 
03702 void KHTMLView::ensureNodeHasFocus(NodeImpl *node)
03703 {
03704   if (m_part->isCaretMode() || m_part->isEditable()) return;
03705   if (node->focused()) return;
03706 
03707   // Find first ancestor whose "user-input" is "enabled"
03708   NodeImpl *firstAncestor = 0;
03709   while (node) {
03710     if (node->renderer()
03711        && node->renderer()->style()->userInput() != UI_ENABLED)
03712       break;
03713     firstAncestor = node;
03714     node = node->parentNode();
03715   }/*wend*/
03716 
03717   if (!node) firstAncestor = 0;
03718 
03719   DocumentImpl *doc = m_part->xmlDocImpl();
03720   // ensure that embedded widgets don't lose their focus
03721   if (!firstAncestor && doc->focusNode() && doc->focusNode()->renderer()
03722     && doc->focusNode()->renderer()->isWidget())
03723     return;
03724 
03725   // Set focus node on the document
03726 #if DEBUG_CARETMODE > 1
03727   kdDebug(6200) << k_funcinfo << "firstAncestor " << firstAncestor << ": "
03728     << (firstAncestor ? firstAncestor->nodeName().string() : QString::null) << endl;
03729 #endif
03730   doc->setFocusNode(firstAncestor);
03731   emit m_part->nodeActivated(Node(firstAncestor));
03732 }
03733 
03734 void KHTMLView::recalcAndStoreCaretPos(CaretBox *hintBox)
03735 {
03736     if (!m_part || m_part->d->caretNode().isNull()) return;
03737     d->caretViewContext();
03738     NodeImpl *caretNode = m_part->d->caretNode().handle();
03739 #if DEBUG_CARETMODE > 0
03740   kdDebug(6200) << "recalcAndStoreCaretPos: caretNode=" << caretNode << (caretNode ? " "+caretNode->nodeName().string() : QString::null) << " r@" << caretNode->renderer() << (caretNode->renderer() && caretNode->renderer()->isText() ? " \"" + QConstString(static_cast<RenderText *>(caretNode->renderer())->str->s, kMin(static_cast<RenderText *>(caretNode->renderer())->str->l, 15u)).string() + "\"" : QString::null) << endl;
03741 #endif
03742     caretNode->getCaret(m_part->d->caretOffset(), caretOverrides(),
03743             d->m_caretViewContext->x, d->m_caretViewContext->y,
03744         d->m_caretViewContext->width,
03745         d->m_caretViewContext->height);
03746 
03747     if (hintBox && d->m_caretViewContext->x == -1) {
03748 #if DEBUG_CARETMODE > 1
03749         kdDebug(6200) << "using hint inline box coordinates" << endl;
03750 #endif
03751     RenderObject *r = caretNode->renderer();
03752     const QFontMetrics &fm = r->style()->fontMetrics();
03753         int absx, absy;
03754     r->containingBlock()->absolutePosition(absx, absy,
03755                         false); // ### what about fixed?
03756     d->m_caretViewContext->x = absx + hintBox->xPos();
03757     d->m_caretViewContext->y = absy + hintBox->yPos();
03758 //              + hintBox->baseline() - fm.ascent();
03759     d->m_caretViewContext->width = 1;
03760     // ### firstline not regarded. But I think it can be safely neglected
03761     // as hint boxes are only used for empty lines.
03762     d->m_caretViewContext->height = fm.height();
03763     }/*end if*/
03764 
03765 #if DEBUG_CARETMODE > 4
03766 //    kdDebug(6200) << "freqTimerId: "<<d->m_caretViewContext->freqTimerId<<endl;
03767 #endif
03768 #if DEBUG_CARETMODE > 0
03769     kdDebug(6200) << "caret: ofs="<<m_part->d->caretOffset()<<" "
03770         <<" x="<<d->m_caretViewContext->x<<" y="<<d->m_caretViewContext->y
03771     <<" h="<<d->m_caretViewContext->height<<endl;
03772 #endif
03773 }
03774 
03775 void KHTMLView::caretOn()
03776 {
03777     if (d->m_caretViewContext) {
03778         killTimer(d->m_caretViewContext->freqTimerId);
03779 
03780     if (hasFocus() || d->m_caretViewContext->displayNonFocused
03781             == KHTMLPart::CaretBlink) {
03782             d->m_caretViewContext->freqTimerId = startTimer(500);
03783     } else {
03784         d->m_caretViewContext->freqTimerId = -1;
03785     }/*end if*/
03786 
03787         d->m_caretViewContext->visible = true;
03788         if ((d->m_caretViewContext->displayed = (hasFocus()
03789         || d->m_caretViewContext->displayNonFocused
03790             != KHTMLPart::CaretInvisible))) {
03791         updateContents(d->m_caretViewContext->x, d->m_caretViewContext->y,
03792                 d->m_caretViewContext->width,
03793             d->m_caretViewContext->height);
03794     }/*end if*/
03795 //        kdDebug(6200) << "caret on" << endl;
03796     }/*end if*/
03797 }
03798 
03799 void KHTMLView::caretOff()
03800 {
03801     if (d->m_caretViewContext) {
03802         killTimer(d->m_caretViewContext->freqTimerId);
03803     d->m_caretViewContext->freqTimerId = -1;
03804         d->m_caretViewContext->displayed = false;
03805         if (d->m_caretViewContext->visible) {
03806             d->m_caretViewContext->visible = false;
03807         updateContents(d->m_caretViewContext->x, d->m_caretViewContext->y,
03808                 d->m_caretViewContext->width,
03809                 d->m_caretViewContext->height);
03810     }/*end if*/
03811 //        kdDebug(6200) << "caret off" << endl;
03812     }/*end if*/
03813 }
03814 
03815 void KHTMLView::showCaret(bool forceRepaint)
03816 {
03817     if (d->m_caretViewContext) {
03818         d->m_caretViewContext->displayed = true;
03819         if (d->m_caretViewContext->visible) {
03820         if (!forceRepaint) {
03821             updateContents(d->m_caretViewContext->x, d->m_caretViewContext->y,
03822                 d->m_caretViewContext->width,
03823             d->m_caretViewContext->height);
03824             } else {
03825             repaintContents(d->m_caretViewContext->x, d->m_caretViewContext->y,
03826                 d->m_caretViewContext->width,
03827                 d->m_caretViewContext->height);
03828         }/*end if*/
03829     }/*end if*/
03830 //        kdDebug(6200) << "caret shown" << endl;
03831     }/*end if*/
03832 }
03833 
03834 bool KHTMLView::foldSelectionToCaret(NodeImpl *startNode, long startOffset,
03835                     NodeImpl *endNode, long endOffset)
03836 {
03837   m_part->d->m_selectionStart = m_part->d->m_selectionEnd = m_part->d->caretNode();
03838   m_part->d->m_startOffset = m_part->d->m_endOffset = m_part->d->caretOffset();
03839   m_part->d->m_extendAtEnd = true;
03840 
03841   bool folded = startNode != endNode || startOffset != endOffset;
03842 
03843   // Only clear the selection if there has been one.
03844   if (folded) {
03845     m_part->xmlDocImpl()->clearSelection();
03846   }/*end if*/
03847 
03848   return folded;
03849 }
03850 
03851 void KHTMLView::hideCaret()
03852 {
03853     if (d->m_caretViewContext) {
03854         if (d->m_caretViewContext->visible) {
03855 //            kdDebug(6200) << "redraw caret hidden" << endl;
03856         d->m_caretViewContext->visible = false;
03857         // force repaint, otherwise the event won't be handled
03858         // before the focus leaves the window
03859         repaintContents(d->m_caretViewContext->x, d->m_caretViewContext->y,
03860                 d->m_caretViewContext->width,
03861                 d->m_caretViewContext->height);
03862         d->m_caretViewContext->visible = true;
03863     }/*end if*/
03864         d->m_caretViewContext->displayed = false;
03865 //        kdDebug(6200) << "caret hidden" << endl;
03866     }/*end if*/
03867 }
03868 
03869 int KHTMLView::caretDisplayPolicyNonFocused() const
03870 {
03871   if (d->m_caretViewContext)
03872     return d->m_caretViewContext->displayNonFocused;
03873   else
03874     return KHTMLPart::CaretInvisible;
03875 }
03876 
03877 void KHTMLView::setCaretDisplayPolicyNonFocused(int policy)
03878 {
03879   d->caretViewContext();
03880 //  int old = d->m_caretViewContext->displayNonFocused;
03881   d->m_caretViewContext->displayNonFocused = (KHTMLPart::CaretDisplayPolicy)policy;
03882 
03883   // make change immediately take effect if not focused
03884   if (!hasFocus()) {
03885     switch (d->m_caretViewContext->displayNonFocused) {
03886       case KHTMLPart::CaretInvisible:
03887         hideCaret();
03888     break;
03889       case KHTMLPart::CaretBlink:
03890     if (d->m_caretViewContext->freqTimerId != -1) break;
03891     d->m_caretViewContext->freqTimerId = startTimer(500);
03892     // fall through
03893       case KHTMLPart::CaretVisible:
03894         d->m_caretViewContext->displayed = true;
03895         showCaret();
03896     break;
03897     }/*end switch*/
03898   }/*end if*/
03899 }
03900 
03901 bool KHTMLView::placeCaret(CaretBox *hintBox)
03902 {
03903   CaretViewContext *cv = d->caretViewContext();
03904   caretOff();
03905   NodeImpl *caretNode = m_part->d->caretNode().handle();
03906   // ### why is it sometimes null?
03907   if (!caretNode || !caretNode->renderer()) return false;
03908   ensureNodeHasFocus(caretNode);
03909   if (m_part->isCaretMode() || m_part->isEditable()
03910      || caretNode->renderer()->style()->userInput() == UI_ENABLED) {
03911     recalcAndStoreCaretPos(hintBox);
03912 
03913     cv->origX = cv->x;
03914 
03915     caretOn();
03916     return true;
03917   }/*end if*/
03918   return false;
03919 }
03920 
03921 void KHTMLView::ensureCaretVisible()
03922 {
03923   CaretViewContext *cv = d->m_caretViewContext;
03924   if (!cv) return;
03925   ensureVisible(cv->x, cv->y, cv->width, cv->height);
03926   d->scrollBarMoved = false;
03927 }
03928 
03929 bool KHTMLView::extendSelection(NodeImpl *oldStartSel, long oldStartOfs,
03930                 NodeImpl *oldEndSel, long oldEndOfs)
03931 {
03932   bool changed = false;
03933   if (m_part->d->m_selectionStart == m_part->d->m_selectionEnd
03934       && m_part->d->m_startOffset == m_part->d->m_endOffset) {
03935     changed = foldSelectionToCaret(oldStartSel, oldStartOfs, oldEndSel, oldEndOfs);
03936     m_part->d->m_extendAtEnd = true;
03937   } else do {
03938     changed = m_part->d->m_selectionStart.handle() != oldStartSel
03939             || m_part->d->m_startOffset != oldStartOfs
03940         || m_part->d->m_selectionEnd.handle() != oldEndSel
03941         || m_part->d->m_endOffset != oldEndOfs;
03942     if (!changed) break;
03943 
03944     // determine start position -- caret position is always at end.
03945     NodeImpl *startNode;
03946     long startOffset;
03947     if (m_part->d->m_extendAtEnd) {
03948       startNode = m_part->d->m_selectionStart.handle();
03949       startOffset = m_part->d->m_startOffset;
03950     } else {
03951       startNode = m_part->d->m_selectionEnd.handle();
03952       startOffset = m_part->d->m_endOffset;
03953       m_part->d->m_selectionEnd = m_part->d->m_selectionStart;
03954       m_part->d->m_endOffset = m_part->d->m_startOffset;
03955       m_part->d->m_extendAtEnd = true;
03956     }/*end if*/
03957 
03958     bool swapNeeded = false;
03959     if (!m_part->d->m_selectionEnd.isNull() && startNode) {
03960       swapNeeded = RangeImpl::compareBoundaryPoints(startNode, startOffset,
03961                 m_part->d->m_selectionEnd.handle(),
03962             m_part->d->m_endOffset) >= 0;
03963     }/*end if*/
03964 
03965     m_part->d->m_selectionStart = startNode;
03966     m_part->d->m_startOffset = startOffset;
03967 
03968     if (swapNeeded) {
03969       m_part->xmlDocImpl()->setSelection(m_part->d->m_selectionEnd.handle(),
03970         m_part->d->m_endOffset, m_part->d->m_selectionStart.handle(),
03971         m_part->d->m_startOffset);
03972     } else {
03973       m_part->xmlDocImpl()->setSelection(m_part->d->m_selectionStart.handle(),
03974         m_part->d->m_startOffset, m_part->d->m_selectionEnd.handle(),
03975         m_part->d->m_endOffset);
03976     }/*end if*/
03977   } while(false);/*end if*/
03978   return changed;
03979 }
03980 
03981 void KHTMLView::updateSelection(NodeImpl *oldStartSel, long oldStartOfs,
03982                 NodeImpl *oldEndSel, long oldEndOfs)
03983 {
03984   if (m_part->d->m_selectionStart == m_part->d->m_selectionEnd
03985       && m_part->d->m_startOffset == m_part->d->m_endOffset) {
03986     if (foldSelectionToCaret(oldStartSel, oldStartOfs, oldEndSel, oldEndOfs)) {
03987       m_part->emitSelectionChanged();
03988     }/*end if*/
03989     m_part->d->m_extendAtEnd = true;
03990   } else {
03991     // check if the extending end has passed the immobile end
03992     if (!m_part->d->m_selectionEnd.isNull() && !m_part->d->m_selectionEnd.isNull()) {
03993       bool swapNeeded = RangeImpl::compareBoundaryPoints(
03994                 m_part->d->m_selectionStart.handle(), m_part->d->m_startOffset,
03995             m_part->d->m_selectionEnd.handle(), m_part->d->m_endOffset) >= 0;
03996       if (swapNeeded) {
03997         DOM::Node tmpNode = m_part->d->m_selectionStart;
03998         long tmpOffset = m_part->d->m_startOffset;
03999         m_part->d->m_selectionStart = m_part->d->m_selectionEnd;
04000         m_part->d->m_startOffset = m_part->d->m_endOffset;
04001         m_part->d->m_selectionEnd = tmpNode;
04002         m_part->d->m_endOffset = tmpOffset;
04003         m_part->d->m_startBeforeEnd = true;
04004         m_part->d->m_extendAtEnd = !m_part->d->m_extendAtEnd;
04005       }/*end if*/
04006     }/*end if*/
04007 
04008     m_part->xmlDocImpl()->setSelection(m_part->d->m_selectionStart.handle(),
04009         m_part->d->m_startOffset, m_part->d->m_selectionEnd.handle(),
04010         m_part->d->m_endOffset);
04011     m_part->emitSelectionChanged();
04012   }/*end if*/
04013 }
04014 
04015 void KHTMLView::caretKeyPressEvent(QKeyEvent *_ke)
04016 {
04017   NodeImpl *oldStartSel = m_part->d->m_selectionStart.handle();
04018   long oldStartOfs = m_part->d->m_startOffset;
04019   NodeImpl *oldEndSel = m_part->d->m_selectionEnd.handle();
04020   long oldEndOfs = m_part->d->m_endOffset;
04021 
04022   NodeImpl *oldCaretNode = m_part->d->caretNode().handle();
04023   long oldOffset = m_part->d->caretOffset();
04024 
04025   bool ctrl = _ke->state() & ControlButton;
04026 
04027 // FIXME: this is that widely indented because I will write ifs around it.
04028       switch(_ke->key()) {
04029         case Key_Space:
04030           break;
04031 
04032         case Key_Down:
04033       moveCaretNextLine(1);
04034           break;
04035 
04036         case Key_Up:
04037       moveCaretPrevLine(1);
04038           break;
04039 
04040         case Key_Left:
04041       moveCaretBy(false, ctrl ? CaretByWord : CaretByCharacter, 1);
04042           break;
04043 
04044         case Key_Right:
04045       moveCaretBy(true, ctrl ? CaretByWord : CaretByCharacter, 1);
04046           break;
04047 
04048         case Key_Next:
04049       moveCaretNextPage();
04050           break;
04051 
04052         case Key_Prior:
04053       moveCaretPrevPage();
04054           break;
04055 
04056         case Key_Home:
04057       if (ctrl)
04058         moveCaretToDocumentBoundary(false);
04059       else
04060         moveCaretToLineBegin();
04061           break;
04062 
04063         case Key_End:
04064       if (ctrl)
04065         moveCaretToDocumentBoundary(true);
04066       else
04067         moveCaretToLineEnd();
04068           break;
04069 
04070       }/*end switch*/
04071 
04072   if ((m_part->d->caretNode().handle() != oldCaretNode
04073     || m_part->d->caretOffset() != oldOffset)
04074     // node should never be null, but faulty conditions may cause it to be
04075     && !m_part->d->caretNode().isNull()) {
04076 
04077     d->m_caretViewContext->caretMoved = true;
04078 
04079     if (_ke->state() & ShiftButton) {   // extend selection
04080       updateSelection(oldStartSel, oldStartOfs, oldEndSel, oldEndOfs);
04081     } else {            // clear any selection
04082       if (foldSelectionToCaret(oldStartSel, oldStartOfs, oldEndSel, oldEndOfs))
04083         m_part->emitSelectionChanged();
04084     }/*end if*/
04085 
04086     m_part->emitCaretPositionChanged(m_part->d->caretNode(), m_part->d->caretOffset());
04087   }/*end if*/
04088 
04089   _ke->accept();
04090 }
04091 
04092 bool KHTMLView::moveCaretTo(NodeImpl *node, long offset, bool clearSel)
04093 {
04094   if (!node) return false;
04095   ElementImpl *baseElem = determineBaseElement(node);
04096   RenderFlow *base = static_cast<RenderFlow *>(baseElem ? baseElem->renderer() : 0);
04097   if (!node) return false;
04098 
04099   // need to find out the node's inline box. If there is none, this function
04100   // will snap to the next node that has one. This is necessary to make the
04101   // caret visible in any case.
04102   CaretBoxLineDeleter cblDeleter;
04103 //   RenderBlock *cb;
04104   long r_ofs;
04105   CaretBoxIterator cbit;
04106   CaretBoxLine *cbl = findCaretBoxLine(node, offset, &cblDeleter, base, r_ofs, cbit);
04107   if(!cbl) {
04108       kdWarning() << "KHTMLView::moveCaretTo - findCaretBoxLine() returns NULL" << endl;
04109       return false;
04110   }
04111 
04112 #if DEBUG_CARETMODE > 3
04113   if (cbl) kdDebug(6200) << cbl->information() << endl;
04114 #endif
04115   CaretBox *box = *cbit;
04116   if (cbit != cbl->end() && box->object() != node->renderer()) {
04117     if (box->object()->element()) {
04118       mapRenderPosToDOMPos(box->object(), r_ofs, box->isOutside(),
04119                 box->isOutsideEnd(), node, offset);
04120       //if (!outside) offset = node->minOffset();
04121 #if DEBUG_CARETMODE > 1
04122       kdDebug(6200) << "set new node " << node->nodeName().string() << "@" << node << endl;
04123 #endif
04124     } else {    // box has no associated element -> do not use
04125       // this case should actually never happen.
04126       box = 0;
04127       kdError(6200) << "Box contains no node! Crash imminent" << endl;
04128     }/*end if*/
04129   }
04130 
04131   NodeImpl *oldStartSel = m_part->d->m_selectionStart.handle();
04132   long oldStartOfs = m_part->d->m_startOffset;
04133   NodeImpl *oldEndSel = m_part->d->m_selectionEnd.handle();
04134   long oldEndOfs = m_part->d->m_endOffset;
04135 
04136   // test for position change
04137   bool posChanged = m_part->d->caretNode().handle() != node
04138         || m_part->d->caretOffset() != offset;
04139   bool selChanged = false;
04140 
04141   m_part->d->caretNode() = node;
04142   m_part->d->caretOffset() = offset;
04143   if (clearSel || !oldStartSel || !oldEndSel) {
04144     selChanged = foldSelectionToCaret(oldStartSel, oldStartOfs, oldEndSel, oldEndOfs);
04145   } else {
04146     //kdDebug(6200) << "moveToCaret: extendSelection: m_extendAtEnd " << m_part->d->m_extendAtEnd << endl;
04147     //kdDebug(6200) << "selection: start(" << m_part->d->m_selectionStart.handle() << "," << m_part->d->m_startOffset << "), end(" << m_part->d->m_selectionEnd.handle() << "," << m_part->d->m_endOffset << "), caret(" << m_part->d->caretNode().handle() << "," << m_part->d->caretOffset() << ")" << endl;
04148     selChanged = extendSelection(oldStartSel, oldStartOfs, oldEndSel, oldEndOfs);
04149     //kdDebug(6200) << "after extendSelection: m_extendAtEnd " << m_part->d->m_extendAtEnd << endl;
04150     //kdDebug(6200) << "selection: start(" << m_part->d->m_selectionStart.handle() << "," << m_part->d->m_startOffset << "), end(" << m_part->d->m_selectionEnd.handle() << "," << m_part->d->m_endOffset << "), caret(" << m_part->d->caretNode().handle() << "," << m_part->d->caretOffset() << ")" << endl;
04151   }/*end if*/
04152 
04153   d->caretViewContext()->caretMoved = true;
04154 
04155   bool visible_caret = placeCaret(box);
04156 
04157   // FIXME: if the old position was !visible_caret, and the new position is
04158   // also, then two caretPositionChanged signals with a null Node are
04159   // emitted in series.
04160   if (posChanged) {
04161     m_part->emitCaretPositionChanged(visible_caret ? node : 0, offset);
04162   }/*end if*/
04163 
04164   return selChanged;
04165 }
04166 
04167 void KHTMLView::moveCaretByLine(bool next, int count)
04168 {
04169   Node &caretNodeRef = m_part->d->caretNode();
04170   if (caretNodeRef.isNull()) return;
04171 
04172   NodeImpl *caretNode = caretNodeRef.handle();
04173 //  kdDebug(6200) << ": caretNode=" << caretNode << endl;
04174   long offset = m_part->d->caretOffset();
04175 
04176   CaretViewContext *cv = d->caretViewContext();
04177 
04178   ElementImpl *baseElem = determineBaseElement(caretNode);
04179   LinearDocument ld(m_part, caretNode, offset, LeafsOnly, baseElem);
04180 
04181   ErgonomicEditableLineIterator it(ld.current(), cv->origX);
04182 
04183   // move count lines vertically
04184   while (count > 0 && it != ld.end() && it != ld.preBegin()) {
04185     count--;
04186     if (next) ++it; else --it;
04187   }/*wend*/
04188 
04189   // Nothing? Then leave everything as is.
04190   if (it == ld.end() || it == ld.preBegin()) return;
04191 
04192   int x, absx, absy;
04193   CaretBox *caretBox = nearestCaretBox(it, d->m_caretViewContext, x, absx, absy);
04194 
04195   placeCaretOnLine(caretBox, x, absx, absy);
04196 }
04197 
04198 void KHTMLView::placeCaretOnLine(CaretBox *caretBox, int x, int absx, int absy)
04199 {
04200   // paranoia sanity check
04201   if (!caretBox) return;
04202 
04203   RenderObject *caretRender = caretBox->object();
04204 
04205 #if DEBUG_CARETMODE > 0
04206   kdDebug(6200) << "got valid caretBox " << caretBox << endl;
04207   kdDebug(6200) << "xPos: " << caretBox->xPos() << " yPos: " << caretBox->yPos()
04208         << " width: " << caretBox->width() << " height: " << caretBox->height() << endl;
04209   InlineTextBox *tb = static_cast<InlineTextBox *>(caretBox->inlineBox());
04210   if (caretBox->isInlineTextBox()) { kdDebug(6200) << "contains \"" << QString(static_cast<RenderText *>(tb->object())->str->s + tb->m_start, tb->m_len) << "\"" << endl;}
04211 #endif
04212   // inquire height of caret
04213   int caretHeight = caretBox->height();
04214   bool isText = caretBox->isInlineTextBox();
04215   int yOfs = 0;     // y-offset for text nodes
04216   if (isText) {
04217     // text boxes need extrawurst
04218     RenderText *t = static_cast<RenderText *>(caretRender);
04219     const QFontMetrics &fm = t->metrics(caretBox->inlineBox()->m_firstLine);
04220     caretHeight = fm.height();
04221     yOfs = caretBox->inlineBox()->baseline() - fm.ascent();
04222   }/*end if*/
04223 
04224   caretOff();
04225 
04226   // set new caret node
04227   NodeImpl *caretNode;
04228   long &offset = m_part->d->caretOffset();
04229   mapRenderPosToDOMPos(caretRender, offset, caretBox->isOutside(),
04230         caretBox->isOutsideEnd(), caretNode, offset);
04231 
04232   // set all variables not needing special treatment
04233   d->m_caretViewContext->y = caretBox->yPos() + yOfs;
04234   d->m_caretViewContext->height = caretHeight;
04235   d->m_caretViewContext->width = 1; // FIXME: regard override
04236 
04237   int xPos = caretBox->xPos();
04238   int caretBoxWidth = caretBox->width();
04239   d->m_caretViewContext->x = xPos;
04240 
04241   if (!caretBox->isOutside()) {
04242     // before or at beginning of inline box -> place at beginning
04243     long r_ofs = 0;
04244     if (x <= xPos) {
04245       r_ofs = caretBox->minOffset();
04246   // somewhere within this block
04247     } else if (x > xPos && x <= xPos + caretBoxWidth) {
04248       if (isText) { // find out where exactly
04249         r_ofs = static_cast<InlineTextBox *>(caretBox->inlineBox())
04250             ->offsetForPoint(x, d->m_caretViewContext->x);
04251 #if DEBUG_CARETMODE > 2
04252         kdDebug(6200) << "deviation from origX " << d->m_caretViewContext->x - x << endl;
04253 #endif
04254 #if 0
04255       } else {  // snap to nearest end
04256         if (xPos + caretBoxWidth - x < x - xPos) {
04257           d->m_caretViewContext->x = xPos + caretBoxWidth;
04258           r_ofs = caretNode ? caretNode->maxOffset() : 1;
04259         } else {
04260           d->m_caretViewContext->x = xPos;
04261           r_ofs = caretNode ? caretNode->minOffset() : 0;
04262         }/*end if*/
04263 #endif
04264       }/*end if*/
04265     } else {        // after the inline box -> place at end
04266       d->m_caretViewContext->x = xPos + caretBoxWidth;
04267       r_ofs = caretBox->maxOffset();
04268     }/*end if*/
04269     offset = r_ofs;
04270   }/*end if*/
04271 #if DEBUG_CARETMODE > 0
04272       kdDebug(6200) << "new offset: " << offset << endl;
04273 #endif
04274 
04275   m_part->d->caretNode() = caretNode;
04276   m_part->d->caretOffset() = offset;
04277 
04278   d->m_caretViewContext->x += absx;
04279   d->m_caretViewContext->y += absy;
04280 
04281 #if DEBUG_CARETMODE > 1
04282     kdDebug(6200) << "new caret position: x " << d->m_caretViewContext->x << " y " << d->m_caretViewContext->y << " w " << d->m_caretViewContext->width << " h " << d->m_caretViewContext->height << " absx " << absx << " absy " << absy << endl;
04283 #endif
04284 
04285   ensureVisible(d->m_caretViewContext->x, d->m_caretViewContext->y,
04286     d->m_caretViewContext->width, d->m_caretViewContext->height);
04287   d->scrollBarMoved = false;
04288 
04289   ensureNodeHasFocus(caretNode);
04290   caretOn();
04291 }
04292 
04293 void KHTMLView::moveCaretToLineBoundary(bool end)
04294 {
04295   Node &caretNodeRef = m_part->d->caretNode();
04296   if (caretNodeRef.isNull()) return;
04297 
04298   NodeImpl *caretNode = caretNodeRef.handle();
04299 //  kdDebug(6200) << ": caretNode=" << caretNode << endl;
04300   long offset = m_part->d->caretOffset();
04301 
04302   ElementImpl *baseElem = determineBaseElement(caretNode);
04303   LinearDocument ld(m_part, caretNode, offset, LeafsOnly, baseElem);
04304 
04305   EditableLineIterator it = ld.current();
04306   if (it == ld.end()) return;   // should not happen, but who knows
04307 
04308   EditableCaretBoxIterator fbit(it, end);
04309   Q_ASSERT(fbit != (*it)->end() && fbit != (*it)->preBegin());
04310   CaretBox *b = *fbit;
04311 
04312   RenderObject *cb = b->containingBlock();
04313   int absx, absy;
04314 
04315   if (cb) cb->absolutePosition(absx,absy);
04316   else absx = absy = 0;
04317 
04318   int x = b->xPos() + (end && !b->isOutside() ? b->width() : 0);
04319   d->m_caretViewContext->origX = absx + x;
04320   placeCaretOnLine(b, x, absx, absy);
04321 }
04322 
04323 void KHTMLView::moveCaretToDocumentBoundary(bool end)
04324 {
04325   Node &caretNodeRef = m_part->d->caretNode();
04326   if (caretNodeRef.isNull()) return;
04327 
04328   NodeImpl *caretNode = caretNodeRef.handle();
04329 //  kdDebug(6200) << ": caretNode=" << caretNode << endl;
04330   long offset = m_part->d->caretOffset();
04331 
04332   ElementImpl *baseElem = determineBaseElement(caretNode);
04333   LinearDocument ld(m_part, caretNode, offset, IndicatedFlows, baseElem);
04334 
04335   EditableLineIterator it(end ? ld.preEnd() : ld.begin(), end);
04336   if (it == ld.end() || it == ld.preBegin()) return;    // should not happen, but who knows
04337 
04338   EditableCaretBoxIterator fbit = it;
04339   Q_ASSERT(fbit != (*it)->end() && fbit != (*it)->preBegin());
04340   CaretBox *b = *fbit;
04341 
04342   RenderObject *cb = (*it)->containingBlock();
04343   int absx, absy;
04344 
04345   if (cb) cb->absolutePosition(absx, absy);
04346   else absx = absy = 0;
04347 
04348   int x = b->xPos()/* + (end ? b->width() : 0) reactivate for rtl*/;
04349   d->m_caretViewContext->origX = absx + x;
04350   placeCaretOnLine(b, x, absx, absy);
04351 }
04352 
04353 void KHTMLView::moveCaretBy(bool next, CaretMovement cmv, int count)
04354 {
04355   if (!m_part) return;
04356   Node &caretNodeRef = m_part->d->caretNode();
04357   if (caretNodeRef.isNull()) return;
04358 
04359   NodeImpl *caretNode = caretNodeRef.handle();
04360 //  kdDebug(6200) << ": caretNode=" << caretNode << endl;
04361   long &offset = m_part->d->caretOffset();
04362 
04363   ElementImpl *baseElem = determineBaseElement(caretNode);
04364   CaretAdvancePolicy advpol = cmv != CaretByWord ? IndicatedFlows : LeafsOnly;
04365   LinearDocument ld(m_part, caretNode, offset, advpol, baseElem);
04366 
04367   EditableCharacterIterator it(&ld);
04368   while (!it.isEnd() && count > 0) {
04369     count--;
04370     if (cmv == CaretByCharacter) {
04371       if (next) ++it;
04372       else --it;
04373     } else if (cmv == CaretByWord) {
04374       if (next) moveItToNextWord(it);
04375       else moveItToPrevWord(it);
04376     }/*end if*/
04377 //kdDebug(6200) << "movecaret" << endl;
04378   }/*wend*/
04379   CaretBox *hintBox = 0;    // make gcc uninit warning disappear
04380   if (!it.isEnd()) {
04381     NodeImpl *node = caretNodeRef.handle();
04382     hintBox = it.caretBox();
04383 //kdDebug(6200) << "hintBox = " << hintBox << endl;
04384 //kdDebug(6200) << " outside " << hintBox->isOutside() << " outsideEnd " << hintBox->isOutsideEnd() << " r " << it.renderer() << " ofs " << it.offset() << " cb " << hintBox->containingBlock() << endl;
04385     mapRenderPosToDOMPos(it.renderer(), it.offset(), hintBox->isOutside(),
04386             hintBox->isOutsideEnd(), node, offset);
04387 //kdDebug(6200) << "mapRTD" << endl;
04388     caretNodeRef = node;
04389 #if DEBUG_CARETMODE > 2
04390     kdDebug(6200) << "set by valid node " << node << " " << (node?node->nodeName().string():QString::null) << " offset: " << offset << endl;
04391 #endif
04392   } else {
04393     offset = next ? caretNode->maxOffset() : caretNode->minOffset();
04394 #if DEBUG_CARETMODE > 0
04395     kdDebug(6200) << "set by INvalid node. offset: " << offset << endl;
04396 #endif
04397   }/*end if*/
04398   placeCaretOnChar(hintBox);
04399 }
04400 
04401 void KHTMLView::placeCaretOnChar(CaretBox *hintBox)
04402 {
04403   caretOff();
04404   recalcAndStoreCaretPos(hintBox);
04405   ensureVisible(d->m_caretViewContext->x, d->m_caretViewContext->y,
04406     d->m_caretViewContext->width, d->m_caretViewContext->height);
04407   d->m_caretViewContext->origX = d->m_caretViewContext->x;
04408   d->scrollBarMoved = false;
04409 #if DEBUG_CARETMODE > 3
04410   //if (caretNode->isTextNode())  kdDebug(6200) << "text[0] = " << (int)*((TextImpl *)caretNode)->data().unicode() << " text :\"" << ((TextImpl *)caretNode)->data().string() << "\"" << endl;
04411 #endif
04412   ensureNodeHasFocus(m_part->d->caretNode().handle());
04413   caretOn();
04414 }
04415 
04416 void KHTMLView::moveCaretByPage(bool next)
04417 {
04418   Node &caretNodeRef = m_part->d->caretNode();
04419   if (caretNodeRef.isNull()) return;
04420 
04421   NodeImpl *caretNode = caretNodeRef.handle();
04422 //  kdDebug(6200) << ": caretNode=" << caretNode << endl;
04423   long offset = m_part->d->caretOffset();
04424 
04425   int offs = (clipper()->height() < 30) ? clipper()->height() : 30;
04426   // Minimum distance the caret must be moved
04427   int mindist = clipper()->height() - offs;
04428 
04429   CaretViewContext *cv = d->caretViewContext();
04430 //  int y = cv->y;      // we always measure the top border
04431 
04432   ElementImpl *baseElem = determineBaseElement(caretNode);
04433   LinearDocument ld(m_part, caretNode, offset, LeafsOnly, baseElem);
04434 
04435   ErgonomicEditableLineIterator it(ld.current(), cv->origX);
04436 
04437   moveIteratorByPage(ld, it, mindist, next);
04438 
04439   int x, absx, absy;
04440   CaretBox *caretBox = nearestCaretBox(it, d->m_caretViewContext, x, absx, absy);
04441 
04442   placeCaretOnLine(caretBox, x, absx, absy);
04443 }
04444 
04445 void KHTMLView::moveCaretPrevWord()
04446 {
04447   moveCaretBy(false, CaretByWord, 1);
04448 }
04449 
04450 void KHTMLView::moveCaretNextWord()
04451 {
04452   moveCaretBy(true, CaretByWord, 1);
04453 }
04454 
04455 void KHTMLView::moveCaretPrevLine(int n)
04456 {
04457   moveCaretByLine(false, n);
04458 }
04459 
04460 void KHTMLView::moveCaretNextLine(int n)
04461 {
04462   moveCaretByLine(true, n);
04463 }
04464 
04465 void KHTMLView::moveCaretPrevPage()
04466 {
04467   moveCaretByPage(false);
04468 }
04469 
04470 void KHTMLView::moveCaretNextPage()
04471 {
04472   moveCaretByPage(true);
04473 }
04474 
04475 void KHTMLView::moveCaretToLineBegin()
04476 {
04477   moveCaretToLineBoundary(false);
04478 }
04479 
04480 void KHTMLView::moveCaretToLineEnd()
04481 {
04482   moveCaretToLineBoundary(true);
04483 }
04484 
04485 #endif // KHTML_NO_CARET
04486 
04487 #ifndef NO_SMOOTH_SCROLL_HACK
04488 #define timer timer2
04489 
04490 // All scrolls must be completed within 240ms of last keypress
04491 static const int SCROLL_TIME = 240;
04492 // Each step is 20 ms == 50 frames/second
04493 static const int SCROLL_TICK = 20;
04494 
04495 void KHTMLView::scrollBy(int dx, int dy)
04496 {
04497     KConfigGroup cfg( KGlobal::config(), "KDE" );
04498     if( !cfg.readBoolEntry( "SmoothScrolling", true )) {
04499         QScrollView::scrollBy( dx, dy );
04500         return;
04501     }
04502     // scrolling destination
04503     int full_dx = d->dx + dx;
04504     int full_dy = d->dy + dy;
04505 
04506     // scrolling speed
04507     int ddx = 0;
04508     int ddy = 0;
04509 
04510     int steps = SCROLL_TIME/SCROLL_TICK;
04511 
04512     ddx = (full_dx*16)/steps;
04513     ddy = (full_dy*16)/steps;
04514 
04515     // don't go under 1px/step
04516     if (ddx > 0 && ddx < 16) ddx = 16;
04517     if (ddy > 0 && ddy < 16) ddy = 16;
04518     if (ddx < 0 && ddx > -16) ddx = -16;
04519     if (ddy < 0 && ddy > -16) ddy = -16;
04520 
04521     d->dx = full_dx;
04522     d->dy = full_dy;
04523     d->ddx = ddx;
04524     d->ddy = ddy;
04525 
04526     if (!d->scrolling) {
04527         scrollTick();
04528         startScrolling();
04529     }
04530 }
04531 
04532 void KHTMLView::scrollTick() {
04533     if (d->dx == 0 && d->dy == 0) {
04534         stopScrolling();
04535         return;
04536     }
04537 
04538     int tddx = d->ddx + d->rdx;
04539     int tddy = d->ddy + d->rdy;
04540 
04541     int ddx = tddx / 16;
04542     int ddy = tddy / 16;
04543     d->rdx = tddx % 16;
04544     d->rdy = tddy % 16;
04545 
04546     if (d->dx > 0 && ddx > d->dx) ddx = d->dx;
04547     else
04548     if (d->dx < 0 && ddx < d->dx) ddx = d->dx;
04549 
04550     if (d->dy > 0 && ddy > d->dy) ddy = d->dy;
04551     else
04552     if (d->dy < 0 && ddy < d->dy) ddy = d->dy;
04553 
04554     d->dx -= ddx;
04555     d->dy -= ddy;
04556 
04557 //    QScrollView::setContentsPos( contentsX() + ddx, contentsY() + ddy);
04558     QScrollView::scrollBy(ddx, ddy);
04559 }
04560 
04561 void KHTMLView::startScrolling()
04562 {
04563     d->scrolling = true;
04564     d->timer.start(SCROLL_TICK, false);
04565 }
04566 
04567 void KHTMLView::stopScrolling()
04568 {
04569     d->timer.stop();
04570     d->dx = d->dy = 0;
04571     d->scrolling = false;
04572 }
04573 
04574 // Overloaded from QScrollView and QScrollBar
04575 void KHTMLView::scrollViewWheelEvent( QWheelEvent *e )
04576 {
04577     int pageStep = verticalScrollBar()->pageStep();
04578     int lineStep = verticalScrollBar()->lineStep();
04579     int step = QMIN( QApplication::wheelScrollLines()*lineStep, pageStep );
04580     if ( ( e->state() & ControlButton ) || ( e->state() & ShiftButton ) )
04581         step = pageStep;
04582 
04583     if(e->orientation() == Horizontal)
04584         scrollBy(-((e->delta()*step)/120), 0);
04585     else if(e->orientation() == Vertical)
04586         scrollBy(0,-((e->delta()*step)/120));
04587 
04588     e->accept();
04589 }
04590 
04591 #undef timer
04592 
04593 #endif // NO_SMOOTH_SCROLL_HACK
04594 
04595 #undef DEBUG_CARETMODE
KDE Home | KDE Accessibility Home | Description of Access Keys