1 // Copyright (c) 2012 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.
5 #ifndef IPC_IPC_FORWARDING_MESSAGE_FILTER_H_
6 #define IPC_IPC_FORWARDING_MESSAGE_FILTER_H_
11 #include "base/bind.h"
12 #include "base/callback_forward.h"
13 #include "base/synchronization/lock.h"
14 #include "base/task_runner.h"
15 #include "ipc/message_filter.h"
19 // This class can be used to intercept routed messages and
20 // deliver them to a different task runner than they would otherwise
21 // be sent. Messages are filtered based on type. To route these messages,
22 // add a MessageRouter to the handler.
24 // The user of this class implements ForwardingMessageFilter::Client,
25 // which will receive the intercepted messages, on the specified target thread.
26 class IPC_EXPORT ForwardingMessageFilter
: public MessageFilter
{
29 // The handler is invoked on the thread associated with
30 // |target_task_runner| with messages that were intercepted by this filter.
31 typedef base::Callback
<void(const Message
&)> Handler
;
33 // This filter will intercept |message_ids_to_filter| and post
34 // them to the provided |target_task_runner|, where they will be given
37 // The caller must ensure that |handler| outlives the lifetime of the filter.
38 ForwardingMessageFilter(
39 const uint32
* message_ids_to_filter
,
40 size_t num_message_ids_to_filter
,
41 base::TaskRunner
* target_task_runner
);
43 // Define the message routes to be filtered.
44 void AddRoute(int routing_id
, const Handler
& handler
);
45 void RemoveRoute(int routing_id
);
47 // MessageFilter methods:
48 bool OnMessageReceived(const Message
& message
) override
;
51 ~ForwardingMessageFilter() override
;
53 std::set
<int> message_ids_to_filter_
;
55 // The handler_ only gets Run on the thread corresponding to
56 // target_task_runner_.
57 scoped_refptr
<base::TaskRunner
> target_task_runner_
;
59 // Protects access to routes_.
60 base::Lock handlers_lock_
;
62 // Indicates the routing_ids for which messages should be filtered.
63 std::map
<int, Handler
> handlers_
;
65 DISALLOW_COPY_AND_ASSIGN(ForwardingMessageFilter
);
70 #endif // IPC_IPC_FORWARDING_MESSAGE_FILTER_H_