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