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 #include "bridge/cj_frontend/interfaces/cj_ffi/utils.h"
17 
18 #include "bridge/cj_frontend/frontend/cj_frontend_abstract.h"
19 
20 using namespace OHOS::Ace;
21 using namespace OHOS::Ace::Framework;
22 
MallocCString(const std::string & origin)23 ExternalString Utils::MallocCString(const std::string& origin)
24 {
25     if (origin.empty()) {
26         return {nullptr, nullptr};
27     }
28     auto len = origin.length() + 1;
29     char* res = (char*)malloc(sizeof(char) * len);
30     if (res == nullptr) {
31         return {nullptr, nullptr};
32     }
33     std::char_traits<char>::copy(res, origin.c_str(), len);
34     return {res, reinterpret_cast<void(*)(const void*)>(free)};
35 }
36 
GetCurrentFrontend()37 RefPtr<Frontend> Utils::GetCurrentFrontend()
38 {
39     auto container = Container::Current();
40     if (!container) {
41         container = Container::GetActive();
42         if (!container) {
43             LOGE("Can not found valid container");
44             return nullptr;
45         }
46     }
47     return container->GetFrontend();
48 }
49 
GetFunctionKey(int32_t functionKey)50 std::string Utils::GetFunctionKey(int32_t functionKey)
51 {
52     std::map<FunctionKey, std::string> keyNameMap {
53         {FunctionKey::ESC, "ESC"},
54         {FunctionKey::F1, "F1"},
55         {FunctionKey::F2, "F2"},
56         {FunctionKey::F3, "F3"},
57         {FunctionKey::F4, "F4"},
58         {FunctionKey::F5, "F5"},
59         {FunctionKey::F6, "F6"},
60         {FunctionKey::F7, "F7"},
61         {FunctionKey::F8, "F8"},
62         {FunctionKey::F9, "F9"},
63         {FunctionKey::F10, "F10"},
64         {FunctionKey::F11, "F11"},
65         {FunctionKey::F12, "F12"},
66         {FunctionKey::TAB, "TAB"},
67         {FunctionKey::DPAD_UP, "DPAD_UP"},
68         {FunctionKey::DPAD_DOWN, "DPAD_DOWN"},
69         {FunctionKey::DPAD_LEFT, "DPAD_LEFT"},
70         {FunctionKey::DPAD_RIGHT, "DPAD_RIGHT"}
71     };
72     auto result = keyNameMap.find(static_cast<FunctionKey>(functionKey));
73     return (result != keyNameMap.end()) ? result->second : std::string();
74 }
75