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