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