ppb_message_loop_proxy.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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.
4
5#include "ppapi/proxy/ppb_message_loop_proxy.h"
6
7#include <vector>
8
9#include "base/bind.h"
10#include "base/compiler_specific.h"
11#include "base/message_loop.h"
12#include "base/message_loop_proxy.h"
13#include "ppapi/c/dev/ppb_message_loop_dev.h"
14#include "ppapi/c/pp_errors.h"
15#include "ppapi/proxy/plugin_dispatcher.h"
16#include "ppapi/proxy/plugin_globals.h"
17#include "ppapi/shared_impl/proxy_lock.h"
18#include "ppapi/thunk/enter.h"
19
20using ppapi::thunk::PPB_MessageLoop_API;
21
22namespace ppapi {
23namespace proxy {
24
25namespace {
26typedef thunk::EnterResource<PPB_MessageLoop_API> EnterMessageLoop;
27}
28
29MessageLoopResource::MessageLoopResource(PP_Instance instance)
30    : MessageLoopShared(instance),
31      nested_invocations_(0),
32      destroyed_(false),
33      should_destroy_(false),
34      is_main_thread_loop_(false) {
35}
36
37MessageLoopResource::MessageLoopResource(ForMainThread for_main_thread)
38    : MessageLoopShared(for_main_thread),
39      nested_invocations_(0),
40      destroyed_(false),
41      should_destroy_(false),
42      is_main_thread_loop_(true) {
43  // We attach the main thread immediately. We can't use AttachToCurrentThread,
44  // because the MessageLoop already exists.
45
46  // This must be called only once, so the slot must be empty.
47  CHECK(!PluginGlobals::Get()->msg_loop_slot());
48  base::ThreadLocalStorage::Slot* slot =
49      new base::ThreadLocalStorage::Slot(&ReleaseMessageLoop);
50  PluginGlobals::Get()->set_msg_loop_slot(slot);
51
52  // Take a ref to the MessageLoop on behalf of the TLS. Note that this is an
53  // internal ref and not a plugin ref so the plugin can't accidentally
54  // release it. This is released by ReleaseMessageLoop().
55  AddRef();
56  slot->Set(this);
57
58  loop_proxy_ = base::MessageLoopProxy::current();
59}
60
61
62MessageLoopResource::~MessageLoopResource() {
63}
64
65PPB_MessageLoop_API* MessageLoopResource::AsPPB_MessageLoop_API() {
66  return this;
67}
68
69int32_t MessageLoopResource::AttachToCurrentThread() {
70  if (is_main_thread_loop_)
71    return PP_ERROR_INPROGRESS;
72
73  PluginGlobals* globals = PluginGlobals::Get();
74
75  base::ThreadLocalStorage::Slot* slot = globals->msg_loop_slot();
76  if (!slot) {
77    slot = new base::ThreadLocalStorage::Slot(&ReleaseMessageLoop);
78    globals->set_msg_loop_slot(slot);
79  } else {
80    if (slot->Get())
81      return PP_ERROR_INPROGRESS;
82  }
83  // TODO(dmichael) check that the current thread can support a message loop.
84
85  // Take a ref to the MessageLoop on behalf of the TLS. Note that this is an
86  // internal ref and not a plugin ref so the plugin can't accidentally
87  // release it. This is released by ReleaseMessageLoop().
88  AddRef();
89  slot->Set(this);
90
91  loop_.reset(new MessageLoop(MessageLoop::TYPE_DEFAULT));
92  loop_proxy_ = base::MessageLoopProxy::current();
93
94  // Post all pending work to the message loop.
95  for (size_t i = 0; i < pending_tasks_.size(); i++) {
96    const TaskInfo& info = pending_tasks_[i];
97    PostClosure(info.from_here, info.closure, info.delay_ms);
98  }
99  pending_tasks_.clear();
100
101  return PP_OK;
102}
103
104int32_t MessageLoopResource::Run() {
105  if (!IsCurrent())
106    return PP_ERROR_WRONG_THREAD;
107  if (is_main_thread_loop_)
108    return PP_ERROR_INPROGRESS;
109
110  nested_invocations_++;
111  CallWhileUnlocked(base::Bind(&MessageLoop::Run,
112                               base::Unretained(loop_.get())));
113  nested_invocations_--;
114
115  if (should_destroy_ && nested_invocations_ == 0) {
116    loop_proxy_ = NULL;
117    loop_.reset();
118    destroyed_ = true;
119  }
120  return PP_OK;
121}
122
123int32_t MessageLoopResource::PostWork(PP_CompletionCallback callback,
124                                      int64_t delay_ms) {
125  if (!callback.func)
126    return PP_ERROR_BADARGUMENT;
127  if (destroyed_)
128    return PP_ERROR_FAILED;
129  PostClosure(FROM_HERE,
130              base::Bind(callback.func, callback.user_data,
131                         static_cast<int32_t>(PP_OK)),
132              delay_ms);
133  return PP_OK;
134}
135
136int32_t MessageLoopResource::PostQuit(PP_Bool should_destroy) {
137  if (is_main_thread_loop_)
138    return PP_ERROR_WRONG_THREAD;
139
140  if (PP_ToBool(should_destroy))
141    should_destroy_ = true;
142
143  if (IsCurrent() && nested_invocations_ > 0)
144    loop_->Quit();
145  else
146    PostClosure(FROM_HERE, MessageLoop::QuitClosure(), 0);
147  return PP_OK;
148}
149
150// static
151MessageLoopResource* MessageLoopResource::GetCurrent() {
152  PluginGlobals* globals = PluginGlobals::Get();
153  if (!globals->msg_loop_slot())
154    return NULL;
155  return reinterpret_cast<MessageLoopResource*>(
156      globals->msg_loop_slot()->Get());
157}
158
159void MessageLoopResource::DetachFromThread() {
160  // Note that the message loop must be destroyed on the thread it was created
161  // on.
162  loop_proxy_ = NULL;
163  loop_.reset();
164
165  // Cancel out the AddRef in AttachToCurrentThread().
166  Release();
167  // DANGER: may delete this.
168}
169
170bool MessageLoopResource::IsCurrent() const {
171  PluginGlobals* globals = PluginGlobals::Get();
172  if (!globals->msg_loop_slot())
173    return false;  // Can't be current if there's nothing in the slot.
174  return static_cast<const void*>(globals->msg_loop_slot()->Get()) ==
175         static_cast<const void*>(this);
176}
177
178void MessageLoopResource::PostClosure(
179    const tracked_objects::Location& from_here,
180    const base::Closure& closure,
181    int64 delay_ms) {
182  if (loop_proxy_) {
183    loop_proxy_->PostDelayedTask(from_here,
184                                 closure,
185                                 base::TimeDelta::FromMilliseconds(delay_ms));
186  } else {
187    TaskInfo info;
188    info.from_here = FROM_HERE;
189    info.closure = closure;
190    info.delay_ms = delay_ms;
191    pending_tasks_.push_back(info);
192  }
193}
194
195// static
196void MessageLoopResource::ReleaseMessageLoop(void* value) {
197  static_cast<MessageLoopResource*>(value)->DetachFromThread();
198}
199
200// -----------------------------------------------------------------------------
201
202PP_Resource Create(PP_Instance instance) {
203  // Validate the instance.
204  PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance);
205  if (!dispatcher)
206    return 0;
207  return (new MessageLoopResource(instance))->GetReference();
208}
209
210PP_Resource GetForMainThread() {
211  return PluginGlobals::Get()->loop_for_main_thread()->GetReference();
212}
213
214PP_Resource GetCurrent() {
215  Resource* resource = MessageLoopResource::GetCurrent();
216  if (resource)
217    return resource->GetReference();
218  return 0;
219}
220
221int32_t AttachToCurrentThread(PP_Resource message_loop) {
222  EnterMessageLoop enter(message_loop, true);
223  if (enter.succeeded())
224    return enter.object()->AttachToCurrentThread();
225  return PP_ERROR_BADRESOURCE;
226}
227
228int32_t Run(PP_Resource message_loop) {
229  EnterMessageLoop enter(message_loop, true);
230  if (enter.succeeded())
231    return enter.object()->Run();
232  return PP_ERROR_BADRESOURCE;
233}
234
235int32_t PostWork(PP_Resource message_loop,
236                 PP_CompletionCallback callback,
237                 int64_t delay_ms) {
238  EnterMessageLoop enter(message_loop, true);
239  if (enter.succeeded())
240    return enter.object()->PostWork(callback, delay_ms);
241  return PP_ERROR_BADRESOURCE;
242}
243
244int32_t PostQuit(PP_Resource message_loop, PP_Bool should_destroy) {
245  EnterMessageLoop enter(message_loop, true);
246  if (enter.succeeded())
247    return enter.object()->PostQuit(should_destroy);
248  return PP_ERROR_BADRESOURCE;
249}
250
251const PPB_MessageLoop_Dev_0_1 ppb_message_loop_interface = {
252  &Create,
253  &GetForMainThread,
254  &GetCurrent,
255  &AttachToCurrentThread,
256  &Run,
257  &PostWork,
258  &PostQuit
259};
260
261PPB_MessageLoop_Proxy::PPB_MessageLoop_Proxy(Dispatcher* dispatcher)
262    : InterfaceProxy(dispatcher) {
263}
264
265PPB_MessageLoop_Proxy::~PPB_MessageLoop_Proxy() {
266}
267
268// static
269const PPB_MessageLoop_Dev_0_1* PPB_MessageLoop_Proxy::GetInterface() {
270  return &ppb_message_loop_interface;
271}
272
273}  // namespace proxy
274}  // namespace ppapi
275