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