1 /* 2 * Copyright (c) 2021 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 FOUNDATION_ACE_CORE_COMPONENTS_MULTI_CHILD_H 17 #define FOUNDATION_ACE_CORE_COMPONENTS_MULTI_CHILD_H 18 19 #include <list> 20 21 #include "base/memory/ace_type.h" 22 #include "core/pipeline/base/component.h" 23 24 namespace OHOS::Ace { 25 26 class MultiChild : public virtual AceType { 27 DECLARE_ACE_TYPE(MultiChild, AceType); 28 29 public: 30 MultiChild() = default; MultiChild(const std::list<RefPtr<Component>> & children)31 explicit MultiChild(const std::list<RefPtr<Component>>& children) : children_(children) {} 32 ~MultiChild() override = default; 33 GetChildren()34 const std::list<RefPtr<Component>>& GetChildren() 35 { 36 return ExpandChildren(); 37 } 38 AddChild(const RefPtr<Component> & child)39 void AddChild(const RefPtr<Component>& child) 40 { 41 if (!child) { 42 return; 43 } 44 45 auto& children = ExpandChildren(); 46 auto it = std::find(children.begin(), children.end(), child); 47 if (it != children.end()) { 48 return; 49 } 50 51 child->SetParent(AceType::WeakClaim(AceType::DynamicCast<Component>(this))); 52 children.emplace_back(child); 53 } 54 RemoveChild(const RefPtr<Component> & child)55 void RemoveChild(const RefPtr<Component>& child) 56 { 57 if (!child) { 58 return; 59 } 60 61 auto& children = ExpandChildren(); 62 auto it = std::find(children.begin(), children.end(), child); 63 if (it == children.end()) { 64 return; 65 } 66 67 child->SetParent(nullptr); 68 children.erase(it); 69 } 70 RemoveChildren()71 void RemoveChildren() 72 { 73 auto& children = ExpandChildren(); 74 for (auto& child : children) { 75 child->SetParent(nullptr); 76 } 77 children.clear(); 78 } 79 Count()80 virtual size_t Count() 81 { 82 const auto& children = GetChildren(); 83 size_t count = children.size(); 84 for (const auto& child : children) { 85 auto multiChild = AceType::DynamicCast<MultiChild>(child); 86 if (multiChild) { 87 --count; 88 count += multiChild->Count(); 89 } 90 } 91 return count; 92 } 93 94 protected: ExpandChildren()95 virtual std::list<RefPtr<Component>>& ExpandChildren() 96 { 97 return children_; 98 } 99 100 std::list<RefPtr<Component>> children_; 101 }; 102 103 } // namespace OHOS::Ace 104 105 #endif // FOUNDATION_ACE_CORE_COMPONENTS_MULTI_CHILD_H 106