Merge "Use EwkView's variables instead of drawingScaleFactor and drawingScrollPositio...
[framework/web/webkit-efl.git] / Source / WebKit2 / UIProcess / WebContext.cpp
1 /*
2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "WebContext.h"
28
29 #include "DownloadProxy.h"
30 #include "ImmutableArray.h"
31 #include "InjectedBundleMessageKinds.h"
32 #include "Logging.h"
33 #include "MutableDictionary.h"
34 #include "SandboxExtension.h"
35 #include "StatisticsData.h"
36 #include "TextChecker.h"
37 #include "WKContextPrivate.h"
38 #include "WebApplicationCacheManagerProxy.h"
39 #include "WebContextMessageKinds.h"
40 #include "WebContextUserMessageCoders.h"
41 #include "WebCookieManagerProxy.h"
42 #include "WebCoreArgumentCoders.h"
43 #include "WebDatabaseManagerProxy.h"
44 #include "WebGeolocationManagerProxy.h"
45 #include "WebIconDatabase.h"
46 #include "WebKeyValueStorageManagerProxy.h"
47 #include "WebMediaCacheManagerProxy.h"
48 #include "WebNotificationManagerProxy.h"
49 #include "WebPluginSiteDataManager.h"
50 #include "WebPageGroup.h"
51 #include "WebMemorySampler.h"
52 #include "WebProcessCreationParameters.h"
53 #include "WebProcessMessages.h"
54 #include "WebProcessProxy.h"
55 #include "WebResourceCacheManagerProxy.h"
56 #include <WebCore/Language.h>
57 #include <WebCore/LinkHash.h>
58 #include <WebCore/Logging.h>
59 #include <WebCore/ResourceRequest.h>
60 #include <WebCore/RunLoop.h>
61 #include <runtime/InitializeThreading.h>
62 #include <wtf/CurrentTime.h>
63 #include <wtf/MainThread.h>
64
65 #if PLATFORM(MAC)
66 #include "BuiltInPDFView.h"
67 #endif
68
69 #if ENABLE(BATTERY_STATUS)
70 #include "WebBatteryManagerProxy.h"
71 #endif
72
73 #if ENABLE(NETWORK_INFO)
74 #include "WebNetworkInfoManagerProxy.h"
75 #endif
76
77 #if USE(SOUP)
78 #include "WebSoupRequestManagerProxy.h"
79 #endif
80
81 #if ENABLE(TIZEN_FILE_SYSTEM)
82 #include "WebLocalFileSystemManagerProxy.h"
83 #endif
84
85 #if ENABLE(VIBRATION)
86 #include "WebVibrationProxy.h"
87 #endif
88
89 #ifndef NDEBUG
90 #include <wtf/RefCountedLeakCounter.h>
91 #endif
92
93 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, m_process->connection())
94 #define MESSAGE_CHECK_URL(url) MESSAGE_CHECK_BASE(m_process->checkURLReceivedFromWebProcess(url), m_process->connection())
95
96 using namespace WebCore;
97
98 namespace WebKit {
99
100 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webContextCounter, ("WebContext"));
101
102 WebContext* WebContext::sharedProcessContext()
103 {
104     JSC::initializeThreading();
105     WTF::initializeMainThread();
106     RunLoop::initializeMainRunLoop();
107     static WebContext* context = adoptRef(new WebContext(ProcessModelSharedSecondaryProcess, String())).leakRef();
108     return context;
109 }
110
111 WebContext* WebContext::sharedThreadContext()
112 {
113     RunLoop::initializeMainRunLoop();
114     static WebContext* context = adoptRef(new WebContext(ProcessModelSharedSecondaryThread, String())).leakRef();
115     return context;
116 }
117
118 PassRefPtr<WebContext> WebContext::create(const String& injectedBundlePath)
119 {
120     JSC::initializeThreading();
121     WTF::initializeMainThread();
122     RunLoop::initializeMainRunLoop();
123     return adoptRef(new WebContext(ProcessModelSecondaryProcess, injectedBundlePath));
124 }
125
126 static Vector<WebContext*>& contexts()
127 {
128     DEFINE_STATIC_LOCAL(Vector<WebContext*>, contexts, ());
129
130     return contexts;
131 }
132
133 const Vector<WebContext*>& WebContext::allContexts()
134 {
135     return contexts();
136 }
137
138 WebContext::WebContext(ProcessModel processModel, const String& injectedBundlePath)
139     : m_processModel(processModel)
140     , m_defaultPageGroup(WebPageGroup::create())
141     , m_injectedBundlePath(injectedBundlePath)
142     , m_visitedLinkProvider(this)
143     , m_alwaysUsesComplexTextCodePath(false)
144     , m_shouldUseFontSmoothing(true)
145     , m_cacheModel(CacheModelDocumentViewer)
146     , m_memorySamplerEnabled(false)
147     , m_memorySamplerInterval(1400.0)
148     , m_applicationCacheManagerProxy(WebApplicationCacheManagerProxy::create(this))
149 #if ENABLE(BATTERY_STATUS)
150     , m_batteryManagerProxy(WebBatteryManagerProxy::create(this))
151 #endif
152     , m_cookieManagerProxy(WebCookieManagerProxy::create(this))
153 #if ENABLE(SQL_DATABASE)
154     , m_databaseManagerProxy(WebDatabaseManagerProxy::create(this))
155 #endif
156     , m_geolocationManagerProxy(WebGeolocationManagerProxy::create(this))
157     , m_iconDatabase(WebIconDatabase::create(this))
158     , m_keyValueStorageManagerProxy(WebKeyValueStorageManagerProxy::create(this))
159 #if ENABLE(TIZEN_FILE_SYSTEM)
160     , m_localFileSystemManagerProxy(WebLocalFileSystemManagerProxy::create(this))
161 #endif
162     , m_mediaCacheManagerProxy(WebMediaCacheManagerProxy::create(this))
163 #if ENABLE(NETWORK_INFO)
164     , m_networkInfoManagerProxy(WebNetworkInfoManagerProxy::create(this))
165 #endif
166     , m_notificationManagerProxy(WebNotificationManagerProxy::create(this))
167     , m_pluginSiteDataManager(WebPluginSiteDataManager::create(this))
168     , m_resourceCacheManagerProxy(WebResourceCacheManagerProxy::create(this))
169 #if USE(SOUP)
170     , m_soupRequestManagerProxy(WebSoupRequestManagerProxy::create(this))
171 #endif
172 #if ENABLE(VIBRATION)
173     , m_vibrationProxy(WebVibrationProxy::create(this))
174 #endif
175 #if PLATFORM(WIN)
176     , m_shouldPaintNativeControls(true)
177     , m_initialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyAlways)
178 #endif
179     , m_processTerminationEnabled(true)
180     , m_pluginWorkQueue("com.apple.CoreIPC.PluginQueue")
181 {
182 #if !LOG_DISABLED
183     WebKit::initializeLogChannelsIfNecessary();
184 #endif
185
186     contexts().append(this);
187
188     addLanguageChangeObserver(this, languageChanged);
189
190 #if !LOG_DISABLED
191     WebCore::initializeLoggingChannelsIfNecessary();
192 #endif // !LOG_DISABLED
193
194 #ifndef NDEBUG
195     webContextCounter.increment();
196 #endif
197 }
198
199 WebContext::~WebContext()
200 {
201     m_pluginWorkQueue.invalidate();
202
203     if (m_process && m_process->isValid())
204         m_process->connection()->removeQueueClient(this);
205
206     ASSERT(contexts().find(this) != notFound);
207     contexts().remove(contexts().find(this));
208
209     removeLanguageChangeObserver(this);
210
211     m_applicationCacheManagerProxy->invalidate();
212     m_applicationCacheManagerProxy->clearContext();
213
214 #if ENABLE(BATTERY_STATUS)
215     m_batteryManagerProxy->invalidate();
216     m_batteryManagerProxy->clearContext();
217 #endif
218
219     m_cookieManagerProxy->invalidate();
220     m_cookieManagerProxy->clearContext();
221
222 #if ENABLE(SQL_DATABASE)
223     m_databaseManagerProxy->invalidate();
224     m_databaseManagerProxy->clearContext();
225 #endif
226     
227     m_geolocationManagerProxy->invalidate();
228     m_geolocationManagerProxy->clearContext();
229
230     m_iconDatabase->invalidate();
231     m_iconDatabase->clearContext();
232     
233     m_keyValueStorageManagerProxy->invalidate();
234     m_keyValueStorageManagerProxy->clearContext();
235
236 #if ENABLE(TIZEN_FILE_SYSTEM)
237     m_localFileSystemManagerProxy->invalidate();
238     m_localFileSystemManagerProxy->clearContext();
239 #endif
240
241     m_mediaCacheManagerProxy->invalidate();
242     m_mediaCacheManagerProxy->clearContext();
243
244 #if ENABLE(NETWORK_INFO)
245     m_networkInfoManagerProxy->invalidate();
246     m_networkInfoManagerProxy->clearContext();
247 #endif
248     
249     m_notificationManagerProxy->invalidate();
250     m_notificationManagerProxy->clearContext();
251
252     m_pluginSiteDataManager->invalidate();
253     m_pluginSiteDataManager->clearContext();
254
255     m_resourceCacheManagerProxy->invalidate();
256     m_resourceCacheManagerProxy->clearContext();
257
258 #if USE(SOUP)
259     m_soupRequestManagerProxy->invalidate();
260     m_soupRequestManagerProxy->clearContext();
261 #endif
262
263 #if ENABLE(VIBRATION)
264     m_vibrationProxy->invalidate();
265     m_vibrationProxy->clearContext();
266 #endif
267
268     invalidateCallbackMap(m_dictionaryCallbacks);
269
270     platformInvalidateContext();
271     
272 #ifndef NDEBUG
273     webContextCounter.decrement();
274 #endif
275 }
276
277 void WebContext::initializeInjectedBundleClient(const WKContextInjectedBundleClient* client)
278 {
279     m_injectedBundleClient.initialize(client);
280 }
281
282 void WebContext::initializeConnectionClient(const WKContextConnectionClient* client)
283 {
284     m_connectionClient.initialize(client);
285 }
286
287 void WebContext::initializeHistoryClient(const WKContextHistoryClient* client)
288 {
289     m_historyClient.initialize(client);
290
291     sendToAllProcesses(Messages::WebProcess::SetShouldTrackVisitedLinks(m_historyClient.shouldTrackVisitedLinks()));
292 }
293
294 void WebContext::initializeDownloadClient(const WKContextDownloadClient* client)
295 {
296     m_downloadClient.initialize(client);
297 }
298     
299 void WebContext::languageChanged(void* context)
300 {
301     static_cast<WebContext*>(context)->languageChanged();
302 }
303
304 void WebContext::languageChanged()
305 {
306     sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged(userPreferredLanguages()));
307 }
308
309 void WebContext::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled)
310 {
311     sendToAllProcesses(Messages::WebProcess::FullKeyboardAccessModeChanged(fullKeyboardAccessEnabled));
312 }
313
314 void WebContext::ensureWebProcess()
315 {
316     if (m_process)
317         return;
318
319     m_process = WebProcessProxy::create(this);
320
321     WebProcessCreationParameters parameters;
322
323     if (!injectedBundlePath().isEmpty()) {
324         parameters.injectedBundlePath = injectedBundlePath();
325         SandboxExtension::createHandle(parameters.injectedBundlePath, SandboxExtension::ReadOnly, parameters.injectedBundlePathExtensionHandle);
326     }
327
328     parameters.shouldTrackVisitedLinks = m_historyClient.shouldTrackVisitedLinks();
329     parameters.cacheModel = m_cacheModel;
330     parameters.languages = userPreferredLanguages();
331     parameters.applicationCacheDirectory = applicationCacheDirectory();
332     parameters.databaseDirectory = databaseDirectory();
333 #if ENABLE(TIZEN_FILE_SYSTEM)
334     parameters.localFileSystemDirectory = localFileSystemDirectory();
335 #endif
336     parameters.localStorageDirectory = localStorageDirectory();
337 #if ENABLE(TIZEN_INDEXED_DATABASE)
338     parameters.indexedDatabaseDirectory = indexedDatabaseDirectory();
339 #endif
340
341 #if PLATFORM(MAC)
342     parameters.presenterApplicationPid = getpid();
343 #endif
344
345     copyToVector(m_schemesToRegisterAsEmptyDocument, parameters.urlSchemesRegistererdAsEmptyDocument);
346     copyToVector(m_schemesToRegisterAsSecure, parameters.urlSchemesRegisteredAsSecure);
347     copyToVector(m_schemesToSetDomainRelaxationForbiddenFor, parameters.urlSchemesForWhichDomainRelaxationIsForbidden);
348
349     parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath;
350     parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing;
351     
352     parameters.iconDatabaseEnabled = !iconDatabasePath().isEmpty();
353
354     parameters.textCheckerState = TextChecker::state();
355
356     parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled();
357
358     parameters.defaultRequestTimeoutInterval = WebURLRequest::defaultTimeoutInterval();
359
360 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
361     m_notificationManagerProxy->populateCopyOfNotificationPermissions(parameters.notificationPermissions);
362 #endif
363
364     // Add any platform specific parameters
365     platformInitializeWebProcess(parameters);
366
367     RefPtr<APIObject> injectedBundleInitializationUserData = m_injectedBundleClient.getInjectedBundleInitializationUserData(this);
368     if (!injectedBundleInitializationUserData)
369         injectedBundleInitializationUserData = m_injectedBundleInitializationUserData;
370     m_process->send(Messages::WebProcess::InitializeWebProcess(parameters, WebContextUserMessageEncoder(injectedBundleInitializationUserData.get())), 0);
371
372     for (size_t i = 0; i != m_pendingMessagesToPostToInjectedBundle.size(); ++i) {
373         pair<String, RefPtr<APIObject> >& message = m_pendingMessagesToPostToInjectedBundle[i];
374         m_process->deprecatedSend(InjectedBundleMessage::PostMessage, 0, CoreIPC::In(message.first, WebContextUserMessageEncoder(message.second.get())));
375     }
376     m_pendingMessagesToPostToInjectedBundle.clear();
377 }
378
379 void WebContext::warmInitialProcess()  
380 {
381     ensureWebProcess();
382 }
383
384 void WebContext::enableProcessTermination()
385 {
386     m_processTerminationEnabled = true;
387     if (shouldTerminate(m_process.get()))
388         m_process->terminate();
389 }
390
391 bool WebContext::shouldTerminate(WebProcessProxy* process)
392 {
393     // FIXME: Once we support multiple processes per context, this assertion won't hold.
394     ASSERT(process == m_process);
395
396     if (!m_processTerminationEnabled)
397         return false;
398
399     if (!m_downloads.isEmpty())
400         return false;
401
402     if (!m_applicationCacheManagerProxy->shouldTerminate(process))
403         return false;
404     if (!m_cookieManagerProxy->shouldTerminate(process))
405         return false;
406 #if ENABLE(SQL_DATABASE)
407     if (!m_databaseManagerProxy->shouldTerminate(process))
408         return false;
409 #endif
410     if (!m_keyValueStorageManagerProxy->shouldTerminate(process))
411         return false;
412 #if ENABLE(TIZEN_FILE_SYSTEM)
413     if (!m_localFileSystemManagerProxy->shouldTerminate(process))
414         return false;
415 #endif
416     if (!m_mediaCacheManagerProxy->shouldTerminate(process))
417         return false;
418     if (!m_pluginSiteDataManager->shouldTerminate(process))
419         return false;
420     if (!m_resourceCacheManagerProxy->shouldTerminate(process))
421         return false;
422
423     return true;
424 }
425
426 void WebContext::processDidFinishLaunching(WebProcessProxy* process)
427 {
428     // FIXME: Once we support multiple processes per context, this assertion won't hold.
429     ASSERT_UNUSED(process, process == m_process);
430
431     m_visitedLinkProvider.processDidFinishLaunching();
432
433     m_process->connection()->addQueueClient(this);
434     
435     // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching
436     // so check if it needs to be started here
437     if (m_memorySamplerEnabled) {
438         SandboxExtension::Handle sampleLogSandboxHandle;        
439         double now = WTF::currentTime();
440         String sampleLogFilePath = String::format("WebProcess%llu", static_cast<unsigned long long>(now));
441         sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::WriteOnly, sampleLogSandboxHandle);
442         
443         m_process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0);
444     }
445
446     m_connectionClient.didCreateConnection(this, process->webConnection());
447 }
448
449 void WebContext::disconnectProcess(WebProcessProxy* process)
450 {
451     // FIXME: Once we support multiple processes per context, this assertion won't hold.
452     ASSERT_UNUSED(process, process == m_process);
453
454     m_visitedLinkProvider.processDidClose();
455
456     // Invalidate all outstanding downloads.
457     for (HashMap<uint64_t, RefPtr<DownloadProxy> >::iterator::Values it = m_downloads.begin().values(), end = m_downloads.end().values(); it != end; ++it) {
458         (*it)->processDidClose();
459         (*it)->invalidate();
460     }
461
462     m_downloads.clear();
463
464     m_applicationCacheManagerProxy->invalidate();
465 #if ENABLE(BATTERY_STATUS)
466     m_batteryManagerProxy->invalidate();
467 #endif
468     m_cookieManagerProxy->invalidate();
469 #if ENABLE(SQL_DATABASE)
470     m_databaseManagerProxy->invalidate();
471 #endif
472     m_geolocationManagerProxy->invalidate();
473     m_keyValueStorageManagerProxy->invalidate();
474 #if ENABLE(TIZEN_FILE_SYSTEM)
475     m_localFileSystemManagerProxy->invalidate();
476 #endif
477     m_mediaCacheManagerProxy->invalidate();
478 #if ENABLE(NETWORK_INFO)
479     m_networkInfoManagerProxy->invalidate();
480 #endif
481     m_notificationManagerProxy->invalidate();
482     m_resourceCacheManagerProxy->invalidate();
483 #if USE(SOUP)
484     m_soupRequestManagerProxy->invalidate();
485 #endif
486 #if ENABLE(VIBRATION)
487     m_vibrationProxy->invalidate();
488 #endif
489
490     // When out of process plug-ins are enabled, we don't want to invalidate the plug-in site data
491     // manager just because the web process crashes since it's not involved.
492 #if !ENABLE(PLUGIN_PROCESS)
493     m_pluginSiteDataManager->invalidate();
494 #endif
495
496     // This can cause the web context to be destroyed.
497     m_process = 0;
498 }
499
500 PassRefPtr<WebPageProxy> WebContext::createWebPage(PageClient* pageClient, WebPageGroup* pageGroup)
501 {
502     ensureWebProcess();
503
504     if (!pageGroup)
505         pageGroup = m_defaultPageGroup.get();
506
507     return m_process->createWebPage(pageClient, this, pageGroup);
508 }
509
510 WebProcessProxy* WebContext::relaunchProcessIfNecessary()
511 {
512     ensureWebProcess();
513
514     ASSERT(m_process);
515     return m_process.get();
516 }
517
518 DownloadProxy* WebContext::download(WebPageProxy* initiatingPage, const ResourceRequest& request)
519 {
520     ensureWebProcess();
521
522     DownloadProxy* download = createDownloadProxy();
523     uint64_t initiatingPageID = initiatingPage ? initiatingPage->pageID() : 0;
524
525 #if PLATFORM(QT)
526     ASSERT(initiatingPage); // Our design does not suppport downloads without a WebPage.
527     initiatingPage->handleDownloadRequest(download);
528 #endif
529
530     process()->send(Messages::WebProcess::DownloadRequest(download->downloadID(), initiatingPageID, request), 0);
531     return download;
532 }
533
534 void WebContext::postMessageToInjectedBundle(const String& messageName, APIObject* messageBody)
535 {
536     if (!m_process || !m_process->canSendMessage()) {
537         m_pendingMessagesToPostToInjectedBundle.append(std::make_pair(messageName, messageBody));
538         return;
539     }
540
541     // FIXME: We should consider returning false from this function if the messageBody cannot
542     // be encoded.
543     m_process->deprecatedSend(InjectedBundleMessage::PostMessage, 0, CoreIPC::In(messageName, WebContextUserMessageEncoder(messageBody)));
544 }
545
546 // InjectedBundle client
547
548 void WebContext::didReceiveMessageFromInjectedBundle(const String& messageName, APIObject* messageBody)
549 {
550     m_injectedBundleClient.didReceiveMessageFromInjectedBundle(this, messageName, messageBody);
551 }
552
553 void WebContext::didReceiveSynchronousMessageFromInjectedBundle(const String& messageName, APIObject* messageBody, RefPtr<APIObject>& returnData)
554 {
555     m_injectedBundleClient.didReceiveSynchronousMessageFromInjectedBundle(this, messageName, messageBody, returnData);
556 }
557
558 // HistoryClient
559
560 void WebContext::didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore& store, uint64_t frameID) 
561 {
562     WebPageProxy* page = m_process->webPage(pageID);
563     if (!page)
564         return;
565     
566     WebFrameProxy* frame = m_process->webFrame(frameID);
567     MESSAGE_CHECK(frame);
568     MESSAGE_CHECK(frame->page() == page);
569     
570     m_historyClient.didNavigateWithNavigationData(this, page, store, frame);
571 }
572
573 void WebContext::didPerformClientRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID)
574 {
575     WebPageProxy* page = m_process->webPage(pageID);
576     if (!page)
577         return;
578
579     if (sourceURLString.isEmpty() || destinationURLString.isEmpty())
580         return;
581     
582     WebFrameProxy* frame = m_process->webFrame(frameID);
583     MESSAGE_CHECK(frame);
584     MESSAGE_CHECK(frame->page() == page);
585     MESSAGE_CHECK_URL(sourceURLString);
586     MESSAGE_CHECK_URL(destinationURLString);
587
588     m_historyClient.didPerformClientRedirect(this, page, sourceURLString, destinationURLString, frame);
589 }
590
591 void WebContext::didPerformServerRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID)
592 {
593     WebPageProxy* page = m_process->webPage(pageID);
594     if (!page)
595         return;
596     
597     if (sourceURLString.isEmpty() || destinationURLString.isEmpty())
598         return;
599     
600     WebFrameProxy* frame = m_process->webFrame(frameID);
601     MESSAGE_CHECK(frame);
602     MESSAGE_CHECK(frame->page() == page);
603     MESSAGE_CHECK_URL(sourceURLString);
604     MESSAGE_CHECK_URL(destinationURLString);
605
606     m_historyClient.didPerformServerRedirect(this, page, sourceURLString, destinationURLString, frame);
607 }
608
609 void WebContext::didUpdateHistoryTitle(uint64_t pageID, const String& title, const String& url, uint64_t frameID)
610 {
611     WebPageProxy* page = m_process->webPage(pageID);
612     if (!page)
613         return;
614
615     WebFrameProxy* frame = m_process->webFrame(frameID);
616     MESSAGE_CHECK(frame);
617     MESSAGE_CHECK(frame->page() == page);
618     MESSAGE_CHECK_URL(url);
619
620     m_historyClient.didUpdateHistoryTitle(this, page, title, url, frame);
621 }
622
623 void WebContext::populateVisitedLinks()
624 {
625     m_historyClient.populateVisitedLinks(this);
626 }
627
628 WebContext::Statistics& WebContext::statistics()
629 {
630     static Statistics statistics = Statistics();
631
632     return statistics;
633 }
634
635 void WebContext::setAdditionalPluginsDirectory(const String& directory)
636 {
637     Vector<String> directories;
638     directories.append(directory);
639
640     m_pluginInfoStore.setAdditionalPluginsDirectories(directories);
641 }
642
643 void WebContext::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText)
644 {
645     m_alwaysUsesComplexTextCodePath = alwaysUseComplexText;
646     sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText));
647 }
648
649 void WebContext::setShouldUseFontSmoothing(bool useFontSmoothing)
650 {
651     m_shouldUseFontSmoothing = useFontSmoothing;
652     sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing));
653 }
654
655 void WebContext::registerURLSchemeAsEmptyDocument(const String& urlScheme)
656 {
657     m_schemesToRegisterAsEmptyDocument.add(urlScheme);
658     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme));
659 }
660
661 void WebContext::registerURLSchemeAsSecure(const String& urlScheme)
662 {
663     m_schemesToRegisterAsSecure.add(urlScheme);
664     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
665 }
666
667 void WebContext::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
668 {
669     m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme);
670     sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme));
671 }
672
673 void WebContext::setCacheModel(CacheModel cacheModel)
674 {
675     m_cacheModel = cacheModel;
676     sendToAllProcesses(Messages::WebProcess::SetCacheModel(static_cast<uint32_t>(m_cacheModel)));
677 }
678
679 #if ENABLE(TIZEN_CACHE_CONTROL)
680 void WebContext::setCacheDisabled(bool cacheDisabled)
681 {
682     m_cacheDisabled = cacheDisabled;
683     sendToAllProcesses(Messages::WebProcess::SetCacheDisabled(m_cacheDisabled));
684 }
685 #endif
686
687 void WebContext::setDefaultRequestTimeoutInterval(double timeoutInterval)
688 {
689     sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval));
690 }
691
692 void WebContext::addVisitedLink(const String& visitedURL)
693 {
694     if (visitedURL.isEmpty())
695         return;
696
697     LinkHash linkHash = visitedLinkHash(visitedURL.characters(), visitedURL.length());
698     addVisitedLinkHash(linkHash);
699 }
700
701 void WebContext::addVisitedLinkHash(LinkHash linkHash)
702 {
703     m_visitedLinkProvider.addVisitedLink(linkHash);
704 }
705
706 void WebContext::sendDidGetPlugins(uint64_t requestID, PassOwnPtr<Vector<PluginInfo> > pluginInfos)
707 {
708     ASSERT(isMainThread());
709
710     OwnPtr<Vector<PluginInfo> > plugins(pluginInfos);
711
712 #if PLATFORM(MAC)
713     // Add built-in PDF last, so that it's not used when a real plug-in is installed.
714     // NOTE: This has to be done on the main thread as it calls localizedString().
715     if (!omitPDFSupport())
716         plugins->append(BuiltInPDFView::pluginInfo());
717 #endif
718
719     process()->send(Messages::WebProcess::DidGetPlugins(requestID, *plugins), 0);
720 }
721
722 void WebContext::handleGetPlugins(uint64_t requestID, bool refresh)
723 {
724     if (refresh)
725         m_pluginInfoStore.refresh();
726
727     OwnPtr<Vector<PluginInfo> > pluginInfos = adoptPtr(new Vector<PluginInfo>);
728
729     Vector<PluginModuleInfo> plugins = m_pluginInfoStore.plugins();
730     for (size_t i = 0; i < plugins.size(); ++i)
731         pluginInfos->append(plugins[i].info);
732
733     // NOTE: We have to pass the PluginInfo vector to the secondary thread via a pointer as otherwise
734     //       we'd end up with a deref() race on all the WTF::Strings it contains.
735     RunLoop::main()->dispatch(bind(&WebContext::sendDidGetPlugins, this, requestID, pluginInfos.release()));
736 }
737
738 void WebContext::getPlugins(CoreIPC::Connection*, uint64_t requestID, bool refresh)
739 {
740     m_pluginWorkQueue.dispatch(bind(&WebContext::handleGetPlugins, this, requestID, refresh));
741 }
742
743 void WebContext::getPluginPath(const String& mimeType, const String& urlString, String& pluginPath, bool& blocked)
744 {
745     MESSAGE_CHECK_URL(urlString);
746
747     String newMimeType = mimeType.lower();
748
749     blocked = false;
750     PluginModuleInfo plugin = pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString));
751     if (!plugin.path)
752         return;
753
754     if (pluginInfoStore().shouldBlockPlugin(plugin)) {
755         blocked = true;
756         return;
757     }
758
759     pluginPath = plugin.path;
760 }
761
762 #if !ENABLE(PLUGIN_PROCESS)
763 void WebContext::didGetSitesWithPluginData(const Vector<String>& sites, uint64_t callbackID)
764 {
765     m_pluginSiteDataManager->didGetSitesWithData(sites, callbackID);
766 }
767
768 void WebContext::didClearPluginSiteData(uint64_t callbackID)
769 {
770     m_pluginSiteDataManager->didClearSiteData(callbackID);
771 }
772 #endif
773
774 DownloadProxy* WebContext::createDownloadProxy()
775 {
776     RefPtr<DownloadProxy> downloadProxy = DownloadProxy::create(this);
777     m_downloads.set(downloadProxy->downloadID(), downloadProxy);
778     return downloadProxy.get();
779 }
780
781 void WebContext::downloadFinished(DownloadProxy* downloadProxy)
782 {
783     ASSERT(m_downloads.contains(downloadProxy->downloadID()));
784
785     downloadProxy->invalidate();
786     m_downloads.remove(downloadProxy->downloadID());
787 }
788
789 // FIXME: This is not the ideal place for this function.
790 HashSet<String, CaseFoldingHash> WebContext::pdfAndPostScriptMIMETypes()
791 {
792     HashSet<String, CaseFoldingHash> mimeTypes;
793
794     mimeTypes.add("application/pdf");
795     mimeTypes.add("application/postscript");
796     mimeTypes.add("text/pdf");
797     
798     return mimeTypes;
799 }
800
801 void WebContext::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
802 {
803     if (messageID.is<CoreIPC::MessageClassWebContext>()) {
804         didReceiveWebContextMessage(connection, messageID, arguments);
805         return;
806     }
807
808     if (messageID.is<CoreIPC::MessageClassDownloadProxy>()) {
809         if (DownloadProxy* downloadProxy = m_downloads.get(arguments->destinationID()).get())
810             downloadProxy->didReceiveDownloadProxyMessage(connection, messageID, arguments);
811         
812         return;
813     }
814
815     if (messageID.is<CoreIPC::MessageClassWebApplicationCacheManagerProxy>()) {
816         m_applicationCacheManagerProxy->didReceiveMessage(connection, messageID, arguments);
817         return;
818     }
819
820 #if ENABLE(BATTERY_STATUS)
821     if (messageID.is<CoreIPC::MessageClassWebBatteryManagerProxy>()) {
822         m_batteryManagerProxy->didReceiveMessage(connection, messageID, arguments);
823         return;
824     }
825 #endif
826
827     if (messageID.is<CoreIPC::MessageClassWebCookieManagerProxy>()) {
828         m_cookieManagerProxy->didReceiveMessage(connection, messageID, arguments);
829         return;
830     }
831
832 #if ENABLE(SQL_DATABASE)
833     if (messageID.is<CoreIPC::MessageClassWebDatabaseManagerProxy>()) {
834         m_databaseManagerProxy->didReceiveWebDatabaseManagerProxyMessage(connection, messageID, arguments);
835         return;
836     }
837 #endif
838
839     if (messageID.is<CoreIPC::MessageClassWebGeolocationManagerProxy>()) {
840         m_geolocationManagerProxy->didReceiveMessage(connection, messageID, arguments);
841         return;
842     }
843     
844     if (messageID.is<CoreIPC::MessageClassWebIconDatabase>()) {
845         m_iconDatabase->didReceiveMessage(connection, messageID, arguments);
846         return;
847     }
848
849     if (messageID.is<CoreIPC::MessageClassWebKeyValueStorageManagerProxy>()) {
850         m_keyValueStorageManagerProxy->didReceiveMessage(connection, messageID, arguments);
851         return;
852     }
853
854 #if ENABLE(TIZEN_FILE_SYSTEM)
855     if (messageID.is<CoreIPC::MessageClassWebLocalFileSystemManagerProxy>()) {
856         m_localFileSystemManagerProxy->didReceiveMessage(connection, messageID, arguments);
857         return;
858     }
859 #endif
860
861     if (messageID.is<CoreIPC::MessageClassWebMediaCacheManagerProxy>()) {
862         m_mediaCacheManagerProxy->didReceiveMessage(connection, messageID, arguments);
863         return;
864     }
865
866 #if ENABLE(NETWORK_INFO)
867     if (messageID.is<CoreIPC::MessageClassWebNetworkInfoManagerProxy>()) {
868         m_networkInfoManagerProxy->didReceiveMessage(connection, messageID, arguments);
869         return;
870     }
871 #endif
872     
873     if (messageID.is<CoreIPC::MessageClassWebNotificationManagerProxy>()) {
874         m_notificationManagerProxy->didReceiveMessage(connection, messageID, arguments);
875         return;
876     }
877
878     if (messageID.is<CoreIPC::MessageClassWebResourceCacheManagerProxy>()) {
879         m_resourceCacheManagerProxy->didReceiveWebResourceCacheManagerProxyMessage(connection, messageID, arguments);
880         return;
881     }
882
883 #if USE(SOUP)
884     if (messageID.is<CoreIPC::MessageClassWebSoupRequestManagerProxy>()) {
885         m_soupRequestManagerProxy->didReceiveMessage(connection, messageID, arguments);
886         return;
887     }
888 #endif
889
890 #if ENABLE(VIBRATION)
891     if (messageID.is<CoreIPC::MessageClassWebVibrationProxy>()) {
892         m_vibrationProxy->didReceiveMessage(connection, messageID, arguments);
893         return;
894     }
895 #endif
896
897     switch (messageID.get<WebContextLegacyMessage::Kind>()) {
898         case WebContextLegacyMessage::PostMessage: {
899             String messageName;
900             RefPtr<APIObject> messageBody;
901             WebContextUserMessageDecoder messageDecoder(messageBody, this);
902             if (!arguments->decode(CoreIPC::Out(messageName, messageDecoder)))
903                 return;
904
905             didReceiveMessageFromInjectedBundle(messageName, messageBody.get());
906             return;
907         }
908         case WebContextLegacyMessage::PostSynchronousMessage:
909             ASSERT_NOT_REACHED();
910     }
911
912     ASSERT_NOT_REACHED();
913 }
914
915 void WebContext::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
916 {
917     if (messageID.is<CoreIPC::MessageClassWebContext>()) {
918         didReceiveSyncWebContextMessage(connection, messageID, arguments, reply);
919         return;
920     }
921
922     if (messageID.is<CoreIPC::MessageClassDownloadProxy>()) {
923         if (DownloadProxy* downloadProxy = m_downloads.get(arguments->destinationID()).get())
924             downloadProxy->didReceiveSyncDownloadProxyMessage(connection, messageID, arguments, reply);
925         return;
926     }
927     
928     if (messageID.is<CoreIPC::MessageClassWebIconDatabase>()) {
929         m_iconDatabase->didReceiveSyncMessage(connection, messageID, arguments, reply);
930         return;
931     }
932
933 #if ENABLE(NETWORK_INFO)
934     if (messageID.is<CoreIPC::MessageClassWebNetworkInfoManagerProxy>()) {
935         m_networkInfoManagerProxy->didReceiveSyncMessage(connection, messageID, arguments, reply);
936         return;
937     }
938 #endif
939     
940     switch (messageID.get<WebContextLegacyMessage::Kind>()) {
941         case WebContextLegacyMessage::PostSynchronousMessage: {
942             // FIXME: We should probably encode something in the case that the arguments do not decode correctly.
943
944             String messageName;
945             RefPtr<APIObject> messageBody;
946             WebContextUserMessageDecoder messageDecoder(messageBody, this);
947             if (!arguments->decode(CoreIPC::Out(messageName, messageDecoder)))
948                 return;
949
950             RefPtr<APIObject> returnData;
951             didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody.get(), returnData);
952             reply->encode(CoreIPC::In(WebContextUserMessageEncoder(returnData.get())));
953             return;
954         }
955         case WebContextLegacyMessage::PostMessage:
956             ASSERT_NOT_REACHED();
957     }
958 }
959
960 void WebContext::setEnhancedAccessibility(bool flag)
961 {
962     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
963 }
964     
965 void WebContext::startMemorySampler(const double interval)
966 {    
967     // For new WebProcesses we will also want to start the Memory Sampler
968     m_memorySamplerEnabled = true;
969     m_memorySamplerInterval = interval;
970     
971     // For UIProcess
972 #if ENABLE(MEMORY_SAMPLER)
973     WebMemorySampler::shared()->start(interval);
974 #endif
975     
976     // For WebProcess
977     SandboxExtension::Handle sampleLogSandboxHandle;    
978     double now = WTF::currentTime();
979     String sampleLogFilePath = String::format("WebProcess%llu", static_cast<unsigned long long>(now));
980     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::WriteOnly, sampleLogSandboxHandle);
981     
982     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
983 }
984
985 void WebContext::stopMemorySampler()
986 {    
987     // For WebProcess
988     m_memorySamplerEnabled = false;
989     
990     // For UIProcess
991 #if ENABLE(MEMORY_SAMPLER)
992     WebMemorySampler::shared()->stop();
993 #endif
994
995     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
996 }
997
998 String WebContext::databaseDirectory() const
999 {
1000     if (!m_overrideDatabaseDirectory.isEmpty())
1001         return m_overrideDatabaseDirectory;
1002
1003     return platformDefaultDatabaseDirectory();
1004 }
1005
1006 void WebContext::setIconDatabasePath(const String& path)
1007 {
1008     m_overrideIconDatabasePath = path;
1009     m_iconDatabase->setDatabasePath(path);
1010 }
1011
1012 String WebContext::iconDatabasePath() const
1013 {
1014     if (!m_overrideIconDatabasePath.isEmpty())
1015         return m_overrideIconDatabasePath;
1016
1017     return platformDefaultIconDatabasePath();
1018 }
1019
1020 #if ENABLE(TIZEN_FILE_SYSTEM)
1021 String WebContext::localFileSystemDirectory() const
1022 {
1023     if (!m_overrideLocalFileSystemDirectory.isEmpty())
1024         return m_overrideLocalFileSystemDirectory;
1025
1026     return platformDefaultLocalFileSystemDirectory();
1027 }
1028 #endif
1029
1030 String WebContext::localStorageDirectory() const
1031 {
1032     if (!m_overrideLocalStorageDirectory.isEmpty())
1033         return m_overrideLocalStorageDirectory;
1034
1035     return platformDefaultLocalStorageDirectory();
1036 }
1037
1038 #if ENABLE(TIZEN_INDEXED_DATABASE)
1039 String WebContext::indexedDatabaseDirectory() const
1040 {
1041     if (!m_overrideIndexedDatabaseDirectory.isEmpty())
1042         return m_overrideIndexedDatabaseDirectory;
1043
1044     return platformDefaultIndexedDatabaseDirectory();
1045 }
1046 #endif
1047
1048 void WebContext::setHTTPPipeliningEnabled(bool enabled)
1049 {
1050 #if PLATFORM(MAC)
1051     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1052 #endif
1053 }
1054
1055 bool WebContext::httpPipeliningEnabled() const
1056 {
1057 #if PLATFORM(MAC)
1058     return ResourceRequest::httpPipeliningEnabled();
1059 #else
1060     return false;
1061 #endif
1062 }
1063
1064 void WebContext::getWebCoreStatistics(PassRefPtr<DictionaryCallback> callback)
1065 {
1066     if (!m_process) {
1067         callback->invalidate();
1068         return;
1069     }
1070     
1071     uint64_t callbackID = callback->callbackID();
1072     m_dictionaryCallbacks.set(callbackID, callback.get());
1073     process()->send(Messages::WebProcess::GetWebCoreStatistics(callbackID), 0);
1074 }
1075
1076 static PassRefPtr<MutableDictionary> createDictionaryFromHashMap(const HashMap<String, uint64_t>& map)
1077 {
1078     RefPtr<MutableDictionary> result = MutableDictionary::create();
1079     HashMap<String, uint64_t>::const_iterator end = map.end();
1080     for (HashMap<String, uint64_t>::const_iterator it = map.begin(); it != end; ++it)
1081         result->set(it->first, RefPtr<WebUInt64>(WebUInt64::create(it->second)).get());
1082     
1083     return result;
1084 }
1085
1086 void WebContext::didGetWebCoreStatistics(const StatisticsData& statisticsData, uint64_t callbackID)
1087 {
1088     RefPtr<DictionaryCallback> callback = m_dictionaryCallbacks.take(callbackID);
1089     if (!callback) {
1090         // FIXME: Log error or assert.
1091         return;
1092     }
1093
1094     RefPtr<MutableDictionary> statistics = createDictionaryFromHashMap(statisticsData.statisticsNumbers);
1095     statistics->set("JavaScriptProtectedObjectTypeCounts", createDictionaryFromHashMap(statisticsData.javaScriptProtectedObjectTypeCounts).get());
1096     statistics->set("JavaScriptObjectTypeCounts", createDictionaryFromHashMap(statisticsData.javaScriptObjectTypeCounts).get());
1097     
1098     size_t cacheStatisticsCount = statisticsData.webCoreCacheStatistics.size();
1099     Vector<RefPtr<APIObject> > cacheStatisticsVector(cacheStatisticsCount);
1100     for (size_t i = 0; i < cacheStatisticsCount; ++i)
1101         cacheStatisticsVector[i] = createDictionaryFromHashMap(statisticsData.webCoreCacheStatistics[i]);
1102     statistics->set("WebCoreCacheStatistics", ImmutableArray::adopt(cacheStatisticsVector).get());
1103     
1104     callback->performCallbackWithReturnValue(statistics.get());
1105 }
1106     
1107 void WebContext::garbageCollectJavaScriptObjects()
1108 {
1109     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1110 }
1111
1112 void WebContext::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1113 {
1114     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1115 }
1116
1117 void WebContext::didReceiveMessageOnConnectionWorkQueue(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, bool& didHandleMessage)
1118 {
1119     if (messageID.is<CoreIPC::MessageClassWebContext>()) {
1120         didReceiveWebContextMessageOnConnectionWorkQueue(connection, messageID, arguments, didHandleMessage);
1121         return;
1122     }
1123 }
1124
1125 } // namespace WebKit