1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "MessagePump.h"
9 #include <Foundation/Foundation.h>
11 #include "base/scoped_nsautorelease_pool.h"
12 #include "mozilla/ProfilerMarkers.h"
13 #include "nsISupportsImpl.h"
15 using namespace mozilla::ipc;
17 static void NoOp(void* info) {}
19 NS_IMPL_ADDREF_INHERITED(MessagePumpForNonMainUIThreads, MessagePump)
20 NS_IMPL_RELEASE_INHERITED(MessagePumpForNonMainUIThreads, MessagePump)
21 NS_IMPL_QUERY_INTERFACE(MessagePumpForNonMainUIThreads, nsIThreadObserver)
23 MessagePumpForNonMainUIThreads::MessagePumpForNonMainUIThreads(
24 nsISerialEventTarget* aEventTarget)
25 : mEventTarget(aEventTarget), keep_running_(true) {
26 MOZ_ASSERT(mEventTarget);
27 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
28 source_context.perform = NoOp;
29 quit_source_ = CFRunLoopSourceCreate(nullptr, // allocator
32 CFRunLoopAddSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
35 MessagePumpForNonMainUIThreads::~MessagePumpForNonMainUIThreads() {
36 CFRunLoopRemoveSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
37 CFRelease(quit_source_);
40 void MessagePumpForNonMainUIThreads::DoRun(
41 base::MessagePump::Delegate* aDelegate) {
42 // If this is a chromium thread and no nsThread is associated with it, this
43 // call will create a new nsThread.
44 nsIThread* thread = NS_GetCurrentThread();
47 // Set the main thread observer so we can wake up when xpcom events need to
49 nsCOMPtr<nsIThreadInternal> ti(do_QueryInterface(thread));
51 ti->SetObserver(this);
53 base::ScopedNSAutoreleasePool autoReleasePool;
55 while (keep_running_) {
56 // Drain the xpcom event loop first.
57 if (NS_ProcessNextEvent(nullptr, false)) {
61 autoReleasePool.Recycle();
67 // Now process the CFRunLoop. It exits after running once.
68 // NSRunLoop manages autorelease pools itself.
69 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
70 beforeDate:[NSDate distantFuture]];
73 ti->SetObserver(nullptr);
77 void MessagePumpForNonMainUIThreads::Quit() {
78 keep_running_ = false;
79 CFRunLoopSourceSignal(quit_source_);
80 CFRunLoopWakeUp(run_loop());
83 NS_IMETHODIMP MessagePumpForNonMainUIThreads::OnDispatchedEvent() {
84 // ScheduleWork will signal an input source to the run loop, making it exit so
85 // it can process the xpcom event.
91 MessagePumpForNonMainUIThreads::OnProcessNextEvent(nsIThreadInternal* thread,
97 MessagePumpForNonMainUIThreads::AfterProcessNextEvent(nsIThreadInternal* thread,
98 bool eventWasProcessed) {