Add keypad layout that has number variation
[framework/web/webkit-efl.git] / Source / WebKit2 / WebProcess / WebPage / WebPage.cpp
1 /*
2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2012 Intel Corporation. All rights reserved.
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 "Arguments.h"
31 #include "DataReference.h"
32 #include "DecoderAdapter.h"
33 #include "DrawingArea.h"
34 #include "InjectedBundle.h"
35 #include "InjectedBundleBackForwardList.h"
36 #include "LayerTreeHost.h"
37 #include "MessageID.h"
38 #include "NetscapePlugin.h"
39 #include "NotificationPermissionRequestManager.h"
40 #include "PageOverlay.h"
41 #include "PluginProxy.h"
42 #include "PluginView.h"
43 #include "PrintInfo.h"
44 #include "SessionState.h"
45 #include "ShareableBitmap.h"
46 #include "WebAlternativeTextClient.h"
47 #include "WebBackForwardList.h"
48 #include "WebBackForwardListItem.h"
49 #include "WebBackForwardListProxy.h"
50 #include "WebChromeClient.h"
51 #include "WebColorChooser.h"
52 #include "WebContextMenu.h"
53 #include "WebContextMenuClient.h"
54 #include "WebContextMessages.h"
55 #include "WebCoreArgumentCoders.h"
56 #include "WebDragClient.h"
57 #include "WebEditorClient.h"
58 #include "WebEvent.h"
59 #include "WebEventConversion.h"
60 #include "WebFrame.h"
61 #include "WebFullScreenManager.h"
62 #include "WebGeolocationClient.h"
63 #include "WebGeometry.h"
64 #include "WebImage.h"
65 #include "WebInspector.h"
66 #include "WebInspectorClient.h"
67 #include "WebNotificationClient.h"
68 #include "WebOpenPanelResultListener.h"
69 #include "WebPageCreationParameters.h"
70 #include "WebPageGroupProxy.h"
71 #include "WebPageProxyMessages.h"
72 #include "WebPopupMenu.h"
73 #include "WebPreferencesStore.h"
74 #include "WebProcess.h"
75 #include "WebProcessProxyMessages.h"
76 #include <JavaScriptCore/APICast.h>
77 #include <WebCore/AbstractDatabase.h>
78 #include <WebCore/ArchiveResource.h>
79 #include <WebCore/Chrome.h>
80 #include <WebCore/ContextMenuController.h>
81 #include <WebCore/DocumentFragment.h>
82 #include <WebCore/DocumentLoader.h>
83 #include <WebCore/DocumentMarkerController.h>
84 #include <WebCore/DragController.h>
85 #include <WebCore/DragData.h>
86 #include <WebCore/DragSession.h>
87 #include <WebCore/EventHandler.h>
88 #include <WebCore/FocusController.h>
89 #include <WebCore/FormState.h>
90 #include <WebCore/Frame.h>
91 #include <WebCore/FrameLoadRequest.h>
92 #include <WebCore/FrameLoaderTypes.h>
93 #include <WebCore/FrameView.h>
94 #include <WebCore/HTMLFormElement.h>
95 #include <WebCore/HTMLInputElement.h>
96 #include <WebCore/HTMLPlugInElement.h>
97 #include <WebCore/HistoryItem.h>
98 #include <WebCore/KeyboardEvent.h>
99 #include <WebCore/MouseEvent.h>
100 #include <WebCore/Page.h>
101 #include <WebCore/PlatformKeyboardEvent.h>
102 #include <WebCore/PluginDocument.h>
103 #include <WebCore/PrintContext.h>
104 #include <WebCore/RenderLayer.h>
105 #include <WebCore/RenderTreeAsText.h>
106 #include <WebCore/RenderView.h>
107 #include <WebCore/ResourceRequest.h>
108 #include <WebCore/RunLoop.h>
109 #include <WebCore/SchemeRegistry.h>
110 #include <WebCore/ScriptValue.h>
111 #include <WebCore/SerializedScriptValue.h>
112 #include <WebCore/Settings.h>
113 #include <WebCore/SharedBuffer.h>
114 #include <WebCore/SubstituteData.h>
115 #include <WebCore/TextIterator.h>
116 #include <WebCore/markup.h>
117 #include <runtime/JSLock.h>
118 #include <runtime/JSValue.h>
119
120 #include <WebCore/Range.h>
121 #include <WebCore/VisiblePosition.h>
122
123 #if ENABLE(MHTML)
124 #include <WebCore/MHTMLArchive.h>
125 #endif
126
127 #if ENABLE(PLUGIN_PROCESS)
128 #if PLATFORM(MAC)
129 #include "MachPort.h"
130 #endif
131 #endif
132
133 #if ENABLE(BATTERY_STATUS)
134 #include "WebBatteryClient.h"
135 #endif
136
137 #if ENABLE(NETWORK_INFO)
138 #include "WebNetworkInfoClient.h"
139 #endif
140
141 #if ENABLE(WEB_INTENTS)
142 #include "IntentData.h"
143 #endif
144
145 #if ENABLE(VIBRATION)
146 #include "WebVibrationClient.h"
147 #endif
148
149 #if ENABLE(TIZEN_REGISTER_PROTOCOL_HANDLER) || ENABLE(TIZEN_CUSTOM_SCHEME_HANDLER)
150 #include "WebRegisterProtocolHandlerClient.h"
151 #endif
152
153 #if ENABLE(TIZEN_REGISTER_CONTENT_HANDLER)
154 #include "WebRegisterContentHandlerClient.h"
155 #endif
156
157 #if PLATFORM(MAC)
158 #include "BuiltInPDFView.h"
159 #endif
160
161 #if PLATFORM(QT)
162 #if ENABLE(DEVICE_ORIENTATION)
163 #include "DeviceMotionClientQt.h"
164 #include "DeviceOrientationClientQt.h"
165 #endif
166 #include "HitTestResult.h"
167 #include <QMimeData>
168 #endif
169
170 #if PLATFORM(GTK)
171 #include <gtk/gtk.h>
172 #include "DataObjectGtk.h"
173 #include "WebPrintOperationGtk.h"
174 #endif
175
176 #if ENABLE(TIZEN_MEDIA_STREAM)
177 #include "WebUserMediaClient.h"
178 #include "UserMediaPermissionRequestManager.h"
179 #endif
180
181 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
182 #include <WebCore/NodeList.h>
183 #include "HTMLLinkElement.h"
184 #include "HTMLMetaElement.h"
185 #endif
186
187 #if ENABLE(TIZEN_GEOLOCATION)
188 #include <WebCore/GeolocationClientMock.h>
189 #include <WebCore/GeolocationController.h>
190 #endif
191
192 #ifndef NDEBUG
193 #include <wtf/RefCountedLeakCounter.h>
194 #endif
195
196 #if ENABLE(TIZEN_INDEXED_DATABASE)
197 #include <WebCore/PageGroup.h>
198 #include <WebCore/GroupSettings.h>
199 #endif
200
201 #if ENABLE(TIZEN_ISF_PORT)
202 #include "NativeWebKeyboardEvent.h"
203 #endif
204
205 #if ENABLE(TIZEN_NATIVE_MEMORY_SNAPSHOT)
206 #include "AboutDataTizen.h"
207 #endif
208
209 #if ENABLE(TIZEN_DRAG_SUPPORT)
210 #include "DataObjectTizen.h"
211 #endif
212
213 #if ENABLE(TIZEN_WEBKIT2_CONTEXT_MENU_TEXT_SELECTION_MODE)
214 #include "HTMLImageElement.h"
215 #endif
216
217 using namespace JSC;
218 using namespace WebCore;
219 using namespace std;
220
221 namespace WebKit {
222
223 class SendStopResponsivenessTimer {
224 public:
225     SendStopResponsivenessTimer(WebPage* page)
226         : m_page(page)
227     {
228     }
229     
230     ~SendStopResponsivenessTimer()
231     {
232         m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
233     }
234
235 private:
236     WebPage* m_page;
237 };
238
239 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
240
241 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
242 {
243     RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
244
245     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
246         WebProcess::shared().injectedBundle()->didCreatePage(page.get());
247
248     return page.release();
249 }
250
251 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
252     : m_viewSize(parameters.viewSize)
253     , m_useFixedLayout(false)
254     , m_drawsBackground(true)
255     , m_drawsTransparentBackground(false)
256     , m_isInRedo(false)
257     , m_isClosed(false)
258     , m_tabToLinks(false)
259 #if PLATFORM(MAC)
260     , m_windowIsVisible(false)
261     , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
262     , m_layerHostingMode(parameters.layerHostingMode)
263     , m_keyboardEventBeingInterpreted(0)
264 #elif PLATFORM(WIN)
265     , m_nativeWindow(parameters.nativeWindow)
266 #elif PLATFORM(GTK)
267     , m_accessibilityObject(0)
268 #endif
269     , m_setCanStartMediaTimer(WebProcess::shared().runLoop(), this, &WebPage::setCanStartMediaTimerFired)
270     , m_findController(this)
271 #if ENABLE(TOUCH_EVENTS)
272 #if PLATFORM(QT)
273     , m_tapHighlightController(this)
274 #endif
275 #endif
276 #if ENABLE(INPUT_TYPE_COLOR)
277     , m_activeColorChooser(0)
278 #endif
279 #if ENABLE(GEOLOCATION)
280     , m_geolocationPermissionRequestManager(this)
281 #endif
282     , m_pageID(pageID)
283     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
284     , m_canRunModal(parameters.canRunModal)
285     , m_isRunningModal(false)
286     , m_cachedMainFrameIsPinnedToLeftSide(false)
287     , m_cachedMainFrameIsPinnedToRightSide(false)
288     , m_canShortCircuitHorizontalWheelEvents(false)
289     , m_numWheelEventHandlers(0)
290     , m_cachedPageCount(0)
291 #if ENABLE(CONTEXT_MENUS)
292     , m_isShowingContextMenu(false)
293 #endif
294     , m_willGoToBackForwardItemCallbackEnabled(true)
295 #if PLATFORM(WIN)
296     , m_gestureReachedScrollingLimit(false)
297 #endif
298 #if ENABLE(PAGE_VISIBILITY_API)
299     , m_visibilityState(WebCore::PageVisibilityStateVisible)
300 #endif
301 #if ENABLE(TIZEN_SYNC_REQUEST_ANIMATION_FRAME)
302     , m_suspendedAnimationController(false)
303 #endif
304     , m_inspectorClient(0)
305 {
306     ASSERT(m_pageID);
307     // FIXME: This is a non-ideal location for this Setting and
308     // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
309 #if ENABLE(TIZEN_DOM_TIMER_MIN_INTERVAL_SET)
310     Settings::setDefaultMinDOMTimerInterval(0.001);
311 #else
312     Settings::setDefaultMinDOMTimerInterval(0.004);
313 #endif
314
315     Page::PageClients pageClients;
316     pageClients.chromeClient = new WebChromeClient(this);
317 #if ENABLE(CONTEXT_MENUS)
318     pageClients.contextMenuClient = new WebContextMenuClient(this);
319 #endif
320     pageClients.editorClient = new WebEditorClient(this);
321 #if ENABLE(DRAG_SUPPORT)
322     pageClients.dragClient = new WebDragClient(this);
323 #endif
324     pageClients.backForwardClient = WebBackForwardListProxy::create(this);
325 #if ENABLE(INSPECTOR)
326     m_inspectorClient = new WebInspectorClient(this);
327     pageClients.inspectorClient = m_inspectorClient;
328 #endif
329 #if USE(AUTOCORRECTION_PANEL)
330     pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
331 #endif
332     
333     m_page = adoptPtr(new Page(pageClients));
334
335 #if ENABLE(BATTERY_STATUS)
336     WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
337 #endif
338 #if ENABLE(GEOLOCATION)
339 #if ENABLE(TIZEN_GEOLOCATION) && ENABLE(TIZEN_WEBKIT2_EFL_WTR)
340     if (WebProcess::shared().injectedBundle() && WebProcess::shared().injectedBundle()->testRunnerModeEnabled()) {
341         GeolocationClientMock* mock = new GeolocationClientMock();
342         WebCore::provideGeolocationTo(m_page.get(), mock);
343         mock->setController(WebCore::GeolocationController::from(m_page.get()));
344     } else
345 #endif // ENABLE(TIZEN_GEOLOCATION) && ENABLE(TIZEN_WEBKIT2_EFL_WTR)
346     WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
347 #endif
348 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(QT)
349     WebCore::provideDeviceMotionTo(m_page.get(), new DeviceMotionClientQt);
350     WebCore::provideDeviceOrientationTo(m_page.get(), new DeviceOrientationClientQt);
351 #endif
352 #if ENABLE(NETWORK_INFO)
353     WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this));
354 #endif
355 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
356     WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
357 #endif
358 #if ENABLE(VIBRATION)
359     WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
360 #endif
361
362 #if ENABLE(VIBRATION)
363     WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
364 #endif
365
366 #if ENABLE(TIZEN_MEDIA_STREAM)
367     WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(this));
368 #endif
369
370 #if ENABLE(TIZEN_REGISTER_PROTOCOL_HANDLER) || ENABLE(TIZEN_CUSTOM_SCHEME_HANDLER)
371     WebCore::provideRegisterProtocolHandlerTo(m_page.get(), new WebRegisterProtocolHandlerClient(this));
372 #endif
373
374 #if ENABLE(TIZEN_REGISTER_CONTENT_HANDLER)
375     WebCore::provideRegisterContentHandlerTo(m_page.get(), new WebRegisterContentHandlerClient(this));
376 #endif
377
378     // Qt does not yet call setIsInWindow. Until it does, just leave
379     // this line out so plug-ins and video will work. Eventually all platforms
380     // should call setIsInWindow and this comment and #if should be removed,
381     // leaving behind the setCanStartMedia call.
382 #if !PLATFORM(QT)
383     m_page->setCanStartMedia(false);
384 #endif
385
386     updatePreferences(parameters.store);
387
388     m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
389     m_page->setGroupName(m_pageGroup->identifier());
390     m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
391
392     platformInitialize();
393
394     m_drawingArea = DrawingArea::create(this, parameters);
395     m_drawingArea->setPaintingEnabled(false);
396
397     m_mainFrame = WebFrame::createMainFrame(this);
398
399     setUseFixedLayout(parameters.useFixedLayout);
400
401     setDrawsBackground(parameters.drawsBackground);
402     setDrawsTransparentBackground(parameters.drawsTransparentBackground);
403
404     setPaginationMode(parameters.paginationMode);
405     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
406     setPageLength(parameters.pageLength);
407     setGapBetweenPages(parameters.gapBetweenPages);
408
409     setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
410
411     setActive(parameters.isActive);
412     setFocused(parameters.isFocused);
413     setIsInWindow(parameters.isInWindow);
414
415     m_userAgent = parameters.userAgent;
416
417     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
418     
419     if (!parameters.sessionState.isEmpty())
420         restoreSession(parameters.sessionState);
421
422     m_drawingArea->setPaintingEnabled(true);
423     
424     setMediaVolume(parameters.mediaVolume);
425
426 #ifndef NDEBUG
427     webPageCounter.increment();
428 #endif
429 }
430
431 WebPage::~WebPage()
432 {
433     if (m_backForwardList)
434         m_backForwardList->detach();
435
436     ASSERT(!m_page);
437
438     m_sandboxExtensionTracker.invalidate();
439
440     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
441         (*it)->webPageDestroyed();
442
443 #ifndef NDEBUG
444     webPageCounter.decrement();
445 #endif
446 }
447
448 void WebPage::dummy(bool&)
449 {
450 }
451
452 CoreIPC::Connection* WebPage::connection() const
453 {
454     return WebProcess::shared().connection();
455 }
456
457 #if ENABLE(CONTEXT_MENUS)
458 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
459 {
460     m_contextMenuClient.initialize(client);
461 }
462 #endif
463
464 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
465 {
466     m_editorClient.initialize(client);
467 }
468
469 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
470 {
471     m_formClient.initialize(client);
472 }
473
474 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
475 {
476     m_loaderClient.initialize(client);
477 }
478
479 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
480 {
481     m_policyClient.initialize(client);
482 }
483
484 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
485 {
486     m_resourceLoadClient.initialize(client);
487 }
488
489 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
490 {
491     m_uiClient.initialize(client);
492 }
493
494 #if ENABLE(FULLSCREEN_API)
495 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
496 {
497     m_fullScreenClient.initialize(client);
498 }
499 #endif
500
501 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClient* client)
502 {
503     m_logDiagnosticMessageClient.initialize(client);
504 }
505
506 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters)
507 {
508     String pluginPath;
509     bool blocked = false;
510
511     if (!WebProcess::shared().connection()->sendSync(
512             Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()), 
513             Messages::WebContext::GetPluginPath::Reply(pluginPath, blocked), 0)) {
514         return 0;
515     }
516
517     if (blocked) {
518         if (pluginElement->renderer()->isEmbeddedObject())
519             toRenderEmbeddedObject(pluginElement->renderer())->setPluginUnavailabilityReason(RenderEmbeddedObject::InsecurePluginVersion);
520
521         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string()));
522         return 0;
523     }
524
525     if (pluginPath.isNull()) {
526 #if PLATFORM(MAC)
527         if (parameters.mimeType == "application/pdf"
528             || (parameters.mimeType.isEmpty() && parameters.url.path().lower().endsWith(".pdf")))
529             return BuiltInPDFView::create(frame);
530 #else
531         UNUSED_PARAM(frame);
532 #endif
533         return 0;
534     }
535
536 #if ENABLE(PLUGIN_PROCESS)
537     return PluginProxy::create(pluginPath);
538 #elif ENABLE(NETSCAPE_PLUGIN_API)
539     NetscapePlugin::setSetExceptionFunction(NPRuntimeObjectMap::setGlobalException);
540     return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
541 #else
542     return 0;
543 #endif
544 }
545
546 EditorState WebPage::editorState() const
547 {
548     Frame* frame = m_page->focusController()->focusedOrMainFrame();
549     ASSERT(frame);
550
551     EditorState result;
552     result.selectionIsNone = frame->selection()->isNone();
553     result.selectionIsRange = frame->selection()->isRange();
554     result.isContentEditable = frame->selection()->isContentEditable();
555     result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
556     result.isInPasswordField = frame->selection()->isInPasswordField();
557     result.hasComposition = frame->editor()->hasComposition();
558     result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
559
560 #if ENABLE(TIZEN_WEBKIT2_TEXT_SELECTION) || ENABLE(TIZEN_ISF_PORT)
561     Element* rootEditableElement = frame->selection()->rootEditableElement();
562     if (!rootEditableElement)
563         return result;
564
565     result.editorRect = frame->view()->contentsToWindow(rootEditableElement->getPixelSnappedRect());
566     if (result.editorRect.maxX() <= 0 || result.editorRect.maxY() <= 0)
567         result.isContentEditable = false;
568
569 #if ENABLE(TIZEN_WEBKIT2_GET_TEXT_STYLE_FOR_SELECTION)
570     result.bgColor = frame->editor()->selectionStartCSSPropertyValue(CSSPropertyBackgroundColor);
571     result.color = frame->editor()->selectionStartCSSPropertyValue(CSSPropertyColor);
572 #endif
573 #endif
574
575 #if ENABLE(TIZEN_ISF_PORT)
576     if (!result.shouldIgnoreCompositionSelectionChange && result.isContentEditable) {
577         result.inputMethodContextID = reinterpret_cast<uintptr_t>(rootEditableElement);
578
579         Node* hostNode = rootEditableElement->shadowHost();
580         if (!hostNode)
581             hostNode = rootEditableElement;
582
583         HTMLTextFormControlElement* formControl = toTextFormControl(hostNode);
584         if (formControl) {
585             const AtomicString& type = formControl->type();
586
587             if (type == "number" && formControl->hasTagName(HTMLNames::inputTag)) {
588                 StepRange stepRange = static_cast<HTMLInputElement*>(formControl)->createStepRange(RejectAny);
589                 bool needsSigned = stepRange.minimum().isNegative();
590                 bool needsDecimal = (stepRange.step().floor() != stepRange.step());
591
592                 if (needsSigned && needsDecimal)
593                     result.inputMethodHints = "signedDecimalNumber";
594                 else if (needsSigned)
595                     result.inputMethodHints = "signedNumber";
596                 else if (needsDecimal)
597                     result.inputMethodHints = "decimalNumber";
598                 else
599                     result.inputMethodHints = "number";
600             } else
601                 result.inputMethodHints = type;
602
603             result.surroundingText = formControl->value();
604         }
605
606         Position base = frame->selection()->base();
607         Node* baseNode = base.containerNode();
608         if (baseNode)
609             result.cursorPosition = baseNode->isTextNode() ? base.offsetInContainerNode() : 0;
610     }
611 #endif
612
613 #if PLATFORM(QT)
614     size_t location = 0;
615     size_t length = 0;
616
617     Element* selectionRoot = frame->selection()->rootEditableElement();
618     Element* scope = selectionRoot ? selectionRoot : frame->document()->documentElement();
619
620     if (!scope)
621         return result;
622
623     if (scope->hasTagName(HTMLNames::inputTag)) {
624         HTMLInputElement* input = static_cast<HTMLInputElement*>(scope);
625         if (input->isTelephoneField())
626             result.inputMethodHints |= Qt::ImhDialableCharactersOnly;
627         else if (input->isNumberField())
628             result.inputMethodHints |= Qt::ImhDigitsOnly;
629         else if (input->isEmailField()) {
630             result.inputMethodHints |= Qt::ImhEmailCharactersOnly;
631             result.inputMethodHints |= Qt::ImhNoAutoUppercase;
632         } else if (input->isURLField()) {
633             result.inputMethodHints |= Qt::ImhUrlCharactersOnly;
634             result.inputMethodHints |= Qt::ImhNoAutoUppercase;
635         } else if (input->isPasswordField()) {
636             // Set ImhHiddenText flag for password fields. The Qt platform
637             // is responsible for determining which widget will receive input
638             // method events for password fields.
639             result.inputMethodHints |= Qt::ImhHiddenText;
640             result.inputMethodHints |= Qt::ImhNoAutoUppercase;
641             result.inputMethodHints |= Qt::ImhNoPredictiveText;
642             result.inputMethodHints |= Qt::ImhSensitiveData;
643         }
644     }
645
646     if (selectionRoot)
647         result.editorRect = frame->view()->contentsToWindow(selectionRoot->getPixelSnappedRect());
648
649     RefPtr<Range> range;
650     if (result.hasComposition && (range = frame->editor()->compositionRange())) {
651         frame->editor()->getCompositionSelection(result.anchorPosition, result.cursorPosition);
652
653         result.compositionRect = frame->view()->contentsToWindow(range->boundingBox());
654     }
655
656     if (!result.hasComposition && !result.selectionIsNone && (range = frame->selection()->selection().firstRange())) {
657         TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
658         bool baseIsFirst = frame->selection()->selection().isBaseFirst();
659
660         result.cursorPosition = (baseIsFirst) ? location + length : location;
661         result.anchorPosition = (baseIsFirst) ? location : location + length;
662         result.selectedText = range->text();
663     }
664
665     if (range)
666         result.cursorRect = frame->view()->contentsToWindow(frame->editor()->firstRectForRange(range.get()));
667
668     // FIXME: We should only transfer innerText when it changes and do this on the UI side.
669     if (result.isContentEditable && !result.isInPasswordField) {
670         result.surroundingText = scope->innerText();
671         if (result.hasComposition) {
672             // The anchor is always the left position when they represent a composition.
673             result.surroundingText.remove(result.anchorPosition, result.cursorPosition - result.anchorPosition);
674         }
675     }
676 #endif
677
678     return result;
679 }
680
681 String WebPage::renderTreeExternalRepresentation() const
682 {
683     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
684 }
685
686 uint64_t WebPage::renderTreeSize() const
687 {
688     if (!m_page)
689         return 0;
690     return m_page->renderTreeSize().treeSize;
691 }
692
693 void WebPage::setPaintedObjectsCounterThreshold(uint64_t threshold)
694 {
695     if (!m_page)
696         return;
697     m_page->setRelevantRepaintedObjectsCounterThreshold(threshold);
698 }
699
700 void WebPage::setTracksRepaints(bool trackRepaints)
701 {
702     if (FrameView* view = mainFrameView())
703         view->setTracksRepaints(trackRepaints);
704 }
705
706 bool WebPage::isTrackingRepaints() const
707 {
708     if (FrameView* view = mainFrameView())
709         return view->isTrackingRepaints();
710
711     return false;
712 }
713
714 void WebPage::resetTrackedRepaints()
715 {
716     if (FrameView* view = mainFrameView())
717         view->resetTrackedRepaints();
718 }
719
720 PassRefPtr<ImmutableArray> WebPage::trackedRepaintRects()
721 {
722     FrameView* view = mainFrameView();
723     if (!view)
724         return ImmutableArray::create();
725
726     const Vector<IntRect>& rects = view->trackedRepaintRects();
727     size_t size = rects.size();
728     if (!size)
729         return ImmutableArray::create();
730
731     Vector<RefPtr<APIObject> > vector;
732     vector.reserveInitialCapacity(size);
733
734     for (size_t i = 0; i < size; ++i)
735         vector.uncheckedAppend(WebRect::create(toAPI(rects[i])));
736
737     return ImmutableArray::adopt(vector);
738 }
739
740 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
741 {
742     Frame* frame = m_page->focusController()->focusedOrMainFrame();
743     if (!frame)
744         return;
745     frame->editor()->command(commandName).execute(argument);
746 }
747
748 bool WebPage::isEditingCommandEnabled(const String& commandName)
749 {
750     Frame* frame = m_page->focusController()->focusedOrMainFrame();
751     if (!frame)
752         return false;
753     
754     Editor::Command command = frame->editor()->command(commandName);
755     return command.isSupported() && command.isEnabled();
756 }
757     
758 void WebPage::clearMainFrameName()
759 {
760     if (Frame* frame = mainFrame())
761         frame->tree()->clearName();
762 }
763
764 #if USE(ACCELERATED_COMPOSITING)
765 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
766 {
767     m_drawingArea->setRootCompositingLayer(layer);
768 }
769
770 void WebPage::exitAcceleratedCompositingMode()
771 {
772     m_drawingArea->setRootCompositingLayer(0);
773 }
774 #endif
775
776 void WebPage::close()
777 {
778     if (m_isClosed)
779         return;
780
781     m_isClosed = true;
782
783     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
784         WebProcess::shared().injectedBundle()->willDestroyPage(this);
785
786 #if ENABLE(INSPECTOR)
787     m_inspector = 0;
788 #endif
789 #if ENABLE(FULLSCREEN_API)
790     m_fullScreenManager = 0;
791 #endif
792
793     if (m_activePopupMenu) {
794         m_activePopupMenu->disconnectFromPage();
795         m_activePopupMenu = 0;
796     }
797
798     if (m_activeOpenPanelResultListener) {
799         m_activeOpenPanelResultListener->disconnectFromPage();
800         m_activeOpenPanelResultListener = 0;
801     }
802
803 #if ENABLE(INPUT_TYPE_COLOR)
804     if (m_activeColorChooser) {
805         m_activeColorChooser->disconnectFromPage();
806         m_activeColorChooser = 0;
807     }
808 #endif
809
810     m_sandboxExtensionTracker.invalidate();
811
812     m_underlayPage = nullptr;
813     m_printContext = nullptr;
814     m_mainFrame->coreFrame()->loader()->detachFromParent();
815     m_page = nullptr;
816     m_drawingArea = nullptr;
817
818     bool isRunningModal = m_isRunningModal;
819     m_isRunningModal = false;
820
821     // The WebPage can be destroyed by this call.
822     WebProcess::shared().removeWebPage(m_pageID);
823
824     if (isRunningModal)
825         WebProcess::shared().runLoop()->stop();
826 }
827
828 void WebPage::tryClose()
829 {
830     SendStopResponsivenessTimer stopper(this);
831
832     if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
833         send(Messages::WebPageProxy::StopResponsivenessTimer());
834         return;
835     }
836
837     send(Messages::WebPageProxy::ClosePage(true));
838 }
839
840 void WebPage::sendClose()
841 {
842     send(Messages::WebPageProxy::ClosePage(false));
843 }
844
845 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
846 {
847     loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
848 }
849
850 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
851 {
852     SendStopResponsivenessTimer stopper(this);
853
854     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
855     m_mainFrame->coreFrame()->loader()->load(request, false);
856 }
857
858 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
859 {
860     SendStopResponsivenessTimer stopper(this);
861
862     ResourceRequest request(baseURL);
863     SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
864     m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
865 }
866
867 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
868 {
869 #if ENABLE(TIZEN_LOAD_HTML_STRING_AS_UTF8)
870     CString html = htmlString.utf8();
871     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(html.data()), html.length());
872     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
873     loadData(sharedBuffer, "text/html", "utf-8", baseURL, KURL());
874 #else
875     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
876     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
877     loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
878 #endif
879 }
880
881 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
882 {
883     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
884     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
885     KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
886     loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
887 }
888
889 void WebPage::loadPlainTextString(const String& string)
890 {
891     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
892     loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
893 }
894
895 void WebPage::loadWebArchiveData(const CoreIPC::DataReference& webArchiveData)
896 {
897     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
898     loadData(sharedBuffer, "application/x-webarchive", "utf-16", blankURL(), KURL());
899 }
900
901 #if OS(TIZEN)
902 void WebPage::loadContentsbyMimeType(const CoreIPC::DataReference& contents, const String& mimeType, const String& encoding, const String& baseURL)
903 {
904     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(contents.data()), contents.size() * sizeof(uint8_t));
905     KURL baseKURL(WebCore::KURL(), baseURL);
906     loadData(sharedBuffer, mimeType, encoding, baseKURL, KURL());
907 }
908 #endif
909
910 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
911 {
912     Frame* frame = m_page->mainFrame();
913     if (!frame)
914         return;
915
916     RefPtr<Event> coreEvent;
917     if (event.type() != WebEvent::NoType)
918         coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
919
920     frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)), 
921         false, false, coreEvent.get(), 0, MaybeSendReferrer);
922 }
923
924 void WebPage::stopLoadingFrame(uint64_t frameID)
925 {
926     WebFrame* frame = WebProcess::shared().webFrame(frameID);
927     if (!frame)
928         return;
929
930     frame->coreFrame()->loader()->stopForUserCancel();
931 }
932
933 void WebPage::stopLoading()
934 {
935     SendStopResponsivenessTimer stopper(this);
936
937     m_mainFrame->coreFrame()->loader()->stopForUserCancel();
938 }
939
940 void WebPage::setDefersLoading(bool defersLoading)
941 {
942     m_page->setDefersLoading(defersLoading);
943 }
944
945 void WebPage::reload(bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
946 {
947     SendStopResponsivenessTimer stopper(this);
948
949     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
950     m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
951 }
952
953 void WebPage::goForward(uint64_t backForwardItemID)
954 {
955     SendStopResponsivenessTimer stopper(this);
956
957     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
958     ASSERT(item);
959     if (!item)
960         return;
961
962     m_page->goToItem(item, FrameLoadTypeForward);
963 }
964
965 void WebPage::goBack(uint64_t backForwardItemID)
966 {
967     SendStopResponsivenessTimer stopper(this);
968
969     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
970     ASSERT(item);
971     if (!item)
972         return;
973
974     m_page->goToItem(item, FrameLoadTypeBack);
975 }
976
977 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
978 {
979     SendStopResponsivenessTimer stopper(this);
980
981     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
982     ASSERT(item);
983     if (!item)
984         return;
985
986     m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
987 }
988
989 void WebPage::tryRestoreScrollPosition()
990 {
991     m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
992 }
993
994 void WebPage::layoutIfNeeded()
995 {
996     if (m_mainFrame->coreFrame()->view())
997         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
998
999     if (m_underlayPage) {
1000         if (FrameView *frameView = m_underlayPage->mainFrameView())
1001             frameView->updateLayoutAndStyleIfNeededRecursive();
1002     }
1003 }
1004
1005 void WebPage::setSize(const WebCore::IntSize& viewSize)
1006 {
1007     FrameView* view = m_page->mainFrame()->view();
1008
1009 #if USE(TILED_BACKING_STORE)
1010     // If we are resizing to content ignore external attempts.
1011     if (view->useFixedLayout())
1012         return;
1013 #endif
1014
1015     if (m_viewSize == viewSize)
1016         return;
1017
1018     view->resize(viewSize);
1019     view->setNeedsLayout();
1020     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
1021     
1022     m_viewSize = viewSize;
1023 }
1024
1025 #if USE(TILED_BACKING_STORE)
1026 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1027 {
1028     ASSERT(m_useFixedLayout);
1029
1030     m_page->mainFrame()->view()->setFixedVisibleContentRect(rect);
1031 }
1032
1033 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
1034 {
1035     ASSERT(m_useFixedLayout);
1036     ASSERT(!targetLayoutSize.isEmpty());
1037
1038     FrameView* view = m_page->mainFrame()->view();
1039
1040     view->setDelegatesScrolling(true);
1041     view->setUseFixedLayout(true);
1042     view->setPaintsEntireContents(true);
1043
1044     if (view->fixedLayoutSize() == targetLayoutSize)
1045         return;
1046
1047     m_page->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
1048     m_page->settings()->setFixedElementsLayoutRelativeToFrame(true);
1049     m_page->settings()->setFixedPositionCreatesStackingContext(true);
1050
1051     // Always reset even when empty. This also takes care of the relayout.
1052     setFixedLayoutSize(targetLayoutSize);
1053 }
1054
1055 void WebPage::resizeToContentsIfNeeded()
1056 {
1057     ASSERT(m_useFixedLayout);
1058
1059     FrameView* view = m_page->mainFrame()->view();
1060
1061     if (!view->useFixedLayout())
1062         return;
1063
1064     IntSize newSize = view->contentsSize().expandedTo(view->fixedLayoutSize());
1065
1066     if (newSize == m_viewSize)
1067         return;
1068
1069     m_viewSize = newSize;
1070     view->resize(newSize);
1071     view->setNeedsLayout();
1072 }
1073
1074 void WebPage::sendViewportAttributesChanged()
1075 {
1076     ASSERT(m_useFixedLayout);
1077
1078     // Viewport properties have no impact on zero sized fixed viewports.
1079     if (m_viewportSize.isEmpty())
1080         return;
1081
1082     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1083     Settings* settings = m_page->settings();
1084
1085 #if OS(TIZEN)
1086     // As android and iphone does, we set layout width to 980 for desktop content
1087     int minimumLayoutFallbackWidth = settings->layoutFallbackWidth();
1088 #else
1089     int minimumLayoutFallbackWidth = std::max(settings->layoutFallbackWidth(), m_viewportSize.width());
1090 #endif
1091
1092     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1093     int deviceWidth = (settings->deviceWidth() > 0) ? settings->deviceWidth() : m_viewportSize.width();
1094     int deviceHeight = (settings->deviceHeight() > 0) ? settings->deviceHeight() : m_viewportSize.height();
1095
1096     ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, m_page->deviceScaleFactor(), m_viewportSize);
1097     WebCore::restrictMinimumScaleFactorToViewportSize(attr, m_viewportSize);
1098     WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(attr);
1099
1100 #if ENABLE(TIZEN_VIEWPORT_META_TAG)
1101     // On WebProcess, JS runs before visible content rect is updated by UIProcess
1102     // In this case, JS returns incorrect inner size value because scale factor is not updated yet
1103     // So, we update fixed visible content rect at here.
1104     // FIXME: scale factor needs to be calculated and set fixed visible content rect
1105
1106     // if constrainsScrollingToContentEdge is true, scroll position will be adjusted with contents size.
1107     // disable this to avoid adjust scroll position on setFixedVisibleContentRect() because contents size is not fixed yet.
1108     bool constrainsScrollingToContentEdge = mainFrameView()->constrainsScrollingToContentEdge();
1109     mainFrameView()->setConstrainsScrollingToContentEdge(false);
1110
1111     FloatSize contentFixedSize = m_viewportSize;
1112     contentFixedSize.scale(1 / (attr.initialScale * attr.devicePixelRatio));
1113     mainFrameView()->setFixedVisibleContentRect(IntRect(mainFrameView()->scrollPosition(), roundedIntSize(contentFixedSize)));
1114
1115     // If viewport meta tag is not defined or initial scale factor is not defined,
1116     // initial scale factor can be defined by "Default View" setting of UIProcess.
1117     // Therefore we set initialScale as ValueAuto as WebKit opensource does, to handle it with setting on UIProcess.
1118     // You can find this implementation on WebKit bug.
1119     // https://bugs.webkit.org/show_bug.cgi?id=102392
1120     if (m_page->viewportArguments().type == ViewportArguments::Implicit
1121         || m_page->viewportArguments().initialScale == ViewportArguments::ValueAuto)
1122         attr.initialScale = ViewportArguments::ValueAuto;
1123 #endif
1124
1125     setResizesToContentsUsingLayoutSize(IntSize(static_cast<int>(attr.layoutSize.width()), static_cast<int>(attr.layoutSize.height())));
1126
1127 #if ENABLE(TIZEN_VIEWPORT_META_TAG)
1128     // recover constrainsScrollingToContentEdge
1129     mainFrameView()->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge);
1130 #endif
1131
1132     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1133 }
1134
1135 void WebPage::setViewportSize(const IntSize& size)
1136 {
1137     ASSERT(m_useFixedLayout);
1138
1139     if (m_viewportSize == size)
1140         return;
1141
1142      m_viewportSize = size;
1143
1144     sendViewportAttributesChanged();
1145 }
1146
1147 #endif
1148
1149 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1150 {
1151     Frame* frame = m_page->mainFrame();
1152
1153     IntPoint scrollPosition = frame->view()->scrollPosition();
1154     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
1155
1156     // If the current scroll position in a direction is the max scroll position 
1157     // we don't want to scroll at all.
1158     IntSize newScrollOffset;
1159     if (scrollPosition.x() < maximumScrollPosition.x())
1160         newScrollOffset.setWidth(scrollOffset.width());
1161     if (scrollPosition.y() < maximumScrollPosition.y())
1162         newScrollOffset.setHeight(scrollOffset.height());
1163
1164     if (newScrollOffset.isZero())
1165         return;
1166
1167     frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
1168 }
1169
1170 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1171 {
1172     GraphicsContextStateSaver stateSaver(graphicsContext);
1173     graphicsContext.clip(rect);
1174
1175     if (m_underlayPage) {
1176         m_underlayPage->drawRect(graphicsContext, rect);
1177
1178         graphicsContext.beginTransparencyLayer(1);
1179         m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1180         graphicsContext.endTransparencyLayer();
1181         return;
1182     }
1183
1184     m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1185 }
1186
1187 #if ENABLE(TIZEN_WEBKIT2_CONTEXT_MENU_TEXT_SELECTION_MODE)
1188 void WebPage::selectLink(WebCore::IntPoint positionForSelection, bool& result)
1189 {
1190     result = false;
1191     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1192     if (!frame)
1193         return;
1194
1195     FrameView* frameView = frame->view();
1196     if (!frameView)
1197         return;
1198
1199     HitTestResult hitTestResult = frame->eventHandler()->hitTestResultAtPoint(frameView->windowToContents(positionForSelection), false);
1200
1201     RefPtr<Range> range;
1202     Element* URLElement = hitTestResult.URLElement();
1203     if (URLElement) {
1204         for (Node* childNode = URLElement->firstChild(); childNode; childNode = childNode->traverseNextNode(URLElement)) {
1205             RenderObject* r = childNode->renderer();
1206             if (r && (r->isText() || r->isImage())) {
1207                 if (!range)
1208                     range = VisibleSelection::selectionFromContentsOfNode(childNode).toNormalizedRange();
1209                 else if (!hitTestResult.image()) {
1210                     RefPtr<Range> extendedRange = VisibleSelection::selectionFromContentsOfNode(childNode).toNormalizedRange();
1211                     range->setEnd(childNode, extendedRange->endOffset());
1212                 }
1213             }
1214         }
1215         if(!range)
1216             range = VisibleSelection::selectionFromContentsOfNode(URLElement).toNormalizedRange();
1217     } else
1218         range = VisibleSelection::selectionFromContentsOfNode(hitTestResult.innerNonSharedNode()).toNormalizedRange();
1219
1220     WebCore::FrameSelection* frameSelection = frame->selection();
1221     if (!frameSelection)
1222         return;
1223
1224     EAffinity affinity = frameSelection->affinity();
1225     frameSelection->setSelectedRange(range.get(), affinity, true);
1226
1227     if (frameSelection->isRange())
1228         result = true;
1229
1230     return;
1231 }
1232 #endif
1233
1234 #if ENABLE(TIZEN_ORIENTATION_EVENTS)
1235 void WebPage::sendOrientationChangeEvent(int newOrientation)
1236 {
1237     Frame* frame = m_mainFrame->coreFrame();
1238     if (!frame || frame->orientation() == newOrientation)
1239         return;
1240
1241     frame->sendOrientationChangeEvent(newOrientation);
1242     for (WebCore::Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1243         child->sendOrientationChangeEvent(newOrientation);
1244 }
1245 #endif
1246
1247 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
1248 {
1249     ASSERT(m_pageOverlay);
1250
1251     GraphicsContextStateSaver stateSaver(graphicsContext);
1252     graphicsContext.clip(rect);
1253     m_pageOverlay->drawRect(graphicsContext, rect);
1254 }
1255
1256 double WebPage::textZoomFactor() const
1257 {
1258     Frame* frame = m_mainFrame->coreFrame();
1259     if (!frame)
1260         return 1;
1261     return frame->textZoomFactor();
1262 }
1263
1264 void WebPage::setTextZoomFactor(double zoomFactor)
1265 {
1266     Frame* frame = m_mainFrame->coreFrame();
1267     if (!frame)
1268         return;
1269     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1270 }
1271
1272 double WebPage::pageZoomFactor() const
1273 {
1274     Frame* frame = m_mainFrame->coreFrame();
1275     if (!frame)
1276         return 1;
1277     return frame->pageZoomFactor();
1278 }
1279
1280 void WebPage::setPageZoomFactor(double zoomFactor)
1281 {
1282     Frame* frame = m_mainFrame->coreFrame();
1283     if (!frame)
1284         return;
1285     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1286 }
1287
1288 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1289 {
1290     Frame* frame = m_mainFrame->coreFrame();
1291     if (!frame)
1292         return;
1293     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1294 }
1295
1296 void WebPage::windowScreenDidChange(uint64_t displayID)
1297 {
1298     m_page->windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1299 }
1300
1301 void WebPage::setViewMode(Page::ViewMode mode)
1302 {
1303     m_page->setViewMode(mode);
1304 }
1305
1306 void WebPage::scalePage(double scale, const IntPoint& origin)
1307 {
1308     m_page->setPageScaleFactor(scale, origin);
1309
1310     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1311         (*it)->pageScaleFactorDidChange();
1312
1313     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1314 }
1315
1316 double WebPage::pageScaleFactor() const
1317 {
1318     return m_page->pageScaleFactor();
1319 }
1320
1321 void WebPage::setDeviceScaleFactor(float scaleFactor)
1322 {
1323     if (scaleFactor == m_page->deviceScaleFactor())
1324         return;
1325
1326     m_page->setDeviceScaleFactor(scaleFactor);
1327
1328     // Tell all our plug-in views that the device scale factor changed.
1329 #if PLATFORM(MAC)
1330     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1331         (*it)->setDeviceScaleFactor(scaleFactor);
1332 #endif
1333
1334     if (m_findController.isShowingOverlay()) {
1335         // We must have updated layout to get the selection rects right.
1336         layoutIfNeeded();
1337         m_findController.deviceScaleFactorDidChange();
1338     }
1339 }
1340
1341 float WebPage::deviceScaleFactor() const
1342 {
1343     return m_page->deviceScaleFactor();
1344 }
1345
1346 void WebPage::setUseFixedLayout(bool fixed)
1347 {
1348     m_useFixedLayout = fixed;
1349
1350     FrameView* view = mainFrameView();
1351     if (!view)
1352         return;
1353
1354     view->setUseFixedLayout(fixed);
1355     if (!fixed)
1356         setFixedLayoutSize(IntSize());
1357 }
1358
1359 void WebPage::setFixedLayoutSize(const IntSize& size)
1360 {
1361     FrameView* view = mainFrameView();
1362     if (!view || view->fixedLayoutSize() == size)
1363         return;
1364
1365     view->setFixedLayoutSize(size);
1366     // Do not force it until the first layout, this would then become our first layout prematurely.
1367     if (view->didFirstLayout())
1368         view->forceLayout();
1369 }
1370
1371 void WebPage::setPaginationMode(uint32_t mode)
1372 {
1373     Page::Pagination pagination = m_page->pagination();
1374     pagination.mode = static_cast<Page::Pagination::Mode>(mode);
1375     m_page->setPagination(pagination);
1376 }
1377
1378 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1379 {
1380     Page::Pagination pagination = m_page->pagination();
1381     pagination.behavesLikeColumns = behavesLikeColumns;
1382     m_page->setPagination(pagination);
1383 }
1384
1385 void WebPage::setPageLength(double pageLength)
1386 {
1387     Page::Pagination pagination = m_page->pagination();
1388     pagination.pageLength = pageLength;
1389     m_page->setPagination(pagination);
1390 }
1391
1392 void WebPage::setGapBetweenPages(double gap)
1393 {
1394     Page::Pagination pagination = m_page->pagination();
1395     pagination.gap = gap;
1396     m_page->setPagination(pagination);
1397 }
1398
1399 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
1400 {
1401     bool shouldFadeIn = true;
1402     
1403     if (m_pageOverlay) {
1404         m_pageOverlay->setPage(0);
1405
1406         if (pageOverlay) {
1407             // We're installing a page overlay when a page overlay is already active.
1408             // In this case we don't want to fade in the new overlay.
1409             shouldFadeIn = false;
1410         }
1411     }
1412
1413     m_pageOverlay = pageOverlay;
1414     m_pageOverlay->setPage(this);
1415
1416     if (shouldFadeIn)
1417         m_pageOverlay->startFadeInAnimation();
1418
1419     m_drawingArea->didInstallPageOverlay();
1420 #if PLATFORM(WIN)
1421     send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
1422 #endif
1423
1424     m_pageOverlay->setNeedsDisplay();
1425 }
1426
1427 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
1428 {
1429     if (pageOverlay != m_pageOverlay)
1430         return;
1431
1432     if (fadeOut) {
1433         m_pageOverlay->startFadeOutAnimation();
1434         return;
1435     }
1436
1437     m_pageOverlay->setPage(0);
1438     m_pageOverlay = nullptr;
1439
1440     m_drawingArea->didUninstallPageOverlay();
1441 #if PLATFORM(WIN)
1442     send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
1443 #endif
1444 }
1445
1446 #if PLATFORM(EFL) && OS(TIZEN)
1447 PassRefPtr<WebImage> WebPage::scaledSnapshotInViewCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1448 {
1449     FrameView* frameView = m_mainFrame->coreFrame()->view();
1450     if (!frameView)
1451         return 0;
1452
1453     IntSize size(ceil(rect.width() * scaleFactor), ceil(rect.height() * scaleFactor));
1454     RefPtr<WebImage> snapshot = WebImage::create(size, options);
1455     if (!snapshot->bitmap())
1456         return 0;
1457
1458     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1459     graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1460     graphicsContext->translate(-rect.x(), -rect.y());
1461
1462     frameView->updateLayoutAndStyleIfNeededRecursive();
1463
1464     PaintBehavior oldBehavior = frameView->paintBehavior();
1465     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1466     frameView->paint(graphicsContext.get(), rect);
1467     frameView->setPaintBehavior(oldBehavior);
1468
1469     return snapshot.release();
1470 }
1471
1472 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1473 {
1474     return scaledSnapshotInViewCoordinates(rect, 1, options);
1475 }
1476 #else
1477 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1478 {
1479     FrameView* frameView = m_mainFrame->coreFrame()->view();
1480     if (!frameView)
1481         return 0;
1482
1483     IntSize bitmapSize = rect.size();
1484     float deviceScaleFactor = corePage()->deviceScaleFactor();
1485     bitmapSize.scale(deviceScaleFactor);
1486
1487     RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, options);
1488     if (!snapshot->bitmap())
1489         return 0;
1490     
1491     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1492     graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1493     graphicsContext->translate(-rect.x(), -rect.y());
1494
1495     frameView->updateLayoutAndStyleIfNeededRecursive();
1496
1497     PaintBehavior oldBehavior = frameView->paintBehavior();
1498     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1499     frameView->paint(graphicsContext.get(), rect);
1500     frameView->setPaintBehavior(oldBehavior);
1501
1502     return snapshot.release();
1503 }
1504 #endif
1505
1506 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1507 {
1508     FrameView* frameView = m_mainFrame->coreFrame()->view();
1509     if (!frameView)
1510         return 0;
1511
1512     float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor();
1513     IntSize size(ceil(rect.width() * combinedScaleFactor), ceil(rect.height() * combinedScaleFactor));
1514     RefPtr<WebImage> snapshot = WebImage::create(size, options);
1515     if (!snapshot->bitmap())
1516         return 0;
1517
1518     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1519     graphicsContext->applyDeviceScaleFactor(combinedScaleFactor);
1520     graphicsContext->translate(-rect.x(), -rect.y());
1521
1522     frameView->updateLayoutAndStyleIfNeededRecursive();
1523
1524     PaintBehavior oldBehavior = frameView->paintBehavior();
1525     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1526     frameView->paintContents(graphicsContext.get(), rect);
1527     frameView->setPaintBehavior(oldBehavior);
1528
1529     return snapshot.release();
1530 }
1531
1532 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
1533 {
1534     return scaledSnapshotInDocumentCoordinates(rect, 1, options);
1535 }
1536
1537 void WebPage::pageDidScroll()
1538 {
1539     m_uiClient.pageDidScroll(this);
1540
1541     send(Messages::WebPageProxy::PageDidScroll());
1542 }
1543
1544 #if USE(TILED_BACKING_STORE)
1545 void WebPage::pageDidRequestScroll(const IntPoint& point)
1546 {
1547     send(Messages::WebPageProxy::PageDidRequestScroll(point));
1548 }
1549 #endif
1550
1551 #if ENABLE(TIZEN_WEBKIT2_HISTORICAL_RESTORE_VISIBLE_CONTENT_RECT)
1552 void WebPage::pageDidRequestRestoreVisibleContentRect(const IntPoint& point, float scale)
1553 {
1554     send(Messages::WebPageProxy::pageDidRequestRestoreVisibleContentRect(point, scale));
1555 }
1556 #endif
1557
1558 #if ENABLE(CONTEXT_MENUS)
1559 WebContextMenu* WebPage::contextMenu()
1560 {
1561     if (!m_contextMenu)
1562         m_contextMenu = WebContextMenu::create(this);
1563     return m_contextMenu.get();
1564 }
1565 #endif
1566
1567 // Events 
1568
1569 static const WebEvent* g_currentEvent = 0;
1570
1571 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1572 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1573 // platform events passed to the event handler code.
1574 const WebEvent* WebPage::currentEvent()
1575 {
1576     return g_currentEvent;
1577 }
1578
1579 class CurrentEvent {
1580 public:
1581     explicit CurrentEvent(const WebEvent& event)
1582         : m_previousCurrentEvent(g_currentEvent)
1583     {
1584         g_currentEvent = &event;
1585     }
1586
1587     ~CurrentEvent()
1588     {
1589         g_currentEvent = m_previousCurrentEvent;
1590     }
1591
1592 private:
1593     const WebEvent* m_previousCurrentEvent;
1594 };
1595
1596 #if ENABLE(CONTEXT_MENUS)
1597 static bool isContextClick(const PlatformMouseEvent& event)
1598 {
1599     if (event.button() == WebCore::RightButton)
1600         return true;
1601
1602 #if PLATFORM(MAC)
1603     // FIXME: this really should be about OSX-style UI, not about the Mac port
1604     if (event.button() == WebCore::LeftButton && event.ctrlKey())
1605         return true;
1606 #endif
1607
1608     return false;
1609 }
1610
1611 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1612 {
1613     IntPoint point = page->corePage()->mainFrame()->view()->windowToContents(platformMouseEvent.position());
1614     HitTestResult result = page->corePage()->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1615
1616     Frame* frame = page->corePage()->mainFrame();
1617 #if !ENABLE(TIZEN_CONTEXT_MENU_WEBKIT_2)
1618     if (result.innerNonSharedNode())
1619         frame = result.innerNonSharedNode()->document()->frame();
1620 #endif
1621
1622     bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1623     if (handled)
1624         page->contextMenu()->show();
1625
1626 #if ENABLE(TIZEN_DRAG_SUPPORT)
1627     if(result.isDragSupport()) {
1628         if (result.innerNonSharedNode())
1629             frame = result.innerNonSharedNode()->document()->frame();
1630
1631         PlatformMouseEvent event(frame->view()->windowToContents(platformMouseEvent.position()), platformMouseEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1632         frame->page()->dragController()->setPosition(event);
1633     }
1634 #endif
1635
1636     return handled;
1637 }
1638 #endif
1639
1640 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1641 {
1642     Frame* frame = page->corePage()->mainFrame();
1643     if (!frame->view())
1644         return false;
1645
1646     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1647
1648     switch (platformMouseEvent.type()) {
1649         case PlatformEvent::MousePressed: {
1650 #if ENABLE(CONTEXT_MENUS)
1651             if (isContextClick(platformMouseEvent))
1652                 page->corePage()->contextMenuController()->clearContextMenu();
1653 #endif
1654
1655 #if ENABLE(TIZEN_CONTEXT_MENU_WEBKIT_2)
1656             bool handled;
1657             if (!isContextClick(platformMouseEvent))
1658                 handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1659 #else
1660             bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1661 #endif
1662 #if ENABLE(CONTEXT_MENUS)
1663             if (isContextClick(platformMouseEvent))
1664                 handled = handleContextMenuEvent(platformMouseEvent, page);
1665 #endif
1666 #if PLATFORM(GTK)
1667             bool gtkMouseButtonPressHandled = page->handleMousePressedEvent(platformMouseEvent);
1668             handled = handled || gtkMouseButtonPressHandled;
1669 #endif
1670
1671             return handled;
1672         }
1673         case PlatformEvent::MouseReleased:
1674             return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1675         case PlatformEvent::MouseMoved:
1676             if (onlyUpdateScrollbars)
1677                 return frame->eventHandler()->passMouseMovedEventToScrollbars(platformMouseEvent);
1678             return frame->eventHandler()->mouseMoved(platformMouseEvent);
1679         default:
1680             ASSERT_NOT_REACHED();
1681             return false;
1682     }
1683 }
1684
1685 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1686 {
1687 #if ENABLE(CONTEXT_MENUS)
1688     // Don't try to handle any pending mouse events if a context menu is showing.
1689     if (m_isShowingContextMenu) {
1690         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1691         return;
1692     }
1693 #endif
1694
1695     bool handled = false;
1696     
1697     if (m_pageOverlay) {
1698         // Let the page overlay handle the event.
1699         handled = m_pageOverlay->mouseEvent(mouseEvent);
1700     }
1701
1702     if (!handled) {
1703         CurrentEvent currentEvent(mouseEvent);
1704
1705         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1706         // button is currently pressed. It is possible that neither of those things will be true since on 
1707         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1708         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1709         // efficient scrollbars-only version of the event.
1710         bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1711         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1712     }
1713
1714     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1715 }
1716
1717 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1718 {
1719     handled = m_pageOverlay && m_pageOverlay->mouseEvent(mouseEvent);
1720
1721     if (!handled) {
1722         CurrentEvent currentEvent(mouseEvent);
1723
1724         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1725         // button is currently pressed. It is possible that neither of those things will be true since on 
1726         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1727         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1728         // efficient scrollbars-only version of the event.
1729         bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1730         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1731     }
1732 }
1733
1734 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1735 {
1736     Frame* frame = page->mainFrame();
1737     if (!frame->view())
1738         return false;
1739
1740     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1741     return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1742 }
1743
1744 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1745 {
1746     CurrentEvent currentEvent(wheelEvent);
1747
1748     bool handled = handleWheelEvent(wheelEvent, m_page.get());
1749     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1750 }
1751
1752 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1753 {
1754     CurrentEvent currentEvent(wheelEvent);
1755
1756     handled = handleWheelEvent(wheelEvent, m_page.get());
1757 }
1758
1759 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1760 {
1761     if (!page->mainFrame()->view())
1762         return false;
1763
1764     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1765         return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1766     return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1767 }
1768
1769 #if ENABLE(TIZEN_ISF_PORT)
1770 void WebPage::keyEvent(const NativeWebKeyboardEvent& keyboardEvent)
1771 #else
1772 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1773 #endif
1774 {
1775     CurrentEvent currentEvent(keyboardEvent);
1776
1777     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1778     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1779     if (!handled)
1780         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1781
1782     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1783 }
1784
1785 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1786 {
1787     CurrentEvent currentEvent(keyboardEvent);
1788
1789     handled = handleKeyEvent(keyboardEvent, m_page.get());
1790     if (!handled)
1791         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1792 }
1793
1794 #if ENABLE(GESTURE_EVENTS)
1795 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1796 {
1797     Frame* frame = page->mainFrame();
1798     if (!frame->view())
1799         return false;
1800
1801     PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1802     return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1803 }
1804
1805 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1806 {
1807     CurrentEvent currentEvent(gestureEvent);
1808
1809     bool handled = handleGestureEvent(gestureEvent, m_page.get());
1810     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1811 }
1812 #endif
1813
1814 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1815 {
1816     bool isEnabled = false;
1817     int32_t state = 0;
1818     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1819     if (frame) {
1820         Editor::Command command = frame->editor()->command(commandName);
1821         state = command.state();
1822         isEnabled = command.isSupported() && command.isEnabled();
1823     }
1824
1825     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1826 }
1827
1828 void WebPage::executeEditCommand(const String& commandName)
1829 {
1830     executeEditingCommand(commandName, String());
1831 }
1832
1833 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1834 {
1835     const BackForwardListItemVector& list = sessionState.list();
1836     size_t size = list.size();
1837     uint64_t currentItemID = 0;
1838     for (size_t i = 0; i < size; ++i) {
1839         WebBackForwardListItem* webItem = list[i].get();
1840         DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1841         
1842         RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1843         if (!item) {
1844             LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1845             return 0;
1846         }
1847         
1848         if (i == sessionState.currentIndex())
1849             currentItemID = webItem->itemID();
1850         
1851         WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1852     }    
1853     ASSERT(currentItemID);
1854     return currentItemID;
1855 }
1856
1857 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1858 {
1859     if (uint64_t currentItemID = restoreSession(sessionState))
1860         goToBackForwardItem(currentItemID);
1861 }
1862
1863 #if ENABLE(TOUCH_EVENTS)
1864 #if PLATFORM(QT)
1865 void WebPage::highlightPotentialActivation(const IntPoint& point, const IntSize& area)
1866 {
1867     if (point == IntPoint::zero()) {
1868         // An empty point deactivates the highlighting.
1869         tapHighlightController().hideHighlight();
1870     } else {
1871         Frame* mainframe = m_page->mainFrame();
1872         Node* activationNode = 0;
1873         Node* adjustedNode = 0;
1874         IntPoint adjustedPoint;
1875
1876 #if ENABLE(TOUCH_ADJUSTMENT)
1877         if (!mainframe->eventHandler()->bestClickableNodeForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), adjustedPoint, adjustedNode))
1878             return;
1879
1880 #else
1881         HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1882         adjustedNode = result.innerNode();
1883 #endif
1884         // Find the node to highlight. This is not the same as the node responding the tap gesture, because many
1885         // pages has a global click handler and we do not want to highlight the body.
1886         // Instead find the enclosing link or focusable element, or the last enclosing inline element.
1887         for (Node* node = adjustedNode; node; node = node->parentOrHostNode()) {
1888             if (node->isMouseFocusable() || node->isLink()) {
1889                 activationNode = node;
1890                 break;
1891             }
1892             if (node->renderer() && node->renderer()->isInline())
1893                 activationNode = node;
1894             else if (activationNode)
1895                 break;
1896         }
1897
1898         if (activationNode)
1899             tapHighlightController().highlight(activationNode);
1900     }
1901 }
1902 #endif
1903
1904 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1905 {
1906     Frame* frame = page->mainFrame();
1907     if (!frame->view())
1908         return false;
1909
1910     return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1911 }
1912
1913 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1914 {
1915     CurrentEvent currentEvent(touchEvent);
1916
1917     bool handled = handleTouchEvent(touchEvent, m_page.get());
1918
1919 #if ENABLE(TIZEN_CSS_OVERFLOW_SCROLL_ACCELERATION)
1920     static bool checkOverflow = false;
1921     if (touchEvent.type() == WebEvent::TouchStart && touchEvent.touchPoints().size() == 1) {
1922         checkOverflow = true;
1923     } else if (checkOverflow && touchEvent.type() == WebEvent::TouchMove && touchEvent.touchPoints().size() == 1) {
1924         bool pressed = false;
1925         uint32_t id = 0;
1926 #if ENABLE(TIZEN_CSS_OVERFLOW_SCROLL_ACCELERATION_ON_UI_SIDE)
1927         setPressedNodeAtPoint(touchEvent.touchPoints()[0].position(), true, pressed, id);
1928 #else
1929         setPressedNodeAtPoint(touchEvent.touchPoints()[0].position(), false, pressed, id);
1930 #endif
1931         send(Messages::WebPageProxy::SetOverflowResult(pressed, id));
1932         checkOverflow = false;
1933     }
1934 #endif
1935     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1936 }
1937
1938 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1939 {
1940     CurrentEvent currentEvent(touchEvent);
1941     handled = handleTouchEvent(touchEvent, m_page.get());
1942 }
1943 #endif
1944
1945 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1946 {
1947     page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1948 }
1949
1950 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1951 {
1952     page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1953 }
1954
1955 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1956 {
1957     scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1958 }
1959
1960 void WebPage::centerSelectionInVisibleArea()
1961 {
1962     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1963     if (!frame)
1964         return;
1965     
1966     frame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
1967     m_findController.showFindIndicatorInSelection();
1968 }
1969
1970 void WebPage::setActive(bool isActive)
1971 {
1972     m_page->focusController()->setActive(isActive);
1973
1974 #if PLATFORM(MAC)    
1975     // Tell all our plug-in views that the window focus changed.
1976     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1977         (*it)->setWindowIsFocused(isActive);
1978 #endif
1979 }
1980
1981 void WebPage::setDrawsBackground(bool drawsBackground)
1982 {
1983     if (m_drawsBackground == drawsBackground)
1984         return;
1985
1986     m_drawsBackground = drawsBackground;
1987
1988     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1989         if (FrameView* view = coreFrame->view())
1990             view->setTransparent(!drawsBackground);
1991     }
1992
1993     m_drawingArea->pageBackgroundTransparencyChanged();
1994     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1995 }
1996
1997 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1998 {
1999     if (m_drawsTransparentBackground == drawsTransparentBackground)
2000         return;
2001
2002     m_drawsTransparentBackground = drawsTransparentBackground;
2003
2004     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2005     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2006         if (FrameView* view = coreFrame->view())
2007             view->setBaseBackgroundColor(backgroundColor);
2008     }
2009
2010     m_drawingArea->pageBackgroundTransparencyChanged();
2011     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2012 }
2013
2014 void WebPage::viewWillStartLiveResize()
2015 {
2016     if (!m_page)
2017         return;
2018
2019     // FIXME: This should propagate to all ScrollableAreas.
2020     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
2021         if (FrameView* view = frame->view())
2022             view->willStartLiveResize();
2023     }
2024 }
2025
2026 void WebPage::viewWillEndLiveResize()
2027 {
2028     if (!m_page)
2029         return;
2030
2031     // FIXME: This should propagate to all ScrollableAreas.
2032     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
2033         if (FrameView* view = frame->view())
2034             view->willEndLiveResize();
2035     }
2036 }
2037
2038 void WebPage::setFocused(bool isFocused)
2039 {
2040     m_page->focusController()->setFocused(isFocused);
2041 }
2042
2043 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2044 {
2045     if (!m_page || !m_page->focusController())
2046         return;
2047
2048     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2049     frame->document()->setFocusedNode(0);
2050
2051     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2052         PlatformKeyboardEvent platformEvent(platform(event));
2053         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2054         m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame->document()->defaultView()).get());
2055         return;
2056     }
2057
2058     m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2059 }
2060
2061 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2062 {
2063     if (m_windowResizerSize == windowResizerSize)
2064         return;
2065
2066     m_windowResizerSize = windowResizerSize;
2067
2068     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2069         FrameView* view = coreFrame->view();
2070         if (view)
2071             view->windowResizerRectChanged();
2072     }
2073 }
2074
2075 void WebPage::setCanStartMediaTimerFired()
2076 {
2077     if (m_page)
2078         m_page->setCanStartMedia(true);
2079 }
2080
2081 void WebPage::setIsInWindow(bool isInWindow)
2082 {
2083     if (!isInWindow) {
2084         m_setCanStartMediaTimer.stop();
2085         m_page->setCanStartMedia(false);
2086         m_page->willMoveOffscreen();
2087     } else {
2088         // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
2089         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2090         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2091         m_setCanStartMediaTimer.startOneShot(0);
2092         m_page->didMoveOnscreen();
2093     }
2094 }
2095
2096 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2097 {
2098     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2099     if (!frame)
2100         return;
2101     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2102 }
2103
2104 void WebPage::show()
2105 {
2106     send(Messages::WebPageProxy::ShowPage());
2107 }
2108
2109 void WebPage::setUserAgent(const String& userAgent)
2110 {
2111     m_userAgent = userAgent;
2112 }
2113 #if ENABLE(TIZEN_CUSTOM_HEADERS)
2114 void WebPage::addCustomHeader(const String& name, const String& value)
2115 {
2116     m_customHeaders.add(name, value);
2117 }
2118
2119 void WebPage::removeCustomHeader(const String& name)
2120 {
2121     m_customHeaders.remove(name);
2122 }
2123
2124 void WebPage::clearCustomHeaders()
2125 {
2126     m_customHeaders.clear();
2127 }
2128
2129 WebCore::HTTPHeaderMap WebPage::customHeaders()
2130 {
2131     return m_customHeaders;
2132 }
2133 #endif
2134
2135 void WebPage::suspendActiveDOMObjectsAndAnimations()
2136 {
2137     m_page->suspendActiveDOMObjectsAndAnimations();
2138 }
2139
2140 void WebPage::resumeActiveDOMObjectsAndAnimations()
2141 {
2142     m_page->resumeActiveDOMObjectsAndAnimations();
2143
2144     // We need to repaint on resume to kickstart animated painting again.
2145     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2146 }
2147
2148 IntPoint WebPage::screenToWindow(const IntPoint& point)
2149 {
2150     IntPoint windowPoint;
2151     sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
2152     return windowPoint;
2153 }
2154     
2155 IntRect WebPage::windowToScreen(const IntRect& rect)
2156 {
2157     IntRect screenRect;
2158     sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
2159     return screenRect;
2160 }
2161
2162 IntRect WebPage::windowResizerRect() const
2163 {
2164     if (m_windowResizerSize.isEmpty())
2165         return IntRect();
2166
2167     IntSize frameViewSize;
2168     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2169         if (FrameView* view = coreFrame->view())
2170             frameViewSize = view->size();
2171     }
2172
2173     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
2174                    m_windowResizerSize.width(), m_windowResizerSize.height());
2175 }
2176
2177 KeyboardUIMode WebPage::keyboardUIMode()
2178 {
2179     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2180     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2181 }
2182
2183 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2184 {
2185     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2186     // disappear during script execution.
2187
2188     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2189     // long enough for the DataReference to be encoded by the sent message.
2190     RefPtr<SerializedScriptValue> serializedResultValue;
2191     CoreIPC::DataReference dataReference;
2192
2193     JSLockHolder lock(JSDOMWindow::commonJSGlobalData());
2194     if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
2195         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2196             dataReference = serializedResultValue->data();
2197     }
2198
2199     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2200 }
2201
2202 void WebPage::getContentsAsString(uint64_t callbackID)
2203 {
2204     String resultString = m_mainFrame->contentsAsString();
2205     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2206 }
2207
2208 #if ENABLE(MHTML)
2209 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2210 {
2211     CoreIPC::DataReference dataReference;
2212
2213     RefPtr<SharedBuffer> buffer = useBinaryEncoding
2214         ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2215         : MHTMLArchive::generateMHTMLData(m_page.get());
2216
2217     if (buffer)
2218         dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2219
2220     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2221 }
2222 #endif
2223
2224 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2225 {
2226     String resultString = renderTreeExternalRepresentation();
2227     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2228 }
2229
2230 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2231 {
2232     String resultString = m_mainFrame->selectionAsString();
2233     if (resultString.isEmpty())
2234         resultString = m_mainFrame->contentsAsString();
2235     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2236 }
2237
2238 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2239 {
2240     String resultString;
2241     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2242        resultString = frame->source();
2243
2244     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2245 }
2246
2247 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2248 {
2249     CoreIPC::DataReference dataReference;
2250
2251     RefPtr<SharedBuffer> buffer;
2252     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2253         if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
2254             if ((buffer = loader->mainResourceData()))
2255                 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2256         }
2257     }
2258
2259     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2260 }
2261
2262 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
2263 {
2264     DocumentLoader* loader = frame->loader()->documentLoader();
2265     if (!loader)
2266         return 0;
2267
2268     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2269     if (!subresource)
2270         return 0;
2271
2272     return subresource->data();
2273 }
2274
2275 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2276 {
2277     CoreIPC::DataReference dataReference;
2278     KURL resourceURL(KURL(), resourceURLString);
2279
2280     RefPtr<SharedBuffer> buffer;
2281     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2282         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2283         if (!buffer) {
2284             // Try to get the resource data from the cache.
2285             buffer = cachedResponseDataForURL(resourceURL);
2286         }
2287
2288         if (buffer)
2289             dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2290     }
2291
2292     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2293 }
2294
2295 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2296 {
2297     CoreIPC::DataReference dataReference;
2298
2299 #if PLATFORM(MAC) || PLATFORM(WIN)
2300     RetainPtr<CFDataRef> data;
2301     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2302         if ((data = frame->webArchiveData(0, 0)))
2303             dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2304     }
2305 #endif
2306
2307     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2308 }
2309
2310 void WebPage::forceRepaintWithoutCallback()
2311 {
2312     m_drawingArea->forceRepaint();
2313 }
2314
2315 void WebPage::forceRepaint(uint64_t callbackID)
2316 {
2317     if (m_drawingArea->forceRepaintAsync(callbackID))
2318         return;
2319
2320     forceRepaintWithoutCallback();
2321     send(Messages::WebPageProxy::VoidCallback(callbackID));
2322 }
2323
2324 #if ENABLE(WEB_INTENTS)
2325 void WebPage::deliverIntentToFrame(uint64_t frameID, const IntentData& intentData)
2326 {
2327     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2328     if (!frame)
2329         return;
2330
2331     frame->deliverIntent(intentData);
2332 }
2333 #endif
2334
2335 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2336 {
2337     WebPreferencesStore::removeTestRunnerOverrides();
2338     updatePreferences(store);
2339 }
2340
2341 void WebPage::updatePreferences(const WebPreferencesStore& store)
2342 {
2343     Settings* settings = m_page->settings();
2344
2345     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2346
2347     // FIXME: This should be generated from macro expansion for all preferences,
2348     // but we currently don't match the naming of WebCore exactly so we are
2349     // handrolling the boolean and integer preferences until that is fixed.
2350
2351 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2352
2353     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2354
2355 #undef INITIALIZE_SETTINGS
2356
2357     settings->setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2358     settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2359     settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2360     settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2361     settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2362     settings->setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
2363     settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2364     settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2365     settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2366     settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2367     settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2368     settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2369     settings->setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2370     settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2371     settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2372     settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2373     settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2374     settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2375 #if ENABLE(WEB_ARCHIVE)
2376     settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2377 #endif
2378     settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2379     settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2380     settings->setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2381     settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2382     settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2383     settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2384     settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2385     settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2386     settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2387     settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2388     settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2389
2390     settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2391     settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2392     settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2393     settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2394     settings->setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2395     settings->setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2396     settings->setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2397     settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2398     settings->setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2399
2400     settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2401     settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2402     settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2403     settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2404     settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2405     settings->setCSSCustomFilterEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCustomFilterEnabledKey()));
2406     settings->setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2407     settings->setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2408     settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2409     settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2410     settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2411     settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2412     settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2413     settings->setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2414     settings->setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2415
2416     // <rdar://problem/10697417>: It is necessary to force compositing when accelerate drawing
2417     // is enabled on Mac so that scrollbars are always in their own layers.
2418 #if PLATFORM(MAC)
2419     if (settings->acceleratedDrawingEnabled())
2420         settings->setForceCompositingMode(LayerTreeHost::supportsAcceleratedCompositing());
2421     else
2422 #endif
2423         settings->setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2424
2425 #if ENABLE(TIZEN_RUNTIME_BACKEND_SELECTION)
2426     if (!settings->acceleratedCompositingEnabled()) {
2427         settings->setAcceleratedCompositingFor3DTransformsEnabled(false);
2428         settings->setAcceleratedCompositingForVideoEnabled(false);
2429         settings->setAcceleratedCompositingForPluginsEnabled(false);
2430         settings->setAcceleratedCompositingForCanvasEnabled(false);
2431         settings->setAcceleratedCompositingForAnimationEnabled(false);
2432     }
2433 #endif
2434 #if ENABLE(TIZEN_WEBKIT2_MEMORY_SAVING_MODE)
2435     settings->setMemorySavingMode(WebProcess::shared().memorySavingModeEnabled());
2436 #endif
2437
2438 #if ENABLE(SQL_DATABASE)
2439     AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2440 #endif
2441
2442 #if ENABLE(FULLSCREEN_API)
2443     settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2444 #endif
2445
2446 #if ENABLE(TIZEN_WEBKIT2_ASYNCHRONOUS_SPELLCHECKING)
2447     settings->setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2448 #endif
2449     settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
2450
2451 #if USE(AVFOUNDATION)
2452     settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2453 #endif
2454
2455 #if ENABLE(WEB_AUDIO)
2456     settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2457 #endif
2458
2459     settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2460     settings->setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2461     settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2462     settings->setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2463     settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2464
2465 #if ENABLE(VIDEO_TRACK)
2466     settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2467     settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2468     settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2469 #endif
2470
2471 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2472     settings->setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2473 #endif
2474
2475     settings->setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2476
2477 #if ENABLE(TIZEN_INDEXED_DATABASE)
2478     m_page->group().groupSettings()->setIndexedDBDatabasePath(WebProcess::shared().indexedDatabaseDirectory());
2479     m_page->group().groupSettings()->setIndexedDBQuotaBytes(0x6400000); //100M
2480 #endif
2481
2482     settings->setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2483
2484 #if ENABLE(TEXT_AUTOSIZING)
2485     settings->setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2486 #endif
2487
2488 #if ENABLE(TIZEN_FILE_SYSTEM)
2489     m_page->group().groupSettings()->setLocalFileSystemQuotaBytes(0x6400000); //100M
2490 #endif
2491
2492 #if ENABLE(TIZEN_WORKERS)
2493     m_page->group().groupSettings()->setAllowUniversalAccessFromFileURLs(settings->allowUniversalAccessFromFileURLs());
2494 #endif
2495
2496     platformPreferencesDidChange(store);
2497
2498     if (m_drawingArea)
2499         m_drawingArea->updatePreferences();
2500 }
2501
2502 #if ENABLE(INSPECTOR)
2503 WebInspector* WebPage::inspector()
2504 {
2505     if (m_isClosed)
2506         return 0;
2507     if (!m_inspector)
2508         m_inspector = WebInspector::create(this, m_inspectorClient);
2509     return m_inspector.get();
2510 }
2511 #endif
2512
2513 #if ENABLE(FULLSCREEN_API)
2514 WebFullScreenManager* WebPage::fullScreenManager()
2515 {
2516     if (!m_fullScreenManager)
2517         m_fullScreenManager = WebFullScreenManager::create(this);
2518     return m_fullScreenManager.get();
2519 }
2520 #endif
2521
2522 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2523 {
2524     if (m_notificationPermissionRequestManager)
2525         return m_notificationPermissionRequestManager.get();
2526
2527     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2528     return m_notificationPermissionRequestManager.get();
2529 }
2530
2531 #if ENABLE(TIZEN_MEDIA_STREAM)
2532 UserMediaPermissionRequestManager* WebPage::userMediaPermissionRequestManager()
2533 {
2534     if (m_userMediaPermissionRequestManager)
2535         return m_userMediaPermissionRequestManager.get();
2536
2537     m_userMediaPermissionRequestManager = UserMediaPermissionRequestManager::create(this);
2538     return m_userMediaPermissionRequestManager.get();
2539 }
2540 #endif
2541
2542 #if !PLATFORM(GTK) && !PLATFORM(MAC)
2543 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2544 {
2545     Node* node = evt->target()->toNode();
2546     ASSERT(node);
2547     Frame* frame = node->document()->frame();
2548     ASSERT(frame);
2549
2550     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2551     if (!keyEvent)
2552         return false;
2553
2554     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
2555
2556     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2557         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2558         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2559         // (e.g. Tab that inserts a Tab character, or Enter).
2560         return !command.isTextInsertion() && command.execute(evt);
2561     }
2562
2563     if (command.execute(evt))
2564         return true;
2565
2566     // Don't allow text insertion for nodes that cannot edit.
2567     if (!frame->editor()->canEdit())
2568         return false;
2569
2570     // Don't insert null or control characters as they can result in unexpected behaviour
2571     if (evt->charCode() < ' ')
2572         return false;
2573
2574     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
2575 }
2576 #endif
2577
2578 #if ENABLE(DRAG_SUPPORT)
2579
2580 #if PLATFORM(WIN)
2581 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
2582 {
2583     if (!m_page) {
2584         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2585         return;
2586     }
2587
2588     DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2589     switch (action) {
2590     case DragControllerActionEntered:
2591         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2592         break;
2593
2594     case DragControllerActionUpdated:
2595         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2596         break;
2597         
2598     case DragControllerActionExited:
2599         m_page->dragController()->dragExited(&dragData);
2600         break;
2601         
2602     case DragControllerActionPerformDrag:
2603         m_page->dragController()->performDrag(&dragData);
2604         break;
2605         
2606     default:
2607         ASSERT_NOT_REACHED();
2608     }
2609 }
2610
2611 #elif PLATFORM(QT) || PLATFORM(GTK) || ENABLE(TIZEN_DRAG_SUPPORT)
2612 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2613 {
2614     if (!m_page) {
2615         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2616 #if PLATFORM(QT)
2617         QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2618         delete data;
2619 #elif PLATFORM(GTK)
2620         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2621         data->deref();
2622 #endif
2623 #if ENABLE(TIZEN_DRAG_SUPPORT)
2624         DataObjectTizen* data = const_cast<DataObjectTizen*>(dragData.platformData());
2625         data->deref();
2626 #endif
2627         return;
2628     }
2629
2630     switch (action) {
2631     case DragControllerActionEntered:
2632         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2633         break;
2634
2635     case DragControllerActionUpdated:
2636         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2637         break;
2638
2639     case DragControllerActionExited:
2640         m_page->dragController()->dragExited(&dragData);
2641         break;
2642
2643     case DragControllerActionPerformDrag: {
2644         m_page->dragController()->performDrag(&dragData);
2645         break;
2646     }
2647
2648     default:
2649         ASSERT_NOT_REACHED();
2650     }
2651     // DragData does not delete its platformData so we need to do that here.
2652 #if PLATFORM(QT)
2653     QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2654     delete data;
2655 #elif PLATFORM(GTK)
2656     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2657     data->deref();
2658 #endif
2659 #if ENABLE(TIZEN_DRAG_SUPPORT)
2660     DataObjectTizen* data = const_cast<DataObjectTizen*>(dragData.platformData());
2661     data->deref();
2662 #endif
2663 }
2664
2665 #else
2666 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsHandleArray)
2667 {
2668     if (!m_page) {
2669         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2670         return;
2671     }
2672
2673     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2674     switch (action) {
2675     case DragControllerActionEntered:
2676         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2677         break;
2678
2679     case DragControllerActionUpdated:
2680         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2681         break;
2682         
2683     case DragControllerActionExited:
2684         m_page->dragController()->dragExited(&dragData);
2685         break;
2686         
2687     case DragControllerActionPerformDrag: {
2688         ASSERT(!m_pendingDropSandboxExtension);
2689
2690         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2691         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2692             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2693                 m_pendingDropExtensionsForFileUpload.append(extension);
2694         }
2695
2696         m_page->dragController()->performDrag(&dragData);
2697
2698         // If we started loading a local file, the sandbox extension tracker would have adopted this
2699         // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2700         if (m_pendingDropSandboxExtension) {
2701             m_pendingDropSandboxExtension->invalidate();
2702             m_pendingDropSandboxExtension = nullptr;
2703         }
2704         for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2705             m_pendingDropExtensionsForFileUpload[i]->invalidate();
2706
2707         m_pendingDropExtensionsForFileUpload.clear();
2708         break;
2709     }
2710
2711     default:
2712         ASSERT_NOT_REACHED();
2713     }
2714 }
2715 #endif
2716
2717 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2718 {
2719     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2720     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2721
2722     m_page->dragController()->dragEnded();
2723     FrameView* view = m_page->mainFrame()->view();
2724     if (!view)
2725         return;
2726     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2727     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2728     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2729 }
2730
2731 void WebPage::willPerformLoadDragDestinationAction()
2732 {
2733     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2734 }
2735
2736 void WebPage::mayPerformUploadDragDestinationAction()
2737 {
2738     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2739         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2740     m_pendingDropExtensionsForFileUpload.clear();
2741 }
2742     
2743 #endif // ENABLE(DRAG_SUPPORT)
2744
2745 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2746 {
2747     return m_undoStepMap.get(stepID).get();
2748 }
2749
2750 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2751 {
2752     m_undoStepMap.set(stepID, entry);
2753 }
2754
2755 void WebPage::removeWebEditCommand(uint64_t stepID)
2756 {
2757     m_undoStepMap.remove(stepID);
2758 }
2759
2760 void WebPage::unapplyEditCommand(uint64_t stepID)
2761 {
2762     WebUndoStep* step = webUndoStep(stepID);
2763     if (!step)
2764         return;
2765
2766     step->step()->unapply();
2767 }
2768
2769 void WebPage::reapplyEditCommand(uint64_t stepID)
2770 {
2771     WebUndoStep* step = webUndoStep(stepID);
2772     if (!step)
2773         return;
2774
2775     m_isInRedo = true;
2776     step->step()->reapply();
2777     m_isInRedo = false;
2778 }
2779
2780 void WebPage::didRemoveEditCommand(uint64_t commandID)
2781 {
2782     removeWebEditCommand(commandID);
2783 }
2784
2785 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2786 {
2787     m_activePopupMenu = menu;
2788 }
2789
2790 #if ENABLE(INPUT_TYPE_COLOR)
2791 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2792 {
2793     m_activeColorChooser = colorChooser;
2794 }
2795
2796 void WebPage::didEndColorChooser()
2797 {
2798     m_activeColorChooser->didEndChooser();
2799 }
2800
2801 void WebPage::didChooseColor(const WebCore::Color& color)
2802 {
2803     m_activeColorChooser->didChooseColor(color);
2804 }
2805 #endif
2806
2807 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2808 {
2809     m_activeOpenPanelResultListener = openPanelResultListener;
2810 }
2811
2812 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2813 {
2814     return m_page->findString(target, options);
2815 }
2816
2817 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2818 {
2819     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2820 }
2821
2822 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2823 {
2824     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2825 }
2826
2827 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2828 {
2829     m_findController.getImageForFindMatch(matchIndex);
2830 }
2831
2832 void WebPage::selectFindMatch(uint32_t matchIndex)
2833 {
2834     m_findController.selectFindMatch(matchIndex);
2835 }
2836
2837 void WebPage::hideFindUI()
2838 {
2839     m_findController.hideFindUI();
2840 }
2841
2842 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2843 {
2844     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2845 }
2846
2847 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2848 {
2849     changeSelectedIndex(newIndex);
2850
2851     // Since applictions on tizen may provide a way to select item more than one time,
2852     // we need to keep the active popup menu to allow repetitive selection.
2853 #if !OS(TIZEN)
2854     m_activePopupMenu = 0;
2855 #endif
2856 }
2857
2858 void WebPage::changeSelectedIndex(int32_t index)
2859 {
2860     if (!m_activePopupMenu)
2861         return;
2862
2863     m_activePopupMenu->didChangeSelectedIndex(index);
2864 }
2865
2866 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2867 {
2868     if (!m_activeOpenPanelResultListener)
2869         return;
2870
2871     m_activeOpenPanelResultListener->didChooseFiles(files);
2872     m_activeOpenPanelResultListener = 0;
2873 }
2874
2875 void WebPage::didCancelForOpenPanel()
2876 {
2877     m_activeOpenPanelResultListener = 0;
2878 }
2879
2880 #if OS(TIZEN)
2881 void WebPage::cancelForOpenPanel()
2882 {
2883     if (m_activeOpenPanelResultListener) {
2884         m_activeOpenPanelResultListener->disconnectFromPage();
2885         m_activeOpenPanelResultListener = 0;
2886     }
2887 }
2888 #endif
2889
2890 #if ENABLE(WEB_PROCESS_SANDBOX)
2891 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2892 {
2893     SandboxExtension::create(handle)->consumePermanently();
2894 }
2895 #endif
2896
2897 #if ENABLE(GEOLOCATION)
2898 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2899 {
2900     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2901 }
2902 #endif
2903
2904 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2905 {
2906     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2907 }
2908
2909 #if ENABLE(TIZEN_MEDIA_STREAM)
2910 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed)
2911 {
2912     userMediaPermissionRequestManager()->didReceiveUserMediaPermissionDecision(userMediaID, allowed);
2913 }
2914 #endif
2915
2916 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2917 {
2918     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2919     frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2920 }
2921
2922 void WebPage::changeSpellingToWord(const String& word)
2923 {
2924     replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2925 }
2926
2927 void WebPage::unmarkAllMisspellings()
2928 {
2929     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2930         if (Document* document = frame->document())
2931             document->markers()->removeMarkers(DocumentMarker::Spelling);
2932     }
2933 }
2934
2935 void WebPage::unmarkAllBadGrammar()
2936 {
2937     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2938         if (Document* document = frame->document())
2939             document->markers()->removeMarkers(DocumentMarker::Grammar);
2940     }
2941 }
2942
2943 #if USE(APPKIT)
2944 void WebPage::uppercaseWord()
2945 {
2946     m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2947 }
2948
2949 void WebPage::lowercaseWord()
2950 {
2951     m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2952 }
2953
2954 void WebPage::capitalizeWord()
2955 {
2956     m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2957 }
2958 #endif
2959     
2960 void WebPage::setTextForActivePopupMenu(int32_t index)
2961 {
2962     if (!m_activePopupMenu)
2963         return;
2964
2965     m_activePopupMenu->setTextForIndex(index);
2966 }
2967
2968 #if PLATFORM(GTK)
2969 void WebPage::failedToShowPopupMenu()
2970 {
2971     if (!m_activePopupMenu)
2972         return;
2973
2974     m_activePopupMenu->client()->popupDidHide();
2975 }
2976 #endif
2977
2978 #if ENABLE(CONTEXT_MENUS)
2979 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2980 {
2981     if (!m_contextMenu)
2982         return;
2983
2984     m_contextMenu->itemSelected(item);
2985     m_contextMenu = 0;
2986 }
2987 #endif
2988
2989 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
2990 {
2991     bool selectReplacement = true;
2992     bool smartReplace = false;
2993     return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
2994 }
2995
2996 void WebPage::clearSelection()
2997 {
2998     m_page->focusController()->focusedOrMainFrame()->selection()->clear();
2999 }
3000
3001 bool WebPage::mainFrameHasCustomRepresentation() const
3002 {
3003     if (Frame* frame = mainFrame())
3004         return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
3005
3006     return false;
3007 }
3008
3009 void WebPage::didChangeScrollOffsetForMainFrame()
3010 {
3011     Frame* frame = m_page->mainFrame();
3012     IntPoint scrollPosition = frame->view()->scrollPosition();
3013     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
3014     IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
3015
3016 #if PLATFORM(EFL) && OS(TIZEN)
3017     send(Messages::WebPageProxy::DidChangeScrollPositionForMainFrame(scrollPosition));
3018 #endif
3019
3020     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3021     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3022
3023     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
3024         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
3025         
3026         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3027         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3028     }
3029 }
3030
3031 void WebPage::mainFrameDidLayout()
3032 {
3033     unsigned pageCount = m_page->pageCount();
3034     if (pageCount != m_cachedPageCount) {
3035         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3036         m_cachedPageCount = pageCount;
3037     }
3038
3039     double red, green, blue, alpha;
3040     m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3041     send(Messages::WebPageProxy::SetBackgroundColor(red, green, blue, alpha));
3042 }
3043
3044 void WebPage::addPluginView(PluginView* pluginView)
3045 {
3046     ASSERT(!m_pluginViews.contains(pluginView));
3047
3048     m_pluginViews.add(pluginView);
3049 }
3050
3051 void WebPage::removePluginView(PluginView* pluginView)
3052 {
3053     ASSERT(m_pluginViews.contains(pluginView));
3054
3055     m_pluginViews.remove(pluginView);
3056 }
3057
3058 #if PLATFORM(MAC)
3059 void WebPage::setWindowIsVisible(bool windowIsVisible)
3060 {
3061     m_windowIsVisible = windowIsVisible;
3062
3063     corePage()->focusController()->setContainingWindowIsVisible(windowIsVisible);
3064
3065     // Tell all our plug-in views that the window visibility changed.
3066     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
3067         (*it)->setWindowIsVisible(windowIsVisible);
3068 }
3069
3070 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
3071 {
3072     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3073     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3074     m_accessibilityPosition = accessibilityViewCoordinates;
3075     
3076     // Tell all our plug-in views that the window and view frames have changed.
3077     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
3078         (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
3079 }
3080 #endif
3081
3082 bool WebPage::windowIsFocused() const
3083 {
3084     return m_page->focusController()->isActive();
3085 }
3086
3087 bool WebPage::windowAndWebPageAreFocused() const
3088 {
3089 #if PLATFORM(MAC)
3090     if (!m_windowIsVisible)
3091         return false;
3092 #endif
3093     return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
3094 }
3095
3096 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
3097 {
3098     if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
3099         if (m_drawingArea)
3100             m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
3101         return;
3102     }
3103
3104 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
3105     if (messageID.is<CoreIPC::MessageClassLayerTreeCoordinator>()) {
3106         if (m_drawingArea)
3107             m_drawingArea->didReceiveLayerTreeCoordinatorMessage(connection, messageID, arguments);
3108         return;
3109     }
3110 #endif
3111     
3112 #if ENABLE(INSPECTOR)
3113     if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
3114         if (WebInspector* inspector = this->inspector())
3115             inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
3116         return;
3117     }
3118 #endif
3119
3120 #if ENABLE(FULLSCREEN_API)
3121     if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
3122         fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
3123         return;
3124     }
3125 #endif
3126
3127     didReceiveWebPageMessage(connection, messageID, arguments);
3128 }
3129
3130 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
3131 {   
3132     didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
3133 }
3134     
3135 InjectedBundleBackForwardList* WebPage::backForwardList()
3136 {
3137     if (!m_backForwardList)
3138         m_backForwardList = InjectedBundleBackForwardList::create(this);
3139     return m_backForwardList.get();
3140 }
3141
3142 #if PLATFORM(QT) || OS(TIZEN)
3143 #if ENABLE(TOUCH_ADJUSTMENT)
3144 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3145 {
3146     Node* node = 0;
3147     IntRect zoomableArea;
3148     bool foundAreaForTouchPoint = m_mainFrame->coreFrame()->eventHandler()->bestZoomableAreaForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), zoomableArea, node);
3149     ASSERT(node);
3150
3151     if (!foundAreaForTouchPoint)
3152         return;
3153
3154     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3155 }
3156
3157 #else
3158 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3159 {
3160     UNUSED_PARAM(area);
3161     Frame* mainframe = m_mainFrame->coreFrame();
3162     HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
3163
3164     Node* node = result.innerNode();
3165
3166     if (!node)
3167         return;
3168
3169 #if OS(TIZEN) // FIXME: This is to fix wrong codes of open source.
3170     IntRect zoomableArea = enclosingIntRect(node->getRect());
3171 #else
3172     IntRect zoomableArea = node->getRect();
3173 #endif
3174
3175     while (true) {
3176         bool found = !node->isTextNode() && !node->isShadowRoot();
3177
3178         // No candidate found, bail out.
3179         if (!found && !node->parentNode())
3180             return;
3181
3182         // Candidate found, and it is a better candidate than its parent.
3183         // NB: A parent is considered a better candidate iff the node is
3184         // contained by it and it is the only child.
3185         if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
3186             break;
3187
3188         node = node->parentNode();
3189 #if OS(TIZEN) // FIXME: This is to fix wrong codes of open source.
3190         zoomableArea.unite(enclosingIntRect(node->getRect()));
3191 #else
3192         zoomableArea.unite(node->getRect());
3193 #endif
3194     }
3195
3196     if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
3197         const ScrollView* view = node->document()->frame()->view();
3198         zoomableArea = view->contentsToWindow(zoomableArea);
3199     }
3200
3201     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3202 }
3203 #endif
3204 #endif
3205
3206 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3207 {
3208     invalidate();
3209 }
3210
3211 void WebPage::SandboxExtensionTracker::invalidate()
3212 {
3213     if (m_pendingProvisionalSandboxExtension) {
3214         m_pendingProvisionalSandboxExtension->invalidate();
3215         m_pendingProvisionalSandboxExtension = 0;
3216     }
3217
3218     if (m_provisionalSandboxExtension) {
3219         m_provisionalSandboxExtension->invalidate();
3220         m_provisionalSandboxExtension = 0;
3221     }
3222
3223     if (m_committedSandboxExtension) {
3224         m_committedSandboxExtension->invalidate();
3225         m_committedSandboxExtension = 0;
3226     }
3227 }
3228
3229 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3230 {
3231     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3232 }
3233
3234 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3235 {
3236     ASSERT(frame->isMainFrame());
3237
3238     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3239 }
3240
3241 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3242 {
3243     // If we get two beginLoad calls in succession, without a provisional load starting, then
3244     // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
3245     if (m_pendingProvisionalSandboxExtension) {
3246         m_pendingProvisionalSandboxExtension->invalidate();
3247         m_pendingProvisionalSandboxExtension = nullptr;
3248     }
3249     
3250     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3251 }
3252
3253 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3254 {
3255     ASSERT(frame->isMainFrame());
3256
3257     FrameLoader* frameLoader = frame->coreFrame()->loader();
3258     FrameLoadType frameLoadType = frameLoader->loadType();
3259
3260     // If the page is being reloaded, it should reuse whatever extension is committed.
3261     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3262         return true;
3263
3264     DocumentLoader* documentLoader = frameLoader->documentLoader();
3265     DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
3266     if (!documentLoader || !provisionalDocumentLoader)
3267         return false;
3268
3269     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3270         return true;
3271
3272     return false;
3273 }
3274
3275 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3276 {
3277     if (!frame->isMainFrame())
3278         return;
3279
3280     // We should only reuse the commited sandbox extension if it is not null. It can be
3281     // null if the last load was for an error page.
3282     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
3283         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
3284         ASSERT(!m_committedSandboxExtension);
3285     }
3286
3287     ASSERT(!m_provisionalSandboxExtension);
3288
3289     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3290     if (!m_provisionalSandboxExtension)
3291         return;
3292
3293     m_provisionalSandboxExtension->consume();
3294 }
3295
3296 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3297 {
3298     if (!frame->isMainFrame())
3299         return;
3300
3301     // Generally, there should be no pending extension at this stage, but we can have one if UI process
3302     // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3303     if (m_pendingProvisionalSandboxExtension) {
3304         m_pendingProvisionalSandboxExtension->invalidate();
3305         m_pendingProvisionalSandboxExtension = nullptr;
3306     }
3307
3308     // The provisional load has been committed. Invalidate the currently committed sandbox
3309     // extension and make the provisional sandbox extension the committed sandbox extension.
3310     if (m_committedSandboxExtension)
3311         m_committedSandboxExtension->invalidate();
3312
3313     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3314 }
3315
3316 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3317 {
3318     if (!frame->isMainFrame())
3319         return;
3320
3321     // Generally, there should be no pending extension at this stage, but we can have one if UI process
3322     // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3323     if (m_pendingProvisionalSandboxExtension) {
3324         m_pendingProvisionalSandboxExtension->invalidate();
3325         m_pendingProvisionalSandboxExtension = nullptr;
3326     }
3327
3328     if (!m_provisionalSandboxExtension)
3329         return;
3330
3331     m_provisionalSandboxExtension->invalidate();
3332     m_provisionalSandboxExtension = nullptr;
3333 }
3334
3335 bool WebPage::hasLocalDataForURL(const KURL& url)
3336 {
3337     if (url.isLocalFile())
3338         return true;
3339
3340     FrameLoader* frameLoader = m_page->mainFrame()->loader();
3341     DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
3342     if (documentLoader && documentLoader->subresource(url))
3343         return true;
3344
3345     return platformHasLocalDataForURL(url);
3346 }
3347
3348 void WebPage::setCustomTextEncodingName(const String& encoding)
3349 {
3350     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
3351 }
3352
3353 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3354 {
3355     WebBackForwardListProxy::removeItem(itemID);
3356 }
3357
3358 #if PLATFORM(MAC)
3359
3360 bool WebPage::isSpeaking()
3361 {
3362     bool result;
3363     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3364 }
3365
3366 void WebPage::speak(const String& string)
3367 {
3368     send(Messages::WebPageProxy::Speak(string));
3369 }
3370
3371 void WebPage::stopSpeaking()
3372 {
3373     send(Messages::WebPageProxy::StopSpeaking());
3374 }
3375
3376 #endif
3377
3378 #if PLATFORM(MAC)
3379 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3380 {
3381     Document* document = coreFrame->document();
3382     if (!document)
3383         return 0;
3384
3385     if (!document->isPluginDocument())
3386         return 0;
3387
3388     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3389     if (!pluginView)
3390         return 0;
3391
3392     return pluginView->pdfDocumentForPrinting();
3393 }
3394 #endif // PLATFORM(MAC)
3395
3396 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3397 {
3398     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3399     if (!frame)
3400         return;
3401
3402     Frame* coreFrame = frame->coreFrame();
3403     if (!coreFrame)
3404         return;
3405
3406 #if PLATFORM(MAC)
3407     if (pdfDocumentForPrintingFrame(coreFrame))
3408         return;
3409 #endif // PLATFORM(MAC)
3410
3411     if (!m_printContext)
3412         m_printContext = adoptPtr(new PrintContext(coreFrame));
3413
3414     drawingArea()->setLayerTreeStateIsFrozen(true);
3415     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3416
3417     float fullPageHeight;
3418     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3419
3420 #if PLATFORM(GTK)
3421     if (!m_printOperation)
3422         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3423 #endif
3424 }
3425
3426 void WebPage::endPrinting()
3427 {
3428     drawingArea()->setLayerTreeStateIsFrozen(false);
3429 #if PLATFORM(GTK)
3430     m_printOperation = 0;
3431 #endif
3432     m_printContext = nullptr;
3433 }
3434
3435 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3436 {
3437     Vector<IntRect> resultPageRects;
3438     double resultTotalScaleFactorForPrinting = 1;
3439
3440     beginPrinting(frameID, printInfo);
3441
3442     if (m_printContext) {
3443         resultPageRects = m_printContext->pageRects();
3444         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3445     }
3446 #if PLATFORM(MAC)
3447     else
3448         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3449 #endif // PLATFORM(MAC)
3450
3451     // If we're asked to print, we should actually print at least a blank page.
3452     if (resultPageRects.isEmpty())
3453         resultPageRects.append(IntRect(0, 0, 1, 1));
3454
3455     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3456 }
3457
3458 #if PLATFORM(MAC) || PLATFORM(WIN)
3459 void WebPage::drawRectToPDF(uint64_t frameID, const PrintInfo& printInfo, const WebCore::IntRect& rect, uint64_t callbackID)
3460 {
3461     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3462     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3463
3464     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3465
3466 #if USE(CG)
3467     if (coreFrame) {
3468 #if PLATFORM(MAC)
3469         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3470 #else
3471         ASSERT(coreFrame->document()->printing());
3472 #endif
3473
3474         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3475         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3476
3477         CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
3478         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3479         RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3480         CGPDFContextBeginPage(context.get(), pageInfo.get());
3481
3482 #if PLATFORM(MAC)
3483         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3484             ASSERT(!m_printContext);
3485             drawRectToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, rect);
3486         } else
3487 #endif
3488         {
3489             GraphicsContext ctx(context.get());
3490             ctx.scale(FloatSize(1, -1));
3491             ctx.translate(0, -rect.height());
3492             m_printContext->spoolRect(ctx, rect);
3493         }
3494
3495         CGPDFContextEndPage(context.get());
3496         CGPDFContextClose(context.get());
3497     }
3498 #endif
3499
3500     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3501 }
3502
3503 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3504 {
3505     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3506     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3507
3508     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3509
3510 #if USE(CG)
3511     if (coreFrame) {
3512
3513 #if PLATFORM(MAC)
3514         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3515 #else
3516         ASSERT(coreFrame->document()->printing());
3517 #endif
3518
3519         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3520         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3521
3522         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3523         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3524
3525 #if PLATFORM(MAC)
3526         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3527             ASSERT(!m_printContext);
3528             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3529         } else
3530 #endif
3531         {
3532             size_t pageCount = m_printContext->pageCount();
3533             for (uint32_t page = first; page < first + count; ++page) {
3534                 if (page >= pageCount)
3535                     break;
3536
3537                 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3538                 CGPDFContextBeginPage(context.get(), pageInfo.get());
3539
3540                 GraphicsContext ctx(context.get());
3541                 ctx.scale(FloatSize(1, -1));
3542                 ctx.translate(0, -m_printContext->pageRect(page).height());
3543                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3544
3545                 CGPDFContextEndPage(context.get());
3546             }
3547         }
3548         CGPDFContextClose(context.get());
3549     }
3550 #endif
3551
3552     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3553 }
3554
3555 #elif PLATFORM(GTK)
3556
3557 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3558 {
3559     beginPrinting(frameID, printInfo);
3560     if (m_printContext && m_printOperation) {
3561         m_printOperation->startPrint(m_printContext.get(), callbackID);
3562         return;
3563     }
3564
3565     send(Messages::WebPageProxy::VoidCallback(callbackID));
3566 }
3567 #endif
3568
3569 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
3570 void WebPage::getWebAppCapable(uint64_t callbackID)
3571 {
3572     RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("meta");
3573     bool capable = false;
3574
3575     for (unsigned i = 0; i < nodeList->length(); i++) {
3576         WebCore::HTMLMetaElement* metaElement = static_cast<WebCore::HTMLMetaElement*>(nodeList->item(i));
3577         if (metaElement->name() == "apple-mobile-web-app-capable") {
3578             capable = metaElement->content() == "yes" ? true : false;
3579             break;
3580         }
3581     }
3582
3583     send(Messages::WebPageProxy::DidGetWebAppCapable(capable, callbackID));
3584 }
3585
3586 void WebPage::getWebAppIconURL(uint64_t callbackID)
3587 {
3588     RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("link");
3589     String iconURL;
3590
3591     for (unsigned i = 0; i < nodeList->length(); i++) {
3592         WebCore::HTMLLinkElement* linkElement = static_cast<WebCore::HTMLLinkElement*>(nodeList->item(i));
3593         if (linkElement->rel() == "apple-touch-icon" || linkElement->rel() == "apple-touch-icon-precomposed")
3594             iconURL = linkElement->href().string();
3595     }
3596
3597     send(Messages::WebPageProxy::DidGetWebAppIconURL(iconURL, callbackID));
3598 }
3599
3600 void WebPage::getWebAppIconURLs(uint64_t callbackID)
3601 {
3602     RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("link");
3603     Vector<std::pair<String, String> > iconURLs;
3604
3605     for (unsigned i = 0; i < nodeList->length(); i++) {
3606         WebCore::HTMLLinkElement* linkElement = static_cast<WebCore::HTMLLinkElement*>(nodeList->item(i));
3607         if (linkElement->rel() == "apple-touch-icon" || linkElement->rel() == "apple-touch-icon-precomposed")
3608             iconURLs.append(pair<String, String>(linkElement->href().string(), linkElement->iconSizes()));
3609     }
3610
3611     send(Messages::WebPageProxy::DidGetWebAppIconURLs(iconURLs, callbackID));
3612 }
3613 #endif
3614
3615 void WebPage::setMediaVolume(float volume)
3616 {
3617     m_page->setMediaVolume(volume);
3618 }
3619
3620 void WebPage::runModal()
3621 {
3622     if (m_isClosed)
3623         return;
3624     if (m_isRunningModal)
3625         return;
3626
3627     m_isRunningModal = true;
3628     send(Messages::WebPageProxy::RunModal());
3629     RunLoop::run();
3630     ASSERT(!m_isRunningModal);
3631 }
3632
3633 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3634 {
3635     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3636 }
3637
3638 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3639 {
3640     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3641         return true;
3642     return platformCanHandleRequest(request);
3643 }
3644
3645 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
3646 void WebPage::handleAlternativeTextUIResult(const String& result)
3647 {
3648     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3649     if (!frame)
3650         return;
3651     frame->editor()->handleAlternativeTextUIResult(result);
3652 }
3653 #endif
3654
3655 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3656 {
3657     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3658 }
3659
3660 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3661 {
3662     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3663 }
3664
3665 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3666 {
3667     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3668 }
3669
3670 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3671 {
3672     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3673     if (!frame || !frame->editor()->canEdit())
3674         return;
3675
3676     Vector<CompositionUnderline> underlines;
3677     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3678     frame->editor()->setComposition(compositionString, underlines, from, from + length);
3679 }
3680
3681 bool WebPage::hasCompositionForTesting()
3682 {
3683     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3684     return frame && frame->editor()->hasComposition();
3685 }
3686
3687 void WebPage::confirmCompositionForTesting(const String& compositionString)
3688 {
3689     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3690     if (!frame || !frame->editor()->canEdit())
3691         return;
3692
3693     if (compositionString.isNull())
3694         frame->editor()->confirmComposition();
3695     frame->editor()->confirmComposition(compositionString);
3696 }
3697
3698 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3699 {
3700     if (m_numWheelEventHandlers == numWheelEventHandlers)
3701         return;
3702
3703     m_numWheelEventHandlers = numWheelEventHandlers;
3704     recomputeShortCircuitHorizontalWheelEventsState();
3705 }
3706
3707 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3708 {
3709     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3710         return scrollbar->enabled();
3711
3712     return false;
3713 }
3714
3715 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3716 {
3717     if (FrameView* frameView = mainFrame->view()) {
3718         if (hasEnabledHorizontalScrollbar(frameView))
3719             return true;
3720     }
3721
3722     for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext()) {
3723         FrameView* frameView = frame->view();
3724         if (!frameView)
3725             continue;
3726
3727         const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3728         if (!scrollableAreas)
3729             continue;
3730
3731         for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3732             ScrollableArea* scrollableArea = *it;
3733             if (!scrollableArea->isOnActivePage())
3734                 continue;
3735
3736             if (hasEnabledHorizontalScrollbar(scrollableArea))
3737                 return true;
3738         }
3739     }
3740
3741     return false;
3742 }
3743
3744 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3745 {
3746     bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3747
3748     if (canShortCircuitHorizontalWheelEvents) {
3749         // Check if we have any horizontal scroll bars on the page.
3750         if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3751             canShortCircuitHorizontalWheelEvents = false;
3752     }
3753
3754     if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3755         return;
3756
3757     m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3758     send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3759 }
3760
3761 Frame* WebPage::mainFrame() const
3762 {
3763     return m_page ? m_page->mainFrame() : 0;
3764 }
3765
3766 FrameView* WebPage::mainFrameView() const
3767 {
3768     if (Frame* frame = mainFrame())
3769         return frame->view();
3770     
3771     return 0;
3772 }
3773
3774 #if ENABLE(PAGE_VISIBILITY_API)
3775 void WebPage::setVisibilityState(int visibilityState, bool isInitialState)
3776 {
3777     if (!m_page)
3778         return;
3779
3780     WebCore::PageVisibilityState state = static_cast<WebCore::PageVisibilityState>(visibilityState);
3781
3782     if (m_visibilityState == state)
3783         return;
3784
3785     FrameView* view = m_page->mainFrame() ? m_page->mainFrame()->view() : 0;
3786
3787     if (state == WebCore::PageVisibilityStateVisible) {
3788         m_page->didMoveOnscreen();
3789         if (view)
3790             view->show();
3791     }
3792
3793     m_page->setVisibilityState(state, isInitialState);
3794     m_visibilityState = state;
3795
3796     if (state == WebCore::PageVisibilityStateHidden) {
3797         m_page->willMoveOffscreen();
3798         if (view)
3799             view->hide();
3800     }
3801 }
3802 #endif
3803
3804 #if ENABLE(TIZEN_NATIVE_MEMORY_SNAPSHOT)
3805 const char* dumpFileName = "/tmp/webkit_memory";
3806 char* lastUrl = 0;
3807
3808 void dumpMemorySnapshotForUrl(char* url)
3809 {
3810     PrintFormat format = PRINT_FORMAT_JSON;
3811     FILE* fp = 0;
3812     fp = fopen(dumpFileName, "a");
3813     if (fp) {
3814         if (format == PRINT_FORMAT_JSON)
3815             fprintf(fp, "{");
3816         else
3817             fprintf(fp, "URL:%s\n", url);
3818         fprintf(fp, "%s", memoryPage(format).utf8().data());
3819         if (format == PRINT_FORMAT_JSON)
3820             fprintf(fp, "\"URL\":\"%s\"}\n", url);
3821         fclose(fp);
3822     }
3823     lastUrl = url;
3824 }
3825
3826 void dumpMemorySnapshot()
3827 {
3828     dumpMemorySnapshotForUrl(lastUrl);
3829 }
3830
3831 void WebPage::dumpMemorySnapshot()
3832 {
3833     char* url = strdup(mainWebFrame()->url().utf8().data());
3834     if (lastUrl)
3835         free(lastUrl);
3836     lastUrl = url;
3837 }
3838 #endif
3839
3840 } // namespace WebKit