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