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 BASE_MAC_BIND_OBJC_BLOCK_H_
6 #define BASE_MAC_BIND_OBJC_BLOCK_H_
7
8 #include <Block.h>
9
10 #include "base/bind.h"
11 #include "base/callback_forward.h"
12 #include "base/mac/scoped_block.h"
13
14 // BindBlock builds a callback from an Objective-C block. Example usages:
15 //
16 // Closure closure = BindBlock(^{DoSomething();});
17 //
18 // Callback<int(void)> callback = BindBlock(^{return 42;});
19 //
20 // Callback<void(const std::string&, const std::string&)> callback =
21 // BindBlock(^(const std::string& arg0, const std::string& arg1) {
22 // ...
23 // });
24
25 namespace base {
26
27 namespace internal {
28
29 // Helper functions to run the block contained in the parameter.
30 template<typename R>
RunBlock(base::mac::ScopedBlock<R (^)()> block)31 R RunBlock(base::mac::ScopedBlock<R(^)()> block) {
32 R(^extracted_block)() = block.get();
33 return extracted_block();
34 }
35
36 template<typename R, typename A1>
RunBlock(base::mac::ScopedBlock<R (^)(A1)> block,A1 a)37 R RunBlock(base::mac::ScopedBlock<R(^)(A1)> block, A1 a) {
38 R(^extracted_block)(A1) = block.get();
39 return extracted_block(a);
40 }
41
42 template<typename R, typename A1, typename A2>
RunBlock(base::mac::ScopedBlock<R (^)(A1,A2)> block,A1 a,A2 b)43 R RunBlock(base::mac::ScopedBlock<R(^)(A1, A2)> block, A1 a, A2 b) {
44 R(^extracted_block)(A1, A2) = block.get();
45 return extracted_block(a, b);
46 }
47
48 } // namespace internal
49
50 // Construct a callback with no argument from an objective-C block.
51 template<typename R>
52 base::Callback<R(void)> BindBlock(R(^block)()) {
53 return base::Bind(&base::internal::RunBlock<R>,
54 base::mac::ScopedBlock<R(^)()>(Block_copy(block)));
55 }
56
57 // Construct a callback with one argument from an objective-C block.
58 template<typename R, typename A1>
59 base::Callback<R(A1)> BindBlock(R(^block)(A1)) {
60 return base::Bind(&base::internal::RunBlock<R, A1>,
61 base::mac::ScopedBlock<R(^)(A1)>(Block_copy(block)));
62 }
63
64 // Construct a callback with two arguments from an objective-C block.
65 template<typename R, typename A1, typename A2>
66 base::Callback<R(A1, A2)> BindBlock(R(^block)(A1, A2)) {
67 return base::Bind(&base::internal::RunBlock<R, A1, A2>,
68 base::mac::ScopedBlock<R(^)(A1, A2)>(Block_copy(block)));
69 }
70
71 } // namespace base
72
73 #endif // BASE_MAC_BIND_OBJC_BLOCK_H_
74