Default to current UI locale when recommended locales are invalid
[chromium-blink-merge.git] / content / renderer / render_thread_impl.h
blob68828f67cb87210463264b595da4765f758ac17b
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
6 #define CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
8 #include <set>
9 #include <string>
10 #include <vector>
12 #include "base/memory/memory_pressure_listener.h"
13 #include "base/metrics/user_metrics_action.h"
14 #include "base/observer_list.h"
15 #include "base/strings/string16.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/timer/timer.h"
18 #include "build/build_config.h"
19 #include "content/child/child_thread.h"
20 #include "content/common/content_export.h"
21 #include "content/common/gpu/client/gpu_channel_host.h"
22 #include "content/common/gpu/gpu_result_codes.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "net/base/network_change_notifier.h"
25 #include "third_party/WebKit/public/platform/WebConnectionType.h"
26 #include "ui/gfx/native_widget_types.h"
28 #if defined(OS_MACOSX)
29 #include "third_party/WebKit/public/web/mac/WebScrollbarTheme.h"
30 #endif
32 class GrContext;
33 class SkBitmap;
34 struct ViewMsg_New_Params;
35 struct WorkerProcessMsg_CreateWorker_Params;
37 namespace blink {
38 class WebGamepads;
39 class WebGraphicsContext3D;
40 class WebMediaStreamCenter;
41 class WebMediaStreamCenterClient;
44 namespace base {
45 class MessageLoopProxy;
46 class Thread;
49 namespace cc {
50 class ContextProvider;
53 namespace IPC {
54 class ForwardingMessageFilter;
55 class MessageFilter;
58 namespace media {
59 class AudioHardwareConfig;
60 class GpuVideoAcceleratorFactories;
63 namespace v8 {
64 class Extension;
67 namespace webkit {
68 namespace gpu {
69 class ContextProviderWebContext;
70 class GrContextForWebGraphicsContext3D;
74 namespace content {
76 class AppCacheDispatcher;
77 class AecDumpMessageFilter;
78 class AudioInputMessageFilter;
79 class AudioMessageFilter;
80 class AudioRendererMixerManager;
81 class ContextProviderCommandBuffer;
82 class DBMessageFilter;
83 class DevToolsAgentFilter;
84 class DomStorageDispatcher;
85 class EmbeddedWorkerDispatcher;
86 class GpuChannelHost;
87 class IndexedDBDispatcher;
88 class InputEventFilter;
89 class InputHandlerManager;
90 class MediaStreamCenter;
91 class MemoryObserver;
92 class PeerConnectionDependencyFactory;
93 class MidiMessageFilter;
94 class NetInfoDispatcher;
95 class P2PSocketDispatcher;
96 class PeerConnectionTracker;
97 class RendererDemuxerAndroid;
98 class RendererWebKitPlatformSupportImpl;
99 class RenderProcessObserver;
100 class VideoCaptureImplManager;
101 class WebGraphicsContext3DCommandBufferImpl;
102 class WebRTCIdentityService;
104 // The RenderThreadImpl class represents a background thread where RenderView
105 // instances live. The RenderThread supports an API that is used by its
106 // consumer to talk indirectly to the RenderViews and supporting objects.
107 // Likewise, it provides an API for the RenderViews to talk back to the main
108 // process (i.e., their corresponding WebContentsImpl).
110 // Most of the communication occurs in the form of IPC messages. They are
111 // routed to the RenderThread according to the routing IDs of the messages.
112 // The routing IDs correspond to RenderView instances.
113 class CONTENT_EXPORT RenderThreadImpl : public RenderThread,
114 public ChildThread,
115 public GpuChannelHostFactory {
116 public:
117 static RenderThreadImpl* current();
119 RenderThreadImpl();
120 // Constructor that's used when running in single process mode.
121 explicit RenderThreadImpl(const std::string& channel_name);
122 virtual ~RenderThreadImpl();
123 virtual void Shutdown() OVERRIDE;
125 // When initializing WebKit, ensure that any schemes needed for the content
126 // module are registered properly. Static to allow sharing with tests.
127 static void RegisterSchemes();
129 // Notify V8 that the date/time configuration of the system might have
130 // changed.
131 static void NotifyTimezoneChange();
133 // RenderThread implementation:
134 virtual bool Send(IPC::Message* msg) OVERRIDE;
135 virtual base::MessageLoop* GetMessageLoop() OVERRIDE;
136 virtual IPC::SyncChannel* GetChannel() OVERRIDE;
137 virtual std::string GetLocale() OVERRIDE;
138 virtual IPC::SyncMessageFilter* GetSyncMessageFilter() OVERRIDE;
139 virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy()
140 OVERRIDE;
141 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
142 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
143 virtual int GenerateRoutingID() OVERRIDE;
144 virtual void AddFilter(IPC::MessageFilter* filter) OVERRIDE;
145 virtual void RemoveFilter(IPC::MessageFilter* filter) OVERRIDE;
146 virtual void AddObserver(RenderProcessObserver* observer) OVERRIDE;
147 virtual void RemoveObserver(RenderProcessObserver* observer) OVERRIDE;
148 virtual void SetResourceDispatcherDelegate(
149 ResourceDispatcherDelegate* delegate) OVERRIDE;
150 virtual void EnsureWebKitInitialized() OVERRIDE;
151 virtual void RecordAction(const base::UserMetricsAction& action) OVERRIDE;
152 virtual void RecordComputedAction(const std::string& action) OVERRIDE;
153 virtual scoped_ptr<base::SharedMemory> HostAllocateSharedMemoryBuffer(
154 size_t buffer_size) OVERRIDE;
155 virtual void RegisterExtension(v8::Extension* extension) OVERRIDE;
156 virtual void ScheduleIdleHandler(int64 initial_delay_ms) OVERRIDE;
157 virtual void IdleHandler() OVERRIDE;
158 virtual int64 GetIdleNotificationDelayInMs() const OVERRIDE;
159 virtual void SetIdleNotificationDelayInMs(
160 int64 idle_notification_delay_in_ms) OVERRIDE;
161 virtual void UpdateHistograms(int sequence_number) OVERRIDE;
162 virtual int PostTaskToAllWebWorkers(const base::Closure& closure) OVERRIDE;
163 virtual bool ResolveProxy(const GURL& url, std::string* proxy_list) OVERRIDE;
164 virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE;
165 #if defined(OS_WIN)
166 virtual void PreCacheFont(const LOGFONT& log_font) OVERRIDE;
167 virtual void ReleaseCachedFonts() OVERRIDE;
168 #endif
169 virtual ServiceRegistry* GetServiceRegistry() OVERRIDE;
171 // Synchronously establish a channel to the GPU plugin if not previously
172 // established or if it has been lost (for example if the GPU plugin crashed).
173 // If there is a pending asynchronous request, it will be completed by the
174 // time this routine returns.
175 GpuChannelHost* EstablishGpuChannelSync(CauseForGpuLaunch);
178 // These methods modify how the next message is sent. Normally, when sending
179 // a synchronous message that runs a nested message loop, we need to suspend
180 // callbacks into WebKit. This involves disabling timers and deferring
181 // resource loads. However, there are exceptions when we need to customize
182 // the behavior.
183 void DoNotSuspendWebKitSharedTimer();
184 void DoNotNotifyWebKitOfModalLoop();
186 // True if we are running layout tests. This currently disables forwarding
187 // various status messages to the console, skips network error pages, and
188 // short circuits size update and focus events.
189 bool layout_test_mode() const {
190 return layout_test_mode_;
192 void set_layout_test_mode(bool layout_test_mode) {
193 layout_test_mode_ = layout_test_mode;
196 RendererWebKitPlatformSupportImpl* webkit_platform_support() const {
197 DCHECK(webkit_platform_support_);
198 return webkit_platform_support_.get();
201 IPC::ForwardingMessageFilter* compositor_output_surface_filter() const {
202 return compositor_output_surface_filter_.get();
205 InputHandlerManager* input_handler_manager() const {
206 return input_handler_manager_.get();
209 // Will be NULL if threaded compositing has not been enabled.
210 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy() const {
211 return compositor_message_loop_proxy_;
214 bool is_gpu_rasterization_enabled() const {
215 return is_gpu_rasterization_enabled_;
218 bool is_gpu_rasterization_forced() const {
219 return is_gpu_rasterization_forced_;
222 bool is_impl_side_painting_enabled() const {
223 return is_impl_side_painting_enabled_;
226 bool is_low_res_tiling_enabled() const { return is_low_res_tiling_enabled_; }
228 bool is_lcd_text_enabled() const { return is_lcd_text_enabled_; }
230 bool is_distance_field_text_enabled() const {
231 return is_distance_field_text_enabled_;
234 bool is_zero_copy_enabled() const { return is_zero_copy_enabled_; }
236 bool is_one_copy_enabled() const { return is_one_copy_enabled_; }
238 AppCacheDispatcher* appcache_dispatcher() const {
239 return appcache_dispatcher_.get();
242 DomStorageDispatcher* dom_storage_dispatcher() const {
243 return dom_storage_dispatcher_.get();
246 EmbeddedWorkerDispatcher* embedded_worker_dispatcher() const {
247 return embedded_worker_dispatcher_.get();
250 AudioInputMessageFilter* audio_input_message_filter() {
251 return audio_input_message_filter_.get();
254 AudioMessageFilter* audio_message_filter() {
255 return audio_message_filter_.get();
258 MidiMessageFilter* midi_message_filter() {
259 return midi_message_filter_.get();
262 #if defined(OS_ANDROID)
263 RendererDemuxerAndroid* renderer_demuxer() {
264 return renderer_demuxer_.get();
266 #endif
268 // Creates the embedder implementation of WebMediaStreamCenter.
269 // The resulting object is owned by WebKit and deleted by WebKit at tear-down.
270 blink::WebMediaStreamCenter* CreateMediaStreamCenter(
271 blink::WebMediaStreamCenterClient* client);
273 #if defined(ENABLE_WEBRTC)
274 // Returns a factory used for creating RTC PeerConnection objects.
275 PeerConnectionDependencyFactory* GetPeerConnectionDependencyFactory();
277 PeerConnectionTracker* peer_connection_tracker() {
278 return peer_connection_tracker_.get();
281 // Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
282 P2PSocketDispatcher* p2p_socket_dispatcher() {
283 return p2p_socket_dispatcher_.get();
285 #endif
287 VideoCaptureImplManager* video_capture_impl_manager() const {
288 return vc_manager_.get();
291 // Get the GPU channel. Returns NULL if the channel is not established or
292 // has been lost.
293 GpuChannelHost* GetGpuChannel();
295 // Returns a MessageLoopProxy instance corresponding to the message loop
296 // of the thread on which file operations should be run. Must be called
297 // on the renderer's main thread.
298 scoped_refptr<base::MessageLoopProxy> GetFileThreadMessageLoopProxy();
300 // Returns a MessageLoopProxy instance corresponding to the message loop
301 // of the thread on which media operations should be run. Must be called
302 // on the renderer's main thread.
303 scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy();
305 // Causes the idle handler to skip sending idle notifications
306 // on the two next scheduled calls, so idle notifications are
307 // not sent for at least one notification delay.
308 void PostponeIdleNotification();
310 scoped_refptr<media::GpuVideoAcceleratorFactories> GetGpuFactories();
312 scoped_refptr<webkit::gpu::ContextProviderWebContext>
313 SharedMainThreadContextProvider();
315 // AudioRendererMixerManager instance which manages renderer side mixer
316 // instances shared based on configured audio parameters. Lazily created on
317 // first call.
318 AudioRendererMixerManager* GetAudioRendererMixerManager();
320 // AudioHardwareConfig contains audio hardware configuration for
321 // renderer side clients. Creation requires a synchronous IPC call so it is
322 // lazily created on the first call.
323 media::AudioHardwareConfig* GetAudioHardwareConfig();
325 #if defined(OS_WIN)
326 void PreCacheFontCharacters(const LOGFONT& log_font,
327 const base::string16& str);
328 #endif
330 #if defined(ENABLE_WEBRTC)
331 WebRTCIdentityService* get_webrtc_identity_service() {
332 return webrtc_identity_service_.get();
334 #endif
336 // For producing custom V8 histograms. Custom histograms are produced if all
337 // RenderViews share the same host, and the host is in the pre-specified set
338 // of hosts we want to produce custom diagrams for. The name for a custom
339 // diagram is the name of the corresponding generic diagram plus a
340 // host-specific suffix.
341 class CONTENT_EXPORT HistogramCustomizer {
342 public:
343 HistogramCustomizer();
344 ~HistogramCustomizer();
346 // Called when a top frame of a RenderView navigates. This function updates
347 // RenderThreadImpl's information about whether all RenderViews are
348 // displaying a page from the same host. |host| is the host where a
349 // RenderView navigated, and |view_count| is the number of RenderViews in
350 // this process.
351 void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
353 // Used for customizing some histograms if all RenderViews share the same
354 // host. Returns the current custom histogram name to use for
355 // |histogram_name|, or |histogram_name| if it shouldn't be customized.
356 std::string ConvertToCustomHistogramName(const char* histogram_name) const;
358 private:
359 friend class RenderThreadImplUnittest;
361 // Used for updating the information on which is the common host which all
362 // RenderView's share (if any). If there is no common host, this function is
363 // called with an empty string.
364 void SetCommonHost(const std::string& host);
366 // The current common host of the RenderViews; empty string if there is no
367 // common host.
368 std::string common_host_;
369 // The corresponding suffix.
370 std::string common_host_histogram_suffix_;
371 // Set of histograms for which we want to produce a custom histogram if
372 // possible.
373 std::set<std::string> custom_histograms_;
375 DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
378 HistogramCustomizer* histogram_customizer() {
379 return &histogram_customizer_;
382 void SetFlingCurveParameters(const std::vector<float>& new_touchpad,
383 const std::vector<float>& new_touchscreen);
385 // Retrieve current gamepad data.
386 void SampleGamepads(blink::WebGamepads* data);
388 // Called by a RenderWidget when it is created or destroyed. This
389 // allows the process to know when there are no visible widgets.
390 void WidgetCreated();
391 void WidgetDestroyed();
392 void WidgetHidden();
393 void WidgetRestored();
395 void AddEmbeddedWorkerRoute(int32 routing_id, IPC::Listener* listener);
396 void RemoveEmbeddedWorkerRoute(int32 routing_id);
398 void RegisterPendingRenderFrameConnect(int routing_id,
399 mojo::ScopedMessagePipeHandle handle);
401 private:
402 // ChildThread
403 virtual bool OnControlMessageReceived(const IPC::Message& msg) OVERRIDE;
405 // GpuChannelHostFactory implementation:
406 virtual bool IsMainThread() OVERRIDE;
407 virtual base::MessageLoop* GetMainLoop() OVERRIDE;
408 virtual scoped_refptr<base::MessageLoopProxy> GetIOLoopProxy() OVERRIDE;
409 virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(
410 size_t size) OVERRIDE;
411 virtual CreateCommandBufferResult CreateViewCommandBuffer(
412 int32 surface_id,
413 const GPUCreateCommandBufferConfig& init_params,
414 int32 route_id) OVERRIDE;
415 virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
416 size_t width,
417 size_t height,
418 unsigned internalformat,
419 unsigned usage) OVERRIDE;
420 virtual void DeleteGpuMemoryBuffer(
421 scoped_ptr<gfx::GpuMemoryBuffer> buffer) OVERRIDE;
423 void Init();
425 void OnCreateNewFrame(int routing_id, int parent_routing_id);
426 void OnCreateNewFrameProxy(int routing_id,
427 int parent_routing_id,
428 int render_view_routing_id);
429 void OnSetZoomLevelForCurrentURL(const std::string& scheme,
430 const std::string& host,
431 double zoom_level);
432 void OnCreateNewView(const ViewMsg_New_Params& params);
433 void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
434 void OnPurgePluginListCache(bool reload_pages);
435 void OnNetworkTypeChanged(net::NetworkChangeNotifier::ConnectionType type);
436 void OnGetAccessibilityTree();
437 void OnTempCrashWithData(const GURL& data);
438 void OnUpdateTimezone();
439 void OnMemoryPressure(
440 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
441 #if defined(OS_ANDROID)
442 void OnSetWebKitSharedTimersSuspended(bool suspend);
443 #endif
444 #if defined(OS_MACOSX)
445 void OnUpdateScrollbarTheme(float initial_button_delay,
446 float autoscroll_button_delay,
447 bool jump_on_track_click,
448 blink::ScrollerStyle preferred_scroller_style,
449 bool redraw);
450 #endif
451 void OnCreateNewSharedWorker(
452 const WorkerProcessMsg_CreateWorker_Params& params);
454 void IdleHandlerInForegroundTab();
456 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> CreateOffscreenContext3d();
458 // These objects live solely on the render thread.
459 scoped_ptr<AppCacheDispatcher> appcache_dispatcher_;
460 scoped_ptr<DomStorageDispatcher> dom_storage_dispatcher_;
461 scoped_ptr<IndexedDBDispatcher> main_thread_indexed_db_dispatcher_;
462 scoped_ptr<RendererWebKitPlatformSupportImpl> webkit_platform_support_;
463 scoped_ptr<EmbeddedWorkerDispatcher> embedded_worker_dispatcher_;
465 // Used on the render thread and deleted by WebKit at shutdown.
466 blink::WebMediaStreamCenter* media_stream_center_;
468 // Used on the renderer and IPC threads.
469 scoped_refptr<DBMessageFilter> db_message_filter_;
470 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter_;
471 scoped_refptr<AudioMessageFilter> audio_message_filter_;
472 scoped_refptr<MidiMessageFilter> midi_message_filter_;
473 #if defined(OS_ANDROID)
474 scoped_refptr<RendererDemuxerAndroid> renderer_demuxer_;
475 #endif
476 scoped_refptr<DevToolsAgentFilter> devtools_agent_message_filter_;
478 #if defined(ENABLE_WEBRTC)
479 scoped_ptr<PeerConnectionDependencyFactory> peer_connection_factory_;
481 // This is used to communicate to the browser process the status
482 // of all the peer connections created in the renderer.
483 scoped_ptr<PeerConnectionTracker> peer_connection_tracker_;
485 // Dispatches all P2P sockets.
486 scoped_refptr<P2PSocketDispatcher> p2p_socket_dispatcher_;
487 #endif
489 // Used on the render thread.
490 scoped_ptr<VideoCaptureImplManager> vc_manager_;
492 // Used for communicating registering AEC dump consumers with the browser and
493 // receving AEC dump file handles when AEC dump is enabled. An AEC dump is
494 // diagnostic audio data for WebRTC stored locally when enabled by the user in
495 // chrome://webrtc-internals.
496 scoped_refptr<AecDumpMessageFilter> aec_dump_message_filter_;
498 // The count of RenderWidgets running through this thread.
499 int widget_count_;
501 // The count of hidden RenderWidgets running through this thread.
502 int hidden_widget_count_;
504 // The current value of the idle notification timer delay.
505 int64 idle_notification_delay_in_ms_;
507 // The number of idle handler calls that skip sending idle notifications.
508 int idle_notifications_to_skip_;
510 bool suspend_webkit_shared_timer_;
511 bool notify_webkit_of_modal_loop_;
512 bool webkit_shared_timer_suspended_;
514 // The following flag is used to control layout test specific behavior.
515 bool layout_test_mode_;
517 // Timer that periodically calls IdleHandler.
518 base::RepeatingTimer<RenderThreadImpl> idle_timer_;
520 // The channel from the renderer process to the GPU process.
521 scoped_refptr<GpuChannelHost> gpu_channel_;
523 // Cache of variables that are needed on the compositor thread by
524 // GpuChannelHostFactory methods.
525 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
527 // A lazily initiated thread on which file operations are run.
528 scoped_ptr<base::Thread> file_thread_;
530 // May be null if overridden by ContentRendererClient.
531 scoped_ptr<base::Thread> compositor_thread_;
533 // Thread for running multimedia operations (e.g., video decoding).
534 scoped_ptr<base::Thread> media_thread_;
536 // Will point to appropriate MessageLoopProxy after initialization,
537 // regardless of whether |compositor_thread_| is overriden.
538 scoped_refptr<base::MessageLoopProxy> compositor_message_loop_proxy_;
540 // May be null if unused by the |input_handler_manager_|.
541 scoped_refptr<InputEventFilter> input_event_filter_;
542 scoped_ptr<InputHandlerManager> input_handler_manager_;
543 scoped_refptr<IPC::ForwardingMessageFilter> compositor_output_surface_filter_;
545 scoped_refptr<webkit::gpu::ContextProviderWebContext>
546 shared_main_thread_contexts_;
548 ObserverList<RenderProcessObserver> observers_;
550 scoped_refptr<ContextProviderCommandBuffer> gpu_va_context_provider_;
552 scoped_ptr<AudioRendererMixerManager> audio_renderer_mixer_manager_;
553 scoped_ptr<media::AudioHardwareConfig> audio_hardware_config_;
555 HistogramCustomizer histogram_customizer_;
557 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
559 #if defined(ENABLE_WEBRTC)
560 scoped_ptr<WebRTCIdentityService> webrtc_identity_service_;
561 #endif
563 // TODO(reveman): Allow AllocateGpuMemoryBuffer to be called from
564 // multiple threads. Current allocation mechanism for IOSurface
565 // backed GpuMemoryBuffers prevent this. crbug.com/325045
566 base::ThreadChecker allocate_gpu_memory_buffer_thread_checker_;
568 scoped_ptr<MemoryObserver> memory_observer_;
570 // Compositor settings
571 bool is_gpu_rasterization_enabled_;
572 bool is_gpu_rasterization_forced_;
573 bool is_impl_side_painting_enabled_;
574 bool is_low_res_tiling_enabled_;
575 bool is_lcd_text_enabled_;
576 bool is_distance_field_text_enabled_;
577 bool is_zero_copy_enabled_;
578 bool is_one_copy_enabled_;
580 std::map<int, mojo::MessagePipeHandle> pending_render_frame_connects_;
582 DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
585 } // namespace content
587 #endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_