2e90a7360b888b56951dd79f83bc2c838031ec72
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / qt / WebPageQt.cpp
1 /*
2  * Copyright (C) 2010 Apple Inc. All rights reserved.
3  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "WebPage.h"
29
30 #include "NotImplemented.h"
31 #include "WebEditorClient.h"
32 #include "WebEvent.h"
33 #include "WebPageProxyMessages.h"
34 #include "WebProcess.h"
35 #include <WebCore/DOMWrapperWorld.h>
36 #include <WebCore/FocusController.h>
37 #include <WebCore/Frame.h>
38 #include <WebCore/KeyboardEvent.h>
39 #include <WebCore/Page.h>
40 #include <WebCore/PageGroup.h>
41 #include <WebCore/PlatformKeyboardEvent.h>
42 #include <WebCore/Range.h>
43 #include <WebCore/Settings.h>
44 #include <WebCore/Text.h>
45 #include <WebCore/TextIterator.h>
46
47 #ifndef VK_UNKNOWN
48 #define VK_UNKNOWN 0
49 #define VK_BACK 0x08
50 #define VK_TAB 0x09
51 #define VK_CLEAR 0x0C
52 #define VK_RETURN 0x0D
53 #define VK_SHIFT 0x10
54 #define VK_CONTROL 0x11 // CTRL key
55 #define VK_MENU 0x12 // ALT key
56 #define VK_PAUSE 0x13 // PAUSE key
57 #define VK_CAPITAL 0x14 // CAPS LOCK key
58 #define VK_KANA 0x15 // Input Method Editor (IME) Kana mode
59 #define VK_HANGUL 0x15 // IME Hangul mode
60 #define VK_JUNJA 0x17 // IME Junja mode
61 #define VK_FINAL 0x18 // IME final mode
62 #define VK_HANJA 0x19 // IME Hanja mode 
63 #define VK_KANJI 0x19 // IME Kanji mode
64 #define VK_ESCAPE 0x1B // ESC key
65 #define VK_CONVERT 0x1C // IME convert
66 #define VK_NONCONVERT 0x1D // IME nonconvert
67 #define VK_ACCEPT 0x1E // IME accept
68 #define VK_MODECHANGE 0x1F // IME mode change request
69 #define VK_SPACE 0x20 // SPACE key
70 #define VK_PRIOR 0x21 // PAGE UP key
71 #define VK_NEXT 0x22 // PAGE DOWN key
72 #define VK_END 0x23 // END key
73 #define VK_HOME 0x24 // HOME key
74 #define VK_LEFT 0x25 // LEFT ARROW key
75 #define VK_UP 0x26 // UP ARROW key
76 #define VK_RIGHT 0x27 // RIGHT ARROW key
77 #define VK_DOWN 0x28 // DOWN ARROW key
78 #define VK_SELECT 0x29 // SELECT key
79 #define VK_PRINT 0x2A // PRINT key
80 #define VK_EXECUTE 0x2B // EXECUTE key
81 #define VK_SNAPSHOT 0x2C // PRINT SCREEN key
82 #define VK_INSERT 0x2D // INS key
83 #define VK_DELETE 0x2E // DEL key
84 #define VK_HELP 0x2F // HELP key
85 // Windows 2000/XP: For any country/region, the '.' key
86 #define VK_OEM_PERIOD 0xBE
87 #endif
88
89 using namespace WebCore;
90
91 namespace WebKit {
92     
93 void WebPage::platformInitialize()
94 {
95 }
96
97 void WebPage::platformPreferencesDidChange(const WebPreferencesStore&)
98 {
99 }
100
101 static const unsigned CtrlKey = 1 << 0;
102 static const unsigned AltKey = 1 << 1;
103 static const unsigned ShiftKey = 1 << 2;
104
105 struct KeyDownEntry {
106     unsigned virtualKey;
107     unsigned modifiers;
108     const char* name;
109 };
110
111 struct KeyPressEntry {
112     unsigned charCode;
113     unsigned modifiers;
114     const char* name;
115 };
116
117 static const KeyDownEntry keyDownEntries[] = {
118     { VK_LEFT,   0,                  "MoveLeft"                                    },
119     { VK_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"                  },
120     { VK_LEFT,   CtrlKey,            "MoveWordLeft"                                },
121     { VK_LEFT,   CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection"              },
122     { VK_RIGHT,  0,                  "MoveRight"                                   },
123     { VK_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"                 },
124     { VK_RIGHT,  CtrlKey,            "MoveWordRight"                               },
125     { VK_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"             },
126     { VK_UP,     0,                  "MoveUp"                                      },
127     { VK_UP,     ShiftKey,           "MoveUpAndModifySelection"                    },
128     { VK_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"                },
129     { VK_DOWN,   0,                  "MoveDown"                                    },
130     { VK_DOWN,   ShiftKey,           "MoveDownAndModifySelection"                  },
131     { VK_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"              },
132     { VK_PRIOR,  0,                  "MovePageUp"                                  },
133     { VK_NEXT,   0,                  "MovePageDown"                                },
134     { VK_HOME,   0,                  "MoveToBeginningOfLine"                       },
135     { VK_HOME,   ShiftKey,           "MoveToBeginningOfLineAndModifySelection"     },
136     { VK_HOME,   CtrlKey,            "MoveToBeginningOfDocument"                   },
137     { VK_HOME,   CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
138     
139     { VK_END,    0,                  "MoveToEndOfLine"                             },
140     { VK_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"           },
141     { VK_END,    CtrlKey,            "MoveToEndOfDocument"                         },
142     { VK_END,    CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection"       },
143     
144     { VK_BACK,   0,                  "DeleteBackward"                              },
145     { VK_BACK,   ShiftKey,           "DeleteBackward"                              },
146     { VK_DELETE, 0,                  "DeleteForward"                               },
147     { VK_BACK,   CtrlKey,            "DeleteWordBackward"                          },
148     { VK_DELETE, CtrlKey,            "DeleteWordForward"                           },
149     
150     { 'B',       CtrlKey,            "ToggleBold"                                  },
151     { 'I',       CtrlKey,            "ToggleItalic"                                },
152     
153     { VK_ESCAPE, 0,                  "Cancel"                                      },
154     { VK_OEM_PERIOD, CtrlKey,        "Cancel"                                      },
155     { VK_TAB,    0,                  "InsertTab"                                   },
156     { VK_TAB,    ShiftKey,           "InsertBacktab"                               },
157     { VK_RETURN, 0,                  "InsertNewline"                               },
158     { VK_RETURN, CtrlKey,            "InsertNewline"                               },
159     { VK_RETURN, AltKey,             "InsertNewline"                               },
160     { VK_RETURN, ShiftKey,           "InsertNewline"                               },
161     { VK_RETURN, AltKey | ShiftKey,  "InsertNewline"                               },
162     
163     // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
164     // in the application or in WebKit. We chose WebKit.
165     { 'C',       CtrlKey,            "Copy"                                        },
166     { 'V',       CtrlKey,            "Paste"                                       },
167     { 'X',       CtrlKey,            "Cut"                                         },
168     { 'A',       CtrlKey,            "SelectAll"                                   },
169     { VK_INSERT, CtrlKey,            "Copy"                                        },
170     { VK_DELETE, ShiftKey,           "Cut"                                         },
171     { VK_INSERT, ShiftKey,           "Paste"                                       },
172     { 'Z',       CtrlKey,            "Undo"                                        },
173     { 'Z',       CtrlKey | ShiftKey, "Redo"                                        },
174 };
175
176 static const KeyPressEntry keyPressEntries[] = {
177     { '\t',   0,                  "InsertTab"                                   },
178     { '\t',   ShiftKey,           "InsertBacktab"                               },
179     { '\r',   0,                  "InsertNewline"                               },
180     { '\r',   CtrlKey,            "InsertNewline"                               },
181     { '\r',   AltKey,             "InsertNewline"                               },
182     { '\r',   ShiftKey,           "InsertNewline"                               },
183     { '\r',   AltKey | ShiftKey,  "InsertNewline"                               },
184 };
185
186 const char* WebPage::interpretKeyEvent(const KeyboardEvent* evt)
187 {
188     ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
189     
190     static HashMap<int, const char*>* keyDownCommandsMap = 0;
191     static HashMap<int, const char*>* keyPressCommandsMap = 0;
192     
193     if (!keyDownCommandsMap) {
194         keyDownCommandsMap = new HashMap<int, const char*>;
195         keyPressCommandsMap = new HashMap<int, const char*>;
196         
197         for (unsigned i = 0; i < (sizeof(keyDownEntries) / sizeof(keyDownEntries[0])); i++)
198             keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
199         
200         for (unsigned i = 0; i < (sizeof(keyPressEntries) / sizeof(keyPressEntries[0])); i++)
201             keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
202     }
203     
204     unsigned modifiers = 0;
205     if (evt->shiftKey())
206         modifiers |= ShiftKey;
207     if (evt->altKey())
208         modifiers |= AltKey;
209     if (evt->ctrlKey())
210         modifiers |= CtrlKey;
211     
212     if (evt->type() == eventNames().keydownEvent) {
213         int mapKey = modifiers << 16 | evt->keyEvent()->windowsVirtualKeyCode();
214         return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
215     }
216     
217     int mapKey = modifiers << 16 | evt->charCode();
218     return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
219 }
220
221 static inline void scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
222 {
223     page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
224 }
225
226 static inline void logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
227 {
228     page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
229 }
230
231 bool WebPage::performDefaultBehaviorForKeyEvent(const WebKeyboardEvent& keyboardEvent)
232 {
233     if (keyboardEvent.type() != WebEvent::KeyDown && keyboardEvent.type() != WebEvent::RawKeyDown)
234         return false;
235
236     switch (keyboardEvent.windowsVirtualKeyCode()) {
237     case VK_BACK:
238         if (keyboardEvent.shiftKey())
239             m_page->goForward();
240         else
241             m_page->goBack();
242         break;
243     case VK_SPACE:
244         logicalScroll(m_page.get(), keyboardEvent.shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward, ScrollByPage);
245         break;
246     case VK_LEFT:
247         scroll(m_page.get(), ScrollLeft, ScrollByLine);
248         break;
249     case VK_RIGHT:
250         scroll(m_page.get(), ScrollRight, ScrollByLine);
251         break;
252     case VK_UP:
253         scroll(m_page.get(), ScrollUp, ScrollByLine);
254         break;
255     case VK_DOWN:
256         scroll(m_page.get(), ScrollDown, ScrollByLine);
257         break;
258     case VK_HOME:
259         logicalScroll(m_page.get(), ScrollBlockDirectionBackward, ScrollByDocument);
260         break;
261     case VK_END:
262         logicalScroll(m_page.get(), ScrollBlockDirectionForward, ScrollByDocument);
263         break;
264     case VK_PRIOR:
265         logicalScroll(m_page.get(), ScrollBlockDirectionBackward, ScrollByPage);
266         break;
267     case VK_NEXT:
268         logicalScroll(m_page.get(), ScrollBlockDirectionForward, ScrollByPage);
269         break;
270     default:
271         return false;
272     }
273
274     return true;
275 }
276
277 bool WebPage::platformHasLocalDataForURL(const KURL&)
278 {
279     notImplemented();
280     return false;
281 }
282
283 String WebPage::cachedResponseMIMETypeForURL(const KURL&)
284 {
285     notImplemented();
286     return String();
287 }
288
289 bool WebPage::platformCanHandleRequest(const ResourceRequest&)
290 {
291     notImplemented();
292     return true;
293 }
294
295 String WebPage::cachedSuggestedFilenameForURL(const KURL&)
296 {
297     notImplemented();
298     return String();
299 }
300
301 PassRefPtr<SharedBuffer> WebPage::cachedResponseDataForURL(const KURL&)
302 {
303     notImplemented();
304     return 0;
305 }
306
307 static Frame* targetFrameForEditing(WebPage* page)
308 {
309     Frame* targetFrame = page->corePage()->focusController()->focusedOrMainFrame();
310
311     if (!targetFrame || !targetFrame->editor())
312         return 0;
313
314     Editor* editor = targetFrame->editor();
315     if (!editor->canEdit())
316         return 0;
317
318     if (editor->hasComposition()) {
319         // We should verify the parent node of this IME composition node are
320         // editable because JavaScript may delete a parent node of the composition
321         // node. In this case, WebKit crashes while deleting texts from the parent
322         // node, which doesn't exist any longer.
323         if (PassRefPtr<Range> range = editor->compositionRange()) {
324             Node* node = range->startContainer();
325             if (!node || !node->isContentEditable())
326                 return 0;
327         }
328     }
329     return targetFrame;
330 }
331
332 void WebPage::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength)
333 {
334     Frame* targetFrame = targetFrameForEditing(this);
335     if (!targetFrame)
336         return;
337
338     Editor* editor = targetFrame->editor();
339     editor->confirmComposition(compositionString);
340
341     if (selectionStart == -1)
342         return;
343
344     Element* scope = targetFrame->selection()->rootEditableElement();
345     RefPtr<Range> selectionRange = TextIterator::rangeFromLocationAndLength(scope, selectionStart, selectionLength);
346     ASSERT_WITH_MESSAGE(selectionRange, "Invalid selection: [%lld:%lld] in text of length %d", static_cast<long long>(selectionStart), static_cast<long long>(selectionLength), scope->innerText().length());
347
348     if (selectionRange) {
349         VisibleSelection selection(selectionRange.get(), SEL_DEFAULT_AFFINITY);
350         targetFrame->selection()->setSelection(selection);
351     }
352
353     // FIXME: static_cast<WebEditorClient*>(editor->client())->sendSelectionChangedMessage();
354 }
355
356 void WebPage::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementStart, uint64_t replacementLength)
357 {
358     Frame* targetFrame = targetFrameForEditing(this);
359     if (!targetFrame)
360         return;
361
362     Element* scope = targetFrame->selection()->rootEditableElement();
363
364     if (targetFrame->selection()->isContentEditable()) {
365         if (replacementLength > 0) {
366             // The layout needs to be uptodate before setting a selection
367             targetFrame->document()->updateLayout();
368
369             RefPtr<Range> replacementRange = TextIterator::rangeFromLocationAndLength(scope, replacementStart, replacementLength);
370
371             targetFrame->editor()->setIgnoreCompositionSelectionChange(true);
372             targetFrame->selection()->setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
373             targetFrame->editor()->setIgnoreCompositionSelectionChange(false);
374         }
375
376         targetFrame->editor()->setComposition(text, underlines, selectionStart, selectionEnd);
377
378         // FIXME: static_cast<WebEditorClient*>(targetFrame->editor()->client())->sendSelectionChangedMessage();
379     }
380 }
381
382 void WebPage::cancelComposition()
383 {
384     Frame* frame = targetFrameForEditing(this);
385
386     frame->editor()->cancelComposition();
387
388     // FIXME: static_cast<WebEditorClient*>(targetFrame->editor()->client())->sendSelectionChangedMessage();
389 }
390
391 void WebPage::registerApplicationScheme(const String& scheme)
392 {
393     QtNetworkAccessManager* qnam = qobject_cast<QtNetworkAccessManager*>(WebProcess::shared().networkAccessManager());
394     if (!qnam)
395         return;
396     qnam->registerApplicationScheme(this, QString(scheme));
397 }
398
399 void WebPage::receivedApplicationSchemeRequest(const QNetworkRequest& request, QtNetworkReply* reply)
400 {
401     QtNetworkRequestData requestData(request, reply);
402     m_applicationSchemeReplies.add(requestData.m_replyUuid, reply);
403     send(Messages::WebPageProxy::ResolveApplicationSchemeRequest(requestData));
404 }
405
406 void WebPage::applicationSchemeReply(const QtNetworkReplyData& replyData)
407 {
408     if (!m_applicationSchemeReplies.contains(replyData.m_replyUuid))
409         return;
410
411     QtNetworkReply* networkReply = m_applicationSchemeReplies.take(replyData.m_replyUuid);
412     networkReply->setReplyData(replyData);
413     networkReply->finalize();
414 }
415
416 void WebPage::setUserScripts(const Vector<String>& scripts)
417 {
418     // This works because we keep an unique page group for each Page.
419     PageGroup* pageGroup = PageGroup::pageGroup(this->pageGroup()->identifier());
420     pageGroup->removeUserScriptsFromWorld(mainThreadNormalWorld());
421     for (unsigned i = 0; i < scripts.size(); ++i)
422         pageGroup->addUserScriptToWorld(mainThreadNormalWorld(), scripts.at(i), KURL(), nullptr, nullptr, InjectAtDocumentEnd, InjectInTopFrameOnly);
423 }
424
425 } // namespace WebKit