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