c3b57bb0038ae5eaddb62817d85d2f917654cee1
[WebKit-https.git] / WebKit / qt / Api / qwebpage.cpp
1 /*
2     Copyright (C) 2007 Trolltech ASA
3     Copyright (C) 2007 Staikos Computing Services Inc.
4     Copyright (C) 2007 Apple Inc.
5
6     This library is free software; you can redistribute it and/or
7     modify it under the terms of the GNU Library General Public
8     License as published by the Free Software Foundation; either
9     version 2 of the License, or (at your option) any later version.
10
11     This library is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14     Library General Public License for more details.
15
16     You should have received a copy of the GNU Library General Public License
17     along with this library; see the file COPYING.LIB.  If not, write to
18     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19     Boston, MA 02110-1301, USA.
20
21     This class provides all functionality needed for loading images, style sheets and html
22     pages from the web. It has a memory cache for these objects.
23 */
24 #include "config.h"
25 #include "qwebpage.h"
26 #include "qwebframe.h"
27 #include "qwebpage_p.h"
28 #include "qwebframe_p.h"
29 #include "qwebnetworkinterface.h"
30 #include "qwebpagehistory.h"
31 #include "qwebpagehistory_p.h"
32 #include "qwebsettings.h"
33
34 #include "Frame.h"
35 #include "ChromeClientQt.h"
36 #include "ContextMenu.h"
37 #include "ContextMenuClientQt.h"
38 #include "DragClientQt.h"
39 #include "DragController.h"
40 #include "DragData.h"
41 #include "EditorClientQt.h"
42 #include "Settings.h"
43 #include "Page.h"
44 #include "FrameLoader.h"
45 #include "FrameLoadRequest.h"
46 #include "KURL.h"
47 #include "Image.h"
48 #include "IconDatabase.h"
49 #include "InspectorClientQt.h"
50 #include "FocusController.h"
51 #include "Editor.h"
52 #include "PlatformScrollBar.h"
53 #include "PlatformKeyboardEvent.h"
54 #include "PlatformWheelEvent.h"
55 #include "ProgressTracker.h"
56 #include "RefPtr.h"
57 #include "HashMap.h"
58 #include "HitTestResult.h"
59 #include "LocalizedStrings.h"
60
61 #include <QDebug>
62 #include <QDragEnterEvent>
63 #include <QDragLeaveEvent>
64 #include <QDragMoveEvent>
65 #include <QDropEvent>
66 #include <QFileDialog>
67 #include <QHttpRequestHeader>
68 #include <QInputDialog>
69 #include <QMessageBox>
70 #include <QNetworkProxy>
71 #include <QUndoStack>
72 #include <QUrl>
73 #include <QPainter>
74
75 using namespace WebCore;
76
77 QWebPagePrivate::QWebPagePrivate(QWebPage *qq)
78     : q(qq)
79     , modified(false)
80 {
81     q->setMouseTracking(true);
82     q->setFocusPolicy(Qt::ClickFocus);
83     chromeClient = new ChromeClientQt(q);
84     contextMenuClient = new ContextMenuClientQt();
85     editorClient = new EditorClientQt(q);
86     page = new Page(chromeClient, contextMenuClient, editorClient,
87                     new DragClientQt(q), new InspectorClientQt());
88
89     // ### should be configurable
90     page->settings()->setDefaultTextEncodingName("iso-8859-1");
91     page->settings()->setDOMPasteAllowed(true);
92
93     settings = new QWebSettings(page->settings());
94
95     undoStack = 0;
96     mainFrame = 0;
97     networkInterface = 0;
98     insideOpenCall = false;
99
100     history.d = new QWebPageHistoryPrivate(page->backForwardList());
101     memset(actions, 0, sizeof(actions));
102 }
103
104 QWebPagePrivate::~QWebPagePrivate()
105 {
106     delete undoStack;
107     delete settings;
108     delete page;
109 }
110
111 QWebPage::NavigationRequestResponse QWebPagePrivate::navigationRequested(QWebFrame *frame, const QWebNetworkRequest &request, QWebPage::NavigationType type)
112 {
113     if (insideOpenCall
114         && frame == mainFrame)
115         return QWebPage::AcceptNavigationRequest;
116     return q->navigationRequested(frame, request, type);
117 }
118
119 void QWebPagePrivate::createMainFrame()
120 {
121     if (!mainFrame) {
122         QWebFrameData frameData;
123         frameData.ownerElement = 0;
124         frameData.allowsScrolling = true;
125         frameData.marginWidth = 0;
126         frameData.marginHeight = 0;
127         mainFrame = new QWebFrame(q, &frameData);
128         QObject::connect(mainFrame, SIGNAL(titleChanged(const QString&)),
129                 q, SIGNAL(titleChanged(const QString&)));
130         QObject::connect(mainFrame, SIGNAL(hoveringOverLink(const QString&, const QString&)),
131                 q, SIGNAL(hoveringOverLink(const QString&, const QString&)));
132         
133         mainFrame->d->frameView->setFrameGeometry(q->geometry());
134
135         emit q->frameCreated(mainFrame);
136     }
137 }
138
139 static QWebPage::WebAction webActionForContextMenuAction(WebCore::ContextMenuAction action)
140 {
141     switch (action) {
142         case WebCore::ContextMenuItemTagOpenLink: return QWebPage::OpenLink;
143         case WebCore::ContextMenuItemTagOpenLinkInNewWindow: return QWebPage::OpenLinkInNewWindow;
144         case WebCore::ContextMenuItemTagDownloadLinkToDisk: return QWebPage::DownloadLinkToDisk;
145         case WebCore::ContextMenuItemTagCopyLinkToClipboard: return QWebPage::CopyLinkToClipboard;
146         case WebCore::ContextMenuItemTagOpenImageInNewWindow: return QWebPage::OpenImageInNewWindow;
147         case WebCore::ContextMenuItemTagDownloadImageToDisk: return QWebPage::DownloadImageToDisk;
148         case WebCore::ContextMenuItemTagCopyImageToClipboard: return QWebPage::CopyImageToClipboard;
149         case WebCore::ContextMenuItemTagOpenFrameInNewWindow: return QWebPage::OpenFrameInNewWindow;
150         case WebCore::ContextMenuItemTagCopy: return QWebPage::Copy;
151         case WebCore::ContextMenuItemTagGoBack: return QWebPage::GoBack;
152         case WebCore::ContextMenuItemTagGoForward: return QWebPage::GoForward;
153         case WebCore::ContextMenuItemTagStop: return QWebPage::Stop;
154         case WebCore::ContextMenuItemTagReload: return QWebPage::Reload;
155         case WebCore::ContextMenuItemTagCut: return QWebPage::Cut;
156         case WebCore::ContextMenuItemTagPaste: return QWebPage::Paste;
157         default: break;
158     }
159     return QWebPage::NoWebAction;
160 }
161
162 QMenu *QWebPagePrivate::createContextMenu(QList<WebCore::ContextMenuItem> *items)
163 {
164     QMenu *menu = new QMenu;
165     for (int i = 0; i < items->count(); ++i) {
166         const ContextMenuItem &item = items->at(i);
167         switch (item.type()) {
168             case WebCore::ActionType: {
169                 QWebPage::WebAction action = webActionForContextMenuAction(item.action());
170                 QAction *a = q->webAction(action);
171                 if (a)
172                     menu->addAction(a);
173                 break;
174             }
175             case WebCore::SeparatorType:
176                 menu->addSeparator();
177                 break;
178             case WebCore::SubmenuType: {
179                 QMenu *subMenu = createContextMenu(item.platformSubMenu());
180                 subMenu->setTitle(item.title());
181                 menu->addAction(subMenu->menuAction());
182                 break;
183             }
184         }
185     }
186     return menu;
187 }
188
189 QWebFrame *QWebPagePrivate::frameAt(const QPoint &pos) const
190 {
191     QWebFrame *frame = mainFrame;
192
193 redo:
194     QList<QWebFrame*> children = frame->childFrames();
195     for (int i = 0; i < children.size(); ++i) {
196         if (children.at(i)->geometry().contains(pos)) {
197             frame = children.at(i);
198             goto redo;
199         }
200     }
201     if (frame->geometry().contains(pos))
202         return frame;
203     return 0;
204 }
205
206 void QWebPagePrivate::_q_webActionTriggered(bool checked)
207 {
208     QAction *a = qobject_cast<QAction *>(q->sender());
209     if (!a)
210         return;
211     QWebPage::WebAction action = static_cast<QWebPage::WebAction>(a->data().toInt());
212     q->webActionTriggered(action, checked);
213 }
214
215 void QWebPagePrivate::updateAction(QWebPage::WebAction action)
216 {
217     QAction *a = actions[action];
218     if (!a || !mainFrame)
219         return;
220
221     WebCore::FrameLoader *loader = mainFrame->d->frame->loader();
222     WebCore::Editor *editor = page->focusController()->focusedOrMainFrame()->editor();
223
224     bool enabled = a->isEnabled();
225
226     switch (action) {
227         case QWebPage::GoBack:
228             enabled = loader->canGoBackOrForward(-1);
229             break;
230         case QWebPage::GoForward:
231             enabled = loader->canGoBackOrForward(1);
232             break;
233         case QWebPage::Stop:
234             enabled = loader->isLoading();
235             break;
236         case QWebPage::Reload:
237             enabled = !loader->isLoading();
238             break;
239         case QWebPage::Cut:
240             enabled = editor->canCut();
241             break;
242         case QWebPage::Copy:
243             enabled = editor->canCopy();
244             break;
245         case QWebPage::Paste:
246             enabled = editor->canPaste();
247             break;
248         case QWebPage::Undo:
249         case QWebPage::Redo:
250             // those two are handled by QUndoStack
251             break;
252         default: break;
253     }
254
255     a->setEnabled(enabled);
256 }
257
258 void QWebPagePrivate::updateNavigationActions()
259 {
260     updateAction(QWebPage::GoBack);
261     updateAction(QWebPage::GoForward);
262     updateAction(QWebPage::Stop);
263     updateAction(QWebPage::Reload);
264 }
265
266 void QWebPagePrivate::updateEditorActions()
267 {
268     updateAction(QWebPage::Cut);
269     updateAction(QWebPage::Copy);
270     updateAction(QWebPage::Paste);
271 }
272
273 QWebPage::QWebPage(QWidget *parent)
274     : QWidget(parent)
275     , d(new QWebPagePrivate(this))
276 {
277
278     QPalette pal = palette();
279     pal.setBrush(QPalette::Background, Qt::white);
280
281     setAttribute(Qt::WA_OpaquePaintEvent);
282
283     setPalette(pal);
284     setAcceptDrops(true);
285     connect(this, SIGNAL(loadProgressChanged(int)), this, SLOT(_q_onLoadProgressChanged(int)));
286 }
287
288 QWebPage::~QWebPage()
289 {
290     FrameLoader *loader = d->mainFrame->d->frame->loader();
291     if (loader)
292         loader->detachFromParent();
293     delete d;
294 }
295
296 void QWebPage::open(const QUrl &url)
297 {
298     open(QWebNetworkRequest(url));
299 }
300
301 void QWebPage::open(const QWebNetworkRequest &req)
302 {
303     d->insideOpenCall = true;
304
305     QUrl url = req.url();
306     QHttpRequestHeader httpHeader = req.httpHeader();
307     QByteArray postData = req.postData();
308
309     WebCore::ResourceRequest request(KURL(url.toString()));
310
311     QString method = httpHeader.method();
312     if (!method.isEmpty())
313         request.setHTTPMethod(method);
314
315     QList<QPair<QString, QString> > values = httpHeader.values();
316     for (int i = 0; i < values.size(); ++i) {
317         const QPair<QString, QString> &val = values.at(i);
318         request.addHTTPHeaderField(val.first, val.second);
319     }
320
321     if (!postData.isEmpty()) {
322         WTF::RefPtr<WebCore::FormData> formData = new WebCore::FormData(postData.constData(), postData.size());
323         request.setHTTPBody(formData);
324     }
325
326     mainFrame()->d->frame->loader()->load(request);
327     d->insideOpenCall = false;
328 }
329
330 QUrl QWebPage::url() const
331 {
332     return QUrl((QString)mainFrame()->d->frame->loader()->url().url());
333 }
334
335 QString QWebPage::title() const
336 {
337     return mainFrame()->title();
338 }
339
340 QWebFrame *QWebPage::mainFrame() const
341 {
342     d->createMainFrame();
343     return d->mainFrame;
344 }
345
346 QSize QWebPage::sizeHint() const
347 {
348     return QSize(800, 600);
349 }
350
351 void QWebPage::stop()
352 {
353     webActionTriggered(Stop);
354 }
355
356 QWebPageHistory *QWebPage::history() const
357 {
358     return &d->history;
359 }
360
361 void QWebPage::goBack()
362 {
363     webActionTriggered(GoBack);
364 }
365
366 void QWebPage::goForward()
367 {
368     webActionTriggered(GoForward);
369 }
370
371 void QWebPage::goToHistoryItem(const QWebHistoryItem &item)
372 {
373     d->page->goToItem(item.d->item, FrameLoadTypeIndexedBackForward);
374 }
375
376 void QWebPage::javaScriptConsoleMessage(const QString& message, unsigned int lineNumber, const QString& sourceID)
377 {
378 }
379
380 void QWebPage::javaScriptAlert(QWebFrame *frame, const QString& msg)
381 {
382     //FIXME frame pos...
383     QMessageBox::information(this, title(), msg, QMessageBox::Ok);
384 }
385
386 bool QWebPage::javaScriptConfirm(QWebFrame *frame, const QString& msg)
387 {
388     //FIXME frame pos...
389     return 0 == QMessageBox::information(this, title(), msg, QMessageBox::Yes, QMessageBox::No);
390 }
391
392 bool QWebPage::javaScriptPrompt(QWebFrame *frame, const QString& msg, const QString& defaultValue, QString* result)
393 {
394     //FIXME frame pos...
395     bool ok = false;
396 #ifndef QT_NO_INPUTDIALOG
397     QString x = QInputDialog::getText(this, title(), msg, QLineEdit::Normal, defaultValue, &ok);
398     if (ok && result) {
399         *result = x;
400     }
401 #endif
402     return ok;
403 }
404
405 QWebPage *QWebPage::createWindow()
406 {
407     return 0;
408 }
409
410 QWebPage *QWebPage::createModalDialog()
411 {
412     return 0;
413 }
414
415 QObject *QWebPage::createPlugin(const QString &classid, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues)
416 {
417     Q_UNUSED(classid)
418     Q_UNUSED(url)
419     Q_UNUSED(paramNames)
420     Q_UNUSED(paramValues)
421     return 0;
422 }
423
424 static WebCore::FrameLoadRequest frameLoadRequest(const QUrl &url, WebCore::Frame *frame)
425 {
426     WebCore::ResourceRequest rr(WebCore::KURL(url.toString()),
427                                 frame->loader()->outgoingReferrer());
428     return WebCore::FrameLoadRequest(rr);
429 }
430
431 static void openNewWindow(const QUrl& url, WebCore::Frame* frame)
432 {
433     if (Page* oldPage = frame->page())
434         if (Page* newPage = oldPage->chrome()->createWindow(frame,
435                 frameLoadRequest(url, frame)))
436             newPage->chrome()->show();
437 }
438
439 void QWebPage::webActionTriggered(WebAction action, bool checked)
440 {
441     WebCore::Frame *frame = d->page->focusController()->focusedOrMainFrame();
442     WebCore::Editor *editor = frame->editor();
443     const char *command = 0;
444
445     switch (action) {
446         case OpenLink:
447             if (QWebFrame *targetFrame = d->currentContext.targetFrame()) {
448                 WTF::RefPtr<WebCore::Frame> wcFrame = targetFrame->d->frame;
449                 targetFrame->d->frame->loader()->load(frameLoadRequest(d->currentContext.linkUrl(), wcFrame.get()),
450                                                       /*lockHistory*/ false,
451                                                       /*userGesture*/ true,
452                                                       /*event*/ 0,
453                                                       /*HTMLFormElement*/ 0,
454                                                       /*formValues*/
455                                                       WTF::HashMap<String, String>());
456                 break;
457             } else {
458             }
459             // fall through
460         case OpenLinkInNewWindow:
461             openNewWindow(d->currentContext.linkUrl(), frame);
462             break;
463         case OpenFrameInNewWindow:
464             break;
465         case DownloadLinkToDisk:
466         case CopyLinkToClipboard:
467             editor->copyURL(WebCore::KURL(d->currentContext.linkUrl().toString()), d->currentContext.text());
468             break;
469         case OpenImageInNewWindow:
470             openNewWindow(d->currentContext.imageUrl(), frame);
471             break;
472         case DownloadImageToDisk:
473         case CopyImageToClipboard:
474             break;
475         case GoBack:
476             d->page->goBack();
477             break;
478         case GoForward:
479             d->page->goForward();
480             break;
481         case Stop:
482             mainFrame()->d->frame->loader()->stopForUserCancel();
483             break;
484         case Reload:
485             mainFrame()->d->frame->loader()->reload();
486             break;
487         case Cut:
488             editor->cut();
489             break;
490         case Copy:
491             editor->copy();
492             break;
493         case Paste:
494             editor->paste();
495             break;
496
497         case Undo:
498             editor->undo();
499             break;
500         case Redo:
501             editor->redo();
502             break;
503
504         case MoveToNextChar:
505             command = "MoveForward";
506             break;
507         case MoveToPreviousChar:
508             command = "MoveBackward";
509             break;
510         case MoveToNextWord:
511             command = "MoveWordForward";
512             break;
513         case MoveToPreviousWord:
514             command = "MoveWordBackward";
515             break;
516         case MoveToNextLine:
517             command = "MoveDown";
518             break;
519         case MoveToPreviousLine:
520             command = "MoveUp";
521             break;
522         case MoveToStartOfLine:
523             command = "MoveToBeginningOfLine";
524             break;
525         case MoveToEndOfLine:
526             command = "MoveToEndOfLine";
527             break;
528         case MoveToStartOfBlock:
529             command = "MoveToBeginningOfParagraph";
530             break;
531         case MoveToEndOfBlock:
532             command = "MoveToEndOfParagraph";
533             break;
534         case MoveToStartOfDocument:
535             command = "MoveToBeginningOfDocument";
536             break;
537         case MoveToEndOfDocument:
538             command = "MoveToEndOfDocument";
539             break;
540         case SelectNextChar:
541             command = "MoveForwardAndModifySelection";
542             break;
543         case SelectPreviousChar:
544             command = "MoveBackwardAndModifySelection";
545             break;
546         case SelectNextWord:
547             command = "MoveWordForwardAndModifySelection";
548             break;
549         case SelectPreviousWord:
550             command = "MoveWordBackwardAndModifySelection";
551             break;
552         case SelectNextLine:
553             command = "MoveDownAndModifySelection";
554             break;
555         case SelectPreviousLine:
556             command = "MoveUpAndModifySelection";
557             break;
558         case SelectStartOfLine:
559             command = "MoveToBeginningOfLineAndModifySelection";
560             break;
561         case SelectEndOfLine:
562             command = "MoveToEndOfLineAndModifySelection";
563             break;
564         case SelectStartOfBlock:
565             command = "MoveToBeginningOfParagraphAndModifySelection";
566             break;
567         case SelectEndOfBlock:
568             command = "MoveToEndOfParagraphAndModifySelection";
569             break;
570         case SelectStartOfDocument:
571             command = "MoveToBeginningOfDocumentAndModifySelection";
572             break;
573         case SelectEndOfDocument:
574             command = "MoveToEndOfDocumentAndModifySelection";
575             break;
576         case DeleteStartOfWord:
577             command = "DeleteWordBackward";
578             break;
579         case DeleteEndOfWord:
580             command = "DeleteWordForward";
581             break;
582
583         default: break;
584     }
585
586     if (command)
587         editor->execCommand(command);
588 }
589
590 QWebPage::NavigationRequestResponse QWebPage::navigationRequested(QWebFrame *frame, const QWebNetworkRequest &request, QWebPage::NavigationType type)
591 {
592     Q_UNUSED(request)
593     return AcceptNavigationRequest;
594 }
595
596 void QWebPage::setWindowGeometry(const QRect& geom)
597 {
598     Q_UNUSED(geom)
599 }
600
601 bool QWebPage::canCut() const
602 {
603     return d->page->focusController()->focusedOrMainFrame()->editor()->canCut();
604 }
605
606 bool QWebPage::canCopy() const
607 {
608     return d->page->focusController()->focusedOrMainFrame()->editor()->canCopy();
609 }
610
611 bool QWebPage::canPaste() const
612 {
613     return d->page->focusController()->focusedOrMainFrame()->editor()->canPaste();
614 }
615
616 void QWebPage::cut()
617 {
618     webActionTriggered(Cut);
619 }
620
621 void QWebPage::copy()
622 {
623     webActionTriggered(Copy);
624 }
625
626 void QWebPage::paste()
627 {
628     webActionTriggered(Paste);
629 }
630
631 QString QWebPage::selectedText() const
632 {
633     return d->page->focusController()->focusedOrMainFrame()->selectedText();
634 }
635
636 QAction *QWebPage::webAction(WebAction action) const
637 {
638     if (action == QWebPage::NoWebAction) return 0;
639     if (d->actions[action])
640         return d->actions[action];
641
642     QString text;
643
644     switch (action) {
645         case OpenLink:
646             text = contextMenuItemTagOpenLink();
647             break;
648         case OpenLinkInNewWindow:
649             text = contextMenuItemTagOpenLinkInNewWindow();
650             break;
651         case OpenFrameInNewWindow:
652             text = contextMenuItemTagOpenFrameInNewWindow();
653             break;
654
655         case DownloadLinkToDisk:
656             text = contextMenuItemTagDownloadLinkToDisk();
657             break;
658         case CopyLinkToClipboard:
659             text = contextMenuItemTagCopyLinkToClipboard();
660             break;
661
662         case OpenImageInNewWindow:
663             text = contextMenuItemTagOpenImageInNewWindow();
664             break;
665         case DownloadImageToDisk:
666             text = contextMenuItemTagDownloadImageToDisk();
667             break;
668         case CopyImageToClipboard:
669             text = contextMenuItemTagCopyImageToClipboard();
670             break;
671
672         case GoBack:
673             text = contextMenuItemTagGoBack();
674             break;
675         case GoForward:
676             text = contextMenuItemTagGoForward();
677             break;
678         case Stop:
679             text = contextMenuItemTagStop();
680             break;
681         case Reload:
682             text = contextMenuItemTagReload();
683             break;
684
685         case Cut:
686             text = contextMenuItemTagCut();
687             break;
688         case Copy:
689             text = contextMenuItemTagCopy();
690             break;
691         case Paste:
692             text = contextMenuItemTagPaste();
693             break;
694
695         case Undo: {
696             QAction *a = undoStack()->createUndoAction(d->q);
697             d->actions[action] = a;
698             return a;
699         }
700         case Redo: {
701             QAction *a = undoStack()->createRedoAction(d->q);
702             d->actions[action] = a;
703             return a;
704         }
705         case MoveToNextChar:
706         case MoveToPreviousChar:
707         case MoveToNextWord:
708         case MoveToPreviousWord:
709         case MoveToNextLine:
710         case MoveToPreviousLine:
711         case MoveToStartOfLine:
712         case MoveToEndOfLine:
713         case MoveToStartOfBlock:
714         case MoveToEndOfBlock:
715         case MoveToStartOfDocument:
716         case MoveToEndOfDocument:
717         case SelectNextChar:
718         case SelectPreviousChar:
719         case SelectNextWord:
720         case SelectPreviousWord:
721         case SelectNextLine:
722         case SelectPreviousLine:
723         case SelectStartOfLine:
724         case SelectEndOfLine:
725         case SelectStartOfBlock:
726         case SelectEndOfBlock:
727         case SelectStartOfDocument:
728         case SelectEndOfDocument:
729         case DeleteStartOfWord:
730         case DeleteEndOfWord:
731             break; // ####
732
733         case NoWebAction:
734             return 0;
735     }
736
737     if (text.isEmpty())
738         return 0;
739
740     QAction *a = new QAction(d->q);
741     a->setText(text);
742     a->setData(action);
743
744     connect(a, SIGNAL(triggered(bool)),
745             this, SLOT(_q_webActionTriggered(bool)));
746
747     d->actions[action] = a;
748     d->updateAction(action);
749     return a;
750 }
751
752 /*!
753   Returns true if the page contains unsubmitted form data.
754 */
755 bool QWebPage::isModified() const
756 {
757     return d->modified;
758 }
759
760
761 QUndoStack *QWebPage::undoStack() const
762 {
763     if (!d->undoStack)
764         d->undoStack = new QUndoStack(const_cast<QWebPage *>(this));
765
766     return d->undoStack;
767 }
768
769 static inline DragOperation dropActionToDragOp(Qt::DropActions actions)
770 {
771     unsigned result = 0;
772     if (actions & Qt::CopyAction)
773         result |= DragOperationCopy;
774     if (actions & Qt::MoveAction)
775         result |= DragOperationMove;
776     if (actions & Qt::LinkAction)
777         result |= DragOperationLink;
778     return (DragOperation)result;    
779 }
780
781 static inline Qt::DropAction dragOpToDropAction(unsigned actions)
782 {
783     Qt::DropAction result = Qt::IgnoreAction;
784     if (actions & DragOperationCopy)
785         result = Qt::CopyAction;
786     else if (actions & DragOperationMove)
787         result = Qt::MoveAction;
788     else if (actions & DragOperationLink)
789         result = Qt::LinkAction;
790     return result;    
791 }
792
793 void QWebPage::resizeEvent(QResizeEvent *e)
794 {
795     QWidget::resizeEvent(e);
796     if (mainFrame()->d->frame && mainFrame()->d->frameView) {
797         mainFrame()->d->frameView->setFrameGeometry(rect());
798         mainFrame()->d->frame->forceLayout();
799         mainFrame()->d->frame->view()->adjustViewSize();
800     }
801 }
802
803 void QWebPage::paintEvent(QPaintEvent *ev)
804 {
805 #ifdef QWEBKIT_TIME_RENDERING
806     QTime time;
807     time.start();
808 #endif
809
810     QPainter p(this);
811
812     QVector<QRect> vector = ev->region().rects();
813     if (!vector.isEmpty()) {
814         for (int i = 0; i < vector.size(); ++i) {
815             mainFrame()->render(&p, vector.at(i));
816         }
817     } else {
818         mainFrame()->render(&p, ev->rect());
819     }
820
821 #ifdef    QWEBKIT_TIME_RENDERING
822     int elapsed = time.elapsed();
823     qDebug()<<"paint event on "<<ev->region()<<", took to render =  "<<elapsed;
824 #endif
825 }
826
827 void QWebPage::mouseMoveEvent(QMouseEvent *ev)
828 {
829     QWebFramePrivate *frame = d->currentFrame(ev->pos())->d;
830     if (!frame->frameView)
831         return;
832
833     frame->eventHandler->handleMouseMoveEvent(PlatformMouseEvent(ev, 0));
834     const int xOffset =
835         frame->horizontalScrollBar() ? frame->horizontalScrollBar()->value() : 0;
836     const int yOffset =
837         frame->verticalScrollBar() ? frame->verticalScrollBar()->value() : 0;
838     IntPoint pt(ev->x() + xOffset, ev->y() + yOffset);
839     WebCore::HitTestResult result = frame->eventHandler->hitTestResultAtPoint(pt, false);
840     WebCore::Element *link = result.URLElement();
841     if (link != frame->lastHoverElement) {
842         frame->lastHoverElement = link;
843         emit hoveringOverLink(result.absoluteLinkURL().prettyURL(), result.title());
844     }
845 }
846
847 void QWebPage::mousePressEvent(QMouseEvent *ev)
848 {
849     d->frameUnderMouse = d->frameAt(ev->pos());
850     QWebFramePrivate *frame = d->frameUnderMouse->d;
851     if (!frame->eventHandler)
852         return;
853
854     frame->eventHandler->handleMousePressEvent(PlatformMouseEvent(ev, 1));
855
856     //FIXME need to keep track of subframe focus for key events!
857     frame->page->setFocus();
858 }
859
860 void QWebPage::mouseDoubleClickEvent(QMouseEvent *ev)
861 {
862     QWebFramePrivate *frame = d->currentFrame(ev->pos())->d;
863     if (!frame->eventHandler)
864         return;
865
866     frame->eventHandler->handleMousePressEvent(PlatformMouseEvent(ev, 2));
867
868     //FIXME need to keep track of subframe focus for key events!
869     frame->page->setFocus();
870 }
871
872 void QWebPage::mouseReleaseEvent(QMouseEvent *ev)
873 {
874     QWebFramePrivate *frame = d->currentFrame(ev->pos())->d;
875     if (frame->frameView) {
876         frame->eventHandler->handleMouseReleaseEvent(PlatformMouseEvent(ev, 0));
877
878         //FIXME need to keep track of subframe focus for key events!
879         frame->page->setFocus();
880     }
881     d->frameUnderMouse = 0;
882 }
883
884 void QWebPage::contextMenuEvent(QContextMenuEvent *ev)
885 {
886     QWebFramePrivate *frame = d->currentFrame(ev->pos())->d;
887     if (!frame->eventHandler)
888         return;
889     d->page->contextMenuController()->clearContextMenu();
890     frame->eventHandler->sendContextMenuEvent(PlatformMouseEvent(ev, 1));
891     ContextMenu *menu = d->page->contextMenuController()->contextMenu();
892
893     QWebPageContext oldContext = d->currentContext;
894     d->currentContext = QWebPageContext(menu->hitTestResult());
895
896     QList<ContextMenuItem> *items = menu->platformDescription();
897     QMenu *qmenu = d->createContextMenu(items);
898     if (qmenu) {
899         qmenu->exec(ev->globalPos());
900         delete qmenu;
901     }
902     d->currentContext = oldContext;
903 }
904
905 void QWebPage::wheelEvent(QWheelEvent *ev)
906 {
907     QWebFramePrivate *frame = d->currentFrame(ev->pos())->d;
908
909     bool accepted = false;
910     if (frame->eventHandler) {
911         WebCore::PlatformWheelEvent pev(ev);
912         accepted = frame->eventHandler->handleWheelEvent(pev);
913     }
914
915     ev->setAccepted(accepted);
916
917     //FIXME need to keep track of subframe focus for key events!
918     frame->page->setFocus();
919
920     if (!ev->isAccepted())
921         QWidget::wheelEvent(ev);
922 }
923
924 void QWebPage::keyPressEvent(QKeyEvent *ev)
925 {
926     if (!mainFrame()->d->eventHandler)
927         return;
928
929     bool handled = false;
930     QWebFrame *frame = mainFrame();
931     WebCore::Editor *editor = frame->d->frame->editor();
932     if (editor->canEdit()) {
933         if (ev == QKeySequence::Cut) {
934             webActionTriggered(Cut);
935             handled = true;
936         } else if (ev == QKeySequence::Copy) {
937             webActionTriggered(Copy);
938             handled = true;
939         } else if (ev == QKeySequence::Paste) {
940             webActionTriggered(Paste);
941             handled = true;
942         } else if (ev == QKeySequence::Undo) {
943             webActionTriggered(Undo);
944             handled = true;
945         } else if (ev == QKeySequence::Redo) {
946             webActionTriggered(Redo);
947             handled = true;
948         } else if(ev == QKeySequence::MoveToNextChar) {
949             webActionTriggered(MoveToNextChar);
950             handled = true;
951         } else if(ev == QKeySequence::MoveToPreviousChar) {
952             webActionTriggered(MoveToPreviousChar);
953             handled = true;
954         } else if(ev == QKeySequence::MoveToNextWord) {
955             webActionTriggered(MoveToNextWord);
956             handled = true;
957         } else if(ev == QKeySequence::MoveToPreviousWord) {
958             webActionTriggered(MoveToPreviousWord);
959             handled = true;
960         } else if(ev == QKeySequence::MoveToNextLine) {
961             webActionTriggered(MoveToNextLine);
962             handled = true;
963         } else if(ev == QKeySequence::MoveToPreviousLine) {
964             webActionTriggered(MoveToPreviousLine);
965             handled = true;
966 //             } else if(ev == QKeySequence::MoveToNextPage) {
967 //             } else if(ev == QKeySequence::MoveToPreviousPage) {
968         } else if(ev == QKeySequence::MoveToStartOfLine) {
969             webActionTriggered(MoveToStartOfLine);
970             handled = true;
971         } else if(ev == QKeySequence::MoveToEndOfLine) {
972             webActionTriggered(MoveToEndOfLine);
973             handled = true;
974         } else if(ev == QKeySequence::MoveToStartOfBlock) {
975             webActionTriggered(MoveToStartOfBlock);
976             handled = true;
977         } else if(ev == QKeySequence::MoveToEndOfBlock) {
978             webActionTriggered(MoveToEndOfBlock);
979             handled = true;
980         } else if(ev == QKeySequence::MoveToStartOfDocument) {
981             webActionTriggered(MoveToStartOfDocument);
982             handled = true;
983         } else if(ev == QKeySequence::MoveToEndOfDocument) {
984             webActionTriggered(MoveToEndOfDocument);
985             handled = true;
986         } else if(ev == QKeySequence::SelectNextChar) {
987             webActionTriggered(SelectNextChar);
988             handled = true;
989         } else if(ev == QKeySequence::SelectPreviousChar) {
990             webActionTriggered(SelectPreviousChar);
991             handled = true;
992         } else if(ev == QKeySequence::SelectNextWord) {
993             webActionTriggered(SelectNextWord);
994             handled = true;
995         } else if(ev == QKeySequence::SelectPreviousWord) {
996             webActionTriggered(SelectPreviousWord);
997             handled = true;
998         } else if(ev == QKeySequence::SelectNextLine) {
999             webActionTriggered(SelectNextLine);
1000             handled = true;
1001         } else if(ev == QKeySequence::SelectPreviousLine) {
1002             webActionTriggered(SelectPreviousLine);
1003             handled = true;
1004 //             } else if(ev == QKeySequence::SelectNextPage) {
1005 //             } else if(ev == QKeySequence::SelectPreviousPage) {
1006         } else if(ev == QKeySequence::SelectStartOfLine) {
1007             webActionTriggered(SelectStartOfLine);
1008             handled = true;
1009         } else if(ev == QKeySequence::SelectEndOfLine) {
1010             webActionTriggered(SelectEndOfLine);
1011             handled = true;
1012         } else if(ev == QKeySequence::SelectStartOfBlock) {
1013             webActionTriggered(SelectStartOfBlock);
1014             handled = true;
1015         } else if(ev == QKeySequence::SelectEndOfBlock) {
1016             webActionTriggered(SelectEndOfBlock);
1017             handled = true;
1018         } else if(ev == QKeySequence::SelectStartOfDocument) {
1019             webActionTriggered(SelectStartOfDocument);
1020             handled = true;
1021         } else if(ev == QKeySequence::SelectEndOfDocument) {
1022             webActionTriggered(SelectEndOfDocument);
1023             handled = true;
1024         } else if(ev == QKeySequence::DeleteStartOfWord) {
1025             webActionTriggered(DeleteStartOfWord);
1026             handled = true;
1027         } else if(ev == QKeySequence::DeleteEndOfWord) {
1028             webActionTriggered(DeleteEndOfWord);
1029             handled = true;
1030 //             } else if(ev == QKeySequence::DeleteEndOfLine) {
1031         }
1032     }
1033     if (!handled) 
1034         handled = frame->d->eventHandler->keyEvent(ev);
1035     if (!handled) {
1036         handled = true;
1037         PlatformScrollbar *h, *v;
1038         h = mainFrame()->d->horizontalScrollBar();
1039         v = mainFrame()->d->verticalScrollBar();
1040
1041         if (ev == QKeySequence::MoveToNextPage) {
1042             if (v)
1043                 v->setValue(v->value() + height());
1044         } else if (ev == QKeySequence::MoveToPreviousPage) {
1045             if (v)
1046                 v->setValue(v->value() - height());
1047         } else {
1048             switch (ev->key()) {
1049             case Qt::Key_Up:
1050                 if (v)
1051                     v->setValue(v->value() - 10);
1052                 break;
1053             case Qt::Key_Down:
1054                 if (v)
1055                     v->setValue(v->value() + 10);
1056                 break;
1057             case Qt::Key_Left:
1058                 if (h)
1059                     h->setValue(h->value() - 10);
1060                 break;
1061             case Qt::Key_Right:
1062                 if (h)
1063                     h->setValue(h->value() + 10);
1064                 break;
1065             default:
1066                 handled = false;
1067                 break;
1068             }
1069         }
1070     }
1071
1072     ev->setAccepted(handled);
1073 }
1074
1075 void QWebPage::keyReleaseEvent(QKeyEvent *ev)
1076 {
1077     if (ev->isAutoRepeat()) {
1078         ev->setAccepted(true);
1079         return;
1080     }
1081
1082     if (!mainFrame()->d->eventHandler)
1083         return;
1084
1085     bool handled = mainFrame()->d->eventHandler->keyEvent(ev);
1086     ev->setAccepted(handled);
1087 }
1088
1089 void QWebPage::focusInEvent(QFocusEvent *ev)
1090 {
1091     if (ev->reason() != Qt::PopupFocusReason) 
1092         mainFrame()->d->frame->page()->focusController()->setFocusedFrame(mainFrame()->d->frame);
1093     QWidget::focusInEvent(ev);
1094 }
1095
1096 void QWebPage::focusOutEvent(QFocusEvent *ev)
1097 {
1098     QWidget::focusOutEvent(ev);
1099     if (ev->reason() != Qt::PopupFocusReason) {
1100         mainFrame()->d->frame->selectionController()->clear();
1101         mainFrame()->d->frame->setIsActive(false);
1102     }
1103 }
1104
1105 bool QWebPage::focusNextPrevChild(bool next)
1106 {
1107     Q_UNUSED(next)
1108     return false;
1109 }
1110
1111 void QWebPage::dragEnterEvent(QDragEnterEvent *ev)
1112 {
1113 #ifndef QT_NO_DRAGANDDROP
1114     DragData dragData(ev->mimeData(), ev->pos(), QCursor::pos(), 
1115                       dropActionToDragOp(ev->possibleActions()));
1116     Qt::DropAction action = dragOpToDropAction(d->page->dragController()->dragEntered(&dragData));
1117     ev->setDropAction(action);
1118     ev->accept();
1119 #endif
1120 }
1121
1122 void QWebPage::dragLeaveEvent(QDragLeaveEvent *ev)
1123 {
1124 #ifndef QT_NO_DRAGANDDROP
1125     DragData dragData(0, IntPoint(), QCursor::pos(), DragOperationNone);
1126     d->page->dragController()->dragExited(&dragData);
1127     ev->accept();
1128 #endif
1129 }
1130
1131 void QWebPage::dragMoveEvent(QDragMoveEvent *ev)
1132 {
1133 #ifndef QT_NO_DRAGANDDROP
1134     DragData dragData(ev->mimeData(), ev->pos(), QCursor::pos(), 
1135                       dropActionToDragOp(ev->possibleActions()));
1136     Qt::DropAction action = dragOpToDropAction(d->page->dragController()->dragUpdated(&dragData));
1137     ev->setDropAction(action);
1138     ev->accept();
1139 #endif
1140 }
1141
1142 void QWebPage::dropEvent(QDropEvent *ev)
1143 {
1144 #ifndef QT_NO_DRAGANDDROP
1145     DragData dragData(ev->mimeData(), ev->pos(), QCursor::pos(), 
1146                       dropActionToDragOp(ev->possibleActions()));
1147     Qt::DropAction action = dragOpToDropAction(d->page->dragController()->performDrag(&dragData));
1148     ev->accept();
1149 #endif
1150 }
1151
1152 void QWebPage::setNetworkInterface(QWebNetworkInterface *interface)
1153 {
1154     d->networkInterface = interface;
1155 }
1156
1157 QWebNetworkInterface *QWebPage::networkInterface() const
1158 {
1159     if (d->networkInterface)
1160         return d->networkInterface;
1161     else
1162         return QWebNetworkInterface::defaultInterface();
1163 }
1164
1165 QPixmap QWebPage::icon() const
1166 {
1167     Image* image = iconDatabase()->iconForPageURL(url().toString(), IntSize(16, 16));
1168     if (!image || image->isNull()) {
1169         image = iconDatabase()->defaultIcon(IntSize(16, 16));
1170     }
1171
1172     if (!image) {
1173         return QPixmap();
1174     }
1175
1176     QPixmap *icon = image->getPixmap();
1177     if (!icon) {
1178         return QPixmap();
1179     }
1180     return *icon;
1181 }
1182
1183 QWebSettings *QWebPage::settings()
1184 {
1185     return d->settings;
1186 }
1187
1188 QString QWebPage::chooseFile(QWebFrame *parentFrame, const QString& oldFile)
1189 {
1190     //FIXME frame pos...
1191 #ifndef QT_NO_FILEDIALOG
1192     return QFileDialog::getOpenFileName(this, QString::null, oldFile);
1193 #else
1194     return QString::null;
1195 #endif
1196 }
1197
1198 #ifndef QT_NO_NETWORKPROXY
1199 void QWebPage::setNetworkProxy(const QNetworkProxy& proxy)
1200 {
1201     d->networkProxy = proxy;
1202 }
1203
1204 QNetworkProxy QWebPage::networkProxy() const
1205 {
1206     return d->networkProxy;
1207 }
1208 #endif
1209
1210 QString QWebPage::userAgentStringForUrl(const QUrl& forUrl) const {
1211     Q_UNUSED(forUrl)
1212     return QLatin1String("Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/418.9.1 (KHTML, like Gecko) Safari/419.3 Qt");
1213 }
1214
1215
1216 void QWebPagePrivate::_q_onLoadProgressChanged(int) {
1217     m_totalBytes = page->progress()->totalPageAndResourceBytesToLoad();
1218     m_bytesReceived = page->progress()->totalBytesReceived();
1219 }
1220
1221
1222 quint64 QWebPage::totalBytes() const {
1223     return d->m_bytesReceived;
1224 }
1225
1226
1227 quint64 QWebPage::bytesReceived() const {
1228     return d->m_totalBytes;
1229 }
1230
1231 QWebPageContext::QWebPageContext(const WebCore::HitTestResult &hitTest)
1232     : d(new QWebPageContextPrivate)
1233 {
1234     d->pos = hitTest.point();
1235     d->text = hitTest.textContent();
1236     d->linkUrl = hitTest.absoluteLinkURL().url();
1237     d->imageUrl = hitTest.absoluteImageURL().url();
1238     WebCore::Image *img = hitTest.image();
1239     if (img) {
1240         QPixmap *pix = img->getPixmap();
1241         if (pix)
1242             d->image = *pix;
1243     }
1244     WebCore::Frame *frame = hitTest.targetFrame();
1245     if (frame)
1246         d->targetFrame = frame->view()->qwebframe();
1247 }
1248
1249 QWebPageContext::QWebPageContext()
1250     : d(0)
1251 {
1252 }
1253
1254 QWebPageContext::QWebPageContext(const QWebPageContext &other)
1255     : d(0)
1256 {
1257     if (other.d)
1258         d = new QWebPageContextPrivate(*other.d);
1259 }
1260
1261 QWebPageContext &QWebPageContext::operator=(const QWebPageContext &other)
1262 {
1263     if (this != &other) {
1264         if (other.d) {
1265             if (!d)
1266                 d = new QWebPageContextPrivate;
1267             *d = *other.d;
1268         } else {
1269             delete d;
1270             d = 0;
1271         }
1272     }
1273     return *this;
1274 }
1275
1276 QWebPageContext::~QWebPageContext()
1277 {
1278     delete d;
1279 }
1280
1281 QPoint QWebPageContext::pos() const
1282 {
1283     if (!d)
1284         return QPoint();
1285     return d->pos;
1286 }
1287
1288 QString QWebPageContext::text() const
1289 {
1290     if (!d)
1291         return QString();
1292     return d->text;
1293 }
1294
1295 QUrl QWebPageContext::linkUrl() const
1296 {
1297     if (!d)
1298         return QUrl();
1299     return d->linkUrl;
1300 }
1301
1302 QUrl QWebPageContext::imageUrl() const
1303 {
1304     if (!d)
1305         return QUrl();
1306     return d->linkUrl;
1307 }
1308
1309 QPixmap QWebPageContext::image() const
1310 {
1311     if (!d)
1312         return QPixmap();
1313     return d->image;
1314 }
1315
1316 QWebFrame *QWebPageContext::targetFrame() const
1317 {
1318     if (!d)
1319         return 0;
1320     return d->targetFrame;
1321 }
1322
1323 #include "moc_qwebpage.cpp"