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 #include "napi_base_context.h"
17
18 #define OHOS_CALL_NAPI_RETURN(call) \
19 do { \
20 napi_status ret = (call); \
21 if (ret != napi_ok) { \
22 return ret; \
23 } \
24 } while (0)
25
26 namespace OHOS {
27 namespace AbilityRuntime {
IsStageContext(napi_env env,napi_value object,bool & stageMode)28 napi_status IsStageContext(napi_env env, napi_value object, bool& stageMode)
29 {
30 napi_value boolValue;
31 OHOS_CALL_NAPI_RETURN(napi_get_named_property(env, object, "stageMode", &boolValue));
32
33 bool value = false;
34 OHOS_CALL_NAPI_RETURN(napi_get_value_bool(env, boolValue, &value));
35
36 stageMode = value;
37 return napi_ok;
38 }
39
GetStageModeContext(napi_env env,napi_value object)40 std::shared_ptr<Context> GetStageModeContext(napi_env env, napi_value object)
41 {
42 void* wrapped = nullptr;
43 napi_status ret = napi_unwrap(env, object, &wrapped);
44 if (ret != napi_ok) {
45 return nullptr;
46 }
47
48 auto weakContext = static_cast<std::weak_ptr<Context>*>(wrapped);
49 return weakContext != nullptr ? weakContext->lock() : nullptr;
50 }
51
GetCurrentAbility(napi_env env)52 AppExecFwk::Ability* GetCurrentAbility(napi_env env)
53 {
54 napi_value global;
55 napi_status status = napi_get_global(env, &global);
56 if (status != napi_ok) {
57 return nullptr;
58 }
59
60 napi_value abilityObj;
61 status = napi_get_named_property(env, global, "ability", &abilityObj);
62 if (status != napi_ok || abilityObj == nullptr) {
63 return nullptr;
64 }
65
66 void* pointer = nullptr;
67 status = napi_get_value_external(env, abilityObj, &pointer);
68 if (status != napi_ok) {
69 return nullptr;
70 }
71
72 return static_cast<AppExecFwk::Ability*>(pointer);
73 }
74 } // namespace AbilityRuntime
75 } // namespace OHOS
76