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