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