• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 #include <future>
17 #include <napi/native_api.h>
18 #include <napi/native_node_api.h>
19 #include <queue>
20 #include <set>
21 #include <string>
22 #include <unistd.h>
23 #include "json.hpp"
24 #include "pasteboard_client.h"
25 #include "common_utilities_hpp.h"
26 #include "frontend_api_defines.h"
27 #include "ipc_transactor.h"
28 #include "ui_event_observer_napi.h"
29 
30 namespace OHOS::uitest {
31     using namespace nlohmann;
32     using namespace std;
33 
34     static constexpr size_t NAPI_MAX_BUF_LEN = 1024;
35     static constexpr size_t NAPI_MAX_ARG_COUNT = 8;
36     static constexpr size_t BACKEND_OBJ_GC_BATCH = 100;
37     // type of unexpected or napi-internal error
38     static constexpr napi_status NAPI_ERR = napi_status::napi_generic_failure;
39     // the name of property that represents the objectRef of the backend object
40     static constexpr char PROP_BACKEND_OBJ_REF[] = "backendObjRef";
41     /**For dfx usage, records the uncalled js apis. */
42     static set<string> g_unCalledJsFuncNames;
43     /**For gc usage, records the backend objRefs about to delete. */
44     static queue<string> g_backendObjsAboutToDelete;
45     static mutex g_gcQueueMutex;
46     /**IPC client. */
47     static ApiTransactor g_apiTransactClient(false);
48     static future<void> g_establishConnectionFuture;
49 
50     /** Convert js string to cpp string.*/
JsStrToCppStr(napi_env env,napi_value jsStr)51     static string JsStrToCppStr(napi_env env, napi_value jsStr)
52     {
53         if (jsStr == nullptr) {
54             return "";
55         }
56         napi_valuetype type;
57         NAPI_CALL_BASE(env, napi_typeof(env, jsStr, &type), "");
58         if (type == napi_undefined || type == napi_null) {
59             return "";
60         }
61         size_t bufSize = 0;
62         char buf[NAPI_MAX_BUF_LEN] = {0};
63         NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, jsStr, buf, NAPI_MAX_BUF_LEN, &bufSize), "");
64         return string(buf, bufSize);
65     }
66 
67     /**Lifecycle function, establish connection async, called externally.*/
ScheduleEstablishConnection(napi_env env,napi_callback_info info)68     static napi_value ScheduleEstablishConnection(napi_env env, napi_callback_info info)
69     {
70         size_t argc = 1;
71         napi_value value = nullptr;
72         napi_value argv[1] = {0};
73         NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &value, nullptr));
74         NAPI_ASSERT(env, argc > 0, "Need session token argument!");
75         auto token = JsStrToCppStr(env, argv[0]);
76         g_establishConnectionFuture = async(launch::async, [env, token]() {
77             auto &instance = UiEventObserverNapi::Get();
78             using namespace std::placeholders;
79             auto callbackHandler = std::bind(&UiEventObserverNapi::HandleEventCallback, &instance, env, _1, _2);
80             auto result = g_apiTransactClient.InitAndConnectPeer(token, callbackHandler);
81             LOG_I("End setup transaction connection, result=%{public}d", result);
82         });
83         return nullptr;
84     }
85 
86     /**Wait connection result sync if need.*/
WaitForConnectionIfNeed()87     static void WaitForConnectionIfNeed()
88     {
89         if (g_establishConnectionFuture.valid()) {
90             LOG_I("Begin WaitForConnection");
91             g_establishConnectionFuture.get();
92         }
93     }
94 
95     /**Encapsulates the data objects needed in once api transaction.*/
96     struct TransactionContext {
97         napi_value jsThis_ = nullptr;
98         napi_value *jsArgs_ = nullptr;
99         ApiCallInfo callInfo_;
100     };
101 
CreateJsException(napi_env env,uint32_t code,string_view msg)102     static napi_value CreateJsException(napi_env env, uint32_t code, string_view msg)
103     {
104         napi_value codeValue, msgValue, errorValue;
105         napi_create_uint32(env, code, &codeValue);
106         napi_create_string_utf8(env, msg.data(), NAPI_AUTO_LENGTH, &msgValue);
107         napi_create_error(env, nullptr, msgValue, &errorValue);
108         napi_set_named_property(env, errorValue, "code", codeValue);
109         return errorValue;
110     }
111 
112     /**Set object constructor function to global as attribute.*/
MountJsConstructorToGlobal(napi_env env,string_view typeName,napi_value function)113     static napi_status MountJsConstructorToGlobal(napi_env env, string_view typeName, napi_value function)
114     {
115         NAPI_ASSERT_BASE(env, function != nullptr, "Null constructor function", napi_invalid_arg);
116         const string name = "constructor_" + string(typeName);
117         napi_value global = nullptr;
118         NAPI_CALL_BASE(env, napi_get_global(env, &global), NAPI_ERR);
119         NAPI_CALL_BASE(env, napi_set_named_property(env, global, name.c_str(), function), NAPI_ERR);
120         return napi_ok;
121     }
122 
123     /**Get object constructor function from global as attribute.*/
GetJsConstructorFromGlobal(napi_env env,string_view typeName,napi_value * pFunction)124     static napi_status GetJsConstructorFromGlobal(napi_env env, string_view typeName, napi_value *pFunction)
125     {
126         NAPI_ASSERT_BASE(env, pFunction != nullptr, "Null constructor receiver", napi_invalid_arg);
127         const string name = "constructor_" + string(typeName);
128         napi_value global = nullptr;
129         NAPI_CALL_BASE(env, napi_get_global(env, &global), NAPI_ERR);
130         NAPI_CALL_BASE(env, napi_get_named_property(env, global, name.c_str(), pFunction), NAPI_ERR);
131         return napi_ok;
132     }
133 
134     /**Conversion between value and string, using the builtin JSON methods.*/
ValueStringConvert(napi_env env,napi_value in,napi_value * out,bool stringify)135     static napi_status ValueStringConvert(napi_env env, napi_value in, napi_value *out, bool stringify)
136     {
137         if (in == nullptr || out == nullptr) {
138             return napi_invalid_arg;
139         }
140         napi_value global = nullptr;
141         napi_value jsonProp = nullptr;
142         napi_value jsonFunc = nullptr;
143         NAPI_CALL_BASE(env, napi_get_global(env, &global), NAPI_ERR);
144         NAPI_CALL_BASE(env, napi_get_named_property(env, global, "JSON", &jsonProp), NAPI_ERR);
145         if (stringify) {
146             NAPI_CALL_BASE(env, napi_get_named_property(env, jsonProp, "stringify", &jsonFunc), NAPI_ERR);
147         } else {
148             NAPI_CALL_BASE(env, napi_get_named_property(env, jsonProp, "parse", &jsonFunc), NAPI_ERR);
149         }
150         napi_value argv[1] = {in};
151         NAPI_CALL_BASE(env, napi_call_function(env, jsonProp, jsonFunc, 1, argv, out), NAPI_ERR);
152         return napi_ok;
153     }
154 
155     /**Unmarshal object from json, throw error and return false if the object cannot be deserialized.*/
UnmarshalObject(napi_env env,const json & in,napi_value * pOut,napi_value jsThis)156     static napi_status UnmarshalObject(napi_env env, const json &in, napi_value *pOut, napi_value jsThis)
157     {
158         NAPI_ASSERT_BASE(env, pOut != nullptr, "Illegal arguments", napi_invalid_arg);
159         const auto type = in.type();
160         if (type == nlohmann::detail::value_t::null) { // return null
161             NAPI_CALL_BASE(env, napi_get_null(env, pOut), NAPI_ERR);
162             return napi_ok;
163         }
164         if (type != nlohmann::detail::value_t::string) { // non-string value, convert and return object
165             NAPI_CALL_BASE(env, napi_create_string_utf8(env, in.dump().c_str(), NAPI_AUTO_LENGTH, pOut), NAPI_ERR);
166             NAPI_CALL_BASE(env, ValueStringConvert(env, *pOut, pOut, false), NAPI_ERR);
167             return napi_ok;
168         }
169         const auto cppString = in.get<string>();
170         string frontendTypeName;
171         bool bindJsThis = false;
172         for (const auto &classDef : FRONTEND_CLASS_DEFS) {
173             const auto objRefFormat = string(classDef->name_) + "#";
174             if (cppString.find(objRefFormat) == 0) {
175                 frontendTypeName = string(classDef->name_);
176                 bindJsThis = classDef->bindUiDriver_;
177                 break;
178             }
179         }
180         NAPI_CALL_BASE(env, napi_create_string_utf8(env, cppString.c_str(), NAPI_AUTO_LENGTH, pOut), NAPI_ERR);
181         if (frontendTypeName.empty()) { // plain string, return it
182             return napi_ok;
183         }
184         LOG_D("Convert to frontend object: '%{public}s'", frontendTypeName.c_str());
185         // covert to wrapper object and bind the backend objectRef
186         napi_value refValue = *pOut;
187         napi_value constructor = nullptr;
188         NAPI_CALL_BASE(env, GetJsConstructorFromGlobal(env, frontendTypeName, &constructor), NAPI_ERR);
189         NAPI_CALL_BASE(env, napi_new_instance(env, constructor, 1, &refValue, pOut), NAPI_ERR);
190         NAPI_CALL_BASE(env, napi_set_named_property(env, *pOut, PROP_BACKEND_OBJ_REF, refValue), NAPI_ERR);
191         if (bindJsThis) { // bind the jsThis object
192             LOG_D("Bind jsThis");
193             NAPI_ASSERT_BASE(env, jsThis != nullptr, "null jsThis", NAPI_ERR);
194             NAPI_CALL_BASE(env, napi_set_named_property(env, *pOut, "boundObject", jsThis), NAPI_ERR);
195         }
196         return napi_ok;
197     }
198 
199     /**Evaluate and convert transaction reply to object. Return the exception raised during the
200      * transaction if any, else return the result object. */
UnmarshalReply(napi_env env,const TransactionContext & ctx,const ApiReplyInfo & reply)201     static napi_value UnmarshalReply(napi_env env, const TransactionContext &ctx, const ApiReplyInfo &reply)
202     {
203         if (ctx.callInfo_.fdParamIndex_ >= 0) {
204             auto fd = ctx.callInfo_.paramList_.at(INDEX_ZERO).get<int>();
205             (void) close(fd);
206         }
207         LOG_D("Start to Unmarshal transaction result");
208         const auto &message = reply.exception_.message_;
209         ErrCode code = reply.exception_.code_;
210         if (code == INTERNAL_ERROR || code == ERR_INTERNAL) {
211             LOG_E("ErrorInfo: code='%{public}u', message='%{public}s'", code, message.c_str());
212         } else if (reply.exception_.code_ != NO_ERROR) {
213             LOG_I("ErrorInfo: code='%{public}u', message='%{public}s'", code, message.c_str());
214             return CreateJsException(env, code, message);
215         }
216         LOG_D("Start to Unmarshal return value: %{public}s", reply.resultValue_.dump().c_str());
217         const auto resultType = reply.resultValue_.type();
218         napi_value result = nullptr;
219         if (resultType == nlohmann::detail::value_t::null) { // return null
220             NAPI_CALL(env, napi_get_null(env, &result));
221         } else if (resultType == nlohmann::detail::value_t::array) { // return array
222             NAPI_CALL(env, napi_create_array_with_length(env, reply.resultValue_.size(), &result));
223             for (size_t idx = 0; idx < reply.resultValue_.size(); idx++) {
224                 napi_value item = nullptr;
225                 NAPI_CALL(env, UnmarshalObject(env, reply.resultValue_.at(idx), &item, ctx.jsThis_));
226                 NAPI_CALL(env, napi_set_element(env, result, idx, item));
227             }
228         } else { // return single value
229             NAPI_CALL(env, UnmarshalObject(env, reply.resultValue_, &result, ctx.jsThis_));
230         }
231         return result;
232     }
233 
234     /**Call api with parameters out, wait for and return result value or throw raised exception.*/
TransactSync(napi_env env,TransactionContext & ctx)235     napi_value TransactSync(napi_env env, TransactionContext &ctx)
236     {
237         WaitForConnectionIfNeed();
238         LOG_D("TargetApi=%{public}s", ctx.callInfo_.apiId_.data());
239         auto reply = ApiReplyInfo();
240         g_apiTransactClient.Transact(ctx.callInfo_, reply);
241         auto resultValue = UnmarshalReply(env, ctx, reply);
242         auto isError = false;
243         NAPI_CALL(env, napi_is_error(env, resultValue, &isError));
244         if (isError) {
245             NAPI_CALL(env, napi_throw(env, resultValue));
246             NAPI_CALL(env, napi_get_undefined(env, &resultValue)); // return undefined it's error
247         }
248         // notify backend objects deleting
249         if (g_backendObjsAboutToDelete.size() >= BACKEND_OBJ_GC_BATCH) {
250             auto gcCall = ApiCallInfo {.apiId_ = "BackendObjectsCleaner"};
251             unique_lock<mutex> lock(g_gcQueueMutex);
252             for (size_t count = 0; count < BACKEND_OBJ_GC_BATCH; count++) {
253                 gcCall.paramList_.emplace_back(g_backendObjsAboutToDelete.front());
254                 g_backendObjsAboutToDelete.pop();
255             }
256             lock.unlock();
257             auto gcReply = ApiReplyInfo();
258             g_apiTransactClient.Transact(gcCall, gcReply);
259         }
260         return resultValue;
261     }
262 
263     /**Encapsulates the data objects needed for async transaction.*/
264     struct AsyncTransactionCtx {
265         TransactionContext ctx_;
266         ApiReplyInfo reply_;
267         napi_async_work asyncWork_ = nullptr;
268         napi_deferred deferred_ = nullptr;
269         napi_ref jsThisRef_ = nullptr;
270     };
271 
272     /**Call api with parameters out, return a promise.*/
TransactAsync(napi_env env,TransactionContext & ctx)273     static napi_value TransactAsync(napi_env env, TransactionContext &ctx)
274     {
275         constexpr uint32_t refCount = 1;
276         LOG_D("TargetApi=%{public}s", ctx.callInfo_.apiId_.data());
277         napi_value resName;
278         NAPI_CALL(env, napi_create_string_latin1(env, __FUNCTION__, NAPI_AUTO_LENGTH, &resName));
279         auto aCtx = new AsyncTransactionCtx();
280         aCtx->ctx_ = ctx;
281         napi_value promise;
282         NAPI_CALL(env, napi_create_promise(env, &(aCtx->deferred_), &promise));
283         NAPI_CALL(env, napi_create_reference(env, ctx.jsThis_, refCount, &(aCtx->jsThisRef_)));
284         napi_create_async_work(
285             env, nullptr, resName,
286             [](napi_env env, void *data) {
287                 auto aCtx = reinterpret_cast<AsyncTransactionCtx *>(data);
288                 // NOT:: use 'auto&' rather than 'auto', or the result will be set to copy-constructed temp-object
289                 auto &ctx = aCtx->ctx_;
290                 g_apiTransactClient.Transact(ctx.callInfo_, aCtx->reply_);
291             },
292             [](napi_env env, napi_status status, void *data) {
293                 auto aCtx = reinterpret_cast<AsyncTransactionCtx *>(data);
294                 napi_handle_scope scope = nullptr;
295                 napi_open_handle_scope(env, &scope);
296                 if (scope == nullptr) {
297                     return;
298                 }
299                 napi_get_reference_value(env, aCtx->jsThisRef_, &(aCtx->ctx_.jsThis_));
300                 auto resultValue = UnmarshalReply(env, aCtx->ctx_, aCtx->reply_);
301                 napi_delete_reference(env, aCtx->jsThisRef_);
302                 auto isError = false;
303                 napi_is_error(env, resultValue, &isError);
304                 if (isError) {
305                     napi_reject_deferred(env, aCtx->deferred_, resultValue);
306                 } else {
307                     napi_resolve_deferred(env, aCtx->deferred_, resultValue);
308                 }
309                 napi_delete_async_work(env, aCtx->asyncWork_);
310                 napi_close_handle_scope(env, scope);
311                 delete aCtx;
312             },
313             (void *)aCtx, &(aCtx->asyncWork_));
314         napi_queue_async_work(env, aCtx->asyncWork_);
315         return promise;
316     }
317 
GetBackendObjRefProp(napi_env env,napi_value value,napi_value * pOut)318     static napi_status GetBackendObjRefProp(napi_env env, napi_value value, napi_value* pOut)
319     {
320         napi_valuetype type = napi_undefined;
321         NAPI_CALL_BASE(env, napi_typeof(env, value, &type), NAPI_ERR);
322         if (type != napi_object) {
323             *pOut = nullptr;
324             return napi_ok;
325         }
326         bool hasRef = false;
327         NAPI_CALL_BASE(env, napi_has_named_property(env, value, PROP_BACKEND_OBJ_REF, &hasRef), NAPI_ERR);
328         if (!hasRef) {
329             *pOut = nullptr;
330         } else {
331             NAPI_CALL_BASE(env, napi_get_named_property(env, value, PROP_BACKEND_OBJ_REF, pOut), NAPI_ERR);
332         }
333         return napi_ok;
334     }
335 
SetPasteBoardData(string_view text)336     static void SetPasteBoardData(string_view text)
337     {
338         auto pasteBoardMgr = MiscServices::PasteboardClient::GetInstance();
339         pasteBoardMgr->Clear();
340         auto pasteData = MiscServices::PasteboardClient::GetInstance()->CreatePlainTextData(string(text));
341         pasteBoardMgr->SetPasteData(*pasteData);
342     }
343 
PreprocessTransaction(napi_env env,TransactionContext & ctx,napi_value & error)344     static void PreprocessTransaction(napi_env env, TransactionContext &ctx, napi_value &error)
345     {
346         auto &paramList = ctx.callInfo_.paramList_;
347         const auto &id = ctx.callInfo_.apiId_;
348         if (id  == "Component.inputText" && paramList.size() > 0) {
349             auto text = paramList.at(INDEX_ZERO).get<string>();
350             SetPasteBoardData(text);
351         } else if (id  == "Driver.screenCap" || id  == "UiDriver.screenCap" || id  == "Driver.screenCapture") {
352             if (paramList.size() < 1 || paramList.at(0).type() != nlohmann::detail::value_t::string) {
353                 LOG_E("Missing file path argument");
354                 error = CreateJsException(env, ERR_INVALID_INPUT, "Missing file path argument");
355                 return;
356             }
357             auto path = paramList.at(INDEX_ZERO).get<string>();
358             auto fd = open(path.c_str(), O_RDWR | O_CREAT, 0666);
359             if (fd == -1) {
360                 LOG_E("Invalid file path: %{public}s", path.data());
361                 error = CreateJsException(env, ERR_INVALID_INPUT, "Invalid file path:" + path);
362                 return;
363             }
364             paramList[INDEX_ZERO] = fd;
365             ctx.callInfo_.fdParamIndex_ = INDEX_ZERO;
366         } else if (id  == "UIEventObserver.once") {
367             auto err = ApiCallErr(NO_ERROR);
368             UiEventObserverNapi::Get().PreprocessCallOnce(env, ctx.callInfo_, ctx.jsThis_, ctx.jsArgs_, err);
369             if (err.code_ != NO_ERROR) {
370                 error = CreateJsException(env, err.code_, err.message_);
371             }
372         }
373     }
374 
375     /**Generic js-api callback.*/
GenericCallback(napi_env env,napi_callback_info info)376     static napi_value GenericCallback(napi_env env, napi_callback_info info)
377     {
378         // extract callback data
379         TransactionContext ctx;
380         napi_value argv[NAPI_MAX_ARG_COUNT] = {nullptr};
381         auto count = NAPI_MAX_ARG_COUNT;
382         void *pData = nullptr;
383         NAPI_CALL(env, napi_get_cb_info(env, info, &count, argv, &(ctx.jsThis_), &pData));
384         NAPI_ASSERT(env, pData != nullptr, "Null methodDef");
385         ctx.jsArgs_ = argv;
386         auto methodDef = reinterpret_cast<const FrontendMethodDef *>(pData);
387         g_unCalledJsFuncNames.erase(string(methodDef->name_)); // api used
388         // 1. marshal parameters into json-array
389         napi_value paramArray = nullptr;
390         NAPI_CALL(env, napi_create_array_with_length(env, count, &paramArray));
391         if (count > NAPI_MAX_ARG_COUNT) {
392             count = NAPI_MAX_ARG_COUNT;
393         }
394         for (size_t idx = 0; idx < count; idx++) {
395             napi_value item = nullptr; // convert to backendObjRef if any
396             NAPI_CALL(env, GetBackendObjRefProp(env, argv[idx], &item));
397             if (item == nullptr) {
398                 item = argv[idx];
399             }
400             NAPI_CALL(env, napi_set_element(env, paramArray, idx, item));
401         }
402         napi_value jsTempObj = nullptr;
403         NAPI_CALL(env, ValueStringConvert(env, paramArray, &jsTempObj, true));
404         ctx.callInfo_.paramList_ = nlohmann::json::parse(JsStrToCppStr(env, jsTempObj));
405         // 2. marshal jsThis into json (backendObjRef)
406         if (!methodDef->static_) {
407             NAPI_CALL(env, GetBackendObjRefProp(env, ctx.jsThis_, &jsTempObj));
408             ctx.callInfo_.callerObjRef_ = JsStrToCppStr(env, jsTempObj);
409         }
410         // 3. fill-in apiId
411         ctx.callInfo_.apiId_ = methodDef->name_;
412         napi_value error = nullptr;
413         PreprocessTransaction(env, ctx, error);
414         if (error != nullptr) {
415             NAPI_CALL(env, napi_throw(env, error));
416             NAPI_CALL(env, napi_get_undefined(env, &error));
417             return error;
418         }
419         // 4. call out, sync or async
420         if (methodDef->fast_) {
421             return TransactSync(env, ctx);
422         } else {
423             return TransactAsync(env, ctx);
424         }
425     }
426 
427     /**Exports uitest js wrapper-classes and its global constructor.*/
ExportClass(napi_env env,napi_value exports,const FrontEndClassDef & classDef)428     static napi_status ExportClass(napi_env env, napi_value exports, const FrontEndClassDef &classDef)
429     {
430         NAPI_ASSERT_BASE(env, exports != nullptr, "Illegal export params", NAPI_ERR);
431         const auto name = classDef.name_.data();
432         const auto methodNeatNameOffset = classDef.name_.length() + 1;
433         auto descs = make_unique<napi_property_descriptor[]>(classDef.methodCount_);
434         for (size_t idx = 0; idx < classDef.methodCount_; idx++) {
435             const auto &methodDef = classDef.methods_[idx];
436             g_unCalledJsFuncNames.insert(string(methodDef.name_));
437             const auto neatName = methodDef.name_.substr(methodNeatNameOffset);
438             napi_property_descriptor desc = DECLARE_NAPI_FUNCTION(neatName.data(), GenericCallback);
439             if (methodDef.static_) {
440                 desc.attributes = napi_static;
441             }
442             desc.data = (void *)(&methodDef);
443             descs[idx] = desc;
444         }
445         constexpr auto initializer = [](napi_env env, napi_callback_info info) {
446             auto argc = NAPI_MAX_ARG_COUNT;
447             napi_value argv[NAPI_MAX_ARG_COUNT] = { nullptr };
448             napi_value jsThis = nullptr;
449             NAPI_CALL_BASE(env, napi_get_cb_info(env, info, &argc, argv, &jsThis, nullptr), jsThis);
450             auto ref = make_unique<string>(argc <= 0 ? "" : JsStrToCppStr(env, argv[0]));
451             auto finalizer = [](napi_env env, void *data, void *hint) {
452                 auto ref = reinterpret_cast<string *>(data);
453                 if (ref->length() > 0) {
454                     LOG_D("Finalizing object: %{public}s", ref->c_str());
455                     unique_lock<mutex> lock(g_gcQueueMutex);
456                     g_backendObjsAboutToDelete.push(*ref);
457                 }
458                 delete ref;
459             };
460             NAPI_CALL_BASE(env, napi_wrap(env, jsThis, ref.release(), finalizer, nullptr, nullptr), jsThis);
461             return jsThis;
462         };
463         // define class, provide the js-class members(property) and initializer.
464         napi_value ctor = nullptr;
465         NAPI_CALL_BASE(env, napi_define_class(env, name, NAPI_AUTO_LENGTH, initializer, nullptr,
466                                               classDef.methodCount_, descs.get(), &ctor), NAPI_ERR);
467         NAPI_CALL_BASE(env, napi_set_named_property(env, exports, name, ctor), NAPI_ERR);
468         NAPI_CALL_BASE(env, MountJsConstructorToGlobal(env, name, ctor), NAPI_ERR);
469         if (string_view(name) == "On" || string_view(name) == "By") {
470             // create seed-On/By with special objectRef and mount to exporter
471             auto seedName = string_view(name) == "On" ? "ON" : "BY";
472             auto seedRef = string_view(name) == "On" ? REF_SEED_ON.data() : REF_SEED_BY.data();
473             napi_value seed = nullptr;
474             NAPI_CALL_BASE(env, napi_new_instance(env, ctor, 0, nullptr, &seed), NAPI_ERR);
475             napi_value prop = nullptr;
476             NAPI_CALL_BASE(env, napi_create_string_utf8(env, seedRef, NAPI_AUTO_LENGTH, &prop), NAPI_ERR);
477             NAPI_CALL_BASE(env, napi_set_named_property(env, seed, PROP_BACKEND_OBJ_REF, prop), NAPI_ERR);
478             NAPI_CALL_BASE(env, napi_set_named_property(env, exports, seedName, seed), NAPI_ERR);
479         }
480         return napi_ok;
481     }
482 
483     /**Exports enumerator class.*/
ExportEnumerator(napi_env env,napi_value exports,const FrontendEnumeratorDef & enumDef)484     static napi_status ExportEnumerator(napi_env env, napi_value exports, const FrontendEnumeratorDef &enumDef)
485     {
486         NAPI_ASSERT_BASE(env, exports != nullptr, "Illegal export params", NAPI_ERR);
487         napi_value enumerator;
488         NAPI_CALL_BASE(env, napi_create_object(env, &enumerator), NAPI_ERR);
489         for (size_t idx = 0; idx < enumDef.valueCount_; idx++) {
490             const auto &def = enumDef.values_[idx];
491             napi_value prop = nullptr;
492             NAPI_CALL_BASE(env, napi_create_string_utf8(env, def.valueJson_.data(), NAPI_AUTO_LENGTH, &prop), NAPI_ERR);
493             NAPI_CALL_BASE(env, ValueStringConvert(env, prop, &prop, false), NAPI_ERR);
494             NAPI_CALL_BASE(env, napi_set_named_property(env, enumerator, def.name_.data(), prop), NAPI_ERR);
495         }
496         NAPI_CALL_BASE(env, napi_set_named_property(env, exports, enumDef.name_.data(), enumerator), NAPI_ERR);
497         return napi_ok;
498     }
499 
500     /**Function used for statistics, return an array of uncalled js-api names.*/
GetUnCalledJsApis(napi_env env,napi_callback_info info)501     static napi_value GetUnCalledJsApis(napi_env env, napi_callback_info info)
502     {
503         napi_value nameArray;
504         NAPI_CALL(env, napi_create_array_with_length(env, g_unCalledJsFuncNames.size(), &nameArray));
505         size_t idx = 0;
506         for (auto &name : g_unCalledJsFuncNames) {
507             napi_value nameItem = nullptr;
508             NAPI_CALL(env, napi_create_string_utf8(env, name.c_str(), NAPI_AUTO_LENGTH, &nameItem));
509             NAPI_CALL(env, napi_set_element(env, nameArray, idx, nameItem));
510             idx++;
511         }
512         return nameArray;
513     }
514 
Export(napi_env env,napi_value exports)515     napi_value Export(napi_env env, napi_value exports)
516     {
517         LOG_I("Begin export uitest apis");
518         // export transaction-environment-lifecycle callbacks and dfx functions
519         napi_property_descriptor props[] = {
520             DECLARE_NAPI_STATIC_FUNCTION("scheduleEstablishConnection", ScheduleEstablishConnection),
521             DECLARE_NAPI_STATIC_FUNCTION("getUnCalledJsApis", GetUnCalledJsApis),
522         };
523         NAPI_CALL(env, napi_define_properties(env, exports, sizeof(props) / sizeof(props[0]), props));
524         NAPI_CALL(env, ExportClass(env, exports, BY_DEF));
525         NAPI_CALL(env, ExportClass(env, exports, UI_DRIVER_DEF));
526         NAPI_CALL(env, ExportClass(env, exports, UI_COMPONENT_DEF));
527         NAPI_CALL(env, ExportClass(env, exports, ON_DEF));
528         NAPI_CALL(env, ExportClass(env, exports, DRIVER_DEF));
529         NAPI_CALL(env, ExportClass(env, exports, COMPONENT_DEF));
530         NAPI_CALL(env, ExportClass(env, exports, UI_WINDOW_DEF));
531         NAPI_CALL(env, ExportClass(env, exports, POINTER_MATRIX_DEF));
532         NAPI_CALL(env, ExportClass(env, exports, UI_EVENT_OBSERVER_DEF));
533         NAPI_CALL(env, ExportEnumerator(env, exports, MATCH_PATTERN_DEF));
534         NAPI_CALL(env, ExportEnumerator(env, exports, RESIZE_DIRECTION_DEF));
535         NAPI_CALL(env, ExportEnumerator(env, exports, WINDOW_MODE_DEF));
536         NAPI_CALL(env, ExportEnumerator(env, exports, DISPLAY_ROTATION_DEF));
537         NAPI_CALL(env, ExportEnumerator(env, exports, MOUSE_BUTTON_DEF));
538         NAPI_CALL(env, ExportEnumerator(env, exports, UI_DIRECTION_DEF));
539         LOG_I("End export uitest apis");
540         return exports;
541     }
542 
543     static napi_module module = {
544         .nm_version = 1,
545         .nm_flags = 0,
546         .nm_filename = nullptr,
547         .nm_register_func = Export,
548         .nm_modname = "UiTest",
549         .nm_priv = ((void *)0),
550         .reserved = {0},
551     };
552 
RegisterModule(void)553     extern "C" __attribute__((constructor)) void RegisterModule(void)
554     {
555         napi_module_register(&module);
556     }
557 } // namespace OHOS::uitest
558 
559 // put register functions out of namespace to ensure C-linkage
560 extern const char _binary_uitest_exporter_js_start[];
561 extern const char _binary_uitest_exporter_js_end[];
562 extern const char _binary_uitest_exporter_abc_start[];
563 extern const char _binary_uitest_exporter_abc_end[];
564 
NAPI_UiTest_GetJSCode(const char ** buf,int * bufLen)565 extern "C" __attribute__((visibility("default"))) void NAPI_UiTest_GetJSCode(const char **buf, int *bufLen)
566 {
567     if (buf != nullptr) {
568         *buf = _binary_uitest_exporter_js_start;
569     }
570     if (bufLen != nullptr) {
571         *bufLen = _binary_uitest_exporter_js_end - _binary_uitest_exporter_js_start;
572     }
573 }
574 
NAPI_UiTest_GetABCCode(const char ** buf,int * bufLen)575 extern "C" __attribute__((visibility("default"))) void NAPI_UiTest_GetABCCode(const char **buf, int *bufLen)
576 {
577     if (buf != nullptr) {
578         *buf = _binary_uitest_exporter_abc_start;
579     }
580     if (bufLen != nullptr) {
581         *bufLen = _binary_uitest_exporter_abc_end - _binary_uitest_exporter_abc_start;
582     }
583 }
584