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