• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 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 "pasteboard_observer_napi.h"
17 
18 #include <sys/syscall.h>
19 #include "pasteboard_hilog.h"
20 
21 #include <thread>
22 
23 using namespace OHOS::MiscServices;
24 
25 namespace OHOS {
26 namespace MiscServicesNapi {
PasteboardObserverInstance(napi_threadsafe_function callback,napi_env env)27 PasteboardObserverInstance::PasteboardObserverInstance(napi_threadsafe_function callback, napi_env env)
28     : callback_(callback), env_(env)
29 {
30 }
31 
~PasteboardObserverInstance()32 PasteboardObserverInstance::~PasteboardObserverInstance()
33 {
34     napi_status status = napi_release_threadsafe_function(callback_, napi_tsfn_release);
35     PASTEBOARD_CHECK_AND_RETURN_LOGE(status == napi_ok, PASTEBOARD_MODULE_JS_NAPI,
36         "release callback failed, status=%{public}d", status);
37 }
38 
OnPasteboardChanged()39 void PasteboardObserverInstance::OnPasteboardChanged()
40 {
41     pid_t threadId = syscall(SYS_gettid);
42     PASTEBOARD_HILOGD(PASTEBOARD_MODULE_JS_NAPI, "enter");
43     auto task = [callback = callback_, threadId]() {
44         PASTEBOARD_HILOGI(PASTEBOARD_MODULE_JS_NAPI, "napi_send_event start, originTid=%{public}d", threadId);
45         napi_status status = napi_acquire_threadsafe_function(callback);
46         PASTEBOARD_CHECK_AND_RETURN_LOGE(status == napi_ok, PASTEBOARD_MODULE_JS_NAPI,
47             "acquire callback failed, status=%{public}d", status);
48         status = napi_call_threadsafe_function(callback, nullptr, napi_tsfn_blocking);
49         if (status != napi_ok) {
50             PASTEBOARD_HILOGE(PASTEBOARD_MODULE_JS_NAPI, "call callback failed, status=%{public}d", status);
51         }
52         status = napi_release_threadsafe_function(callback, napi_tsfn_release);
53         PASTEBOARD_CHECK_AND_RETURN_LOGE(status == napi_ok, PASTEBOARD_MODULE_JS_NAPI,
54             "release callback failed, status=%{public}d", status);
55     };
56     auto ret = napi_send_event(env_, task, napi_eprio_high);
57     PASTEBOARD_CHECK_AND_RETURN_LOGE(ret == napi_ok, PASTEBOARD_MODULE_JS_NAPI,
58         "napi_send_event failed, result=%{public}d", ret);
59 }
60 
61 } // namespace MiscServicesNapi
62 } // namespace OHOS