[content shell] implement testRunner.overridePreference
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobfd98057a01f35c3fbfb17426fd45ce00a5a4228b
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/browser/browser_main_loop.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/debug/trace_event.h"
10 #include "base/hi_res_timer_manager.h"
11 #include "base/logging.h"
12 #include "base/message_loop.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram.h"
15 #include "base/run_loop.h"
16 #include "base/string_number_conversions.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "content/browser/browser_thread_impl.h"
19 #include "content/browser/download/save_file_manager.h"
20 #include "content/browser/gamepad/gamepad_service.h"
21 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
22 #include "content/browser/gpu/gpu_data_manager_impl.h"
23 #include "content/browser/gpu/gpu_process_host.h"
24 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
25 #include "content/browser/histogram_synchronizer.h"
26 #include "content/browser/in_process_webkit/webkit_thread.h"
27 #include "content/browser/loader/resource_dispatcher_host_impl.h"
28 #include "content/browser/net/browser_online_state_observer.h"
29 #include "content/browser/plugin_service_impl.h"
30 #include "content/browser/renderer_host/media/media_stream_manager.h"
31 #include "content/browser/speech/speech_recognition_manager_impl.h"
32 #include "content/browser/trace_controller_impl.h"
33 #include "content/public/browser/browser_main_parts.h"
34 #include "content/public/browser/browser_shutdown.h"
35 #include "content/public/browser/compositor_util.h"
36 #include "content/public/browser/content_browser_client.h"
37 #include "content/public/browser/render_process_host.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/main_function_params.h"
40 #include "content/public/common/result_codes.h"
41 #include "crypto/nss_util.h"
42 #include "media/audio/audio_manager.h"
43 #include "net/base/network_change_notifier.h"
44 #include "net/base/ssl_config_service.h"
45 #include "net/socket/client_socket_factory.h"
46 #include "net/socket/tcp_client_socket.h"
47 #include "ui/base/clipboard/clipboard.h"
49 #if defined(USE_AURA)
50 #include "content/browser/renderer_host/image_transport_factory.h"
51 #endif
53 #if defined(OS_ANDROID)
54 #include "base/android/jni_android.h"
55 #include "content/browser/android/surface_texture_peer_browser_impl.h"
56 #include "content/browser/device_orientation/data_fetcher_impl_android.h"
57 #endif
59 #if defined(OS_WIN)
60 #include <windows.h>
61 #include <commctrl.h>
62 #include <shellapi.h>
64 #include "content/browser/system_message_window_win.h"
65 #include "content/common/sandbox_policy.h"
66 #include "ui/base/l10n/l10n_util_win.h"
67 #include "net/base/winsock_init.h"
68 #endif
70 #if defined(OS_LINUX) || defined(OS_OPENBSD)
71 #include <glib-object.h>
72 #endif
74 #if defined(OS_LINUX)
75 #include "content/browser/device_monitor_linux.h"
76 #elif defined(OS_MACOSX) && !defined(OS_IOS)
77 #include "content/browser/device_monitor_mac.h"
78 #endif
80 #if defined(TOOLKIT_GTK)
81 #include "ui/gfx/gtk_util.h"
82 #endif
84 #if defined(OS_POSIX) && !defined(OS_MACOSX)
85 #include <sys/stat.h>
87 #include "base/process_util.h"
88 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
89 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
90 #endif
92 #if defined(USE_X11)
93 #include <X11/Xlib.h>
94 #endif
96 // One of the linux specific headers defines this as a macro.
97 #ifdef DestroyAll
98 #undef DestroyAll
99 #endif
101 namespace content {
102 namespace {
104 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
105 void SetupSandbox(const CommandLine& parsed_command_line) {
106 // TODO(evanm): move this into SandboxWrapper; I'm just trying to move this
107 // code en masse out of chrome_main for now.
108 const char* sandbox_binary = NULL;
109 struct stat st;
111 // In Chromium branded builds, developers can set an environment variable to
112 // use the development sandbox. See
113 // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
114 if (stat(base::kProcSelfExe, &st) == 0 && st.st_uid == getuid())
115 sandbox_binary = getenv("CHROME_DEVEL_SANDBOX");
117 #if defined(LINUX_SANDBOX_PATH)
118 if (!sandbox_binary)
119 sandbox_binary = LINUX_SANDBOX_PATH;
120 #endif
122 std::string sandbox_cmd;
123 if (sandbox_binary && !parsed_command_line.HasSwitch(switches::kNoSandbox))
124 sandbox_cmd = sandbox_binary;
126 // Tickle the sandbox host and zygote host so they fork now.
127 RenderSandboxHostLinux::GetInstance()->Init(sandbox_cmd);
128 ZygoteHostImpl::GetInstance()->Init(sandbox_cmd);
130 #endif
132 #if defined(OS_LINUX) || defined(OS_OPENBSD)
133 static void GLibLogHandler(const gchar* log_domain,
134 GLogLevelFlags log_level,
135 const gchar* message,
136 gpointer userdata) {
137 if (!log_domain)
138 log_domain = "<unknown>";
139 if (!message)
140 message = "<no message>";
142 if (strstr(message, "Loading IM context type") ||
143 strstr(message, "wrong ELF class: ELFCLASS64")) {
144 // http://crbug.com/9643
145 // Until we have a real 64-bit build or all of these 32-bit package issues
146 // are sorted out, don't fatal on ELF 32/64-bit mismatch warnings and don't
147 // spam the user with more than one of them.
148 static bool alerted = false;
149 if (!alerted) {
150 LOG(ERROR) << "Bug 9643: " << log_domain << ": " << message;
151 alerted = true;
153 } else if (strstr(message, "Unable to retrieve the file info for")) {
154 LOG(ERROR) << "GTK File code error: " << message;
155 } else if (strstr(message, "Theme file for default has no") ||
156 strstr(message, "Theme directory") ||
157 strstr(message, "theme pixmap") ||
158 strstr(message, "locate theme engine")) {
159 LOG(ERROR) << "GTK theme error: " << message;
160 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
161 strstr(log_domain, "<unknown>")) {
162 LOG(ERROR) << "GTK menu proxy create failed";
163 } else if (strstr(message, "gtk_drag_dest_leave: assertion")) {
164 LOG(ERROR) << "Drag destination deleted: http://crbug.com/18557";
165 } else if (strstr(message, "Out of memory") &&
166 strstr(log_domain, "<unknown>")) {
167 LOG(ERROR) << "DBus call timeout or out of memory: "
168 << "http://crosbug.com/15496";
169 } else if (strstr(message, "XDG_RUNTIME_DIR variable not set")) {
170 LOG(ERROR) << message << " (http://bugs.chromium.org/97293)";
171 } else if (strstr(message, "Attempting to store changes into") ||
172 strstr(message, "Attempting to set the permissions of")) {
173 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
174 } else {
175 LOG(DFATAL) << log_domain << ": " << message;
179 static void SetUpGLibLogHandler() {
180 // Register GLib-handled assertions to go through our logging system.
181 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
182 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
183 g_log_set_handler(kLogDomains[i],
184 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
185 G_LOG_FLAG_FATAL |
186 G_LOG_LEVEL_ERROR |
187 G_LOG_LEVEL_CRITICAL |
188 G_LOG_LEVEL_WARNING),
189 GLibLogHandler,
190 NULL);
193 #endif
195 } // namespace
197 // The currently-running BrowserMainLoop. There can be one or zero.
198 BrowserMainLoop* g_current_browser_main_loop = NULL;
200 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
201 // the public interface of BrowserMainLoop.
202 class BrowserShutdownImpl {
203 public:
204 static void ImmediateShutdownAndExitProcess() {
205 DCHECK(g_current_browser_main_loop);
206 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
208 #if defined(OS_WIN)
209 // At this point the message loop is still running yet we've shut everything
210 // down. If any messages are processed we'll likely crash. Exit now.
211 ExitProcess(RESULT_CODE_NORMAL_EXIT);
212 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
213 _exit(RESULT_CODE_NORMAL_EXIT);
214 #else
215 NOTIMPLEMENTED();
216 #endif
220 void ImmediateShutdownAndExitProcess() {
221 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
224 // static
225 media::AudioManager* BrowserMainLoop::GetAudioManager() {
226 return g_current_browser_main_loop->audio_manager_.get();
229 // static
230 MediaStreamManager* BrowserMainLoop::GetMediaStreamManager() {
231 return g_current_browser_main_loop->media_stream_manager_.get();
233 // BrowserMainLoop construction / destruction =============================
235 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
236 : parameters_(parameters),
237 parsed_command_line_(parameters.command_line),
238 result_code_(RESULT_CODE_NORMAL_EXIT) {
239 DCHECK(!g_current_browser_main_loop);
240 g_current_browser_main_loop = this;
243 BrowserMainLoop::~BrowserMainLoop() {
244 DCHECK_EQ(this, g_current_browser_main_loop);
245 #if !defined(OS_IOS)
246 ui::Clipboard::DestroyClipboardForCurrentThread();
247 #endif // !defined(OS_IOS)
248 g_current_browser_main_loop = NULL;
251 void BrowserMainLoop::Init() {
252 parts_.reset(
253 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
256 // BrowserMainLoop stages ==================================================
258 void BrowserMainLoop::EarlyInitialization() {
259 #if defined(USE_X11)
260 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
261 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
262 if (!XInitThreads()) {
263 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
266 #endif
268 if (parts_.get())
269 parts_->PreEarlyInitialization();
271 #if defined(OS_WIN)
272 net::EnsureWinsockInit();
273 #endif
275 #if !defined(USE_OPENSSL)
276 // Use NSS for SSL by default.
277 // The default client socket factory uses NSS for SSL by default on
278 // Windows and Mac.
279 bool init_nspr = false;
280 #if defined(OS_WIN) || defined(OS_MACOSX)
281 if (parsed_command_line_.HasSwitch(switches::kUseSystemSSL)) {
282 net::ClientSocketFactory::UseSystemSSL();
283 } else {
284 init_nspr = true;
286 UMA_HISTOGRAM_BOOLEAN("Chrome.CommandLineUseSystemSSL", !init_nspr);
287 #elif defined(USE_NSS)
288 init_nspr = true;
289 #endif
290 if (init_nspr) {
291 // We want to be sure to init NSPR on the main thread.
292 crypto::EnsureNSPRInit();
294 #endif // !defined(USE_OPENSSL)
296 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
297 SetupSandbox(parsed_command_line_);
298 #endif
300 if (parsed_command_line_.HasSwitch(switches::kEnableSSLCachedInfo))
301 net::SSLConfigService::EnableCachedInfo();
303 // TODO(abarth): Should this move to InitializeNetworkOptions? This doesn't
304 // seem dependent on SSL initialization().
305 if (parsed_command_line_.HasSwitch(switches::kEnableTcpFastOpen))
306 net::set_tcp_fastopen_enabled(true);
308 #if !defined(OS_IOS)
309 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
310 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
311 switches::kRendererProcessLimit);
312 size_t process_limit;
313 if (base::StringToSizeT(limit_string, &process_limit)) {
314 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
317 #endif // !defined(OS_IOS)
319 if (parts_.get())
320 parts_->PostEarlyInitialization();
323 void BrowserMainLoop::MainMessageLoopStart() {
324 if (parts_.get())
325 parts_->PreMainMessageLoopStart();
327 #if defined(OS_WIN)
328 // If we're running tests (ui_task is non-null), then the ResourceBundle
329 // has already been initialized.
330 if (!parameters_.ui_task) {
331 // Override the configured locale with the user's preferred UI language.
332 l10n_util::OverrideLocaleWithUILanguageList();
334 #endif
336 // Create a MessageLoop if one does not already exist for the current thread.
337 if (!MessageLoop::current())
338 main_message_loop_.reset(new MessageLoop(MessageLoop::TYPE_UI));
340 InitializeMainThread();
342 system_monitor_.reset(new base::SystemMonitor);
343 hi_res_timer_manager_.reset(new HighResolutionTimerManager);
344 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
345 audio_manager_.reset(media::AudioManager::Create());
347 #if !defined(OS_IOS)
348 // Start tracing to a file if needed.
349 if (base::debug::TraceLog::GetInstance()->IsEnabled()) {
350 TraceControllerImpl::GetInstance()->InitStartupTracing(
351 parsed_command_line_);
354 online_state_observer_.reset(new BrowserOnlineStateObserver);
356 // Prior to any processing happening on the io thread, we create the
357 // plugin service as it is predominantly used from the io thread,
358 // but must be created on the main thread. The service ctor is
359 // inexpensive and does not invoke the io_thread() accessor.
360 PluginService::GetInstance()->Init();
361 #endif // !defined(OS_IOS)
363 #if defined(OS_WIN)
364 system_message_window_.reset(new SystemMessageWindowWin);
365 #endif
367 if (parts_.get())
368 parts_->PostMainMessageLoopStart();
370 #if defined(OS_ANDROID)
371 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl(
372 parameters_.command_line.HasSwitch(
373 switches::kMediaPlayerInRenderProcess)));
374 DataFetcherImplAndroid::Init(base::android::AttachCurrentThread());
375 #endif
378 void BrowserMainLoop::CreateThreads() {
379 if (parts_.get())
380 result_code_ = parts_->PreCreateThreads();
382 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
383 // Single-process is an unsupported and not fully tested mode, so
384 // don't enable it for official Chrome builds (except on Android).
385 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
386 RenderProcessHost::SetRunRendererInProcess(true);
387 #endif
389 if (result_code_ > 0)
390 return;
392 base::Thread::Options default_options;
393 base::Thread::Options io_message_loop_options;
394 io_message_loop_options.message_loop_type = MessageLoop::TYPE_IO;
395 base::Thread::Options ui_message_loop_options;
396 ui_message_loop_options.message_loop_type = MessageLoop::TYPE_UI;
398 // Start threads in the order they occur in the BrowserThread::ID
399 // enumeration, except for BrowserThread::UI which is the main
400 // thread.
402 // Must be size_t so we can increment it.
403 for (size_t thread_id = BrowserThread::UI + 1;
404 thread_id < BrowserThread::ID_COUNT;
405 ++thread_id) {
406 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
407 base::Thread::Options* options = &default_options;
409 switch (thread_id) {
410 case BrowserThread::DB:
411 thread_to_start = &db_thread_;
412 break;
413 case BrowserThread::WEBKIT_DEPRECATED:
414 // Special case as WebKitThread is a separate
415 // type. |thread_to_start| is not used in this case.
416 break;
417 case BrowserThread::FILE_USER_BLOCKING:
418 thread_to_start = &file_user_blocking_thread_;
419 break;
420 case BrowserThread::FILE:
421 thread_to_start = &file_thread_;
422 #if defined(OS_WIN)
423 // On Windows, the FILE thread needs to be have a UI message loop
424 // which pumps messages in such a way that Google Update can
425 // communicate back to us.
426 options = &ui_message_loop_options;
427 #else
428 options = &io_message_loop_options;
429 #endif
430 break;
431 case BrowserThread::PROCESS_LAUNCHER:
432 thread_to_start = &process_launcher_thread_;
433 break;
434 case BrowserThread::CACHE:
435 thread_to_start = &cache_thread_;
436 options = &io_message_loop_options;
437 break;
438 case BrowserThread::IO:
439 thread_to_start = &io_thread_;
440 options = &io_message_loop_options;
441 break;
442 case BrowserThread::UI:
443 case BrowserThread::ID_COUNT:
444 default:
445 NOTREACHED();
446 break;
449 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
451 if (thread_id == BrowserThread::WEBKIT_DEPRECATED) {
452 #if !defined(OS_IOS)
453 webkit_thread_.reset(new WebKitThread);
454 webkit_thread_->Initialize();
455 #endif
456 } else if (thread_to_start) {
457 (*thread_to_start).reset(new BrowserProcessSubThread(id));
458 (*thread_to_start)->StartWithOptions(*options);
459 } else {
460 NOTREACHED();
464 BrowserThreadsStarted();
466 if (parts_.get())
467 parts_->PreMainMessageLoopRun();
469 // If the UI thread blocks, the whole UI is unresponsive.
470 // Do not allow disk IO from the UI thread.
471 base::ThreadRestrictions::SetIOAllowed(false);
472 base::ThreadRestrictions::DisallowWaiting();
475 void BrowserMainLoop::RunMainMessageLoopParts() {
476 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
478 bool ran_main_loop = false;
479 if (parts_.get())
480 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
482 if (!ran_main_loop)
483 MainMessageLoopRun();
485 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
488 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
489 // Teardown may start in PostMainMessageLoopRun, and during teardown we
490 // need to be able to perform IO.
491 base::ThreadRestrictions::SetIOAllowed(true);
492 BrowserThread::PostTask(
493 BrowserThread::IO, FROM_HERE,
494 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
495 true));
497 if (parts_.get())
498 parts_->PostMainMessageLoopRun();
500 #if !defined(OS_IOS)
501 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
502 // delete related objects on the GPU thread. This must be done before
503 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
504 // processes so this has to happen before stopping the IO thread.
505 GpuProcessHostUIShim::DestroyAll();
507 // Cancel pending requests and prevent new requests.
508 if (resource_dispatcher_host_.get())
509 resource_dispatcher_host_.get()->Shutdown();
511 #if defined(USE_AURA)
512 ImageTransportFactory::Terminate();
513 #endif
514 BrowserGpuChannelHostFactory::Terminate();
516 // The device monitors are using |system_monitor_| as dependency, so delete
517 // them before |system_monitor_| goes away.
518 // On Mac and windows, the monitor needs to be destroyed on the same thread
519 // as they were created. On Linux, the monitor will be deleted when IO thread
520 // goes away.
521 #if defined(OS_WIN)
522 system_message_window_.reset();
523 #elif defined(OS_MACOSX)
524 device_monitor_mac_.reset();
525 #endif
526 #endif // !defined(OS_IOS)
528 // Must be size_t so we can subtract from it.
529 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
530 thread_id >= (BrowserThread::UI + 1);
531 --thread_id) {
532 // Find the thread object we want to stop. Looping over all valid
533 // BrowserThread IDs and DCHECKing on a missing case in the switch
534 // statement helps avoid a mismatch between this code and the
535 // BrowserThread::ID enumeration.
537 // The destruction order is the reverse order of occurrence in the
538 // BrowserThread::ID list. The rationale for the order is as
539 // follows (need to be filled in a bit):
542 // - The IO thread is the only user of the CACHE thread.
544 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
545 // the IO thread posted a task to terminate a process on the
546 // process launcher thread.
548 // - (Not sure why FILE needs to stop before WEBKIT.)
550 // - The WEBKIT thread (which currently is the responsibility of
551 // the embedder to stop, by destroying ResourceDispatcherHost
552 // before the DB thread is stopped)
554 // - (Not sure why DB stops last.)
555 scoped_ptr<BrowserProcessSubThread>* thread_to_stop = NULL;
556 switch (thread_id) {
557 case BrowserThread::DB:
558 thread_to_stop = &db_thread_;
559 break;
560 case BrowserThread::WEBKIT_DEPRECATED:
561 // Special case as WebKitThread is a separate
562 // type. |thread_to_stop| is not used in this case.
564 // Need to destroy ResourceDispatcherHost before PluginService
565 // and since it caches a pointer to it.
566 resource_dispatcher_host_.reset();
567 break;
568 case BrowserThread::FILE_USER_BLOCKING:
569 thread_to_stop = &file_user_blocking_thread_;
570 break;
571 case BrowserThread::FILE:
572 thread_to_stop = &file_thread_;
574 #if !defined(OS_IOS)
575 // Clean up state that lives on or uses the file_thread_ before
576 // it goes away.
577 if (resource_dispatcher_host_.get())
578 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
579 #endif // !defined(OS_IOS)
580 break;
581 case BrowserThread::PROCESS_LAUNCHER:
582 thread_to_stop = &process_launcher_thread_;
583 break;
584 case BrowserThread::CACHE:
585 thread_to_stop = &cache_thread_;
586 break;
587 case BrowserThread::IO:
588 thread_to_stop = &io_thread_;
589 break;
590 case BrowserThread::UI:
591 case BrowserThread::ID_COUNT:
592 default:
593 NOTREACHED();
594 break;
597 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
599 if (id == BrowserThread::WEBKIT_DEPRECATED) {
600 #if !defined(OS_IOS)
601 webkit_thread_.reset();
602 #endif
603 } else if (thread_to_stop) {
604 thread_to_stop->reset();
605 } else {
606 NOTREACHED();
610 // Close the blocking I/O pool after the other threads. Other threads such
611 // as the I/O thread may need to schedule work like closing files or flushing
612 // data during shutdown, so the blocking pool needs to be available. There
613 // may also be slow operations pending that will blcok shutdown, so closing
614 // it here (which will block until required operations are complete) gives
615 // more head start for those operations to finish.
616 BrowserThreadImpl::ShutdownThreadPool();
618 #if !defined(OS_IOS)
619 // Must happen after the I/O thread is shutdown since this class lives on the
620 // I/O thread and isn't threadsafe.
621 GamepadService::GetInstance()->Terminate();
622 #endif // !defined(OS_IOS)
624 if (parts_.get())
625 parts_->PostDestroyThreads();
628 void BrowserMainLoop::InitializeMainThread() {
629 const char* kThreadName = "CrBrowserMain";
630 base::PlatformThread::SetName(kThreadName);
631 if (main_message_loop_.get())
632 main_message_loop_->set_thread_name(kThreadName);
634 // Register the main thread by instantiating it, but don't call any methods.
635 main_thread_.reset(new BrowserThreadImpl(BrowserThread::UI,
636 MessageLoop::current()));
640 void BrowserMainLoop::BrowserThreadsStarted() {
641 #if !defined(OS_IOS)
642 HistogramSynchronizer::GetInstance();
644 BrowserGpuChannelHostFactory::Initialize();
645 #if defined(USE_AURA)
646 ImageTransportFactory::Initialize();
647 #endif
649 #if defined(OS_LINUX)
650 device_monitor_linux_.reset(new DeviceMonitorLinux());
651 #elif defined(OS_MACOSX)
652 device_monitor_mac_.reset(new DeviceMonitorMac());
653 #endif
655 // RDH needs the IO thread to be created.
656 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
658 // MediaStreamManager needs the IO thread to be created.
659 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
661 // Initialize the GpuDataManager before we set up the MessageLoops because
662 // otherwise we'll trigger the assertion about doing IO on the UI thread.
663 GpuDataManagerImpl::GetInstance()->Initialize();
664 #endif // !OS_IOS
666 #if defined(ENABLE_INPUT_SPEECH)
667 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl());
668 #endif
670 #if !defined(OS_IOS)
671 // Alert the clipboard class to which threads are allowed to access the
672 // clipboard:
673 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
674 // The current thread is the UI thread.
675 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
676 #if defined(OS_WIN)
677 // On Windows, clipboards are also used on the File or IO threads.
678 allowed_clipboard_threads.push_back(file_thread_->thread_id());
679 allowed_clipboard_threads.push_back(io_thread_->thread_id());
680 #endif
681 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
683 // When running the GPU thread in-process, avoid optimistically starting it
684 // since creating the GPU thread races against creation of the one-and-only
685 // ChildProcess instance which is created by the renderer thread.
686 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed() &&
687 content::IsForceCompositingModeEnabled() &&
688 !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) &&
689 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
690 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
691 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process");
692 BrowserThread::PostTask(
693 BrowserThread::IO, FROM_HERE, base::Bind(
694 base::IgnoreResult(&GpuProcessHost::Get),
695 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
696 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
698 #endif // !defined(OS_IOS)
701 void BrowserMainLoop::InitializeToolkit() {
702 // TODO(evan): this function is rather subtle, due to the variety
703 // of intersecting ifdefs we have. To keep it easy to follow, there
704 // are no #else branches on any #ifs.
705 // TODO(stevenjb): Move platform specific code into platform specific Parts
706 // (Need to add InitializeToolkit stage to BrowserParts).
707 #if defined(OS_LINUX) || defined(OS_OPENBSD)
708 // Glib type system initialization. Needed at least for gconf,
709 // used in net/proxy/proxy_config_service_linux.cc. Most likely
710 // this is superfluous as gtk_init() ought to do this. It's
711 // definitely harmless, so retained as a reminder of this
712 // requirement for gconf.
713 g_type_init();
715 #if !defined(USE_AURA)
716 gfx::GtkInitFromCommandLine(parsed_command_line_);
717 #endif
719 SetUpGLibLogHandler();
720 #endif
722 #if defined(TOOLKIT_GTK)
723 // It is important for this to happen before the first run dialog, as it
724 // styles the dialog as well.
725 gfx::InitRCStyles();
726 #endif
728 #if defined(OS_WIN)
729 // Init common control sex.
730 INITCOMMONCONTROLSEX config;
731 config.dwSize = sizeof(config);
732 config.dwICC = ICC_WIN95_CLASSES;
733 if (!InitCommonControlsEx(&config))
734 LOG_GETLASTERROR(FATAL);
735 #endif
737 if (parts_.get())
738 parts_->ToolkitInitialized();
741 void BrowserMainLoop::MainMessageLoopRun() {
742 #if defined(OS_ANDROID)
743 // Android's main message loop is the Java message loop.
744 NOTREACHED();
745 #else
746 DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type());
747 if (parameters_.ui_task)
748 MessageLoopForUI::current()->PostTask(FROM_HERE, *parameters_.ui_task);
750 base::RunLoop run_loop;
751 run_loop.Run();
752 #endif
755 } // namespace content