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