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