Fix crash on app list start page contents not existing.
[chromium-blink-merge.git] / content / renderer / render_thread_impl.cc
blob35bd5e3f4e6f931153c499fdd4310855ce83febd
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 #include "content/renderer/render_thread_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <vector>
12 #include "base/allocator/allocator_extension.h"
13 #include "base/command_line.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/memory/discardable_memory.h"
17 #include "base/memory/discardable_memory_emulated.h"
18 #include "base/memory/discardable_memory_shmem_allocator.h"
19 #include "base/memory/shared_memory.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram.h"
22 #include "base/path_service.h"
23 #include "base/single_thread_task_runner.h"
24 #include "base/strings/string16.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_tokenizer.h"
27 #include "base/strings/sys_string_conversions.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/threading/thread_local.h"
30 #include "base/threading/thread_restrictions.h"
31 #include "base/trace_event/trace_event.h"
32 #include "base/values.h"
33 #include "cc/base/switches.h"
34 #include "cc/blink/web_external_bitmap_impl.h"
35 #include "cc/blink/web_layer_impl.h"
36 #include "cc/resources/tile_task_worker_pool.h"
37 #include "content/child/appcache/appcache_dispatcher.h"
38 #include "content/child/appcache/appcache_frontend_impl.h"
39 #include "content/child/child_discardable_shared_memory_manager.h"
40 #include "content/child/child_gpu_memory_buffer_manager.h"
41 #include "content/child/child_histogram_message_filter.h"
42 #include "content/child/child_resource_message_filter.h"
43 #include "content/child/child_shared_bitmap_manager.h"
44 #include "content/child/content_child_helpers.h"
45 #include "content/child/db_message_filter.h"
46 #include "content/child/indexed_db/indexed_db_dispatcher.h"
47 #include "content/child/indexed_db/indexed_db_message_filter.h"
48 #include "content/child/npapi/npobject_util.h"
49 #include "content/child/plugin_messages.h"
50 #include "content/child/resource_dispatcher.h"
51 #include "content/child/resource_scheduling_filter.h"
52 #include "content/child/runtime_features.h"
53 #include "content/child/thread_safe_sender.h"
54 #include "content/child/web_database_observer_impl.h"
55 #include "content/child/worker_task_runner.h"
56 #include "content/common/child_process_messages.h"
57 #include "content/common/content_constants_internal.h"
58 #include "content/common/database_messages.h"
59 #include "content/common/dom_storage/dom_storage_messages.h"
60 #include "content/common/frame_messages.h"
61 #include "content/common/gpu/client/context_provider_command_buffer.h"
62 #include "content/common/gpu/client/gpu_channel_host.h"
63 #include "content/common/gpu/gpu_messages.h"
64 #include "content/common/gpu/gpu_process_launch_causes.h"
65 #include "content/common/render_frame_setup.mojom.h"
66 #include "content/common/resource_messages.h"
67 #include "content/common/view_messages.h"
68 #include "content/common/worker_messages.h"
69 #include "content/public/common/content_constants.h"
70 #include "content/public/common/content_paths.h"
71 #include "content/public/common/content_switches.h"
72 #include "content/public/common/mojo_channel_switches.h"
73 #include "content/public/common/renderer_preferences.h"
74 #include "content/public/common/url_constants.h"
75 #include "content/public/renderer/content_renderer_client.h"
76 #include "content/public/renderer/render_process_observer.h"
77 #include "content/public/renderer/render_view_visitor.h"
78 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
79 #include "content/renderer/devtools/devtools_agent_filter.h"
80 #include "content/renderer/devtools/v8_sampling_profiler.h"
81 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
82 #include "content/renderer/dom_storage/webstoragearea_impl.h"
83 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
84 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
85 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
86 #include "content/renderer/gpu/compositor_output_surface.h"
87 #include "content/renderer/input/input_event_filter.h"
88 #include "content/renderer/input/input_handler_manager.h"
89 #include "content/renderer/input/main_thread_input_event_filter.h"
90 #include "content/renderer/media/aec_dump_message_filter.h"
91 #include "content/renderer/media/audio_input_message_filter.h"
92 #include "content/renderer/media/audio_message_filter.h"
93 #include "content/renderer/media/audio_renderer_mixer_manager.h"
94 #include "content/renderer/media/media_stream_center.h"
95 #include "content/renderer/media/midi_message_filter.h"
96 #include "content/renderer/media/render_media_client.h"
97 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
98 #include "content/renderer/media/video_capture_impl_manager.h"
99 #include "content/renderer/media/video_capture_message_filter.h"
100 #include "content/renderer/net_info_helper.h"
101 #include "content/renderer/p2p/socket_dispatcher.h"
102 #include "content/renderer/render_frame_proxy.h"
103 #include "content/renderer/render_process_impl.h"
104 #include "content/renderer/render_view_impl.h"
105 #include "content/renderer/renderer_blink_platform_impl.h"
106 #include "content/renderer/scheduler/renderer_scheduler.h"
107 #include "content/renderer/scheduler/resource_dispatch_throttler.h"
108 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
109 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
110 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
111 #include "gin/public/debug.h"
112 #include "gpu/GLES2/gl2extchromium.h"
113 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
114 #include "ipc/ipc_channel_handle.h"
115 #include "ipc/ipc_platform_file.h"
116 #include "ipc/mojo/ipc_channel_mojo.h"
117 #include "media/base/audio_hardware_config.h"
118 #include "media/base/media.h"
119 #include "media/filters/gpu_video_accelerator_factories.h"
120 #include "mojo/common/common_type_converters.h"
121 #include "net/base/net_errors.h"
122 #include "net/base/net_util.h"
123 #include "skia/ext/event_tracer_impl.h"
124 #include "third_party/WebKit/public/platform/WebString.h"
125 #include "third_party/WebKit/public/platform/WebThread.h"
126 #include "third_party/WebKit/public/web/WebCache.h"
127 #include "third_party/WebKit/public/web/WebColorName.h"
128 #include "third_party/WebKit/public/web/WebDatabase.h"
129 #include "third_party/WebKit/public/web/WebDocument.h"
130 #include "third_party/WebKit/public/web/WebFrame.h"
131 #include "third_party/WebKit/public/web/WebImageCache.h"
132 #include "third_party/WebKit/public/web/WebKit.h"
133 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
134 #include "third_party/WebKit/public/web/WebPopupMenu.h"
135 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
136 #include "third_party/WebKit/public/web/WebScriptController.h"
137 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
138 #include "third_party/WebKit/public/web/WebView.h"
139 #include "third_party/skia/include/core/SkGraphics.h"
140 #include "ui/base/layout.h"
141 #include "ui/base/ui_base_switches.h"
142 #include "v8/include/v8.h"
144 #if defined(OS_ANDROID)
145 #include <cpu-features.h>
146 #include "content/renderer/android/synchronous_compositor_factory.h"
147 #include "content/renderer/media/android/renderer_demuxer_android.h"
148 #endif
150 #if defined(OS_MACOSX)
151 #include "base/mac/mac_util.h"
152 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
153 #endif
155 #if defined(OS_POSIX)
156 #include "ipc/ipc_channel_posix.h"
157 #endif
159 #if defined(OS_WIN)
160 #include <windows.h>
161 #include <objbase.h>
162 #else
163 // TODO(port)
164 #include "content/child/npapi/np_channel_base.h"
165 #endif
167 #if defined(ENABLE_PLUGINS)
168 #include "content/renderer/npapi/plugin_channel_host.h"
169 #endif
171 #if defined(ENABLE_WEBRTC)
172 #include "content/renderer/media/peer_connection_tracker.h"
173 #include "content/renderer/media/rtc_peer_connection_handler.h"
174 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
175 #include "content/renderer/media/webrtc_identity_service.h"
176 #endif
178 #ifdef ENABLE_VTUNE_JIT_INTERFACE
179 #include "v8/src/third_party/vtune/v8-vtune.h"
180 #endif
182 using base::ThreadRestrictions;
183 using blink::WebDocument;
184 using blink::WebFrame;
185 using blink::WebNetworkStateNotifier;
186 using blink::WebRuntimeFeatures;
187 using blink::WebScriptController;
188 using blink::WebSecurityPolicy;
189 using blink::WebString;
190 using blink::WebView;
192 namespace content {
194 namespace {
196 const int64 kInitialIdleHandlerDelayMs = 1000;
197 const int64 kLongIdleHandlerDelayMs = 30*1000;
199 #if defined(OS_ANDROID)
200 // On Android, resource messages can each take ~1.5ms to dispatch on the browser
201 // IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
202 // induced work takes but a fraction (~1/4) of the overall frame budget.
203 const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
204 #else
205 const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
206 #endif
207 const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
209 // Maximum allocation size allowed for image scaling filters that
210 // require pre-scaling. Skia will fallback to a filter that doesn't
211 // require pre-scaling if the default filter would require an
212 // allocation that exceeds this limit.
213 const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
215 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden =
216 4 * 1024 * 1024;
218 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
219 // incorrectly from the wrong thread.
220 base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
221 lazy_tls = LAZY_INSTANCE_INITIALIZER;
223 class RenderViewZoomer : public RenderViewVisitor {
224 public:
225 RenderViewZoomer(const std::string& scheme,
226 const std::string& host,
227 double zoom_level) : scheme_(scheme),
228 host_(host),
229 zoom_level_(zoom_level) {
232 bool Visit(RenderView* render_view) override {
233 WebView* webview = render_view->GetWebView();
234 WebDocument document = webview->mainFrame()->document();
236 // Don't set zoom level for full-page plugin since they don't use the same
237 // zoom settings.
238 if (document.isPluginDocument())
239 return true;
240 GURL url(document.url());
241 // Empty scheme works as wildcard that matches any scheme,
242 if ((net::GetHostOrSpecFromURL(url) == host_) &&
243 (scheme_.empty() || scheme_ == url.scheme()) &&
244 !static_cast<RenderViewImpl*>(render_view)
245 ->uses_temporary_zoom_level()) {
246 webview->hidePopups();
247 webview->setZoomLevel(zoom_level_);
249 return true;
252 private:
253 const std::string scheme_;
254 const std::string host_;
255 const double zoom_level_;
257 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
260 std::string HostToCustomHistogramSuffix(const std::string& host) {
261 if (host == "mail.google.com")
262 return ".gmail";
263 if (host == "docs.google.com" || host == "drive.google.com")
264 return ".docs";
265 if (host == "plus.google.com")
266 return ".plus";
267 return std::string();
270 void* CreateHistogram(
271 const char *name, int min, int max, size_t buckets) {
272 if (min <= 0)
273 min = 1;
274 std::string histogram_name;
275 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
276 if (render_thread_impl) { // Can be null in tests.
277 histogram_name = render_thread_impl->
278 histogram_customizer()->ConvertToCustomHistogramName(name);
279 } else {
280 histogram_name = std::string(name);
282 base::HistogramBase* histogram = base::Histogram::FactoryGet(
283 histogram_name, min, max, buckets,
284 base::Histogram::kUmaTargetedHistogramFlag);
285 return histogram;
288 void AddHistogramSample(void* hist, int sample) {
289 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
290 histogram->Add(sample);
293 scoped_ptr<cc::SharedBitmap> AllocateSharedBitmapFunction(
294 const gfx::Size& size) {
295 return ChildThreadImpl::current()->shared_bitmap_manager()->
296 AllocateSharedBitmap(size);
299 void EnableBlinkPlatformLogChannels(const std::string& channels) {
300 if (channels.empty())
301 return;
302 base::StringTokenizer t(channels, ", ");
303 while (t.GetNext())
304 blink::enableLogChannel(t.token().c_str());
307 void NotifyTimezoneChangeOnThisThread() {
308 v8::Isolate* isolate = v8::Isolate::GetCurrent();
309 if (!isolate)
310 return;
311 v8::Date::DateTimeConfigurationChangeNotification(isolate);
314 void LowMemoryNotificationOnThisThread() {
315 v8::Isolate* isolate = v8::Isolate::GetCurrent();
316 if (!isolate)
317 return;
318 isolate->LowMemoryNotification();
321 class RenderFrameSetupImpl : public mojo::InterfaceImpl<RenderFrameSetup> {
322 public:
323 RenderFrameSetupImpl()
324 : routing_id_highmark_(-1) {
327 void ExchangeServiceProviders(
328 int32_t frame_routing_id,
329 mojo::InterfaceRequest<mojo::ServiceProvider> services,
330 mojo::ServiceProviderPtr exposed_services)
331 override {
332 // TODO(morrita): This is for investigating http://crbug.com/415059 and
333 // should be removed once it is fixed.
334 CHECK_LT(routing_id_highmark_, frame_routing_id);
335 routing_id_highmark_ = frame_routing_id;
337 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
338 // We can receive a GetServiceProviderForFrame message for a frame not yet
339 // created due to a race between the message and a ViewMsg_New IPC that
340 // triggers creation of the RenderFrame we want.
341 if (!frame) {
342 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
343 frame_routing_id, services.Pass(), exposed_services.Pass());
344 return;
347 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
350 private:
351 int32_t routing_id_highmark_;
354 void CreateRenderFrameSetup(mojo::InterfaceRequest<RenderFrameSetup> request) {
355 mojo::BindToRequest(new RenderFrameSetupImpl(), &request);
358 blink::WebGraphicsContext3D::Attributes GetOffscreenAttribs() {
359 blink::WebGraphicsContext3D::Attributes attributes;
360 attributes.shareResources = true;
361 attributes.depth = false;
362 attributes.stencil = false;
363 attributes.antialias = false;
364 attributes.noAutomaticFlushes = true;
365 return attributes;
368 } // namespace
370 // For measuring memory usage after each task. Behind a command line flag.
371 class MemoryObserver : public base::MessageLoop::TaskObserver {
372 public:
373 MemoryObserver() {}
374 ~MemoryObserver() override {}
376 void WillProcessTask(const base::PendingTask& pending_task) override {}
378 void DidProcessTask(const base::PendingTask& pending_task) override {
379 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
382 private:
383 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
386 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
387 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
388 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
389 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
392 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
394 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
395 const std::string& host, size_t view_count) {
396 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
397 switches::kDisableHistogramCustomizer)) {
398 return;
400 // Check if all RenderViews are displaying a page from the same host. If there
401 // is only one RenderView, the common host is this view's host. If there are
402 // many, check if this one shares the common host of the other
403 // RenderViews. It's ok to not detect some cases where the RenderViews share a
404 // common host. This information is only used for producing custom histograms.
405 if (view_count == 1)
406 SetCommonHost(host);
407 else if (host != common_host_)
408 SetCommonHost(std::string());
411 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
412 const char* histogram_name) const {
413 std::string name(histogram_name);
414 if (!common_host_histogram_suffix_.empty() &&
415 custom_histograms_.find(name) != custom_histograms_.end())
416 name += common_host_histogram_suffix_;
417 return name;
420 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
421 const std::string& host) {
422 if (host != common_host_) {
423 common_host_ = host;
424 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
425 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
429 RenderThreadImpl* RenderThreadImpl::current() {
430 return lazy_tls.Pointer()->Get();
433 // When we run plugins in process, we actually run them on the render thread,
434 // which means that we need to make the render thread pump UI events.
435 RenderThreadImpl::RenderThreadImpl()
436 : ChildThreadImpl(Options(ShouldUseMojoChannel())) {
437 Init();
440 RenderThreadImpl::RenderThreadImpl(const std::string& channel_name)
441 : ChildThreadImpl(Options(channel_name, ShouldUseMojoChannel())) {
442 Init();
445 RenderThreadImpl::RenderThreadImpl(
446 scoped_ptr<base::MessageLoop> main_message_loop)
447 : ChildThreadImpl(Options(ShouldUseMojoChannel())),
448 main_message_loop_(main_message_loop.Pass()) {
449 Init();
452 void RenderThreadImpl::Init() {
453 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
455 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
456 base::PlatformThread::CurrentId(),
457 kTraceEventRendererMainThreadSortIndex);
459 #if defined(OS_MACOSX) || defined(OS_ANDROID)
460 // On Mac and Android, the select popups are rendered by the browser.
461 blink::WebView::setUseExternalPopupMenus(true);
462 #endif
464 lazy_tls.Pointer()->Set(this);
466 // Register this object as the main thread.
467 ChildProcess::current()->set_main_thread(this);
469 // In single process the single process is all there is.
470 suspend_webkit_shared_timer_ = true;
471 notify_webkit_of_modal_loop_ = true;
472 webkit_shared_timer_suspended_ = false;
473 widget_count_ = 0;
474 hidden_widget_count_ = 0;
475 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
476 idle_notifications_to_skip_ = 0;
477 layout_test_mode_ = false;
479 appcache_dispatcher_.reset(
480 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
481 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
482 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
483 thread_safe_sender()));
484 renderer_scheduler_ = RendererScheduler::Create();
485 channel()->SetListenerTaskRunner(renderer_scheduler_->DefaultTaskRunner());
486 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
488 // Note: This may reorder messages from the ResourceDispatcher with respect to
489 // other subsystems.
490 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
491 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
492 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
493 kMaxResourceRequestsPerFlushWhenThrottled));
494 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
496 media_stream_center_ = NULL;
498 db_message_filter_ = new DBMessageFilter();
499 AddFilter(db_message_filter_.get());
501 vc_manager_.reset(new VideoCaptureImplManager());
502 AddFilter(vc_manager_->video_capture_message_filter());
504 browser_plugin_manager_.reset(new BrowserPluginManager());
505 AddObserver(browser_plugin_manager_.get());
507 #if defined(ENABLE_WEBRTC)
508 peer_connection_tracker_.reset(new PeerConnectionTracker());
509 AddObserver(peer_connection_tracker_.get());
511 p2p_socket_dispatcher_ =
512 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
513 AddFilter(p2p_socket_dispatcher_.get());
515 webrtc_identity_service_.reset(new WebRTCIdentityService());
517 aec_dump_message_filter_ =
518 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
519 message_loop()->message_loop_proxy());
520 AddFilter(aec_dump_message_filter_.get());
522 peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
523 p2p_socket_dispatcher_.get()));
524 #endif // defined(ENABLE_WEBRTC)
526 audio_input_message_filter_ =
527 new AudioInputMessageFilter(GetIOMessageLoopProxy());
528 AddFilter(audio_input_message_filter_.get());
530 audio_message_filter_ = new AudioMessageFilter(GetIOMessageLoopProxy());
531 AddFilter(audio_message_filter_.get());
533 midi_message_filter_ = new MidiMessageFilter(GetIOMessageLoopProxy());
534 AddFilter(midi_message_filter_.get());
536 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
538 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
540 GetContentClient()->renderer()->RenderThreadStarted();
542 InitSkiaEventTracer();
544 const base::CommandLine& command_line =
545 *base::CommandLine::ForCurrentProcess();
547 is_impl_side_painting_enabled_ =
548 !command_line.HasSwitch(switches::kDisableImplSidePainting);
549 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
550 is_impl_side_painting_enabled_);
552 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
553 is_one_copy_enabled_ = !command_line.HasSwitch(switches::kDisableOneCopy);
555 #if defined(OS_MACOSX) && !defined(OS_IOS)
556 is_elastic_overscroll_enabled_ =
557 !base::CommandLine::ForCurrentProcess()->HasSwitch(
558 switches::kDisableThreadedEventHandlingMac) &&
559 base::mac::IsOSLionOrLater();
560 if (is_elastic_overscroll_enabled_) {
561 base::ScopedCFTypeRef<CFStringRef> key(
562 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
563 Boolean key_exists = false;
564 Boolean value = CFPreferencesGetAppBooleanValue(
565 key, kCFPreferencesCurrentApplication, &key_exists);
566 if (key_exists && !value)
567 is_elastic_overscroll_enabled_ = false;
569 #else
570 is_elastic_overscroll_enabled_ = false;
571 #endif
573 use_image_texture_target_ = GL_TEXTURE_2D;
574 if (command_line.HasSwitch(switches::kUseImageTextureTarget)) {
575 std::string target_string =
576 command_line.GetSwitchValueASCII(switches::kUseImageTextureTarget);
577 const unsigned targets[] = {
578 GL_TEXTURE_RECTANGLE_ARB,
579 GL_TEXTURE_EXTERNAL_OES
581 for (auto target : targets) {
582 if (target_string == gpu::gles2::GLES2Util::GetStringEnum(target))
583 use_image_texture_target_ = target;
587 if (command_line.HasSwitch(switches::kDisableLCDText)) {
588 is_lcd_text_enabled_ = false;
589 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
590 is_lcd_text_enabled_ = true;
591 } else {
592 #if defined(OS_ANDROID)
593 is_lcd_text_enabled_ = false;
594 #else
595 is_lcd_text_enabled_ = true;
596 #endif
599 is_gpu_rasterization_enabled_ =
600 command_line.HasSwitch(switches::kEnableGpuRasterization);
601 is_gpu_rasterization_forced_ =
602 command_line.HasSwitch(switches::kForceGpuRasterization);
604 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
605 std::string string_value = command_line.GetSwitchValueASCII(
606 switches::kGpuRasterizationMSAASampleCount);
607 bool parsed_msaa_sample_count =
608 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
609 DCHECK(parsed_msaa_sample_count) << string_value;
610 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
611 } else {
612 gpu_rasterization_msaa_sample_count_ = 0;
614 is_threaded_gpu_rasterization_enabled_ =
615 command_line.HasSwitch(switches::kEnableThreadedGpuRasterization);
617 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
618 is_distance_field_text_enabled_ = false;
619 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
620 is_distance_field_text_enabled_ = true;
621 } else {
622 is_distance_field_text_enabled_ = false;
625 // Note that under Linux, the media library will normally already have
626 // been initialized by the Zygote before this instance became a Renderer.
627 base::FilePath media_path;
628 PathService::Get(DIR_MEDIA_LIBS, &media_path);
629 if (!media_path.empty())
630 media::InitializeMediaLibrary(media_path);
632 memory_pressure_listener_.reset(new base::MemoryPressureListener(
633 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this))));
635 std::vector<base::DiscardableMemoryType> supported_types;
636 base::DiscardableMemory::GetSupportedTypes(&supported_types);
637 DCHECK(!supported_types.empty());
639 // The default preferred type is always the first one in list.
640 base::DiscardableMemoryType type = supported_types[0];
642 if (command_line.HasSwitch(switches::kUseDiscardableMemory)) {
643 std::string requested_type_name = command_line.GetSwitchValueASCII(
644 switches::kUseDiscardableMemory);
645 base::DiscardableMemoryType requested_type =
646 base::DiscardableMemory::GetNamedType(requested_type_name);
647 if (std::find(supported_types.begin(),
648 supported_types.end(),
649 requested_type) != supported_types.end()) {
650 type = requested_type;
651 } else {
652 LOG(ERROR) << "Requested discardable memory type is not supported.";
656 base::DiscardableMemory::SetPreferredType(type);
658 if (is_impl_side_painting_enabled_) {
659 int num_raster_threads = 0;
660 std::string string_value =
661 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
662 bool parsed_num_raster_threads =
663 base::StringToInt(string_value, &num_raster_threads);
664 DCHECK(parsed_num_raster_threads) << string_value;
665 DCHECK_GT(num_raster_threads, 0);
667 // Force maximum 1 thread for threaded GPU rasterization.
668 // TODO(vmiura): crbug.com/459760 Support existence of multiple raster
669 // threads in GPU raster mode.
670 if (is_threaded_gpu_rasterization_enabled_)
671 num_raster_threads = 1;
672 cc::TileTaskWorkerPool::SetNumWorkerThreads(num_raster_threads);
674 #if defined(OS_ANDROID) || defined(OS_LINUX)
675 if (!command_line.HasSwitch(
676 switches::kUseNormalPriorityForTileTaskWorkerThreads)) {
677 cc::TileTaskWorkerPool::SetWorkerThreadPriority(
678 base::kThreadPriority_Background);
680 #endif
683 base::DiscardableMemoryShmemAllocator::SetInstance(
684 ChildThreadImpl::discardable_shared_memory_manager());
686 service_registry()->AddService<RenderFrameSetup>(
687 base::Bind(CreateRenderFrameSetup));
689 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
692 RenderThreadImpl::~RenderThreadImpl() {
695 void RenderThreadImpl::Shutdown() {
696 FOR_EACH_OBSERVER(
697 RenderProcessObserver, observers_, OnRenderProcessShutdown());
699 ChildThreadImpl::Shutdown();
701 if (memory_observer_) {
702 message_loop()->RemoveTaskObserver(memory_observer_.get());
703 memory_observer_.reset();
706 // Wait for all databases to be closed.
707 if (blink_platform_impl_) {
708 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
709 // processing timer events while we're already in the process of shutting
710 // down blink, put a ScopePageLoadDeferrer on the stack.
711 WebView::willEnterModalLoop();
712 blink_platform_impl_->web_database_observer_impl()
713 ->WaitForAllDatabasesToClose();
714 WebView::didExitModalLoop();
717 // Shutdown in reverse of the initialization order.
718 if (devtools_agent_message_filter_.get()) {
719 RemoveFilter(devtools_agent_message_filter_.get());
720 devtools_agent_message_filter_ = NULL;
723 RemoveFilter(audio_input_message_filter_.get());
724 audio_input_message_filter_ = NULL;
726 #if defined(ENABLE_WEBRTC)
727 RTCPeerConnectionHandler::DestructAllHandlers();
728 // |peer_connection_factory_| cannot be deleted until after the main message
729 // loop has been destroyed. This is because there may be pending tasks that
730 // hold on to objects produced by the PC factory that depend on threads owned
731 // by the PC factory. Once those tasks have been freed, the factory can be
732 // deleted.
733 #endif
734 RemoveFilter(vc_manager_->video_capture_message_filter());
735 vc_manager_.reset();
737 RemoveFilter(db_message_filter_.get());
738 db_message_filter_ = NULL;
740 // Shutdown the file thread if it's running.
741 if (file_thread_)
742 file_thread_->Stop();
744 if (compositor_message_filter_.get()) {
745 RemoveFilter(compositor_message_filter_.get());
746 compositor_message_filter_ = NULL;
749 media_thread_.reset();
751 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
752 RemoveFilter(audio_message_filter_.get());
753 audio_message_filter_ = NULL;
755 compositor_thread_.reset();
757 main_input_callback_.Cancel();
758 input_handler_manager_.reset();
759 if (input_event_filter_.get()) {
760 RemoveFilter(input_event_filter_.get());
761 input_event_filter_ = NULL;
764 // RemoveEmbeddedWorkerRoute may be called while deleting
765 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
766 // RenderThreadImpl.
767 embedded_worker_dispatcher_.reset();
769 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
770 // hold pointers to V8 objects (e.g., via pending requests).
771 main_thread_indexed_db_dispatcher_.reset();
773 main_thread_compositor_task_runner_ = NULL;
775 if (gpu_channel_.get())
776 gpu_channel_->DestroyChannel();
778 // TODO(port)
779 #if defined(OS_WIN)
780 // Clean up plugin channels before this thread goes away.
781 NPChannelBase::CleanupChannels();
782 #endif
784 // Shut down the message loop before shutting down Blink.
785 // This prevents a scenario where a pending task in the message loop accesses
786 // Blink objects after Blink shuts down.
787 // This must be at the very end of the shutdown sequence. You must not touch
788 // the message loop after this.
789 main_message_loop_.reset();
790 if (blink_platform_impl_)
791 blink::shutdown();
793 lazy_tls.Pointer()->Set(NULL);
796 bool RenderThreadImpl::Send(IPC::Message* msg) {
797 // Certain synchronous messages cannot always be processed synchronously by
798 // the browser, e.g., putting up UI and waiting for the user. This could cause
799 // a complete hang of Chrome if a windowed plug-in is trying to communicate
800 // with the renderer thread since the browser's UI thread could be stuck
801 // (within a Windows API call) trying to synchronously communicate with the
802 // plug-in. The remedy is to pump messages on this thread while the browser
803 // is processing this request. This creates an opportunity for re-entrancy
804 // into WebKit, so we need to take care to disable callbacks, timers, and
805 // pending network loads that could trigger such callbacks.
806 bool pumping_events = false;
807 if (msg->is_sync()) {
808 if (msg->is_caller_pumping_messages()) {
809 pumping_events = true;
813 bool suspend_webkit_shared_timer = true; // default value
814 std::swap(suspend_webkit_shared_timer, suspend_webkit_shared_timer_);
816 bool notify_webkit_of_modal_loop = true; // default value
817 std::swap(notify_webkit_of_modal_loop, notify_webkit_of_modal_loop_);
819 #if defined(ENABLE_PLUGINS)
820 int render_view_id = MSG_ROUTING_NONE;
821 #endif
823 if (pumping_events) {
824 if (suspend_webkit_shared_timer)
825 blink_platform_impl_->SuspendSharedTimer();
827 if (notify_webkit_of_modal_loop)
828 WebView::willEnterModalLoop();
829 #if defined(ENABLE_PLUGINS)
830 RenderViewImpl* render_view =
831 RenderViewImpl::FromRoutingID(msg->routing_id());
832 if (render_view) {
833 render_view_id = msg->routing_id();
834 PluginChannelHost::Broadcast(
835 new PluginMsg_SignalModalDialogEvent(render_view_id));
837 #endif
840 bool rv = ChildThreadImpl::Send(msg);
842 if (pumping_events) {
843 #if defined(ENABLE_PLUGINS)
844 if (render_view_id != MSG_ROUTING_NONE) {
845 PluginChannelHost::Broadcast(
846 new PluginMsg_ResetModalDialogEvent(render_view_id));
848 #endif
850 if (notify_webkit_of_modal_loop)
851 WebView::didExitModalLoop();
853 if (suspend_webkit_shared_timer)
854 blink_platform_impl_->ResumeSharedTimer();
857 return rv;
860 scoped_refptr<base::SingleThreadTaskRunner> RenderThreadImpl::GetTaskRunner() {
861 return GetRendererScheduler()->DefaultTaskRunner();
864 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
865 return channel();
868 std::string RenderThreadImpl::GetLocale() {
869 // The browser process should have passed the locale to the renderer via the
870 // --lang command line flag.
871 const base::CommandLine& parsed_command_line =
872 *base::CommandLine::ForCurrentProcess();
873 const std::string& lang =
874 parsed_command_line.GetSwitchValueASCII(switches::kLang);
875 DCHECK(!lang.empty());
876 return lang;
879 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
880 return sync_message_filter();
883 scoped_refptr<base::MessageLoopProxy>
884 RenderThreadImpl::GetIOMessageLoopProxy() {
885 return ChildProcess::current()->io_message_loop_proxy();
888 void RenderThreadImpl::AddRoute(int32 routing_id, IPC::Listener* listener) {
889 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
890 PendingRenderFrameConnectMap::iterator it =
891 pending_render_frame_connects_.find(routing_id);
892 if (it == pending_render_frame_connects_.end())
893 return;
895 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
896 if (!frame)
897 return;
899 scoped_refptr<PendingRenderFrameConnect> connection(it->second);
900 mojo::InterfaceRequest<mojo::ServiceProvider> services(
901 connection->services.Pass());
902 mojo::ServiceProviderPtr exposed_services(
903 connection->exposed_services.Pass());
904 pending_render_frame_connects_.erase(it);
906 frame->BindServiceRegistry(services.Pass(), exposed_services.Pass());
909 void RenderThreadImpl::RemoveRoute(int32 routing_id) {
910 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
913 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id,
914 IPC::Listener* listener) {
915 AddRoute(routing_id, listener);
916 if (devtools_agent_message_filter_.get()) {
917 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
918 routing_id);
922 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id) {
923 RemoveRoute(routing_id);
924 if (devtools_agent_message_filter_.get()) {
925 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
926 routing_id);
930 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
931 int routing_id,
932 mojo::InterfaceRequest<mojo::ServiceProvider> services,
933 mojo::ServiceProviderPtr exposed_services) {
934 std::pair<PendingRenderFrameConnectMap::iterator, bool> result =
935 pending_render_frame_connects_.insert(std::make_pair(
936 routing_id,
937 make_scoped_refptr(new PendingRenderFrameConnect(
938 services.Pass(),
939 exposed_services.Pass()))));
940 CHECK(result.second) << "Inserting a duplicate item.";
943 int RenderThreadImpl::GenerateRoutingID() {
944 int routing_id = MSG_ROUTING_NONE;
945 Send(new ViewHostMsg_GenerateRoutingID(&routing_id));
946 return routing_id;
949 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
950 channel()->AddFilter(filter);
953 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
954 channel()->RemoveFilter(filter);
957 void RenderThreadImpl::AddObserver(RenderProcessObserver* observer) {
958 observers_.AddObserver(observer);
961 void RenderThreadImpl::RemoveObserver(RenderProcessObserver* observer) {
962 observers_.RemoveObserver(observer);
965 void RenderThreadImpl::SetResourceDispatcherDelegate(
966 ResourceDispatcherDelegate* delegate) {
967 resource_dispatcher()->set_delegate(delegate);
970 void RenderThreadImpl::SetResourceDispatchTaskQueue(
971 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
972 // Add a filter that forces resource messages to be dispatched via a
973 // particular task runner.
974 resource_scheduling_filter_ =
975 new ResourceSchedulingFilter(resource_task_queue, resource_dispatcher());
976 channel()->AddFilter(resource_scheduling_filter_.get());
978 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
979 // same queue to ensure tasks are executed in the expected order.
980 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue);
981 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue);
984 void RenderThreadImpl::EnsureWebKitInitialized() {
985 if (blink_platform_impl_)
986 return;
988 const base::CommandLine& command_line =
989 *base::CommandLine::ForCurrentProcess();
991 #ifdef ENABLE_VTUNE_JIT_INTERFACE
992 if (command_line.HasSwitch(switches::kEnableVtune))
993 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
994 #endif
996 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
998 blink_platform_impl_.reset(
999 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
1000 blink::initialize(blink_platform_impl_.get());
1002 v8::Isolate* isolate = blink::mainThreadIsolate();
1003 isolate->SetCreateHistogramFunction(CreateHistogram);
1004 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1006 main_thread_compositor_task_runner_ =
1007 renderer_scheduler_->CompositorTaskRunner();
1009 main_input_callback_.Reset(
1010 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1011 base::Unretained(this)));
1013 SetResourceDispatchTaskQueue(renderer_scheduler_->LoadingTaskRunner());
1015 bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
1016 if (enable) {
1017 #if defined(OS_ANDROID)
1018 if (SynchronousCompositorFactory* factory =
1019 SynchronousCompositorFactory::GetInstance())
1020 compositor_message_loop_proxy_ =
1021 factory->GetCompositorMessageLoop();
1022 #endif
1023 if (!compositor_message_loop_proxy_.get()) {
1024 compositor_thread_.reset(new base::Thread("Compositor"));
1025 compositor_thread_->Start();
1026 #if defined(OS_ANDROID)
1027 compositor_thread_->SetPriority(base::kThreadPriority_Display);
1028 #endif
1029 compositor_message_loop_proxy_ =
1030 compositor_thread_->message_loop_proxy();
1031 compositor_message_loop_proxy_->PostTask(
1032 FROM_HERE,
1033 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1034 false));
1037 InputHandlerManagerClient* input_handler_manager_client = NULL;
1038 #if defined(OS_ANDROID)
1039 if (SynchronousCompositorFactory* factory =
1040 SynchronousCompositorFactory::GetInstance()) {
1041 input_handler_manager_client = factory->GetInputHandlerManagerClient();
1043 #endif
1044 if (!input_handler_manager_client) {
1045 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1046 new InputEventFilter(main_input_callback_.callback(),
1047 main_thread_compositor_task_runner_,
1048 compositor_message_loop_proxy_));
1049 input_handler_manager_client = compositor_input_event_filter.get();
1050 input_event_filter_ = compositor_input_event_filter;
1052 input_handler_manager_.reset(new InputHandlerManager(
1053 compositor_message_loop_proxy_, input_handler_manager_client,
1054 renderer_scheduler_.get()));
1057 if (!input_event_filter_.get()) {
1058 // Always provide an input event filter implementation to ensure consistent
1059 // input event scheduling and prioritization.
1060 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1061 // MainThreadInputEventFilter, crbug.com/436057.
1062 input_event_filter_ = new MainThreadInputEventFilter(
1063 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1065 AddFilter(input_event_filter_.get());
1067 scoped_refptr<base::MessageLoopProxy> compositor_impl_side_loop;
1068 if (enable)
1069 compositor_impl_side_loop = compositor_message_loop_proxy_;
1070 else
1071 compositor_impl_side_loop = base::MessageLoopProxy::current();
1073 compositor_message_filter_ = new CompositorForwardingMessageFilter(
1074 compositor_impl_side_loop.get());
1075 AddFilter(compositor_message_filter_.get());
1077 RenderThreadImpl::RegisterSchemes();
1079 EnableBlinkPlatformLogChannels(
1080 command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
1082 if (!media::IsMediaLibraryInitialized()) {
1083 WebRuntimeFeatures::enableWebAudio(false);
1086 RenderMediaClient::Initialize();
1088 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
1090 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1091 AddFilter(devtools_agent_message_filter_.get());
1093 v8_sampling_profiler_.reset(new V8SamplingProfiler());
1095 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1096 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1098 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction);
1100 // Limit use of the scaled image cache to when deferred image decoding is
1101 // enabled.
1102 if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
1103 !is_impl_side_painting_enabled_)
1104 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1106 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1107 kImageCacheSingleAllocationByteLimit);
1109 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1110 memory_observer_.reset(new MemoryObserver());
1111 message_loop()->AddTaskObserver(memory_observer_.get());
1115 void RenderThreadImpl::RegisterSchemes() {
1116 // swappedout: pages should not be accessible, and should also
1117 // be treated as empty documents that can commit synchronously.
1118 WebString swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme));
1119 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme);
1120 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme);
1123 void RenderThreadImpl::NotifyTimezoneChange() {
1124 NotifyTimezoneChangeOnThisThread();
1125 RenderThread::Get()->PostTaskToAllWebWorkers(
1126 base::Bind(&NotifyTimezoneChangeOnThisThread));
1129 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
1130 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1133 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
1134 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1137 scoped_ptr<base::SharedMemory>
1138 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
1139 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender());
1142 cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1143 return shared_bitmap_manager();
1146 void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
1147 WebScriptController::registerExtension(extension);
1150 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms) {
1151 idle_notification_delay_in_ms_ = initial_delay_ms;
1152 idle_timer_.Stop();
1153 idle_timer_.Start(FROM_HERE,
1154 base::TimeDelta::FromMilliseconds(initial_delay_ms),
1155 this, &RenderThreadImpl::IdleHandler);
1158 void RenderThreadImpl::IdleHandler() {
1159 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
1160 GetContentClient()->renderer()->
1161 RunIdleHandlerWhenWidgetsHidden();
1162 if (run_in_foreground_tab) {
1163 if (idle_notifications_to_skip_ > 0) {
1164 --idle_notifications_to_skip_;
1165 } else {
1166 base::allocator::ReleaseFreeMemory();
1167 base::DiscardableMemory::ReduceMemoryUsage();
1169 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1170 return;
1173 base::allocator::ReleaseFreeMemory();
1174 discardable_shared_memory_manager()->ReleaseFreeMemory();
1176 // Continue the idle timer if the webkit shared timer is not suspended or
1177 // something is left to do.
1178 bool continue_timer = !webkit_shared_timer_suspended_;
1180 if (blink::mainThreadIsolate() &&
1181 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1182 continue_timer = true;
1184 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1185 continue_timer = true;
1188 // Schedule next invocation. When the tab is originally hidden, an invocation
1189 // is scheduled for kInitialIdleHandlerDelayMs in
1190 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1191 // After that, idle calls can be much less frequent, so run at a maximum of
1192 // once every kLongIdleHandlerDelayMs.
1193 // Dampen the delay using the algorithm (if delay is in seconds):
1194 // delay = delay + 1 / (delay + 2)
1195 // Using floor(delay) has a dampening effect such as:
1196 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1197 // If the delay is in milliseconds, the above formula is equivalent to:
1198 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1199 // which is equivalent to
1200 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1201 if (continue_timer) {
1202 ScheduleIdleHandler(
1203 std::max(kLongIdleHandlerDelayMs,
1204 idle_notification_delay_in_ms_ +
1205 1000000 / (idle_notification_delay_in_ms_ + 2000)));
1207 } else {
1208 idle_timer_.Stop();
1211 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, IdleNotification());
1214 int64 RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1215 return idle_notification_delay_in_ms_;
1218 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1219 int64 idle_notification_delay_in_ms) {
1220 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
1223 void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1224 child_histogram_message_filter()->SendHistograms(sequence_number);
1227 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
1228 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure);
1231 bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1232 bool result = false;
1233 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1234 return result;
1237 void RenderThreadImpl::PostponeIdleNotification() {
1238 idle_notifications_to_skip_ = 2;
1241 scoped_refptr<media::GpuVideoAcceleratorFactories>
1242 RenderThreadImpl::GetGpuFactories() {
1243 DCHECK(IsMainThread());
1245 scoped_refptr<GpuChannelHost> gpu_channel_host = GetGpuChannel();
1246 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1247 scoped_refptr<media::GpuVideoAcceleratorFactories> gpu_factories;
1248 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1249 GetMediaThreadTaskRunner();
1250 if (!cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
1251 if (!gpu_va_context_provider_.get() ||
1252 gpu_va_context_provider_->DestroyedOnMainThread()) {
1253 if (!gpu_channel_host.get()) {
1254 gpu_channel_host = EstablishGpuChannelSync(
1255 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);
1257 blink::WebGraphicsContext3D::Attributes attributes;
1258 bool lose_context_when_out_of_memory = false;
1259 gpu_va_context_provider_ = ContextProviderCommandBuffer::Create(
1260 make_scoped_ptr(
1261 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1262 gpu_channel_host.get(),
1263 attributes,
1264 lose_context_when_out_of_memory,
1265 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1266 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1267 NULL)),
1268 "GPU-VideoAccelerator-Offscreen");
1271 if (gpu_va_context_provider_.get()) {
1272 gpu_factories = RendererGpuVideoAcceleratorFactories::Create(
1273 gpu_channel_host.get(), media_task_runner, gpu_va_context_provider_);
1275 return gpu_factories;
1278 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
1279 RenderThreadImpl::CreateOffscreenContext3d() {
1280 blink::WebGraphicsContext3D::Attributes attributes(GetOffscreenAttribs());
1281 bool lose_context_when_out_of_memory = true;
1283 scoped_refptr<GpuChannelHost> gpu_channel_host(EstablishGpuChannelSync(
1284 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE));
1285 return make_scoped_ptr(
1286 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1287 gpu_channel_host.get(),
1288 attributes,
1289 lose_context_when_out_of_memory,
1290 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1291 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1292 NULL));
1295 scoped_refptr<cc_blink::ContextProviderWebContext>
1296 RenderThreadImpl::SharedMainThreadContextProvider() {
1297 DCHECK(IsMainThread());
1298 if (!shared_main_thread_contexts_.get() ||
1299 shared_main_thread_contexts_->DestroyedOnMainThread()) {
1300 shared_main_thread_contexts_ = NULL;
1301 #if defined(OS_ANDROID)
1302 if (SynchronousCompositorFactory* factory =
1303 SynchronousCompositorFactory::GetInstance()) {
1304 shared_main_thread_contexts_ = factory->CreateOffscreenContextProvider(
1305 GetOffscreenAttribs(), "Offscreen-MainThread");
1307 #endif
1308 if (!shared_main_thread_contexts_.get()) {
1309 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
1310 CreateOffscreenContext3d(), "Offscreen-MainThread");
1312 if (shared_main_thread_contexts_.get() &&
1313 !shared_main_thread_contexts_->BindToCurrentThread())
1314 shared_main_thread_contexts_ = NULL;
1316 return shared_main_thread_contexts_;
1319 AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
1320 if (!audio_renderer_mixer_manager_) {
1321 audio_renderer_mixer_manager_.reset(new AudioRendererMixerManager(
1322 GetAudioHardwareConfig()));
1325 return audio_renderer_mixer_manager_.get();
1328 media::AudioHardwareConfig* RenderThreadImpl::GetAudioHardwareConfig() {
1329 if (!audio_hardware_config_) {
1330 media::AudioParameters input_params;
1331 media::AudioParameters output_params;
1332 Send(new ViewHostMsg_GetAudioHardwareConfig(
1333 &input_params, &output_params));
1335 audio_hardware_config_.reset(new media::AudioHardwareConfig(
1336 input_params, output_params));
1337 audio_message_filter_->SetAudioHardwareConfig(audio_hardware_config_.get());
1340 return audio_hardware_config_.get();
1343 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1344 return ChildProcess::current()->GetShutDownEvent();
1347 #if defined(OS_WIN)
1348 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT& log_font,
1349 const base::string16& str) {
1350 Send(new ViewHostMsg_PreCacheFontCharacters(log_font, str));
1353 #endif // OS_WIN
1355 ServiceRegistry* RenderThreadImpl::GetServiceRegistry() {
1356 return service_registry();
1359 bool RenderThreadImpl::IsImplSidePaintingEnabled() {
1360 return is_impl_side_painting_enabled_;
1363 bool RenderThreadImpl::IsGpuRasterizationForced() {
1364 return is_gpu_rasterization_forced_;
1367 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1368 return is_gpu_rasterization_enabled_;
1371 bool RenderThreadImpl::IsThreadedGpuRasterizationEnabled() {
1372 return is_threaded_gpu_rasterization_enabled_;
1375 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1376 return gpu_rasterization_msaa_sample_count_;
1379 bool RenderThreadImpl::IsLcdTextEnabled() {
1380 return is_lcd_text_enabled_;
1383 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1384 return is_distance_field_text_enabled_;
1387 bool RenderThreadImpl::IsZeroCopyEnabled() {
1388 return is_zero_copy_enabled_;
1391 bool RenderThreadImpl::IsOneCopyEnabled() {
1392 return is_one_copy_enabled_;
1395 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1396 return is_elastic_overscroll_enabled_;
1399 bool RenderThreadImpl::UseSingleThreadScheduler() {
1400 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
1401 return !cmd->HasSwitch(switches::kDisableSingleThreadProxyScheduler);
1404 uint32 RenderThreadImpl::GetImageTextureTarget() {
1405 return use_image_texture_target_;
1408 scoped_refptr<base::SingleThreadTaskRunner>
1409 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1410 return main_thread_compositor_task_runner_;
1413 scoped_refptr<base::SingleThreadTaskRunner>
1414 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1415 return compositor_message_loop_proxy_;
1418 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1419 return gpu_memory_buffer_manager();
1422 RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
1423 return renderer_scheduler_.get();
1426 cc::ContextProvider* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1427 return SharedMainThreadContextProvider().get();
1430 scoped_ptr<cc::BeginFrameSource>
1431 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
1432 #if defined(OS_ANDROID)
1433 if (SynchronousCompositorFactory* factory =
1434 SynchronousCompositorFactory::GetInstance()) {
1435 return factory->CreateExternalBeginFrameSource(routing_id);
1437 #endif
1438 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1439 compositor_message_filter_.get(), sync_message_filter(), routing_id));
1442 bool RenderThreadImpl::IsMainThread() {
1443 return !!current();
1446 base::MessageLoop* RenderThreadImpl::GetMainLoop() {
1447 return message_loop();
1450 scoped_refptr<base::MessageLoopProxy> RenderThreadImpl::GetIOLoopProxy() {
1451 return io_message_loop_proxy_;
1454 scoped_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
1455 size_t size) {
1456 return scoped_ptr<base::SharedMemory>(
1457 HostAllocateSharedMemoryBuffer(size));
1460 CreateCommandBufferResult RenderThreadImpl::CreateViewCommandBuffer(
1461 int32 surface_id,
1462 const GPUCreateCommandBufferConfig& init_params,
1463 int32 route_id) {
1464 TRACE_EVENT1("gpu",
1465 "RenderThreadImpl::CreateViewCommandBuffer",
1466 "surface_id",
1467 surface_id);
1469 CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;
1470 IPC::Message* message = new GpuHostMsg_CreateViewCommandBuffer(
1471 surface_id,
1472 init_params,
1473 route_id,
1474 &result);
1476 // Allow calling this from the compositor thread.
1477 thread_safe_sender()->Send(message);
1479 return result;
1482 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1483 suspend_webkit_shared_timer_ = false;
1486 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1487 notify_webkit_of_modal_loop_ = false;
1490 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1491 ObserverListBase<RenderProcessObserver>::Iterator it(observers_);
1492 RenderProcessObserver* observer;
1493 while ((observer = it.GetNext()) != NULL) {
1494 if (observer->OnControlMessageReceived(msg))
1495 return true;
1498 // Some messages are handled by delegates.
1499 if (appcache_dispatcher_->OnMessageReceived(msg) ||
1500 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1501 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
1502 return true;
1505 bool handled = true;
1506 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
1507 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame)
1508 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy)
1509 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL,
1510 OnSetZoomLevelForCurrentURL)
1511 // TODO(port): removed from render_messages_internal.h;
1512 // is there a new non-windows message I should add here?
1513 IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
1514 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged)
1515 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData)
1516 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
1517 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1518 #if defined(OS_ANDROID)
1519 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended,
1520 OnSetWebKitSharedTimersSuspended)
1521 #endif
1522 #if defined(OS_MACOSX)
1523 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme)
1524 #endif
1525 #if defined(ENABLE_PLUGINS)
1526 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache)
1527 #endif
1528 IPC_MESSAGE_UNHANDLED(handled = false)
1529 IPC_END_MESSAGE_MAP()
1530 return handled;
1533 void RenderThreadImpl::OnCreateNewFrame(
1534 int routing_id,
1535 int parent_routing_id,
1536 int proxy_routing_id,
1537 const FrameReplicationState& replicated_state,
1538 FrameMsg_NewFrame_WidgetParams params) {
1539 CompositorDependencies* compositor_deps = this;
1540 RenderFrameImpl::CreateFrame(routing_id, parent_routing_id, proxy_routing_id,
1541 replicated_state, compositor_deps, params);
1544 void RenderThreadImpl::OnCreateNewFrameProxy(
1545 int routing_id,
1546 int parent_routing_id,
1547 int render_view_routing_id,
1548 const FrameReplicationState& replicated_state) {
1549 RenderFrameProxy::CreateFrameProxy(routing_id, parent_routing_id,
1550 render_view_routing_id, replicated_state);
1553 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string& scheme,
1554 const std::string& host,
1555 double zoom_level) {
1556 RenderViewZoomer zoomer(scheme, host, zoom_level);
1557 RenderView::ForEach(&zoomer);
1560 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) {
1561 EnsureWebKitInitialized();
1562 CompositorDependencies* compositor_deps = this;
1563 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1564 RenderViewImpl::Create(params, compositor_deps, false);
1567 GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
1568 CauseForGpuLaunch cause_for_gpu_launch) {
1569 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1571 if (gpu_channel_.get()) {
1572 // Do nothing if we already have a GPU channel or are already
1573 // establishing one.
1574 if (!gpu_channel_->IsLost())
1575 return gpu_channel_.get();
1577 // Recreate the channel if it has been lost.
1578 gpu_channel_ = NULL;
1581 // Ask the browser for the channel name.
1582 int client_id = 0;
1583 IPC::ChannelHandle channel_handle;
1584 gpu::GPUInfo gpu_info;
1585 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
1586 &client_id,
1587 &channel_handle,
1588 &gpu_info)) ||
1589 #if defined(OS_POSIX)
1590 channel_handle.socket.fd == -1 ||
1591 #endif
1592 channel_handle.name.empty()) {
1593 // Otherwise cancel the connection.
1594 return NULL;
1597 GetContentClient()->SetGpuInfo(gpu_info);
1599 // Cache some variables that are needed on the compositor thread for our
1600 // implementation of GpuChannelHostFactory.
1601 io_message_loop_proxy_ = ChildProcess::current()->io_message_loop_proxy();
1603 gpu_channel_ =
1604 GpuChannelHost::Create(this,
1605 gpu_info,
1606 channel_handle,
1607 ChildProcess::current()->GetShutDownEvent(),
1608 gpu_memory_buffer_manager());
1609 return gpu_channel_.get();
1612 blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
1613 blink::WebMediaStreamCenterClient* client) {
1614 #if defined(OS_ANDROID)
1615 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1616 switches::kDisableWebRTC))
1617 return NULL;
1618 #endif
1620 #if defined(ENABLE_WEBRTC)
1621 if (!media_stream_center_) {
1622 media_stream_center_ = GetContentClient()->renderer()
1623 ->OverrideCreateWebMediaStreamCenter(client);
1624 if (!media_stream_center_) {
1625 scoped_ptr<MediaStreamCenter> media_stream_center(
1626 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
1627 media_stream_center_ = media_stream_center.release();
1630 #endif
1631 return media_stream_center_;
1634 #if defined(ENABLE_WEBRTC)
1635 PeerConnectionDependencyFactory*
1636 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1637 return peer_connection_factory_.get();
1639 #endif
1641 GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1642 if (!gpu_channel_.get())
1643 return NULL;
1645 if (gpu_channel_->IsLost())
1646 return NULL;
1648 return gpu_channel_.get();
1651 #if defined(ENABLE_PLUGINS)
1652 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages) {
1653 EnsureWebKitInitialized();
1654 // The call below will cause a GetPlugins call with refresh=true, but at this
1655 // point we already know that the browser has refreshed its list, so disable
1656 // refresh temporarily to prevent each renderer process causing the list to be
1657 // regenerated.
1658 blink_platform_impl_->set_plugin_refresh_allowed(false);
1659 blink::resetPluginCache(reload_pages);
1660 blink_platform_impl_->set_plugin_refresh_allowed(true);
1662 FOR_EACH_OBSERVER(RenderProcessObserver, observers_, PluginListChanged());
1664 #endif
1666 void RenderThreadImpl::OnNetworkTypeChanged(
1667 net::NetworkChangeNotifier::ConnectionType type) {
1668 EnsureWebKitInitialized();
1669 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1670 WebNetworkStateNotifier::setOnLine(online);
1671 FOR_EACH_OBSERVER(
1672 RenderProcessObserver, observers_, NetworkStateChanged(online));
1673 WebNetworkStateNotifier::setWebConnectionType(
1674 NetConnectionTypeToWebConnectionType(type));
1677 void RenderThreadImpl::OnTempCrashWithData(const GURL& data) {
1678 GetContentClient()->SetActiveURL(data);
1679 CHECK(false);
1682 void RenderThreadImpl::OnUpdateTimezone() {
1683 if (!blink_platform_impl_)
1684 return;
1685 NotifyTimezoneChange();
1688 #if defined(OS_ANDROID)
1689 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend) {
1690 if (suspend_webkit_shared_timer_) {
1691 EnsureWebKitInitialized();
1692 if (suspend) {
1693 blink_platform_impl_->SuspendSharedTimer();
1694 } else {
1695 blink_platform_impl_->ResumeSharedTimer();
1697 webkit_shared_timer_suspended_ = suspend;
1700 #endif
1702 #if defined(OS_MACOSX)
1703 void RenderThreadImpl::OnUpdateScrollbarTheme(
1704 float initial_button_delay,
1705 float autoscroll_button_delay,
1706 bool jump_on_track_click,
1707 blink::ScrollerStyle preferred_scroller_style,
1708 bool redraw) {
1709 EnsureWebKitInitialized();
1710 static_cast<WebScrollbarBehaviorImpl*>(
1711 blink_platform_impl_->scrollbarBehavior())
1712 ->set_jump_on_track_click(jump_on_track_click);
1713 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay,
1714 autoscroll_button_delay,
1715 preferred_scroller_style,
1716 redraw);
1718 #endif
1720 void RenderThreadImpl::OnCreateNewSharedWorker(
1721 const WorkerProcessMsg_CreateWorker_Params& params) {
1722 // EmbeddedSharedWorkerStub will self-destruct.
1723 new EmbeddedSharedWorkerStub(params.url,
1724 params.name,
1725 params.content_security_policy,
1726 params.security_policy_type,
1727 params.pause_on_start,
1728 params.route_id);
1731 void RenderThreadImpl::OnMemoryPressure(
1732 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1733 base::allocator::ReleaseFreeMemory();
1735 // Do not call into blink if it is not initialized.
1736 if (blink_platform_impl_) {
1737 blink::WebCache::pruneAll();
1739 if (blink::mainThreadIsolate()) {
1740 // Trigger full v8 garbage collection on memory pressure notifications.
1741 // This will potentially hang the renderer for a long time, however, when
1742 // we receive a memory pressure notification, we might be about to be
1743 // killed.
1744 blink::mainThreadIsolate()->LowMemoryNotification();
1745 RenderThread::Get()->PostTaskToAllWebWorkers(
1746 base::Bind(&LowMemoryNotificationOnThisThread));
1749 if (memory_pressure_level ==
1750 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1751 // Clear the image cache.
1752 blink::WebImageCache::clear();
1754 // Purge Skia font cache, by setting it to 0 and then again to the
1755 // previous limit.
1756 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
1757 SkGraphics::SetFontCacheLimit(font_cache_limit);
1762 scoped_refptr<base::MessageLoopProxy>
1763 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1764 DCHECK(message_loop() == base::MessageLoop::current());
1765 if (!file_thread_) {
1766 file_thread_.reset(new base::Thread("Renderer::FILE"));
1767 file_thread_->Start();
1769 return file_thread_->message_loop_proxy();
1772 scoped_refptr<base::SingleThreadTaskRunner>
1773 RenderThreadImpl::GetMediaThreadTaskRunner() {
1774 DCHECK(message_loop() == base::MessageLoop::current());
1775 if (!media_thread_) {
1776 media_thread_.reset(new base::Thread("Media"));
1777 media_thread_->Start();
1779 #if defined(OS_ANDROID)
1780 renderer_demuxer_ = new RendererDemuxerAndroid();
1781 AddFilter(renderer_demuxer_.get());
1782 #endif
1784 return media_thread_->message_loop_proxy();
1787 void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
1788 blink_platform_impl_->sampleGamepads(*data);
1791 void RenderThreadImpl::WidgetCreated() {
1792 widget_count_++;
1795 void RenderThreadImpl::WidgetDestroyed() {
1796 widget_count_--;
1799 void RenderThreadImpl::WidgetHidden() {
1800 DCHECK_LT(hidden_widget_count_, widget_count_);
1801 hidden_widget_count_++;
1803 if (widget_count_ && hidden_widget_count_ == widget_count_) {
1804 // TODO(reveman): Remove this when we have a better mechanism to prevent
1805 // total discardable memory used by all renderers from growing too large.
1806 base::internal::DiscardableMemoryEmulated::
1807 ReduceMemoryUsageUntilWithinLimit(
1808 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden);
1810 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1811 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
1815 void RenderThreadImpl::WidgetRestored() {
1816 DCHECK_GT(hidden_widget_count_, 0);
1817 hidden_widget_count_--;
1819 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1820 return;
1823 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
1826 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1827 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1828 mojo::ServiceProviderPtr exposed_services)
1829 : services(services.Pass()),
1830 exposed_services(exposed_services.Pass()) {
1833 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1836 } // namespace content