michael@0: // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #ifndef BASE_MESSAGE_PUMP_WIN_H_ michael@0: #define BASE_MESSAGE_PUMP_WIN_H_ michael@0: michael@0: #include michael@0: michael@0: #include michael@0: michael@0: #include "base/lock.h" michael@0: #include "base/message_pump.h" michael@0: #include "base/observer_list.h" michael@0: #include "base/scoped_handle.h" michael@0: #include "base/time.h" michael@0: michael@0: namespace base { michael@0: michael@0: // MessagePumpWin serves as the base for specialized versions of the MessagePump michael@0: // for Windows. It provides basic functionality like handling of observers and michael@0: // controlling the lifetime of the message pump. michael@0: class MessagePumpWin : public MessagePump { michael@0: public: michael@0: // An Observer is an object that receives global notifications from the michael@0: // MessageLoop. michael@0: // michael@0: // NOTE: An Observer implementation should be extremely fast! michael@0: // michael@0: class Observer { michael@0: public: michael@0: virtual ~Observer() {} michael@0: michael@0: // This method is called before processing a message. michael@0: // The message may be undefined in which case msg.message is 0 michael@0: virtual void WillProcessMessage(const MSG& msg) = 0; michael@0: michael@0: // This method is called when control returns from processing a UI message. michael@0: // The message may be undefined in which case msg.message is 0 michael@0: virtual void DidProcessMessage(const MSG& msg) = 0; michael@0: }; michael@0: michael@0: // Dispatcher is used during a nested invocation of Run to dispatch events. michael@0: // If Run is invoked with a non-NULL Dispatcher, MessageLoop does not michael@0: // dispatch events (or invoke TranslateMessage), rather every message is michael@0: // passed to Dispatcher's Dispatch method for dispatch. It is up to the michael@0: // Dispatcher to dispatch, or not, the event. michael@0: // michael@0: // The nested loop is exited by either posting a quit, or returning false michael@0: // from Dispatch. michael@0: class Dispatcher { michael@0: public: michael@0: virtual ~Dispatcher() {} michael@0: // Dispatches the event. If true is returned processing continues as michael@0: // normal. If false is returned, the nested loop exits immediately. michael@0: virtual bool Dispatch(const MSG& msg) = 0; michael@0: }; michael@0: michael@0: MessagePumpWin() : have_work_(0), state_(NULL) {} michael@0: virtual ~MessagePumpWin() {} michael@0: michael@0: // Add an Observer, which will start receiving notifications immediately. michael@0: void AddObserver(Observer* observer); michael@0: michael@0: // Remove an Observer. It is safe to call this method while an Observer is michael@0: // receiving a notification callback. michael@0: void RemoveObserver(Observer* observer); michael@0: michael@0: // Give a chance to code processing additional messages to notify the michael@0: // message loop observers that another message has been processed. michael@0: void WillProcessMessage(const MSG& msg); michael@0: void DidProcessMessage(const MSG& msg); michael@0: michael@0: // Like MessagePump::Run, but MSG objects are routed through dispatcher. michael@0: void RunWithDispatcher(Delegate* delegate, Dispatcher* dispatcher); michael@0: michael@0: // MessagePump methods: michael@0: virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); } michael@0: virtual void Quit(); michael@0: michael@0: protected: michael@0: struct RunState { michael@0: Delegate* delegate; michael@0: Dispatcher* dispatcher; michael@0: michael@0: // Used to flag that the current Run() invocation should return ASAP. michael@0: bool should_quit; michael@0: michael@0: // Used to count how many Run() invocations are on the stack. michael@0: int run_depth; michael@0: }; michael@0: michael@0: virtual void DoRunLoop() = 0; michael@0: int GetCurrentDelay() const; michael@0: michael@0: ObserverList observers_; michael@0: michael@0: // The time at which delayed work should run. michael@0: TimeTicks delayed_work_time_; michael@0: michael@0: // A boolean value used to indicate if there is a kMsgDoWork message pending michael@0: // in the Windows Message queue. There is at most one such message, and it michael@0: // can drive execution of tasks when a native message pump is running. michael@0: LONG have_work_; michael@0: michael@0: // State for the current invocation of Run. michael@0: RunState* state_; michael@0: }; michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // MessagePumpForUI extends MessagePumpWin with methods that are particular to a michael@0: // MessageLoop instantiated with TYPE_UI. michael@0: // michael@0: // MessagePumpForUI implements a "traditional" Windows message pump. It contains michael@0: // a nearly infinite loop that peeks out messages, and then dispatches them. michael@0: // Intermixed with those peeks are callouts to DoWork for pending tasks, and michael@0: // DoDelayedWork for pending timers. When there are no events to be serviced, michael@0: // this pump goes into a wait state. In most cases, this message pump handles michael@0: // all processing. michael@0: // michael@0: // However, when a task, or windows event, invokes on the stack a native dialog michael@0: // box or such, that window typically provides a bare bones (native?) message michael@0: // pump. That bare-bones message pump generally supports little more than a michael@0: // peek of the Windows message queue, followed by a dispatch of the peeked michael@0: // message. MessageLoop extends that bare-bones message pump to also service michael@0: // Tasks, at the cost of some complexity. michael@0: // michael@0: // The basic structure of the extension (refered to as a sub-pump) is that a michael@0: // special message, kMsgHaveWork, is repeatedly injected into the Windows michael@0: // Message queue. Each time the kMsgHaveWork message is peeked, checks are michael@0: // made for an extended set of events, including the availability of Tasks to michael@0: // run. michael@0: // michael@0: // After running a task, the special message kMsgHaveWork is again posted to michael@0: // the Windows Message queue, ensuring a future time slice for processing a michael@0: // future event. To prevent flooding the Windows Message queue, care is taken michael@0: // to be sure that at most one kMsgHaveWork message is EVER pending in the michael@0: // Window's Message queue. michael@0: // michael@0: // There are a few additional complexities in this system where, when there are michael@0: // no Tasks to run, this otherwise infinite stream of messages which drives the michael@0: // sub-pump is halted. The pump is automatically re-started when Tasks are michael@0: // queued. michael@0: // michael@0: // A second complexity is that the presence of this stream of posted tasks may michael@0: // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER. michael@0: // Such paint and timer events always give priority to a posted message, such as michael@0: // kMsgHaveWork messages. As a result, care is taken to do some peeking in michael@0: // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork michael@0: // is peeked, and before a replacement kMsgHaveWork is posted). michael@0: // michael@0: // NOTE: Although it may seem odd that messages are used to start and stop this michael@0: // flow (as opposed to signaling objects, etc.), it should be understood that michael@0: // the native message pump will *only* respond to messages. As a result, it is michael@0: // an excellent choice. It is also helpful that the starter messages that are michael@0: // placed in the queue when new task arrive also awakens DoRunLoop. michael@0: // michael@0: class MessagePumpForUI : public MessagePumpWin { michael@0: public: michael@0: MessagePumpForUI(); michael@0: virtual ~MessagePumpForUI(); michael@0: michael@0: // MessagePump methods: michael@0: virtual void ScheduleWork(); michael@0: virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); michael@0: michael@0: // Applications can call this to encourage us to process all pending WM_PAINT michael@0: // messages. This method will process all paint messages the Windows Message michael@0: // queue can provide, up to some fixed number (to avoid any infinite loops). michael@0: void PumpOutPendingPaintMessages(); michael@0: michael@0: private: michael@0: static LRESULT CALLBACK WndProcThunk( michael@0: HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); michael@0: virtual void DoRunLoop(); michael@0: void InitMessageWnd(); michael@0: void WaitForWork(); michael@0: void HandleWorkMessage(); michael@0: void HandleTimerMessage(); michael@0: bool ProcessNextWindowsMessage(); michael@0: bool ProcessMessageHelper(const MSG& msg); michael@0: bool ProcessPumpReplacementMessage(); michael@0: michael@0: // A hidden message-only window. michael@0: HWND message_hwnd_; michael@0: }; michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // MessagePumpForIO extends MessagePumpWin with methods that are particular to a michael@0: // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not michael@0: // deal with Windows mesagges, and instead has a Run loop based on Completion michael@0: // Ports so it is better suited for IO operations. michael@0: // michael@0: class MessagePumpForIO : public MessagePumpWin { michael@0: public: michael@0: struct IOContext; michael@0: michael@0: // Clients interested in receiving OS notifications when asynchronous IO michael@0: // operations complete should implement this interface and register themselves michael@0: // with the message pump. michael@0: // michael@0: // Typical use #1: michael@0: // // Use only when there are no user's buffers involved on the actual IO, michael@0: // // so that all the cleanup can be done by the message pump. michael@0: // class MyFile : public IOHandler { michael@0: // MyFile() { michael@0: // ... michael@0: // context_ = new IOContext; michael@0: // context_->handler = this; michael@0: // message_pump->RegisterIOHandler(file_, this); michael@0: // } michael@0: // ~MyFile() { michael@0: // if (pending_) { michael@0: // // By setting the handler to NULL, we're asking for this context michael@0: // // to be deleted when received, without calling back to us. michael@0: // context_->handler = NULL; michael@0: // } else { michael@0: // delete context_; michael@0: // } michael@0: // } michael@0: // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, michael@0: // DWORD error) { michael@0: // pending_ = false; michael@0: // } michael@0: // void DoSomeIo() { michael@0: // ... michael@0: // // The only buffer required for this operation is the overlapped michael@0: // // structure. michael@0: // ConnectNamedPipe(file_, &context_->overlapped); michael@0: // pending_ = true; michael@0: // } michael@0: // bool pending_; michael@0: // IOContext* context_; michael@0: // HANDLE file_; michael@0: // }; michael@0: // michael@0: // Typical use #2: michael@0: // class MyFile : public IOHandler { michael@0: // MyFile() { michael@0: // ... michael@0: // message_pump->RegisterIOHandler(file_, this); michael@0: // } michael@0: // // Plus some code to make sure that this destructor is not called michael@0: // // while there are pending IO operations. michael@0: // ~MyFile() { michael@0: // } michael@0: // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, michael@0: // DWORD error) { michael@0: // ... michael@0: // delete context; michael@0: // } michael@0: // void DoSomeIo() { michael@0: // ... michael@0: // IOContext* context = new IOContext; michael@0: // // This is not used for anything. It just prevents the context from michael@0: // // being considered "abandoned". michael@0: // context->handler = this; michael@0: // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped); michael@0: // } michael@0: // HANDLE file_; michael@0: // }; michael@0: // michael@0: // Typical use #3: michael@0: // Same as the previous example, except that in order to deal with the michael@0: // requirement stated for the destructor, the class calls WaitForIOCompletion michael@0: // from the destructor to block until all IO finishes. michael@0: // ~MyFile() { michael@0: // while(pending_) michael@0: // message_pump->WaitForIOCompletion(INFINITE, this); michael@0: // } michael@0: // michael@0: class IOHandler { michael@0: public: michael@0: virtual ~IOHandler() {} michael@0: // This will be called once the pending IO operation associated with michael@0: // |context| completes. |error| is the Win32 error code of the IO operation michael@0: // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero michael@0: // on error. michael@0: virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, michael@0: DWORD error) = 0; michael@0: }; michael@0: michael@0: // The extended context that should be used as the base structure on every michael@0: // overlapped IO operation. |handler| must be set to the registered IOHandler michael@0: // for the given file when the operation is started, and it can be set to NULL michael@0: // before the operation completes to indicate that the handler should not be michael@0: // called anymore, and instead, the IOContext should be deleted when the OS michael@0: // notifies the completion of this operation. Please remember that any buffers michael@0: // involved with an IO operation should be around until the callback is michael@0: // received, so this technique can only be used for IO that do not involve michael@0: // additional buffers (other than the overlapped structure itself). michael@0: struct IOContext { michael@0: OVERLAPPED overlapped; michael@0: IOHandler* handler; michael@0: }; michael@0: michael@0: MessagePumpForIO(); michael@0: virtual ~MessagePumpForIO() {} michael@0: michael@0: // MessagePump methods: michael@0: virtual void ScheduleWork(); michael@0: virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); michael@0: michael@0: // Register the handler to be used when asynchronous IO for the given file michael@0: // completes. The registration persists as long as |file_handle| is valid, so michael@0: // |handler| must be valid as long as there is pending IO for the given file. michael@0: void RegisterIOHandler(HANDLE file_handle, IOHandler* handler); michael@0: michael@0: // Waits for the next IO completion that should be processed by |filter|, for michael@0: // up to |timeout| milliseconds. Return true if any IO operation completed, michael@0: // regardless of the involved handler, and false if the timeout expired. If michael@0: // the completion port received any message and the involved IO handler michael@0: // matches |filter|, the callback is called before returning from this code; michael@0: // if the handler is not the one that we are looking for, the callback will michael@0: // be postponed for another time, so reentrancy problems can be avoided. michael@0: // External use of this method should be reserved for the rare case when the michael@0: // caller is willing to allow pausing regular task dispatching on this thread. michael@0: bool WaitForIOCompletion(DWORD timeout, IOHandler* filter); michael@0: michael@0: private: michael@0: struct IOItem { michael@0: IOHandler* handler; michael@0: IOContext* context; michael@0: DWORD bytes_transfered; michael@0: DWORD error; michael@0: }; michael@0: michael@0: virtual void DoRunLoop(); michael@0: void WaitForWork(); michael@0: bool MatchCompletedIOItem(IOHandler* filter, IOItem* item); michael@0: bool GetIOItem(DWORD timeout, IOItem* item); michael@0: bool ProcessInternalIOItem(const IOItem& item); michael@0: michael@0: // The completion port associated with this thread. michael@0: ScopedHandle port_; michael@0: // This list will be empty almost always. It stores IO completions that have michael@0: // not been delivered yet because somebody was doing cleanup. michael@0: std::list completed_io_; michael@0: }; michael@0: michael@0: } // namespace base michael@0: michael@0: #endif // BASE_MESSAGE_PUMP_WIN_H_