1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef META_API_PROPERTY_BINDING_H 17 #define META_API_PROPERTY_BINDING_H 18 19 #include <meta/api/function.h> 20 #include <meta/base/interface_macros.h> 21 #include <meta/base/interface_traits.h> 22 #include <meta/interface/property/property.h> 23 META_BEGIN_NAMESPACE()24META_BEGIN_NAMESPACE() 25 26 /** 27 * @brief The Binding class is a helper class for creating inline bindings for META_NS::Object properties. 28 */ 29 class Binding { 30 public: 31 META_NO_COPY(Binding) 32 META_DEFAULT_MOVE(Binding) 33 34 Binding() noexcept = default; 35 virtual ~Binding() = default; 36 37 explicit Binding(const IProperty::ConstPtr& source) noexcept : source_(source) {} 38 explicit Binding(const IFunction::ConstPtr& binding) noexcept : binding_(binding) {} 39 40 /** 41 * @brief Called by the framework to initialize the binding. 42 */ 43 virtual bool MakeBind(const IProperty::Ptr& target) 44 { 45 PropertyLock p(target); 46 if (target) { 47 if (binding_) { 48 return p->SetBind(binding_); 49 } 50 if (const auto source = source_.lock()) { 51 return p->SetBind(source); 52 } 53 // Reset bind 54 p->ResetBind(); 55 return true; 56 } 57 CORE_LOG_E("Cannot create binding: Invalid bind target"); 58 return false; 59 } 60 61 protected: 62 IProperty::ConstWeakPtr source_; 63 IFunction::ConstPtr binding_; 64 }; 65 66 /** 67 * @brief The TypedBinding class is a helper for creating typed binding objects. Usually it is enough 68 * to use the Binding class, TypedBinding is mostly helpful for cleaner syntax when defining 69 * bindings with a lambda function. 70 */ 71 template<class Type> 72 class TypedBinding : public Binding { 73 public: 74 using PropertyType = Property<BASE_NS::remove_const_t<Type>>; 75 76 META_NO_COPY_MOVE(TypedBinding) 77 78 ~TypedBinding() override = default; 79 TypedBinding() noexcept = default; 80 TypedBinding(const Property<const Type> & source)81 explicit TypedBinding(const Property<const Type>& source) noexcept : Binding(source) {} TypedBinding(const PropertyType & source)82 explicit TypedBinding(const PropertyType& source) noexcept : Binding(source) {} 83 84 template<class Callback, typename = EnableIfBindFunction<Callback>> TypedBinding(Callback && callback)85 explicit TypedBinding(Callback&& callback) : Binding(META_NS::CreateBindFunction(BASE_NS::move(callback))) 86 {} 87 }; 88 89 META_END_NAMESPACE() 90 91 #endif 92