Upstream version 7.35.144.0
[platform/framework/web/crosswalk.git] / src / mojo / public / utility / lib / run_loop.cc
1 // Copyright 2014 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 "mojo/public/utility/run_loop.h"
6
7 #include <assert.h>
8
9 #include <algorithm>
10 #include <vector>
11
12 #include "mojo/public/utility/lib/thread_local.h"
13 #include "mojo/public/utility/run_loop_handler.h"
14
15 namespace mojo {
16 namespace {
17
18 internal::ThreadLocalPointer<RunLoop> current_run_loop;
19
20 const MojoTimeTicks kInvalidTimeTicks = static_cast<MojoTimeTicks>(0);
21
22 }  // namespace
23
24 // State needed for one iteration of WaitMany().
25 struct RunLoop::WaitState {
26   WaitState() : deadline(MOJO_DEADLINE_INDEFINITE) {}
27
28   std::vector<Handle> handles;
29   std::vector<MojoWaitFlags> wait_flags;
30   MojoDeadline deadline;
31 };
32
33 struct RunLoop::RunState {
34   RunState() : should_quit(false) {}
35
36   bool should_quit;
37 };
38
39 RunLoop::RunLoop() : run_state_(NULL), next_handler_id_(0) {
40   assert(!current());
41   current_run_loop.Set(this);
42 }
43
44 RunLoop::~RunLoop() {
45   assert(current() == this);
46   current_run_loop.Set(NULL);
47 }
48
49 // static
50 void RunLoop::SetUp() {
51   current_run_loop.Allocate();
52 }
53
54 // static
55 void RunLoop::TearDown() {
56   assert(!current());
57   current_run_loop.Free();
58 }
59
60 // static
61 RunLoop* RunLoop::current() {
62   return current_run_loop.Get();
63 }
64
65 void RunLoop::AddHandler(RunLoopHandler* handler,
66                          const Handle& handle,
67                          MojoWaitFlags wait_flags,
68                          MojoDeadline deadline) {
69   assert(current() == this);
70   assert(handler);
71   assert(handle.is_valid());
72   // Assume it's an error if someone tries to reregister an existing handle.
73   assert(0u == handler_data_.count(handle));
74   HandlerData handler_data;
75   handler_data.handler = handler;
76   handler_data.wait_flags = wait_flags;
77   handler_data.deadline = (deadline == MOJO_DEADLINE_INDEFINITE) ?
78       kInvalidTimeTicks :
79       GetTimeTicksNow() + static_cast<MojoTimeTicks>(deadline);
80   handler_data.id = next_handler_id_++;
81   handler_data_[handle] = handler_data;
82 }
83
84 void RunLoop::RemoveHandler(const Handle& handle) {
85   assert(current() == this);
86   handler_data_.erase(handle);
87 }
88
89 bool RunLoop::HasHandler(const Handle& handle) const {
90   return handler_data_.find(handle) != handler_data_.end();
91 }
92
93 void RunLoop::Run() {
94   assert(current() == this);
95   // We don't currently support nesting.
96   assert(!run_state_);
97   RunState* old_state = run_state_;
98   RunState run_state;
99   run_state_ = &run_state;
100   while (!run_state.should_quit)
101     Wait(false);
102   run_state_ = old_state;
103 }
104
105 void RunLoop::RunUntilIdle() {
106   assert(current() == this);
107   // We don't currently support nesting.
108   assert(!run_state_);
109   RunState* old_state = run_state_;
110   RunState run_state;
111   run_state_ = &run_state;
112   while (!run_state.should_quit) {
113     if (!Wait(true))
114       break;
115   }
116   run_state_ = old_state;
117 }
118
119 void RunLoop::Quit() {
120   assert(current() == this);
121   if (run_state_)
122     run_state_->should_quit = true;
123 }
124
125 bool RunLoop::Wait(bool non_blocking) {
126   const WaitState wait_state = GetWaitState(non_blocking);
127   if (wait_state.handles.empty()) {
128     Quit();
129     return false;
130   }
131
132   const MojoResult result =
133       WaitMany(wait_state.handles, wait_state.wait_flags, wait_state.deadline);
134   if (result >= 0) {
135     const size_t index = static_cast<size_t>(result);
136     assert(handler_data_.find(wait_state.handles[index]) !=
137            handler_data_.end());
138     handler_data_[wait_state.handles[index]].handler->OnHandleReady(
139         wait_state.handles[index]);
140     return true;
141   }
142
143   switch (result) {
144     case MOJO_RESULT_INVALID_ARGUMENT:
145     case MOJO_RESULT_FAILED_PRECONDITION:
146       return RemoveFirstInvalidHandle(wait_state);
147     case MOJO_RESULT_DEADLINE_EXCEEDED:
148       return NotifyDeadlineExceeded();
149   }
150
151   assert(false);
152   return false;
153 }
154
155 bool RunLoop::NotifyDeadlineExceeded() {
156   bool notified = false;
157
158   // Make a copy in case someone tries to add/remove new handlers as part of
159   // notifying.
160   const HandleToHandlerData cloned_handlers(handler_data_);
161   const MojoTimeTicks now(GetTimeTicksNow());
162   for (HandleToHandlerData::const_iterator i = cloned_handlers.begin();
163        i != cloned_handlers.end(); ++i) {
164     // Since we're iterating over a clone of the handlers, verify the handler is
165     // still valid before notifying.
166     if (i->second.deadline != kInvalidTimeTicks &&
167         i->second.deadline < now &&
168         handler_data_.find(i->first) != handler_data_.end() &&
169         handler_data_[i->first].id == i->second.id) {
170       handler_data_.erase(i->first);
171       i->second.handler->OnHandleError(i->first, MOJO_RESULT_DEADLINE_EXCEEDED);
172       notified = true;
173     }
174   }
175
176   return notified;
177 }
178
179 bool RunLoop::RemoveFirstInvalidHandle(const WaitState& wait_state) {
180   for (size_t i = 0; i < wait_state.handles.size(); ++i) {
181     const MojoResult result =
182         mojo::Wait(wait_state.handles[i], wait_state.wait_flags[i],
183                    static_cast<MojoDeadline>(0));
184     if (result == MOJO_RESULT_INVALID_ARGUMENT ||
185         result == MOJO_RESULT_FAILED_PRECONDITION) {
186       // Remove the handle first, this way if OnHandleError() tries to remove
187       // the handle our iterator isn't invalidated.
188       assert(handler_data_.find(wait_state.handles[i]) != handler_data_.end());
189       RunLoopHandler* handler =
190           handler_data_[wait_state.handles[i]].handler;
191       handler_data_.erase(wait_state.handles[i]);
192       handler->OnHandleError(wait_state.handles[i], result);
193       return true;
194     }
195     assert(MOJO_RESULT_DEADLINE_EXCEEDED == result);
196   }
197   return false;
198 }
199
200 RunLoop::WaitState RunLoop::GetWaitState(bool non_blocking) const {
201   WaitState wait_state;
202   MojoTimeTicks min_time = kInvalidTimeTicks;
203   for (HandleToHandlerData::const_iterator i = handler_data_.begin();
204        i != handler_data_.end(); ++i) {
205     wait_state.handles.push_back(i->first);
206     wait_state.wait_flags.push_back(i->second.wait_flags);
207     if (!non_blocking && i->second.deadline != kInvalidTimeTicks &&
208         (min_time == kInvalidTimeTicks || i->second.deadline < min_time)) {
209       min_time = i->second.deadline;
210     }
211   }
212   if (non_blocking) {
213     wait_state.deadline = static_cast<MojoDeadline>(0);
214   } else if (min_time != kInvalidTimeTicks) {
215     const MojoTimeTicks now = GetTimeTicksNow();
216     if (min_time < now)
217       wait_state.deadline = static_cast<MojoDeadline>(0);
218     else
219       wait_state.deadline = static_cast<MojoDeadline>(min_time - now);
220   }
221   return wait_state;
222 }
223
224 }  // namespace mojo