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