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 #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_ 6 #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_ 7 8 #include <windows.h> 9 10 #include <list> 11 12 #include "base/base_export.h" 13 #include "base/basictypes.h" 14 #include "base/message_loop/message_pump.h" 15 #include "base/message_loop/message_pump_dispatcher.h" 16 #include "base/message_loop/message_pump_observer.h" 17 #include "base/observer_list.h" 18 #include "base/time/time.h" 19 #include "base/win/scoped_handle.h" 20 21 namespace base { 22 23 // MessagePumpWin serves as the base for specialized versions of the MessagePump 24 // for Windows. It provides basic functionality like handling of observers and 25 // controlling the lifetime of the message pump. 26 class BASE_EXPORT MessagePumpWin : public MessagePump { 27 public: 28 MessagePumpWin() : have_work_(0), state_(NULL) {} 29 virtual ~MessagePumpWin() {} 30 31 // Add an Observer, which will start receiving notifications immediately. 32 void AddObserver(MessagePumpObserver* observer); 33 34 // Remove an Observer. It is safe to call this method while an Observer is 35 // receiving a notification callback. 36 void RemoveObserver(MessagePumpObserver* observer); 37 38 // Give a chance to code processing additional messages to notify the 39 // message loop observers that another message has been processed. 40 void WillProcessMessage(const MSG& msg); 41 void DidProcessMessage(const MSG& msg); 42 43 // Like MessagePump::Run, but MSG objects are routed through dispatcher. 44 void RunWithDispatcher(Delegate* delegate, MessagePumpDispatcher* dispatcher); 45 46 // MessagePump methods: 47 virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); } 48 virtual void Quit(); 49 50 protected: 51 struct RunState { 52 Delegate* delegate; 53 MessagePumpDispatcher* dispatcher; 54 55 // Used to flag that the current Run() invocation should return ASAP. 56 bool should_quit; 57 58 // Used to count how many Run() invocations are on the stack. 59 int run_depth; 60 }; 61 62 virtual void DoRunLoop() = 0; 63 int GetCurrentDelay() const; 64 65 ObserverList<MessagePumpObserver> observers_; 66 67 // The time at which delayed work should run. 68 TimeTicks delayed_work_time_; 69 70 // A boolean value used to indicate if there is a kMsgDoWork message pending 71 // in the Windows Message queue. There is at most one such message, and it 72 // can drive execution of tasks when a native message pump is running. 73 LONG have_work_; 74 75 // State for the current invocation of Run. 76 RunState* state_; 77 }; 78 79 //----------------------------------------------------------------------------- 80 // MessagePumpForUI extends MessagePumpWin with methods that are particular to a 81 // MessageLoop instantiated with TYPE_UI. 82 // 83 // MessagePumpForUI implements a "traditional" Windows message pump. It contains 84 // a nearly infinite loop that peeks out messages, and then dispatches them. 85 // Intermixed with those peeks are callouts to DoWork for pending tasks, and 86 // DoDelayedWork for pending timers. When there are no events to be serviced, 87 // this pump goes into a wait state. In most cases, this message pump handles 88 // all processing. 89 // 90 // However, when a task, or windows event, invokes on the stack a native dialog 91 // box or such, that window typically provides a bare bones (native?) message 92 // pump. That bare-bones message pump generally supports little more than a 93 // peek of the Windows message queue, followed by a dispatch of the peeked 94 // message. MessageLoop extends that bare-bones message pump to also service 95 // Tasks, at the cost of some complexity. 96 // 97 // The basic structure of the extension (refered to as a sub-pump) is that a 98 // special message, kMsgHaveWork, is repeatedly injected into the Windows 99 // Message queue. Each time the kMsgHaveWork message is peeked, checks are 100 // made for an extended set of events, including the availability of Tasks to 101 // run. 102 // 103 // After running a task, the special message kMsgHaveWork is again posted to 104 // the Windows Message queue, ensuring a future time slice for processing a 105 // future event. To prevent flooding the Windows Message queue, care is taken 106 // to be sure that at most one kMsgHaveWork message is EVER pending in the 107 // Window's Message queue. 108 // 109 // There are a few additional complexities in this system where, when there are 110 // no Tasks to run, this otherwise infinite stream of messages which drives the 111 // sub-pump is halted. The pump is automatically re-started when Tasks are 112 // queued. 113 // 114 // A second complexity is that the presence of this stream of posted tasks may 115 // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER. 116 // Such paint and timer events always give priority to a posted message, such as 117 // kMsgHaveWork messages. As a result, care is taken to do some peeking in 118 // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork 119 // is peeked, and before a replacement kMsgHaveWork is posted). 120 // 121 // NOTE: Although it may seem odd that messages are used to start and stop this 122 // flow (as opposed to signaling objects, etc.), it should be understood that 123 // the native message pump will *only* respond to messages. As a result, it is 124 // an excellent choice. It is also helpful that the starter messages that are 125 // placed in the queue when new task arrive also awakens DoRunLoop. 126 // 127 class BASE_EXPORT MessagePumpForUI : public MessagePumpWin { 128 public: 129 // The application-defined code passed to the hook procedure. 130 static const int kMessageFilterCode = 0x5001; 131 132 MessagePumpForUI(); 133 virtual ~MessagePumpForUI(); 134 135 // MessagePump methods: 136 virtual void ScheduleWork(); 137 virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); 138 139 private: 140 static LRESULT CALLBACK WndProcThunk(HWND window_handle, 141 UINT message, 142 WPARAM wparam, 143 LPARAM lparam); 144 virtual void DoRunLoop(); 145 void InitMessageWnd(); 146 void WaitForWork(); 147 void HandleWorkMessage(); 148 void HandleTimerMessage(); 149 bool ProcessNextWindowsMessage(); 150 bool ProcessMessageHelper(const MSG& msg); 151 bool ProcessPumpReplacementMessage(); 152 153 // Atom representing the registered window class. 154 ATOM atom_; 155 156 // A hidden message-only window. 157 HWND message_hwnd_; 158 }; 159 160 //----------------------------------------------------------------------------- 161 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a 162 // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not 163 // deal with Windows mesagges, and instead has a Run loop based on Completion 164 // Ports so it is better suited for IO operations. 165 // 166 class BASE_EXPORT MessagePumpForIO : public MessagePumpWin { 167 public: 168 struct IOContext; 169 170 // Clients interested in receiving OS notifications when asynchronous IO 171 // operations complete should implement this interface and register themselves 172 // with the message pump. 173 // 174 // Typical use #1: 175 // // Use only when there are no user's buffers involved on the actual IO, 176 // // so that all the cleanup can be done by the message pump. 177 // class MyFile : public IOHandler { 178 // MyFile() { 179 // ... 180 // context_ = new IOContext; 181 // context_->handler = this; 182 // message_pump->RegisterIOHandler(file_, this); 183 // } 184 // ~MyFile() { 185 // if (pending_) { 186 // // By setting the handler to NULL, we're asking for this context 187 // // to be deleted when received, without calling back to us. 188 // context_->handler = NULL; 189 // } else { 190 // delete context_; 191 // } 192 // } 193 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, 194 // DWORD error) { 195 // pending_ = false; 196 // } 197 // void DoSomeIo() { 198 // ... 199 // // The only buffer required for this operation is the overlapped 200 // // structure. 201 // ConnectNamedPipe(file_, &context_->overlapped); 202 // pending_ = true; 203 // } 204 // bool pending_; 205 // IOContext* context_; 206 // HANDLE file_; 207 // }; 208 // 209 // Typical use #2: 210 // class MyFile : public IOHandler { 211 // MyFile() { 212 // ... 213 // message_pump->RegisterIOHandler(file_, this); 214 // } 215 // // Plus some code to make sure that this destructor is not called 216 // // while there are pending IO operations. 217 // ~MyFile() { 218 // } 219 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, 220 // DWORD error) { 221 // ... 222 // delete context; 223 // } 224 // void DoSomeIo() { 225 // ... 226 // IOContext* context = new IOContext; 227 // // This is not used for anything. It just prevents the context from 228 // // being considered "abandoned". 229 // context->handler = this; 230 // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped); 231 // } 232 // HANDLE file_; 233 // }; 234 // 235 // Typical use #3: 236 // Same as the previous example, except that in order to deal with the 237 // requirement stated for the destructor, the class calls WaitForIOCompletion 238 // from the destructor to block until all IO finishes. 239 // ~MyFile() { 240 // while(pending_) 241 // message_pump->WaitForIOCompletion(INFINITE, this); 242 // } 243 // 244 class IOHandler { 245 public: 246 virtual ~IOHandler() {} 247 // This will be called once the pending IO operation associated with 248 // |context| completes. |error| is the Win32 error code of the IO operation 249 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero 250 // on error. 251 virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, 252 DWORD error) = 0; 253 }; 254 255 // An IOObserver is an object that receives IO notifications from the 256 // MessagePump. 257 // 258 // NOTE: An IOObserver implementation should be extremely fast! 259 class IOObserver { 260 public: 261 IOObserver() {} 262 263 virtual void WillProcessIOEvent() = 0; 264 virtual void DidProcessIOEvent() = 0; 265 266 protected: 267 virtual ~IOObserver() {} 268 }; 269 270 // The extended context that should be used as the base structure on every 271 // overlapped IO operation. |handler| must be set to the registered IOHandler 272 // for the given file when the operation is started, and it can be set to NULL 273 // before the operation completes to indicate that the handler should not be 274 // called anymore, and instead, the IOContext should be deleted when the OS 275 // notifies the completion of this operation. Please remember that any buffers 276 // involved with an IO operation should be around until the callback is 277 // received, so this technique can only be used for IO that do not involve 278 // additional buffers (other than the overlapped structure itself). 279 struct IOContext { 280 OVERLAPPED overlapped; 281 IOHandler* handler; 282 }; 283 284 MessagePumpForIO(); 285 virtual ~MessagePumpForIO() {} 286 287 // MessagePump methods: 288 virtual void ScheduleWork(); 289 virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); 290 291 // Register the handler to be used when asynchronous IO for the given file 292 // completes. The registration persists as long as |file_handle| is valid, so 293 // |handler| must be valid as long as there is pending IO for the given file. 294 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler); 295 296 // Register the handler to be used to process job events. The registration 297 // persists as long as the job object is live, so |handler| must be valid 298 // until the job object is destroyed. Returns true if the registration 299 // succeeded, and false otherwise. 300 bool RegisterJobObject(HANDLE job_handle, IOHandler* handler); 301 302 // Waits for the next IO completion that should be processed by |filter|, for 303 // up to |timeout| milliseconds. Return true if any IO operation completed, 304 // regardless of the involved handler, and false if the timeout expired. If 305 // the completion port received any message and the involved IO handler 306 // matches |filter|, the callback is called before returning from this code; 307 // if the handler is not the one that we are looking for, the callback will 308 // be postponed for another time, so reentrancy problems can be avoided. 309 // External use of this method should be reserved for the rare case when the 310 // caller is willing to allow pausing regular task dispatching on this thread. 311 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter); 312 313 void AddIOObserver(IOObserver* obs); 314 void RemoveIOObserver(IOObserver* obs); 315 316 private: 317 struct IOItem { 318 IOHandler* handler; 319 IOContext* context; 320 DWORD bytes_transfered; 321 DWORD error; 322 323 // In some cases |context| can be a non-pointer value casted to a pointer. 324 // |has_valid_io_context| is true if |context| is a valid IOContext 325 // pointer, and false otherwise. 326 bool has_valid_io_context; 327 }; 328 329 virtual void DoRunLoop(); 330 void WaitForWork(); 331 bool MatchCompletedIOItem(IOHandler* filter, IOItem* item); 332 bool GetIOItem(DWORD timeout, IOItem* item); 333 bool ProcessInternalIOItem(const IOItem& item); 334 void WillProcessIOEvent(); 335 void DidProcessIOEvent(); 336 337 // Converts an IOHandler pointer to a completion port key. 338 // |has_valid_io_context| specifies whether completion packets posted to 339 // |handler| will have valid OVERLAPPED pointers. 340 static ULONG_PTR HandlerToKey(IOHandler* handler, bool has_valid_io_context); 341 342 // Converts a completion port key to an IOHandler pointer. 343 static IOHandler* KeyToHandler(ULONG_PTR key, bool* has_valid_io_context); 344 345 // The completion port associated with this thread. 346 win::ScopedHandle port_; 347 // This list will be empty almost always. It stores IO completions that have 348 // not been delivered yet because somebody was doing cleanup. 349 std::list<IOItem> completed_io_; 350 351 ObserverList<IOObserver> io_observers_; 352 }; 353 354 } // namespace base 355 356 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_ 357