1// Copyright 2013 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 CONTENT_CHILD_CROSS_MESSAGE_FILTER_H_
6#define CONTENT_CHILD_CROSS_MESSAGE_FILTER_H_
7
8#include "ipc/ipc_channel_proxy.h"
9
10namespace base {
11class TaskRunner;
12}
13
14namespace content {
15
16class ThreadSafeSender;
17
18// A base class for implementing IPC MessageFilter's that run on a different
19// thread or TaskRunner than the main thread.
20class ChildMessageFilter
21    : public base::RefCountedThreadSafe<ChildMessageFilter>,
22      public IPC::Sender {
23 public:
24  // IPC::Sender implementation. Can be called on any threads.
25  virtual bool Send(IPC::Message* message) OVERRIDE;
26
27  // If implementers want to run OnMessageReceived on a different task
28  // runner it should override this and return the TaskRunner for the message.
29  // Returning NULL runs OnMessageReceived() on the current IPC thread.
30  virtual base::TaskRunner* OverrideTaskRunnerForMessage(
31      const IPC::Message& msg) = 0;
32
33  // If OverrideTaskRunnerForMessage is overriden and returns non-null
34  // this will be called on the returned TaskRunner.
35  virtual bool OnMessageReceived(const IPC::Message& msg) = 0;
36
37  // This method is called when WorkerTaskRunner::PostTask() returned false
38  // for the target thread.  Note that there's still a little chance that
39  // PostTask() returns true but OnMessageReceived() is never called on the
40  // target thread.  By default this does nothing.
41  virtual void OnStaleMessageReceived(const IPC::Message& msg) {}
42
43 protected:
44  ChildMessageFilter();
45  virtual ~ChildMessageFilter();
46
47 private:
48  class Internal;
49  friend class ChildThread;
50  friend class RenderThreadImpl;
51  friend class WorkerThread;
52
53  friend class base::RefCountedThreadSafe<ChildMessageFilter>;
54
55  IPC::ChannelProxy::MessageFilter* GetFilter();
56
57  // This implements IPC::ChannelProxy::MessageFilter to hide the actual
58  // filter methods from child classes.
59  Internal* internal_;
60
61  scoped_refptr<ThreadSafeSender> thread_safe_sender_;
62
63  DISALLOW_COPY_AND_ASSIGN(ChildMessageFilter);
64};
65
66}  // namespace content
67
68#endif  // CONTENT_CHILD_CROSS_MESSAGE_FILTER_H_
69