tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

message_pump_win.h (13761B)


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