1 /* 2 * Copyright (c) 2022 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 VIEW_PROXY_H 17 #define VIEW_PROXY_H 18 19 #include <memory> 20 #include <string> 21 #include <type_traits> 22 #include "components/ui_view.h" 23 #include "log/log.h" 24 25 namespace Updater { 26 class ViewProxy final { 27 public: 28 ViewProxy() = default; ViewProxy(std::unique_ptr<OHOS::UIView> view,const std::string & message)29 ViewProxy(std::unique_ptr<OHOS::UIView> view, const std::string &message) 30 : view_(std::move(view)), errMsg_(message) { } ViewProxy(std::unique_ptr<OHOS::UIView> view)31 explicit ViewProxy(std::unique_ptr<OHOS::UIView> view) : view_(std::move(view)) { } 32 ~ViewProxy() = default; 33 OHOS::UIView *operator->() const 34 { 35 static OHOS::UIView dummy; 36 if (view_ != nullptr) { 37 return view_.get(); 38 } 39 return &dummy; 40 } 41 template<typename T = OHOS::UIView> As()42 T *As() const 43 { 44 std::string errMsg {}; 45 return As<T>(errMsg); 46 } 47 template<typename T = OHOS::UIView> As(std::string & errMsg)48 T *As(std::string &errMsg) const 49 { 50 static T dummy; 51 static_assert(std::is_base_of_v<OHOS::UIView, T>, 52 "template argument should be a derived class of OHOS::UIView"); 53 if (view_ == nullptr) { 54 errMsg = errMsg_ + " view is null"; 55 return &dummy; 56 } 57 if constexpr (std::is_same_v<OHOS::UIView, T>) { 58 return static_cast<T *>(view_.get()); 59 } 60 if (dummy.GetViewType() != view_->GetViewType()) { 61 errMsg = errMsg_ + " view's real type not matched"; 62 LOG(ERROR) << errMsg; 63 return &dummy; 64 } 65 return static_cast<T *>(view_.get()); 66 } 67 private: 68 std::unique_ptr<OHOS::UIView> view_ {nullptr}; 69 std::string errMsg_ {}; 70 }; 71 } // namespace Updater 72 #endif 73