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