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. 4 5 #ifndef IPC_IPC_FORWARDING_MESSAGE_FILTER_H_ 6 #define IPC_IPC_FORWARDING_MESSAGE_FILTER_H_ 7 8 #include <map> 9 #include <set> 10 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" 16 17 namespace IPC { 18 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. 23 // 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 { 27 public: 28 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; 32 33 // This filter will intercept |message_ids_to_filter| and post 34 // them to the provided |target_task_runner|, where they will be given 35 // to |handler|. 36 // 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); 42 43 // Define the message routes to be filtered. 44 void AddRoute(int routing_id, const Handler& handler); 45 void RemoveRoute(int routing_id); 46 47 // MessageFilter methods: 48 virtual bool OnMessageReceived(const Message& message) OVERRIDE; 49 50 private: 51 virtual ~ForwardingMessageFilter(); 52 53 std::set<int> message_ids_to_filter_; 54 55 // The handler_ only gets Run on the thread corresponding to 56 // target_task_runner_. 57 scoped_refptr<base::TaskRunner> target_task_runner_; 58 59 // Protects access to routes_. 60 base::Lock handlers_lock_; 61 62 // Indicates the routing_ids for which messages should be filtered. 63 std::map<int, Handler> handlers_; 64 65 DISALLOW_COPY_AND_ASSIGN(ForwardingMessageFilter); 66 }; 67 68 } // namespace IPC 69 70 #endif // IPC_IPC_FORWARDING_MESSAGE_FILTER_H_ 71