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