Home | History | Annotate | Download | only in mac
      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 // Callback<int(void)> callback = BindBlock(^{return 42;});
     18 
     19 namespace base {
     20 
     21 namespace internal {
     22 
     23 // Helper functions to run the block contained in the parameter.
     24 template<typename R>
     25 R RunBlock(base::mac::ScopedBlock<R(^)()> block) {
     26   R(^extracted_block)() = block.get();
     27   return extracted_block();
     28 }
     29 
     30 template<typename R, typename A1>
     31 R RunBlock(base::mac::ScopedBlock<R(^)(A1)> block, A1 a) {
     32   R(^extracted_block)(A1) = block.get();
     33   return extracted_block(a);
     34 }
     35 
     36 }  // namespace internal
     37 
     38 // Construct a callback with no argument from an objective-C block.
     39 template<typename R>
     40 base::Callback<R(void)> BindBlock(R(^block)()) {
     41   return base::Bind(&base::internal::RunBlock<R>,
     42                     base::mac::ScopedBlock<R(^)()>(Block_copy(block)));
     43 }
     44 
     45 // Construct a callback with one argument from an objective-C block.
     46 template<typename R, typename A1>
     47 base::Callback<R(A1)> BindBlock(R(^block)(A1)) {
     48   return base::Bind(&base::internal::RunBlock<R, A1>,
     49                     base::mac::ScopedBlock<R(^)(A1)>(Block_copy(block)));
     50 }
     51 
     52 }  // namespace base
     53 
     54 #endif  // BASE_MAC_BIND_OBJC_BLOCK_H_
     55