chromium之message_pump_win之一

写了22篇博文,终于到这里了———— MessagePumpWin!!!
MessagePumpWin这个类还是挺复杂的,可以分成好几部分。接下来分块分析

从介绍看,MessagePumpWin 是MessagePump在Windows平台的实现。

接下来分析下观察者模式,觉得最好的解释在这里chromium之observer_list
// MessagePumpWin serves as the base for specialized versions of the MessagePump
// for Windows. It provides basic functionality like handling of observers and
// controlling the lifetime of the message pump.
class MessagePumpWin : public MessagePump {
 public:
  // An Observer is an object that receives global notifications from the
  // MessageLoop.
  //
  // NOTE: An Observer implementation should be extremely fast!
  //
  class Observer {
   public:
    virtual ~Observer() {}

    // This method is called before processing a message.
    // The message may be undefined in which case msg.message is 0
    virtual void WillProcessMessage(const MSG& msg) = 0; // 在处理消息前调用

    // This method is called when control returns from processing a UI message.
    // The message may be undefined in which case msg.message is 0
    virtual void DidProcessMessage(const MSG& msg) = 0; // 当控制从处理UI消息返回时调用此方法。
  };


  // Add an Observer, which will start receiving notifications immediately.
  void AddObserver(Observer* observer);

  // Remove an Observer.  It is safe to call this method while an Observer is
  // receiving a notification callback.
  void RemoveObserver(Observer* observer);

  // Give a chance to code processing additional messages to notify the
  // message loop observers that another message has been processed.
  void WillProcessMessage(const MSG& msg);
  void DidProcessMessage(const MSG& msg);

对应的实现,跟chromium之observer_list一模一样

void MessagePumpWin::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void MessagePumpWin::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void MessagePumpWin::WillProcessMessage(const MSG& msg) {
  FOR_EACH_OBSERVER(Observer, observers_, WillProcessMessage(msg));
}

void MessagePumpWin::DidProcessMessage(const MSG& msg) {
  FOR_EACH_OBSERVER(Observer, observers_, DidProcessMessage(msg));
}

 

关键的第二部分

实现了MessagePump的两个接口Run和Quit

  // Like MessagePump::Run, but MSG objects are routed through dispatcher.
  void RunWithDispatcher(Delegate* delegate, Dispatcher* dispatcher);

  // MessagePump methods:
  virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); }
  virtual void Quit();

 

再详细看下实现

void MessagePumpWin::RunWithDispatcher(
    Delegate* delegate, Dispatcher* dispatcher) {
  RunState s; // 将delegate和dispatcher放在一个类里,
  s.delegate = delegate;
  s.dispatcher = dispatcher;
  s.should_quit = false;
  s.run_depth = state_ ? state_->run_depth + 1 : 1;

  RunState* previous_state = state_;
  state_ = &s;

  DoRunLoop(); //虚函数,有派生类负责实现

  state_ = previous_state;
}

void MessagePumpWin::Quit() {
  DCHECK(state_);
  state_->should_quit = true;
}

 

posted on 2018-06-09 10:19  ckelsel  阅读(305)  评论(0编辑  收藏  举报

导航