diff --git a/.gitattributes b/.gitattributes index 38f7e4a05f8bbf9b10de0237cc0274faff4f94c2..a24ab2a4efe1b867f9034e867f50efd35e9b02ab 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,2 @@ -ohos_nweb/prebuilts/arm/NWeb.hap filter=lfs diff=lfs merge=lfs -text -ohos_nweb/prebuilts/arm64/NWeb.hap filter=lfs diff=lfs merge=lfs -text +ohos_nweb/prebuilts/arm/ArkWebCore.hap filter=lfs diff=lfs merge=lfs -text +ohos_nweb/prebuilts/arm64/ArkWebCore.hap filter=lfs diff=lfs merge=lfs -text diff --git a/OAT.xml b/OAT.xml index 4aa4f7addfb3f9df242edad160a3b0c4a0d033c1..71e70d97cdaaa5ccd0d99e2abf5110975db4e3d9 100644 --- a/OAT.xml +++ b/OAT.xml @@ -64,6 +64,7 @@ Note:If the text contains special characters, please escape them according to th + diff --git a/README.md b/README.md index e98529330f03c4dc5e460522c4ea64d1cc840711..c892749a26224ce02236dc8f36872c99a07060ee 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Below is the software architecture. . ├── ohos_nweb # OpenHarmony adaptation code │ ├── include -│ ├── prebuilts # NWeb.hap, built based on the third_party_chromium source code repository +│ ├── prebuilts # ArkWebCore.hap, built based on the third_party_chromium source code repository │ └── src └── test # nwebview test code ``` diff --git a/README_ZH.md b/README_ZH.md index 1361813fd6f97bb3bce97e7ed6d9b4e3d8ef4b7e..9b72a303ef7a8ee3cc560750b2787ee9cf1aeabc 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -4,7 +4,7 @@ - [相关仓](#相关仓) ## 简介 ### 内容介绍 -nweb是OpenHarmony webview组件的Native引擎,基于Chromium和CEF构建。 +arkweb是OpenHarmony webview组件的Native引擎,基于Chromium和CEF构建。 ### 软件架构 软件架构说明 ![](figures/Web-architecture_ZH.png "web软件架构图") @@ -17,7 +17,7 @@ nweb是OpenHarmony webview组件的Native引擎,基于Chromium和CEF构建。 . ├── ohos_nweb # openharmony适配代码 │   ├── include -│   ├── prebuilts # NWeb.hap,基于third_party_chromium源码仓构建 +│   ├── prebuilts # ArkWebCore.hap,基于third_party_chromium源码仓构建 │   └── src └── test # nwebview测试代码 ``` diff --git a/bundle.json b/bundle.json index 068d0402b2a09b04371314a2a7b7362189057e92..8396495d0c06a28a8004b6f862b7a81a8f32f67f 100644 --- a/bundle.json +++ b/bundle.json @@ -31,6 +31,7 @@ "access_token", "ace_engine", "app_file_service", + "appspawn", "audio_framework", "av_codec", "av_session", @@ -70,28 +71,29 @@ "print_fwk", "relational_store", "resource_schedule_service", + "safwk", "samgr", + "sensor", "soc_perf", "time_service", "window_manager", "netstack", "protobuf", - "libxml2" - + "libxml2", + "openssl" ], "third_party": [ "chromium", - "cef" + "cef" ] }, "build": { "sub_component": [ - "//base/web/webview/interfaces/inner_api:web_inner_kit", "//base/web/webview/interfaces/kits/cj:cj_webview_ffi", "//base/web/webview/interfaces/kits/napi:webview_napi", "//base/web/webview/interfaces/kits/napi:neterrorlist_napi", "//base/web/webview/interfaces/native:webview_ndk", - "//base/web/webview/ohos_nweb:chrome_crashpad_handler", + "//base/web/webview/ohos_nweb:chrome_crashpad_handler", "//base/web/webview/ohos_nweb:libnweb", "//base/web/webview/ohos_nweb:nweb_hap", "//base/web/webview/ohos_adapter:nweb_ohos_adapter", @@ -120,15 +122,6 @@ }, "name": "//base/web/webview/ohos_nweb:libnweb" }, - { - "header": { - "header_files": [ - "web_clipboard_controller.h" - ], - "header_base": "//base/web/webview/interfaces/inner_api/include" - }, - "name": "//base/web/webview/interfaces/inner_api:web_inner_kit" - }, { "header": { "header_files": [ @@ -162,13 +155,28 @@ "//base/web/webview/test/fuzztest/ontouchrelease_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/registerarkjsfunction_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/zoom_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/putbackgroundcolor_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/unregisterarkjsfunction_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/sendkeyevent_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/accesstoken_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/audio_adapter:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/resschedadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/backgroundtask_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/datashareadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/datetimeformat_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/eventhandler_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/printmanager_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer:fuzztest", @@ -210,6 +218,12 @@ "//base/web/webview/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/power_mgr_adapter:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer:fuzztest", @@ -234,7 +248,17 @@ "//base/web/webview/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/cert_mgr_adapter/getcertmaxsize_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/cert_mgr_adapter/getusercertdata_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_adapter/ashmemcreate_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_adapter/systemproperties_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_nweb/loadlib_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_nweb/getnweb_fuzzer:fuzztest", @@ -245,6 +269,10 @@ "//base/web/webview/test/fuzztest/ohos_nweb/flushbuffer_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_nweb/sethttpdns_fuzzer:fuzztest", "//base/web/webview/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_nweb/napi_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_nweb/initandrun_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_nweb/nwebhelper_fuzzer:fuzztest", + "//base/web/webview/test/fuzztest/ohos_nweb/hisysevent_fuzzer:fuzztest", "//base/web/webview/test/unittest/nweb_value_test:unittest", "//base/web/webview/test/unittest/display_manager_adapter_impl_test:unittest", "//base/web/webview/test/unittest/net_connect_adapter_test:unittest", @@ -261,6 +289,7 @@ "//base/web/webview/test/unittest/ohos_adapter/res_sched_adapter_impl_test:unittest", "//base/web/webview/test/unittest/ohos_adapter/web_data_base_adapter_impl_test:unittest", "//base/web/webview/test/unittest/ohos_adapter/ohos_resource_adapter_test:unittest", + "//base/web/webview/test/unittest/ohos_adapter/ohos_image_adapter:unittest", "//base/web/webview/test/unittest/ohos_adapter/graphic_adapter_test:unittest", "//base/web/webview/test/unittest/ohos_adapter/datashare_adapter_impl_test:unittest", "//base/web/webview/test/unittest/ohos_adapter/ohos_init_web_adapter:unittest", @@ -286,7 +315,7 @@ "//base/web/webview/test/unittest/ohos_adapter/imf_adapter_test:unittest", "//base/web/webview/test/unittest/ohos_adapter/media_adapter_test:unittest", "//base/web/webview/test/unittest/ohos_adapter/flowbuffer_adapter_impl_test:unittest", - "//base/web/webview/test/unittest/inner_api_test/clipboard_controller_test:unittest" + "//base/web/webview/test/unittest/ohos_adapter/sensor_adapter_impl_test:unittest" ] } } diff --git a/config.gni b/config.gni index cd08c73099ef4895e139c54cafea6c0faac24c82..efdafbae1a9d238be91ce75277736d7280b9ab3d 100644 --- a/config.gni +++ b/config.gni @@ -24,6 +24,8 @@ declare_args() { webview_print_enable = true webview_enterprise_device_manager_enable = true webview_media_avsession_enable = true + webview_sensors_sensor_enable = true + webview_graphic_2d_ext_enable = true if (defined(global_parts_info) && !defined(global_parts_info.resourceschedule_soc_perf)) { @@ -75,4 +77,24 @@ declare_args() { !defined(global_parts_info.multimedia_av_session)) { webview_media_avsession_enable = false } + if (defined(global_parts_info) && + !defined(global_parts_info.sensors_sensor)) { + webview_sensors_sensor_enable = false + } + if (defined(global_parts_info) && + !defined(global_parts_info.graphic_graphic_2d_ext)) { + webview_graphic_2d_ext_enable = false + } } + +webview_package_name = "com.ohos.arkwebcore" +webview_hap_path = + "/module_update/ArkWebCore/app/${webview_package_name}/ArkWebCore.hap" +webview_sandbox_path = "/data/storage/el1/bundle/arkwebcore/" +webview_sandbox_hap_path = "${webview_sandbox_path}entry.hap" +webview_sandbox_lib_path = "${webview_sandbox_path}libs/${target_cpu}" +webview_sandbox_relative_lib_path = "arkwebcore/libs/${target_cpu}" +webview_crashpad_handler_so = "libarkweb_crashpad_handler.so" +webview_engine_so = "libarkweb_engine.so" +webview_app_hap_path = "/system/app/ArkWeb/ArkWebCore.hap" +webview_app_hap_path2 = "/system/app/${webview_package_name}/ArkWebCore.hap" diff --git a/interfaces/inner_api/src/web_clipboard_controller.cpp b/interfaces/inner_api/src/web_clipboard_controller.cpp deleted file mode 100644 index 754fc1f9304a39cf567a60a52150353263f3d79d..0000000000000000000000000000000000000000 --- a/interfaces/inner_api/src/web_clipboard_controller.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (C) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "web_clipboard_controller.h" - -#include - -#include "nweb_log.h" - -namespace { -const std::string IMG_TAG_PATTERN = ""; -const std::string IMG_TAG_SRC_PATTERN = "src=(['\"])(.*?)\\1"; -const std::string IMG_TAG_SRC_HEAD = "src=\""; -const std::string IMG_LOCAL_URI = "file:///"; -const std::string IMG_LOCAL_PATH = "://"; -constexpr uint32_t FOUR_BYTES = 4; -constexpr uint32_t EIGHT_BIT = 8; - -struct Cmp { - bool operator()(const uint32_t& lhs, const uint32_t& rhs) const - { - return lhs > rhs; - } -}; -} // namespace - -namespace OHOS { -namespace NWeb { - -// static -WebClipboardController& WebClipboardController::GetInstance() -{ - static WebClipboardController instance; - return instance; -} - -std::shared_ptr WebClipboardController::SplitHtml(std::shared_ptr html) noexcept -{ - std::vector> matchVec = SplitHtmlWithImgLabel(html); - std::map> imgSrcMap = SplitHtmlWithImgSrcLabel(matchVec); - std::shared_ptr pasteData = BuildPasteData(html, imgSrcMap); - return pasteData; -} - -std::shared_ptr WebClipboardController::RebuildHtml( - std::shared_ptr pasteData) noexcept -{ - std::vector> pasteDataRecords = pasteData->AllRecords(); - std::shared_ptr htmlData; - std::map, Cmp> replaceUris; - - for (auto& item : pasteDataRecords) { - std::shared_ptr html = item->GetHtmlText(); - if (html) { - htmlData = html; - } - std::shared_ptr uri = item->GetUri(); - std::shared_ptr customData = item->GetCustomData(); - if (!uri || !customData) { - continue; - } - std::map> customItemData = customData->GetItemData(); - for (auto& itemData : customItemData) { - for (uint32_t i = 0; i < itemData.second.size(); i += FOUR_BYTES) { - uint32_t offset = static_cast(itemData.second[i]) | - static_cast(itemData.second[i + 1] << 8) | - static_cast(itemData.second[i + 2] << 16) | - static_cast(itemData.second[i + 3] << 24); - replaceUris[offset] = std::make_pair(uri->ToString(), itemData.first); - } - } - } - - RemoveAllRecord(pasteData); - for (auto& replaceUri : replaceUris) { - htmlData->replace(replaceUri.first, replaceUri.second.second.size(), replaceUri.second.first); - } - pasteData->AddHtmlRecord(*htmlData); - return htmlData; -} - -std::vector> WebClipboardController::SplitHtmlWithImgLabel( - const std::shared_ptr html) noexcept -{ - std::smatch results; - std::string pattern(IMG_TAG_PATTERN); - std::regex r(pattern); - std::string::const_iterator iterStart = html->begin(); - std::string::const_iterator iterEnd = html->end(); - std::vector> matchVec; - - while (std::regex_search(iterStart, iterEnd, results, r)) { - std::string tmp = results[0]; - iterStart = results[0].second; - uint32_t offset = static_cast(results[0].first - html->begin()); - - matchVec.emplace_back(std::make_pair(tmp, offset)); - } - - return matchVec; -} - -std::map> WebClipboardController::SplitHtmlWithImgSrcLabel( - const std::vector>& matchVec) noexcept -{ - std::map> res; - std::smatch match; - std::regex re(IMG_TAG_SRC_PATTERN); - for (auto& node : matchVec) { - std::string::const_iterator iterStart = node.first.begin(); - std::string::const_iterator iterEnd = node.first.end(); - - while (std::regex_search(iterStart, iterEnd, match, re)) { - std::string tmp = match[0]; - iterStart = match[0].second; - uint32_t offset = static_cast(match[0].first - node.first.begin()); - tmp = tmp.substr(IMG_TAG_SRC_HEAD.size()); - tmp.pop_back(); - if (!IsLocalURI(tmp)) { - continue; - } - offset += IMG_TAG_SRC_HEAD.size() + node.second; - for (uint32_t i = 0; i < FOUR_BYTES; i++) { - res[tmp].emplace_back((offset >> (EIGHT_BIT * i)) & 0xff); - } - } - } - return res; -} - -std::shared_ptr WebClipboardController::BuildPasteData( - std::shared_ptr html, const std::map>& imgSrcMap) noexcept -{ - std::shared_ptr pasteData = std::make_shared(); - pasteData->AddHtmlRecord(*html); - for (auto& item : imgSrcMap) { - MiscServices::PasteDataRecord::Builder builder(MiscServices::MIMETYPE_TEXT_URI); - auto uri = std::make_shared(item.first); - builder.SetUri(uri); - auto customData = std::make_shared(); - - customData->AddItemData(item.first, item.second); - builder.SetCustomData(customData); - auto record = builder.Build(); - pasteData->AddRecord(record); - } - return pasteData; -} - -void WebClipboardController::RemoveAllRecord(std::shared_ptr pasteData) noexcept -{ - std::size_t recordCount = pasteData->GetRecordCount(); - for (uint32_t i = 0; i < recordCount; i++) { - if (!pasteData->RemoveRecordAt(0)) { - WVLOG_E("WebClipboardController RemoveRecord filed, i=%{public}u", i); - } - } -} - -bool WebClipboardController::IsLocalURI(std::string& uri) noexcept -{ - return uri.substr(0, IMG_LOCAL_URI.size()) == IMG_LOCAL_URI || uri.find(IMG_LOCAL_PATH) == std::string::npos; -} -} // namespace NWeb -} // namespace OHOS diff --git a/interfaces/kits/cj/BUILD.gn b/interfaces/kits/cj/BUILD.gn index 3603933fbc87c3859fe961c564af806ead333112..22acdd416eaaff74d3ca9be709aa3a3279cb7753 100644 --- a/interfaces/kits/cj/BUILD.gn +++ b/interfaces/kits/cj/BUILD.gn @@ -17,6 +17,7 @@ config("cj_web_public_config") { visibility = [ ":*" ] include_dirs = [ "include", + "$target_gen_dir/../napi/protos", "../../native", ] } @@ -33,7 +34,15 @@ ohos_shared_library("cj_webview_ffi") { if (product_name != "ohos-sdk") { sources = [ + "$target_gen_dir/../napi/protos/web_download.pb.cc", + "$target_gen_dir/../napi/protos/web_download.pb.h", + "src/geolocation_permission.cpp", + "src/native_media_player_impl.cpp", "src/web_cookie_manager.cpp", + "src/web_data_base.cpp", + "src/web_download_delegate_impl.cpp", + "src/web_download_item_impl.cpp", + "src/web_download_manager_impl.cpp", "src/webview_controller_impl.cpp", "src/webview_ffi.cpp", "src/webview_javascript_execute_callback.cpp", @@ -45,6 +54,7 @@ ohos_shared_library("cj_webview_ffi") { "../../../ohos_adapter:nweb_ohos_adapter", "../../../ohos_nweb:libnweb", "../../native:ohweb", + "../napi/protos:proto_gen", ] external_deps = [ @@ -60,6 +70,7 @@ ohos_shared_library("cj_webview_ffi") { "napi:ace_napi", "napi:cj_bind_ffi", "napi:cj_bind_native", + "protobuf:protobuf_lite", ] } else { defines += [ "PREVIEWER" ] diff --git a/interfaces/inner_api/include/web_clipboard_controller.h b/interfaces/kits/cj/include/geolocation_permission.h similarity index 33% rename from interfaces/inner_api/include/web_clipboard_controller.h rename to interfaces/kits/cj/include/geolocation_permission.h index 11059948d32b8012e19bb1057fcd4039ce313aa1..27f9d21b1a6aabf1707b5eb13e7e66afb273dfaa 100644 --- a/interfaces/inner_api/include/web_clipboard_controller.h +++ b/interfaces/kits/cj/include/geolocation_permission.h @@ -1,56 +1,52 @@ -/* - * Copyright (C) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WEB_CLIPBORD_CONTROLLER_H -#define WEB_CLIPBORD_CONTROLLER_H - -#include -#include -#include -#include -#include - -#include "paste_data.h" -#include "paste_data_record.h" -#include "pasteboard_client.h" -#include "refbase.h" - -namespace OHOS { -namespace NWeb { - -class WebClipboardController : public RefBase { -public: - WebClipboardController() {}; - ~WebClipboardController() {}; - - static WebClipboardController& GetInstance(); - - std::shared_ptr SplitHtml(std::shared_ptr html) noexcept; - std::shared_ptr RebuildHtml(std::shared_ptr pasteData) noexcept; - -private: - std::vector> SplitHtmlWithImgLabel( - const std::shared_ptr html) noexcept; - std::map> SplitHtmlWithImgSrcLabel( - const std::vector>& matchVec) noexcept; - std::shared_ptr BuildPasteData( - std::shared_ptr html, const std::map>& imgSrcMap) noexcept; - void RemoveAllRecord(std::shared_ptr pasteData) noexcept; - bool IsLocalURI(std::string& uri) noexcept; -}; -} // namespace NWeb -} // namespace OHOS - -#endif // WEB_CLIPBORD_CONTROLLER_H +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GEOLOCATION_PERMISSION_H +#define GEOLOCATION_PERMISSION_H + +#include +#include +#include + +namespace OHOS { +namespace NWeb { +class GeolocationPermission { +public: + GeolocationPermission() {} + + ~GeolocationPermission() = default; + + static void CjAllowGeolocation(std::string origin, bool incognitoMode, int32_t *errCode); + + static void CjDeleteGeolocation(std::string origin, bool incognitoMode, int32_t *errCode); + + static bool CjGetAccessibleGeolocation(std::string origin, bool incognitoMode, int32_t *errCode); + + static std::vector CjGetStoredGeolocation(bool incognitoMode, int32_t *errCode); + + static void CjDeleteAllGeolocation(bool incognitoMode, int32_t *errCode); + +private: + static void ProcessActionByType(std::string origin, bool incognitoMode, + int32_t operationType, int32_t *errCode); + + static bool ExecuteGetPermissionState(std::string origin, bool incognitoMode, int32_t *errCode); + + static std::vector ExecuteGetOrigins(bool incognitoMode, int32_t *errCode); +}; +} // namespace NWeb +} // namespace OHOS + +#endif // GEOLOCATION_PERMISSION_H diff --git a/interfaces/kits/cj/include/native_media_player_impl.h b/interfaces/kits/cj/include/native_media_player_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..88fee1d8df0d5eb77f7a4365a1a9af1401dad40d --- /dev/null +++ b/interfaces/kits/cj/include/native_media_player_impl.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_MEDIA_PLAYER_IMPL_FFI_H +#define NATIVE_MEDIA_PLAYER_IMPL_FFI_H + +#include +#include +#include "ffi_remote_data.h" +#include "web_errors.h" +#include "webview_javascript_result_callback.h" +#include "nweb.h" +#include "nweb_helper.h" +#include "nweb_native_media_player.h" + +namespace OHOS::Webview { + class NativeMediaPlayerHandlerImpl : public OHOS::FFI::FFIData { + DECL_TYPE(NativeMediaPlayerHandlerImpl, OHOS::FFI::FFIData) + public: + NativeMediaPlayerHandlerImpl()=default; + NativeMediaPlayerHandlerImpl(int32_t nwebId, std::shared_ptr handler); + ~NativeMediaPlayerHandlerImpl() = default; + void HandleStatusChanged(NWeb::PlaybackStatus status); + void HandleVideoSizeChanged(double width,double height); + void HandleError(NWeb::MediaError error,const char* errorMessage); + void HandleSeekFinished(); + void HandleSeeking(); + void HandleFullScreenChanged(bool fullscreen); + void HandleReadyStateChanged(NWeb::ReadyState state); + void HandleNetworkStateChanged(NWeb::NetworkState state); + void HandleEnded(); + void HandleBufferedEndTimeChanged(double bufferedEndTime); + void HandleTimeUpdate(double playTime); + void HandleDurationChanged(double duration); + void HandlePlaybackRateChanged(double playbackRate); + void HandleMutedChanged(bool muted); + void HandleVolumeChanged(double volume); + int32_t nwebId_ = -1; + std::shared_ptr handler_ = nullptr; + }; + + class NWebNativeMediaPlayerBridgeImpl : public NWeb::NWebNativeMediaPlayerBridge, public OHOS::FFI::FFIData { + DECL_TYPE(NWebNativeMediaPlayerBridgeImpl, OHOS::FFI::FFIData) + public: + NWebNativeMediaPlayerBridgeImpl(sptr nativeMediaPlayerImpl); + ~NWebNativeMediaPlayerBridgeImpl() = default; + + void UpdateRect(double x, double y, double width, double height) override; + + void Play() override; + + void Pause() override; + + void Seek(double time) override; + + void SetVolume(double volume) override; + + void SetMuted(bool isMuted) override; + + void SetPlaybackRate(double playbackRate) override; + + void Release() override; + + void EnterFullScreen() override; + + void ExitFullScreen() override; + + void ResumeMediaPlayer() override; + + void SuspendMediaPlayer(NWeb::SuspendType type) override; + + private: + sptr nativeMediaPlayerImpl_; + // the instance of a class that implements interface, + // would be created and pass to construct an instance of this class in callback handle process + }; + + class NWebCreateNativeMediaPlayerCallbackImpl : public NWeb::NWebCreateNativeMediaPlayerCallback, public OHOS::FFI::FFIData { + DECL_TYPE(NWebCreateNativeMediaPlayerCallbackImpl, OHOS::FFI::FFIData) + public: + explicit NWebCreateNativeMediaPlayerCallbackImpl(int32_t nwebId, std::function callback); + ~NWebCreateNativeMediaPlayerCallbackImpl() = default; + + std::shared_ptr OnCreate( + std::shared_ptr handler, std::shared_ptr mediaInfo) override; + + private: + int32_t nwebId_ = -1; + std::function callback_ = nullptr; + }; +} +#endif // NATIVE_MEDIA_PLAYER_IMPL_FFI_H \ No newline at end of file diff --git a/interfaces/kits/cj/include/web_data_base.h b/interfaces/kits/cj/include/web_data_base.h new file mode 100644 index 0000000000000000000000000000000000000000..90f14bcf65671ac6efa9f52c584662e75a2ce03e --- /dev/null +++ b/interfaces/kits/cj/include/web_data_base.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WEB_DATA_BASE_H +#define WEB_DATA_BASE_H + +#include +#include + +namespace OHOS { +namespace NWeb { + +const int MAX_STRING_LENGTH = 40960; +const int MAX_PWD_LENGTH = 256; +class WebDataBase { +public: + WebDataBase() {} + ~WebDataBase() = default; + + static CArrString CJGetHttpAuthCredentials(const std::string &host, const std::string &realm); + static void CJSaveHttpAuthCredentials(const std::string &host, const std::string &realm, + const std::string &username, const std::string &password); + static bool CJExistHttpAuthCredentials(); + static void CJDeleteHttpAuthCredentials(); +}; +} +} + +#endif \ No newline at end of file diff --git a/interfaces/kits/cj/include/web_download_delegate_impl.h b/interfaces/kits/cj/include/web_download_delegate_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..ae19d6dffca0f56e870f31429f7ba96da4c7facb --- /dev/null +++ b/interfaces/kits/cj/include/web_download_delegate_impl.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WEB_DOWNLOAD_DELEGATE_IMPL_H +#define WEB_DOWNLOAD_DELEGATE_IMPL_H + +#include "ffi_remote_data.h" +#include "web_download_item_impl.h" +#include "web_errors.h" + +namespace OHOS::Webview { + class __attribute__((visibility("default"))) WebDownloadDelegateImpl : public OHOS::FFI::FFIData { + DECL_TYPE(WebDownloadDelegateImpl, OHOS::FFI::FFIData) + public: + explicit WebDownloadDelegateImpl(); + ~WebDownloadDelegateImpl(); + + void DownloadBeforeStart(WebDownloadItemImpl *webDownloadItemImpl); + void DownloadDidUpdate(WebDownloadItemImpl *webDownloadItemImpl); + void DownloadDidFail(WebDownloadItemImpl *webDownloadItemImpl); + void DownloadDidFinish(WebDownloadItemImpl *webDownloadItemImpl); + + void PutDownloadBeforeStart(std::function callback); + void PutDownloadDidUpdate(std::function callback); + void PutDownloadDidFinish(std::function callback); + void PutDownloadDidFail(std::function callback); + + int32_t GetNWebId(); + void SetNWebId(int32_t nwebId); + + private: + int32_t nwebId_ = -1; + + std::function download_before_start_callback_; + std::function download_did_update_callback_; + std::function download_did_finish_callback_; + std::function download_did_fail_callback_; + }; +} +#endif // WEB_DOWNLOAD_DELEGATE_IMPL_H \ No newline at end of file diff --git a/interfaces/kits/cj/include/web_download_item_impl.h b/interfaces/kits/cj/include/web_download_item_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..bdd21a123ddf164babdfae80f2ab8042c7d88f82 --- /dev/null +++ b/interfaces/kits/cj/include/web_download_item_impl.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WEB_DOWNLOAD_ITEM_IMPL_H +#define WEB_DOWNLOAD_ITEM_IMPL_H + +#include + +#include "ffi_remote_data.h" +#include "nweb_c_api.h" + +namespace OHOS::Webview { + class __attribute__((visibility("default"))) WebDownloadItemImpl : public OHOS::FFI::FFIData { + DECL_TYPE(WebDownloadItemImpl, OHOS::FFI::FFIData) + public: + explicit WebDownloadItemImpl(); + WebDownloadItemImpl(NWebDownloadItem *downloadItem); + ~WebDownloadItemImpl(); + + long webDownloadId; + int currentSpeed; + int percentComplete; + int64_t totalBytes; + int64_t receivedBytes; + int lastErrorCode; + + std::string guid; + std::string fullPath; + std::string url; + std::string etag; + std::string originalUrl; + std::string suggestedFileName; + std::string contentDisposition; + std::string mimeType; + std::string lastModified; + + NWebDownloadItemState state = NWebDownloadItemState::MAX_DOWNLOAD_STATE; + std::string method; + std::string receivedSlices; + + std::string downloadPath; + WebBeforeDownloadCallbackWrapper *before_download_callback; + WebDownloadItemCallbackWrapper *download_item_callback; + + int32_t nwebId; + }; +} // namespace OHOS::Webview + +#endif // WEB_DOWNLOAD_ITEM_IMPL_H diff --git a/interfaces/kits/cj/include/web_download_manager_impl.h b/interfaces/kits/cj/include/web_download_manager_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..5fdc132784bd94d097786b28ce345d40e7bf9de7 --- /dev/null +++ b/interfaces/kits/cj/include/web_download_manager_impl.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NWEB_WEB_DOWNLOAD_MANAGER_IMPL_H +#define NWEB_WEB_DOWNLOAD_MANAGER_IMPL_H + +#include + +#include "web_download_delegate_impl.h" +#include "web_download_item_impl.h" + +namespace OHOS::Webview { + class WebDownloadDelegateImpl; + + class WebDownloadManagerImpl { + public: + static void SetDownloadDelegate(WebDownloadDelegateImpl *delegate); + static void ResumeDownload(const WebDownloadItemImpl *webDownload); + + static void AddDownloadDelegateForWeb(int32_t nwebId, WebDownloadDelegateImpl *delegate); + static void RemoveDownloadDelegate(WebDownloadDelegateImpl *delegate); + + static bool HasValidDelegate(); + + WebDownloadManagerImpl() = default; + ~WebDownloadManagerImpl() = default; + + private: + static void RegisterDownloadCallback(); + }; +} // namespace OHOS::Webview + +#endif // NWEB_WEB_DOWNLOAD_MANAGER_IMPL_H \ No newline at end of file diff --git a/interfaces/kits/cj/include/web_errors.h b/interfaces/kits/cj/include/web_errors.h index a71d3776e9d8953a1f4fc64bf8793f40cf6b5023..77b789254b51fadfc19146414b5145f49980aa81 100644 --- a/interfaces/kits/cj/include/web_errors.h +++ b/interfaces/kits/cj/include/web_errors.h @@ -47,6 +47,8 @@ constexpr ErrCode REGISTER_CUSTOM_SCHEME_FAILED = 17100020; constexpr ErrCode RESOURCE_HANDLER_INVALID = 17100021; constexpr ErrCode HTTP_BODY_STREAN_INIT_FAILED = 17100022; +constexpr ErrCode HTTP_AUTH_MALLOC_FAILED = 17100023; + std::string GetErrMsgByErrCode(ErrCode code); } } diff --git a/interfaces/kits/cj/include/webview_controller_impl.h b/interfaces/kits/cj/include/webview_controller_impl.h index ddcb4a51df7351b1d0735bc73e07a9154a0e508d..77ad44892a40013eadd835bb73051355e47444e8 100644 --- a/interfaces/kits/cj/include/webview_controller_impl.h +++ b/interfaces/kits/cj/include/webview_controller_impl.h @@ -23,6 +23,7 @@ #include "webview_javascript_result_callback.h" #include "nweb.h" #include "nweb_helper.h" +#include "nweb_web_message.h" namespace OHOS::Webview { enum class WebHitTestType : int { @@ -50,6 +51,16 @@ namespace OHOS::Webview { DANGEROUS = 5 }; + enum class WebMessageType : int { + NOTSUPPORT = 0, + STRING, + NUMBER, + BOOLEAN, + ARRAYBUFFER, + ARRAY, + ERROR + }; + class __attribute__((visibility("default"))) WebviewControllerImpl : public OHOS::FFI::FFIData { DECL_TYPE(WebviewControllerImpl, OHOS::FFI::FFIData) public: @@ -77,6 +88,29 @@ namespace OHOS::Webview { ErrCode LoadData(std::string data, std::string mimeType, std::string encoding, std::string baseUrl, std::string historyUrl); + int32_t PreFetchPage(std::string url); + + int32_t PreFetchPage(std::string url, std::map headers); + + int32_t SetAudioMuted(bool mute); + + void SlideScroll(float vx, float vy); + + void PutNetworkAvailable(bool enable); + + void ClearClientAuthenticationCache(); + + void ClearSslCache(); + + void SearchNext(bool forward); + + void ClearMatches(); + + void SearchAllAsync(std::string str); + + ErrCode DeleteJavaScriptRegister(const std::string& objName, + const std::vector& methodList); + void Refresh(); std::string GetUserAgent(); @@ -119,6 +153,8 @@ namespace OHOS::Webview { int32_t ZoomOut(); + int32_t RequestFocus(); + void ClearHistory(); bool AccessStep(int32_t step); @@ -153,6 +189,16 @@ namespace OHOS::Webview { void Stop(); + void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive); + + int32_t PostUrl(std::string& url, std::vector& postData); + + void OnCreateNativeMediaPlayer(std::function callback); + + std::vector CreateWebMessagePorts(); + + ErrCode PostWebMessage(std::string& message, std::vector& ports, std::string& targetUrl); + public: static std::string customeSchemeCmdLine_; static bool existNweb_; @@ -183,5 +229,232 @@ namespace OHOS::Webview { private: std::shared_ptr sptrHistoryList_ = nullptr; }; + + class WebMessagePortImpl : public OHOS::FFI::FFIData { + DECL_TYPE(WebMessagePortImpl, OHOS::FFI::FFIData) + public: + WebMessagePortImpl(int32_t nwebId, std::string port, bool isExtentionType); + + ~WebMessagePortImpl() = default; + + ErrCode ClosePort(); + + ErrCode PostPortMessage(std::shared_ptr data); + + ErrCode SetPortMessageCallback(std::shared_ptr callback); + + std::string GetPortHandle() const; + + bool IsExtentionType() + { + return isExtentionType_; + } + + private: + int32_t nwebId_ = -1; + std::string portHandle_; + bool isExtentionType_; + }; + + class WebMessageExtImpl : public OHOS::FFI::FFIData { + DECL_TYPE(WebMessageExtImpl, OHOS::FFI::FFIData) + public: + explicit WebMessageExtImpl(std::shared_ptr data) : data_(data) {}; + ~WebMessageExtImpl() = default; + + void SetType(int type) + { + type_ = type; + WebMessageType jsType = static_cast(type); + NWeb::NWebValue::Type nwebType = NWeb::NWebValue::Type::NONE; + switch (jsType) { + case WebMessageType::STRING: { + nwebType = NWeb::NWebValue::Type::STRING; + break; + } + case WebMessageType::NUMBER: { + nwebType = NWeb::NWebValue::Type::DOUBLE; + break; + } + case WebMessageType::BOOLEAN: { + nwebType = NWeb::NWebValue::Type::BOOLEAN; + break; + } + case WebMessageType::ARRAYBUFFER: { + nwebType = NWeb::NWebValue::Type::BINARY; + break; + } + case WebMessageType::ARRAY: { + nwebType = NWeb::NWebValue::Type::STRINGARRAY; + break; + } + case WebMessageType::ERROR: { + nwebType = NWeb::NWebValue::Type::ERROR; + break; + } + default: { + nwebType = NWeb::NWebValue::Type::NONE; + break; + } + } + if (data_) { + data_->SetType(nwebType); + } + } + + int ConvertNwebType2JsType(NWeb::NWebValue::Type type) + { + WebMessageType jsType = WebMessageType::NOTSUPPORT; + switch (type) { + case NWeb::NWebValue::Type::STRING: { + jsType = WebMessageType::STRING; + break; + } + case NWeb::NWebValue::Type::DOUBLE: + case NWeb::NWebValue::Type::INTEGER: { + jsType = WebMessageType::NUMBER; + break; + } + case NWeb::NWebValue::Type::BOOLEAN: { + jsType = WebMessageType::BOOLEAN; + break; + } + case NWeb::NWebValue::Type::STRINGARRAY: + case NWeb::NWebValue::Type::DOUBLEARRAY: + case NWeb::NWebValue::Type::INT64ARRAY: + case NWeb::NWebValue::Type::BOOLEANARRAY: { + jsType = WebMessageType::ARRAY; + break; + } + case NWeb::NWebValue::Type::BINARY: { + jsType = WebMessageType::ARRAYBUFFER; + break; + } + case NWeb::NWebValue::Type::ERROR: { + jsType = WebMessageType::ERROR; + break; + } + default: { + jsType = WebMessageType::NOTSUPPORT; + break; + } + } + return static_cast(jsType); + } + + int GetType() + { + if (data_) { + return ConvertNwebType2JsType(data_->GetType()); + } + return static_cast(WebMessageType::NOTSUPPORT); + } + + void SetString(std::string value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::STRING); + data_->SetString(value); + } + } + + void SetNumber(double value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::DOUBLE); + data_->SetDouble(value); + } + } + + void SetBoolean(bool value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::BOOLEAN); + data_->SetBoolean(value); + } + } + + void SetArrayBuffer(std::vector& value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::BINARY); + data_->SetBinary(value); + } + } + + void SetStringArray(std::vector value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::STRINGARRAY); + data_->SetStringArray(value); + } + } + + void SetDoubleArray(std::vector value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::DOUBLEARRAY); + data_->SetDoubleArray(value); + } + } + + void SetInt64Array(std::vector value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::INT64ARRAY); + data_->SetInt64Array(value); + } + } + + void SetBooleanArray(std::vector value) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::BOOLEANARRAY); + data_->SetBooleanArray(value); + } + } + + void SetError(std::string name, std::string message) + { + if (data_) { + data_->SetType(NWeb::NWebValue::Type::ERROR); + data_->SetErrName(name); + data_->SetErrMsg(message); + } + } + + std::shared_ptr GetData() + { + return data_; + } + + private: + int type_ = 0; + std::shared_ptr data_; + }; + + class NWebMessageCallbackImpl : public NWeb::NWebMessageValueCallback { + public: + NWebMessageCallbackImpl(std::function callback) + : callback_(callback) + {} + ~NWebMessageCallbackImpl() = default; + void OnReceiveValue(std::shared_ptr result) override; + + private: + std::function callback_; + }; + + class NWebWebMessageExtCallbackImpl : public NWeb::NWebMessageValueCallback { + public: + NWebWebMessageExtCallbackImpl(std::function callback) + : callback_(callback) + {} + ~NWebWebMessageExtCallbackImpl() = default; + void OnReceiveValue(std::shared_ptr result) override; + + private: + std::function callback_; + }; } #endif // WEBVIEW_CONTROLLER_IMPL_FFI_H \ No newline at end of file diff --git a/interfaces/kits/cj/include/webview_ffi.h b/interfaces/kits/cj/include/webview_ffi.h index af456fc2ca2331176ba9f5709797e7c9e75273f4..40029ce76652356e8ae32cb647bb92d88ad754cd 100644 --- a/interfaces/kits/cj/include/webview_ffi.h +++ b/interfaces/kits/cj/include/webview_ffi.h @@ -31,7 +31,13 @@ extern "C" { FFI_EXPORT int32_t FfiOHOSWebviewCtlLoadUrlWithHeaders(int64_t id, char *url, OHOS::Webview::ArrWebHeader headers); FFI_EXPORT int32_t FfiOHOSWebviewCtlLoadData(int64_t id, OHOS::Webview::LoadDatas loadDatas); FFI_EXPORT int32_t FfiOHOSWebviewCtlRefresh(int64_t id); + FFI_EXPORT int32_t FFiOHOSWebviewCtlPreFetchPage(int64_t id, char* url); + FFI_EXPORT int32_t FFiOHOSWebviewCtlPreFetchPageWithHeaders(int64_t id, char* url, + OHOS::Webview::ArrWebHeader headers); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSetAudioMuted(int64_t id, bool mute); FFI_EXPORT char *FfiOHOSWebviewCtlGetUserAgent(int64_t id, int32_t *errCode); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSetConnectionTimeout(int32_t timeout); + FFI_EXPORT int32_t FfiOHOSWebviewCtlGetWebId(int64_t id, int32_t *errCode); FFI_EXPORT bool FfiOHOSWebviewCtlAccessForward(int64_t id, int32_t *errCode); FFI_EXPORT bool FfiOHOSWebviewCtlAccessBackward(int64_t id, int32_t *errCode); FFI_EXPORT int32_t FfiOHOSWebviewCtlSetCustomUserAgent(int64_t id, char *cUserAgent); @@ -54,6 +60,7 @@ extern "C" { FFI_EXPORT int32_t FfiOHOSWebviewCtlZoom(int64_t id, float factor); FFI_EXPORT int32_t FfiOHOSWebviewCtlZoomIn(int64_t id); FFI_EXPORT int32_t FfiOHOSWebviewCtlZoomOut(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebviewCtlRequestFocus(int64_t id); FFI_EXPORT int32_t FfiOHOSWebviewCtlClearHistory(int64_t id); FFI_EXPORT bool FfiOHOSWebviewCtlAccessStep(int64_t id, int32_t *errCode, int32_t step); FFI_EXPORT int32_t FfiOHOSWebviewCtlOnActive(int64_t id); @@ -69,6 +76,24 @@ extern "C" { FFI_EXPORT int32_t FfiOHOSWebviewCtlRemoveCache(int64_t id, bool clearRom); FFI_EXPORT int64_t FfiOHOSWebviewCtlGetBackForwardEntries(int64_t id, int32_t *errCode); FFI_EXPORT int32_t FfiOHOSWebviewCtlStop(int64_t id); + FFI_EXPORT int64_t FfiOHOSWebviewCtlGetFavicon(int64_t id, int32_t *errCode); + FFI_EXPORT int32_t FfiOHOSWebviewCtlPrepareForPageLoad(char *url, bool preconnectable, int32_t numSockets); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSlideScroll(int64_t id, float vx, float vy); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSetNetworkAvailable(int64_t id, bool enable); + FFI_EXPORT int32_t FfiOHOSWebviewCtlClearClientAuthenticationCache(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebviewCtlClearSslChache(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSearchNext(int64_t id, bool forward); + FFI_EXPORT int32_t FfiOHOSWebviewCtlClearMatches(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSearchAllAsync(int64_t id, char *searchString); + FFI_EXPORT int32_t FfiOHOSWebviewCtlDeleteJavaScriptRegister(int64_t id, char *name); + FFI_EXPORT int32_t FfiOHOSWebviewCtlEnableWholeWebPageDrawing(); + FFI_EXPORT int32_t FfiOHOSWebviewCtlClearPrefetchedResource(CArrString cacheKeyList); + FFI_EXPORT int32_t FfiOHOSWebviewCtlPostUrl(int64_t id, char *url, CArrUI8 buffer); + FFI_EXPORT int32_t FfiOHOSWebviewCtlSetDownloadDelegate(int64_t id, int64_t delegateId); + FFI_EXPORT int32_t FfiOHOSWebviewCtlStartDownload(int64_t id, char *url); + FFI_EXPORT CArrI64 FfiOHOSWebviewCtlCreateWebMessagePorts(int64_t id, bool isExtentionType, int32_t *errCode); + FFI_EXPORT int32_t FfiOHOSWebviewCtlPostMessage(int64_t id, char* name, CArrI64 ports, char* uri); + FFI_EXPORT void FfiOHOSWebviewCtlOnCreateNativeMediaPlayer(int64_t id, int64_t (*callback)(int64_t, OHOS::Webview::CMediaInfo)); // BackForwardList FFI_EXPORT int32_t FfiOHOSBackForwardListCurrentIndex(int64_t id, int32_t *errCode); @@ -85,6 +110,111 @@ extern "C" { FFI_EXPORT bool FfiOHOSCookieMgrExistCookie(bool incognitoMode); FFI_EXPORT void FfiOHOSCookieMgrClearAllCookiesSync(bool incognitoMode); FFI_EXPORT void FfiOHOSCookieMgrClearSessionCookieSync(); + + // NativeMediaPlayerHandler + FFI_EXPORT int64_t FfiOHOSNmphConstuctor(); + FFI_EXPORT int32_t FfiOHOSNmphhandleVideoSizeChanged(int64_t id,double width,double height); + FFI_EXPORT int32_t FfiOHOSNmphhandleError(int64_t id,int32_t error,const char* errorMessage); + FFI_EXPORT int32_t FfiOHOSNmphhandleSeekFinished(int64_t id); + FFI_EXPORT int32_t FfiOHOSNmphhandleSeeking(int64_t id); + FFI_EXPORT int32_t FfiOHOSNmphhandleFullscreenChanged(int64_t id,bool fullscreen); + FFI_EXPORT int32_t FfiOHOSNmphhandleReadyStateChanged(int64_t id,int32_t state); + FFI_EXPORT int32_t FfiOHOSNmphhandleNetworkStateChanged(int64_t id,int32_t state); + FFI_EXPORT int32_t FfiOHOSNmphhandleEnded(int64_t id); + FFI_EXPORT int32_t FfiOHOSNmphhandleBufferedEndTimeChanged(int64_t id,double bufferedEndTime); + FFI_EXPORT int32_t FfiOHOSNmphhandleTimeUpdate(int64_t id,double currentPlayTime); + FFI_EXPORT int32_t FfiOHOSNmphhandleDurationChanged(int64_t id,double duration); + FFI_EXPORT int32_t FfiOHOSNmphhandlePlaybackRateChanged(int64_t id,double playbackRate); + FFI_EXPORT int32_t FfiOHOSNmphhandleMutedChanged(int64_t id,bool muted); + FFI_EXPORT int32_t FfiOHOSNmphhandleVolumeChanged(int64_t id,double volume); + FFI_EXPORT int32_t FfiOHOSNmphhandleStatusChanged(int64_t id, int32_t status); + + // NativeMediaPlayerBridge + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeExitFullscreen(int64_t id); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeEnterFullscreen(int64_t id); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeRelease(int64_t id); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeSetPlaybackRate(int64_t id, double playbackRate); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeSetMuted(int64_t id, bool muted); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeSetVolume(int64_t id, double volume); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgeSeek(int64_t id, double targetTime); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgePause(int64_t id); + FFI_EXPORT int32_t FfiOHOSNativeMediaPlayerBridgePlay(int64_t id); + FFI_EXPORT int32_t + FfiOHOSNativeMediaPlayerBridgeUpdateRect(int64_t id, double x, double y, double width, double height); + + // data_base + FFI_EXPORT RetDataCArrString FfiOHOSDBGetHttpAuthCredentials(const char *host, + const char *realm); + FFI_EXPORT void FfiOHOSDBSaveHttpAuthCredentials(const char *host, const char *realm, + const char *username, const char *password); + FFI_EXPORT bool FfiOHOSDBExistHttpAuthCredentials(); + FFI_EXPORT void FfiOHOSDBDeleteHttpAuthCredentials(); + + // WebDownloadItemImpl + FFI_EXPORT int64_t FfiOHOSWebDownloadItemImplConstructor(); + FFI_EXPORT RetDataCString FfiOHOSWebDownloadItemImplGetGuid(int64_t id); + FFI_EXPORT int64_t FfiOHOSWebDownloadItemImplGetCurrentSpeed(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FfiOHOSWebDownloadItemImplGetPercentComplete(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FfiOHOSWebDownloadItemImplGetTotalBytes(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FfiOHOSWebDownloadItemImplGetReceivedBytes(int64_t id, int32_t *errCode); + FFI_EXPORT int32_t FfiOHOSWebDownloadItemImplGetState(int64_t id, int32_t *errCode); + FFI_EXPORT int32_t FfiOHOSWebDownloadItemImplGetLastErrorCode(int64_t id, int32_t *errCode); + FFI_EXPORT RetDataCString FfiOHOSWebDownloadItemImplGetMethod(int64_t id); + FFI_EXPORT RetDataCString FfiOHOSWebDownloadItemImplGetMimeType(int64_t id); + FFI_EXPORT RetDataCString FfiOHOSWebDownloadItemImplGetUrl(int64_t id); + FFI_EXPORT RetDataCString FfiOHOSWebDownloadItemImplGetSuggestedFileName(int64_t id); + FFI_EXPORT RetDataCString FfiOHOSWebDownloadItemImplGetFullPath(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebDownloadItemImplStart(int64_t id, char *downloadPath); + FFI_EXPORT int32_t FfiOHOSWebDownloadItemImplCancel(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebDownloadItemImplPause(int64_t id); + FFI_EXPORT int32_t FfiOHOSWebDownloadItemImplResume(int64_t id); + FFI_EXPORT CArrUI8 FfiOHOSWebDownloadItemImplSerialize(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FfiOHOSWebDownloadItemImplDeserialize(CArrUI8 serializedData, int32_t *errCode); + + // WebDownloadDelegateImpl + FFI_EXPORT int64_t FfiOHOSWebDownloadDelegateImplConstructor(); + FFI_EXPORT void FfiOHOSWebDownloadDelegateImplOnBeforeDownload(int64_t id, void (*callback)(int64_t)); + FFI_EXPORT void FfiOHOSWebDownloadDelegateImplOnDownloadUpdated(int64_t id, void (*callback)(int64_t)); + FFI_EXPORT void FfiOHOSWebDownloadDelegateImplOnDownloadFinish(int64_t id, void (*callback)(int64_t)); + FFI_EXPORT void FfiOHOSWebDownloadDelegateImplOnDownloadFailed(int64_t id, void (*callback)(int64_t)); + + // WebDownloadManagerImpl + FFI_EXPORT void FfiOHOSWebDownloadManagerImplSetDownloadDelegate(int64_t delegateId); + FFI_EXPORT int32_t FfiOHOSWebDownloadManagerImplResumeDownload(int64_t itemId); + + // GeolocationPermissions + FFI_EXPORT void FfiOHOSGeolocationAllowGeolocation(char* origin, bool incognito, int32_t *errCode); + FFI_EXPORT void FfiOHOSGeolocationDeleteGeolocation(char* origin, bool incognito, int32_t *errCode); + FFI_EXPORT bool FfiOHOSGeolocationGetAccessibleGeolocation(char* origin, bool incognito, int32_t *errCode); + FFI_EXPORT CArrString FfiOHOSGeolocationGetStoredGeolocation(bool incognito, int32_t *errCode); + FFI_EXPORT void FfiOHOSGeolocationDeleteAllGeolocation(bool incognito, int32_t *errCode); + + // WebMessagePort + FFI_EXPORT void FfiOHOSWebMessagePortPostMessageEvent(int64_t msgPortId, char* stringValue, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessagePortPostMessageEventArr(int64_t msgPortId, CArrUI8 arrBuf, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessagePortPostMessageEventExt(int64_t msgPortId, int64_t msgExtId, int32_t *errCode); + FFI_EXPORT bool FfiOHOSWebMessagePortIsExtentionType(int64_t msgPortId); + FFI_EXPORT void FfiOHOSWebMessagePortOnMessageEvent(int64_t msgPortId, + void (*callback)(OHOS::Webview::RetWebMessage), int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessagePortOnMessageEventExt(int64_t msgPortId, + void (*callback)(int64_t), int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessagePortClose(int64_t msgPortId, int32_t *errCode); + + // WebMessageExt + FFI_EXPORT int64_t FfiOHOSWebMessageExtImplConstructor(); + FFI_EXPORT int32_t FfiOHOSWebMessageExtImplGetType(int64_t msgExtId, int32_t *errCode); + FFI_EXPORT char* FfiOHOSWebMessageExtImplGetString(int64_t msgExtId, int32_t *errCode); + FFI_EXPORT OHOS::Webview::RetNumber FfiOHOSWebMessageExtImplGetNumber(int64_t msgExtId, int32_t *errCode); + FFI_EXPORT bool FfiOHOSWebMessageExtImplGetBoolean(int64_t msgExtId, int32_t *errCode); + FFI_EXPORT CArrUI8 FfiOHOSWebMessageExtImplGetArrayBuffer(int64_t msgExtId, int32_t *errCode); + FFI_EXPORT OHOS::Webview::CError FfiOHOSWebMessageExtImplGetError(int64_t msgExtId, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessageExtImplSetType(int64_t msgExtId, int32_t type, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessageExtImplSetString(int64_t msgExtId, char* message, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessageExtImplSetNumber(int64_t msgExtId, double value, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessageExtImplSetBoolean(int64_t msgExtId, bool value, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessageExtImplSetArrayBuffer(int64_t msgExtId, CArrUI8 value, int32_t *errCode); + FFI_EXPORT void FfiOHOSWebMessageExtImplSetError(int64_t msgExtId, + OHOS::Webview::CError value, int32_t *errCode); } #endif // WEBVIEW_FFI_H \ No newline at end of file diff --git a/interfaces/kits/cj/include/webview_javascript_result_callback.h b/interfaces/kits/cj/include/webview_javascript_result_callback.h index bc4c56379197880be3be41314166166972c12983..d9f76bd9db20a581cc546cac75a81216d939483c 100644 --- a/interfaces/kits/cj/include/webview_javascript_result_callback.h +++ b/interfaces/kits/cj/include/webview_javascript_result_callback.h @@ -153,6 +153,8 @@ public: void RemoveTransientJavaScriptObject() override; + bool DeleteJavaScriptRegister(const std::string &objName); + int32_t GetNWebId() { return nwebId_; @@ -170,7 +172,7 @@ private: bool ConstructArgv(void* ashmem, std::vector> args, std::vector& argv, std::shared_ptr jsObj, int32_t routingId); - char* FlowbufStrAtIndex(void* mem, int flowbuf_index, int* arg_index, int* str_len); + char* FlowbufStrAtIndex(void* mem, int flowbufIndex, int* argIndex, int* strLen); std::shared_ptr GetJavaScriptResultSelfHelper(std::shared_ptr jsObj, const std::string& method, int32_t routingId, std::vector argv); diff --git a/interfaces/kits/cj/include/webview_utils.h b/interfaces/kits/cj/include/webview_utils.h index f7c8ee7da6c8f5c67357985a9576c113f7c56717..cab69a6f3077d9457bd768bac6a98d36e319565c 100644 --- a/interfaces/kits/cj/include/webview_utils.h +++ b/interfaces/kits/cj/include/webview_utils.h @@ -19,6 +19,8 @@ #include #include #include +#include +#include "cj_common_ffi.h" namespace OHOS { namespace Webview { @@ -47,7 +49,74 @@ namespace Webview { const char* cHistoryUrl; }; + struct CMediaSourceInfo + { + const char* format; + const char* source; + int32_t type; + }; + + struct CArrMediaSourceInfo { + CMediaSourceInfo* head; + int64_t size; + }; + + struct MapItem { + char* key; + char* value; + }; + + struct ArrMapItem { + MapItem* head; + int64_t size; + }; + + struct CRectEvent { + double x; + double y; + double width; + double height; + }; + + struct CNativeMediaPlayerSurfaceInfo { + CRectEvent rect; + const char* id; + }; + + struct CMediaInfo + { + const char* embedID; + int32_t mediaType; + CArrMediaSourceInfo mediaSrcList; + CNativeMediaPlayerSurfaceInfo surfaceInfo; + bool controlsShown; + CArrString controlList; + bool muted; + const char* posterUrl; + int32_t preload; + ArrMapItem headers; + ArrMapItem attributes; + }; + + struct RetWebMessage { + char* messageStr; + CArrUI8 messageArr; + }; + + struct CError { + char *errorName; + char *errorMsg; + }; + + struct RetNumber { + int64_t numberInt; + double numberDouble; + }; + char* MallocCString(const std::string& origin); + uint8_t* MallocUInt8(const std::string& origin); + char** VectorToCArrString(const std::vector& vec); + uint8_t* VectorToCArrUI8(const std::vector vec); } } diff --git a/interfaces/kits/cj/src/geolocation_permission.cpp b/interfaces/kits/cj/src/geolocation_permission.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9358806caf04b640723d217d703f3e9edbbc2ffe --- /dev/null +++ b/interfaces/kits/cj/src/geolocation_permission.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "geolocation_permission.h" + +#include +#include + +#include "nweb_data_base.h" +#include "nweb_helper.h" +#include "web_errors.h" +#include "securec.h" + +namespace { +constexpr int32_t INTERFACE_OK = 0; +constexpr int32_t INTERFACE_ERROR = -1; +constexpr int32_t ALLOW_PERMISSION_OPERATION = 1; +constexpr int32_t DELETE_PERMISSION_OPERATION = 2; + +} // namespace + +namespace OHOS { +namespace NWeb { + +void GeolocationPermission::ProcessActionByType(std::string origin, bool incognitoMode, + int32_t operationType, int32_t *errCode) +{ + std::shared_ptr dataBase = OHOS::NWeb::NWebHelper::Instance().GetDataBase(); + if (!dataBase) { + return; + } + if (operationType == ALLOW_PERMISSION_OPERATION) { + if (dataBase->SetPermissionByOrigin(origin, OHOS::NWeb::NWebDataBase::WebPermissionType::GEOLOCATION_TYPE, true, + incognitoMode) == NWebError::INVALID_ORIGIN) { + *errCode = NWebError::INVALID_ORIGIN; + return; + } + } else if (operationType == DELETE_PERMISSION_OPERATION) { + if (dataBase->ClearPermissionByOrigin(origin, OHOS::NWeb::NWebDataBase::WebPermissionType::GEOLOCATION_TYPE, + incognitoMode) == NWebError::INVALID_ORIGIN) { + *errCode =NWebError::INVALID_ORIGIN; + return; + } + } + return; +} + +bool GeolocationPermission::ExecuteGetPermissionState(std::string origin, bool incognitoMode, int32_t *errCode) +{ + bool retValue = false; + std::shared_ptr dataBase = OHOS::NWeb::NWebHelper::Instance().GetDataBase(); + if (!dataBase) { + *errCode = INTERFACE_ERROR; + return retValue; + } + if (dataBase->GetPermissionResultByOrigin(origin, + OHOS::NWeb::NWebDataBase::WebPermissionType::GEOLOCATION_TYPE, retValue, incognitoMode)) { + *errCode = INTERFACE_OK; + } else { + *errCode = NWebError::INVALID_ORIGIN; + } + return retValue; +} + + +std::vector GeolocationPermission::ExecuteGetOrigins(bool incognitoMode, int32_t *errCode) +{ + std::vector origins; + std::shared_ptr dataBase = OHOS::NWeb::NWebHelper::Instance().GetDataBase(); + if (!dataBase) { + *errCode = INTERFACE_ERROR; + return origins; + } + origins = dataBase->GetOriginsByPermission( + OHOS::NWeb::NWebDataBase::WebPermissionType::GEOLOCATION_TYPE, incognitoMode); + *errCode = INTERFACE_OK; + return origins; +} + +void GeolocationPermission::CjAllowGeolocation(std::string origin, bool incognitoMode, int32_t *errCode) +{ + return ProcessActionByType(origin, incognitoMode, ALLOW_PERMISSION_OPERATION, errCode); +} + +void GeolocationPermission::CjDeleteGeolocation(std::string origin, bool incognitoMode, int32_t *errCode) +{ + return ProcessActionByType(origin, incognitoMode, DELETE_PERMISSION_OPERATION, errCode); +} + +bool GeolocationPermission::CjGetAccessibleGeolocation(std::string origin, bool incognitoMode, int32_t *errCode) +{ + return ExecuteGetPermissionState(origin, incognitoMode, errCode); +} + +std::vector GeolocationPermission::CjGetStoredGeolocation(bool incognitoMode, int32_t *errCode) +{ + return ExecuteGetOrigins(incognitoMode, errCode); +} + +void GeolocationPermission::CjDeleteAllGeolocation(bool incognitoMode, int32_t *errCode) +{ + std::shared_ptr dataBase = OHOS::NWeb::NWebHelper::Instance().GetDataBase(); + if (dataBase != nullptr) { + dataBase->ClearAllPermission(OHOS::NWeb::NWebDataBase::WebPermissionType::GEOLOCATION_TYPE, incognitoMode); + } + return; +} + +} // namespace NWeb +} // namespace OHOS diff --git a/interfaces/kits/cj/src/native_media_player_impl.cpp b/interfaces/kits/cj/src/native_media_player_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0db1ed995e81a77aef5aef05f2ef7f6f48d59dc --- /dev/null +++ b/interfaces/kits/cj/src/native_media_player_impl.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "webview_controller_impl.h" +#include "webview_javascript_execute_callback.h" +#include "webview_javascript_result_callback.h" +#include "native_arkweb_utils.h" +#include "native_interface_arkweb.h" +#include "cj_common_ffi.h" +#include "application_context.h" +#include "webview_log.h" +#include "webview_utils.h" +#include "nweb_store_web_archive_callback.h" +#include "native_media_player_impl.h" + +namespace OHOS::Webview { + +NativeMediaPlayerHandlerImpl :: NativeMediaPlayerHandlerImpl( + int32_t nwebId, std::shared_ptr handler) + : nwebId_(nwebId), handler_(handler) + {} + +void NativeMediaPlayerHandlerImpl::HandleVideoSizeChanged(double width,double height) +{ + if(handler_){ + handler_->HandleVideoSizeChanged(width,height); + } +} + +void NativeMediaPlayerHandlerImpl::HandleError(NWeb::MediaError error,const char* errorMessage) +{ + if(handler_){ + handler_->HandleError(error,errorMessage); + } +} + +void NativeMediaPlayerHandlerImpl::HandleSeekFinished() +{ + if(handler_){ + handler_->HandleSeekFinished(); + } +} + +void NativeMediaPlayerHandlerImpl::HandleSeeking() +{ + if(handler_){ + handler_->HandleSeeking(); + } +} + +void NativeMediaPlayerHandlerImpl::HandleFullScreenChanged(bool fullscreen) +{ + if(handler_){ + handler_->HandleFullScreenChanged(fullscreen); + } +} + +void NativeMediaPlayerHandlerImpl::HandleReadyStateChanged(NWeb::ReadyState state) +{ + if(handler_){ + handler_->HandleReadyStateChanged(state); + } +} + +void NativeMediaPlayerHandlerImpl::HandleNetworkStateChanged(NWeb::NetworkState state) +{ + if(handler_){ + handler_->HandleNetworkStateChanged(state); + } +} + +void NativeMediaPlayerHandlerImpl::HandleEnded() +{ + if(handler_){ + handler_->HandleEnded(); + } +} + +void NativeMediaPlayerHandlerImpl::HandleBufferedEndTimeChanged(double bufferedEndTime) +{ + if(handler_){ + handler_->HandleBufferedEndTimeChanged(bufferedEndTime); + } +} + +void NativeMediaPlayerHandlerImpl::NativeMediaPlayerHandlerImpl::HandleTimeUpdate(double playTime) +{ + if(handler_){ + handler_->HandleTimeUpdate(playTime); + } +} + +void NativeMediaPlayerHandlerImpl::HandleDurationChanged(double duration) +{ + if(handler_){ + handler_->HandleDurationChanged(duration); + } +} + +void NativeMediaPlayerHandlerImpl::HandlePlaybackRateChanged(double playbackRate) +{ + if(handler_){ + handler_->HandlePlaybackRateChanged(playbackRate); + } +} + +void NativeMediaPlayerHandlerImpl::HandleMutedChanged(bool muted) +{ + if(handler_){ + handler_->HandleMutedChanged(muted); + } +} + +void NativeMediaPlayerHandlerImpl::HandleVolumeChanged(double volume) +{ + if(handler_){ + handler_->HandleVolumeChanged(volume); + } +} + +void NativeMediaPlayerHandlerImpl::HandleStatusChanged(NWeb::PlaybackStatus status){ + if(handler_){ + handler_->HandleStatusChanged(status); + } +} + +NWebNativeMediaPlayerBridgeImpl::NWebNativeMediaPlayerBridgeImpl +(sptr nativeMediaPlayerImpl) + : nativeMediaPlayerImpl_(nativeMediaPlayerImpl) +{} + +void NWebNativeMediaPlayerBridgeImpl::ExitFullScreen() +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->ExitFullScreen(); + } +} + +void NWebNativeMediaPlayerBridgeImpl::EnterFullScreen() +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->EnterFullScreen(); + } +} + +void NWebNativeMediaPlayerBridgeImpl::Release() +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->Release(); + } +} + +void NWebNativeMediaPlayerBridgeImpl::SetPlaybackRate(double playbackRate) +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->SetPlaybackRate(playbackRate); + } +} + +void NWebNativeMediaPlayerBridgeImpl::SetMuted(bool isMuted) +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->SetMuted(isMuted); + } +} + +void NWebNativeMediaPlayerBridgeImpl::SetVolume(double volume) +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->SetVolume(volume); + } +} + +void NWebNativeMediaPlayerBridgeImpl::Seek(double time) +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->Seek(time); + } +} + +void NWebNativeMediaPlayerBridgeImpl::Pause() +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->Pause(); + } +} + +void NWebNativeMediaPlayerBridgeImpl::Play() +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->Play(); + } +} + +void NWebNativeMediaPlayerBridgeImpl::UpdateRect(double x, double y, double width, double height) +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->UpdateRect(x, y, width, height); + } +} + +void NWebNativeMediaPlayerBridgeImpl::ResumeMediaPlayer() +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->ResumeMediaPlayer(); + } +} + +void NWebNativeMediaPlayerBridgeImpl::SuspendMediaPlayer(NWeb::SuspendType type) +{ + if(nativeMediaPlayerImpl_ != nullptr){ + nativeMediaPlayerImpl_->SuspendMediaPlayer(type); + } +} + +NWebCreateNativeMediaPlayerCallbackImpl::NWebCreateNativeMediaPlayerCallbackImpl( + int32_t nwebId, std::function callback) + : nwebId_(nwebId), callback_(callback) +{} + +std::shared_ptr NWebCreateNativeMediaPlayerCallbackImpl::OnCreate( + std::shared_ptr handler, std::shared_ptr mediaInfo) +{ + WEBVIEWLOGD("begin to create native media player,nweb id is %{public}d", nwebId_); + + if(!callback_){ + WEBVIEWLOGD("callback is null,nweb id is %{public}d", nwebId_); + return nullptr; + } + + if (!handler || !mediaInfo) { + WEBVIEWLOGD("param is null,nweb id is %{public}d", nwebId_); + return nullptr; + } + + auto handlerImpl = FFIData::Create(nwebId_, handler); + int64_t handlerId = handlerImpl->GetID(); + std::string embedID_ = mediaInfo->GetEmbedId(); + const char* embedID = MallocCString(embedID_); + int32_t mediaType = static_cast(mediaInfo->GetMediaType()); + std::vector> mediaSrcList_ = mediaInfo->GetSourceInfos(); + CMediaSourceInfo* result = static_cast(malloc(sizeof(CMediaSourceInfo) * mediaSrcList_.size())); + if(result == nullptr){ + return nullptr; + } + for(size_t i = 0; i < mediaSrcList_.size(); i++){ + const char* format = MallocCString(mediaSrcList_[i]->GetFormat()); + const char* source = MallocCString(mediaSrcList_[i]->GetSource()); + int32_t type = static_cast(mediaSrcList_[i]->GetType()); + CMediaSourceInfo cMediaSourceInfo = {format, source, type}; + result[i] = cMediaSourceInfo; + } + CArrMediaSourceInfo mediaSrcList = {result, mediaSrcList_.size()}; + std::shared_ptr surfaceInfo_ = mediaInfo->GetSurfaceInfo(); + CNativeMediaPlayerSurfaceInfo surfaceInfo; + CRectEvent event; + surfaceInfo.id = MallocCString(surfaceInfo_->GetId()); + event.x = surfaceInfo_->GetX(); + event.y = surfaceInfo_->GetY(); + event.width = surfaceInfo_->GetWidth(); + event.height = surfaceInfo_->GetHeight(); + surfaceInfo.rect = event; + bool controlsShown = mediaInfo->GetIsControlsShown(); + std::vector controlList_ = mediaInfo->GetControls(); + char** result2 = static_cast(malloc(sizeof(char *) * controlList_.size())); + if(result2 == nullptr){ + return nullptr; + } + for(size_t i = 0; i < controlList_.size(); i++){ + result2[i] = MallocCString(controlList_[i]); + } + CArrString controlList = {result2, controlList_.size()}; + bool muted = mediaInfo->GetIsMuted(); + std::string posterUrl_ = mediaInfo->GetPosterUrl(); + const char* posterUrl = MallocCString(posterUrl_); + int32_t preload = static_cast(mediaInfo->GetPreload()); + std::map headers_ = mediaInfo->GetHeaders(); + MapItem* result3 = static_cast(malloc(sizeof(MapItem) * headers_.size())); + if(result3 == nullptr){ + return nullptr; + } + size_t i = 0; + for(const auto& pair : headers_){ + MapItem mapItem = {MallocCString(pair.first), MallocCString(pair.second)}; + result3[i] = mapItem; + i++; + } + ArrMapItem headers = {result3, headers_.size()}; + std::map attributes_ = mediaInfo->GetAttributes(); + MapItem* result4 = static_cast(malloc(sizeof(MapItem) * attributes_.size())); + if(result4 == nullptr){ + return nullptr; + } + size_t j = 0; + for(const auto& pair : attributes_){ + MapItem mapItem = {MallocCString(pair.first), MallocCString(pair.second)}; + result4[j] = mapItem; + j++; + } + ArrMapItem attributes = {result4, attributes_.size()}; + CMediaInfo cMediaInfo = {embedID, mediaType, mediaSrcList, surfaceInfo, controlsShown, controlList, muted, posterUrl, preload, headers, attributes}; + int64_t nativeMediaPlayerBridgeId = callback_(handlerId, cMediaInfo); + auto nativePlayer = FFIData::GetData(nativeMediaPlayerBridgeId); + return std::make_shared(nativePlayer); +} + +} // namespace OHOS::Webview \ No newline at end of file diff --git a/interfaces/kits/cj/src/web_cookie_manager.cpp b/interfaces/kits/cj/src/web_cookie_manager.cpp index 5810abfcca5cb74a9dd4ede32dd2b9fe70243c78..8956d29de979467398ff29d03c58265ba23e8dff 100644 --- a/interfaces/kits/cj/src/web_cookie_manager.cpp +++ b/interfaces/kits/cj/src/web_cookie_manager.cpp @@ -31,7 +31,7 @@ std::string WebCookieManager::CjGetCookie(const std::string &url, bool incognito } if (cookieContent == "" && !isValid) { errCode = NWebError::INVALID_URL; - return nullptr; + return ""; } errCode = NWebError::NO_ERROR; return cookieContent; diff --git a/interfaces/kits/cj/src/web_data_base.cpp b/interfaces/kits/cj/src/web_data_base.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93820b52333bb299fbe5645b8bc9137961dca25f --- /dev/null +++ b/interfaces/kits/cj/src/web_data_base.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "web_data_base.h" +#include "nweb_data_base.h" +#include "nweb_helper.h" +#include "web_errors.h" +#include "webview_utils.h" +#include "webview_log.h" +#include "securec.h" +#include + +namespace OHOS { +namespace NWeb { +const int DEFAULT_AUTH_LENGTH = 2; +const int HTTP_AUTH_INIT_LENGTH = -1; + +CArrString WebDataBase::CJGetHttpAuthCredentials(const std::string &host, const std::string &realm) +{ + CArrString ret = {nullptr, HTTP_AUTH_INIT_LENGTH}; + std::string username_s; + char password[MAX_PWD_LENGTH + 1] = {0}; + + char** result = static_cast(malloc(sizeof(char*) * DEFAULT_AUTH_LENGTH)); + if (result == nullptr) { + WEBVIEWLOGI("Webdatabase getHttpAuthCredentials malloc result failed!"); + return ret; + } + + result[0] = static_cast(malloc(sizeof(char) * (MAX_STRING_LENGTH + 1))); + if (result[0] == nullptr) { + WEBVIEWLOGI("Webdatabase getHttpAuthCredentials malloc username failed!"); + free(result); + return ret; + } + + result[1] = static_cast(malloc(sizeof(char) * (MAX_PWD_LENGTH + 1))); + if (result[1] == nullptr) { + WEBVIEWLOGI("Webdatabase getHttpAuthCredentials malloc password failed!"); + free(result[0]); + free(result); + return ret; + } + + std::shared_ptr database = NWebHelper::Instance().GetDataBase(); + if (database != nullptr) { + database->GetHttpAuthCredentials(host, realm, username_s, password, MAX_PWD_LENGTH + 1); + } + + if (username_s.empty() || strlen(password) == 0) { + ret.size = 0; + return ret; + } + + result[0] = OHOS::Webview::MallocCString(username_s); + if (result[0] == nullptr) { + WEBVIEWLOGI("Webdatabase getHttpAuthCredentials transfer username_s failed!"); + for (int i = 0; i < DEFAULT_AUTH_LENGTH; i++) + free(result[i]); + free(result); + return ret; + } + + result[1] = std::char_traits::copy(result[1], password, MAX_PWD_LENGTH); + (void)memset_s(password, MAX_PWD_LENGTH + 1, 0, MAX_PWD_LENGTH + 1); + ret.head = result; + ret.size = DEFAULT_AUTH_LENGTH; + return ret; +} + +void WebDataBase::CJSaveHttpAuthCredentials(const std::string &host, const std::string &realm, + const std::string &username, const std::string &password) +{ + // get web database instance; + std::shared_ptr database = NWebHelper::Instance().GetDataBase(); + if (database != nullptr) { + database->SaveHttpAuthCredentials(host, realm, username, password.c_str()); + } +} + +bool WebDataBase::CJExistHttpAuthCredentials() +{ + bool isExist = false; + // get web database instance; + std::shared_ptr database = NWebHelper::Instance().GetDataBase(); + if (database != nullptr) { + isExist = database->ExistHttpAuthCredentials(); + } + return isExist; +} + +void WebDataBase::CJDeleteHttpAuthCredentials() +{ + // get web database instance; + std::shared_ptr database = NWebHelper::Instance().GetDataBase(); + if (database != nullptr) { + database->DeleteHttpAuthCredentials(); + } +} +} +} \ No newline at end of file diff --git a/interfaces/kits/cj/src/web_download_delegate_impl.cpp b/interfaces/kits/cj/src/web_download_delegate_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..632719fcc00da3fc416c93ed56f983d3306c46c2 --- /dev/null +++ b/interfaces/kits/cj/src/web_download_delegate_impl.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "web_download_delegate_impl.h" + +#include + +#include "nweb_c_api.h" +#include "webview_log.h" +#include "web_download_manager_impl.h" + +namespace OHOS::Webview { + WebDownloadDelegateImpl::WebDownloadDelegateImpl() + : download_before_start_callback_(nullptr), + download_did_update_callback_(nullptr), + download_did_finish_callback_(nullptr), + download_did_fail_callback_(nullptr) + { + WEBVIEWLOGD("WebDownloadDelegate::WebDownloadDelegate"); + } + + WebDownloadDelegateImpl::~WebDownloadDelegateImpl() + { + WEBVIEWLOGI("[DOWNLOAD] WebDownloadDelegate::~WebDownloadDelegate"); + WebDownloadManagerImpl::RemoveDownloadDelegate(this); + } + + void WebDownloadDelegateImpl::DownloadBeforeStart(WebDownloadItemImpl *webDownloadItemImpl) + { + WEBVIEWLOGI("[DOWNLOAD] WebDownloadDelegate::DownloadBeforeStart"); + if (!download_before_start_callback_) { + WEBVIEWLOGE("[DOWNLOAD] downloadBeforeStart not exists."); + return; + } + download_before_start_callback_(webDownloadItemImpl->GetID()); + } + + void WebDownloadDelegateImpl::DownloadDidUpdate(WebDownloadItemImpl *webDownloadItemImpl) + { + WEBVIEWLOGI("[DOWNLOAD] WebDownloadDelegate::DownloadDidUpdate"); + if (!download_did_update_callback_) { + WEBVIEWLOGE("[DOWNLOAD] downloadBeforeStart not exists."); + return; + } + download_did_update_callback_(webDownloadItemImpl->GetID()); + } + + void WebDownloadDelegateImpl::DownloadDidFail(WebDownloadItemImpl *webDownloadItemImpl) + { + WEBVIEWLOGI("WebDownloadDelegate::DownloadDidFail"); + if (!download_did_fail_callback_) { + WEBVIEWLOGE("[DOWNLOAD] downloadDidFail not exists."); + return; + } + download_did_fail_callback_(webDownloadItemImpl->GetID()); + } + + void WebDownloadDelegateImpl::DownloadDidFinish(WebDownloadItemImpl *webDownloadItemImpl) + { + WEBVIEWLOGI("WebDownloadDelegate::DownloadDidFinish"); + if (!download_did_finish_callback_) { + WEBVIEWLOGE("[DOWNLOAD] downloadBeforeStart not exists."); + return; + } + download_did_finish_callback_(webDownloadItemImpl->GetID()); + } + + void WebDownloadDelegateImpl::PutDownloadBeforeStart(std::function callback) + { + WEBVIEWLOGD("WebDownloadDelegate::PutDownloadBeforeStart"); + download_before_start_callback_ = callback; + } + + void WebDownloadDelegateImpl::PutDownloadDidUpdate(std::function callback) + { + WEBVIEWLOGI("[DOWNLOAD] WebDownloadDelegate::PutDownloadDidUpdate"); + download_did_update_callback_ = callback; + } + + void WebDownloadDelegateImpl::PutDownloadDidFinish(std::function callback) + { + WEBVIEWLOGD("WebDownloadDelegate::PutDownloadDidFinish"); + download_did_finish_callback_ = callback; + } + + void WebDownloadDelegateImpl::PutDownloadDidFail(std::function callback) + { + WEBVIEWLOGD("WebDownloadDelegate::PutDownloadDidFail"); + download_did_fail_callback_ = callback; + } + + int32_t WebDownloadDelegateImpl::GetNWebId() + { + return nwebId_; + } + + void WebDownloadDelegateImpl::SetNWebId(int32_t nwebId) + { + nwebId_ = nwebId; + } + +} // namespace OHOS:WebView diff --git a/interfaces/kits/cj/src/web_download_item_impl.cpp b/interfaces/kits/cj/src/web_download_item_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26b0ca093d4363b70b5fcd1eb40903d3bb9eabe5 --- /dev/null +++ b/interfaces/kits/cj/src/web_download_item_impl.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "web_download_item_impl.h" + +#include + +#include "webview_log.h" + +namespace OHOS::Webview { + WebDownloadItemImpl::WebDownloadItemImpl() + : guid(""), + fullPath(""), + url(""), + etag(""), + originalUrl(""), + suggestedFileName(""), + contentDisposition(""), + mimeType(""), + lastModified(""), + method(""), + receivedSlices(""), + downloadPath(""), + before_download_callback(nullptr), + download_item_callback(nullptr) + { + WEBVIEWLOGD("[DOWNLOAD] WebDownloadItemImpl::constructor"); + this->currentSpeed = 0; + this->percentComplete = 0; + this->totalBytes = 0; + this->receivedBytes = 0; + this->lastErrorCode = 0; + this->webDownloadId = 0; + this->nwebId = 0; + } + + WebDownloadItemImpl::WebDownloadItemImpl(NWebDownloadItem *downloadItem) + : guid(""), + fullPath(""), + url(""), + etag(""), + originalUrl(""), + suggestedFileName(""), + contentDisposition(""), + mimeType(""), + lastModified(""), + method(""), + receivedSlices(""), + downloadPath(""), + before_download_callback(nullptr), + download_item_callback(nullptr) + { + WEBVIEWLOGD("[DOWNLOAD] WebDownloadItem constructor"); + this->webDownloadId = WebDownloadItem_GetDownloadItemId(downloadItem); + this->state = WebDownloadItem_GetState(downloadItem); + this->currentSpeed = WebDownloadItem_CurrentSpeed(downloadItem); + this->percentComplete = WebDownloadItem_PercentComplete(downloadItem); + this->totalBytes = WebDownloadItem_TotalBytes(downloadItem); + this->receivedBytes = WebDownloadItem_ReceivedBytes(downloadItem); + this->guid = std::string(WebDownloadItem_Guid(downloadItem)); + this->fullPath = std::string(WebDownloadItem_FullPath(downloadItem)); + this->url = std::string(WebDownloadItem_Url(downloadItem)); + this->originalUrl = std::string(WebDownloadItem_OriginalUrl(downloadItem)); + this->suggestedFileName = std::string(WebDownloadItem_SuggestedFileName(downloadItem)); + this->contentDisposition = std::string(WebDownloadItem_ContentDisposition(downloadItem)); + this->method = std::string(WebDownloadItem_Method(downloadItem)); + this->lastModified = std::string(WebDownloadItem_LastModified(downloadItem)); + this->lastErrorCode = WebDownloadItem_LastErrorCode(downloadItem); + this->receivedSlices = std::string(WebDownloadItem_ReceivedSlices(downloadItem)); + this->etag = std::string(WebDownloadItem_ETag(downloadItem)); + this->mimeType = std::string(WebDownloadItem_MimeType(downloadItem)); + this->nwebId = WebDownloadItem_NWebId(downloadItem); + } + + WebDownloadItemImpl::~WebDownloadItemImpl() + { + WEBVIEWLOGD("[DOWNLOAD] WebDownloadItemImpl::~WebDownloadItemImpl()"); + if (before_download_callback) { + DestroyBeforeDownloadCallbackWrapper(before_download_callback); + before_download_callback = nullptr; + } + if (download_item_callback) { + DestroyDownloadItemCallbackWrapper(download_item_callback); + download_item_callback = nullptr; + } + } +} // namespace OHOS::Webview { \ No newline at end of file diff --git a/interfaces/kits/cj/src/web_download_manager_impl.cpp b/interfaces/kits/cj/src/web_download_manager_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c0248e5601642ff6a15f27cbc09cf52f507b28d --- /dev/null +++ b/interfaces/kits/cj/src/web_download_manager_impl.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "web_download_manager_impl.h" + +#include + +#include "ffi_remote_data.h" +#include "nweb_c_api.h" +#include "nweb_helper.h" +#include "webview_log.h" +#include "web_download_delegate_impl.h" + +using namespace OHOS::FFI; + +namespace OHOS::Webview { +namespace { + static sptr g_default_delegate; + static std::unordered_map g_web_download_delegate_map; + static WebDownloadDelegateCallback *g_download_callback; + + WebDownloadDelegateImpl *GetWebDownloadDelegate(int32_t nwebId) + { + auto it = g_web_download_delegate_map.find(nwebId); + if (it != g_web_download_delegate_map.end()) { + return it->second; + } + return nullptr; + } + + void DownloadBeforeStart(NWebDownloadItem *downloadItem, WebBeforeDownloadCallbackWrapper *wrapper) + { + WEBVIEWLOGD("[DOWNLOAD] DownloadBeforeStart."); + if (wrapper == nullptr) { + WEBVIEWLOGE("[DOWNLOAD] WebBeforeDownloadCallbackWrapper is null"); + return; + } + int32_t nwebId = WebDownloadItem_NWebId(downloadItem); + WebDownloadDelegateImpl *webDownloadDelegate = GetWebDownloadDelegate(nwebId); + if (!webDownloadDelegate) { + WEBVIEWLOGD("[DOWNLOAD] donn't found delegate for nweb."); + webDownloadDelegate = g_default_delegate; + } + + if (!webDownloadDelegate) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + + WebDownloadItemImpl *webDownloadItem = FFIData::Create(downloadItem); + // destroy download_item since copied content from download_item. + WebDownloadItem_Destroy(downloadItem); + webDownloadItem->before_download_callback = wrapper; + webDownloadDelegate->DownloadBeforeStart(webDownloadItem); + } + + void DownloadDidUpdate(NWebDownloadItem *downloadItem, WebDownloadItemCallbackWrapper *wrapper) + { + WEBVIEWLOGI("DownloadDidUpdate."); + if (wrapper == nullptr) { + WEBVIEWLOGE("[DOWNLOAD] WebBeforeDownloadCallbackWrapper is null"); + return; + } + + int32_t nwebId = WebDownloadItem_NWebId(downloadItem); + + WebDownloadDelegateImpl *webDownloadDelegate = GetWebDownloadDelegate(nwebId); + if (!webDownloadDelegate) { + WEBVIEWLOGD("[DOWNLOAD] donn't found delegate for nweb."); + webDownloadDelegate = g_default_delegate; + } + + if (!webDownloadDelegate) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + WebDownloadItemImpl *webDownloadItem = FFIData::Create(downloadItem); + // destroy download_item since copied content from download_item. + WebDownloadItem_Destroy(downloadItem); + webDownloadItem->download_item_callback = wrapper; + switch (webDownloadItem->state) { + case NWebDownloadItemState::PENDING: + // When in PENDING state, chromium call downloadDidUpdate + // while file path is temporary file, just stop calling ui. + webDownloadItem = nullptr; + break; + case NWebDownloadItemState::IN_PROGRESS: + case NWebDownloadItemState::PAUSED: + webDownloadDelegate->DownloadDidUpdate(webDownloadItem); + break; + case NWebDownloadItemState::INTERRUPTED: + case NWebDownloadItemState::CANCELED: + webDownloadDelegate->DownloadDidFail(webDownloadItem); + break; + case NWebDownloadItemState::COMPLETE: + webDownloadDelegate->DownloadDidFinish(webDownloadItem); + break; + case NWebDownloadItemState::MAX_DOWNLOAD_STATE: + default: + webDownloadItem = nullptr; + break; + } + } + } // namespace + + // static + void WebDownloadManagerImpl::RegisterDownloadCallback() + { + // Only regist once. + if (g_download_callback == nullptr) { + WEBVIEWLOGI("RegisterDownloadCallback."); + WebDownloader_CreateDownloadDelegateCallback(&g_download_callback); + WebDownloader_SetDownloadBeforeStart(g_download_callback, &DownloadBeforeStart); + WebDownloader_SetDownloadDidUpdate(g_download_callback, &DownloadDidUpdate); + WebDownloadManager_PutDownloadCallback(g_download_callback); + } else { + WEBVIEWLOGE("[DOWNLOAD] had RegisterDownloadCallback."); + } + } + + // static + void WebDownloadManagerImpl::RemoveDownloadDelegate(WebDownloadDelegateImpl *delegate) + { + auto iterator = g_web_download_delegate_map.begin(); + while (iterator != g_web_download_delegate_map.end()) { + if (iterator->second == delegate) { + g_web_download_delegate_map.erase(iterator++); + } else { + iterator++; + } + } + } + + // static + void WebDownloadManagerImpl::AddDownloadDelegateForWeb(int32_t nwebId, WebDownloadDelegateImpl *delegate) + { + OHOS::NWeb::NWebHelper::Instance().LoadNWebSDK(); + g_web_download_delegate_map.insert_or_assign(nwebId, delegate); + RegisterDownloadCallback(); + } + + // static + void WebDownloadManagerImpl::SetDownloadDelegate(WebDownloadDelegateImpl *delegate) + { + OHOS::NWeb::NWebHelper::Instance().LoadNWebSDK(); + if (!g_default_delegate) { + g_default_delegate = delegate; + RegisterDownloadCallback(); + } + } + + // static + bool WebDownloadManagerImpl::HasValidDelegate() + { + if (!g_default_delegate) { + return false; + } + + return true; + } + + // static + void WebDownloadManagerImpl::ResumeDownload(const WebDownloadItemImpl *webDownload) + { + WEBVIEWLOGD("[DOWNLOAD] WebDownloadManager::ResumeDownload"); + if (!webDownload) { + WEBVIEWLOGE("webDownload is nullptr"); + return; + } + OHOS::NWeb::NWebHelper::Instance().LoadNWebSDK(); + NWebDownloadItem *downloadItem = nullptr; + WebDownloadItem_CreateWebDownloadItem(&downloadItem); + WebDownloadItem_SetGuid(downloadItem, webDownload->guid.c_str()); + WebDownloadItem_SetUrl(downloadItem, webDownload->url.c_str()); + WebDownloadItem_SetFullPath(downloadItem, webDownload->fullPath.c_str()); + WebDownloadItem_SetETag(downloadItem, webDownload->etag.c_str()); + WebDownloadItem_SetMimeType(downloadItem, webDownload->mimeType.c_str()); + WebDownloadItem_SetReceivedBytes(downloadItem, webDownload->receivedBytes); + WebDownloadItem_SetTotalBytes(downloadItem, webDownload->totalBytes); + WebDownloadItem_SetReceivedSlices(downloadItem, webDownload->receivedSlices.c_str()); + WebDownloadItem_SetLastModified(downloadItem, webDownload->lastModified.c_str()); + WebDownloader_ResumeDownloadStatic(downloadItem); + return; + } +} // namespace NWeb diff --git a/interfaces/kits/cj/src/web_errors.cpp b/interfaces/kits/cj/src/web_errors.cpp index 93295db9a2e48078d4ec589a38388db734e65826..5e9074d9051ef23c51562d8a5699da1aa160a356 100644 --- a/interfaces/kits/cj/src/web_errors.cpp +++ b/interfaces/kits/cj/src/web_errors.cpp @@ -36,11 +36,13 @@ const std::string TYPE_NOT_MATCH_WITCH_VALUE_MSG = "The type and value of the me const std::string NEW_OOM_MSG = "Memory allocation failed."; const std::string DOWNLOAD_NOT_PAUSED_MSG = "The download task is not paused."; const std::string NO_VALID_CONTROLLER_FOR_DOWNLOAD_MSG = "No valid WebviewController is associated."; -const std::string NO_DOWNLOAD_DELEGATE_SET_MSG = "No valid WebviewController is associated."; +const std::string NO_DOWNLOAD_DELEGATE_SET_MSG = "No WebDownloadDelegate has been set yet."; const std::string DOWNLOAD_NOT_START_MSG = "The download task is not started yet."; const std::string REGISTER_CUSTOM_SCHEME_FAILED_MSG = "Failed to register custom schemes."; const std::string HTTP_BODY_STREAN_INIT_FAILED_MSG = "Failed to initialize the HTTP body stream."; const std::string RESOURCE_HANDLER_INVALID_MSG = "The resource handler is invalid."; +const std::string HTTP_AUTH_MALLOC_FAILED_MSG = "Failed to malloc string memory to get HttpAuth."; +const std::string UNKNOWN_ERROR_MSG = "Unknown error message."; } namespace OHOS { @@ -67,11 +69,16 @@ std::unordered_map g_errCodeMsgMap = { {REGISTER_CUSTOM_SCHEME_FAILED, REGISTER_CUSTOM_SCHEME_FAILED_MSG}, {HTTP_BODY_STREAN_INIT_FAILED, HTTP_BODY_STREAN_INIT_FAILED_MSG}, {RESOURCE_HANDLER_INVALID, RESOURCE_HANDLER_INVALID_MSG}, + {HTTP_AUTH_MALLOC_FAILED, HTTP_AUTH_MALLOC_FAILED_MSG}, }; std::string GetErrMsgByErrCode(ErrCode code) { - return g_errCodeMsgMap[code]; + auto it = g_errCodeMsgMap.find(code); + if (it != g_errCodeMsgMap.end()) { + return it->second; + } + return UNKNOWN_ERROR_MSG; } } // namespace NWebError } // namespace OHOS diff --git a/interfaces/kits/cj/src/webview_controller_impl.cpp b/interfaces/kits/cj/src/webview_controller_impl.cpp index 10b83226cc52c29ad44119ce56fad0f3d468e351..9786cba9a1b5fc3f253e427c31337a15688b6640 100644 --- a/interfaces/kits/cj/src/webview_controller_impl.cpp +++ b/interfaces/kits/cj/src/webview_controller_impl.cpp @@ -15,6 +15,7 @@ #include #include "webview_controller_impl.h" +#include "native_media_player_impl.h" #include "webview_javascript_execute_callback.h" #include "webview_javascript_result_callback.h" #include "native_arkweb_utils.h" @@ -24,6 +25,9 @@ #include "webview_log.h" #include "webview_utils.h" #include "nweb_store_web_archive_callback.h" +#include +#include "web_errors.h" +#include "ffi_remote_data.h" namespace OHOS::Webview { std::unordered_map g_webview_controller_map; @@ -31,6 +35,92 @@ namespace OHOS::Webview { bool WebviewControllerImpl::existNweb_ = false; bool WebviewControllerImpl::webDebuggingAccess_ = false; + // WebMessagePortImpl + WebMessagePortImpl::WebMessagePortImpl(int32_t nwebId, std::string port, bool isExtentionType) + : nwebId_(nwebId), portHandle_(port), isExtentionType_(isExtentionType) + {} + + ErrCode WebMessagePortImpl::ClosePort() + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + + nweb_ptr->ClosePort(portHandle_); + portHandle_.clear(); + return NWebError::NO_ERROR; + } + + ErrCode WebMessagePortImpl::PostPortMessage(std::shared_ptr data) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + + if (portHandle_.empty()) { + WEBVIEWLOGE("can't post message, message port already closed"); + return NWebError::CAN_NOT_POST_MESSAGE; + } + nweb_ptr->PostPortMessage(portHandle_, data); + return NWebError::NO_ERROR; + } + + ErrCode WebMessagePortImpl::SetPortMessageCallback( + std::shared_ptr callback) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + + if (portHandle_.empty()) { + WEBVIEWLOGE("can't register message port callback event, message port already closed"); + return NWebError::CAN_NOT_REGISTER_MESSAGE_EVENT; + } + nweb_ptr->SetPortMessageCallback(portHandle_, callback); + return NWebError::NO_ERROR; + } + + std::string WebMessagePortImpl::GetPortHandle() const + { + return portHandle_; + } + + void NWebMessageCallbackImpl::OnReceiveValue(std::shared_ptr result) + { + WEBVIEWLOGD("message port received msg"); + NWeb::NWebValue::Type type = result->GetType(); + if (type == NWeb::NWebValue::Type::STRING) { + std::string msgStr = result->GetString(); + char* message = MallocCString(msgStr); + RetWebMessage ret = {.messageStr = message, .messageArr = {.head = nullptr, .size = 0}}; + callback_(ret); + free(message); + } else if (type == NWeb::NWebValue::Type::BINARY) { + std::vector msgArr = result->GetBinary(); + uint8_t* result = VectorToCArrUI8(msgArr); + if (result == nullptr) { + return; + } + RetWebMessage ret = {.messageStr = nullptr, .messageArr = CArrUI8{result, msgArr.size()}}; + callback_(ret); + free(result); + } + } + + void NWebWebMessageExtCallbackImpl::OnReceiveValue(std::shared_ptr result) + { + WEBVIEWLOGD("message port received msg"); + WebMessageExtImpl *webMessageExt = OHOS::FFI::FFIData::Create(result); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("new WebMessageExt failed."); + return; + } + callback_(webMessageExt->GetID()); + } + WebviewControllerImpl::WebviewControllerImpl(int32_t nwebId) : nwebId_(nwebId) { if (IsInit()) { @@ -108,6 +198,27 @@ namespace OHOS::Webview { return nweb_ptr->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl); } + int32_t WebviewControllerImpl::PreFetchPage(std::string url) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + std::map httpHeaders; + nweb_ptr->PrefetchPage(url, httpHeaders); + return NWebError::NO_ERROR; + } + + int32_t WebviewControllerImpl::PreFetchPage(std::string url, std::map httpHeaders) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + nweb_ptr->PrefetchPage(url, httpHeaders); + return NWebError::NO_ERROR; + } + void WebviewControllerImpl::Refresh() { auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); @@ -116,6 +227,16 @@ namespace OHOS::Webview { } } + int32_t WebviewControllerImpl::SetAudioMuted(bool mute) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + nweb_ptr->SetAudioMuted(mute); + return NWebError::NO_ERROR; + } + std::string WebviewControllerImpl::GetUserAgent() { auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); @@ -329,6 +450,17 @@ namespace OHOS::Webview { return result; } + int32_t WebviewControllerImpl::RequestFocus() + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + nweb_ptr->OnFocus(); + ErrCode result = NWebError::NO_ERROR; + return result; + } + void WebviewControllerImpl::ClearHistory() { auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); @@ -446,6 +578,9 @@ namespace OHOS::Webview { } ret.code = NWebError::NO_ERROR; ret.data = MallocCString(result); + if (ret.data == nullptr) { + ret.code = NWebError::NEW_OOM; + } cjCallback(ret); }); nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl); @@ -607,4 +742,134 @@ namespace OHOS::Webview { } return; } + + void WebviewControllerImpl::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + WEBVIEWLOGE("WebviewControllerImpl::void SetBackForwardCacheOptions nweb_ptr is null"); + return; + } + nweb_ptr->SetBackForwardCacheOptions(size, timeToLive); + } + + void WebviewControllerImpl::SlideScroll(float vx, float vy) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->SlideScroll(vx, vy); + } + return; + } + + void WebviewControllerImpl::PutNetworkAvailable(bool enable) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->PutNetworkAvailable(enable); + } + return; + } + + void WebviewControllerImpl::ClearClientAuthenticationCache() + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->ClearClientAuthenticationCache(); + } + return; + } + + void WebviewControllerImpl::ClearSslCache() + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->ClearSslCache(); + } + return; + } + + void WebviewControllerImpl::SearchNext(bool forward) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->FindNext(forward); + } + return; + } + + void WebviewControllerImpl::ClearMatches() + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->ClearMatches(); + } + return; + } + + void WebviewControllerImpl::SearchAllAsync(std::string str) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + return nweb_ptr->FindAllAsync(str); + } + return; + } + + ErrCode WebviewControllerImpl::DeleteJavaScriptRegister(const std::string& objName, + const std::vector& methodList) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + nweb_ptr->UnregisterArkJSfunction(objName, methodList); + } + if (javaScriptResultCb_) { + bool ret = javaScriptResultCb_->DeleteJavaScriptRegister(objName); + if (!ret) { + return NWebError::CANNOT_DEL_JAVA_SCRIPT_PROXY; + } + } + return NWebError::NO_ERROR; + } + + int32_t WebviewControllerImpl::PostUrl(std::string& url, std::vector& postData) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + return nweb_ptr->PostUrl(url, postData); + } + + std::vector WebviewControllerImpl::CreateWebMessagePorts() + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + std::vector empty; + return empty; + } + return nweb_ptr->CreateWebMessagePorts(); + } + + ErrCode WebviewControllerImpl::PostWebMessage(std::string& message, + std::vector& ports, std::string& targetUrl) + { + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return NWebError::INIT_ERROR; + } + + nweb_ptr->PostWebMessage(message, ports, targetUrl); + return NWebError::NO_ERROR; + } + + void WebviewControllerImpl::OnCreateNativeMediaPlayer(std::function callback){ + auto nweb_ptr = NWeb::NWebHelper::Instance().GetNWeb(nwebId_); + if(!nweb_ptr){ + return; + } + + auto callbackImpl = std::make_shared(nwebId_, callback); + nweb_ptr->OnCreateNativeMediaPlayer(callbackImpl); + } } diff --git a/interfaces/kits/cj/src/webview_ffi.cpp b/interfaces/kits/cj/src/webview_ffi.cpp index 62028c2aade09bdae76724873a3a861a364e1a4f..30575b035830be383348533840dd2c6a966c1131 100644 --- a/interfaces/kits/cj/src/webview_ffi.cpp +++ b/interfaces/kits/cj/src/webview_ffi.cpp @@ -14,17 +14,29 @@ */ #include "webview_ffi.h" + +#include + #include "webview_controller_impl.h" +#include "web_download_item_impl.h" +#include "web_download_delegate_impl.h" +#include "web_download_manager_impl.h" +#include "webview_utils.h" #include "nweb_helper.h" #include "nweb_init_params.h" #include "web_errors.h" +#include "web_download.pb.h" #include "application_context.h" #include "webview_log.h" #include "parameters.h" #include "web_cookie_manager.h" +#include "web_data_base.h" #include "pixel_map.h" #include "cj_lambda.h" #include "pixel_map_impl.h" +#include "geolocation_permission.h" +#include +#include "native_media_player_impl.h" using namespace OHOS::FFI; using namespace OHOS::NWeb; @@ -32,6 +44,11 @@ using namespace OHOS::NWeb; namespace OHOS { namespace Webview { +constexpr uint32_t SOCKET_MAXIMUM = 6; +constexpr uint32_t URL_MAXIMUM = 2048; +constexpr int INTEGER_TWO = 2; +constexpr char URL_REGEXPR[] = "^http(s)?:\\/\\/.+"; + extern "C" { int64_t FfiOHOSWebviewCtlConstructor() { @@ -101,7 +118,58 @@ extern "C" { } std::string webSrc = url; - int32_t ret = nativeWebviewCtl->LoadUrl(webSrc); + return nativeWebviewCtl->LoadUrl(webSrc); + } + + int32_t FfiOHOSWebviewCtlLoadUrlWithHeaders(int64_t id, char *url, ArrWebHeader headers) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + + std::map httpHeaders; + uint32_t arrayLength = static_cast(headers.size); + for (uint32_t i = 0; i < arrayLength; ++i) { + std::string key = headers.head[i].headerKey; + std::string value = headers.head[i].headerValue; + httpHeaders[key] = value; + } + + return nativeWebviewCtl->LoadUrl(url, httpHeaders); + } + + int32_t FfiOHOSWebviewCtlLoadData(int64_t id, LoadDatas loadDatas) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + std::string data = loadDatas.cData; + std::string mimeType = loadDatas.cMimeType; + std::string encoding = loadDatas.cEncoding; + std::string baseUrl = loadDatas.cBaseUrl; + std::string historyUrl = loadDatas.cHistoryUrl; + return nativeWebviewCtl->LoadData(data, mimeType, encoding, baseUrl, historyUrl); + } + + int32_t FfiOHOSWebviewCtlPreFetchPage(int64_t id, char *url) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + std::string webSrc = url; + if (webSrc.size() > URL_MAXIMUM) { + WEBVIEWLOGE("The URL exceeds the maximum length of %{public}d", URL_MAXIMUM); + return NWebError::PARAM_CHECK_ERROR; + } + + if (!regex_match(webSrc, std::regex(URL_REGEXPR, std::regex_constants::icase))) { + WEBVIEWLOGE("ParsePrepareUrl error"); + return NWebError::PARAM_CHECK_ERROR; + } + int32_t ret = nativeWebviewCtl->PreFetchPage(webSrc); if (ret != NWebError::NO_ERROR) { if (ret == NWebError::NWEB_ERROR) { return ret; @@ -110,13 +178,22 @@ extern "C" { return ret; } - int32_t FfiOHOSWebviewCtlLoadUrlWithHeaders(int64_t id, char *url, ArrWebHeader headers) + int32_t FfiOHOSWebviewCtlPreFetchPageWithHeaders(int64_t id, char *url, ArrWebHeader headers) { auto nativeWebviewCtl = FFIData::GetData(id); if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { return NWebError::INIT_ERROR; } + std::string webSrc = url; + if (webSrc.size() > URL_MAXIMUM) { + WEBVIEWLOGE("The URL exceeds the maximum length of %{public}d", URL_MAXIMUM); + return NWebError::PARAM_CHECK_ERROR; + } + if (!regex_match(webSrc, std::regex(URL_REGEXPR, std::regex_constants::icase))) { + WEBVIEWLOGE("ParsePrepareUrl error"); + return NWebError::PARAM_CHECK_ERROR; + } std::map httpHeaders; uint32_t arrayLength = static_cast(headers.size); for (uint32_t i = 0; i < arrayLength; ++i) { @@ -125,34 +202,30 @@ extern "C" { httpHeaders[key] = value; } - int32_t ret = nativeWebviewCtl->LoadUrl(url, httpHeaders); + int32_t ret = nativeWebviewCtl->PreFetchPage(webSrc, httpHeaders); if (ret != NWebError::NO_ERROR) { if (ret == NWebError::NWEB_ERROR) { - WEBVIEWLOGE("LoadUrl failed."); + WEBVIEWLOGE("preFetchPage failed."); return ret; } } return ret; } - int32_t FfiOHOSWebviewCtlLoadData(int64_t id, LoadDatas loadDatas) + int32_t FfiOHOSWebviewCtlSetAudioMuted(int64_t id, bool mute) { auto nativeWebviewCtl = FFIData::GetData(id); if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { return NWebError::INIT_ERROR; } - std::string data = loadDatas.cData; - std::string mimeType = loadDatas.cMimeType; - std::string encoding = loadDatas.cEncoding; - std::string baseUrl = loadDatas.cBaseUrl; - std::string historyUrl = loadDatas.cHistoryUrl; - ErrCode ret = nativeWebviewCtl->LoadData(data, mimeType, encoding, baseUrl, historyUrl); + int32_t ret = nativeWebviewCtl->SetAudioMuted(mute); if (ret != NWebError::NO_ERROR) { if (ret == NWebError::NWEB_ERROR) { - WEBVIEWLOGE("LoadData failed."); + WEBVIEWLOGE("SetAudioMuted failed, error code: %{public}d", ret); return ret; } } + WEBVIEWLOGI("SetAudioMuted: %{public}s", (mute ? "true" : "false")); return ret; } @@ -173,12 +246,24 @@ extern "C" { *errCode = NWebError::INIT_ERROR; return nullptr; } - std::string userAgent = ""; - userAgent = nativeWebviewCtl->GetUserAgent(); + std::string userAgent = nativeWebviewCtl->GetUserAgent(); *errCode = NWebError::NO_ERROR; return MallocCString(userAgent); } + int32_t FfiOHOSWebviewCtlGetWebId(int64_t id, int32_t *errCode) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + int32_t webId = -1; + webId = nativeWebviewCtl->GetWebId(); + *errCode = NWebError::NO_ERROR; + return webId; + } + bool FfiOHOSWebviewCtlAccessForward(int64_t id, int32_t *errCode) { auto nativeWebviewCtl = FFIData::GetData(id); @@ -326,8 +411,7 @@ extern "C" { { std::string curl = url; std::string cvalue = value; - int32_t errCode = OHOS::NWeb::WebCookieManager::CjSetCookie(curl, cvalue, incognitoMode); - return errCode; + return OHOS::NWeb::WebCookieManager::CjSetCookie(curl, cvalue, incognitoMode); } void FfiOHOSCookieMgrPutAcceptCookieEnabled(bool accept) @@ -449,7 +533,7 @@ extern "C" { int32_t ret = nativeWebviewCtl->Zoom(factor); return ret; } - + int32_t FfiOHOSWebviewCtlZoomIn(int64_t id) { auto nativeWebviewCtl = FFIData::GetData(id); @@ -470,6 +554,16 @@ extern "C" { return ret; } + int32_t FfiOHOSWebviewCtlRequestFocus(int64_t id) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + int32_t ret = nativeWebviewCtl->RequestFocus(); + return ret; + } + int32_t FfiOHOSWebviewCtlClearHistory(int64_t id) { auto nativeWebviewCtl = FFIData::GetData(id); @@ -523,7 +617,7 @@ extern "C" { *errCode = NWebError::NO_ERROR; return type; } - + RetDataCString FfiOHOSWebviewCtlGetHitTestValue(int64_t id, int32_t *errCode) { RetDataCString ret = { .code = NWeb::HitTestResult::UNKNOWN_TYPE, .data = nullptr }; @@ -643,6 +737,141 @@ extern "C" { return NWebError::NO_ERROR; } + int32_t FfiOHOSWebviewCtlPostUrl(int64_t id, char *url, CArrUI8 buffer) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + std::string sUrl = url; + std::vector postData(buffer.head, buffer.head + buffer.size); + return nativeWebviewCtl->PostUrl(sUrl, postData); + } + + int32_t FfiOHOSWebviewCtlSetDownloadDelegate(int64_t id, int64_t delegateId) + { + NWebHelper::Instance().LoadNWebSDK(); + auto delegate = FFIData::GetData(delegateId); + if (!delegate) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return NWebError::INIT_ERROR; + } + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + int32_t nwebId = nativeWebviewCtl->GetWebId(); + WebDownloadManagerImpl::AddDownloadDelegateForWeb(nwebId, delegate); + return NWebError::NO_ERROR; + } + + bool ParsePrepareUrl(std::string& url) + { + if (url.size() > URL_MAXIMUM) { + WEBVIEWLOGE("The URL exceeds the maximum length of %{public}d", URL_MAXIMUM); + return false; + } + if (!regex_match(url, std::regex(URL_REGEXPR, std::regex_constants::icase))) { + WEBVIEWLOGE("ParsePrepareUrl error"); + return false; + } + return true; + } + + int32_t FfiOHOSWebviewCtlStartDownload(int64_t id, char *url) + { + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + std::string webSrc = url; + if (!ParsePrepareUrl(webSrc)) { + return NWebError::INVALID_URL; + } + int32_t nwebId = nativeWebviewCtl->GetWebId(); + NWebHelper::Instance().LoadNWebSDK(); + WebDownloader_StartDownload(nwebId, webSrc.c_str()); + return NWebError::NO_ERROR; + } + + CArrI64 FfiOHOSWebviewCtlCreateWebMessagePorts(int64_t id, bool isExtentionType, int32_t *errCode) + { + CArrI64 messagePorts = {.head = nullptr, .size = 0}; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + *errCode = NWebError::INIT_ERROR; + return messagePorts; + } + + int32_t nwebId = nativeWebviewCtl->GetWebId(); + std::vector ports = nativeWebviewCtl->CreateWebMessagePorts(); + if (ports.size() != INTEGER_TWO) { + WEBVIEWLOGE("create web message port failed"); + *errCode = NWebError::CAN_NOT_POST_MESSAGE; + return messagePorts; + } + auto arr = static_cast(malloc(sizeof(int64_t) * INTEGER_TWO)); + if (!arr) { + WEBVIEWLOGE("FfiOHOSWebviewCtlCreateWebMessagePorts failed to malloc arr."); + *errCode = NWebError::NEW_OOM; + return messagePorts; + } + for (uint32_t i = 0; i < INTEGER_TWO; i++) { + auto nativeWebMessagePort = FFIData::Create(nwebId, ports[i], isExtentionType); + if (nativeWebMessagePort == nullptr) { + *errCode = NWebError::CAN_NOT_POST_MESSAGE; + WEBVIEWLOGE("new nativeWebMessagePort failed"); + free(arr); + return messagePorts; + } + arr[i] = nativeWebMessagePort->GetID(); + } + *errCode = NWebError::NO_ERROR; + messagePorts.head = arr; + messagePorts.size = INTEGER_TWO; + return messagePorts; + } + + int32_t GetSendPorts(CArrI64 ports, std::vector& sendPorts) + { + uint32_t arrayLen = ports.size; + if (arrayLen == 0) { + return NWebError::PARAM_CHECK_ERROR; + } + int64_t* portsId = ports.head; + if (!portsId) { + return NWebError::PARAM_CHECK_ERROR; + } + for (uint32_t i = 0; i < arrayLen; i++) { + WebMessagePortImpl *msgPort = FFIData::GetData(portsId[i]); + if ((!msgPort)) { + return NWebError::PARAM_CHECK_ERROR; + } + std::string portHandle = msgPort->GetPortHandle(); + sendPorts.emplace_back(portHandle); + } + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSWebviewCtlPostMessage(int64_t id, char* name, CArrI64 ports, char* uri) + { + WEBVIEWLOGD("post message port"); + std::string portName = std::string(name); + std::vector sendPorts; + int32_t ret = GetSendPorts(ports, sendPorts); + if (ret != NWebError::NO_ERROR) { + WEBVIEWLOGE("post port to html failed, getSendPorts fail"); + return ret; + } + std::string urlStr = std::string(uri); + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + return NWebError::INIT_ERROR; + } + nativeWebviewCtl->PostWebMessage(portName, sendPorts, urlStr); + return NWebError::NO_ERROR; + } + // BackForwardList int32_t FfiOHOSBackForwardListCurrentIndex(int64_t id, int32_t *errCode) { @@ -734,10 +963,51 @@ extern "C" { uint64_t bufferSize = stride * static_cast(height); pixelMap->WritePixels(static_cast(data), bufferSize); auto nativeImage = FFIData::Create(move(pixelMap)); + if (nativeImage == nullptr) { + return -1; + } WEBVIEWLOGI("[PixelMap] create PixelMap success"); return nativeImage->GetID(); } + int64_t FfiOHOSWebviewCtlGetFavicon(int64_t id, int32_t *errCode) + { + int64_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + *errCode = NWebError::INIT_ERROR; + return ret; + } + std::shared_ptr list = nativeWebviewCtl->GetHistoryList(); + if (!list) { + *errCode = NWebError::INIT_ERROR; + return ret; + } + auto nativeWebHistoryListImpl = FFIData::Create(list); + if (nativeWebHistoryListImpl == nullptr) { + *errCode = NWebError::INIT_ERROR; + WEBVIEWLOGE("new WebHistoryListImpl failed"); + return ret; + } + int32_t index = nativeWebHistoryListImpl->GetCurrentIndex(); + if (index >= nativeWebHistoryListImpl->GetListSize() || index < 0) { + *errCode = NWebError::PARAM_CHECK_ERROR; + return ret; + } + std::shared_ptr item = nativeWebHistoryListImpl->GetItem(index); + if (!item) { + *errCode = NWebError::NWEB_ERROR; + return ret; + } + ret = GetFavicon(item); + if (!ret) { + *errCode = NWebError::NWEB_ERROR; + return ret; + } + *errCode = NWebError::NO_ERROR; + return ret; + } + CHistoryItem FfiOHOSGetItemAtIndex(int64_t id, int32_t index, int32_t *errCode) { CHistoryItem ret = {.icon = -1, .historyUrl = nullptr, .historyRawUrl = nullptr, .title = nullptr}; @@ -762,6 +1032,1265 @@ extern "C" { *errCode = NWebError::NO_ERROR; return ret; } + + int32_t FfiOHOSWebviewCtlEnableWholeWebPageDrawing(){ + NWebHelper::Instance().EnableWholeWebPageDrawing(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSWebviewCtlClearPrefetchedResource(CArrString cacheKeyList){ + std::vector CcacheKeyList; + for (int64_t i = 0; i < cacheKeyList.size; i++) { + CcacheKeyList.push_back(std::string(cacheKeyList.head[i])); + } + NWebHelper::Instance().ClearPrefetchedResource(CcacheKeyList); + return NWebError::NO_ERROR; + } + + // NativeMediaPlayerHandler + int64_t FfiOHOSNmphConstuctor() + { + auto Nmph=FFIData::Create(); + if (Nmph == nullptr) { + return -1; + } + return Nmph->GetID(); + } + + int32_t FfiOHOSNmphhandleVideoSizeChanged(int64_t id,double width,double height) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleVideoSizeChanged(width,height); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleError(int64_t id,int32_t error,const char* errorMessage) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleError(static_cast(error),errorMessage); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleSeekFinished(int64_t id) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleSeekFinished(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleSeeking(int64_t id) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleSeeking(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleFullscreenChanged(int64_t id,bool fullscreen) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleFullScreenChanged(fullscreen); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleReadyStateChanged(int64_t id,int32_t state) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleReadyStateChanged(static_cast(state)); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphNetworkStateChanged(int64_t id,int32_t state) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleNetworkStateChanged(static_cast(state)); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleEnded(int64_t id) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleEnded(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleBufferedEndTimeChanged(int64_t id,double bufferedEndTime) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleBufferedEndTimeChanged(bufferedEndTime); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOHNmphhandleTimeUpdate(int64_t id,double currentPlayTime) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleTimeUpdate(currentPlayTime); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleDurationChanged(int64_t id,double duration) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleDurationChanged(duration); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandlePlaybackRateChanged(int64_t id,double playbackRate) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandlePlaybackRateChanged(playbackRate); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleMutedChanged(int64_t id,bool muted) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleMutedChanged(muted); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNmphhandleVolumeChanged(int64_t id,double volume) + { + auto Nmph=FFIData::GetData(id); + if (Nmph == nullptr) { + return NWebError::INIT_ERROR; + } + Nmph->HandleVolumeChanged(volume); + return NWebError::NO_ERROR; + } + + + int32_t FFfiOHOSNmphhandleStatusChanged(int64_t id, int32_t status){ + if(status < static_cast(NWeb::PlaybackStatus::PAUSED) + || status > static_cast(NWeb::PlaybackStatus::PLAYING)) { + return NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + } + + auto nativeMediaPlayerHandlerImpl = FFIData::GetData(id); + if(nativeMediaPlayerHandlerImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nativeMediaPlayerHandlerImpl->HandleStatusChanged(static_cast(status)); + return NWebError::NO_ERROR; + } + + // NativeMediaPlayerBridge + int32_t FfiOHOSNativeMediaPlayerBridgeExitFullscreen(int64_t id){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->ExitFullScreen(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeEnterFullscreen(int64_t id){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->EnterFullScreen(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeRelease(int64_t id){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->Release(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeSetPlaybackRate(int64_t id, double playbackRate){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->SetPlaybackRate(playbackRate); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeSetMuted(int64_t id, bool muted){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->SetMuted(muted); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeSetVolume(int64_t id, double volume){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->SetVolume(volume); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeSeek(int64_t id, double targetTime){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->Seek(targetTime); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgePause(int64_t id){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->Pause(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgePlay(int64_t id){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->Play(); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSNativeMediaPlayerBridgeUpdateRect(int64_t id, double x, double y, double width, double height){ + auto nwebNativeMediaPlayerBridgeImpl = FFIData::GetData(id); + if(nwebNativeMediaPlayerBridgeImpl == nullptr){ + return NWebError::INIT_ERROR; + } + nwebNativeMediaPlayerBridgeImpl->UpdateRect(x, y, width, height); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSWebviewCtlPrepareForPageLoad(char *url, bool preconnectable, int32_t numSockets) + { + int32_t ret = -1; + std::string webSrc = url; + if (webSrc.size() > URL_MAXIMUM) { + WEBVIEWLOGE("The URL exceeds the maximum length of %{public}d", URL_MAXIMUM); + return NWebError::PARAM_CHECK_ERROR; + } + + if (!regex_match(webSrc, std::regex(URL_REGEXPR, std::regex_constants::icase))) { + WEBVIEWLOGE("ParsePrepareUrl error"); + return NWebError::PARAM_CHECK_ERROR; + } + + if (numSockets <= 0 || static_cast(numSockets) > SOCKET_MAXIMUM) { + return NWebError::PARAM_CHECK_ERROR; + } + NWeb::NWebHelper::Instance().PrepareForPageLoad(webSrc, preconnectable, numSockets); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlSetConnectionTimeout(int32_t timeout) + { + int32_t ret = -1; + if (timeout <= 0) { + return NWebError::PARAM_CHECK_ERROR; + } + NWeb::NWebHelper::Instance().SetConnectionTimeout(timeout); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlSlideScroll(int64_t id, float vx, float vy) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + nativeWebviewCtl->SlideScroll(vx, vy); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlSetNetworkAvailable(int64_t id, bool enable) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + nativeWebviewCtl->PutNetworkAvailable(enable); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlClearClientAuthenticationCache(int64_t id) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + nativeWebviewCtl->ClearClientAuthenticationCache(); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlClearSslCache(int64_t id) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + nativeWebviewCtl->ClearSslCache(); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlSearchNext(int64_t id, bool forward) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + nativeWebviewCtl->SearchNext(forward); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlClearMatches(int64_t id) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + nativeWebviewCtl->ClearMatches(); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlSearchAllAsync(int64_t id, char * searchString) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + std::string str = searchString; + nativeWebviewCtl->SearchAllAsync(str); + ret = NWebError::NO_ERROR; + return ret; + } + + int32_t FfiOHOSWebviewCtlDeleteJavaScriptRegister(int64_t id, char *name) + { + int32_t ret = -1; + auto nativeWebviewCtl = FFIData::GetData(id); + if (nativeWebviewCtl == nullptr || !nativeWebviewCtl->IsInit()) { + ret = NWebError::INIT_ERROR; + return ret; + } + std::string str = name; + ret = nativeWebviewCtl->DeleteJavaScriptRegister(str, {}); + return ret; + } + + // web data base; + RetDataCArrString FfiOHOSDBGetHttpAuthCredentials(const char *host, const char *realm) + { + std::string host_s = std::string(host); + std::string realm_s = std::string(realm); + + CArrString result = OHOS::NWeb::WebDataBase::CJGetHttpAuthCredentials(host_s, realm_s); + RetDataCArrString ret; + + if (result.size == -1) { + ret.code = NWebError::HTTP_AUTH_MALLOC_FAILED; + } else { + ret.code = NWebError::NO_ERROR; + } + + ret.data = result; + return ret; + } + + void FfiOHOSDBSaveHttpAuthCredentials(const char *host, const char *realm, + const char *username, const char *password) + { + std::string host_s = std::string(host); + std::string realm_s = std::string(realm); + std::string username_s = std::string(username); + std::string password_s = std::string(password); + + OHOS::NWeb::WebDataBase::CJSaveHttpAuthCredentials(host_s, realm_s, username_s, password_s); + } + + bool FfiOHOSDBExistHttpAuthCredentials() + { + return OHOS::NWeb::WebDataBase::CJExistHttpAuthCredentials(); + } + + void FfiOHOSDBDeleteHttpAuthCredentials() + { + OHOS::NWeb::WebDataBase::CJDeleteHttpAuthCredentials(); + } + + // WebDownloadItemImpl + int64_t FfiOHOSWebDownloadItemImplConstructor() + { + auto nativeWebDownloadItemImpl = FFIData::Create(); + if (nativeWebDownloadItemImpl == nullptr) { + WEBVIEWLOGE("new web download item failed"); + return -1; + } + return nativeWebDownloadItemImpl->GetID(); + } + + RetDataCString FfiOHOSWebDownloadItemImplGetGuid(int64_t id) + { + RetDataCString ret = { .code = NWebError::INIT_ERROR, .data = nullptr }; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return ret; + } + std::string guid = nativeWebDownloadItemImpl->guid; + ret.code = NWebError::NO_ERROR; + ret.data = MallocCString(guid); + return ret; + } + + int64_t FfiOHOSWebDownloadItemImplGetCurrentSpeed(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + *errCode = NWebError::NO_ERROR; + return static_cast(nativeWebDownloadItemImpl->currentSpeed); + } + + int64_t FfiOHOSWebDownloadItemImplGetPercentComplete(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + *errCode = NWebError::NO_ERROR; + return static_cast(nativeWebDownloadItemImpl->percentComplete); + } + + int64_t FfiOHOSWebDownloadItemImplGetTotalBytes(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + *errCode = NWebError::NO_ERROR; + return static_cast(nativeWebDownloadItemImpl->totalBytes); + } + + int64_t FfiOHOSWebDownloadItemImplGetReceivedBytes(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + *errCode = NWebError::NO_ERROR; + return static_cast(nativeWebDownloadItemImpl->receivedBytes); + } + + int32_t FfiOHOSWebDownloadItemImplGetState(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + *errCode = NWebError::NO_ERROR; + return static_cast(nativeWebDownloadItemImpl->state); + } + + int32_t FfiOHOSWebDownloadItemImplGetLastErrorCode(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + *errCode = NWebError::NO_ERROR; + return static_cast(nativeWebDownloadItemImpl->lastErrorCode); + } + + RetDataCString FfiOHOSWebDownloadItemImplGetMethod(int64_t id) + { + RetDataCString ret = { .code = NWebError::INIT_ERROR, .data = nullptr }; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return ret; + } + std::string methodValue = nativeWebDownloadItemImpl->method; + ret.code = NWebError::NO_ERROR; + ret.data = MallocCString(methodValue); + return ret; + } + + RetDataCString FfiOHOSWebDownloadItemImplGetMimeType(int64_t id) + { + RetDataCString ret = { .code = NWebError::INIT_ERROR, .data = nullptr }; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return ret; + } + std::string mimeTypeValue = nativeWebDownloadItemImpl->mimeType; + ret.code = NWebError::NO_ERROR; + ret.data = MallocCString(mimeTypeValue); + return ret; + } + + RetDataCString FfiOHOSWebDownloadItemImplGetUrl(int64_t id) + { + RetDataCString ret = { .code = NWebError::INIT_ERROR, .data = nullptr }; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return ret; + } + std::string urlValue = nativeWebDownloadItemImpl->url; + ret.code = NWebError::NO_ERROR; + ret.data = MallocCString(urlValue); + return ret; + } + + RetDataCString FfiOHOSWebDownloadItemImplGetSuggestedFileName(int64_t id) + { + RetDataCString ret = { .code = NWebError::INIT_ERROR, .data = nullptr }; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return ret; + } + std::string fileNameValue = nativeWebDownloadItemImpl->suggestedFileName; + ret.code = NWebError::NO_ERROR; + ret.data = MallocCString(fileNameValue); + return ret; + } + + RetDataCString FfiOHOSWebDownloadItemImplGetFullPath(int64_t id) + { + RetDataCString ret = { .code = NWebError::INIT_ERROR, .data = nullptr }; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return ret; + } + std::string fullPath = nativeWebDownloadItemImpl->fullPath; + ret.code = NWebError::NO_ERROR; + ret.data = MallocCString(fullPath); + return ret; + } + + int32_t FfiOHOSWebDownloadItemImplStart(int64_t id, char *downloadPath) + { + std::string sDownloadPath = downloadPath; + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return NWebError::INIT_ERROR; + } + nativeWebDownloadItemImpl->downloadPath = sDownloadPath; + WebDownload_Continue(nativeWebDownloadItemImpl->before_download_callback, + nativeWebDownloadItemImpl->downloadPath.c_str()); + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSWebDownloadItemImplCancel(int64_t id) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return NWebError::INIT_ERROR; + } + if (nativeWebDownloadItemImpl->download_item_callback) { + WebDownload_Cancel(nativeWebDownloadItemImpl->download_item_callback); + } else if (nativeWebDownloadItemImpl->before_download_callback) { + WebDownload_CancelBeforeDownload(nativeWebDownloadItemImpl->before_download_callback); + } else { + WEBVIEWLOGE("[DOWNLOAD] WebDownloadItem::Cancel failed for callback nullptr"); + } + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSWebDownloadItemImplPause(int64_t id) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return NWebError::INIT_ERROR; + } + NWebDownloadItemState state = WebDownload_GetItemState( + nativeWebDownloadItemImpl->nwebId, nativeWebDownloadItemImpl->webDownloadId); + if (state != NWebDownloadItemState::IN_PROGRESS && + state != NWebDownloadItemState::PENDING) { + return NWebError::DOWNLOAD_NOT_START; + } + if (nativeWebDownloadItemImpl->download_item_callback) { + WebDownload_Pause(nativeWebDownloadItemImpl->download_item_callback); + } else if (nativeWebDownloadItemImpl->before_download_callback) { + WebDownload_PauseBeforeDownload(nativeWebDownloadItemImpl->before_download_callback); + } else { + WEBVIEWLOGE("[DOWNLOAD] WebDownloadItem::Pause failed for callback nullptr"); + } + return NWebError::NO_ERROR; + } + + int32_t FfiOHOSWebDownloadItemImplResume(int64_t id) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + return NWebError::INIT_ERROR; + } + NWebDownloadItemState state = WebDownload_GetItemState( + nativeWebDownloadItemImpl->nwebId, nativeWebDownloadItemImpl->webDownloadId); + if (state != NWebDownloadItemState::PAUSED) { + return NWebError::DOWNLOAD_NOT_PAUSED; + } + + if (nativeWebDownloadItemImpl->download_item_callback) { + WebDownload_Resume(nativeWebDownloadItemImpl->download_item_callback); + } else if (nativeWebDownloadItemImpl->before_download_callback) { + WebDownload_ResumeBeforeDownload(nativeWebDownloadItemImpl->before_download_callback); + } else { + WEBVIEWLOGE("[DOWNLOAD] WebDownloadItem::Resume failed for callback nullptr"); + } + return NWebError::NO_ERROR; + } + + CArrUI8 FfiOHOSWebDownloadItemImplSerialize(int64_t id, int32_t *errCode) + { + auto nativeWebDownloadItemImpl = FFIData::GetData(id); + if (!nativeWebDownloadItemImpl) { + *errCode = NWebError::INIT_ERROR; + return CArrUI8{nullptr, 0}; + } + + browser_service::WebDownload webDownloadPb; + webDownloadPb.set_web_download_id(nativeWebDownloadItemImpl->webDownloadId); + webDownloadPb.set_current_speed(nativeWebDownloadItemImpl->currentSpeed); + webDownloadPb.set_percent_complete(nativeWebDownloadItemImpl->percentComplete); + webDownloadPb.set_total_bytes(nativeWebDownloadItemImpl->totalBytes); + webDownloadPb.set_received_bytes(nativeWebDownloadItemImpl->receivedBytes); + webDownloadPb.set_guid(nativeWebDownloadItemImpl->guid); + webDownloadPb.set_full_path(nativeWebDownloadItemImpl->fullPath); + webDownloadPb.set_url(nativeWebDownloadItemImpl->url); + webDownloadPb.set_etag(nativeWebDownloadItemImpl->etag); + webDownloadPb.set_original_url(nativeWebDownloadItemImpl->originalUrl); + webDownloadPb.set_suggested_file_name(nativeWebDownloadItemImpl->suggestedFileName); + webDownloadPb.set_content_disposition(nativeWebDownloadItemImpl->contentDisposition); + webDownloadPb.set_mime_type(nativeWebDownloadItemImpl->mimeType); + webDownloadPb.set_last_modified(nativeWebDownloadItemImpl->lastModified); + webDownloadPb.set_state( + static_cast(nativeWebDownloadItemImpl->state)); + webDownloadPb.set_method(nativeWebDownloadItemImpl->method); + webDownloadPb.set_last_error_code(nativeWebDownloadItemImpl->lastErrorCode); + webDownloadPb.set_received_slices(nativeWebDownloadItemImpl->receivedSlices); + webDownloadPb.set_download_path(nativeWebDownloadItemImpl->downloadPath); + + std::string webDownloadValue; + webDownloadPb.SerializeToString(&webDownloadValue); + uint8_t* result = MallocUInt8(webDownloadValue); + if (result == nullptr) { + WEBVIEWLOGE("[DOWNLOAD] malloc failed"); + *errCode = NWebError::NEW_OOM; + return CArrUI8{nullptr, 0}; + } + *errCode = NWebError::NO_ERROR; + return CArrUI8{result, webDownloadValue.length()}; + } + + int64_t FfiOHOSWebDownloadItemImplDeserialize(CArrUI8 serializedData, int32_t *errCode) + { + char *buffer = (char *)serializedData.head; + browser_service::WebDownload webDownloadPb; + bool result = webDownloadPb.ParseFromArray(buffer, serializedData.size); + if (!result) { + *errCode = NWebError::INIT_ERROR; + return -1; + } + WebDownloadItemImpl *webDownloadItem = FFIData::Create(); + if (webDownloadItem == nullptr) { + WEBVIEWLOGE("new web download item failed"); + *errCode = NWebError::INIT_ERROR; + return -1; + } + webDownloadItem->webDownloadId = webDownloadPb.web_download_id(); + webDownloadItem->currentSpeed = webDownloadPb.current_speed(); + webDownloadItem->percentComplete = webDownloadPb.percent_complete(); + webDownloadItem->totalBytes = webDownloadPb.total_bytes(); + webDownloadItem->receivedBytes = webDownloadPb.received_bytes(); + webDownloadItem->guid = webDownloadPb.guid(); + webDownloadItem->fullPath = webDownloadPb.full_path(); + webDownloadItem->url = webDownloadPb.url(); + webDownloadItem->etag = webDownloadPb.etag(); + webDownloadItem->originalUrl = webDownloadPb.original_url(); + webDownloadItem->suggestedFileName = webDownloadPb.suggested_file_name(); + webDownloadItem->contentDisposition = webDownloadPb.content_disposition(); + webDownloadItem->mimeType = webDownloadPb.mime_type(); + webDownloadItem->lastModified = webDownloadPb.last_modified(); + webDownloadItem->state = static_cast(webDownloadPb.state()); + webDownloadItem->method = webDownloadPb.method(); + webDownloadItem->lastErrorCode = webDownloadPb.last_error_code(); + webDownloadItem->receivedSlices = webDownloadPb.received_slices(); + webDownloadItem->downloadPath = webDownloadPb.download_path(); + *errCode = NWebError::NO_ERROR; + return webDownloadItem->GetID(); + } + + // WebDownloadDelegateImpl + int64_t FfiOHOSWebDownloadDelegateImplConstructor() + { + auto nativeWebDownloadDelegateImpl = FFIData::Create(); + if (nativeWebDownloadDelegateImpl == nullptr) { + WEBVIEWLOGE("new web download delegate failed"); + return -1; + } + return nativeWebDownloadDelegateImpl->GetID(); + } + + void FfiOHOSWebDownloadDelegateImplOnBeforeDownload(int64_t id, void (*callback)(int64_t)) + { + auto nativeWebDownloadDelegateImpl = FFIData::GetData(id); + if (!nativeWebDownloadDelegateImpl) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + nativeWebDownloadDelegateImpl->PutDownloadBeforeStart(CJLambda::Create(callback)); + } + + void FfiOHOSWebDownloadDelegateImplOnDownloadUpdated(int64_t id, void (*callback)(int64_t)) + { + auto nativeWebDownloadDelegateImpl = FFIData::GetData(id); + if (!nativeWebDownloadDelegateImpl) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + nativeWebDownloadDelegateImpl->PutDownloadDidUpdate(CJLambda::Create(callback)); + } + + void FfiOHOSWebDownloadDelegateImplOnDownloadFinish(int64_t id, void (*callback)(int64_t)) + { + auto nativeWebDownloadDelegateImpl = FFIData::GetData(id); + if (!nativeWebDownloadDelegateImpl) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + nativeWebDownloadDelegateImpl->PutDownloadDidFinish(CJLambda::Create(callback)); + } + + void FfiOHOSWebDownloadDelegateImplOnDownloadFailed(int64_t id, void (*callback)(int64_t)) + { + auto nativeWebDownloadDelegateImpl = FFIData::GetData(id); + if (!nativeWebDownloadDelegateImpl) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + nativeWebDownloadDelegateImpl->PutDownloadDidFail(CJLambda::Create(callback)); + } + + // WebDownloadManagerImpl + void FfiOHOSWebDownloadManagerImplSetDownloadDelegate(int64_t delegateId) + { + auto nativeWebDownloadDelegateImpl = FFIData::GetData(delegateId); + if (!nativeWebDownloadDelegateImpl) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return; + } + WebDownloadManagerImpl::SetDownloadDelegate(nativeWebDownloadDelegateImpl); + } + + int32_t FfiOHOSWebDownloadManagerImplResumeDownload(int64_t itemId) + { + if (!WebDownloadManagerImpl::HasValidDelegate()) { + return NWebError::NO_DOWNLOAD_DELEGATE_SET; + } + auto nativeWebDownloadItemImpl = FFIData::GetData(itemId); + if (!nativeWebDownloadItemImpl) { + WEBVIEWLOGE("[DOWNLOAD] webDownloadDelegate is null"); + return NWebError::INIT_ERROR; + } + WebDownloadManagerImpl::ResumeDownload(nativeWebDownloadItemImpl); + return NWebError::NO_ERROR; + } + + void FfiOHOSWebviewCtlOnCreateNativeMediaPlayer(int64_t id, int64_t (*callback)(int64_t, CMediaInfo)){ + auto webviewControllerImpl = FFIData::GetData(id); + if(!webviewControllerImpl){ + WEBVIEWLOGE("webview controller is null or not init"); + } + webviewControllerImpl->OnCreateNativeMediaPlayer(CJLambda::Create(callback)); + } + + // GeolocationPermissions + void FfiOHOSGeolocationAllowGeolocation(char* origin, bool incognito, int32_t *errCode) + { + std::string originStr = std::string(origin); + GeolocationPermission::CjAllowGeolocation(originStr, incognito, errCode); + } + + void FfiOHOSGeolocationDeleteGeolocation(char* origin, bool incognito, int32_t *errCode) + { + std::string originStr = std::string(origin); + GeolocationPermission::CjDeleteGeolocation(originStr, incognito, errCode); + } + + bool FfiOHOSGeolocationGetAccessibleGeolocation(char* origin, bool incognito, int32_t *errCode) + { + std::string originStr = std::string(origin); + return GeolocationPermission::CjGetAccessibleGeolocation(originStr, incognito, errCode); + } + + CArrString FfiOHOSGeolocationGetStoredGeolocation(bool incognito, int32_t *errCode) + { + std::vector origins = GeolocationPermission::CjGetStoredGeolocation(incognito, errCode); + CArrString arrOrigins = {.head = nullptr, .size = 0}; + if (errCode && *errCode != 0) { + return arrOrigins; + } + arrOrigins.size = (int64_t)origins.size(); + arrOrigins.head = OHOS::Webview::VectorToCArrString(origins); + return arrOrigins; + } + + void FfiOHOSGeolocationDeleteAllGeolocation(bool incognito, int32_t *errCode) + { + return GeolocationPermission::CjDeleteAllGeolocation(incognito, errCode); + } + + // WebMessagePort + void FfiOHOSWebMessagePortPostMessageEvent(int64_t msgPortId, char* stringValue, int32_t *errCode) + { + WEBVIEWLOGD("message port post message"); + auto webMsg = std::make_shared(NWebValue::Type::NONE); + std::string message(stringValue); + webMsg->SetType(NWebValue::Type::STRING); + webMsg->SetString(message); + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("post message failed, ffi unwrap msg port failed"); + *errCode = NWebError::CAN_NOT_POST_MESSAGE; + return; + } + *errCode = msgPort->PostPortMessage(webMsg); + return; + } + + void FfiOHOSWebMessagePortPostMessageEventArr(int64_t msgPortId, CArrUI8 arrBuf, int32_t *errCode) + { + WEBVIEWLOGD("message port post message"); + auto webMsg = std::make_shared(NWebValue::Type::NONE); + std::vector vecData(arrBuf.head, arrBuf.head + arrBuf.size); + webMsg->SetType(NWebValue::Type::BINARY); + webMsg->SetBinary(vecData); + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("post message failed, ffi unwrap msg port failed"); + *errCode = NWebError::CAN_NOT_POST_MESSAGE; + return; + } + *errCode = msgPort->PostPortMessage(webMsg); + return; + } + + void FfiOHOSWebMessagePortPostMessageEventExt(int64_t msgPortId, int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("message PostMessageEventExt start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessagePortPostMessageEventExt error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("post message failed, ffi unwrap msg port failed"); + *errCode = NWebError::CAN_NOT_POST_MESSAGE; + return; + } + if (!msgPort->IsExtentionType()) { + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + *errCode = msgPort->PostPortMessage(webMessageExt->GetData()); + return; + } + + bool FfiOHOSWebMessagePortIsExtentionType(int64_t msgPortId) + { + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("post message failed, ffi unwrap msg port failed"); + return false; + } + return msgPort->IsExtentionType(); + } + + void FfiOHOSWebMessagePortOnMessageEvent(int64_t msgPortId, void (*callback)(RetWebMessage), int32_t *errCode) + { + WEBVIEWLOGD("message port set OnMessageEvent callback"); + std::function onMsgEventFunc = CJLambda::Create(callback); + auto callbackImpl = std::make_shared(onMsgEventFunc); + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("post message failed, ffi unwrap msg port failed"); + *errCode = NWebError::CAN_NOT_REGISTER_MESSAGE_EVENT; + return; + } + *errCode = msgPort->SetPortMessageCallback(callbackImpl); + return; + } + + void FfiOHOSWebMessagePortOnMessageEventExt(int64_t msgPortId, void (*callback)(int64_t), int32_t *errCode) + { + WEBVIEWLOGD("message port set OnMessageEventExt callback"); + std::function onMsgEventFunc = CJLambda::Create(callback); + auto callbackImpl = std::make_shared(onMsgEventFunc); + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("post message failed, ffi unwrap msg port failed"); + *errCode = NWebError::CAN_NOT_REGISTER_MESSAGE_EVENT; + return; + } + *errCode = msgPort->SetPortMessageCallback(callbackImpl); + return; + } + + void FfiOHOSWebMessagePortClose(int64_t msgPortId, int32_t *errCode) + { + WebMessagePortImpl *msgPort = FFIData::GetData(msgPortId); + if (msgPort == nullptr) { + WEBVIEWLOGE("close message failed, ffi unwrap msg port failed"); + return; + } + *errCode = msgPort->ClosePort(); + return; + } + + // WebMessageExt + int64_t FfiOHOSWebMessageExtImplConstructor() + { + auto webMsg = std::make_shared(NWebValue::Type::NONE); + WebMessageExtImpl* nativeWebMessageExtImpl = FFIData::Create(webMsg); + if (nativeWebMessageExtImpl == nullptr) { + WEBVIEWLOGE("new webMessageExt failed"); + return -1; + } + return nativeWebMessageExtImpl->GetID(); + } + + int32_t FfiOHOSWebMessageExtImplGetType(int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplGetType::GetType start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetType::GetType error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return -1; + } + int32_t type = webMessageExt->GetType(); + *errCode = NWebError::NO_ERROR; + return type; + } + + char* FfiOHOSWebMessageExtImplGetString(int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplGetString::GetString start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetString::GetString error"); + *errCode = NWebError::INIT_ERROR; + return nullptr; + } + + if (webMessageExt->GetType() != static_cast(WebMessageType::STRING)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return nullptr; + } + auto data = webMessageExt->GetData(); + if (data == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetString::GetString error"); + *errCode = NWebError::INIT_ERROR; + return nullptr; + } + std::string msgStr = data->GetString(); + *errCode = NWebError::NO_ERROR; + return MallocCString(msgStr); + } + + RetNumber FfiOHOSWebMessageExtImplGetNumber(int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplGetNumber::GetNumber start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + RetNumber ret = { .numberInt = 0, .numberDouble = 0.0 }; + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetNumber::GetNumber error"); + *errCode = NWebError::INIT_ERROR; + return ret; + } + + if (webMessageExt->GetType() != static_cast(WebMessageType::NUMBER)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return ret; + } + auto data = webMessageExt->GetData(); + if (data == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetNumber::GetNumber error"); + *errCode = NWebError::INIT_ERROR; + return ret; + } + if (data->GetType() == NWebValue::Type::INTEGER) { + ret.numberInt = data->GetInt64(); + } else { + ret.numberDouble = data->GetDouble(); + } + return ret; + } + + bool FfiOHOSWebMessageExtImplGetBoolean(int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplGetBoolean::GetBoolean start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetBoolean::GetBoolean error"); + *errCode = NWebError::INIT_ERROR; + return false; + } + + if (webMessageExt->GetType() != static_cast(WebMessageType::BOOLEAN)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return false; + } + auto data = webMessageExt->GetData(); + if (data == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetBoolean::GetBoolean error"); + *errCode = NWebError::INIT_ERROR; + return false; + } + double boolean = data->GetBoolean(); + *errCode = NWebError::NO_ERROR; + return boolean; + } + + CArrUI8 FfiOHOSWebMessageExtImplGetArrayBuffer(int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplGetArrayBuffer::GetArrayBuffer start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetArrayBuffer::GetArrayBuffer error"); + *errCode = NWebError::INIT_ERROR; + return CArrUI8{nullptr, 0}; + } + + if (webMessageExt->GetType() != static_cast(WebMessageType::ARRAYBUFFER)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return CArrUI8{nullptr, 0}; + } + auto data = webMessageExt->GetData(); + if (data == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetArrayBuffer::GetArrayBuffer error"); + *errCode = NWebError::INIT_ERROR; + return CArrUI8{nullptr, 0}; + } + std::vector msgArr = data->GetBinary(); + uint8_t* result = VectorToCArrUI8(msgArr); + if (result == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetArrayBuffer malloc failed"); + *errCode = NWebError::NEW_OOM; + return CArrUI8{nullptr, 0}; + } + *errCode = NWebError::NO_ERROR; + return CArrUI8{result, msgArr.size()}; + } + + CError FfiOHOSWebMessageExtImplGetError(int64_t msgExtId, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplGetError::GetError start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + auto err = CError{.errorName = nullptr, .errorMsg = nullptr}; + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetError::GetError error"); + *errCode = NWebError::INIT_ERROR; + return err; + } + if (webMessageExt->GetType() != static_cast(WebMessageType::ERROR)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return err; + } + auto data = webMessageExt->GetData(); + if (data == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetError::GetError error"); + *errCode = NWebError::INIT_ERROR; + return err; + } + *errCode = NWebError::NO_ERROR; + std::string errorName = data->GetErrName(); + std::string errorMsg = data->GetErrName() + ": " + data->GetErrMsg(); + err.errorName = MallocCString(errorName); + err.errorMsg = MallocCString(errorMsg); + return err; + } + + void FfiOHOSWebMessageExtImplSetType(int64_t msgExtId, int32_t type, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplSetType::SetType"); + if (type <= static_cast(WebMessageType::NOTSUPPORT) || type > static_cast(WebMessageType::ERROR)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return; + } + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetArrayBuffer::GetArrayBuffer error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + webMessageExt->SetType(type); + *errCode = NWebError::NO_ERROR; + return; + } + + void FfiOHOSWebMessageExtImplSetString(int64_t msgExtId, char* message, int32_t *errCode) + { + WEBVIEWLOGD("FfiOHOSWebMessageExtImplSetString::SetString start"); + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplSetString::SetString error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + if (webMessageExt->GetType() != static_cast(WebMessageType::STRING)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return ; + } + std::string value = std::string(message); + webMessageExt->SetString(value); + *errCode = NWebError::NO_ERROR; + return; + } + + void FfiOHOSWebMessageExtImplSetNumber(int64_t msgExtId, double value, int32_t *errCode) + { + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplSetNumber::SetNumber error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + if (webMessageExt->GetType() != static_cast(WebMessageType::NUMBER)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return; + } + webMessageExt->SetNumber(value); + *errCode = NWebError::NO_ERROR; + return; + } + + void FfiOHOSWebMessageExtImplSetBoolean(int64_t msgExtId, bool value, int32_t *errCode) + { + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplSetBoolean::SetBoolean error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + if (webMessageExt->GetType() != static_cast(WebMessageType::BOOLEAN)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return; + } + webMessageExt->SetBoolean(value); + *errCode = NWebError::NO_ERROR; + return; + } + + void FfiOHOSWebMessageExtImplSetArrayBuffer(int64_t msgExtId, CArrUI8 value, int32_t *errCode) + { + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplSetArrayBuffer::SetArrayBuffer error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + if (webMessageExt->GetType() != static_cast(WebMessageType::ARRAYBUFFER)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return; + } + uint8_t *arrBuf = value.head; + size_t byteLength = value.size; + std::vector vecData(arrBuf, arrBuf + byteLength); + webMessageExt->SetArrayBuffer(vecData); + *errCode = NWebError::NO_ERROR; + return; + } + + void FfiOHOSWebMessageExtImplSetError(int64_t msgExtId, OHOS::Webview::CError value, int32_t *errCode) + { + WebMessageExtImpl* webMessageExt = FFIData::GetData(msgExtId); + if (webMessageExt == nullptr) { + WEBVIEWLOGE("FfiOHOSWebMessageExtImplGetError::GetError error"); + *errCode = NWebError::PARAM_CHECK_ERROR; + return; + } + if (webMessageExt->GetType() != static_cast(WebMessageType::ERROR)) { + *errCode = NWebError::TYPE_NOT_MATCH_WITCH_VALUE; + return; + } + std::string nameVal = std::string(value.errorName); + std::string msgVal = std::string(value.errorMsg); + *errCode = NWebError::NO_ERROR; + webMessageExt->SetError(nameVal, msgVal); + return; + } } } -} +} \ No newline at end of file diff --git a/interfaces/kits/cj/src/webview_javascript_execute_callback.cpp b/interfaces/kits/cj/src/webview_javascript_execute_callback.cpp index 6a517d884bd7ecdc57d5609e0d6f70caacc1a7d0..d0a6514ffbdcfb87cd6254135f5baf6c3c00b69b 100644 --- a/interfaces/kits/cj/src/webview_javascript_execute_callback.cpp +++ b/interfaces/kits/cj/src/webview_javascript_execute_callback.cpp @@ -34,6 +34,9 @@ void WebviewJavaScriptExecuteCallback::OnReceiveValue(std::shared_ptrGetString()); + if (ret.data == nullptr) { + ret.code = NWebError::NEW_OOM; + } callbackRef_(ret); } diff --git a/interfaces/kits/cj/src/webview_javascript_result_callback.cpp b/interfaces/kits/cj/src/webview_javascript_result_callback.cpp index f3ca8d1d055b55b44ee248022fcb09794f2cdef3..1954441759b4dbcf8f2da1654182074adf7b8a82 100644 --- a/interfaces/kits/cj/src/webview_javascript_result_callback.cpp +++ b/interfaces/kits/cj/src/webview_javascript_result_callback.cpp @@ -20,7 +20,7 @@ #include "webview_log.h" #include "ohos_adapter_helper.h" -#define MAX_FLOWBUF_DATA_SIZE 52428800 /* 50MB*/ +#define MAX_FLOWBUF_DATA_SIZE 52428800 /* 50MB */ #define MAX_ENTRIES 10 #define HEADER_SIZE (MAX_ENTRIES * 8) /* 10 * (int position + int length) */ #define INDEX_SIZE 2 @@ -205,37 +205,37 @@ std::shared_ptr WebviewJavaScriptResultCallBackImpl::GetJavaScriptRes } char* WebviewJavaScriptResultCallBackImpl::FlowbufStrAtIndex( - void* mem, int flowbuf_index, int* arg_index, int* str_len) + void* mem, int flowbufIndex, int* argIndex, int* strLen) { int* header = static_cast(mem); // Cast the memory block to int* for easier access int offset = 0; - if (arg_index == nullptr) { + if (argIndex == nullptr) { return nullptr; } - if (flowbuf_index >= MAX_ENTRIES) { - *arg_index = -1; + if (flowbufIndex >= MAX_ENTRIES) { + *argIndex = -1; return nullptr; } - int* entry = header + (flowbuf_index * INDEX_SIZE); + int* entry = header + (flowbufIndex * INDEX_SIZE); if (entry == nullptr) { return nullptr; } if (*(entry + 1) == 0) { // Check if length is 0, indicating unused entry - *arg_index = -1; + *argIndex = -1; return nullptr; } int i = 0; - for (i = 0; i < flowbuf_index; i++) { + for (i = 0; i < flowbufIndex; i++) { offset += *(header + (i * INDEX_SIZE) + 1); } - if (str_len == nullptr) { + if (strLen == nullptr) { return nullptr; } - *str_len = *(header + (i * INDEX_SIZE) + 1) - 1; + *strLen = *(header + (i * INDEX_SIZE) + 1) - 1; - *arg_index = *entry; + *argIndex = *entry; char* dataSegment = static_cast(mem) + HEADER_SIZE; char* currentString = dataSegment + offset; @@ -248,35 +248,35 @@ bool WebviewJavaScriptResultCallBackImpl::ConstructArgv(void* ashmem, std::shared_ptr jsObj, int32_t routingId) { - int arg_index = -1; - int curr_index = 0; - int flowbuf_index = 0; - int str_len = 0; - char* flowbuf_str = FlowbufStrAtIndex(ashmem, flowbuf_index, &arg_index, &str_len); - flowbuf_index++; - while (arg_index == curr_index) { - argv.push_back(std::string(flowbuf_str)); - curr_index ++; - flowbuf_str = FlowbufStrAtIndex(ashmem, flowbuf_index, &arg_index, &str_len); - flowbuf_index++; + int argIndex = -1; + int currIndex = 0; + int flowbufIndex = 0; + int strLen = 0; + char* flowbufStr = FlowbufStrAtIndex(ashmem, flowbufIndex, &argIndex, &strLen); + flowbufIndex++; + while (argIndex == currIndex) { + argv.push_back(std::string(flowbufStr)); + currIndex ++; + flowbufStr = FlowbufStrAtIndex(ashmem, flowbufIndex, &argIndex, &strLen); + flowbufIndex++; } for (std::shared_ptr input : args) { - while (arg_index == curr_index) { - argv.push_back(std::string(flowbuf_str)); - curr_index ++; - flowbuf_str = FlowbufStrAtIndex(ashmem, flowbuf_index, &arg_index, &str_len); - flowbuf_index++; + while (argIndex == currIndex) { + argv.push_back(std::string(flowbufStr)); + currIndex ++; + flowbufStr = FlowbufStrAtIndex(ashmem, flowbufIndex, &argIndex, &strLen); + flowbufIndex++; } argv.push_back(input->GetString()); - curr_index++; + currIndex++; } - while (arg_index == curr_index) { - argv.push_back(std::string(flowbuf_str)); - curr_index ++; - flowbuf_str = FlowbufStrAtIndex(ashmem, flowbuf_index, &arg_index, &str_len); - flowbuf_index++; + while (argIndex == currIndex) { + argv.push_back(std::string(flowbufStr)); + currIndex ++; + flowbufStr = FlowbufStrAtIndex(ashmem, flowbufIndex, &argIndex, &strLen); + flowbufIndex++; } return true; } @@ -380,6 +380,11 @@ bool WebviewJavaScriptResultCallBackImpl::HasJavaScriptObjectMethods(int32_t obj return ret; } +bool WebviewJavaScriptResultCallBackImpl::DeleteJavaScriptRegister(const std::string &objName) +{ + return RemoveNamedObject(objName); +} + void WebviewJavaScriptResultCallBackImpl::RemoveJavaScriptObjectHolder(int32_t holder, JavaScriptOb::ObjectID objectId) {} diff --git a/interfaces/kits/cj/src/webview_mock.cpp b/interfaces/kits/cj/src/webview_mock.cpp index 07fcd5d92ced33016aa38d1422e7e844f308070f..638bf74ff9ddf6b15aad743090b5d29666208701 100644 --- a/interfaces/kits/cj/src/webview_mock.cpp +++ b/interfaces/kits/cj/src/webview_mock.cpp @@ -60,6 +60,9 @@ FFI_EXPORT int FfiOHOSWebviewCtlIsIncognitoMode = 0; FFI_EXPORT int FfiOHOSWebviewCtlRemoveCache = 0; FFI_EXPORT int FfiOHOSWebviewCtlGetBackForwardEntries = 0; FFI_EXPORT int FfiOHOSWebviewCtlStop = 0; +FFI_EXPORT int FfiOHOSWebviewCtlPostUrl = 0; +FFI_EXPORT int FfiOHOSWebviewCtlSetDownloadDelegate = 0; +FFI_EXPORT int FfiOHOSWebviewCtlStartDownload = 0; // webCookieView FFI_EXPORT int FfiOHOSCookieMgrClearSessionCookieSync = 0; @@ -76,4 +79,36 @@ FFI_EXPORT int FfiOHOSCookieMgrFetchCookieSync = 0; FFI_EXPORT int FfiOHOSBackForwardListCurrentIndex = 0; FFI_EXPORT int FfiOHOSBackForwardListSize = 0; FFI_EXPORT int FfiOHOSGetItemAtIndex = 0; + +// WebDownloadItemImpl +FFI_EXPORT int FfiOHOSWebDownloadItemImplConstructor = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetGuid = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetCurrentSpeed = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetPercentComplete = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetTotalBytes = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetReceivedBytes = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetState = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetLastErrorCode = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetMethod = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetMimeType = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetUrl = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetSuggestedFileName = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplGetFullPath = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplStart = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplCancel = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplPause = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplResume = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplSerialize = 0; +FFI_EXPORT int FfiOHOSWebDownloadItemImplDeserialize = 0; + +// WebDownloadDelegateImpl +FFI_EXPORT int FfiOHOSWebDownloadDelegateImplConstructor = 0; +FFI_EXPORT int FfiOHOSWebDownloadDelegateImplOnBeforeDownload = 0; +FFI_EXPORT int FfiOHOSWebDownloadDelegateImplOnDownloadUpdated = 0; +FFI_EXPORT int FfiOHOSWebDownloadDelegateImplOnDownloadFinish = 0; +FFI_EXPORT int FfiOHOSWebDownloadDelegateImplOnDownloadFailed = 0; + +// WebDownloadManagerImpl +FFI_EXPORT int FfiOHOSWebDownloadManagerImplSetDownloadDelegate = 0; +FFI_EXPORT int FfiOHOSWebDownloadManagerImplResumeDownload = 0; } \ No newline at end of file diff --git a/interfaces/kits/cj/src/webview_utils.cpp b/interfaces/kits/cj/src/webview_utils.cpp index 79db2bbbaba0da00d042b65831e7eb61ec39a312..2d52d3bc9db5fbd100183efc720be7b4f805e5f4 100644 --- a/interfaces/kits/cj/src/webview_utils.cpp +++ b/interfaces/kits/cj/src/webview_utils.cpp @@ -22,6 +22,9 @@ namespace OHOS { namespace Webview { char* MallocCString(const std::string& origin) { + if (origin.empty()) { + return nullptr; + } auto len = origin.length() + 1; char* res = static_cast(malloc(sizeof(char) * len)); if (res == nullptr) { @@ -29,5 +32,42 @@ namespace Webview { } return std::char_traits::copy(res, origin.c_str(), len); } + + uint8_t* MallocUInt8(const std::string& origin) + { + auto len = origin.length(); + if (len <= 0) { + return nullptr; + } + char* res = static_cast(malloc(sizeof(char) * len)); + if (res == nullptr) { + return nullptr; + } + return reinterpret_cast(std::char_traits::copy(res, origin.c_str(), len)); + } + + char** VectorToCArrString(const std::vector& vec) + { + char** result = static_cast(malloc(sizeof(char*) * vec.size())); + if (result == nullptr) { + return nullptr; + } + for (size_t i = 0; i < vec.size(); i++) { + result[i] = MallocCString(vec[i]); + } + return result; + } + + uint8_t* VectorToCArrUI8(const std::vector vec) + { + uint8_t* result = static_cast(malloc(sizeof(uint8_t) * vec.size())); + if (result == nullptr) { + return nullptr; + } + for (size_t i = 0; i < vec.size(); i++) { + result[i] = vec[i]; + } + return result; + } } } \ No newline at end of file diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn index ad331007d034c05db81f5a807b31e95a8f07fac9..536ed4565eaddb662802fa622d0727d41d289c92 100644 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -51,6 +51,10 @@ ohos_shared_library("webview_napi") { "webfunction/napi_webview_function.cpp", "webfunction/webview_web_inited_callback.cpp", "webstorage/napi_web_storage.cpp", + "webviewcontroller/back_forward_cache_options.cpp", + "webviewcontroller/back_forward_cache_options.h", + "webviewcontroller/napi_back_forward_cache_options.cpp", + "webviewcontroller/napi_back_forward_cache_options.h", "webviewcontroller/napi_native_media_player.cpp", "webviewcontroller/napi_native_media_player.h", "webviewcontroller/napi_web_download_delegate.cpp", @@ -73,6 +77,7 @@ ohos_shared_library("webview_napi") { "webviewcontroller/web_scheme_handler_request.cpp", "webviewcontroller/web_scheme_handler_request.h", "webviewcontroller/webview_controller.cpp", + "webviewcontroller/webview_createpdf_execute_callback.cpp", "webviewcontroller/webview_hasimage_callback.cpp", "webviewcontroller/webview_javascript_execute_callback.cpp", "webviewcontroller/webview_javascript_result_callback.cpp", diff --git a/interfaces/kits/napi/common/napi_common_macros.h b/interfaces/kits/napi/common/napi_common_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..9b3457e0ff5150c5e40ecaaa0d3f50598cf7fad5 --- /dev/null +++ b/interfaces/kits/napi/common/napi_common_macros.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_COMMON_NACROS_H +#define NAPI_COMMON_NACROS_H + +#define NAPI_GET_CALLBACK_RETURN_VOID(env, value, name, callback) \ + do { \ + napi_get_named_property(env, value, name, &(callback)); \ + napi_valuetype valueType = napi_undefined; \ + napi_typeof(env, callback, &valueType); \ + if (valueType != napi_function) { \ + WVLOG_I("failed to get callback %{public}s", name); \ + return; \ + } \ + } while (0) + +#endif // NAPI_COMMON_NACROS_H diff --git a/interfaces/kits/napi/common/napi_webview_native_module.cpp b/interfaces/kits/napi/common/napi_webview_native_module.cpp index d09ed21fa2c7753a81bd5e56c80386f9c1e7ef7e..4047842051ce1c7e463f50def5a65af0283f9ae2 100644 --- a/interfaces/kits/napi/common/napi_webview_native_module.cpp +++ b/interfaces/kits/napi/common/napi_webview_native_module.cpp @@ -30,6 +30,7 @@ #include "napi_web_download_item.h" #include "napi_web_download_delegate.h" #include "napi_web_scheme_handler_request.h" +#include "napi_back_forward_cache_options.h" namespace OHOS { namespace NWeb { @@ -51,6 +52,8 @@ static napi_value WebViewExport(napi_env env, napi_value exports) NapiWebAdsBlockManager::Init(env, exports); WebFunctionInit(env, exports); NapiNativeMediaPlayerHandler::Init(env, exports); + NapiBackForwardCacheOptions::Init(env, exports); + NapiBackForwardCacheSupportedFeatures::Init(env, exports); return exports; } EXTERN_C_END diff --git a/interfaces/kits/napi/common/nweb_napi_scope.h b/interfaces/kits/napi/common/nweb_napi_scope.h new file mode 100644 index 0000000000000000000000000000000000000000..5378b015f2b28ef29daae33d53abc1e2790cc01b --- /dev/null +++ b/interfaces/kits/napi/common/nweb_napi_scope.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NWEB_NAPI_SCOPE_H +#define NWEB_NAPI_SCOPE_H + +#include +#include "napi/native_api.h" + +namespace OHOS { +struct NApiScope { + NApiScope(napi_env env) : env_(env) { + // Enable the napi_handle_scope to manage the life cycle of the napi_value. + // Otherwise, memory leakage occurs. + napi_open_handle_scope(env_, &scope_); + } + + ~NApiScope() { + if (scope_) { + napi_close_handle_scope(env_, scope_); + } + } + + napi_env env_; + napi_handle_scope scope_ = nullptr; +}; +} + +#endif // NWEB_NAPI_SCOPE_H \ No newline at end of file diff --git a/interfaces/kits/napi/common/web_errors.cpp b/interfaces/kits/napi/common/web_errors.cpp index eec5c783e426aef788f09a9954c272d73818dfc0..44e393ae9bdad643c0a9e9c2a476cc926310a8e3 100644 --- a/interfaces/kits/napi/common/web_errors.cpp +++ b/interfaces/kits/napi/common/web_errors.cpp @@ -37,7 +37,7 @@ const std::string TYPE_NOT_MATCH_WITCH_VALUE_MSG = "The type and value of the me const std::string NEW_OOM_MSG = "Memory allocation failed."; const std::string DOWNLOAD_NOT_PAUSED_MSG = "The download task is not paused."; const std::string NO_VALID_CONTROLLER_FOR_DOWNLOAD_MSG = "No valid WebviewController is associated."; -const std::string NO_DOWNLOAD_DELEGATE_SET_MSG = "No valid WebviewController is associated."; +const std::string NO_DOWNLOAD_DELEGATE_SET_MSG = "No WebDownloadDelegate has been set yet."; const std::string DOWNLOAD_NOT_START_MSG = "The download task is not started yet."; const std::string REGISTER_CUSTOM_SCHEME_FAILED_MSG = "Failed to register custom schemes."; const std::string HTTP_BODY_STREAN_INIT_FAILED_MSG = "Failed to initialize the HTTP body stream."; diff --git a/interfaces/kits/napi/js/BUILD.gn b/interfaces/kits/napi/js/BUILD.gn index 6eea635061186ddf0d38e17111e51139719482b8..8ea861dd83d5283739522443b3cfa93c37f78d02 100644 --- a/interfaces/kits/napi/js/BUILD.gn +++ b/interfaces/kits/napi/js/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_webview_export_abc") { diff --git a/interfaces/kits/napi/js/webview_export.js b/interfaces/kits/napi/js/webview_export.js index 872b6e5c812e231ece1ebe3696911a9849fc47ef..87fd6b15a42a6c2dc32cabb8bebe39715e8a7e52 100644 --- a/interfaces/kits/napi/js/webview_export.js +++ b/interfaces/kits/napi/js/webview_export.js @@ -16,6 +16,7 @@ let cert = requireInternal('security.cert'); let webview = requireInternal('web.webview'); let picker = requireNapi('file.picker'); +let photoAccessHelper = requireNapi('file.photoAccessHelper'); let cameraPicker = requireNapi('multimedia.cameraPicker'); let camera = requireNapi('multimedia.camera'); let accessControl = requireNapi('abilityAccessCtrl'); @@ -28,11 +29,11 @@ let errMsgMap = new Map(); errMsgMap.set(PARAM_CHECK_ERROR, ERROR_MSG_INVALID_PARAM); class BusinessError extends Error { - constructor(code, errorMsg = "undefined") { - if(errorMsg === "undefined") { + constructor(code, errorMsg = 'undefined') { + if (errorMsg === 'undefined') { let msg = errMsgMap.get(code); super(msg); - }else{ + } else { super(errorMsg); } this.code = code; @@ -197,21 +198,21 @@ function isContainVideoMimeType(acceptTypes) { function selectPicture(param, selectResult) { try { let photoResultArray = []; - let photoSelectOptions = new picker.PhotoSelectOptions(); + let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); if (param.getMode() === FileSelectorMode.FileOpenMode) { console.log('allow select single photo or video'); photoSelectOptions.maxSelectNumber = 1; } let acceptTypes = param.getAcceptType(); - photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE; + photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE; if (isContainImageMimeType(acceptTypes) && !isContainVideoMimeType(acceptTypes)) { - photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; + photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; } if (!isContainImageMimeType(acceptTypes) && isContainVideoMimeType(acceptTypes)) { - photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.VIDEO_TYPE; + photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE; } - let photoPicker = new picker.PhotoViewPicker(); + let photoPicker = new photoAccessHelper.PhotoViewPicker(); photoPicker.select(photoSelectOptions).then((photoSelectResult) => { if (photoSelectResult.photoUris.length <= 0) { return; @@ -230,7 +231,7 @@ Object.defineProperty(webview.WebviewController.prototype, 'getCertificate', { value: function (callback) { if (arguments.length !== 0 && arguments.length !== 1) { throw new BusinessError(PARAM_CHECK_ERROR, - "BusinessError 401: Parameter error. The number of params must be zero or one."); + 'BusinessError 401: Parameter error. The number of params must be zero or one.'); } let certChainData = this.innerGetCertificate(); @@ -241,9 +242,9 @@ Object.defineProperty(webview.WebviewController.prototype, 'getCertificate', { console.log('get certificate async callback'); if (typeof callback !== 'function') { throw new BusinessError(PARAM_CHECK_ERROR, - "BusinessError 401: Parameter error. The type of 'callback' must be function." ); + 'BusinessError 401: Parameter error. The type of "callback" must be function.' ); } - getCertificatePromise(certChainData).then(x509CertArray => { + return getCertificatePromise(certChainData).then(x509CertArray => { callback(undefined, x509CertArray); }).catch(error => { callback(error, undefined); diff --git a/interfaces/kits/napi/webviewcontroller/back_forward_cache_options.cpp b/interfaces/kits/napi/webviewcontroller/back_forward_cache_options.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6fcbb15d833af46b983cd79cf56902821618a95 --- /dev/null +++ b/interfaces/kits/napi/webviewcontroller/back_forward_cache_options.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "back_forward_cache_options.h" + +#include + +#include "napi_parse_utils.h" +#include "nweb_log.h" +#include "business_error.h" +#include "web_errors.h" + +namespace OHOS::NWeb { +BackForwardCacheOptions::BackForwardCacheOptions() +{ + WVLOG_D("Created a BackForwardCacheOptions class."); +} + +int32_t BackForwardCacheOptions::GetSize() +{ + return size_; +} + +int32_t BackForwardCacheOptions::GetTimeToLive() +{ + return timeToLive_; +} + +BackForwardCacheSupportedFeatures::BackForwardCacheSupportedFeatures() +{ + WVLOG_D("Created a BackForwardCacheSupportedFeatures class."); +} + +bool BackForwardCacheSupportedFeatures::IsEnableNativeEmbed() +{ + return nativeEmbed_; +} + +bool BackForwardCacheSupportedFeatures::IsEnableMediaTakeOver() +{ + return mediaTakeOver_; +} + +} \ No newline at end of file diff --git a/interfaces/kits/napi/webviewcontroller/back_forward_cache_options.h b/interfaces/kits/napi/webviewcontroller/back_forward_cache_options.h new file mode 100644 index 0000000000000000000000000000000000000000..e11da84d483da4edae3d1ad43adf674f4cdc5e24 --- /dev/null +++ b/interfaces/kits/napi/webviewcontroller/back_forward_cache_options.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NWEB_BACK_FORWARD_CACHE_OPTIONS_H +#define NWEB_BACK_FORWARD_CACHE_OPTIONS_H + +#include +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +#define BFCACHE_DEFAULT_SIZE 1 +#define BFCACHE_DEFAULT_TIMETOLIVE 600 + +namespace OHOS { +namespace NWeb { +class BackForwardCacheOptions { +public: + BackForwardCacheOptions(); + int32_t GetSize(); + int32_t GetTimeToLive(); + +private: + int32_t size_ = 1; + int32_t timeToLive_ = 600; +}; + +class BackForwardCacheSupportedFeatures { +public: + BackForwardCacheSupportedFeatures(); + bool IsEnableNativeEmbed(); + bool IsEnableMediaTakeOver(); + +private: + bool nativeEmbed_ = false; + bool mediaTakeOver_ = false; +}; + +} +} + +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/webviewcontroller/napi_back_forward_cache_options.cpp b/interfaces/kits/napi/webviewcontroller/napi_back_forward_cache_options.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f149c6007c5c5cb47891aded0113f6e1d74b7e6d --- /dev/null +++ b/interfaces/kits/napi/webviewcontroller/napi_back_forward_cache_options.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_back_forward_cache_options.h" + +#include +#include +#include +#include +#include + +#include "back_forward_cache_options.h" +#include "business_error.h" +#include "nweb_log.h" +#include "napi_parse_utils.h" +#include "napi/native_node_api.h" +#include "web_errors.h" + +using namespace OHOS::NWebError; + +namespace OHOS { +namespace NWeb { +napi_value NapiBackForwardCacheOptions::JS_Constructor(napi_env env, napi_callback_info info) +{ + WVLOG_I("NapiBackForwardCacheOptions::JS_Constructor is called"); + napi_value thisVar = nullptr; + void *data = nullptr; + size_t argc = 2; + napi_value argv[2] = {0}; + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + + BackForwardCacheOptions *options = new BackForwardCacheOptions(); + + napi_wrap( + env, thisVar, options, + [](napi_env /* env */, void *data, void * /* hint */) { + BackForwardCacheOptions *options = (BackForwardCacheOptions *)data; + delete options; + options = nullptr; + }, + nullptr, nullptr); + + return thisVar; +} + +napi_value NapiBackForwardCacheSupportedFeatures::JS_Constructor(napi_env env, napi_callback_info info) +{ + WVLOG_I("NapiBackForwardCacheSupportedFeatures::JS_Constructor is called"); + napi_value thisVar = nullptr; + void *data = nullptr; + size_t argc = 2; + napi_value argv[2] = {0}; + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + + BackForwardCacheSupportedFeatures *features = new BackForwardCacheSupportedFeatures(); + + napi_wrap( + env, thisVar, features, + [](napi_env /* env */, void *data, void * /* hint */) { + BackForwardCacheSupportedFeatures *features = (BackForwardCacheSupportedFeatures *)data; + delete features; + features = nullptr; + }, + nullptr, nullptr); + + return thisVar; +} + +napi_value NapiBackForwardCacheOptions::Init(napi_env env, napi_value exports) +{ + WVLOG_D("NapiBackForwardCacheOptions::Init"); + napi_value backForwardCacheOptions = nullptr; + napi_define_class(env, BACK_FORWARD_CACHE_OPTIONS.c_str(), + BACK_FORWARD_CACHE_OPTIONS.length(), + JS_Constructor, nullptr, 0, nullptr, &backForwardCacheOptions); + napi_set_named_property(env, exports, BACK_FORWARD_CACHE_OPTIONS.c_str(), + backForwardCacheOptions); + return exports; +} + +napi_value NapiBackForwardCacheSupportedFeatures::Init(napi_env env, napi_value exports) +{ + WVLOG_D("NapiBackForwardCacheSupportedFeatures::Init"); + napi_value backForwardCacheSupportedFeatures = nullptr; + napi_define_class(env, BACK_FORWARD_CACHE_SUPPORTED_FEATURES.c_str(), + BACK_FORWARD_CACHE_SUPPORTED_FEATURES.length(), + JS_Constructor, nullptr, 0, nullptr, &backForwardCacheSupportedFeatures); + napi_set_named_property(env, exports, BACK_FORWARD_CACHE_SUPPORTED_FEATURES.c_str(), + backForwardCacheSupportedFeatures); + return exports; +} + +} +} \ No newline at end of file diff --git a/interfaces/kits/napi/webviewcontroller/napi_back_forward_cache_options.h b/interfaces/kits/napi/webviewcontroller/napi_back_forward_cache_options.h new file mode 100644 index 0000000000000000000000000000000000000000..2d04145c96a5648acb7ecedc032d274ee732c373 --- /dev/null +++ b/interfaces/kits/napi/webviewcontroller/napi_back_forward_cache_options.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NWEB_NAPI_BACK_FORWARD_CACHE_OPTIONS_H +#define NWEB_NAPI_BACK_FORWARD_CACHE_OPTIONS_H + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace NWeb { + +const std::string BACK_FORWARD_CACHE_OPTIONS = "BackForwardCacheOptions"; +const std::string BACK_FORWARD_CACHE_SUPPORTED_FEATURES = "BackForwardCacheSupportedFeatures"; + +class NapiBackForwardCacheOptions { +public: + NapiBackForwardCacheOptions() = default; + ~NapiBackForwardCacheOptions() = default; + + static napi_value Init(napi_env env, napi_value exports); + static napi_value JS_Constructor(napi_env env, napi_callback_info info); +}; + +class NapiBackForwardCacheSupportedFeatures { +public: + NapiBackForwardCacheSupportedFeatures() = default; + ~NapiBackForwardCacheSupportedFeatures() = default; + + static napi_value Init(napi_env env, napi_value exports); + static napi_value JS_Constructor(napi_env env, napi_callback_info info); +}; + +} +} + +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/webviewcontroller/napi_native_media_player.cpp b/interfaces/kits/napi/webviewcontroller/napi_native_media_player.cpp index a49293da2a107161eb50a22021f61024775b0cb5..17ca2f7c416ee5b0af3359f4c5b9b8252caf4f86 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_native_media_player.cpp +++ b/interfaces/kits/napi/webviewcontroller/napi_native_media_player.cpp @@ -40,6 +40,8 @@ void NapiNativeMediaPlayerHandler::Init(napi_env env, napi_value value) NAPI_CALL_RETURN_VOID(env, ExportEnumReadyState(env, &value)); + NAPI_CALL_RETURN_VOID(env, ExportEnumSuspendType(env, &value)); + NAPI_CALL_RETURN_VOID(env, ExportEnumNetworkState(env, &value)); NAPI_CALL_RETURN_VOID(env, ExportEnumPlaybackStatus(env, &value)); @@ -172,16 +174,16 @@ napi_status NapiNativeMediaPlayerHandler::ExportEnumReadyState(napi_env env, nap napi_status NapiNativeMediaPlayerHandler::ExportEnumSuspendType(napi_env env, napi_value* value) { - WVLOG_D("begin to export enum suspend type state"); + WVLOG_D("begin to export enum suspend type"); const std::string NPI_SUSPEND_TYPE_ENUM_NAME = "SuspendType"; napi_property_descriptor properties[] = { + DECLARE_NAPI_STATIC_PROPERTY("ENTER_BACK_FORWARD_CACHE", + NapiParseUtils::ToInt32Value(env, static_cast(SuspendType::ENTER_BACK_FORWARD_CACHE))), DECLARE_NAPI_STATIC_PROPERTY( - "EnterBFCache", NapiParseUtils::ToInt32Value(env, static_cast(SuspendType::EnterBFCache))), - DECLARE_NAPI_STATIC_PROPERTY( - "EnterBackground", NapiParseUtils::ToInt32Value(env, static_cast(SuspendType::EnterBackground))), + "ENTER_BACKGROUND", NapiParseUtils::ToInt32Value(env, static_cast(SuspendType::ENTER_BACKGROUND))), DECLARE_NAPI_STATIC_PROPERTY( - "PausedOverTime", NapiParseUtils::ToInt32Value(env, static_cast(SuspendType::PausedOverTime))), + "AUTO_CLEANUP", NapiParseUtils::ToInt32Value(env, static_cast(SuspendType::AUTO_CLEANUP))), }; napi_value enumValue = nullptr; diff --git a/interfaces/kits/napi/webviewcontroller/napi_native_media_player.h b/interfaces/kits/napi/webviewcontroller/napi_native_media_player.h index 641131d7071cc9519b3fbe30267ebe571b5b910f..dfba1d8e708090cacfde8d0193589b3289cbc9e6 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_native_media_player.h +++ b/interfaces/kits/napi/webviewcontroller/napi_native_media_player.h @@ -79,4 +79,4 @@ private: } // namespace OHOS::NWeb -#endif // NAPI_WEBVIEW_NATIVE_MEDIA_PLAYER_H +#endif // NAPI_NATIVE_MEDIA_PLAYER_H diff --git a/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.cpp b/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.cpp index 8f8fe08974c2ca33704de43b626f2a15c0a3ead2..068f0c4808d6cc73afc7c1d94ee911deaf46d6fa 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.cpp +++ b/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.cpp @@ -15,11 +15,11 @@ #include "napi_web_download_delegate.h" +#include #include #include #include #include -#include #include "nweb_log.h" #include "web_download_delegate.h" @@ -141,6 +141,7 @@ napi_value NapiWebDownloadDelegate::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("onDownloadFinish", JS_DownloadDidFinish), DECLARE_NAPI_FUNCTION("onDownloadFailed", JS_DownloadDidFail), }; + const std::string WEB_DOWNLOAD_DELEGATE = "WebDownloadDelegate"; napi_value webDownloadDelegateClass = nullptr; napi_define_class(env, WEB_DOWNLOAD_DELEGATE.c_str(), WEB_DOWNLOAD_DELEGATE.length(), JS_Constructor, nullptr, sizeof(properties) / sizeof(properties[0]), properties, &webDownloadDelegateClass); diff --git a/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.h b/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.h index ccdc0b35b22076042a4f9a5064a92e515cbdac64..fce4734b3b347cf127744f7074232aa3686b342e 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.h +++ b/interfaces/kits/napi/webviewcontroller/napi_web_download_delegate.h @@ -24,7 +24,6 @@ namespace OHOS { namespace NWeb { -const std::string WEB_DOWNLOAD_DELEGATE = "WebDownloadDelegate"; class NapiWebDownloadDelegate { public: diff --git a/interfaces/kits/napi/webviewcontroller/napi_web_download_item.cpp b/interfaces/kits/napi/webviewcontroller/napi_web_download_item.cpp index 0c9742d589f939b03e9dcfe046f8af0f7412df75..9830fe8a9490a1f5cbea392743e03c7e930c886d 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_web_download_item.cpp +++ b/interfaces/kits/napi/webviewcontroller/napi_web_download_item.cpp @@ -202,6 +202,10 @@ napi_value NapiWebDownloadItem::JS_GetMethod(napi_env env, napi_callback_info cb napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetMethod webDownloadItem is null"); + return nullptr; + } napi_value methodValue; napi_status status = napi_create_string_utf8(env, webDownloadItem->method.c_str(), NAPI_AUTO_LENGTH, &methodValue); @@ -223,6 +227,10 @@ napi_value NapiWebDownloadItem::JS_GetMimeType(napi_env env, napi_callback_info napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetMimeType webDownloadItem is null"); + return nullptr; + } napi_value mimeTypeValue; napi_status status = @@ -245,6 +253,10 @@ napi_value NapiWebDownloadItem::JS_GetUrl(napi_env env, napi_callback_info cbinf napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetUrl webDownloadItem is null"); + return nullptr; + } napi_value urlValue; napi_status status = napi_create_string_utf8(env, webDownloadItem->url.c_str(), NAPI_AUTO_LENGTH, &urlValue); @@ -266,6 +278,10 @@ napi_value NapiWebDownloadItem::JS_GetSuggestedFileName(napi_env env, napi_callb napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetSuggestedFileName webDownloadItem is null"); + return nullptr; + } napi_value fileNameValue; napi_status status = @@ -288,6 +304,10 @@ napi_value NapiWebDownloadItem::JS_GetCurrentSpeed(napi_env env, napi_callback_i napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetCurrentSpeed webDownloadItem is null"); + return nullptr; + } napi_value currentSpeed; napi_status status = napi_create_int64(env, webDownloadItem->currentSpeed, ¤tSpeed); @@ -309,6 +329,10 @@ napi_value NapiWebDownloadItem::JS_GetPercentComplete(napi_env env, napi_callbac napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetPercentComplete webDownloadItem is null"); + return nullptr; + } napi_value percentComplete; napi_status status = napi_create_int64(env, webDownloadItem->percentComplete, &percentComplete); @@ -330,6 +354,10 @@ napi_value NapiWebDownloadItem::JS_GetTotalBytes(napi_env env, napi_callback_inf napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetTotalBytes webDownloadItem is null"); + return nullptr; + } napi_value totalBytes; napi_status status = napi_create_int64(env, webDownloadItem->totalBytes, &totalBytes); @@ -351,6 +379,10 @@ napi_value NapiWebDownloadItem::JS_GetReceivedBytes(napi_env env, napi_callback_ napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, &data); napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if (!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_GetReceivedBytes webDownloadItem is null"); + return nullptr; + } napi_value receivedBytes; napi_status status = napi_create_int64(env, webDownloadItem->receivedBytes, &receivedBytes); @@ -513,8 +545,8 @@ napi_value NapiWebDownloadItem::JS_Pause(napi_env env, napi_callback_info cbinfo WVLOG_E("[DOWNLOAD] unwrap webDownloadItem failed"); return nullptr; } - NWebDownloadItemState state = WebDownload_GetItemState( - webDownloadItem->nwebId, webDownloadItem->webDownloadId); + NWebDownloadItemState state = WebDownload_GetItemStateByGuid(webDownloadItem->guid); + WVLOG_D("[DOWNLOAD] pause state %{public}d", static_cast(state)); if (state != NWebDownloadItemState::IN_PROGRESS && state != NWebDownloadItemState::PENDING) { BusinessError::ThrowErrorByErrcode(env, DOWNLOAD_NOT_START); @@ -545,8 +577,8 @@ napi_value NapiWebDownloadItem::JS_Resume(napi_env env, napi_callback_info cbinf return nullptr; } - NWebDownloadItemState state = WebDownload_GetItemState( - webDownloadItem->nwebId, webDownloadItem->webDownloadId); + NWebDownloadItemState state = WebDownload_GetItemStateByGuid(webDownloadItem->guid); + WVLOG_D("[DOWNLOAD] resume state %{public}d", static_cast(state)); if (state != NWebDownloadItemState::PAUSED) { BusinessError::ThrowErrorByErrcode(env, DOWNLOAD_NOT_PAUSED); return nullptr; @@ -614,20 +646,13 @@ napi_value NapiWebDownloadItem::JS_Start(napi_env env, napi_callback_info cbinfo return nullptr; } webDownloadItem->downloadPath = std::string(stringValue); + WVLOG_D("NapiWebDownloadItem::JS_Start, download_path: %s", webDownloadItem->downloadPath.c_str()); WebDownload_Continue(webDownloadItem->before_download_callback, webDownloadItem->downloadPath.c_str()); return nullptr; } -napi_value NapiWebDownloadItem::JS_Serialize(napi_env env, napi_callback_info cbinfo) +void SetWebDownloadPb(browser_service::WebDownload &webDownloadPb, const WebDownloadItem *webDownloadItem) { - napi_value thisVar = nullptr; - void *data = nullptr; - napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, &data); - - WebDownloadItem *webDownloadItem = nullptr; - napi_unwrap(env, thisVar, (void **)&webDownloadItem); - - browser_service::WebDownload webDownloadPb; webDownloadPb.set_web_download_id(webDownloadItem->webDownloadId); webDownloadPb.set_current_speed(webDownloadItem->currentSpeed); webDownloadPb.set_percent_complete(webDownloadItem->percentComplete); @@ -647,6 +672,23 @@ napi_value NapiWebDownloadItem::JS_Serialize(napi_env env, napi_callback_info cb webDownloadPb.set_last_error_code(webDownloadItem->lastErrorCode); webDownloadPb.set_received_slices(webDownloadItem->receivedSlices); webDownloadPb.set_download_path(webDownloadItem->downloadPath); +} + +napi_value NapiWebDownloadItem::JS_Serialize(napi_env env, napi_callback_info cbinfo) +{ + napi_value thisVar = nullptr; + void *data = nullptr; + napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, &data); + + WebDownloadItem *webDownloadItem = nullptr; + napi_unwrap(env, thisVar, (void **)&webDownloadItem); + if(!webDownloadItem) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadItem::JS_Serialize webDownloadItem is null"); + return nullptr; + } + + browser_service::WebDownload webDownloadPb; + SetWebDownloadPb(webDownloadPb, webDownloadItem); std::string webDownloadValue; webDownloadPb.SerializeToString(&webDownloadValue); @@ -654,21 +696,22 @@ napi_value NapiWebDownloadItem::JS_Serialize(napi_env env, napi_callback_info cb void *bufferData = nullptr; napi_status status = napi_create_arraybuffer(env, webDownloadValue.length(), (void **)&bufferData, &arraybuffer); + if (status != napi_ok) { + WVLOG_E("[DOWNLOAD] create array buffer failed, status: %{public}d", status); + return nullptr; + } if (memcpy_s(bufferData, webDownloadValue.length(), webDownloadValue.c_str(), webDownloadValue.length()) != 0) { - WVLOG_D("[DOWNLOAD] memcpy failed"); + WVLOG_E("[DOWNLOAD] memcpy failed"); return nullptr; } napi_ref arraybufferRef; napi_create_reference(env, arraybuffer, 1, &arraybufferRef); - if (status != napi_ok) { - WVLOG_D("[DOWNLOAD] create array buffer failed, status: %{public}d", status); - return nullptr; - } napi_value typedArray; status = napi_create_typedarray(env, napi_typedarray_type::napi_uint8_array, webDownloadValue.length(), arraybuffer, 0, &typedArray); if (status != napi_ok) { - WVLOG_D("[DOWNLOAD] create typed array failed, status: %{public}d", status); + WVLOG_E("[DOWNLOAD] create typed array failed, status: %{public}d", status); + napi_delete_reference(env, arraybufferRef); return nullptr; } return typedArray; diff --git a/interfaces/kits/napi/webviewcontroller/napi_web_download_manager.cpp b/interfaces/kits/napi/webviewcontroller/napi_web_download_manager.cpp index 7b79c1a45a4cc546ebeb46526f064aaf27e19f20..f342112e9428df1832c6e309ed04375cd351d167 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_web_download_manager.cpp +++ b/interfaces/kits/napi/webviewcontroller/napi_web_download_manager.cpp @@ -49,6 +49,10 @@ napi_value NapiWebDownloadManager::JS_SetDownloadDelegate(napi_env env, napi_cal WebDownloadDelegate *delegate = nullptr; napi_unwrap(env, obj, (void **)&delegate); + if (!delegate) { + WVLOG_E("[DOWNLOAD] NapiWebDownloadManager::JS_SetDownloadDelegate delegate is null"); + return nullptr; + } napi_create_reference(env, obj, 1, &delegate->delegate_); WebDownloadManager::SetDownloadDelegate(delegate); return nullptr; diff --git a/interfaces/kits/napi/webviewcontroller/napi_web_scheme_handler_request.cpp b/interfaces/kits/napi/webviewcontroller/napi_web_scheme_handler_request.cpp index 66c237ff7d5f848c0fb1ff605dea564dbb39cee2..84cb625afc0e65b2ca30ca2f84b55f47ffdb9c5a 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_web_scheme_handler_request.cpp +++ b/interfaces/kits/napi/webviewcontroller/napi_web_scheme_handler_request.cpp @@ -87,12 +87,15 @@ napi_value NapiWebSchemeHandlerRequest::JS_Constructor(napi_env env, napi_callba void *data = nullptr; napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, &data); - WebSchemeHandlerRequest *request = new WebSchemeHandlerRequest(env); + WebSchemeHandlerRequest *request = new (std::nothrow) WebSchemeHandlerRequest(env); + if (request == nullptr) { + return nullptr; + } napi_wrap( env, thisVar, request, [](napi_env /* env */, void *data, void * /* hint */) { - WebSchemeHandlerRequest *request = (WebSchemeHandlerRequest *)data; + WebSchemeHandlerRequest *request = reinterpret_cast(data); delete request; }, nullptr, nullptr); @@ -118,6 +121,11 @@ napi_value NapiWebSchemeHandlerRequest::JS_GetHeader(napi_env env, napi_callback napi_create_array(env, &result); size_t headerSize = list.size(); for (size_t index = 0; index < headerSize; index++) { + napi_handle_scope scope; + napi_status status = napi_open_handle_scope(env, &scope); + if (status != napi_ok) { + break; + } napi_value webHeaderObj = nullptr; napi_value headerKey = nullptr; napi_value headerValue = nullptr; @@ -127,6 +135,10 @@ napi_value NapiWebSchemeHandlerRequest::JS_GetHeader(napi_env env, napi_callback napi_set_named_property(env, webHeaderObj, "headerKey", headerKey); napi_set_named_property(env, webHeaderObj, "headerValue", headerValue); napi_set_element(env, result, index, webHeaderObj); + status = napi_close_handle_scope(env, scope); + if (status != napi_ok) { + break; + } } return result; } @@ -284,7 +296,7 @@ napi_value NapiWebSchemeHandlerRequest::JS_HttpBodyStream(napi_env env, napi_cal napi_wrap( env, httpBodyStreamObject, stream, [](napi_env /* env */, void *data, void * /* hint */) { - WebHttpBodyStream *stream = (WebHttpBodyStream *)data; + WebHttpBodyStream *stream = reinterpret_cast(data); delete stream; }, nullptr, nullptr); @@ -1210,7 +1222,7 @@ napi_value NapiWebHttpBodyStream::JS_Initialize(napi_env env, napi_callback_info return result; } -bool checkReadParamsNumber(napi_env env, const size_t argc) { +bool CheckReadParamsNumber(napi_env env, const size_t argc) { size_t argcPromise = INTEGER_ONE; size_t argcCallback = INTEGER_TWO; if (argc != argcPromise && argc != argcCallback) { @@ -1249,7 +1261,7 @@ napi_value NapiWebHttpBodyStream::JS_Read(napi_env env, napi_callback_info info) WVLOG_E("NapiWebHttpBodyStream::JS_Initialize stream is nullptr"); return nullptr; } - if (!checkReadParamsNumber(env, argc)) { + if (!CheckReadParamsNumber(env, argc)) { return nullptr; } diff --git a/interfaces/kits/napi/webviewcontroller/napi_webview_controller.cpp b/interfaces/kits/napi/webviewcontroller/napi_webview_controller.cpp index 84119e8c0e97345d1e4d7f5dd0b8bd6b4512421a..f82c4c9d5c24692b2f5f8fc524f4296cdad992d1 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_webview_controller.cpp +++ b/interfaces/kits/napi/webviewcontroller/napi_webview_controller.cpp @@ -27,6 +27,7 @@ #include "application_context.h" #include "business_error.h" #include "napi_parse_utils.h" +#include "native_engine/native_engine.h" #include "nweb.h" #include "nweb_adapter_helper.h" #include "nweb_helper.h" @@ -38,12 +39,15 @@ #include "pixel_map_napi.h" #include "web_errors.h" #include "webview_javascript_execute_callback.h" +#include "webview_createpdf_execute_callback.h" #include "web_download_delegate.h" #include "web_download_manager.h" #include "arkweb_scheme_handler.h" #include "web_scheme_handler_request.h" +#include "back_forward_cache_options.h" + namespace OHOS { namespace NWeb { using namespace NWebError; @@ -56,6 +60,11 @@ constexpr char URL_REGEXPR[] = "^http(s)?:\\/\\/.+"; constexpr size_t MAX_RESOURCES_COUNT = 30; constexpr size_t MAX_RESOURCE_SIZE = 10 * 1024 * 1024; constexpr size_t MAX_URL_TRUST_LIST_STR_LEN = 10 * 1024 * 1024; // 10M +constexpr double A4_WIDTH = 8.5; +constexpr double A4_HEIGHT = 11.0; +constexpr double SCALE_MIN = 0.1; +constexpr double SCALE_MAX = 2.0; +constexpr double HALF = 2.0; using WebPrintWriteResultCallback = std::function; bool ParsePrepareUrl(napi_env env, napi_value urlObj, std::string& url) @@ -333,6 +342,58 @@ std::shared_ptr ParsePrefetchArgs(napi_env env, napi_val return prefetchArgs; } +std::shared_ptr ParsePDFConfigArgs(napi_env env, napi_value preArgs) +{ + napi_value widthObj = nullptr; + double width = A4_WIDTH; + napi_get_named_property(env, preArgs, "width", &widthObj); + NapiParseUtils::ParseDouble(env, widthObj, width); + + napi_value heightObj = nullptr; + double height = A4_HEIGHT; + napi_get_named_property(env, preArgs, "height", &heightObj); + NapiParseUtils::ParseDouble(env, heightObj, height); + + napi_value scaleObj = nullptr; + double scale = 1.0; + napi_get_named_property(env, preArgs, "scale", &scaleObj); + NapiParseUtils::ParseDouble(env, scaleObj, scale); + scale = scale > SCALE_MAX ? SCALE_MAX : scale < SCALE_MIN ? SCALE_MIN : scale; + + napi_value marginTopObj = nullptr; + double marginTop = 0.0; + napi_get_named_property(env, preArgs, "marginTop", &marginTopObj); + NapiParseUtils::ParseDouble(env, marginTopObj, marginTop); + marginTop = marginTop >= height / HALF ? 0.0 : marginTop; + + napi_value marginBottomObj = nullptr; + double marginBottom = 0.0; + napi_get_named_property(env, preArgs, "marginBottom", &marginBottomObj); + NapiParseUtils::ParseDouble(env, marginBottomObj, marginBottom); + marginBottom = marginBottom >= height / HALF ? 0.0 : marginBottom; + + napi_value marginRightObj = nullptr; + double marginRight = 0.0; + napi_get_named_property(env, preArgs, "marginRight", &marginRightObj); + NapiParseUtils::ParseDouble(env, marginRightObj, marginRight); + marginRight = marginRight >= width / HALF ? 0.0 : marginRight; + + napi_value marginLeftObj = nullptr; + double marginLeft = 0.0; + napi_get_named_property(env, preArgs, "marginLeft", &marginLeftObj); + NapiParseUtils::ParseDouble(env, marginLeftObj, marginLeft); + marginLeft = marginLeft >= width / HALF ? 0.0 : marginLeft; + + napi_value shouldPrintBackgroundObj = nullptr; + bool shouldPrintBackground = false; + napi_get_named_property(env, preArgs, "shouldPrintBackground", &shouldPrintBackgroundObj); + NapiParseUtils::ParseBoolean(env, shouldPrintBackgroundObj, shouldPrintBackground); + + std::shared_ptr pdfConfig = std::make_shared( + width, height, scale, marginTop, marginBottom, marginRight, marginLeft, shouldPrintBackground); + return pdfConfig; +} + void JsErrorCallback(napi_env env, napi_ref jsCallback, int32_t err) { napi_value jsError = nullptr; @@ -446,6 +507,7 @@ napi_value NapiWebviewController::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("deleteJavaScriptRegister", NapiWebviewController::DeleteJavaScriptRegister), DECLARE_NAPI_FUNCTION("runJavaScript", NapiWebviewController::RunJavaScript), DECLARE_NAPI_FUNCTION("runJavaScriptExt", NapiWebviewController::RunJavaScriptExt), + DECLARE_NAPI_FUNCTION("createPdf", NapiWebviewController::RunCreatePDFExt), DECLARE_NAPI_FUNCTION("getUrl", NapiWebviewController::GetUrl), DECLARE_NAPI_FUNCTION("terminateRenderProcess", NapiWebviewController::TerminateRenderProcess), DECLARE_NAPI_FUNCTION("getOriginalUrl", NapiWebviewController::GetOriginalUrl), @@ -525,6 +587,13 @@ napi_value NapiWebviewController::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("webPageSnapshot", NapiWebviewController::WebPageSnapshot), DECLARE_NAPI_FUNCTION("setPathAllowingUniversalAccess", NapiWebviewController::SetPathAllowingUniversalAccess), + DECLARE_NAPI_STATIC_FUNCTION("enableBackForwardCache", NapiWebviewController::EnableBackForwardCache), + DECLARE_NAPI_FUNCTION("setBackForwardCacheOptions", NapiWebviewController::SetBackForwardCacheOptions), + DECLARE_NAPI_STATIC_FUNCTION("trimMemoryByPressureLevel", + NapiWebviewController::TrimMemoryByPressureLevel), + DECLARE_NAPI_FUNCTION("getScrollOffset", + NapiWebviewController::GetScrollOffset), + DECLARE_NAPI_FUNCTION("scrollByWithResult", NapiWebviewController::ScrollByWithResult), }; napi_value constructor = nullptr; napi_define_class(env, WEBVIEW_CONTROLLER_CLASS_NAME.c_str(), WEBVIEW_CONTROLLER_CLASS_NAME.length(), @@ -708,7 +777,30 @@ napi_value NapiWebviewController::Init(napi_env env, napi_value exports) sizeof(offlineResourceTypeProperties[0]), offlineResourceTypeProperties, &offlineResourceTypeEnum); napi_set_named_property(env, exports, OFFLINE_RESOURCE_TYPE_ENUM_NAME.c_str(), offlineResourceTypeEnum); + napi_value pressureLevelEnum = nullptr; + napi_property_descriptor pressureLevelProperties[] = { + DECLARE_NAPI_STATIC_PROPERTY("MEMORY_PRESSURE_LEVEL_MODERATE", NapiParseUtils::ToInt32Value(env, + static_cast(PressureLevel::MEMORY_PRESSURE_LEVEL_MODERATE))), + DECLARE_NAPI_STATIC_PROPERTY("MEMORY_PRESSURE_LEVEL_CRITICAL", NapiParseUtils::ToInt32Value(env, + static_cast(PressureLevel::MEMORY_PRESSURE_LEVEL_CRITICAL))), + }; + napi_define_class(env, WEB_PRESSURE_LEVEL_ENUM_NAME.c_str(), WEB_PRESSURE_LEVEL_ENUM_NAME.length(), + NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(pressureLevelProperties) / + sizeof(pressureLevelProperties[0]), pressureLevelProperties, &pressureLevelEnum); + napi_set_named_property(env, exports, WEB_PRESSURE_LEVEL_ENUM_NAME.c_str(), pressureLevelEnum); + + napi_value scrollTypeEnum = nullptr; + napi_property_descriptor scrollTypeProperties[] = { + DECLARE_NAPI_STATIC_PROPERTY("EVENT", NapiParseUtils::ToInt32Value(env, + static_cast(ScrollType::EVENT))), + }; + napi_define_class(env, WEB_SCROLL_TYPE_ENUM_NAME.c_str(), WEB_SCROLL_TYPE_ENUM_NAME.length(), + NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(scrollTypeProperties) / + sizeof(scrollTypeProperties[0]), scrollTypeProperties, &scrollTypeEnum); + napi_set_named_property(env, exports, WEB_SCROLL_TYPE_ENUM_NAME.c_str(), scrollTypeEnum); + WebviewJavaScriptExecuteCallback::InitJSExcute(env, exports); + WebviewCreatePDFExecuteCallback::InitJSExcute(env, exports); return exports; } @@ -888,7 +980,10 @@ napi_value NapiWebviewController::EnableSafeBrowsing(napi_env env, napi_callback WebviewController *controller = nullptr; napi_unwrap(env, thisVar, (void **)&controller); - if (!controller || !controller->IsInit()) { + if (!controller) { + return result; + } + if (!controller->IsInit()) { BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return result; } @@ -1041,7 +1136,7 @@ napi_value NapiWebviewController::InnerGetCustomeSchemeCmdLine(napi_env env, nap { WebviewController::existNweb_ = true; napi_value result = nullptr; - std::string cmdLine = WebviewController::customeSchemeCmdLine_; + const std::string& cmdLine = WebviewController::customeSchemeCmdLine_; napi_create_string_utf8(env, cmdLine.c_str(), cmdLine.length(), &result); return result; } @@ -1148,11 +1243,12 @@ napi_value NapiWebviewController::OnActive(napi_env env, napi_callback_info info napi_value result = nullptr; WebviewController *webviewController = GetWebviewController(env, info); if (!webviewController) { + WVLOG_E("NapiWebviewController::OnActive get controller failed"); return nullptr; } webviewController->OnActive(); - WVLOG_D("The web component has been successfully activated"); + WVLOG_I("The web component has been successfully activated"); NAPI_CALL(env, napi_get_undefined(env, &result)); return result; } @@ -1162,11 +1258,12 @@ napi_value NapiWebviewController::OnInactive(napi_env env, napi_callback_info in napi_value result = nullptr; WebviewController *webviewController = GetWebviewController(env, info); if (!webviewController) { + WVLOG_E("NapiWebviewController::OnInactive get controller failed"); return nullptr; } webviewController->OnInactive(); - WVLOG_D("The web component has been successfully inactivated"); + WVLOG_I("The web component has been successfully inactivated"); NAPI_CALL(env, napi_get_undefined(env, &result)); return result; } @@ -1200,7 +1297,9 @@ napi_value NapiWebMessageExt::JsConstructor(napi_env env, napi_callback_info inf NAPI_CALL(env, napi_wrap(env, thisVar, webMessageExt, [](napi_env env, void *data, void *hint) { WebMessageExt *webMessageExt = static_cast(data); - delete webMessageExt; + if (webMessageExt) { + delete webMessageExt; + } }, nullptr, nullptr)); return thisVar; @@ -2074,6 +2173,7 @@ napi_value NapiWebMessagePort::OnMessageEventExt(napi_env env, napi_callback_inf NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&msgPort)); if (msgPort == nullptr) { WVLOG_E("set message event callback failed, napi unwrap msg port failed"); + napi_delete_reference(env, onMsgEventFunc); return nullptr; } ErrCode ret = msgPort->SetPortMessageCallback(callbackImpl); @@ -2160,12 +2260,36 @@ void NWebValueCallbackImpl::UvWebMessageOnReceiveValueCallback(uv_work_t *work, napi_close_handle_scope(data->env_, scope); } +static void InvokeWebMessageCallback(NapiWebMessagePort::WebMsgPortParam *data) +{ + napi_handle_scope scope = nullptr; + napi_open_handle_scope(data->env_, &scope); + if (scope == nullptr) { + WVLOG_E("scope is null"); + return; + } + napi_value result[INTEGER_ONE] = {0}; + if (!UvWebMsgOnReceiveCbDataHandler(data, result[INTEGER_ZERO])) { + WVLOG_E("get result failed"); + napi_close_handle_scope(data->env_, scope); + return; + } + + napi_value onMsgEventFunc = nullptr; + napi_get_reference_value(data->env_, data->callback_, &onMsgEventFunc); + napi_value placeHodler = nullptr; + napi_call_function(data->env_, nullptr, onMsgEventFunc, INTEGER_ONE, &result[INTEGER_ZERO], &placeHodler); + + napi_close_handle_scope(data->env_, scope); +} + void NWebValueCallbackImpl::OnReceiveValue(std::shared_ptr result) { WVLOG_D("message port received msg"); uv_loop_s *loop = nullptr; uv_work_t *work = nullptr; napi_get_uv_event_loop(env_, &loop); + auto engine = reinterpret_cast(env_); if (loop == nullptr) { WVLOG_E("get uv event loop failed"); return; @@ -2185,14 +2309,19 @@ void NWebValueCallbackImpl::OnReceiveValue(std::shared_ptr result) param->callback_ = callback_; param->msg_ = result; param->extention_ = extention_; - work->data = reinterpret_cast(param); - uv_queue_work_with_qos( - loop, work, [](uv_work_t* work) {}, UvWebMessageOnReceiveValueCallback, uv_qos_user_initiated); + if (pthread_self() == engine->GetTid()) { + InvokeWebMessageCallback(param); + } else { + work->data = reinterpret_cast(param); + uv_queue_work_with_qos( + loop, work, [](uv_work_t* work) {}, UvWebMessageOnReceiveValueCallback, uv_qos_user_initiated); - { - std::unique_lock lock(param->mutex_); - param->condition_.wait(lock, [¶m] { return param->ready_; }); + { + std::unique_lock lock(param->mutex_); + param->condition_.wait(lock, [¶m] { return param->ready_; }); + } } + if (param != nullptr) { delete param; param = nullptr; @@ -3171,6 +3300,53 @@ napi_value NapiWebviewController::RunJS(napi_env env, napi_callback_info info, b return RunJavaScriptInternal(env, info, script, extention); } +napi_value NapiWebviewController::RunCreatePDFExt(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_value result = nullptr; + size_t argc = INTEGER_ONE; + size_t argcPromise = INTEGER_ONE; + size_t argcCallback = INTEGER_TWO; + napi_value argv[INTEGER_TWO] = { 0 }; + + napi_get_undefined(env, &result); + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + + WebviewController* webviewController = nullptr; + napi_unwrap(env, thisVar, (void**)&webviewController); + + if (!webviewController || !webviewController->IsInit()) { + BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); + return result; + } + + std::shared_ptr pdfConfig = ParsePDFConfigArgs(env, argv[INTEGER_ZERO]); + if (pdfConfig == nullptr) { + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR); + return nullptr; + } + + if (argc == argcCallback) { + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + napi_ref jsCallback = nullptr; + napi_create_reference(env, argv[argcCallback - 1], 1, &jsCallback); + + if (jsCallback) { + webviewController->CreatePDFCallbackExt(env, pdfConfig, std::move(jsCallback)); + } + return result; + } else if (argc == argcPromise) { + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_create_promise(env, &deferred, &promise); + if (promise && deferred) { + webviewController->CreatePDFPromiseExt(env, pdfConfig, deferred); + } + return promise; + } + return result; +} + napi_value NapiWebviewController::RunJavaScriptInternal(napi_env env, napi_callback_info info, const std::string &script, bool extention) { @@ -4185,30 +4361,40 @@ napi_value NapiWebviewController::SetScrollable(napi_env env, napi_callback_info { napi_value thisVar = nullptr; napi_value result = nullptr; - size_t argc = INTEGER_ONE; - napi_value argv[INTEGER_ONE] = { 0 }; - bool isEnableScroll; + size_t argc = INTEGER_TWO; + size_t argcForOld = INTEGER_ONE; + napi_value argv[INTEGER_TWO] = { 0 }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != INTEGER_ONE) { - BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, - NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one")); + if (argc != INTEGER_TWO && argc != argcForOld) { + NWebError::BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR, + NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "one", "two")); return result; } - + bool isEnableScroll; if (!NapiParseUtils::ParseBoolean(env, argv[0], isEnableScroll)) { BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "enable", "boolean")); return result; } - WebviewController *webviewController = nullptr; - napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController); + int32_t scrollType = -1; + if (argc == INTEGER_TWO) { + if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ONE], scrollType) || scrollType < 0 || + scrollType >= INTEGER_ONE) { + WVLOG_E("BusinessError: 401. The character of 'scrollType' must be int32."); + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR); + return result; + } + } + + WebviewController* webviewController = nullptr; + napi_status status = napi_unwrap(env, thisVar, (void**)&webviewController); if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) { BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return nullptr; } - webviewController->SetScrollable(isEnableScroll); + webviewController->SetScrollable(isEnableScroll, scrollType); return result; } @@ -4537,6 +4723,10 @@ napi_value NapiWebviewController::SetDownloadDelegate(napi_env env, napi_callbac WebDownloadDelegate* delegate = nullptr; napi_value obj = argv[0]; napi_unwrap(env, obj, (void**)&delegate); + if (!delegate) { + WVLOG_E("[DOWNLOAD] WebDownloader::JS_SetDownloadDelegate delegate is null"); + return nullptr; + } napi_create_reference(env, obj, 1, &delegate->delegate_); WebviewController *webviewController = nullptr; @@ -5072,6 +5262,10 @@ napi_value NapiWebviewController::SetWebSchemeHandler(napi_env env, napi_callbac WebSchemeHandler* handler = nullptr; napi_value obj = argv[1]; napi_unwrap(env, obj, (void**)&handler); + if (!handler) { + WVLOG_E("NapiWebviewController::SetWebSchemeHandler handler is null"); + return nullptr; + } napi_create_reference(env, obj, 1, &handler->delegate_); if (!webviewController->SetWebSchemeHandler(scheme.c_str(), handler)) { @@ -5116,6 +5310,10 @@ napi_value NapiWebviewController::SetServiceWorkerWebSchemeHandler( WebSchemeHandler* handler = nullptr; napi_value obj = argv[1]; napi_unwrap(env, obj, (void**)&handler); + if (!handler) { + WVLOG_E("NapiWebviewController::SetServiceWorkerWebSchemeHandler handler is null"); + return nullptr; + } napi_create_reference(env, obj, 1, &handler->delegate_); if (!WebviewController::SetWebServiveWorkerSchemeHandler( @@ -5449,7 +5647,6 @@ napi_value NapiWebviewController::PrecompileJavaScript(napi_env env, napi_callba WebviewController* webviewController = GetWebviewController(env, info); if (!webviewController) { WVLOG_E("PrecompileJavaScript: init webview controller error."); - BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return result; } @@ -5481,6 +5678,85 @@ napi_value NapiWebviewController::PrecompileJavaScript(napi_env env, napi_callba return promise; } +napi_value NapiWebviewController::EnableBackForwardCache(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_value result = nullptr; + size_t argc = INTEGER_ONE; + napi_value argv[INTEGER_ONE] = { 0 }; + napi_get_undefined(env, &result); + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != INTEGER_ONE) { + WVLOG_E("SetBackForwardCacheOptions: wrong number of params."); + NWebHelper::Instance().EnableBackForwardCache(false, false); + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; + } + + bool nativeEmbed = false; + bool mediaTakeOver = false; + napi_value embedObj = nullptr; + napi_value mediaObj = nullptr; + if (napi_get_named_property(env, argv[INTEGER_ZERO], "nativeEmbed", &embedObj) == napi_ok) { + if (!NapiParseUtils::ParseBoolean(env, embedObj, nativeEmbed)) { + nativeEmbed = false; + } + } + + if (napi_get_named_property(env, argv[INTEGER_ZERO], "mediaTakeOver", &mediaObj) == napi_ok) { + if (!NapiParseUtils::ParseBoolean(env, mediaObj, mediaTakeOver)) { + mediaTakeOver = false; + } + } + + NWebHelper::Instance().EnableBackForwardCache(nativeEmbed, mediaTakeOver); + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; +} + +napi_value NapiWebviewController::SetBackForwardCacheOptions(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_value result = nullptr; + size_t argc = INTEGER_ONE; + napi_value argv[INTEGER_ONE] = { 0 }; + napi_get_undefined(env, &result); + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + WebviewController* webviewController = GetWebviewController(env, info); + if (!webviewController) { + WVLOG_E("SetBackForwardCacheOptions: Init webview controller error."); + return result; + } + + if (argc != INTEGER_ONE) { + WVLOG_E("SetBackForwardCacheOptions: wrong number of params."); + webviewController->SetBackForwardCacheOptions( + BFCACHE_DEFAULT_SIZE, BFCACHE_DEFAULT_TIMETOLIVE); + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; + } + + int32_t size = 1; + int32_t timeToLive = 600; + napi_value sizeObj = nullptr; + napi_value timeToLiveObj = nullptr; + if (napi_get_named_property(env, argv[INTEGER_ZERO], "size", &sizeObj) == napi_ok) { + if (!NapiParseUtils::ParseInt32(env, sizeObj, size)) { + size = BFCACHE_DEFAULT_SIZE; + } + } + + if (napi_get_named_property(env, argv[INTEGER_ZERO], "timeToLive", &timeToLiveObj) == napi_ok) { + if (!NapiParseUtils::ParseInt32(env, timeToLiveObj, timeToLive)) { + timeToLive = BFCACHE_DEFAULT_TIMETOLIVE; + } + } + + webviewController->SetBackForwardCacheOptions(size, timeToLive); + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; +} + napi_value NapiWebviewController::WarmupServiceWorker(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; @@ -5580,7 +5856,6 @@ void NapiWebviewController::AddResourceItemToMemoryCache(napi_env env, WebviewController* webviewController = GetWebviewController(env, info); if (!webviewController) { WVLOG_E("InjectOfflineResource: init webview controller error."); - BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return; } @@ -5720,7 +5995,6 @@ napi_value NapiWebviewController::EnableAdsBlock( WebviewController *webviewController = GetWebviewController(env, info); if (!webviewController) { WVLOG_E("EnableAdsBlock: init webview controller error."); - BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return result; } @@ -5832,7 +6106,6 @@ napi_value NapiWebviewController::SetUrlTrustList(napi_env env, napi_callback_in WebviewController* webviewController = GetWebviewController(env, info); if (!webviewController) { WVLOG_E("webview controller is null or not init"); - BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return result; } @@ -5950,12 +6223,13 @@ napi_value NapiWebviewController::WebPageSnapshot(napi_env env, napi_callback_in WebviewController *webviewController = GetWebviewController(env, info); if (!webviewController) { WVLOG_E("WebPageSnapshot init webview controller error."); - BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); + napi_delete_reference(env, callback); return result; } if (g_inWebPageSnapshot) { JsErrorCallback(env, std::move(callback), FUNCTION_NOT_ENABLE); + napi_delete_reference(env, callback); return result; } g_inWebPageSnapshot = true; @@ -5982,6 +6256,7 @@ napi_value NapiWebviewController::WebPageSnapshot(napi_env env, napi_callback_in env, snapshotSizeWidth, nativeSnapshotSizeWidthType, nativeSnapshotSizeWidth)) { JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR); g_inWebPageSnapshot = false; + napi_delete_reference(env, callback); return result; } } @@ -5990,6 +6265,7 @@ napi_value NapiWebviewController::WebPageSnapshot(napi_env env, napi_callback_in env, snapshotSizeHeight, nativeSnapshotSizeHeightType, nativeSnapshotSizeHeight)) { JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR); g_inWebPageSnapshot = false; + napi_delete_reference(env, callback); return result; } } @@ -6000,6 +6276,7 @@ napi_value NapiWebviewController::WebPageSnapshot(napi_env env, napi_callback_in WVLOG_E("WebPageSnapshot input different pixel unit"); JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR); g_inWebPageSnapshot = false; + napi_delete_reference(env, callback); return result; } @@ -6013,6 +6290,7 @@ napi_value NapiWebviewController::WebPageSnapshot(napi_env env, napi_callback_in WVLOG_E("WebPageSnapshot input pixel length less than 0"); JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR); g_inWebPageSnapshot = false; + napi_delete_reference(env, callback); return result; } bool pixelCheck = false; @@ -6050,7 +6328,6 @@ napi_value NapiWebviewController::SetPathAllowingUniversalAccess( WebviewController *webviewController = GetWebviewController(env, info); if (!webviewController) { WVLOG_E("SetPathAllowingUniversalAccess init webview controller error."); - BusinessError::ThrowErrorByErrcode(env, INIT_ERROR); return result; } bool isArray = false; @@ -6088,5 +6365,96 @@ napi_value NapiWebviewController::SetPathAllowingUniversalAccess( } return result; } + +napi_value NapiWebviewController::TrimMemoryByPressureLevel(napi_env env, + napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_value result = nullptr; + size_t argc = INTEGER_ONE; + napi_value argv[INTEGER_ONE] = { 0 }; + int32_t memoryLevel; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != INTEGER_ONE) { + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, + NWebError::FormatString( + ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one")); + return result; + } + + if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], memoryLevel)) { + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, + NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, + "PressureLevel", "number")); + return result; + } + + memoryLevel = memoryLevel == 1 ? 0 : memoryLevel; + NWebHelper::Instance().TrimMemoryByPressureLevel(memoryLevel); + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; +} + +napi_value NapiWebviewController::GetScrollOffset(napi_env env, + napi_callback_info info) +{ + napi_value result = nullptr; + napi_value horizontal; + napi_value vertical; + float offsetX = 0; + float offsetY = 0; + + WebviewController* webviewController = GetWebviewController(env, info); + if (!webviewController) { + return nullptr; + } + + webviewController->GetScrollOffset(&offsetX, &offsetY); + + napi_create_object(env, &result); + napi_create_double(env, static_cast(offsetX), &horizontal); + napi_create_double(env, static_cast(offsetY), &vertical); + napi_set_named_property(env, result, "horizontal", horizontal); + napi_set_named_property(env, result, "vertical", vertical); + return result; +} + +napi_value NapiWebviewController::ScrollByWithResult(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_value result = nullptr; + size_t argc = INTEGER_TWO; + napi_value argv[INTEGER_TWO] = { 0 }; + float deltaX; + float deltaY; + + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != INTEGER_TWO) { + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, + NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two")); + return result; + } + + if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ZERO], deltaX)) { + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, + NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "deltaX", "number")); + return result; + } + + if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ONE], deltaY)) { + BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, + NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "deltaY", "number")); + return result; + } + + WebviewController *webviewController = GetWebviewController(env, info); + if (!webviewController) { + return nullptr; + } + + bool scrollByWithResult = webviewController->ScrollByWithResult(deltaX, deltaY); + NAPI_CALL(env, napi_get_boolean(env, scrollByWithResult, &result)); + return result; +} } // namespace NWeb } // namespace OHOS diff --git a/interfaces/kits/napi/webviewcontroller/napi_webview_controller.h b/interfaces/kits/napi/webviewcontroller/napi_webview_controller.h index bab044a4ee8c6b4908f8ac22175005bf46e0b01e..12955ec08f38ecef58c25ac7fb035db5b9ba2728 100644 --- a/interfaces/kits/napi/webviewcontroller/napi_webview_controller.h +++ b/interfaces/kits/napi/webviewcontroller/napi_webview_controller.h @@ -40,6 +40,8 @@ const std::string WEB_PRINT_DOCUMENT_CLASS_NAME = "WebPrintDocument"; const std::string WEB_SECURITY_LEVEL_ENUM_NAME = "SecurityLevel"; const std::string WEB_RENDER_PROCESS_MODE_ENUM_NAME = "RenderProcessMode"; const std::string OFFLINE_RESOURCE_TYPE_ENUM_NAME = "OfflineResourceType"; +const std::string WEB_PRESSURE_LEVEL_ENUM_NAME = "PressureLevel"; +const std::string WEB_SCROLL_TYPE_ENUM_NAME = "ScrollType"; struct Scheme { std::string name; @@ -183,6 +185,8 @@ private: static napi_value RunJavaScriptInternalExt(napi_env env, napi_callback_info info, bool extention); + static napi_value RunCreatePDFExt(napi_env env, napi_callback_info info); + static napi_value TerminateRenderProcess(napi_env env, napi_callback_info info); static napi_value GetUrl(napi_env env, napi_callback_info info); @@ -348,6 +352,15 @@ private: static napi_value SetPathAllowingUniversalAccess(napi_env env, napi_callback_info info); + static napi_value EnableBackForwardCache(napi_env env, napi_callback_info info); + + static napi_value SetBackForwardCacheOptions(napi_env env, napi_callback_info info); + + static napi_value TrimMemoryByPressureLevel(napi_env env, napi_callback_info info); + + static napi_value GetScrollOffset(napi_env env, napi_callback_info info); + + static napi_value ScrollByWithResult(napi_env env, napi_callback_info info); static int32_t maxFdNum_; static std::atomic usedFd_; }; diff --git a/interfaces/kits/napi/webviewcontroller/native_media_player_impl.cpp b/interfaces/kits/napi/webviewcontroller/native_media_player_impl.cpp index ae5aa70a4e26eddaa944723e2dd6a3829b27fad0..a23f9415200eddd5ddf18bff6812d9c9b8ecb2f2 100644 --- a/interfaces/kits/napi/webviewcontroller/native_media_player_impl.cpp +++ b/interfaces/kits/napi/webviewcontroller/native_media_player_impl.cpp @@ -15,6 +15,7 @@ #include "native_media_player_impl.h" +#include "napi_common_macros.h" #include "napi_native_media_player.h" #include "napi_parse_utils.h" #include "nweb_log.h" @@ -30,7 +31,7 @@ void NWebNativeMediaPlayerBridgeImpl::UpdateRect(double x, double y, double widt WVLOG_D("begin to update rect,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "updateRect", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "updateRect", callback); napi_value argv[INTEGER_FOUR] = { nullptr }; NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, x, &argv[INTEGER_ZERO])); @@ -46,7 +47,7 @@ void NWebNativeMediaPlayerBridgeImpl::Play() WVLOG_D("begin to play,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "play", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "play", callback); NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); } @@ -56,7 +57,7 @@ void NWebNativeMediaPlayerBridgeImpl::Pause() WVLOG_D("begin to pause,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "pause", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "pause", callback); NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); } @@ -66,7 +67,7 @@ void NWebNativeMediaPlayerBridgeImpl::Seek(double time) WVLOG_D("begin to seek,nweb id is %{public}d,time is %{public}f", nwebId_, time); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "seek", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "seek", callback); napi_value argv[INTEGER_ONE] = { nullptr }; NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, time, &argv[INTEGER_ZERO])); @@ -79,7 +80,7 @@ void NWebNativeMediaPlayerBridgeImpl::SetVolume(double volume) WVLOG_D("begin to set volume,nweb id is %{public}d,volume is %{public}f", nwebId_, volume); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "setVolume", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "setVolume", callback); napi_value argv[INTEGER_ONE] = { nullptr }; NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, volume, &argv[INTEGER_ZERO])); @@ -92,7 +93,7 @@ void NWebNativeMediaPlayerBridgeImpl::SetMuted(bool isMuted) WVLOG_D("begin to set muted,nweb id is %{public}d,muted flag is %{public}d", nwebId_, isMuted); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "setMuted", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "setMuted", callback); napi_value argv[INTEGER_ONE] = { nullptr }; NAPI_CALL_RETURN_VOID(env_, napi_get_boolean(env_, isMuted, &argv[INTEGER_ZERO])); @@ -105,7 +106,7 @@ void NWebNativeMediaPlayerBridgeImpl::SetPlaybackRate(double playbackRate) WVLOG_D("begin to set playback rate,nweb id is %{public}d,playback rate is %{public}f", nwebId_, playbackRate); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "setPlaybackRate", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "setPlaybackRate", callback); napi_value argv[INTEGER_ONE] = { nullptr }; NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, playbackRate, &argv[INTEGER_ZERO])); @@ -118,7 +119,7 @@ void NWebNativeMediaPlayerBridgeImpl::Release() WVLOG_D("begin to release,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "release", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "release", callback); NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); } @@ -128,7 +129,7 @@ void NWebNativeMediaPlayerBridgeImpl::EnterFullScreen() WVLOG_D("begin to enter full screen,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "enterFullscreen", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "enterFullscreen", callback); NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); } @@ -138,7 +139,7 @@ void NWebNativeMediaPlayerBridgeImpl::ExitFullScreen() WVLOG_D("begin to exit full screen,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "exitFullscreen", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "exitFullscreen", callback); NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); } @@ -148,7 +149,7 @@ void NWebNativeMediaPlayerBridgeImpl::ResumeMediaPlayer() WVLOG_D("begin to resume media player,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "resumePlayer", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "resumePlayer", callback); NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); } @@ -158,12 +159,12 @@ void NWebNativeMediaPlayerBridgeImpl::SuspendMediaPlayer(SuspendType type) WVLOG_D("begin to suspend media player,nweb id is %{public}d", nwebId_); napi_value callback = nullptr; - NAPI_CALL_RETURN_VOID(env_, napi_get_named_property(env_, value_, "suspendPlayer", &callback)); + NAPI_GET_CALLBACK_RETURN_VOID(env_, value_, "suspendPlayer", callback); napi_value argv[INTEGER_ONE] = { nullptr }; NAPI_CALL_RETURN_VOID(env_, napi_create_int32(env_, static_cast(type), &argv[INTEGER_ZERO])); - NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ZERO, nullptr, nullptr)); + NAPI_CALL_RETURN_VOID(env_, napi_call_function(env_, value_, callback, INTEGER_ONE, argv, nullptr)); } NapiNativeMediaPlayerHandlerImpl::NapiNativeMediaPlayerHandlerImpl( @@ -358,21 +359,21 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructRect( { NAPI_CALL_RETURN_VOID(env_, napi_create_object(env_, value)); - napi_value x; - napi_create_double(env_, surfaceInfo->GetX(), &x); - napi_set_named_property(env_, *value, "x", x); + napi_value x = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, surfaceInfo->GetX(), &x)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "x", x)); - napi_value y; - napi_create_double(env_, surfaceInfo->GetY(), &y); - napi_set_named_property(env_, *value, "y", y); + napi_value y = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, surfaceInfo->GetY(), &y)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "y", y)); - napi_value width; - napi_create_double(env_, surfaceInfo->GetWidth(), &width); - napi_set_named_property(env_, *value, "width", width); + napi_value width = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, surfaceInfo->GetWidth(), &width)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "width", width)); - napi_value height; - napi_create_double(env_, surfaceInfo->GetHeight(), &height); - napi_set_named_property(env_, *value, "height", height); + napi_value height = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_double(env_, surfaceInfo->GetHeight(), &height)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "height", height)); } void NWebCreateNativeMediaPlayerCallbackImpl::ConstructHandler( @@ -396,9 +397,10 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructControls( NAPI_CALL_RETURN_VOID(env_, napi_create_array_with_length(env_, controls.size(), value)); for (unsigned int i = 0; i < controls.size(); i++) { - napi_value control; - napi_create_string_utf8(env_, controls[i].c_str(), controls[i].length(), &control); - napi_set_element(env_, *value, i, control); + napi_value control = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8( + env_, controls[i].c_str(), controls[i].length(), &control)); + NAPI_CALL_RETURN_VOID(env_, napi_set_element(env_, *value, i, control)); } } @@ -408,9 +410,10 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructHeaders( NAPI_CALL_RETURN_VOID(env_, napi_create_object(env_, value)); for (const auto& header : headers) { - napi_value argv; - napi_create_string_utf8(env_, header.second.c_str(), header.second.length(), &argv); - napi_set_named_property(env_, *value, header.first.c_str(), argv); + napi_value argv = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8( + env_, header.second.c_str(), header.second.length(), &argv)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, header.first.c_str(), argv)); } } @@ -420,9 +423,10 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructAttributes( NAPI_CALL_RETURN_VOID(env_, napi_create_object(env_, value)); for (const auto& attribute : attributes) { - napi_value argv; - napi_create_string_utf8(env_, attribute.second.c_str(), attribute.second.length(), &argv); - napi_set_named_property(env_, *value, attribute.first.c_str(), argv); + napi_value argv = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8( + env_, attribute.second.c_str(), attribute.second.length(), &argv)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, attribute.first.c_str(), argv)); } } @@ -431,51 +435,51 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructMediaInfo( { NAPI_CALL_RETURN_VOID(env_, napi_create_object(env_, value)); - napi_value embedId; + napi_value embedId = nullptr; std::string id = mediaInfo->GetEmbedId(); - napi_create_string_utf8(env_, id.c_str(), id.length(), &embedId); - napi_set_named_property(env_, *value, "embedID", embedId); + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8(env_, id.c_str(), id.length(), &embedId)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "embedID", embedId)); - napi_value mediaType; - napi_create_int32(env_, static_cast(mediaInfo->GetMediaType()), &mediaType); - napi_set_named_property(env_, *value, "mediaType", mediaType); + napi_value mediaType = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_int32(env_, static_cast(mediaInfo->GetMediaType()), &mediaType)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "mediaType", mediaType)); - napi_value mediaSrcList; + napi_value mediaSrcList = nullptr; ConstructSourceInfos(&mediaSrcList, mediaInfo->GetSourceInfos()); - napi_set_named_property(env_, *value, "mediaSrcList", mediaSrcList); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "mediaSrcList", mediaSrcList)); - napi_value surfaceInfo; + napi_value surfaceInfo = nullptr; ConstructSurfaceInfo(&surfaceInfo, mediaInfo->GetSurfaceInfo()); - napi_set_named_property(env_, *value, "surfaceInfo", surfaceInfo); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "surfaceInfo", surfaceInfo)); - napi_value isControlsShown; - napi_get_boolean(env_, mediaInfo->GetIsControlsShown(), &isControlsShown); - napi_set_named_property(env_, *value, "controlsShown", isControlsShown); + napi_value isControlsShown = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_get_boolean(env_, mediaInfo->GetIsControlsShown(), &isControlsShown)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "controlsShown", isControlsShown)); - napi_value controlList; + napi_value controlList = nullptr; ConstructControls(&controlList, mediaInfo->GetControls()); - napi_set_named_property(env_, *value, "controlList", controlList); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "controlList", controlList)); - napi_value headers; + napi_value headers = nullptr; ConstructHeaders(&headers, mediaInfo->GetHeaders()); - napi_set_named_property(env_, *value, "headers", headers); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "headers", headers)); - napi_value attributes; + napi_value attributes = nullptr; ConstructAttributes(&attributes, mediaInfo->GetAttributes()); - napi_set_named_property(env_, *value, "attributes", attributes); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "attributes", attributes)); - napi_value isMuted; - napi_get_boolean(env_, mediaInfo->GetIsMuted(), &isMuted); - napi_set_named_property(env_, *value, "muted", isMuted); + napi_value isMuted = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_get_boolean(env_, mediaInfo->GetIsMuted(), &isMuted)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "muted", isMuted)); - napi_value posterUrl; + napi_value posterUrl = nullptr; std::string url = mediaInfo->GetPosterUrl(); - napi_create_string_utf8(env_, url.c_str(), url.length(), &posterUrl); - napi_set_named_property(env_, *value, "posterUrl", posterUrl); + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8(env_, url.c_str(), url.length(), &posterUrl)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "posterUrl", posterUrl)); - napi_value preload; - napi_create_int32(env_, static_cast(mediaInfo->GetPreload()), &preload); - napi_set_named_property(env_, *value, "preload", preload); + napi_value preload = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_int32(env_, static_cast(mediaInfo->GetPreload()), &preload)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "preload", preload)); } void NWebCreateNativeMediaPlayerCallbackImpl::ConstructSourceInfos( @@ -488,24 +492,24 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructSourceInfos( continue; } - napi_value sourceInfo; - napi_create_object(env_, &sourceInfo); + napi_value sourceInfo = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_object(env_, &sourceInfo)); - napi_value type; - napi_create_int32(env_, static_cast(sourceInfos[i]->GetType()), &type); - napi_set_named_property(env_, sourceInfo, "type", type); + napi_value type = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_create_int32(env_, static_cast(sourceInfos[i]->GetType()), &type)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, sourceInfo, "type", type)); - napi_value source; + napi_value source = nullptr; std::string mediaSource = sourceInfos[i]->GetSource(); - napi_create_string_utf8(env_, mediaSource.c_str(), mediaSource.length(), &source); - napi_set_named_property(env_, sourceInfo, "source", source); + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8(env_, mediaSource.c_str(), mediaSource.length(), &source)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, sourceInfo, "source", source)); - napi_value format; + napi_value format = nullptr; std::string mediaFormat = sourceInfos[i]->GetFormat(); - napi_create_string_utf8(env_, mediaFormat.c_str(), mediaFormat.length(), &format); - napi_set_named_property(env_, sourceInfo, "format", format); + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8(env_, mediaFormat.c_str(), mediaFormat.length(), &format)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, sourceInfo, "format", format)); - napi_set_element(env_, *value, i, sourceInfo); + NAPI_CALL_RETURN_VOID(env_, napi_set_element(env_, *value, i, sourceInfo)); } } @@ -518,14 +522,14 @@ void NWebCreateNativeMediaPlayerCallbackImpl::ConstructSurfaceInfo( return; } - napi_value surfaceId; + napi_value surfaceId = nullptr; std::string id = surfaceInfo->GetId(); - napi_create_string_utf8(env_, id.c_str(), id.length(), &surfaceId); - napi_set_named_property(env_, *value, "id", surfaceId); + NAPI_CALL_RETURN_VOID(env_, napi_create_string_utf8(env_, id.c_str(), id.length(), &surfaceId)); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "id", surfaceId)); - napi_value rect; + napi_value rect = nullptr; ConstructRect(&rect, surfaceInfo); - napi_set_named_property(env_, *value, "rect", rect); + NAPI_CALL_RETURN_VOID(env_, napi_set_named_property(env_, *value, "rect", rect)); } } // namespace OHOS::NWeb diff --git a/interfaces/kits/napi/webviewcontroller/web_download_delegate.cpp b/interfaces/kits/napi/webviewcontroller/web_download_delegate.cpp index e882b87ff2227c0b9a56f94edcec5f2349146f75..bb2b81d5711ea92496662c6dfd75c10f09bb7b18 100644 --- a/interfaces/kits/napi/webviewcontroller/web_download_delegate.cpp +++ b/interfaces/kits/napi/webviewcontroller/web_download_delegate.cpp @@ -21,6 +21,7 @@ #include "nweb_log.h" #include "napi_web_download_item.h" #include "web_download_manager.h" +#include "nweb_napi_scope.h" namespace OHOS { namespace NWeb { @@ -38,10 +39,18 @@ WebDownloadDelegate::WebDownloadDelegate(napi_env env) WebDownloadDelegate::~WebDownloadDelegate() { WVLOG_D("[DOWNLOAD] WebDownloadDelegate::~WebDownloadDelegate"); - napi_delete_reference(env_, download_before_start_callback_); - napi_delete_reference(env_, download_did_update_callback_); - napi_delete_reference(env_, download_did_finish_callback_); - napi_delete_reference(env_, download_did_fail_callback_); + if (download_before_start_callback_) { + napi_delete_reference(env_, download_before_start_callback_); + } + if (download_did_update_callback_) { + napi_delete_reference(env_, download_did_update_callback_); + } + if (download_did_finish_callback_) { + napi_delete_reference(env_, download_did_finish_callback_); + } + if (download_did_fail_callback_) { + napi_delete_reference(env_, download_did_fail_callback_); + } WebDownloadManager::RemoveDownloadDelegate(this); } @@ -54,6 +63,8 @@ void WebDownloadDelegate::DownloadBeforeStart(WebDownloadItem *webDownloadItem) } size_t paramCount = 1; + OHOS::NApiScope scope(env_); + napi_value callbackFunc = nullptr; napi_status status; @@ -72,8 +83,10 @@ void WebDownloadDelegate::DownloadBeforeStart(WebDownloadItem *webDownloadItem) napi_wrap( env_, webDownloadItemValue, webDownloadItem, [](napi_env /* env */, void *data, void * /* hint */) { - WebDownloadItem *downloadItem = (WebDownloadItem *)data; - delete downloadItem; + if (data) { + WebDownloadItem *downloadItem = (WebDownloadItem *)data; + delete downloadItem; + } }, nullptr, nullptr); NapiWebDownloadItem::DefineProperties(env_, &webDownloadItemValue); @@ -93,6 +106,8 @@ void WebDownloadDelegate::DownloadDidUpdate(WebDownloadItem *webDownloadItem) } size_t paramCount = 1; + OHOS::NApiScope scope(env_); + napi_value callbackFunc = nullptr; napi_status status; @@ -111,8 +126,10 @@ void WebDownloadDelegate::DownloadDidUpdate(WebDownloadItem *webDownloadItem) napi_wrap( env_, webDownloadItemValue, webDownloadItem, [](napi_env /* env */, void *data, void * /* hint */) { - WebDownloadItem *downloadItem = (WebDownloadItem *)data; - delete downloadItem; + if (data) { + WebDownloadItem *downloadItem = (WebDownloadItem *)data; + delete downloadItem; + } }, nullptr, nullptr); NapiWebDownloadItem::DefineProperties(env_, &webDownloadItemValue); @@ -133,6 +150,8 @@ void WebDownloadDelegate::DownloadDidFail(WebDownloadItem *webDownloadItem) } size_t paramCount = 1; + OHOS::NApiScope scope(env_); + napi_value callbackFunc = nullptr; napi_status status; @@ -151,8 +170,10 @@ void WebDownloadDelegate::DownloadDidFail(WebDownloadItem *webDownloadItem) napi_wrap( env_, webDownloadItemValue, webDownloadItem, [](napi_env /* env */, void *data, void * /* hint */) { - WebDownloadItem *downloadItem = (WebDownloadItem *)data; - delete downloadItem; + if (data) { + WebDownloadItem *downloadItem = (WebDownloadItem *)data; + delete downloadItem; + } }, nullptr, nullptr); NapiWebDownloadItem::DefineProperties(env_, &webDownloadItemValue); @@ -173,6 +194,8 @@ void WebDownloadDelegate::DownloadDidFinish(WebDownloadItem *webDownloadItem) } size_t paramCount = 1; + OHOS::NApiScope scope(env_); + napi_value callbackFunc = nullptr; napi_status status; @@ -191,8 +214,10 @@ void WebDownloadDelegate::DownloadDidFinish(WebDownloadItem *webDownloadItem) napi_wrap( env_, webDownloadItemValue, webDownloadItem, [](napi_env /* env */, void *data, void * /* hint */) { - WebDownloadItem *downloadItem = (WebDownloadItem *)data; - delete downloadItem; + if (data) { + WebDownloadItem *downloadItem = (WebDownloadItem *)data; + delete downloadItem; + } }, nullptr, nullptr); NapiWebDownloadItem::DefineProperties(env_, &webDownloadItemValue); @@ -240,7 +265,7 @@ void WebDownloadDelegate::PutDownloadDidFail(napi_env, napi_value callback) } } -int32_t WebDownloadDelegate::GetNWebId() +int32_t WebDownloadDelegate::GetNWebId() const { return nwebId_; } diff --git a/interfaces/kits/napi/webviewcontroller/web_download_delegate.h b/interfaces/kits/napi/webviewcontroller/web_download_delegate.h index 66e14635f2cf28f96dcc2742712368ecc3980318..0dab8a9d167ea10304284dd73566aaa468ab75ec 100644 --- a/interfaces/kits/napi/webviewcontroller/web_download_delegate.h +++ b/interfaces/kits/napi/webviewcontroller/web_download_delegate.h @@ -43,7 +43,7 @@ public: void PutDownloadDidFinish(napi_env, napi_value callback); void PutDownloadDidFail(napi_env, napi_value callback); - int32_t GetNWebId(); + int32_t GetNWebId() const; void SetNWebId(int32_t nwebId); napi_env GetEnv(); diff --git a/interfaces/kits/napi/webviewcontroller/web_download_item.h b/interfaces/kits/napi/webviewcontroller/web_download_item.h index b32de22449e1d50a6ddb654a28e1a5a5b9217baf..a2533c9366918b684b8795c924167a6cde8e059f 100644 --- a/interfaces/kits/napi/webviewcontroller/web_download_item.h +++ b/interfaces/kits/napi/webviewcontroller/web_download_item.h @@ -33,11 +33,11 @@ public: ~WebDownloadItem(); long webDownloadId; - int currentSpeed; - int percentComplete; + int32_t currentSpeed; + int32_t percentComplete; int64_t totalBytes; int64_t receivedBytes; - int lastErrorCode; + int32_t lastErrorCode; std::string guid; std::string fullPath; diff --git a/interfaces/kits/napi/webviewcontroller/web_download_manager.cpp b/interfaces/kits/napi/webviewcontroller/web_download_manager.cpp index 69de158955c6548592cf2eccc541c96c8a4ef588..9c18f7fcfa9aa28b5f2370498bf0a12bfe7bb3a7 100644 --- a/interfaces/kits/napi/webviewcontroller/web_download_manager.cpp +++ b/interfaces/kits/napi/webviewcontroller/web_download_manager.cpp @@ -126,7 +126,7 @@ void WebDownloadManager::RegisterDownloadCallback() WebDownloader_SetDownloadDidUpdate(g_download_callback, &DownloadDidUpdate); WebDownloadManager_PutDownloadCallback(g_download_callback); } else { - WVLOG_E("[DOWNLOAD] had RegisterDownloadCallback."); + WVLOG_I("[DOWNLOAD] had RegisterDownloadCallback."); } } diff --git a/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.cpp b/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.cpp index e5e9ec9dbb9f5323c51c33250da816bd7985bfb5..b4525cba5d6007a23542d037852767e6ed364bb3 100644 --- a/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.cpp +++ b/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.cpp @@ -206,7 +206,7 @@ int32_t WebSchemeHandlerResponse::SetUrl(const char* url) return OH_ArkWebResponse_SetUrl(response_, url); } -int32_t WebSchemeHandlerResponse::GetStatus() +int32_t WebSchemeHandlerResponse::GetStatus() const { return OH_ArkWebResponse_GetStatus(response_); } @@ -248,7 +248,7 @@ int32_t WebSchemeHandlerResponse::SetMimeType(const char* mimeType) return OH_ArkWebResponse_SetMimeType(response_, mimeType); } -char* WebSchemeHandlerResponse::GetEncoding() +char* WebSchemeHandlerResponse::GetEncoding() const { if (!response_) { WVLOG_E("WebSchemeHandlerResponse is nullptr"); @@ -378,14 +378,16 @@ void WebSchemeHandler::RequestStart(ArkWeb_ResourceRequest* request, WVLOG_E("RequestStart, new schemeHandlerRequest failed"); return; } - WebResourceHandler* resourceHandler = new (std::nothrow) WebResourceHandler(env_, ArkWeb_ResourceHandler); + sptr resourceHandler = new (std::nothrow) WebResourceHandler(env_, ArkWeb_ResourceHandler); if (resourceHandler == nullptr) { WVLOG_E("RequestStart, new resourceHandler failed"); delete schemeHandlerRequest; return; } - if (OH_ArkWebResourceRequest_SetUserData(request, resourceHandler) != 0) { + if (OH_ArkWebResourceRequest_SetUserData(request, resourceHandler.GetRefPtr()) != 0) { WVLOG_W("OH_ArkWebResourceRequest_SetUserData failed"); + } else { + resourceHandler->IncStrongRef(nullptr); } napi_wrap( env_, requestValue[0], schemeHandlerRequest, @@ -395,12 +397,12 @@ void WebSchemeHandler::RequestStart(ArkWeb_ResourceRequest* request, }, nullptr, nullptr); NapiWebSchemeHandlerRequest::DefineProperties(env_, &requestValue[0]); napi_wrap( - env_, requestValue[1], resourceHandler, + env_, requestValue[1], resourceHandler.GetRefPtr(), [](napi_env /* env */, void *data, void * /* hint */) { - WebResourceHandler *resourceHandler = (WebResourceHandler *)data; - delete resourceHandler; + static_cast(data)->DecStrongRef(data); }, nullptr, nullptr); NapiWebResourceHandler::DefineProperties(env_, &requestValue[1]); + resourceHandler->IncStrongRef(nullptr); napi_value result = nullptr; status = napi_call_function( env_, nullptr, callbackFunc, paramCount, requestValue, &result); @@ -413,6 +415,7 @@ void WebSchemeHandler::RequestStart(ArkWeb_ResourceRequest* request, } if (!*intercept) { resourceHandler->SetFinishFlag(); + resourceHandler->DecStrongRef(resourceHandler); } napi_close_handle_scope(env_, scope); } @@ -475,6 +478,7 @@ void WebSchemeHandler::RequestStopAfterWorkCb(uv_work_t* work, int status) OH_ArkWebResourceRequest_GetUserData(param->arkWebRequest_)); if (resourceHandler) { resourceHandler->SetFinishFlag(); + resourceHandler->DecStrongRef(resourceHandler); } napi_close_handle_scope(param->env_, scope); delete param; @@ -737,11 +741,11 @@ void WebHttpBodyStream::ExecuteInitComplete(napi_env env, napi_status status, vo { WVLOG_D("WebHttpBodyStream::ExecuteInitComplete"); InitParam* param = static_cast(data); - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); if (!param) { return; } + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); if (!scope) { delete param; return; @@ -774,11 +778,11 @@ void WebHttpBodyStream::ExecuteReadComplete(napi_env env, napi_status status, vo { WVLOG_D("WebHttpBodyStream::ExecuteReadComplete"); ReadParam* param = static_cast(data); - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); if (!param) { return; } + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); if (!scope) { delete param; return; @@ -831,17 +835,17 @@ void WebHttpBodyStream::ExecuteRead(uint8_t* buffer, int bytesRead) napi_queue_async_work_with_qos(env_, param->asyncWork, napi_qos_user_initiated)); } -uint64_t WebHttpBodyStream::GetPostion() +uint64_t WebHttpBodyStream::GetPostion() const { return OH_ArkWebHttpBodyStream_GetPosition(stream_); } -uint64_t WebHttpBodyStream::GetSize() +uint64_t WebHttpBodyStream::GetSize() const { return OH_ArkWebHttpBodyStream_GetSize(stream_); } -bool WebHttpBodyStream::IsChunked() +bool WebHttpBodyStream::IsChunked() const { return OH_ArkWebHttpBodyStream_IsChunked(stream_); } diff --git a/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.h b/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.h index 9277f6e5a6266a49792172b0650ddd6613818182..a447c47f1f7a293327e4e5a9688cd878f0d75a00 100644 --- a/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.h +++ b/interfaces/kits/napi/webviewcontroller/web_scheme_handler_request.h @@ -24,6 +24,7 @@ #include "napi/native_node_api.h" #include "arkweb_scheme_handler.h" +#include "refbase.h" namespace OHOS { namespace NWeb { @@ -66,13 +67,13 @@ public: char* GetUrl(); int32_t SetUrl(const char* url); - int32_t GetStatus(); + int32_t GetStatus() const; int32_t SetStatus(int32_t status); char* GetStatusText(); int32_t SetStatusText(const char* statusText); char* GetMimeType(); int32_t SetMimeType(const char* mimeType); - char* GetEncoding(); + char* GetEncoding() const; int32_t SetEncoding(const char* encoding); char* GetHeaderByName(const char* name); int32_t SetHeaderByName(const char* name, const char* value, bool overwrite); @@ -114,6 +115,7 @@ private: typedef struct RequestStopParam { napi_env env_; napi_ref callbackRef_; + napi_ref requestValueRef_; WebSchemeHandlerRequest* request_; const ArkWeb_ResourceRequest* arkWebRequest_; } RequestStopParam; @@ -127,7 +129,7 @@ private: napi_ref request_stop_callback_ = nullptr; }; -class WebResourceHandler { +class WebResourceHandler : public RefBase { public: explicit WebResourceHandler(napi_env env); WebResourceHandler(napi_env env, const ArkWeb_ResourceHandler* handler); @@ -158,9 +160,9 @@ public: ~WebHttpBodyStream(); void Init(napi_ref jsCallback, napi_deferred deferred); void Read(int bufLen, napi_ref jsCallback, napi_deferred deferred); - uint64_t GetPostion(); - uint64_t GetSize(); - bool IsChunked(); + uint64_t GetPostion() const; + uint64_t GetSize() const; + bool IsChunked() const; bool IsEof(); bool IsInMemory(); diff --git a/interfaces/kits/napi/webviewcontroller/webview_controller.cpp b/interfaces/kits/napi/webviewcontroller/webview_controller.cpp index 8541e8e1f735da55f50e365d5a052e76292110a5..0519275b11d453f08734c6a5f39af29cd9166782 100644 --- a/interfaces/kits/napi/webviewcontroller/webview_controller.cpp +++ b/interfaces/kits/napi/webviewcontroller/webview_controller.cpp @@ -32,6 +32,7 @@ #include "nweb_log.h" #include "nweb_store_web_archive_callback.h" #include "web_errors.h" +#include "webview_createpdf_execute_callback.h" #include "webview_hasimage_callback.h" #include "webview_javascript_execute_callback.h" #include "webview_javascript_result_callback.h" @@ -86,6 +87,7 @@ bool GetAppBundleNameAndModuleName(std::string& bundleName, std::string& moduleN } } using namespace NWebError; +std::mutex g_objectMtx; std::unordered_map g_webview_controller_map; std::string WebviewController::customeSchemeCmdLine_ = ""; bool WebviewController::existNweb_ = false; @@ -96,7 +98,7 @@ int32_t WebviewController::webTagStrId_ = 0; WebviewController::WebviewController(int32_t nwebId) : nwebId_(nwebId) { if (IsInit()) { - std::unique_lock lk(webMtx_); + std::unique_lock lk(g_objectMtx); g_webview_controller_map.emplace(nwebId, this); } } @@ -108,14 +110,14 @@ WebviewController::WebviewController(const std::string& webTag) : webTag_(webTag WebviewController::~WebviewController() { - std::unique_lock lk(webMtx_); + std::unique_lock lk(g_objectMtx); g_webview_controller_map.erase(nwebId_); } void WebviewController::SetWebId(int32_t nwebId) { nwebId_ = nwebId; - std::unique_lock lk(webMtx_); + std::unique_lock lk(g_objectMtx); g_webview_controller_map.emplace(nwebId, this); if (webTag_.empty()) { @@ -140,7 +142,7 @@ void WebviewController::SetWebId(int32_t nwebId) WebviewController* WebviewController::FromID(int32_t nwebId) { - std::unique_lock lk(webMtx_); + std::unique_lock lk(g_objectMtx); if (auto it = g_webview_controller_map.find(nwebId); it != g_webview_controller_map.end()) { auto control = it->second; return control; @@ -197,12 +199,12 @@ void WebviewController::InnerCompleteWindowNew(int32_t parentNwebId) } } -bool WebviewController::IsInit() +bool WebviewController::IsInit() const { return NWebHelper::Instance().GetNWeb(nwebId_) ? true : false; } -bool WebviewController::AccessForward() +bool WebviewController::AccessForward() const { bool access = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -214,7 +216,7 @@ bool WebviewController::AccessForward() return access; } -bool WebviewController::AccessBackward() +bool WebviewController::AccessBackward() const { bool access = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -224,7 +226,7 @@ bool WebviewController::AccessBackward() return access; } -bool WebviewController::AccessStep(int32_t step) +bool WebviewController::AccessStep(int32_t step) const { bool access = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -588,7 +590,7 @@ std::string WebviewController::GenerateWebTag() } bool WebviewController::GetRawFileUrl(const std::string &fileName, - const std::string& bundleName, const std::string& moduleName, std::string &result) + const std::string& bundleName, const std::string& moduleName, std::string &result) const { if (fileName.empty()) { WVLOG_E("File name is empty."); @@ -616,11 +618,11 @@ bool WebviewController::GetRawFileUrl(const std::string &fileName, } result += fileName; } - WVLOG_D("The parsed url is: %{public}s", result.c_str()); + WVLOG_D("The parsed url is: ***"); return true; } -bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result) +bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result) const { napi_valuetype valueType = napi_null; napi_typeof(env, urlObj, &valueType); @@ -630,7 +632,7 @@ bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& r } if (valueType == napi_string) { NapiParseUtils::ParseString(env, urlObj, result); - WVLOG_D("The parsed url is: %{public}s", result.c_str()); + WVLOG_D("The parsed url is: ***"); return true; } napi_value type = nullptr; @@ -656,7 +658,7 @@ bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& r return false; } -bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) +bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const { napi_value paraArray = nullptr; napi_get_named_property(env, urlObj, "params", ¶Array); @@ -681,7 +683,7 @@ bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::st return GetRawFileUrl(fileName, bundleName, moduleName, result); } -bool WebviewController::GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) +bool WebviewController::GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const { napi_value resIdObj = nullptr; napi_value bundleNameObj = nullptr; @@ -829,7 +831,7 @@ void WebviewController::EnableSafeBrowsing(bool enable) } } -bool WebviewController::IsSafeBrowsingEnabled() +bool WebviewController::IsSafeBrowsingEnabled() const { bool isSafeBrowsingEnabled = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1050,6 +1052,47 @@ void WebviewController::RunJavaScriptPromiseExt( nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention); } +void WebviewController::CreatePDFCallbackExt( + napi_env env, std::shared_ptr pdfConfig, napi_ref pdfCallback) +{ + auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + napi_value setResult[RESULT_COUNT] = { 0 }; + setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR); + napi_get_null(env, &setResult[PARAMONE]); + + napi_value args[RESULT_COUNT] = { setResult[PARAMZERO], setResult[PARAMONE] }; + napi_value callback = nullptr; + napi_get_reference_value(env, pdfCallback, &callback); + napi_value callbackResult = nullptr; + napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult); + napi_delete_reference(env, pdfCallback); + return; + } + if (pdfCallback == nullptr) { + return; + } + auto callbackImpl = std::make_shared(env, pdfCallback, nullptr); + nweb_ptr->ExecuteCreatePDFExt(pdfConfig, callbackImpl); +} + +void WebviewController::CreatePDFPromiseExt( + napi_env env, std::shared_ptr pdfConfig, napi_deferred deferred) +{ + auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + napi_value pdfResult = nullptr; + pdfResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR); + napi_reject_deferred(env, deferred, pdfResult); + return; + } + if (deferred == nullptr) { + return; + } + auto callbackImpl = std::make_shared(env, nullptr, deferred); + nweb_ptr->ExecuteCreatePDFExt(pdfConfig, callbackImpl); +} + std::string WebviewController::GetUrl() { std::string url = ""; @@ -1070,7 +1113,7 @@ std::string WebviewController::GetOriginalUrl() return url; } -bool WebviewController::TerminateRenderProcess() +bool WebviewController::TerminateRenderProcess() const { bool ret = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1170,7 +1213,7 @@ int32_t WebHistoryList::GetListSize() } bool WebviewController::GetFavicon( - const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) + const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const { bool isGetFavicon = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1190,7 +1233,7 @@ std::vector WebviewController::SerializeWebState() return empty; } -bool WebviewController::RestoreWebState(const std::vector &state) +bool WebviewController::RestoreWebState(const std::vector &state) const { bool isRestored = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1258,7 +1301,7 @@ void WebviewController::SetScrollable(bool enable) return setting->SetScrollable(enable); } -bool WebviewController::GetScrollable() +bool WebviewController::GetScrollable() const { auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); if (!nweb_ptr) { @@ -1276,7 +1319,7 @@ void WebviewController::InnerSetHapPath(const std::string &hapPath) hapPath_ = hapPath; } -bool WebviewController::GetCertChainDerData(std::vector &certChainDerData) +bool WebviewController::GetCertChainDerData(std::vector &certChainDerData) const { auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); if (!nweb_ptr) { @@ -1406,7 +1449,7 @@ int WebviewController::GetSecurityLevel() return static_cast(securityLevel); } -bool WebviewController::IsIncognitoMode() +bool WebviewController::IsIncognitoMode() const { bool incognitoMode = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1424,7 +1467,7 @@ void WebviewController::SetPrintBackground(bool enable) } } -bool WebviewController::GetPrintBackground() +bool WebviewController::GetPrintBackground() const { bool printBackgroundEnabled = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1443,7 +1486,7 @@ void WebviewController::EnableIntelligentTrackingPrevention(bool enable) } } -bool WebviewController::IsIntelligentTrackingPreventionEnabled() +bool WebviewController::IsIntelligentTrackingPreventionEnabled() const { bool enabled = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1458,7 +1501,7 @@ void WebPrintWriteResultCallbackAdapter::WriteResultCallback(std::string jobId, cb_(jobId, code); } -bool WebviewController::SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) +bool WebviewController::SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const { if (!handler || !scheme) { WVLOG_E("WebviewController::SetWebSchemeHandler handler or scheme is nullptr"); @@ -1623,7 +1666,7 @@ void WebviewController::PrecompileJavaScriptPromise( bool WebviewController::ParseResponseHeaders(napi_env env, napi_value value, - std::map &responseHeaders) + std::map &responseHeaders) const { bool isArray = false; napi_is_array(env, value, &isArray); @@ -1673,15 +1716,15 @@ ParseURLResult WebviewController::ParseURLList(napi_env env, napi_value value, s return ParseURLResult::OK; } -bool WebviewController::CheckURL(std::string& url) +bool WebviewController::CheckURL(std::string& url) const { if (url.size() > URL_MAXIMUM) { - WVLOG_E("The URL exceeds the maximum length of %{public}d. URL: %{public}s", URL_MAXIMUM, url.c_str()); + WVLOG_E("The URL exceeds the maximum length of %{public}d. URL: %{private}s", URL_MAXIMUM, url.c_str()); return false; } if (!regex_match(url, std::regex("^http(s)?:\\/\\/.+", std::regex_constants::icase))) { - WVLOG_E("The Parse URL error. URL: %{public}s", url.c_str()); + WVLOG_E("The Parse URL error. URL: %{private}s", url.c_str()); return false; } @@ -1743,7 +1786,7 @@ void WebviewController::EnableAdsBlock(bool enable) } } -bool WebviewController::IsAdsBlockEnabled() +bool WebviewController::IsAdsBlockEnabled() const { bool enabled = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1753,7 +1796,7 @@ bool WebviewController::IsAdsBlockEnabled() return enabled; } -bool WebviewController::IsAdsBlockEnabledForCurPage() +bool WebviewController::IsAdsBlockEnabledForCurPage() const { bool enabled = false; auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); @@ -1808,7 +1851,7 @@ ErrCode WebviewController::SetUrlTrustList(const std::string& urlTrustList, std: return ret; } bool WebviewController::ParseJsLengthResourceToInt( - napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) + napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const { napi_value resIdObj = nullptr; int32_t resId; @@ -1862,7 +1905,7 @@ bool WebviewController::ParseJsLengthResourceToInt( } bool WebviewController::ParseJsLengthToInt( - napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) + napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const { napi_valuetype jsType = napi_null; napi_typeof(env, jsLength, &jsType); @@ -1973,5 +2016,127 @@ void WebviewController::ScrollByWithAnime(float deltaX, float deltaY, int32_t du } return; } + +void WebviewController::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) +{ + auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return; + } + + nweb_ptr->SetBackForwardCacheOptions(size, timeToLive); +} + +void WebviewController::GetScrollOffset(float* offset_x, float* offset_y) +{ + auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + nweb_ptr->GetScrollOffset(offset_x, offset_y); + } +} + +bool WebviewController::ScrollByWithResult(float deltaX, float deltaY) const +{ + bool enabled = false; + auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); + if (nweb_ptr) { + enabled = nweb_ptr->ScrollByWithResult(deltaX, deltaY); + } + return enabled; +} + +void WebviewController::SetScrollable(bool enable, int32_t scrollType) +{ + auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_); + if (!nweb_ptr) { + return; + } + std::shared_ptr setting = nweb_ptr->GetPreference(); + if (!setting) { + return; + } + return setting->SetScrollable(enable, scrollType); +} + +void WebMessageExt::SetType(int type) +{ + type_ = type; + WebMessageType jsType = static_cast(type); + NWebValue::Type nwebType = NWebValue::Type::NONE; + switch (jsType) { + case WebMessageType::STRING: { + nwebType = NWebValue::Type::STRING; + break; + } + case WebMessageType::NUMBER: { + nwebType = NWebValue::Type::DOUBLE; + break; + } + case WebMessageType::BOOLEAN: { + nwebType = NWebValue::Type::BOOLEAN; + break; + } + case WebMessageType::ARRAYBUFFER: { + nwebType = NWebValue::Type::BINARY; + break; + } + case WebMessageType::ARRAY: { + nwebType = NWebValue::Type::STRINGARRAY; + break; + } + case WebMessageType::ERROR: { + nwebType = NWebValue::Type::ERROR; + break; + } + default: { + nwebType = NWebValue::Type::NONE; + break; + } + } + if (data_) { + data_->SetType(nwebType); + } +} + +int WebMessageExt::ConvertNwebType2JsType(NWebValue::Type type) +{ + WebMessageType jsType = WebMessageType::NOTSUPPORT; + switch (type) { + case NWebValue::Type::STRING: { + jsType = WebMessageType::STRING; + break; + } + case NWebValue::Type::DOUBLE: + case NWebValue::Type::INTEGER: { + jsType = WebMessageType::NUMBER; + break; + } + case NWebValue::Type::BOOLEAN: { + jsType = WebMessageType::BOOLEAN; + break; + } + case NWebValue::Type::STRINGARRAY: + case NWebValue::Type::DOUBLEARRAY: + case NWebValue::Type::INT64ARRAY: + case NWebValue::Type::BOOLEANARRAY: { + jsType = WebMessageType::ARRAY; + break; + } + case NWebValue::Type::BINARY: { + jsType = WebMessageType::ARRAYBUFFER; + break; + } + case NWebValue::Type::ERROR: { + jsType = WebMessageType::ERROR; + break; + } + default: { + jsType = WebMessageType::NOTSUPPORT; + break; + } + } + return static_cast(jsType); +} + } // namespace NWeb } // namespace OHOS diff --git a/interfaces/kits/napi/webviewcontroller/webview_controller.h b/interfaces/kits/napi/webviewcontroller/webview_controller.h index d9f804eaead3774130d1d87f6a9ccc2a5a8b9bf6..26f6e4911eafc2a3cb33cdc129dee9993be49c8f 100644 --- a/interfaces/kits/napi/webviewcontroller/webview_controller.h +++ b/interfaces/kits/napi/webviewcontroller/webview_controller.h @@ -21,6 +21,7 @@ #include #include +#include "back_forward_cache_options.h" #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" @@ -116,6 +117,15 @@ enum class UrlListSetResult : int { SET_OK = 0, }; +enum class PressureLevel : int { + MEMORY_PRESSURE_LEVEL_MODERATE = 1, + MEMORY_PRESSURE_LEVEL_CRITICAL = 2, +}; + +enum class ScrollType : int { + EVENT = 0, +}; + class WebPrintDocument; class WebviewController { public: @@ -124,17 +134,17 @@ public: explicit WebviewController(const std::string& webTag); ~WebviewController(); - bool IsInit(); + bool IsInit() const; void SetWebId(int32_t nwebId); WebviewController* FromID(int32_t nwebId); - bool AccessForward(); + bool AccessForward() const; - bool AccessBackward(); + bool AccessBackward() const; - bool AccessStep(int32_t step); + bool AccessStep(int32_t step) const; void ClearHistory(); @@ -178,7 +188,7 @@ public: void RequestFocus(); - bool ParseUrl(napi_env env, napi_value urlObj, std::string& result); + bool ParseUrl(napi_env env, napi_value urlObj, std::string& result) const; ErrCode LoadUrl(std::string url); @@ -226,7 +236,7 @@ public: std::string GetOriginalUrl(); - bool TerminateRenderProcess(); + bool TerminateRenderProcess() const; void PutNetworkAvailable(bool available); @@ -241,11 +251,11 @@ public: std::shared_ptr GetHistoryList(); bool GetFavicon( - const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType); + const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const; std::vector SerializeWebState(); - bool RestoreWebState(const std::vector &state); + bool RestoreWebState(const std::vector &state) const; void ScrollPageDown(bool bottom); @@ -259,11 +269,13 @@ public: void SetScrollable(bool enable); - bool GetScrollable(); + void SetScrollable(bool enable, int32_t scrollType); + + bool GetScrollable() const; void InnerSetHapPath(const std::string &hapPath); - bool GetCertChainDerData(std::vector &certChainDerData); + bool GetCertChainDerData(std::vector &certChainDerData) const; ErrCode SetAudioMuted(bool muted); @@ -277,19 +289,19 @@ public: void EnableSafeBrowsing(bool enable); - bool IsSafeBrowsingEnabled(); + bool IsSafeBrowsingEnabled() const; - bool IsIncognitoMode(); + bool IsIncognitoMode() const; void SetPrintBackground(bool enable); - bool GetPrintBackground(); + bool GetPrintBackground() const; std::string GetLastJavascriptProxyCallingFrameUrl(); static std::string GenerateWebTag(); - bool SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler); + bool SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const; int32_t ClearWebSchemeHandler(); @@ -310,7 +322,7 @@ public: void EnableIntelligentTrackingPrevention(bool enable); - bool IsIntelligentTrackingPreventionEnabled(); + bool IsIntelligentTrackingPreventionEnabled() const; ErrCode StartCamera(); @@ -331,11 +343,11 @@ public: bool ParseResponseHeaders(napi_env env, napi_value value, - std::map &responseHeaders); + std::map &responseHeaders) const; ParseURLResult ParseURLList(napi_env env, napi_value value, std::vector& urlList); - bool CheckURL(std::string& url); + bool CheckURL(std::string& url) const; std::vector ParseUint8Array(napi_env env, napi_value value); @@ -348,9 +360,9 @@ public: void EnableAdsBlock(bool enable); - bool IsAdsBlockEnabled(); + bool IsAdsBlockEnabled() const; - bool IsAdsBlockEnabledForCurPage(); + bool IsAdsBlockEnabledForCurPage() const; std::string GetSurfaceId(); @@ -359,7 +371,7 @@ public: bool ParseJsLengthToInt(napi_env env, napi_value jsLength, PixelUnit& type, - int32_t& result); + int32_t& result) const; ErrCode WebPageSnapshot(const char* id, PixelUnit type, @@ -373,20 +385,32 @@ public: void ScrollToWithAnime(float x, float y, int32_t duration) ; void ScrollByWithAnime(float deltaX, float deltaY, int32_t duration) ; + + void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive); + + void GetScrollOffset(float* offset_x, float* offset_y); + + void CreatePDFCallbackExt( + napi_env env, std::shared_ptr pdfConfig, napi_ref pdfCallback); + + void CreatePDFPromiseExt( + napi_env env, std::shared_ptr pdfConfig, napi_deferred deferred); + + bool ScrollByWithResult(float deltaX, float deltaY) const; private: int ConverToWebHitTestType(int hitType); bool GetRawFileUrl(const std::string &fileName, - const std::string& bundleName, const std::string& moduleName, std::string &result); + const std::string& bundleName, const std::string& moduleName, std::string &result) const; - bool ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result); + bool ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const; - bool GetResourceUrl(napi_env env, napi_value urlObj, std::string& result); + bool GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const; bool ParseJsLengthResourceToInt(napi_env env, napi_value jsLength, PixelUnit& type, - int32_t& result); + int32_t& result) const; bool GetHapModuleInfo(); public: @@ -435,85 +459,9 @@ public: explicit WebMessageExt(std::shared_ptr data) : data_(data) {}; ~WebMessageExt() = default; - void SetType(int type) - { - type_ = type; - WebMessageType jsType = static_cast(type); - NWebValue::Type nwebType = NWebValue::Type::NONE; - switch (jsType) { - case WebMessageType::STRING: { - nwebType = NWebValue::Type::STRING; - break; - } - case WebMessageType::NUMBER: { - nwebType = NWebValue::Type::DOUBLE; - break; - } - case WebMessageType::BOOLEAN: { - nwebType = NWebValue::Type::BOOLEAN; - break; - } - case WebMessageType::ARRAYBUFFER: { - nwebType = NWebValue::Type::BINARY; - break; - } - case WebMessageType::ARRAY: { - nwebType = NWebValue::Type::STRINGARRAY; - break; - } - case WebMessageType::ERROR: { - nwebType = NWebValue::Type::ERROR; - break; - } - default: { - nwebType = NWebValue::Type::NONE; - break; - } - } - if (data_) { - data_->SetType(nwebType); - } - } + void SetType(int type); - int ConvertNwebType2JsType(NWebValue::Type type) - { - WebMessageType jsType = WebMessageType::NOTSUPPORT; - switch (type) { - case NWebValue::Type::STRING: { - jsType = WebMessageType::STRING; - break; - } - case NWebValue::Type::DOUBLE: - case NWebValue::Type::INTEGER: { - jsType = WebMessageType::NUMBER; - break; - } - case NWebValue::Type::BOOLEAN: { - jsType = WebMessageType::BOOLEAN; - break; - } - case NWebValue::Type::STRINGARRAY: - case NWebValue::Type::DOUBLEARRAY: - case NWebValue::Type::INT64ARRAY: - case NWebValue::Type::BOOLEANARRAY: { - jsType = WebMessageType::ARRAY; - break; - } - case NWebValue::Type::BINARY: { - jsType = WebMessageType::ARRAYBUFFER; - break; - } - case NWebValue::Type::ERROR: { - jsType = WebMessageType::ERROR; - break; - } - default: { - jsType = WebMessageType::NOTSUPPORT; - break; - } - } - return static_cast(jsType); - } + int ConvertNwebType2JsType(NWebValue::Type type); int GetType() { @@ -596,7 +544,7 @@ public: } } - std::shared_ptr GetData() + std::shared_ptr GetData() const { return data_; } diff --git a/interfaces/kits/napi/webviewcontroller/webview_createpdf_execute_callback.cpp b/interfaces/kits/napi/webviewcontroller/webview_createpdf_execute_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b83e8d1f9b02b0c81016ae6a3940df195ce6a823 --- /dev/null +++ b/interfaces/kits/napi/webviewcontroller/webview_createpdf_execute_callback.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "business_error.h" +#include "napi_parse_utils.h" +#include "nweb_log.h" +#include "web_errors.h" +#include "webview_createpdf_execute_callback.h" +namespace OHOS::NWeb { +using namespace NWebError; +const std::string JS_EXT_ARR_CLASS_NAME = "PdfData"; +thread_local napi_ref g_jsArrExtClassRef; +// static +void WebviewCreatePDFExecuteCallback::InitJSExcute(napi_env env, napi_value exports) +{ + napi_value jsArrExtClass = nullptr; + napi_property_descriptor jsArrExtClsProperties[] = { DECLARE_NAPI_FUNCTION( + "pdfArrayBuffer", NapiArrayBufferExt::GetArrayBuffer) }; + napi_define_class(env, JS_EXT_ARR_CLASS_NAME.c_str(), JS_EXT_ARR_CLASS_NAME.length(), + NapiArrayBufferExt::JsConstructor, nullptr, sizeof(jsArrExtClsProperties) / sizeof(jsArrExtClsProperties[0]), + jsArrExtClsProperties, &jsArrExtClass); + napi_create_reference(env, jsArrExtClass, 1, &g_jsArrExtClassRef); + napi_set_named_property(env, exports, JS_EXT_ARR_CLASS_NAME.c_str(), jsArrExtClass); +} + +void WebviewCreatePDFExecuteCallback::OnReceiveValue(const char* result, const long size) +{ + uv_loop_s* loop = nullptr; + uv_work_t* work = nullptr; + + napi_get_uv_event_loop(env_, &loop); + if (loop == nullptr) { + return; + } + work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + return; + } + + ArrayBufferExecuteParam* param = new (std::nothrow) ArrayBufferExecuteParam(); + if (param == nullptr) { + delete work; + return; + } + param->env_ = env_; + param->callbackRef_ = callbackRef_; + param->deferred_ = deferred_; + param->result_ = new (std::nothrow) char[size + 1]; + if (memcpy_s(param->result_, size, result, size) != 0) { + WVLOG_E("[CreatePDF] memcpy failed"); + delete param->result_; + param->result_ = nullptr; + delete param; + param = nullptr; + delete work; + work = nullptr; + return; + } + param->size_ = size; + + work->data = reinterpret_cast(param); + + int ret = uv_queue_work_with_qos( + loop, work, [](uv_work_t* work) {}, UvAfterWorkCb, uv_qos_user_initiated); + if (ret != 0) { + if (param != nullptr) { + delete param->result_; + param->result_ = nullptr; + delete param; + param = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } +} + +void WebviewCreatePDFExecuteCallback::UvAfterWorkCb(uv_work_t* work, int status) +{ + (void)status; + if (!work) { + return; + } + ArrayBufferExecuteParam* param = reinterpret_cast(work->data); + if (!param) { + delete work; + work = nullptr; + delete param->result_; + param->result_ = nullptr; + delete param; + param = nullptr; + return; + } + napi_handle_scope scope = nullptr; + napi_open_handle_scope(param->env_, &scope); + if (scope == nullptr) { + delete work; + work = nullptr; + delete param->result_; + param->result_ = nullptr; + delete param; + param = nullptr; + return; + } + if (param->callbackRef_) { + UvAfterWorkCbAsync(param->env_, param->callbackRef_, param->result_, param->size_); + } else if (param->deferred_) { + UvAfterWorkCbPromise(param->env_, param->deferred_, param->result_, param->size_); + } + + napi_close_handle_scope(param->env_, scope); + delete param->result_; + param->result_ = nullptr; + delete param; + param = nullptr; + delete work; + work = nullptr; +} + +void WebviewCreatePDFExecuteCallback::UvAfterWorkCbAsync( + napi_env env, napi_ref callbackRef, const char* result, const long size) +{ + napi_value setResult[INTEGER_TWO] = { 0 }; + + if (result == nullptr) { + setResult[INTEGER_ZERO] = BusinessError::CreateError(env, NWebError::INVALID_RESOURCE); + napi_get_null(env, &setResult[INTEGER_ONE]); + } else { + napi_get_undefined(env, &setResult[INTEGER_ZERO]); + napi_value jsArrExt = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, g_jsArrExtClassRef, &jsArrExt)); + NAPI_CALL_RETURN_VOID(env, napi_new_instance(env, jsArrExt, 0, NULL, &setResult[INTEGER_ONE])); + + WebJsArrayBufferExt* webArrayBufferExt = new (std::nothrow) WebJsArrayBufferExt(result, size); + if (webArrayBufferExt == nullptr) { + WVLOG_E("new WebJsArrayBufferExt failed."); + return; + } + + napi_status status = napi_wrap( + env, setResult[INTEGER_ONE], webArrayBufferExt, + [](napi_env env, void* data, void* hint) { + WebJsArrayBufferExt* webArrayBufferExt = static_cast(data); + delete webArrayBufferExt; + webArrayBufferExt = nullptr; + }, + nullptr, nullptr); + if (status != napi_status::napi_ok) { + WVLOG_E("napi_wrap failed"); + return; + } + } + napi_value args[INTEGER_TWO] = { setResult[INTEGER_ZERO], setResult[INTEGER_ONE] }; + napi_value callback = nullptr; + napi_value callbackResult = nullptr; + + napi_get_reference_value(env, callbackRef, &callback); + napi_call_function(env, nullptr, callback, INTEGER_TWO, args, &callbackResult); + napi_delete_reference(env, callbackRef); +} + +void WebviewCreatePDFExecuteCallback::UvAfterWorkCbPromise( + napi_env env, napi_deferred deferred, const char* result, const long size) +{ + napi_value setResult[INTEGER_TWO] = { 0 }; + setResult[INTEGER_ZERO] = NWebError::BusinessError::CreateError(env, NWebError::INVALID_RESOURCE); + + napi_value jsArrExt = nullptr; + napi_status status = napi_get_reference_value(env, g_jsArrExtClassRef, &jsArrExt); + if (status != napi_status::napi_ok) { + WVLOG_E("napi_get_reference_value failed."); + return; + } + status = napi_new_instance(env, jsArrExt, 0, NULL, &setResult[INTEGER_ONE]); + if (status != napi_status::napi_ok) { + WVLOG_E("napi_new_instance failed."); + return; + } + WebJsArrayBufferExt* webArrayBufferExt = new (std::nothrow) WebJsArrayBufferExt(result, size); + if (webArrayBufferExt == nullptr) { + WVLOG_E("new WebJsArrayBufferExt failed."); + return; + } + + status = napi_wrap( + env, setResult[INTEGER_ONE], webArrayBufferExt, + [](napi_env env, void* data, void* hint) { + WebJsArrayBufferExt* webArrayBufferExt = static_cast(data); + delete webArrayBufferExt; + webArrayBufferExt = nullptr; + }, + nullptr, nullptr); + if (status != napi_status::napi_ok) { + WVLOG_E("napi_wrap failed."); + return; + } + + napi_value args[INTEGER_TWO] = { setResult[INTEGER_ZERO], setResult[INTEGER_ONE] }; + if (result == nullptr) { + napi_reject_deferred(env, deferred, args[INTEGER_ZERO]); + } else { + napi_resolve_deferred(env, deferred, args[INTEGER_ONE]); + } +} + +napi_value NapiArrayBufferExt::JsConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; +} + +napi_value NapiArrayBufferExt::GetArrayBuffer(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_value result = nullptr; + size_t argc = INTEGER_ONE; + napi_value argv[INTEGER_ONE] = { 0 }; + + WebJsArrayBufferExt* webArrayBufferExt = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_CALL(env, napi_unwrap(env, thisVar, (void**)&webArrayBufferExt)); + if (webArrayBufferExt == nullptr) { + WVLOG_E("unwrap webArrayBufferExt failed."); + return result; + } + + const char* pdfResult = webArrayBufferExt->GetPDFResult(); + const long size = webArrayBufferExt->GetPDFSize(); + napi_value arraybuffer = nullptr; + void* bufferData = nullptr; + + napi_status status = napi_create_arraybuffer(env, size, &bufferData, &arraybuffer); + if (status != napi_ok) { + WVLOG_E("[CreatePDF] create array buffer failed, status: %{public}d", status); + return nullptr; + } + if (memcpy_s(bufferData, size, pdfResult, size) != 0) { + WVLOG_E("[CreatePDF] memcpy failed"); + return nullptr; + } + status = napi_create_typedarray(env, napi_typedarray_type::napi_uint8_array, size, arraybuffer, 0, &result); + if (status != napi_ok) { + WVLOG_E("[CreatePDF] create typed array failed, status: %{public}d", status); + return nullptr; + } + napi_ref arraybufferRef; + napi_create_reference(env, arraybuffer, 1, &arraybufferRef); + + return result; +} + +} // namespace OHOS::NWeb diff --git a/interfaces/kits/napi/webviewcontroller/webview_createpdf_execute_callback.h b/interfaces/kits/napi/webviewcontroller/webview_createpdf_execute_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..802a9dac591812d3d1574343ee8f3477d8224671 --- /dev/null +++ b/interfaces/kits/napi/webviewcontroller/webview_createpdf_execute_callback.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NWEB_WEBVIEW_CREAT_PDF_EXECUTE_CALLBACK_H +#define NWEB_WEBVIEW_CREAT_PDF_EXECUTE_CALLBACK_H + +#include +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "napi_parse_utils.h" +#include "nweb_value_callback.h" +#include "nweb_web_message.h" + +namespace OHOS::NWeb { +enum class JsCreatePDFType : int { ARRAYBUFFER = 0 }; + +class NapiArrayBufferExt { +public: + NapiArrayBufferExt() = default; + ~NapiArrayBufferExt() = default; + + static napi_value JsConstructor(napi_env env, napi_callback_info info); + + static napi_value GetArrayBuffer(napi_env env, napi_callback_info info); +}; + +class WebJsArrayBufferExt { +public: + explicit WebJsArrayBufferExt(const char* value, const long size) : value_(value), size_(size) {}; + ~WebJsArrayBufferExt() = default; + + const char* GetPDFResult() const + { + return value_; + } + + long GetPDFSize() const + { + return size_; + } + +private: + const char* value_ = nullptr; + long size_ = 0; +}; + +class WebviewCreatePDFExecuteCallback : public NWebArrayBufferValueCallback { +public: + explicit WebviewCreatePDFExecuteCallback(napi_env env, napi_ref callbackRef, napi_deferred deferred) + : env_(env), callbackRef_(callbackRef), deferred_(deferred) + {} + ~WebviewCreatePDFExecuteCallback() = default; + void OnReceiveValue(const char* value, const long size) override; + +private: + struct ArrayBufferExecuteParam { + napi_env env_; + napi_ref callbackRef_; + napi_deferred deferred_; + char* result_; + long size_; + }; + + napi_env env_ = nullptr; + napi_ref callbackRef_ = nullptr; + napi_deferred deferred_ = nullptr; + + static void UvAfterWorkCb(uv_work_t* work, int status); + static void UvAfterWorkCbAsync(napi_env env, napi_ref callbackRef, const char* result, const long size); + static void UvAfterWorkCbPromise(napi_env env, napi_deferred deferred, const char* result, const long size); + +public: + static void InitJSExcute(napi_env env, napi_value exports); +}; + +} // namespace OHOS::NWeb +#endif diff --git a/interfaces/kits/napi/webviewcontroller/webview_hasimage_callback.cpp b/interfaces/kits/napi/webviewcontroller/webview_hasimage_callback.cpp index 2591c5880eb8ee9bd60583694b423bd234edf894..f783722adf21bac19b7d6a29b216e430121f5ff0 100644 --- a/interfaces/kits/napi/webviewcontroller/webview_hasimage_callback.cpp +++ b/interfaces/kits/napi/webviewcontroller/webview_hasimage_callback.cpp @@ -40,6 +40,7 @@ void WebviewHasImageCallback::OnReceiveValue(bool result) HasImageParam *param = new (std::nothrow) HasImageParam(); if (param == nullptr) { delete work; + work = nullptr; return; } param->env_ = env_; diff --git a/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.cpp b/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.cpp index ce07709f3d511cdb19ccd732000d811d085259d1..129034b0fc86d44bbf13889afa50c929ae5e00b9 100644 --- a/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.cpp +++ b/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.cpp @@ -25,14 +25,15 @@ #include "nweb_log.h" #include "ohos_adapter_helper.h" -#define MAX_FLOWBUF_DATA_SIZE 52428800 /* 50MB*/ -#define MAX_ENTRIES 10 -#define HEADER_SIZE (MAX_ENTRIES * 8) /* 10 * (int position + int length) */ -#define INDEX_SIZE 2 - namespace OHOS::NWeb { namespace { #define JS_BRIDGE_BINARY_ARGS_COUNT 2 + +const int MAX_FLOWBUF_DATA_SIZE = 52428800; /* 50MB*/ +const int MAX_ENTRIES = 10; +const int HEADER_SIZE = (MAX_ENTRIES * 8); /* 10 * (int position + int length) */ +const int INDEX_SIZE = 2; + // For the sake of the storage API, make this quite large. const uint32_t MAX_RECURSION_DEPTH = 11; const uint32_t MAX_DATA_LENGTH = 10000; @@ -52,11 +53,15 @@ public: public: explicit Level(ValueConvertState* state) : state_(state) { - state_->maxRecursionDepth_--; + if (state_) { + state_->maxRecursionDepth_--; + } } ~Level() { - state_->maxRecursionDepth_++; + if (state_) { + state_->maxRecursionDepth_++; + } } private: @@ -795,6 +800,39 @@ std::vector ParseNapiValue2NwebValue(napi_env env, napi_value* valu } } // namespace +std::shared_ptr JavaScriptOb::CreateNamed( + napi_env env, int32_t containerScopeId, napi_value value, size_t refCount) +{ + return std::make_shared(env, containerScopeId, value, refCount); +} +std::shared_ptr JavaScriptOb::CreateTransient( + napi_env env, int32_t containerScopeId, napi_value value, int32_t holder, size_t refCount) +{ + std::set holders; + holders.insert(holder); + return std::make_shared(env, containerScopeId, value, holders, refCount); +} + +JavaScriptOb::JavaScriptOb(napi_env env, int32_t containerScopeId, napi_value value, size_t refCount) + : env_(env), containerScopeId_(containerScopeId), isStrongRef_(refCount != 0), namesCount_(1) +{ + napi_status s = napi_create_reference(env, value, refCount, &objRef_); + if (s != napi_ok) { + WVLOG_E("create javascript obj fail"); + } +} + +JavaScriptOb::JavaScriptOb( + napi_env env, int32_t containerScopeId, napi_value value, std::set holders, size_t refCount) + : env_(env), containerScopeId_(containerScopeId), isStrongRef_(refCount != 0), namesCount_(0), holders_(holders) +{ + std::unique_lock lock(mutex_); + napi_status s = napi_create_reference(env, value, refCount, &objRef_); + if (s != napi_ok) { + WVLOG_E("create javascript obj fail"); + } +} + WebviewJavaScriptResultCallBack::WebviewJavaScriptResultCallBack(int32_t nwebId) : nwebId_(nwebId) { @@ -1095,7 +1133,7 @@ std::shared_ptr WebviewJavaScriptResultCallBack::GetJavaScriptResultS return ret; } JavaScriptOb::ObjectID returnedObjectId; - if (FindObjectIdInJsTd(jsObj->GetEnv(), callResult, &returnedObjectId)) { + if (FindObjectIdInJsTd(jsObj->GetEnv(), callResult, &returnedObjectId) && FindObject(returnedObjectId)) { FindObject(returnedObjectId)->AddHolder(routingId); } else { returnedObjectId = AddObject(jsObj->GetEnv(), callResult, false, routingId); @@ -1119,6 +1157,9 @@ std::shared_ptr WebviewJavaScriptResultCallBack::GetJavaScriptResultS { std::shared_ptr ret = std::make_shared(NWebValue::Type::NONE); std::shared_ptr jsObj = FindObject(objectId); + if (!jsObj) { + return ret; + } napi_handle_scope scope = nullptr; napi_open_handle_scope(jsObj->GetEnv(), &scope); if (scope == nullptr) { @@ -1126,15 +1167,18 @@ std::shared_ptr WebviewJavaScriptResultCallBack::GetJavaScriptResultS } auto flowbufferAdapter = OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter(); if (!flowbufferAdapter) { + napi_close_handle_scope(jsObj->GetEnv(), scope); return ret; } auto ashmem = flowbufferAdapter->CreateAshmemWithFd(fd, MAX_FLOWBUF_DATA_SIZE + HEADER_SIZE, PROT_READ); if (!ashmem) { + napi_close_handle_scope(jsObj->GetEnv(), scope); return ret; } std::vector argv = {}; if(!ConstructArgv(ashmem, args, argv, jsObj, routingId)) { + napi_close_handle_scope(jsObj->GetEnv(), scope); return ret; } close(fd); diff --git a/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.h b/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.h index 28576b4659f6b118b83e9ca6b142b0c30fa98de3..c3a0bc6fbedc121f03f2b832522278d8917b08e0 100644 --- a/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.h +++ b/interfaces/kits/napi/webviewcontroller/webview_javascript_result_callback.h @@ -51,37 +51,14 @@ public: typedef int32_t ObjectID; static std::shared_ptr CreateNamed( - napi_env env, int32_t containerScopeId, napi_value value, size_t refCount = 1) - { - return std::make_shared(env, containerScopeId, value, refCount); - } + napi_env env, int32_t containerScopeId, napi_value value, size_t refCount = 1); static std::shared_ptr CreateTransient( - napi_env env, int32_t containerScopeId, napi_value value, int32_t holder, size_t refCount = 1) - { - std::set holders; - holders.insert(holder); - return std::make_shared(env, containerScopeId, value, holders, refCount); - } + napi_env env, int32_t containerScopeId, napi_value value, int32_t holder, size_t refCount = 1); - JavaScriptOb(napi_env env, int32_t containerScopeId, napi_value value, size_t refCount = 1) - : env_(env), containerScopeId_(containerScopeId), isStrongRef_(refCount != 0), namesCount_(1) - { - napi_status s = napi_create_reference(env, value, refCount, &objRef_); - if (s != napi_ok) { - WVLOG_E("create javascript obj fail"); - } - } + JavaScriptOb(napi_env env, int32_t containerScopeId, napi_value value, size_t refCount = 1); JavaScriptOb( - napi_env env, int32_t containerScopeId, napi_value value, std::set holders, size_t refCount = 1) - : env_(env), containerScopeId_(containerScopeId), isStrongRef_(refCount != 0), namesCount_(0), holders_(holders) - { - std::unique_lock lock(mutex_); - napi_status s = napi_create_reference(env, value, refCount, &objRef_); - if (s != napi_ok) { - WVLOG_E("create javascript obj fail"); - } - } + napi_env env, int32_t containerScopeId, napi_value value, std::set holders, size_t refCount = 1); JavaScriptOb(const JavaScriptOb& job) { @@ -183,7 +160,7 @@ public: } } - bool IsNamed() + bool IsNamed() const { return namesCount_ > 0; } diff --git a/interfaces/native/arkweb_error_code.h b/interfaces/native/arkweb_error_code.h index 376e8d1480d7859aad86dfb9157ed750154d6409..e4fd26ba40c7ed07b14b700dde8fca34d3fbc661 100644 --- a/interfaces/native/arkweb_error_code.h +++ b/interfaces/native/arkweb_error_code.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,6 +24,7 @@ * @file arkweb_error_code.h * * @brief Declares the APIs for the ArkWeb errors. + * @kit ArkWeb * @library libohweb.so * @syscap SystemCapability.Web.Webview.Core * @since 12 @@ -32,6 +33,22 @@ #define ARKWEB_ERROR_CODE_H typedef enum ArkWeb_ErrorCode { +/* + * @brief Success. + * + * @syscap SystemCapability.Web.Webview.Core + * @since 12 + */ +ARKWEB_SUCCESS = 0, + +/* + * @brief Init error. The WebviewController must be associated with a Web component. + * + * @syscap SystemCapability.Web.Webview.Core + * @since 12 + */ +ARKWEB_INIT_ERROR = 17100001, + /* * @brief Unknown error. * @@ -55,6 +72,22 @@ ARKWEB_INVALID_PARAM = 17100101, * @since 12 */ ARKWEB_SCHEME_REGISTER_FAILED = 17100102, + +/* + * @brief Invalid url. + * + * @syscap SystemCapability.Web.Webview.Core + * @since 12 + */ +ARKWEB_INVALID_URL = 17100103, + +/* + * @brief Invalid cookie value. + * + * @syscap SystemCapability.Web.Webview.Core + * @since 12 + */ +ARKWEB_INVALID_COOKIE_VALUE = 17100104, } ArkWeb_ErrorCode; #endif // ARKWEB_ERROR_CODE_H \ No newline at end of file diff --git a/interfaces/native/arkweb_interface.cpp b/interfaces/native/arkweb_interface.cpp index 9467dda0b1058a189737711cf9f6a5fcf97d268a..3da1b21e11d61a9ec095dc7932afe06fab532e06 100644 --- a/interfaces/native/arkweb_interface.cpp +++ b/interfaces/native/arkweb_interface.cpp @@ -20,24 +20,52 @@ #include "arkweb_type.h" #include "nweb_helper.h" #include "nweb_log.h" +#include "arkweb_error_code.h" namespace { -#define ARKWEB_NATIVE_FOR_EACH_COMPONENT_API_FN(DO) \ - DO(onControllerAttached, OH_ArkWeb_OnControllerAttached) \ - DO(onPageBegin, OH_ArkWeb_OnPageBegin) \ - DO(onPageEnd, OH_ArkWeb_OnPageEnd) \ +#define ARKWEB_NATIVE_FOR_EACH_COMPONENT_API_FN(DO) \ + DO(onControllerAttached, OH_ArkWeb_OnControllerAttached); \ + DO(onPageBegin, OH_ArkWeb_OnPageBegin); \ + DO(onPageEnd, OH_ArkWeb_OnPageEnd); \ DO(onDestroy, OH_ArkWeb_OnDestroy) -#define ARKWEB_NATIVE_FOR_EACH_CONTROLLER_API_FN(DO) \ - DO(runJavaScript, OH_ArkWeb_RunJavaScript) \ - DO(registerJavaScriptProxy, OH_ArkWeb_RegisterJavaScriptProxy) \ - DO(deleteJavaScriptRegister, OH_ArkWeb_DeleteJavaScriptProxy) \ - DO(refresh, OH_ArkWeb_Refresh) \ - DO(registerAsyncJavaScriptProxy, OH_ArkWeb_RegisterAsyncJavaScriptProxy) \ - DO(registerJavaScriptProxyEx, OH_ArkWeb_RegisterJavaScriptProxyEx) +#define ARKWEB_NATIVE_FOR_EACH_CONTROLLER_API_FN(DO) \ + DO(runJavaScript, OH_ArkWeb_RunJavaScript); \ + DO(registerJavaScriptProxy, OH_ArkWeb_RegisterJavaScriptProxy); \ + DO(deleteJavaScriptRegister, OH_ArkWeb_DeleteJavaScriptProxy); \ + DO(refresh, OH_ArkWeb_Refresh); \ + DO(registerAsyncJavaScriptProxy, OH_ArkWeb_RegisterAsyncJavaScriptProxy); \ + DO(createWebMessagePorts, OH_ArkWeb_CreateWebMessagePorts); \ + DO(destroyWebMessagePorts, OH_ArkWeb_DestroyWebMessagePorts); \ + DO(postWebMessage, OH_ArkWeb_PostWebMessage) + +#define ARKWEB_NATIVE_FOR_EACH_WEBMESSAGEPORT_API_FN(DO) \ + DO(postMessage, OH_WebMessage_PostMessage); \ + DO(close, OH_WebMessage_Close); \ + DO(setMessageEventHandler, OH_WebMessage_SetMessageEventHandler) + +#define ARKWEB_NATIVE_FOR_EACH_WEBMESSAGE_API_FN(DO) \ + DO(createWebMessage, OH_WebMessage_CreateWebMessage); \ + DO(destroyWebMessage, OH_WebMessage_DestroyWebMessage); \ + DO(setType, OH_WebMessage_SetType); \ + DO(getType, OH_WebMessage_GetType); \ + DO(setData, OH_WebMessage_SetData); \ + DO(getData, OH_WebMessage_GetData) + +#define ARKWEB_NATIVE_FOR_EACH_WEBCOOKIEMANAGER_API_FN(DO) \ + DO(fetchCookieSync, OH_CookieManager_FetchCookieSync); \ + DO(configCookieSync, OH_CookieManager_ConfigCookieSync); \ + DO(existCookies, OH_CookieManager_ExistCookies); \ + DO(clearAllCookiesSync, OH_CookieManager_ClearAllCookiesSync); \ + DO(clearSessionCookiesSync, OH_CookieManager_ClearSessionCookiesSync) ArkWeb_ComponentAPI* g_ComponentImpl = nullptr; ArkWeb_ControllerAPI* g_ControllerImpl = nullptr; +ArkWeb_WebMessagePortAPI* g_WebMessagePortImpl = nullptr; +ArkWeb_WebMessageAPI* g_WebMessageImpl = nullptr; +ArkWeb_CookieManagerAPI* g_CookieManagerImpl = nullptr; + +void* g_webEngineHandle = nullptr; } // namespace @@ -58,7 +86,7 @@ static bool LoadComponentAPI() WVLOG_I("NativeArkWeb component api already loaded"); return true; } - g_ComponentImpl = new ArkWeb_ComponentAPI(); + g_ComponentImpl = new (std::nothrow) ArkWeb_ComponentAPI(); if (!g_ComponentImpl) { WVLOG_E("NativeArkWeb component api is nullptr"); return false; @@ -70,8 +98,9 @@ static bool LoadComponentAPI() WVLOG_E("NativeArkWeb webEngineHandle is nullptr"); return false; } -#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(webEngineHandle, #ndkFn, &(g_ComponentImpl->fn)); - ARKWEB_NATIVE_FOR_EACH_COMPONENT_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR) + g_webEngineHandle = webEngineHandle; +#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(g_webEngineHandle, #ndkFn, &(g_ComponentImpl->fn)) + ARKWEB_NATIVE_FOR_EACH_COMPONENT_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR); #undef ARKWEB_NATIVE_LOAD_FN_PTR return true; @@ -83,7 +112,7 @@ static bool LoadControllerAPI() WVLOG_I("NativeArkWeb controller api already loaded"); return true; } - g_ControllerImpl = new ArkWeb_ControllerAPI(); + g_ControllerImpl = new (std::nothrow) ArkWeb_ControllerAPI(); if (!g_ControllerImpl) { WVLOG_E("NativeArkWeb controller api is nullptr"); return false; @@ -95,8 +124,90 @@ static bool LoadControllerAPI() WVLOG_E("NativeArkWeb webEngineHandle is nullptr"); return false; } -#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(webEngineHandle, #ndkFn, &(g_ControllerImpl->fn)); - ARKWEB_NATIVE_FOR_EACH_CONTROLLER_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR) + g_webEngineHandle = webEngineHandle; +#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(g_webEngineHandle, #ndkFn, &(g_ControllerImpl->fn)) + ARKWEB_NATIVE_FOR_EACH_CONTROLLER_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR); +#undef ARKWEB_NATIVE_LOAD_FN_PTR + + return true; +} + +static bool LoadWebMessagePortAPI() +{ + if (g_WebMessagePortImpl) { + WVLOG_I("NativeArkWeb web message port api already loaded"); + return true; + } + g_WebMessagePortImpl = new (std::nothrow) ArkWeb_WebMessagePortAPI(); + if (!g_WebMessagePortImpl) { + WVLOG_E("NativeArkWeb web message port api is nullptr"); + return false; + } + g_WebMessagePortImpl->size = sizeof(ArkWeb_WebMessagePortAPI); + + void* webEngineHandle = OHOS::NWeb::NWebHelper::Instance().GetWebEngineHandler(); + if (!webEngineHandle) { + WVLOG_E("NativeArkWeb webEngineHandle is nullptr"); + return false; + } + g_webEngineHandle = webEngineHandle; +#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(g_webEngineHandle, #ndkFn, &(g_WebMessagePortImpl->fn)) + ARKWEB_NATIVE_FOR_EACH_WEBMESSAGEPORT_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR); +#undef ARKWEB_NATIVE_LOAD_FN_PTR + + return true; +} + +static bool LoadWebMessageAPI() +{ + if (g_WebMessageImpl) { + WVLOG_I("NativeArkWeb web message api already loaded"); + return true; + } + g_WebMessageImpl = new (std::nothrow) ArkWeb_WebMessageAPI(); + if (!g_WebMessageImpl) { + WVLOG_E("NativeArkWeb web message api is nullptr"); + return false; + } + g_WebMessageImpl->size = sizeof(ArkWeb_WebMessageAPI); + void* webEngineHandle = OHOS::NWeb::NWebHelper::Instance().GetWebEngineHandler(); + if (!webEngineHandle) { + WVLOG_E("NativeArkWeb webEngineHandle is nullptr"); + return false; + } + g_webEngineHandle = webEngineHandle; +#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(g_webEngineHandle, #ndkFn, &(g_WebMessageImpl->fn)) + ARKWEB_NATIVE_FOR_EACH_WEBMESSAGE_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR); +#undef ARKWEB_NATIVE_LOAD_FN_PTR + + return true; +} + +static bool LoadCookieManagerAPI() +{ + if (g_CookieManagerImpl) { + WVLOG_I("NativeArkWeb cookie manager api already loaded"); + return true; + } + + g_CookieManagerImpl = new ArkWeb_CookieManagerAPI(); + if (!g_CookieManagerImpl) { + WVLOG_E("NativeArkWeb cookie manager api is nullptr"); + return false; + } + + g_CookieManagerImpl->size = sizeof(ArkWeb_CookieManagerAPI); + + if (g_webEngineHandle == nullptr) { + g_webEngineHandle = OHOS::NWeb::NWebHelper::Instance().GetWebEngineHandler(true); + if (!g_webEngineHandle) { + WVLOG_E("NativeArkWeb webEngineHandle is nullptr"); + return false; + } + } + +#define ARKWEB_NATIVE_LOAD_FN_PTR(fn, ndkFn) LoadFunction(g_webEngineHandle, #ndkFn, &(g_CookieManagerImpl->fn)) + ARKWEB_NATIVE_FOR_EACH_WEBCOOKIEMANAGER_API_FN(ARKWEB_NATIVE_LOAD_FN_PTR); #undef ARKWEB_NATIVE_LOAD_FN_PTR return true; @@ -117,6 +228,24 @@ ArkWeb_AnyNativeAPI* OH_ArkWeb_GetNativeAPI(ArkWeb_NativeAPIVariantKind type) } return reinterpret_cast(g_ControllerImpl); } + case ARKWEB_NATIVE_WEB_MESSAGE_PORT: { + if (!LoadWebMessagePortAPI()) { + return nullptr; + } + return reinterpret_cast(g_WebMessagePortImpl); + } + case ARKWEB_NATIVE_WEB_MESSAGE: { + if (!LoadWebMessageAPI()) { + return nullptr; + } + return reinterpret_cast(g_WebMessageImpl); + } + case ARKWEB_NATIVE_COOKIE_MANAGER: { + if (!LoadCookieManagerAPI()) { + return nullptr; + } + return reinterpret_cast(g_CookieManagerImpl); + } default: { WVLOG_E("fail to get %{public}d arkweb api family", type); return nullptr; diff --git a/interfaces/native/arkweb_interface.h b/interfaces/native/arkweb_interface.h index 90f3b80e5a4f1989d23f02a6599b2895d98f17cc..b0afbc363a93fce192f3ea022081da4fd931fdd1 100644 --- a/interfaces/native/arkweb_interface.h +++ b/interfaces/native/arkweb_interface.h @@ -24,6 +24,7 @@ * @file arkweb_interface.h * * @brief Provides a unified entry for the native ArkWeb. + * @kit ArkWeb * @library libohweb.so * @syscap SystemCapability.Web.Webview.Core * @since 12 @@ -58,12 +59,18 @@ typedef enum { ARKWEB_NATIVE_COMPONENT, /** API type related to ArkWeb controller. */ ARKWEB_NATIVE_CONTROLLER, + /** API type related to ArkWeb WebMessagePort. */ + ARKWEB_NATIVE_WEB_MESSAGE_PORT, + /** API type related to ArkWeb WebMessage. */ + ARKWEB_NATIVE_WEB_MESSAGE, + /** API type related to ArkWeb cookie manager. */ + ARKWEB_NATIVE_COOKIE_MANAGER, } ArkWeb_NativeAPIVariantKind; /* * @brief Obtains the native API set of a specified type. * @param type Indicates the type of the native API set provided by ArkWeb. - * @return Returns the pointer to the native API abstract object that carries the size. + * @return Return the pointer to the native API abstract object that carries the size. * * @syscap SystemCapability.Web.Webview.Core * @since 12 diff --git a/interfaces/native/arkweb_scheme_handler.cpp b/interfaces/native/arkweb_scheme_handler.cpp index 1844cd4889a110b40d4b4da8272670d545a663af..c05e79d90f7bd4859a6d2bc2fa3aa6953fdc7ae6 100644 --- a/interfaces/native/arkweb_scheme_handler.cpp +++ b/interfaces/native/arkweb_scheme_handler.cpp @@ -131,7 +131,7 @@ bool EnsureSdkLoaded(void* handle) return false; } - auto* schemeHandlerApi = new SchemeHandlerApi(); + auto* schemeHandlerApi = new (std::nothrow) SchemeHandlerApi(); if (schemeHandlerApi == nullptr) { WVLOG_I("schemeHandlerApi is nullptr."); return false; diff --git a/interfaces/native/arkweb_type.h b/interfaces/native/arkweb_type.h index b5ab54a746561b986e996992a94c32c09b3bade2..d626371eb13fe4cc6ea18cb9e3700e7add4d21c6 100644 --- a/interfaces/native/arkweb_type.h +++ b/interfaces/native/arkweb_type.h @@ -24,6 +24,7 @@ * @file arkweb_type.h * * @brief Defines the common types for the native ArkWeb. + * @kit ArkWeb * @library libohweb.so * @syscap SystemCapability.Web.Webview.Core * @since 12 @@ -35,6 +36,8 @@ #include #include +#include "arkweb_error_code.h" + #ifdef __cplusplus extern "C" { #endif @@ -51,6 +54,27 @@ typedef struct { size_t size; } ArkWeb_JavaScriptBridgeData; +/** + * @brief Defines the data type carried in a ArkWeb_WebMessage. + * + * @since 12 + */ +typedef enum ArkWeb_WebMessageType { + /** Represent error data */ + ARKWEB_NONE = 0, + /** The data carried in the ArkWeb_WebMessage is string. */ + ARKWEB_STRING, + /** The data carried in the ArkWeb_WebMessage is buffer(uint8_t). */ + ARKWEB_BUFFER +} ArkWeb_WebMessageType; + +/** + * @brief Defines the ArkWeb_WebMessage. + * + * @since 12 + */ +typedef struct ArkWeb_WebMessage* ArkWeb_WebMessagePtr; + /** * @brief Defines the javascript callback of the native ArkWeb. * @@ -74,6 +98,26 @@ typedef void (*ArkWeb_OnJavaScriptProxyCallback)( */ typedef void (*ArkWeb_OnComponentCallback)(const char* webTag, void* userData); +/** + * @brief Defines the ArkWeb_WebMessagePort that represent a HTML5 message port. + * + * @since 12 + */ +typedef struct ArkWeb_WebMessagePort* ArkWeb_WebMessagePortPtr; + +/** + * @brief Defines the callback to receive message from HTML. + * + * @param webTag The name of the web component. + * @param port The ArkWeb_WebMessagePort for registering the ArkWeb_OnMessageEventHandler. + * @param message The received ArkWeb_WebMessage. + * @param userData The data set by user. + * + * @since 12 + */ +typedef void (*ArkWeb_OnMessageEventHandler)( + const char* webTag, const ArkWeb_WebMessagePortPtr port, const ArkWeb_WebMessagePtr message, void* userData); + /** * @brief Defines the javascript object. * @@ -120,6 +164,9 @@ typedef struct { /** * @brief Defines the controller API for native ArkWeb. + * Before invoking an API, you are advised to use ARKWEB_MEMBER_MISSING to check + * whether the function structure has a corresponding function pointer to avoid crash + * caused by mismatch between the SDK and the device ROM. * * @since 12 */ @@ -136,9 +183,37 @@ typedef struct { void (*refresh)(const char* webTag); /** Register the JavaScript object and async method list. */ void (*registerAsyncJavaScriptProxy)(const char* webTag, const ArkWeb_ProxyObject* proxyObject); - /** Register the JavaScript object and method list with permission */ - void (*registerJavaScriptProxyEx)(const char* webTag, - const ArkWeb_ProxyObject* proxyObject, const char* permission); + /** + * @brief Creates a message channel to communicate with HTML and returns + * the message ports representing the message channel endpoints. + * + * @param webTag The name of the web component. + * @param size The quantity of message ports. + */ + ArkWeb_WebMessagePortPtr* (*createWebMessagePorts)(const char* webTag, size_t* size); + + /** + * @brief Destroy message ports. + * + * @param ports Address of the message ports array pointer. + * @param size The quantity of message ports. + */ + void (*destroyWebMessagePorts)(ArkWeb_WebMessagePortPtr** ports, size_t size); + + /** + * @brief Post message ports to main frame. + * + * @param webTag The name of the web component. + * @param name Name of the message to be sent. + * @param size The quantity of message ports. + * @param url Indicates the URI for receiving the message. + * @return Post web message result code. + * {@link ARKWEB_SUCCESS} post web message success. + * {@link ARKWEB_INVALID_PARAM} the parameter verification fails. + * {@link ARKWEB_INIT_ERROR} no web associated with this webTag. + */ + ArkWeb_ErrorCode (*postWebMessage)( + const char* webTag, const char* name, ArkWeb_WebMessagePortPtr* webMessagePorts, size_t size, const char* url); } ArkWeb_ControllerAPI; /** @@ -159,6 +234,171 @@ typedef struct { void (*onDestroy)(const char* webTag, ArkWeb_OnComponentCallback callback, void* userData); } ArkWeb_ComponentAPI; +/** + * @brief Defines the web message API for native ArkWeb. + * Before invoking an API, you are advised to use ARKWEB_MEMBER_MISSING to check + * whether the function structure has a corresponding function pointer to avoid crash + * caused by mismatch between the SDK and the device ROM. + * + * @since 12 + */ +typedef struct { + /** The ArkWeb_WebMessagePortAPI struct size. */ + size_t size; + /** + * @brief Post message to HTML. + * + * @param webMessagePort The ArkWeb_WebMessagePort. + * @param webTag The name of the web component. + * @param webMessage The ArkWeb_WebMessage to send. + * @return Post message result code. + * {@link ARKWEB_SUCCESS} post message success. + * {@link ARKWEB_INVALID_PARAM} the parameter verification fails. + * {@link ARKWEB_INIT_ERROR} no web associated with this webTag. + */ + ArkWeb_ErrorCode (*postMessage)( + const ArkWeb_WebMessagePortPtr webMessagePort, const char* webTag, const ArkWeb_WebMessagePtr webMessage); + /** + * @brief Close the message port. + * + * @param webMessagePort The ArkWeb_WebMessagePort. + * @param webTag The name of the web component. + */ + void (*close)(const ArkWeb_WebMessagePortPtr webMessagePort, const char* webTag); + /** + * @brief Set a callback to receive message from HTML. + * + * @param webMessagePort The ArkWeb_WebMessagePort. + * @param webTag The name of the web component. + * @param messageEventHandler The handler to receive message from HTML. + * @param userData The data set by user. + */ + void (*setMessageEventHandler)(const ArkWeb_WebMessagePortPtr webMessagePort, const char* webTag, + ArkWeb_OnMessageEventHandler messageEventHandler, void* userData); +} ArkWeb_WebMessagePortAPI; + +/** + * @brief Defines the web message data API for native ArkWeb. + * Before invoking an API, you are advised to use ARKWEB_MEMBER_MISSING to check + * whether the function structure has a corresponding function pointer to avoid crash + * caused by mismatch between the SDK and the device ROM. + * + * @since 12 + */ +typedef struct { + /** The ArkWeb_WebMessageAPI struct size. */ + size_t size; + /** + * @brief Used to create a ArkWeb_WebMessage. + * + * @return The created ArkWeb_WebMessage, destroy it through + * destroyWebMessage after it is no longer used. + */ + ArkWeb_WebMessagePtr (*createWebMessage)(); + /** + * @brief Used to destroy a ArkWeb_WebMessage. + * + * @param webMessage The ArkWeb_WebMessage to destroy. + */ + void (*destroyWebMessage)(ArkWeb_WebMessagePtr* webMessage); + /** + * @brief Set the type of ArkWeb_WebMessage. + * + * @param webMessage The ArkWeb_WebMessage. + * @param type The type of ArkWeb_WebMessage. + */ + void (*setType)(ArkWeb_WebMessagePtr webMessage, ArkWeb_WebMessageType type); + /** + * @brief Get the type of ArkWeb_WebMessage. + * + * @param webMessage The ArkWeb_WebMessage. + * @return The type of ArkWeb_WebMessage. + */ + ArkWeb_WebMessageType (*getType)(ArkWeb_WebMessagePtr webMessage); + /** + * @brief Set the data of ArkWeb_WebMessage. + * + * @param webMessage The ArkWeb_WebMessage. + * @param data The data of ArkWeb_WebMessage. + * @param dataLength The length of data. + */ + void (*setData)(ArkWeb_WebMessagePtr webMessage, void* data, size_t dataLength); + /** + * @brief Get the data of ArkWeb_WebMessage. + * + * @param webMessage The ArkWeb_WebMessage. + * @param dataLength The length of data. + * @return The data of ArkWeb_WebMessage. + */ + void* (*getData)(ArkWeb_WebMessagePtr webMessage, size_t* dataLength); +} ArkWeb_WebMessageAPI; + +/** + * @brief Defines the native CookieManager API for ArkWeb. + * Before invoking an API, you are advised to use ARKWEB_MEMBER_MISSING to check + * whether the function structure has a corresponding function pointer to avoid crash + * caused by mismatch between the SDK and the device ROM. + * + * @since 12 + */ +typedef struct { + /** The ArkWeb_CookieManagerAPI struct size. */ + size_t size; + + /** + * @brief Obtains the cookie value corresponding to a specified URL. + * + * @param url URL to which the cookie to be obtained belongs. A complete URL is recommended. + * @param incognito True indicates that the memory cookies of the webview in privacy mode are obtained, + * and false indicates that cookies in non-privacy mode are obtained. + * @param includeHttpOnly If true HTTP-only cookies will also be included in the cookieValue. + * @param cookieValue Get the cookie value corresponding to the URL. + * @return Fetch cookie result code. + * {@link ARKWEB_SUCCESS} fetch cookie success. + * {@link ARKWEB_INVALID_URL} invalid url. + * {@link ARKWEB_INVALID_PARAM} cookieValue is nullptr. + */ + ArkWeb_ErrorCode (*fetchCookieSync)(const char* url, bool incognito, bool includeHttpOnly, char** cookieValue); + + /** + * @brief Sets the cookie value for a specified URL. + * + * @param url Specifies the URL to which the cookie belongs. A complete URL is recommended. + * @param cookieValue The value of the cookie to be set. + * @param incognito True indicates that cookies of the corresponding URL are set in privacy mode, + * and false indicates that cookies of the corresponding URL are set in non-privacy mode. + * @param includeHttpOnly If true, HTTP-only cookies can also be overwritten. + * @return Config cookie result code. + * {@link ARKWEB_SUCCESS} config cookie success. + * {@link ARKWEB_INVALID_URL} invalid url. + * {@link ARKWEB_INVALID_COOKIE_VALUE} invalid cookie value. + */ + ArkWeb_ErrorCode (*configCookieSync)(const char* url, + const char* cookieValue, bool incognito, bool includeHttpOnly); + + /** + * @brief Check whether cookies exist. + * + * @param incognito True indicates whether cookies exist in privacy mode, + * and false indicates whether cookies exist in non-privacy mode. + * @return True indicates that the cookie exists, and false indicates that the cookie does not exist. + */ + bool (*existCookies)(bool incognito); + + /** + * @brief Clear all cookies. + * + * @param incognito True indicates that all memory cookies of the webview are cleared in privacy mode, + * and false indicates that persistent cookies in non-privacy mode are cleared. + */ + void (*clearAllCookiesSync)(bool incognito); + + /** + * @brief Clear all session cookies. + */ + void (*clearSessionCookiesSync)(); +} ArkWeb_CookieManagerAPI; + /** * @brief Check whether the member variables of the current struct exist. * @@ -175,6 +415,6 @@ typedef struct { #define ARKWEB_MEMBER_MISSING(s, f) (!ARKWEB_MEMBER_EXISTS(s, f) || !((s)->f)) #ifdef __cplusplus -}; +} #endif #endif // ARKWEB_TYPE_H \ No newline at end of file diff --git a/ohos_adapter/BUILD.gn b/ohos_adapter/BUILD.gn index 2b0e2b7f4389c4837f459a179f2874591d07c626..95fdb42ccbbfa604f4aa467154c307f242c3c621 100644 --- a/ohos_adapter/BUILD.gn +++ b/ohos_adapter/BUILD.gn @@ -19,10 +19,25 @@ config("ohos_adapter_public_interface") { } ohos_shared_library("nweb_ohos_adapter") { - branch_protector_ret = "pac_ret" - branch_protector_frt = "bti" + if (target_cpu == "arm64") { + branch_protector_ret = "pac_ret" + branch_protector_frt = "bti" + } + + defines = [ + "HILOG_TAG=\"webadapter\"", + "WEBVIEW_PACKAGE_NAME=\"${webview_package_name}\"", + "WEBVIEW_SANDBOX_LIB_PATH=\"${webview_sandbox_lib_path}\"", + "WEBVIEW_CRASHPAD_HANDLER_SO=\"${webview_crashpad_handler_so}\"", + "WEBVIEW_SANDBOX_RELATIVE_LIB_PATH=\"${webview_sandbox_relative_lib_path}\"", + "WEBVIEW_ENGINE_SO=\"${webview_engine_so}\"", + "WEBVIEW_SANDBOX_HAP_PATH=\"${webview_sandbox_hap_path}\"", + "WEBVIEW_APP_HAP_PATH=\"${webview_app_hap_path}\"", + "WEBVIEW_APP_HAP_PATH2=\"${webview_app_hap_path2}\"", + "WEBVIEW_HAP_PATH=\"${webview_hap_path}\"", + "WEBVIEW_SANDBOX_PATH=\"${webview_sandbox_path}\"", + ] - defines = [ "HILOG_TAG=\"webadapter\"" ] sources = [ "aafwk_adapter/src/aafwk_app_mgr_client_adapter_impl.cpp", "aafwk_adapter/src/aafwk_browser_client_adapter_impl.cpp", @@ -102,13 +117,13 @@ ohos_shared_library("nweb_ohos_adapter") { "screen_capture_adapter/include", "soc_perf_adapter/include", "system_properties_adapter/include", + "sensor_adapter/include", ] public_configs = [ ":ohos_adapter_public_interface" ] external_deps = [ "ability_base:extractortool", - "ability_base:want", "ability_base:zuri", "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", @@ -134,6 +149,7 @@ ohos_shared_library("nweb_ohos_adapter") { "hisysevent:libhisysevent", "hitrace:hitrace_meter", "huks:libhukssdk", + "i18n:intl_util", "image_framework:image_native", "imf:inputmethod_client", "init:libbeget_proxy", @@ -143,6 +159,7 @@ ohos_shared_library("nweb_ohos_adapter") { "napi:ace_napi", "netmanager_base:net_conn_manager_if", "netstack:net_ssl", + "openssl:libssl_shared", "pasteboard:pasteboard_client", "relational_store:native_rdb", "resource_schedule_service:ressched_client", @@ -150,6 +167,7 @@ ohos_shared_library("nweb_ohos_adapter") { "time_service:time_client", "window_manager:libdm", ] + public_external_deps = [ "ability_base:want" ] if (webview_soc_perf_enable) { external_deps += [ "soc_perf:socperf_client" ] @@ -243,9 +261,11 @@ ohos_shared_library("nweb_ohos_adapter") { if (webview_telephony_enable) { sources += [ + "net_connect_adapter/src/net_capabilities_adapter_impl.cpp", "net_connect_adapter/src/net_connect_adapter_impl.cpp", "net_connect_adapter/src/net_connect_callback_impl.cpp", "net_connect_adapter/src/net_connect_utils.cpp", + "net_connect_adapter/src/net_connection_properties_adapter_impl.cpp", ] external_deps += [ "cellular_data:tel_cellular_data_api", @@ -286,9 +306,20 @@ ohos_shared_library("nweb_ohos_adapter") { defines += [ "NWEB_MEDIA_AVSESSION_ENABLE" ] } + if (webview_sensors_sensor_enable) { + sources += [ "sensor_adapter/src/sensor_adapter_impl.cpp" ] + external_deps += [ "sensor:sensor_interface_native" ] + defines += [ "NWEB_SENSORS_SENSOR_ENABLE" ] + } + innerapi_tags = [ "platformsdk" ] part_name = "webview" subsystem_name = "web" deps = [ "../ohos_nweb:web_configs" ] + + if (webview_graphic_2d_ext_enable) { + external_deps += [ "graphic_2d_ext:libaps_client" ] + defines += [ "NWEB_GRAPHIC_2D_EXT_ENABLE" ] + } } diff --git a/ohos_adapter/aafwk_adapter/src/aafwk_app_mgr_client_adapter_impl.cpp b/ohos_adapter/aafwk_adapter/src/aafwk_app_mgr_client_adapter_impl.cpp index 28ed992b8f763e633233f21e7d48be279d1be048..d38ad725dac6a7900ec65d387309820717332ed4 100644 --- a/ohos_adapter/aafwk_adapter/src/aafwk_app_mgr_client_adapter_impl.cpp +++ b/ohos_adapter/aafwk_adapter/src/aafwk_app_mgr_client_adapter_impl.cpp @@ -164,7 +164,7 @@ void AafwkAppMgrClientAdapterImpl::SaveBrowserConnect(std::shared_ptrSaveBrowserChannel(browser); } } // namespace OHOS::NWeb diff --git a/ohos_adapter/aafwk_adapter/src/aafwk_render_scheduler_impl.cpp b/ohos_adapter/aafwk_adapter/src/aafwk_render_scheduler_impl.cpp index c4785d8e57daf8c1eab5f0c94c01959e87c0838e..d95ea28d093c31d79d62fff70a06fca5cf2d0300 100644 --- a/ohos_adapter/aafwk_adapter/src/aafwk_render_scheduler_impl.cpp +++ b/ohos_adapter/aafwk_adapter/src/aafwk_render_scheduler_impl.cpp @@ -34,7 +34,7 @@ void AafwkRenderSchedulerImpl::NotifyBrowserFd( return; } if (browser == nullptr) { - WVLOG_E("browser is nullptr!"); + WVLOG_D("NotifyBrowserFd for render process."); renderSchedulerHostAdapter_->NotifyBrowser(ipcFd, sharedFd, crashFd, nullptr); } else { sptr browserHost = iface_cast(browser); diff --git a/ohos_adapter/audio_adapter/src/audio_renderer_adapter_impl.cpp b/ohos_adapter/audio_adapter/src/audio_renderer_adapter_impl.cpp index c9da4cf35c361cd245dd6181ce036fcecf71ae61..1545191e294d1fee37d93f96f3d0a9a81c54b689 100644 --- a/ohos_adapter/audio_adapter/src/audio_renderer_adapter_impl.cpp +++ b/ohos_adapter/audio_adapter/src/audio_renderer_adapter_impl.cpp @@ -291,6 +291,10 @@ void AudioRendererAdapterImpl::SetInterruptMode(bool audioExclusive) bool AudioRendererAdapterImpl::IsRendererStateRunning() { + if (audio_renderer_ == nullptr) { + WVLOG_E("audio rendderer is nullptr"); + return false; + } return audio_renderer_->GetStatus() == OHOS::AudioStandard::RendererState::RENDERER_RUNNING; } diff --git a/ohos_adapter/flowbuffer_adapter/src/flowbuffer_adapter_impl.cpp b/ohos_adapter/flowbuffer_adapter/src/flowbuffer_adapter_impl.cpp index df9fe7ea439fefafca7b89ba07b30ad3469c3b8e..11b46303f7b83d32f489623271e52163f35183fa 100644 --- a/ohos_adapter/flowbuffer_adapter/src/flowbuffer_adapter_impl.cpp +++ b/ohos_adapter/flowbuffer_adapter/src/flowbuffer_adapter_impl.cpp @@ -35,7 +35,9 @@ int64_t FlowbufferAdapterImpl::preTimeStamp_ = 0; FlowbufferAdapterImpl::~FlowbufferAdapterImpl() { if (data_ != nullptr) { - ::munmap(data_, size_); + if (::munmap(data_, size_) != 0) { + WVLOG_E("Failed to unmap ashmem region"); + } data_ = nullptr; size_ = 0; } @@ -72,6 +74,7 @@ void* FlowbufferAdapterImpl::CreateAshmem(size_t size, int mapType, int& fd) int result = AshmemSetProt(fd, PROT_READ | PROT_WRITE); if (result < 0) { close(fd); + fd = -1; WVLOG_E("Ashmem set port failed, result: %{public}d", result); return nullptr; } @@ -79,6 +82,7 @@ void* FlowbufferAdapterImpl::CreateAshmem(size_t size, int mapType, int& fd) void *startAddr = ::mmap(nullptr, size, mapType, MAP_SHARED, fd, 0); if (startAddr == MAP_FAILED) { close(fd); + fd = -1; WVLOG_E("Map ashmem failed"); return nullptr; } diff --git a/ohos_adapter/graphic_adapter/include/vsync_adapter_impl.h b/ohos_adapter/graphic_adapter/include/vsync_adapter_impl.h index 5d13d0973ac9128559518d8dfbb8ae3fb80265d4..49be040be66deb75516742bfa7a7b4b24b7cafc2 100644 --- a/ohos_adapter/graphic_adapter/include/vsync_adapter_impl.h +++ b/ohos_adapter/graphic_adapter/include/vsync_adapter_impl.h @@ -41,6 +41,8 @@ public: void SetOnVsyncCallback(void (*callback)()) override; void SetIsGPUProcess(bool isGPU); void SetOnVsyncEndCallback(void (*onVsyncEndCallback)()) override; + + void SetScene(const std::string& sceneName, uint32_t state) override; private: static void OnVsync(int64_t timestamp, void* data); void VsyncCallbackInner(int64_t nanoTimestamp); @@ -61,6 +63,8 @@ private: static void (*onVsyncEndCallback_)(); bool frameRateLinkerEnable_ = false; bool isGPUProcess_ = false; + + std::string pkgName_ {""}; }; } // namespace OHOS::NWeb diff --git a/ohos_adapter/graphic_adapter/src/vsync_adapter_impl.cpp b/ohos_adapter/graphic_adapter/src/vsync_adapter_impl.cpp index 4b79df9c1e3afcc7e02c456076162b7d19b7e4c0..17bfd20c9d149178b8521c1d1b9ffd53da8352cb 100644 --- a/ohos_adapter/graphic_adapter/src/vsync_adapter_impl.cpp +++ b/ohos_adapter/graphic_adapter/src/vsync_adapter_impl.cpp @@ -16,6 +16,10 @@ #include "vsync_adapter_impl.h" #include "aafwk_browser_client_adapter_impl.h" +#include "application_context.h" +#if defined(NWEB_GRAPHIC_2D_EXT_ENABLE) +#include "aps_manager.h" +#endif #include "nweb_log.h" #include "res_sched_client_adapter.h" #include "system_properties_adapter_impl.h" @@ -25,6 +29,9 @@ namespace OHOS::NWeb { namespace { const std::string THREAD_NAME = "VSync-webview"; constexpr int32_t WEBVIEW_FRAME_RATE_TYPE = 4; +#if defined(NWEB_GRAPHIC_2D_EXT_ENABLE) +constexpr int32_t APS_MANAGER_CLOSE_ALL = 2; +#endif } void (*VSyncAdapterImpl::callback_)() = nullptr; @@ -43,6 +50,9 @@ VSyncAdapterImpl::~VSyncAdapterImpl() vsyncHandler_ = nullptr; } hasReportedKeyThread_ = false; +#if defined(NWEB_GRAPHIC_2D_EXT_ENABLE) + Rosen::ApsManager::GetInstance().SetScene(pkgName_, "WEB_LIST_FLING", APS_MANAGER_CLOSE_ALL); +#endif } VSyncAdapterImpl& VSyncAdapterImpl::GetInstance() @@ -165,17 +175,16 @@ int64_t VSyncAdapterImpl::GetVSyncPeriod() void VSyncAdapterImpl::SetFrameRateLinkerEnable(bool enabled) { - WVLOG_I("NWebWindowAdapter SetFrameRateLinkerEnable enabled=%{public}d", enabled); + WVLOG_D("NWebWindowAdapter SetFrameRateLinkerEnable enabled=%{public}d", enabled); if (frameRateLinkerEnable_ == enabled) { return; } - Rosen::FrameRateRange range = {0, RANGE_MAX_REFRESHRATE, 120, WEBVIEW_FRAME_RATE_TYPE}; if (frameRateLinker_) { if (!enabled) { - range = {0, RANGE_MAX_REFRESHRATE, 0, WEBVIEW_FRAME_RATE_TYPE}; + Rosen::FrameRateRange range = {0, RANGE_MAX_REFRESHRATE, 0, WEBVIEW_FRAME_RATE_TYPE}; + frameRateLinker_->UpdateFrameRateRangeImme(range); } - frameRateLinker_->UpdateFrameRateRangeImme(range); frameRateLinker_->SetEnable(enabled); frameRateLinkerEnable_ = enabled; } @@ -206,4 +215,17 @@ void VSyncAdapterImpl::SetOnVsyncEndCallback(void (*onVsyncEndCallback)()) WVLOG_D("callback function: %{public}ld", (long)onVsyncEndCallback); onVsyncEndCallback_ = onVsyncEndCallback; } + +void VSyncAdapterImpl::SetScene(const std::string& sceneName, uint32_t state) { + WVLOG_D("APSManagerAdapterImpl SetScene sceneName=%{public}s state=%{public}u", sceneName.c_str(), state); +#if defined(NWEB_GRAPHIC_2D_EXT_ENABLE) + if (pkgName_.empty()) { + auto appInfo = AbilityRuntime::ApplicationContext::GetInstance()->GetApplicationInfo(); + if (appInfo != nullptr) { + pkgName_ = appInfo->bundleName.c_str(); + } + } + Rosen::ApsManager::GetInstance().SetScene(pkgName_, sceneName, state); +#endif +} } // namespace OHOS::NWeb diff --git a/ohos_adapter/graphic_adapter/src/window_adapter_impl.cpp b/ohos_adapter/graphic_adapter/src/window_adapter_impl.cpp index b452c5c22c1195c21e3050f85d598533309a705d..426a1f3c91852655ce399fc4dec0036c5839f6a7 100644 --- a/ohos_adapter/graphic_adapter/src/window_adapter_impl.cpp +++ b/ohos_adapter/graphic_adapter/src/window_adapter_impl.cpp @@ -54,7 +54,7 @@ int32_t WindowAdapterImpl::NativeWindowSetBufferGeometry(NWebNativeWindow window void WindowAdapterImpl::NativeWindowSurfaceCleanCache(NWebNativeWindow window) { WVLOG_D("WindowAdapterImpl::NativeWindowSurfaceCleanCache"); - auto nativeWindow = reinterpret_cast(window); + auto nativeWindow = reinterpret_cast(window); if (!nativeWindow || !nativeWindow->surface) { WVLOG_D("window or surface is null, no need to clean surface cache"); return; @@ -64,13 +64,14 @@ void WindowAdapterImpl::NativeWindowSurfaceCleanCache(NWebNativeWindow window) void WindowAdapterImpl::NativeWindowSurfaceCleanCacheWithPara(NWebNativeWindow window, bool cleanAll) { - WVLOG_D("WindowAdapterImpl::NativeWindowSurfaceCleanCacheWithPara"); auto nativeWindow = reinterpret_cast(window); if (!nativeWindow || !nativeWindow->surface) { WVLOG_D("window or surface is null, no need to clean surface cache"); return; } - + WVLOG_D("NativeWindowSurfaceCleanCacheWithPara, surface uniqueID: %{public}llu", + nativeWindow->surface->GetUniqueId()); + // eglDestroySurface has disconnected the surface link GSError ret = nativeWindow->surface->Connect(); if (ret == (int32_t)GSERROR_OK) { diff --git a/ohos_adapter/hiviewdfx_adapter/include/hitrace_adapter_impl.h b/ohos_adapter/hiviewdfx_adapter/include/hitrace_adapter_impl.h index 227957c6d94a07d80ada3d8e8a7b77b0850dc3f3..97cde921f0a16addc05bbc0a39f8685bf4db4d07 100644 --- a/ohos_adapter/hiviewdfx_adapter/include/hitrace_adapter_impl.h +++ b/ohos_adapter/hiviewdfx_adapter/include/hitrace_adapter_impl.h @@ -43,14 +43,7 @@ public: void CountOHOSTrace(const std::string& name, int64_t count) override; - void UpdateOHOSTraceTag(const char* value); - bool IsACETraceEnable() override; - -private: - bool firstAceEnable_ = false; - bool isNWEBTraceEnable_ = false; - bool isOHOSTraceEnable_ = false; }; } // namespace OHOS::NWeb diff --git a/ohos_adapter/hiviewdfx_adapter/src/hisysevent_adapter_impl.cpp b/ohos_adapter/hiviewdfx_adapter/src/hisysevent_adapter_impl.cpp index 66f7da4d5624be495391672893f19b980f5aa6e8..19fa066bc940c5fec05a7ae6cac9b2ad278570d3 100644 --- a/ohos_adapter/hiviewdfx_adapter/src/hisysevent_adapter_impl.cpp +++ b/ohos_adapter/hiviewdfx_adapter/src/hisysevent_adapter_impl.cpp @@ -17,6 +17,7 @@ #include "application_context.h" #include "hisysevent_adapter_impl.h" #include "hisysevent.h" +#include "ohos_resource_adapter_impl.h" namespace OHOS::NWeb { namespace { @@ -29,6 +30,7 @@ const HiviewDFX::HiSysEvent::EventType EVENT_TYPES[] = { } static std::string g_currentBundleName = ""; +static std::string g_versionCode = ""; HiSysEventAdapterImpl& HiSysEventAdapterImpl::GetInstance() { static HiSysEventAdapterImpl instance; @@ -45,7 +47,13 @@ static int ForwardToHiSysEvent(const std::string& eventName, HiSysEventAdapter:: g_currentBundleName = appInfo->bundleName.c_str(); } } - std::tuple sysData("BUNDLE_NAME", g_currentBundleName.c_str()); + if (g_versionCode.empty()) { + g_versionCode = OhosResourceAdapterImpl::GetArkWebVersion(); + } + std::tuple sysData( + "BUNDLE_NAME", g_currentBundleName.c_str(), + "VERSION_CODE", g_versionCode.c_str() + ); auto mergeData = std::tuple_cat(sysData, tp); return std::apply( @@ -179,10 +187,16 @@ int HiSysEventAdapterImpl::Write(const std::string& eventName, EventType type, const std::string, const std::string, const std::string, const std::string, const std::string, const std::string, const std::string, const std::string>& data) { + std::string versionCode = OhosResourceAdapterImpl::GetArkWebVersion(); + auto extendedData = std::tuple_cat( + std::make_tuple("VERSION_CODE", versionCode.c_str()), + data + ); + return std::apply( [&](auto&&... args) { return HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::WEBVIEW, eventName, EVENT_TYPES[type], args...); }, - data); + extendedData); } } // namespace OHOS::NWeb diff --git a/ohos_adapter/hiviewdfx_adapter/src/hitrace_adapter_impl.cpp b/ohos_adapter/hiviewdfx_adapter/src/hitrace_adapter_impl.cpp index 27ef05c3c7d75ca9f3818d84e4a196df99c7bd7f..62faf1a0145d0bec7fe6c3752598b42d4b89e1bc 100644 --- a/ohos_adapter/hiviewdfx_adapter/src/hitrace_adapter_impl.cpp +++ b/ohos_adapter/hiviewdfx_adapter/src/hitrace_adapter_impl.cpp @@ -62,47 +62,43 @@ bool HiTraceAdapterImpl::IsHiTraceEnable() static CachedHandle g_Handle = CachedParameterCreate("debug.hitrace.tags.enableflags", "0"); int changed = 0; const char *enable = CachedParameterGetChanged(g_Handle, &changed); - auto tags = ConvertToInt(enable, 0); - firstAceEnable_ = tags & HITRACE_TAG_ACE; + uint64_t tags = static_cast(ConvertToInt(enable, 0)); return (tags & HITRACE_TAG_NWEB); } void HiTraceAdapterImpl::StartOHOSTrace(const std::string& value, float limit) { - if (isOHOSTraceEnable_) { - ::StartTrace(HITRACE_TAG_ACE, value, limit); - } else if (isNWEBTraceEnable_) { + if (IsHiTraceEnable()) { ::StartTrace(HITRACE_TAG_NWEB, value, limit); + } else if (IsACETraceEnable()) { + ::StartTrace(HITRACE_TAG_ACE, value, limit); } } void HiTraceAdapterImpl::FinishOHOSTrace() { - if (isOHOSTraceEnable_) { - ::FinishTrace(HITRACE_TAG_ACE); - } else if (isNWEBTraceEnable_) { + if (IsHiTraceEnable()) { ::FinishTrace(HITRACE_TAG_NWEB); + } else if (IsACETraceEnable()) { + ::FinishTrace(HITRACE_TAG_ACE); } } void HiTraceAdapterImpl::CountOHOSTrace(const std::string& name, int64_t count) { - if (isOHOSTraceEnable_) { - ::CountTrace(HITRACE_TAG_ACE, name, count); - } else if (isNWEBTraceEnable_) { + if (IsHiTraceEnable()) { ::CountTrace(HITRACE_TAG_NWEB, name, count); + } else if (IsACETraceEnable()) { + ::CountTrace(HITRACE_TAG_ACE, name, count); } } -void HiTraceAdapterImpl::UpdateOHOSTraceTag(const char* value) -{ - auto status = std::stoul(value); - isNWEBTraceEnable_ = status & HITRACE_TAG_NWEB; - isOHOSTraceEnable_ = status & HITRACE_TAG_ACE; -} - bool HiTraceAdapterImpl::IsACETraceEnable() { - return firstAceEnable_; + static CachedHandle g_Handle = CachedParameterCreate("debug.hitrace.tags.enableflags", "0"); + int changed = 0; + const char *enable = CachedParameterGetChanged(g_Handle, &changed); + uint64_t tags = static_cast(ConvertToInt(enable, 0)); + return (tags & HITRACE_TAG_ACE); } } // namespace OHOS::NWeb diff --git a/ohos_adapter/inputmethodframework_adapter/include/imf_adapter_impl.h b/ohos_adapter/inputmethodframework_adapter/include/imf_adapter_impl.h index 5c0a35435f5aae2498d81e0abcaf4cafd57f8a5f..46b3ae7e941a0cb0d401e2e66badffb52c943370 100644 --- a/ohos_adapter/inputmethodframework_adapter/include/imf_adapter_impl.h +++ b/ohos_adapter/inputmethodframework_adapter/include/imf_adapter_impl.h @@ -86,6 +86,8 @@ private: std::shared_ptr listener_ = nullptr; const std::string PREVIEW_TEXT_STYLE_KEY = "previewTextStyle"; const std::string PREVIEW_TEXT_STYLE_UNDERLINE = "underline"; + const std::string AUTO_FILL_PARAMS_USERNAME = "com.autofill.params.userName"; + const std::string AUTO_FILL_PARAMS_OTHERACCOUNT = "com.autofill.params.otherAccount"; }; class IMFAdapterImpl : public IMFAdapter { @@ -109,8 +111,13 @@ public: void OnSelectionChange(std::u16string text, int start, int end) override; + bool SendPrivateCommand(const std::string& commandKey, const std::string& commandValue) override; + private: sptr textListener_ = nullptr; + + bool ParseFillContentJsonValue(const std::string& jsonStr, + std::unordered_map>& map); }; } // namespace OHOS::NWeb diff --git a/ohos_adapter/inputmethodframework_adapter/src/imf_adapter_impl.cpp b/ohos_adapter/inputmethodframework_adapter/src/imf_adapter_impl.cpp index e2b5bc8f3d128277b5baef346aa44c4e6e4a047e..cc4942aeec38a4db3d5b6a697871e5691e7feb8b 100644 --- a/ohos_adapter/inputmethodframework_adapter/src/imf_adapter_impl.cpp +++ b/ohos_adapter/inputmethodframework_adapter/src/imf_adapter_impl.cpp @@ -18,6 +18,7 @@ #include "hisysevent_adapter.h" #include "nweb_log.h" #include "ohos_adapter_helper.h" +#include "third_party/cJSON/cJSON.h" namespace OHOS::NWeb { constexpr char INPUT_METHOD[] = "INPUT_METHOD"; @@ -25,6 +26,7 @@ constexpr char ATTACH_CODE[] = "ATTACH_CODE"; constexpr char IS_SHOW_KEY_BOARD[] = "IS_SHOW_KEY_BOARD"; constexpr int32_t IMF_LISTENER_NULL_POINT = 1; constexpr int32_t IMF_TEXT_CONFIG_NULL_POINT = 2; +const std::string AUTO_FILL_CANCEL_PRIVATE_COMMAND = "autofill.cancel"; IMFTextListenerAdapterImpl::IMFTextListenerAdapterImpl(const std::shared_ptr& listener) : listener_(listener) {}; @@ -231,6 +233,22 @@ int32_t IMFTextListenerAdapterImpl::ReceivePrivateCommand( } } + item = privateCommand.find(AUTO_FILL_PARAMS_USERNAME); + if (item != privateCommand.end()) { + if (listener_) { + std::string content = std::get(item->second); + listener_->AutoFillWithIMFEvent(true, false, false, content); + } + } + + item = privateCommand.find(AUTO_FILL_PARAMS_OTHERACCOUNT); + if (item != privateCommand.end()) { + if (listener_) { + std::string content = std::string(""); + listener_->AutoFillWithIMFEvent(false, true, false, content); + } + } + return 0; } @@ -300,9 +318,13 @@ bool IMFAdapterImpl::Attach(std::shared_ptr listener, bo .width = config->GetCursorInfo()->GetWidth(), .height = config->GetCursorInfo()->GetHeight() }; - MiscServices::TextConfig textConfig = { - .inputAttribute = inputAttribute, .cursorInfo = imfInfo, .windowId = config->GetWindowId() - }; + MiscServices::TextConfig textConfig = { .inputAttribute = inputAttribute, + .cursorInfo = imfInfo, + .windowId = config->GetWindowId(), + .positionY = config->GetPositionY(), + .height = config->GetHeight() }; + WVLOG_I("web inputmethod attach, isShowKeyboard=%{public}d, textConfig=%{public}s", isShowKeyboard, + textConfig.ToString().c_str()); int32_t ret = MiscServices::InputMethodController::GetInstance()->Attach(textListener_, isShowKeyboard, textConfig); if (ret != 0) { WVLOG_E("inputmethod attach failed, errcode=%{public}d", ret); @@ -354,4 +376,44 @@ void IMFAdapterImpl::OnSelectionChange(std::u16string text, int start, int end) { MiscServices::InputMethodController::GetInstance()->OnSelectionChange(text, start, end); } + +bool IMFAdapterImpl::SendPrivateCommand(const std::string& commandKey, const std::string& commandValue) +{ + if (commandKey == AUTO_FILL_CANCEL_PRIVATE_COMMAND) { + std::unordered_map privateCommand; + ParseFillContentJsonValue(commandValue, privateCommand); + int32_t ret = MiscServices::InputMethodController::GetInstance()->SendPrivateCommand(privateCommand); + if (ret != 0) { + WVLOG_E("inputmethod SendPrivateCommand failed, errcode=%{public}d", ret); + return false; + } + WVLOG_I("inputmethod SendPrivateCommand success"); + return true; + } + return false; +} + +bool IMFAdapterImpl::ParseFillContentJsonValue(const std::string& commandValue, + std::unordered_map>& map) +{ + cJSON* sourceJson = cJSON_Parse(commandValue.c_str()); + if (sourceJson == nullptr || cJSON_IsNull(sourceJson)) { + cJSON_Delete(sourceJson); + return false; + } + if (cJSON_HasObjectItem(sourceJson, "userName")) { + cJSON* userName = cJSON_GetObjectItem(sourceJson, "userName"); + if (userName != nullptr && cJSON_IsString(userName) && userName->valuestring != nullptr) { + map.insert(std::make_pair("userName", userName->valuestring)); + } + } + if (cJSON_HasObjectItem(sourceJson, "hasAccount")) { + cJSON* hasAccount = cJSON_GetObjectItem(sourceJson, "hasAccount"); + if (hasAccount != nullptr && cJSON_IsString(hasAccount) && hasAccount->valuestring != nullptr) { + map.insert(std::make_pair("hasAccount", hasAccount->valuestring)); + } + } + cJSON_Delete(sourceJson); + return true; +} } // namespace OHOS::NWeb diff --git a/ohos_adapter/location_adapter/src/location_proxy_adapter_impl.cpp b/ohos_adapter/location_adapter/src/location_proxy_adapter_impl.cpp index 7e42d1c82824601bb7b0360906913d28139f2125..7fa1fc59aa7f50b85f4ea5dd46afe614760c1386 100755 --- a/ohos_adapter/location_adapter/src/location_proxy_adapter_impl.cpp +++ b/ohos_adapter/location_adapter/src/location_proxy_adapter_impl.cpp @@ -27,8 +27,10 @@ using namespace OHOS::Location; namespace { #if defined (__aarch64__) || (__x86_64__) const std::string NWEB_WRAPPER_SO_PATH = "/system/lib64/libnweb_ohos_wrapper.z.so"; +const std::string ARKWEB_WRAPPER_SO_PATH = "/system/lib64/libarkweb_os_wrapper.z.so"; #else const std::string NWEB_WRAPPER_SO_PATH = "/system/lib/libnweb_ohos_wrapper.z.so"; +const std::string ARKWEB_WRAPPER_SO_PATH = "/system/lib/libarkweb_os_wrapper.z.so"; #endif int32_t ConvertScenario(int32_t scenario) { @@ -229,6 +231,9 @@ StopLocatingFuncType LocationProxyAdapterImpl::stopLocatingFunc_; LocationProxyAdapterImpl::LocationProxyAdapterImpl() { + if (!wrapperHandle_) { + wrapperHandle_ = dlopen(ARKWEB_WRAPPER_SO_PATH.c_str(), RTLD_NOW | RTLD_GLOBAL); + } if (!wrapperHandle_) { wrapperHandle_ = dlopen(NWEB_WRAPPER_SO_PATH.c_str(), RTLD_NOW | RTLD_GLOBAL); } diff --git a/ohos_adapter/media_adapter/src/media_avsession_adapter_impl.cpp b/ohos_adapter/media_adapter/src/media_avsession_adapter_impl.cpp index 68ad30ecccaac8ac6e2dc660bb645cec9b3e4fe2..bfec063b2f5681f887eb7db6672d91b37d920a9b 100644 --- a/ohos_adapter/media_adapter/src/media_avsession_adapter_impl.cpp +++ b/ohos_adapter/media_adapter/src/media_avsession_adapter_impl.cpp @@ -18,8 +18,13 @@ #include "ability_manager_client.h" #include "avsession_errors.h" #include "avsession_manager.h" +#include "bundle_mgr_proxy.h" #include "element_name.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" #include "nweb_log.h" +#include "parameters.h" +#include "system_ability_definition.h" namespace OHOS::NWeb { @@ -114,6 +119,48 @@ void MediaAVSessionKey::Init() { element_.SetBundleName(context->GetBundleName()); } type_ = MediaAVSessionType::MEDIA_TYPE_INVALID; + + // SA application can get AbilityName by GetTopAbility, but others cannnot. + if (!element_.GetAbilityName().empty()){ + return; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + WVLOG_E("get SystemAbilityManager failed"); + return; + } + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + WVLOG_E("get Bundle Manager failed"); + return; + } + auto bundleMgr = iface_cast(remoteObject); + if (bundleMgr == nullptr) { + WVLOG_E("get Bundle Manager failed"); + return; + } + AppExecFwk::BundleInfo bundleInfo; + auto flag = (static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) | + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY)); + if (bundleMgr->GetBundleInfoForSelf(flag, bundleInfo) != 0) { + WVLOG_E("get bundle info failed"); + return; + } + auto hapModuleInfos = bundleInfo.hapModuleInfos; + if (hapModuleInfos.empty()) { + WVLOG_E("get hapModuleInfos failed"); + return; + } + auto abilityInfos = hapModuleInfos[0].abilityInfos; + if (abilityInfos.empty()) { + WVLOG_E("get abilityInfos failed"); + return; + } + element_.SetAbilityName(abilityInfos[0].name); + return; } int32_t MediaAVSessionKey::GetPID() { @@ -149,7 +196,9 @@ MediaAVSessionAdapterImpl::~MediaAVSessionAdapterImpl() { } bool MediaAVSessionAdapterImpl::CreateAVSession(MediaAVSessionType type) { + WVLOG_I("media avsession adapter CreateAVSession in, type=%{public}d", int32_t(type)); if (MediaAVSessionType::MEDIA_TYPE_INVALID == type) { + WVLOG_E("media avsession adapter CreateAVSession, type invalid return false"); return false; } if (avSession_ && (type != avSessionKey_->GetType())) { @@ -167,6 +216,7 @@ bool MediaAVSessionAdapterImpl::CreateAVSession(MediaAVSessionType type) { DestroyAndEraseSession(); DestroyAVSession(); } else { + WVLOG_E("media avsession adapter CreateAVSession, return false"); return false; } } @@ -175,10 +225,13 @@ bool MediaAVSessionAdapterImpl::CreateAVSession(MediaAVSessionType type) { } void MediaAVSessionAdapterImpl::DestroyAVSession() { + WVLOG_I("media avsession adapter DestroyAVSession in"); if (avSession_) { int32_t ret = avSession_->Destroy(); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter destroy avsession failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter DestroyAVSession Destroy() failed, ret: %{public}d", ret); + } else { + WVLOG_I("media avsession adapter DestroyAVSession Destroy() success, ret: %{public}d", ret); } avSession_.reset(); } @@ -186,15 +239,17 @@ void MediaAVSessionAdapterImpl::DestroyAVSession() { if (iter != avSessionMap.end()) { avSessionMap.erase(iter); } + WVLOG_I("media avsession adapter DestroyAVSession out"); } bool MediaAVSessionAdapterImpl::RegistCallback( std::shared_ptr callbackAdapter) { + WVLOG_I("media avsession adapter RegistCallback in"); if (avSession_ && Activate()) { auto callback = std::make_shared(callbackAdapter); int32_t ret = avSession_->RegisterCallback(callback); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter register callback failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter RegistCallback RegisterCallback() failed, ret: %{public}d", ret); return false; } static const std::vector commands = { @@ -206,32 +261,43 @@ bool MediaAVSessionAdapterImpl::RegistCallback( for (auto command : commands) { ret = avSession_->AddSupportCommand(command); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter add command '%{public}d' failed, ret: %{public}d", command, ret); + WVLOG_E("media avsession adapter RegistCallback AddSupportCommand() '%{public}d' failed", command); + } else { + WVLOG_I("media avsession adapter RegistCallback AddSupportCommand() '%{public}d' success", command); } } + WVLOG_I("media avsession adapter RegistCallback out return true"); return true; } + WVLOG_I("media avsession adapter RegistCallback out return false"); return false; } bool MediaAVSessionAdapterImpl::IsActivated() { + WVLOG_I("media avsession adapter IsActivated in"); if (avSession_) { - return avSession_->IsActive(); + bool ret = avSession_->IsActive(); + WVLOG_I("media avsession adapter IsActive out ret: %{public}d", ret); + return ret; } + WVLOG_E("media avsession adapter IsActivated out avSession is null, return false"); return false; } bool MediaAVSessionAdapterImpl::Activate() { if (!avSession_) { + WVLOG_E("media avsession adapter Activate avSession_ is null, return false"); return false; } else if (avSession_->IsActive()) { + WVLOG_I("media avsession adapter Activate IsActive() is true, return true"); return true; } int32_t ret = avSession_->Activate(); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter activate avsession failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter Activate Activate() failed, ret: %{public}d", ret); return false; } + WVLOG_I("media avsession adapter Activate return true"); return true; } @@ -251,7 +317,9 @@ void MediaAVSessionAdapterImpl::SetMetadata(const std::shared_ptrSetAVMetaData(*avMetadata); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter update metadata info failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter SetMetadata SetAVMetaData() failed, ret: %{public}d", ret); + } else { + WVLOG_I("media avsession adapter SetMetadata SetAVMetaData() success, ret: %{public}d", ret); } } } @@ -262,7 +330,9 @@ void MediaAVSessionAdapterImpl::SetPlaybackState(MediaAVSessionPlayState state) auto avPlaybackState = avPlaybackState_.get(); int32_t ret = avSession_->SetAVPlaybackState(*avPlaybackState); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter update playback state failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter SetPlaybackState SetAVPlaybackState() failed, ret: %{public}d", ret); + } else { + WVLOG_I("media avsession adapter SetPlaybackState SetAVPlaybackState() success, ret: %{public}d", ret); } } } @@ -273,7 +343,9 @@ void MediaAVSessionAdapterImpl::SetPlaybackPosition(const std::shared_ptrSetAVMetaData(*avMetadata); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter update metadata duration failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter SetPlaybackPosition SetAVMetaData() failed, ret: %{public}d", ret); + } else { + WVLOG_I("media avsession adapter SetPlaybackPosition SetAVMetaData() success, ret: %{public}d", ret); } } if (UpdatePlaybackStateCache(position) && avSession_) { @@ -281,7 +353,9 @@ void MediaAVSessionAdapterImpl::SetPlaybackPosition(const std::shared_ptrSetAVPlaybackState(*avPlaybackState); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter update playback position failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter SetPlaybackPosition SetAVPlaybackState() failed, ret: %{public}d", ret); + } else { + WVLOG_I("media avsession adapter SetPlaybackPosition SetAVPlaybackState() success, ret: %{public}d", ret); } } } @@ -300,14 +374,17 @@ bool MediaAVSessionAdapterImpl::UpdateMetaDataCache(const std::shared_ptrSetAlbum(metadata->GetAlbum()); updated = true; } + WVLOG_I("media avsession adapter UpdateMetaDataCache return updated: %{public}d", updated); return updated; } bool MediaAVSessionAdapterImpl::UpdateMetaDataCache(const std::shared_ptr position) { if (avMetadata_->GetDuration() != position->GetDuration()) { avMetadata_->SetDuration(position->GetDuration()); + WVLOG_I("media avsession adapter UpdateMetaDataCache return true"); return true; } + WVLOG_E("media avsession adapter UpdateMetaDataCache return false"); return false; } @@ -327,8 +404,10 @@ bool MediaAVSessionAdapterImpl::UpdatePlaybackStateCache(MediaAVSessionPlayState } if (avPlaybackState_->GetState() != currentState) { avPlaybackState_->SetState(currentState); + WVLOG_I("media avsession adapter UpdatePlaybackStateCache return true"); return true; } + WVLOG_E("media avsession adapter UpdatePlaybackStateCache return false"); return false; } @@ -348,39 +427,44 @@ bool MediaAVSessionAdapterImpl::UpdatePlaybackStateCache( avPlaybackState_->SetPosition(avPosition); updated = true; } + WVLOG_I("media avsession adapter UpdatePlaybackStateCache return updated: %{public}d", updated); return updated; } void MediaAVSessionAdapterImpl::DestroyAndEraseSession() { + WVLOG_I("media avsession adapter DestroyAndEraseSession in"); auto iter = avSessionMap.find(avSessionKey_->ToString()); if (iter == avSessionMap.end()) { - WVLOG_E("media avsession adapter invalid iterator"); + WVLOG_E("media avsession adapter DestroyAndEraseSession invalid iterator return"); return; } if (!iter->second) { - WVLOG_E("media avsession adapter avsession is null pointer in map"); avSessionMap.erase(iter); + WVLOG_E("media avsession adapter DestroyAndEraseSession avsession is null pointer return"); return; } int32_t ret = iter->second->Destroy(); if (ret != AVSession::AVSESSION_SUCCESS) { - WVLOG_E("media avsession adapter destroy previous avsession failed, ret: %{public}d", ret); + WVLOG_E("media avsession adapter DestroyAndEraseSession Destroy failed, ret: %{public}d", ret); + } else { + WVLOG_I("media avsession adapter DestroyAndEraseSession Destroy success, ret: %{public}d", ret); } iter->second.reset(); avSessionMap.erase(iter); + WVLOG_I("media avsession adapter DestroyAndEraseSession out"); } bool MediaAVSessionAdapterImpl::CreateNewSession(const MediaAVSessionType& type) { + WVLOG_I("media avsession adapter CreateNewSession in"); avSession_ = AVSession::AVSessionManager::GetInstance().CreateSession( - avSessionKey_->GetElement().GetBundleName(), - static_cast(type), - avSessionKey_->GetElement()); + avSessionKey_->GetElement().GetBundleName(), static_cast(type), avSessionKey_->GetElement()); if (avSession_) { avSessionKey_->SetType(type); - avSessionMap.insert(std::make_pair(avSessionKey_->ToString(), avSession_)); + avSessionMap.insert( + std::pair>(avSessionKey_->ToString(), avSession_)); return true; } else { - WVLOG_E("media avsession adapter create avsession failed"); + WVLOG_E("media avsession adapter CreateNewSession Fail, out return false"); return false; } } diff --git a/ohos_adapter/net_connect_adapter/include/net_capabilities_adapter_impl.h b/ohos_adapter/net_connect_adapter/include/net_capabilities_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..c53b9526c5fb73ad7e71e7a90e9fdfa3922b86ca --- /dev/null +++ b/ohos_adapter/net_connect_adapter/include/net_capabilities_adapter_impl.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CAPABILITIES_ADAPTER_IMPL_H +#define NET_CAPABILITIES_ADAPTER_IMPL_H + +#include "net_connect_adapter.h" + +namespace OHOS::NWeb { + +class NetCapabilitiesAdapterImpl : public NetCapabilitiesAdapter { +public: + NetCapabilitiesAdapterImpl() = default; + + ~NetCapabilitiesAdapterImpl() override = default; + + int32_t GetNetId() override; + + NetConnectType GetConnectType() override; + + NetConnectSubtype GetConnectSubtype() override; + + void SetNetId(int32_t netId); + + void SetConnectType(NetConnectType type); + + void SetConnectSubtype(NetConnectSubtype subtype); + +private: + int32_t netId_ = -1; + NetConnectType type_ = NetConnectType::CONNECTION_UNKNOWN; + NetConnectSubtype subtype_ = NetConnectSubtype::SUBTYPE_UNKNOWN; +}; + +} // namespace OHOS::NWeb + +#endif // NET_CAPABILITIES_ADAPTER_IMPL_H diff --git a/ohos_adapter/net_connect_adapter/include/net_connection_properties_adapter_impl.h b/ohos_adapter/net_connect_adapter/include/net_connection_properties_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..c453e8e17aeaa5b063b7c002aa170f6abdb268e6 --- /dev/null +++ b/ohos_adapter/net_connect_adapter/include/net_connection_properties_adapter_impl.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONNECTION_PROPERTIES_ADAPTER_IMPL_H +#define NET_CONNECTION_PROPERTIES_ADAPTER_IMPL_H + +#include "net_connect_adapter.h" + +namespace OHOS::NWeb { + +class NetConnectionPropertiesAdapterImpl : public NetConnectionPropertiesAdapter { +public: + NetConnectionPropertiesAdapterImpl() = default; + + ~NetConnectionPropertiesAdapterImpl() override = default; + + int32_t GetNetId() override; + + void SetNetId(int32_t netId); + +private: + int32_t netId_ = -1; +}; + +} // namespace OHOS::NWeb + +#endif // NET_CONNECTION_PROPERTIES_ADAPTER_IMPL_H diff --git a/ohos_adapter/net_connect_adapter/src/net_capabilities_adapter_impl.cpp b/ohos_adapter/net_connect_adapter/src/net_capabilities_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d63e0ea51a6622a964e47e7b7b62c6939ec305e --- /dev/null +++ b/ohos_adapter/net_connect_adapter/src/net_capabilities_adapter_impl.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_capabilities_adapter_impl.h" + +namespace OHOS::NWeb { + +int32_t NetCapabilitiesAdapterImpl::GetNetId() +{ + return netId_; +} + +NetConnectType NetCapabilitiesAdapterImpl::GetConnectType() +{ + return type_; +} + +NetConnectSubtype NetCapabilitiesAdapterImpl::GetConnectSubtype() +{ + return subtype_; +} + +void NetCapabilitiesAdapterImpl::SetNetId(int32_t netId) +{ + netId_ = netId; +} + +void NetCapabilitiesAdapterImpl::SetConnectType(NetConnectType type) +{ + type_ = type; +} + +void NetCapabilitiesAdapterImpl::SetConnectSubtype(NetConnectSubtype subtype) +{ + subtype_ = subtype; +} + +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/ohos_adapter/net_connect_adapter/src/net_connect_callback_impl.cpp b/ohos_adapter/net_connect_adapter/src/net_connect_callback_impl.cpp index ded4a4796617f393515502d7e64c3072d01df56f..151dfcf9e07b6ba34877e500e2a6ff14ae2a25e5 100644 --- a/ohos_adapter/net_connect_adapter/src/net_connect_callback_impl.cpp +++ b/ohos_adapter/net_connect_adapter/src/net_connect_callback_impl.cpp @@ -17,7 +17,9 @@ #include "cellular_data_client.h" #include "core_service_client.h" +#include "net_capabilities_adapter_impl.h" #include "net_connect_utils.h" +#include "net_connection_properties_adapter_impl.h" #include "nweb_log.h" namespace OHOS::NWeb { @@ -68,7 +70,11 @@ int32_t NetConnectCallbackImpl::NetCapabilitiesChange(sptr &netHandle NetConnectType type = NetConnectUtils::ConvertToConnectType(bearerTypes, radioTech); WVLOG_I("net connect type = %{public}s.", NetConnectUtils::ConnectTypeToString(type).c_str()); if (cb_ != nullptr) { - return cb_->NetCapabilitiesChange(type, subtype); + auto capabilites = std::make_shared(); + capabilites->SetNetId(netHandle->GetNetId()); + capabilites->SetConnectType(type); + capabilites->SetConnectSubtype(subtype); + return cb_->OnNetCapabilitiesChanged(capabilites); } } @@ -78,14 +84,16 @@ int32_t NetConnectCallbackImpl::NetCapabilitiesChange(sptr &netHandle int32_t NetConnectCallbackImpl::NetConnectionPropertiesChange(sptr &netHandle, const sptr &info) { if (netHandle == nullptr || info == nullptr) { - WVLOG_E("NetConnCallback enter, NetCapabilitiesChange, netHandle or info is nullptr."); + WVLOG_E("NetConnCallback enter, NetConnectionPropertiesChange, netHandle or info is nullptr."); return 0; } WVLOG_I("NetConnCallback enter, NetConnectionPropertiesChange, net id = %{public}d.", netHandle->GetNetId()); WVLOG_D("%{public}s.", info->ToString("").c_str()); if (cb_ != nullptr) { - return cb_->NetConnectionPropertiesChange(); + auto properties = std::make_shared(); + properties->SetNetId(netHandle->GetNetId()); + return cb_->OnNetConnectionPropertiesChanged(properties); } return 0; diff --git a/ohos_adapter/net_connect_adapter/src/net_connection_properties_adapter_impl.cpp b/ohos_adapter/net_connect_adapter/src/net_connection_properties_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..340aa4aa6b14b89012f1508c83f981c1759c36c6 --- /dev/null +++ b/ohos_adapter/net_connect_adapter/src/net_connection_properties_adapter_impl.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_connection_properties_adapter_impl.h" + +namespace OHOS::NWeb { + +int32_t NetConnectionPropertiesAdapterImpl::GetNetId() +{ + return netId_; +} + +void NetConnectionPropertiesAdapterImpl::SetNetId(int32_t netId) +{ + netId_ = netId; +} + +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/ohos_adapter/ohos_adapter_helper/include/ohos_adapter_helper_impl.h b/ohos_adapter/ohos_adapter_helper/include/ohos_adapter_helper_impl.h index 7ca517ce103ae7972e9aae6aff4da74e27313e27..93256f49a07caf4b398ba124a3d6ff278265cbfe 100644 --- a/ohos_adapter/ohos_adapter_helper/include/ohos_adapter_helper_impl.h +++ b/ohos_adapter/ohos_adapter_helper/include/ohos_adapter_helper_impl.h @@ -110,6 +110,10 @@ public: std::unique_ptr CreateMediaAVSessionAdapter() override; std::unique_ptr CreateOhosImageDecoderAdapter() override; + + std::unique_ptr CreateSensorAdapter() override; + + void SetArkWebCoreHapPathOverride(const std::string& hapPath) override; }; } // namespace OHOS::NWeb diff --git a/ohos_adapter/ohos_adapter_helper/src/ohos_adapter_helper_impl.cpp b/ohos_adapter/ohos_adapter_helper/src/ohos_adapter_helper_impl.cpp index 66b6a8f388c6393945955350c2e100f80c184a7c..0b4fe7f3e88dd5e555dcc7bb62753bc38bb65353 100644 --- a/ohos_adapter/ohos_adapter_helper/src/ohos_adapter_helper_impl.cpp +++ b/ohos_adapter/ohos_adapter_helper/src/ohos_adapter_helper_impl.cpp @@ -70,6 +70,9 @@ #include "system_properties_adapter_impl.h" #include "vsync_adapter_impl.h" #include "window_adapter_impl.h" +#if defined(NWEB_SENSORS_SENSOR_ENABLE) +#include "sensor_adapter_impl.h" +#endif namespace OHOS::NWeb { // static @@ -323,4 +326,19 @@ std::unique_ptr OhosAdapterHelperImpl::CreateOhosImageD { return std::make_unique(); } + +std::unique_ptr OhosAdapterHelperImpl::CreateSensorAdapter() +{ +#if defined(NWEB_SENSORS_SENSOR_ENABLE) + return std::make_unique(); +#else + return nullptr; +#endif +} + +void OhosAdapterHelperImpl::SetArkWebCoreHapPathOverride(const std::string& hapPath) +{ + OhosResourceAdapterImpl::SetArkWebCoreHapPathOverride(hapPath); +} + } // namespace OHOS::NWeb diff --git a/ohos_adapter/ohos_image_adapter/include/ohos_image_decoder_adapter_impl.h b/ohos_adapter/ohos_image_adapter/include/ohos_image_decoder_adapter_impl.h index 4e8af4e680fc62d17aee032267101158acceca7d..02e5125c0936dac2a8100cef31d58d53a0721d31 100755 --- a/ohos_adapter/ohos_image_adapter/include/ohos_image_decoder_adapter_impl.h +++ b/ohos_adapter/ohos_image_adapter/include/ohos_image_decoder_adapter_impl.h @@ -50,6 +50,7 @@ public: void* GetNativeWindowBuffer() override; int32_t GetPlanesCount() override; void ReleasePixelMap() override; + Media::PixelMap* GetPixelMap() { return pixelMap_.get(); } private: Media::ImageInfo imageInfo_; diff --git a/ohos_adapter/ohos_resource_adapter/include/ohos_resource_adapter_impl.h b/ohos_adapter/ohos_resource_adapter/include/ohos_resource_adapter_impl.h index 0375a43a9aa66cdbc284cc6e65c84670b16eafb1..ff776e0a36b8b94f6c9dffa5d3e6d94059e9fac9 100644 --- a/ohos_adapter/ohos_resource_adapter/include/ohos_resource_adapter_impl.h +++ b/ohos_adapter/ohos_resource_adapter/include/ohos_resource_adapter_impl.h @@ -70,6 +70,12 @@ public: static bool GetResourceString(const std::string& bundleName, const std::string& moduleName, const int32_t resId, std::string& result); + static std::string GetArkWebVersion(); + + static void SetArkWebCoreHapPathOverride(const std::string& hapPath); + + std::string GetSystemLanguage() override; + private: void Init(const std::string& hapPath); @@ -92,6 +98,7 @@ private: std::shared_ptr sysExtractor_; std::shared_ptr extractor_; + static std::string arkWebCoreHapPathOverride_; }; } // namespace OHOS::NWeb diff --git a/ohos_adapter/ohos_resource_adapter/src/ohos_resource_adapter_impl.cpp b/ohos_adapter/ohos_resource_adapter/src/ohos_resource_adapter_impl.cpp index 1dfb46511ac710eed88250716ae0e64b7636a039..3349bd4646e7344f974bb97ad7d6b2758785d1d1 100644 --- a/ohos_adapter/ohos_resource_adapter/src/ohos_resource_adapter_impl.cpp +++ b/ohos_adapter/ohos_resource_adapter/src/ohos_resource_adapter_impl.cpp @@ -18,21 +18,36 @@ #include #include #include +#include +#include #include +#include +#include +#include #include "application_context.h" #include "bundle_mgr_proxy.h" +#include "extractor.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" +#include "locale_config.h" #include "nweb_log.h" -#include "system_ability_definition.h" #include "ohos_adapter_helper.h" +#include "parameter.h" +#include "parameters.h" +#include "system_ability_definition.h" using namespace OHOS::AbilityBase; namespace { const std::string NWEB_HAP_PATH = "/system/app/com.ohos.nweb/NWeb.hap"; const std::string NWEB_HAP_PATH_1 = "/system/app/NWeb/NWeb.hap"; +const std::string ARKWEBCORE_HAP_SANDBOX_PATH = "/data/storage/el1/bundle/nweb/entry.hap"; +const std::string PERSIST_ARKWEBCORE_INSTALL_PATH = "persist.arkwebcore.install_path"; +const std::string NWEB_HAP_PATH_MODULE_UPDATE = "/module_update/ArkWebCore/app/com.ohos.nweb/NWeb.hap"; +const std::string HAP_REAL_PATH_PREFIX = "/data/app/el1/bundle/public/"; +const std::string HAP_SANDBOX_PATH_PREFIX = "/data/storage/el1/bundle/nweb/"; + const std::string NWEB_BUNDLE_NAME = "com.ohos.nweb"; const std::string NWEB_PACKAGE = "entry"; const std::string RAWFILE_PREFIX = "resources/rawfile/"; @@ -47,22 +62,6 @@ constexpr uint32_t START_YEAR = 1900; namespace OHOS::NWeb { namespace { -sptr GetBundleMgrProxy() -{ - auto systemAbilityMgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (!systemAbilityMgr) { - WVLOG_E("fail to get system ability mgr."); - return nullptr; - } - auto remoteObject = systemAbilityMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (!remoteObject) { - WVLOG_E("fail to get bundle manager proxy."); - return nullptr; - } - WVLOG_D("get bundle manager proxy success."); - return iface_cast(remoteObject); -} - std::shared_ptr GetResourceMgr( const std::string& bundleName, const std::string& moduleName) { @@ -125,28 +124,118 @@ bool ParseRawFile(const std::string& rawFile, return true; } -std::string GetNWebHapPath() +std::string convertToSandboxPath(const std::string& installPath, const std::string& prefixPath) +{ + if (installPath.empty()) { + return ""; + } + size_t result = installPath.find(HAP_REAL_PATH_PREFIX); + if (result != std::string::npos) { + size_t pos = installPath.find_last_of('/'); + if (pos != std::string::npos && pos != installPath.size() - 1) { + return prefixPath + installPath.substr(pos + 1); + } + } + return installPath; +} + +std::string GetArkWebHapPath(const std::string& arkWebCoreHapPathOverride, + std::vector>& errorMessage) { - auto iBundleMgr = GetBundleMgrProxy(); - if (iBundleMgr) { - OHOS::AppExecFwk::AbilityInfo abilityInfo; - OHOS::AppExecFwk::HapModuleInfo hapModuleInfo; - abilityInfo.bundleName = NWEB_BUNDLE_NAME; - abilityInfo.package = NWEB_PACKAGE; - if (iBundleMgr->GetHapModuleInfo(abilityInfo, hapModuleInfo)) { - WVLOG_D("get hap module info success. %{public}s", hapModuleInfo.hapPath.c_str()); - return hapModuleInfo.hapPath; + std::string prefixPath = WEBVIEW_SANDBOX_PATH; + if (access(arkWebCoreHapPathOverride.c_str(), F_OK) == 0) { + std::string sandboxPath = convertToSandboxPath(arkWebCoreHapPathOverride, prefixPath); + if (access(sandboxPath.c_str(), F_OK) == 0) { + WVLOG_D("eixt HAP_arkWebCoreHapPathOverride"); + return sandboxPath; } } + errorMessage.emplace_back("access arkWebCoreHapPathOverride path failed", errno); + + std::string installPath = convertToSandboxPath( + OHOS::system::GetParameter(PERSIST_ARKWEBCORE_INSTALL_PATH, ""), prefixPath); + if (access(installPath.c_str(), F_OK) == 0) { + WVLOG_D("exit install_path,%{public}s", installPath.c_str()); + return installPath; + } + errorMessage.emplace_back("access nweb install path failed", errno); + + if (access(WEBVIEW_SANDBOX_HAP_PATH, F_OK) == 0) { + WVLOG_D("exit WEBVIEW_SANDBOX_HAP_PATH"); + return WEBVIEW_SANDBOX_HAP_PATH; + } + errorMessage.emplace_back("access arkwebcore hap sandbox path failed", errno); + if (access(WEBVIEW_APP_HAP_PATH2, F_OK) == 0) { + WVLOG_D("exit WEBVIEW_APP_HAP_PATH2"); + return WEBVIEW_APP_HAP_PATH2; + } + errorMessage.emplace_back("access ohos nweb hap path failed", errno); + if (access(WEBVIEW_APP_HAP_PATH, F_OK) == 0) { + WVLOG_D("exit WEBVIEW_APP_HAP_PATH"); + return WEBVIEW_APP_HAP_PATH; + } + errorMessage.emplace_back("access nweb hap path failed", errno); + if (access(WEBVIEW_HAP_PATH, F_OK) == 0) { + WVLOG_D("exit WEBVIEW_HAP_PATH"); + return WEBVIEW_HAP_PATH; + } + errorMessage.emplace_back("access nweb hap module update path failed", errno); + return ""; +} + +std::string GetNWebHapPath(const std::string& arkWebCoreHapPathOverride) +{ + std::vector> errorMessage; + std::string arkWebHapPath = GetArkWebHapPath(arkWebCoreHapPathOverride, errorMessage); + if (!arkWebHapPath.empty()) { + return arkWebHapPath; + } + + std::string prefixPath = HAP_SANDBOX_PATH_PREFIX; + if (access(arkWebCoreHapPathOverride.c_str(), F_OK) == 0) { + WVLOG_D("eixt HAP_arkWebCoreHapPathOverride"); + std::string sandboxPath = convertToSandboxPath(arkWebCoreHapPathOverride, prefixPath); + WVLOG_D("sandboxPath,%{public}s", sandboxPath.c_str()); + if (access(sandboxPath.c_str(), F_OK) == 0) { + return sandboxPath; + } + } + errorMessage.emplace_back("access arkWebCoreHapPathOverride path failed", errno); + + std::string installPath = convertToSandboxPath( + OHOS::system::GetParameter(PERSIST_ARKWEBCORE_INSTALL_PATH, ""), prefixPath); + WVLOG_D("install_path,%{public}s", installPath.c_str()); + if (access(installPath.c_str(), F_OK) == 0) { + return installPath; + } + errorMessage.emplace_back("access nweb install path failed", errno); + + if (access(ARKWEBCORE_HAP_SANDBOX_PATH.c_str(), F_OK) == 0) { + WVLOG_D("eixt ARKWEBCORE_HAP_SANDBOX_PATH"); + return ARKWEBCORE_HAP_SANDBOX_PATH; + } + errorMessage.emplace_back("access arkwebcore hap sandbox path failed", errno); + if (access(NWEB_HAP_PATH.c_str(), F_OK) == 0) { WVLOG_D("eixt NWEB_HAP_PATH"); return NWEB_HAP_PATH; } + errorMessage.emplace_back("access ohos nweb hap path failed", errno); + if (access(NWEB_HAP_PATH_1.c_str(), F_OK) == 0) { WVLOG_D("eixt NWEB_HAP_PATH_1"); return NWEB_HAP_PATH_1; } - WVLOG_E("get nweb hap path failed."); + errorMessage.emplace_back("access nweb hap path failed", errno); + + if (access(NWEB_HAP_PATH_MODULE_UPDATE.c_str(), F_OK) == 0) { + WVLOG_D("eixt NWEB_HAP_PATH_MODULE_UPDATE"); + return NWEB_HAP_PATH_MODULE_UPDATE; + } + errorMessage.emplace_back("access nweb module update path failed", errno); + for (const auto& err : errorMessage) { + WVLOG_E("%{public}s, errno(%{public}d): %{public}s", err.first.c_str(), err.second, strerror(err.second)); + } return ""; } } // namespace @@ -199,6 +288,7 @@ bool OhosFileMapperImpl::UnzipData(uint8_t** dest, size_t& len) return false; } +std::string OhosResourceAdapterImpl::arkWebCoreHapPathOverride_ = ""; OhosResourceAdapterImpl::OhosResourceAdapterImpl(const std::string& hapPath) { Init(hapPath); @@ -207,7 +297,7 @@ OhosResourceAdapterImpl::OhosResourceAdapterImpl(const std::string& hapPath) void OhosResourceAdapterImpl::Init(const std::string& hapPath) { bool newCreate = false; - std::string nwebHapPath = GetNWebHapPath(); + std::string nwebHapPath = GetNWebHapPath(arkWebCoreHapPathOverride_); if (!nwebHapPath.empty()) { sysExtractor_ = ExtractorUtil::GetExtractor(nwebHapPath, newCreate); if (!sysExtractor_) { @@ -426,4 +516,60 @@ std::shared_ptr OhosResourceAdapterImpl::GetRawFileMapper( bool isCompressed = fileMap->IsCompressed(); return std::make_shared(std::move(fileMap), isCompressed ? manager: nullptr); } + +std::string OhosResourceAdapterImpl::GetArkWebVersion() +{ + const std::string hapPaths[] = { + "/module_update/ArkWebCore/app/com.huawei.hmos.arkwebcore/ArkWebCore.hap", + "/system/app/com.ohos.arkwebcore/ArkWebCore.hap" + }; + const std::string packInfoPath = "pack.info"; + + for (const auto& hapPath : hapPaths) { + OHOS::AbilityBase::Extractor extractor(hapPath); + if (!extractor.Init()) { + WVLOG_E("Failed to initialize extractor for HAP file: %{public}s", hapPath.c_str()); + continue; + } + + std::ostringstream contentStream; + bool ret = extractor.ExtractByName(packInfoPath, contentStream); + if (!ret) { + WVLOG_E("Failed to extract pack.info from HAP: %{public}s", hapPath.c_str()); + continue; + } + + std::string configContent = contentStream.str(); + + Json::Value root; + Json::Reader reader; + if (!reader.parse(configContent, root)) { + WVLOG_E("Failed to parse pack.info from HAP: %{public}s", hapPath.c_str()); + continue; + } + + if (root.isMember("summary") && + root["summary"].isMember("app") && + root["summary"]["app"].isMember("version") && + root["summary"]["app"]["version"].isMember("name")) { + return root["summary"]["app"]["version"]["name"].asString(); + } + + WVLOG_E("Version information not found in pack.info from HAP: %{public}s", hapPath.c_str()); + } + + WVLOG_E("Failed to get ArkWeb version from any of the specified paths"); + return ""; +} + +void OhosResourceAdapterImpl::SetArkWebCoreHapPathOverride(const std::string& hapPath) +{ + arkWebCoreHapPathOverride_ = hapPath; +} + +std::string OhosResourceAdapterImpl::GetSystemLanguage() +{ + return OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); +} + } // namespace OHOS::NWeb diff --git a/ohos_adapter/print_manager_adapter/src/print_manager_adapter_impl.cpp b/ohos_adapter/print_manager_adapter/src/print_manager_adapter_impl.cpp index 007806ae6d2b2b44973e659d6d649c18fb034fed..f3e06783fb20b626b35322382a2768e196b836b3 100644 --- a/ohos_adapter/print_manager_adapter/src/print_manager_adapter_impl.cpp +++ b/ohos_adapter/print_manager_adapter/src/print_manager_adapter_impl.cpp @@ -44,7 +44,7 @@ int32_t PrintManagerAdapterImpl::Print(const std::string& printJobName, const std::shared_ptr listener, const PrintAttributesAdapter& printAttributes) { #if defined(NWEB_PRINT_ENABLE) - OHOS::Print::PrintDocumentAdapter* adapter = new PrintDocumentAdapterImpl(listener); + OHOS::Print::PrintDocumentAdapter* adapter = new (std::nothrow) PrintDocumentAdapterImpl(listener); if (!adapter) { WVLOG_E("adapter get failed"); return -1; @@ -75,7 +75,7 @@ int32_t PrintManagerAdapterImpl::Print(const std::string& printJobName, void* contextToken) { #if defined(NWEB_PRINT_ENABLE) - OHOS::Print::PrintDocumentAdapter* adapter = new PrintDocumentAdapterImpl(listener); + OHOS::Print::PrintDocumentAdapter* adapter = new (std::nothrow) PrintDocumentAdapterImpl(listener); if (!adapter) { WVLOG_E("adapter get failed"); return -1; diff --git a/ohos_adapter/res_sched_adapter/src/res_sched_client_adapter_impl.cpp b/ohos_adapter/res_sched_adapter/src/res_sched_client_adapter_impl.cpp index a98a1d3ab1005ffe53a86b8af055f565c0711a2f..afdd14cec969068ff422915d734149f862d75d95 100644 --- a/ohos_adapter/res_sched_adapter/src/res_sched_client_adapter_impl.cpp +++ b/ohos_adapter/res_sched_adapter/src/res_sched_client_adapter_impl.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "app_mgr_constants.h" #include "app_mgr_client.h" @@ -93,6 +94,7 @@ constexpr char STATE[] = "state"; std::set g_nwebSet; std::unordered_map> g_pidNwebMap; std::unordered_map> g_nwebProcessMap; +std::unordered_set g_processInUse; std::mutex g_windowIdMutex {}; int32_t g_windowId = INVALID_NUMBER; int32_t g_nwebId = INVALID_NUMBER; @@ -186,7 +188,25 @@ bool ReportSceneInternal(ResSchedStatusAdapter statusAdapter, ResSchedSceneAdapt return true; } -void ReportStatusData(ResSchedStatusAdapter statusAdapter, pid_t pid, uint32_t windowId, int32_t nwebId) +bool IsSameSourceWebSiteActive(ResSchedStatusAdapter statusAdapter, pid_t pid, int32_t nwebId) +{ + g_pidNwebMap[pid][nwebId] = statusAdapter; + if (statusAdapter == ResSchedStatusAdapter::WEB_INACTIVE) { + auto nwebMap = g_pidNwebMap[pid]; + for (auto it : nwebMap) { + if (it.second == ResSchedStatusAdapter::WEB_ACTIVE) { + WVLOG_D("IsSameSourceWebSiteActive, current nwebId: %{public}d, active nwebId: %{public}d, " + "pid: %{public}d", nwebId, it.first, pid); + return true; + } + } + g_pidNwebMap.erase(pid); + } + return false; +} + +void ReportStatusData(ResSchedStatusAdapter statusAdapter, + pid_t pid, uint32_t windowId, int32_t nwebId, bool isSiteManage) { static uint32_t serialNum = 0; static constexpr uint32_t serialNumMax = 10000; @@ -202,15 +222,10 @@ void ReportStatusData(ResSchedStatusAdapter statusAdapter, pid_t pid, uint32_t w return; } - g_pidNwebMap[pid][nwebId] = statusAdapter; - if (statusAdapter == ResSchedStatusAdapter::WEB_INACTIVE) { - auto nwebMap = g_pidNwebMap[pid]; - for (auto it : nwebMap) { - if (it.second == ResSchedStatusAdapter::WEB_ACTIVE) { - return; - } + if (g_processInUse.count(pid)) { + if (isSiteManage && IsSameSourceWebSiteActive(statusAdapter, pid, nwebId)) { + return; } - g_pidNwebMap.erase(pid); } if (pid == g_lastPid && status == g_lastStatus) { @@ -266,9 +281,13 @@ bool ResSchedClientAdapter::ReportKeyThread( WVLOG_D("ReportKeyThread status: %{public}d, uid: %{public}s, pid: %{public}d, tid:%{public}d, role: %{public}d", static_cast(status), GetUidString().c_str(), pid, tid, static_cast(role)); - if (pid == tid && g_windowId != INVALID_NUMBER && g_nwebId != INVALID_NUMBER && !g_siteIsolationMode) { + if (pid == tid && g_windowId != INVALID_NUMBER && g_nwebId != INVALID_NUMBER) { std::lock_guard lock(g_windowIdMutex); - ReportStatusData(ResSchedStatusAdapter::WEB_ACTIVE, pid, g_windowId, g_nwebId); + ReportStatusData(ResSchedStatusAdapter::WEB_ACTIVE, pid, g_windowId, g_nwebId, false); + } + + if (pid == tid && statusAdapter == ResSchedStatusAdapter::THREAD_DESTROYED) { + g_processInUse.erase(pid); } // Load url may create new render process, repeat report load url event when @@ -305,12 +324,14 @@ void ResSchedClientAdapter::ReportProcessInUse(pid_t pid) nwebId = g_pidNwebMap[pid].begin()->first; } + g_processInUse.insert(pid); + if (nwebId != INVALID_NUMBER) { g_nwebProcessMap[nwebId].push_back(pid); WVLOG_D("ReportProcessInUse nwebId: %{public}d, pid: %{public}d", nwebId, pid); if (g_siteIsolationMode) { - ReportStatusData(ResSchedStatusAdapter::WEB_ACTIVE, pid, g_windowId, nwebId); + ReportStatusData(ResSchedStatusAdapter::WEB_ACTIVE, pid, g_windowId, nwebId, true); } } } @@ -337,12 +358,12 @@ bool ResSchedClientAdapter::ReportWindowStatus( ReportWindowId(windowId, nwebId); } - ReportStatusData(statusAdapter, pid, windowId, nwebId); + ReportStatusData(statusAdapter, pid, windowId, nwebId, true); for (auto pidInNweb : g_nwebProcessMap[nwebId]) { if (pidInNweb == pid) { continue; } - ReportStatusData(statusAdapter, pidInNweb, windowId, nwebId); + ReportStatusData(statusAdapter, pidInNweb, windowId, nwebId, true); } return true; diff --git a/ohos_adapter/sensor_adapter/include/sensor_adapter_impl.h b/ohos_adapter/sensor_adapter/include/sensor_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..319e3cb9df90a22ea0b3468c64c9f940341f232b --- /dev/null +++ b/ohos_adapter/sensor_adapter/include/sensor_adapter_impl.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_ADAPTER_IMPL_H +#define SENSOR_ADAPTER_IMPL_H + +#include "sensor_adapter.h" +#include "sensor_agent.h" + +namespace OHOS::NWeb { + +class SensorCallbackImpl { +public: + SensorCallbackImpl(std::shared_ptr callbackAdapter); + ~SensorCallbackImpl() = default; + + void UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4); +private: + std::shared_ptr callbackAdapter_; +}; + +class SensorAdapterImpl : public SensorAdapter { +public: + SensorAdapterImpl() = default; + ~SensorAdapterImpl() = default; + + int32_t IsOhosSensorSupported(int32_t sensorTypeId) override; + int32_t GetOhosSensorReportingMode(int32_t sensorTypeId) override; + double GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) override; + double GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) override; + double GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) override; + int32_t SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) override; + int32_t RegistOhosSensorCallback(int32_t sensorTypeId, + std::shared_ptr callbackAdapter) override; + int32_t UnsubscribeOhosSensor(int32_t sensorTypeId) override; + +private: + static void OhosSensorCallback(SensorEvent* event); + static std::unordered_map> sensorCallbackMap; + + static void handleAccelerometerData(std::shared_ptr callback, + SensorEvent* event); + static void handleLinearAccelerometerData(std::shared_ptr callback, + SensorEvent* event); + static void handleGravityData(std::shared_ptr callback, + SensorEvent* event); + static void handleCyroscopeData(std::shared_ptr callback, + SensorEvent* event); + static void handleMagnetometerData(std::shared_ptr callback, + SensorEvent* event); + static void handleOrientationData(std::shared_ptr callback, + SensorEvent* event); + static void handleRotationVectorData(std::shared_ptr callback, + SensorEvent* event); + static void handleGameRotationVectorData(std::shared_ptr callback, + SensorEvent* event); + + SensorUser mSensorUser{}; +}; + +} +#endif // SENSOR_ADAPTER_IMPL_H \ No newline at end of file diff --git a/ohos_adapter/sensor_adapter/src/sensor_adapter_impl.cpp b/ohos_adapter/sensor_adapter/src/sensor_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e244a577044b5a5e9cf490137a64045c95adb51f --- /dev/null +++ b/ohos_adapter/sensor_adapter/src/sensor_adapter_impl.cpp @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sensor_adapter_impl.h" + +#include +#include + +#include "nweb_log.h" + +namespace OHOS::NWeb { + +std::unordered_map> SensorAdapterImpl::sensorCallbackMap; +constexpr double NANOSECONDS_IN_SECOND = 1000000000.0; +constexpr double DEFAULT_SAMPLE_PERIOD = 200000000.0; + +SensorTypeId SensorTypeToOhosSensorType(int sensorTypeId) +{ + SensorTypeId ohosSensorTypeId = SENSOR_TYPE_ID_NONE; + const static std::map TO_OHOS_SENSOR_TYPE_MAP = { + {2 /* ACCELEROMETER */, SENSOR_TYPE_ID_ACCELEROMETER }, + {3 /* LINEAR_ACCELERATION */, SENSOR_TYPE_ID_LINEAR_ACCELERATION }, + {4 /* GRAVITY */, SENSOR_TYPE_ID_GRAVITY }, + {5 /* GYROSCOPE */, SENSOR_TYPE_ID_GYROSCOPE }, + {6 /* MAGNETOMETER */, SENSOR_TYPE_ID_MAGNETIC_FIELD }, + {8 /* ABSOLUTE_ORIENTATION_EULER_ANGLES}*/, SENSOR_TYPE_ID_ORIENTATION }, + {9 /* ABSOLUTE_ORIENTATION_QUATERNION} */, SENSOR_TYPE_ID_ROTATION_VECTOR }, + {11 /* RELATIVE_ORIENTATION_QUATERNION} */, SENSOR_TYPE_ID_GAME_ROTATION_VECTOR } + }; + auto checkIter = TO_OHOS_SENSOR_TYPE_MAP.find(sensorTypeId); + if (checkIter != TO_OHOS_SENSOR_TYPE_MAP.end()) { + ohosSensorTypeId = checkIter->second; + } + return ohosSensorTypeId; +} + +std::string SensorTypeToSensorUserName(int sensorTypeId) +{ + const static std::map TO_OHOS_SENSOR_USER_NAME_MAP = { + {2 /* ACCELEROMETER */, "OhosAccelerometerService" }, + {3 /* LINEAR_ACCELERATION */, "OhosLinearAccelerometerService" }, + {4 /* GRAVITY */, "OhosGravityService" }, + {5 /* GYROSCOPE */, "OhosCyroscopeService" }, + {6 /* MAGNETOMETER */, "OhosMagnetometerService" }, + {8 /* ABSOLUTE_ORIENTATION_EULER_ANGLES}*/, "OhosOrientationService" }, + {9 /* ABSOLUTE_ORIENTATION_QUATERNION} */, "OhosRotationVectorService"}, + {11 /* RELATIVE_ORIENTATION_QUATERNION} */, "OhosGameRotationVectorService" } + }; + std::string userName = "OhosSensorService"; + auto checkIter = TO_OHOS_SENSOR_USER_NAME_MAP.find(sensorTypeId); + if (checkIter != TO_OHOS_SENSOR_USER_NAME_MAP.end()) { + userName = checkIter->second; + } + return userName; +} + +SensorCallbackImpl::SensorCallbackImpl( + std::shared_ptr callbackAdapter) + : callbackAdapter_(callbackAdapter) +{} + +void SensorCallbackImpl::UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) +{ + if (callbackAdapter_) { + callbackAdapter_->UpdateOhosSensorData(timestamp, value1, value2, value3, value4); + } +} + +int32_t SensorAdapterImpl::IsOhosSensorSupported(int32_t sensorTypeId) +{ + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + if (ohosSensorTypeId != SENSOR_TYPE_ID_NONE) { + SensorInfo* sensorInfo = nullptr; + int32_t count; + int ret = GetAllSensors(&sensorInfo, &count); + if (ret != SENSOR_SUCCESS || sensorInfo == nullptr || count < 0) { + WVLOG_E("IsOhosSensorSupported Error, ret = %{public}d, count = %{public}d.", ret, count); + return SENSOR_ERROR; + } + + for (int i = 0; i < count; i++) { + if (sensorInfo[i].sensorId == ohosSensorTypeId) { + WVLOG_I("IsOhosSensorSupported SUCCESS, sensorTypeId = %{public}d.", sensorTypeId); + return SENSOR_SUCCESS; + } + } + } + WVLOG_E("IsOhosSensorSupported Error, sensorTypeId = %{public}d is invalid.", sensorTypeId); + return SENSOR_ERROR; +} + +int32_t SensorAdapterImpl::GetOhosSensorReportingMode(int32_t sensorTypeId) +{ + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + int32_t reportingMode = -1; + switch (ohosSensorTypeId) { + case SENSOR_TYPE_ID_ACCELEROMETER: + case SENSOR_TYPE_ID_GRAVITY: + case SENSOR_TYPE_ID_LINEAR_ACCELERATION: + case SENSOR_TYPE_ID_GYROSCOPE: + case SENSOR_TYPE_ID_MAGNETIC_FIELD: + case SENSOR_TYPE_ID_ORIENTATION: + case SENSOR_TYPE_ID_ROTATION_VECTOR: + case SENSOR_TYPE_ID_GAME_ROTATION_VECTOR: + reportingMode = SENSOR_DATA_REPORT_CONTINUOUS; + break; + default: + break; + } + return reportingMode; +} + +double SensorAdapterImpl::GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) +{ + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + double defaultFrequency = 0.0; + if (ohosSensorTypeId != SENSOR_TYPE_ID_NONE) { + defaultFrequency = NANOSECONDS_IN_SECOND / DEFAULT_SAMPLE_PERIOD; + } + WVLOG_I("GetOhosSensorDefaultSupportedFrequency sensorTypeId: %{public}d, defaultFrequency: %{public}f", + sensorTypeId, defaultFrequency); + return defaultFrequency; +} + +double SensorAdapterImpl::GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) +{ + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + double minFrequency = 0.0; + if (ohosSensorTypeId == SENSOR_TYPE_ID_NONE) { + WVLOG_E("GetOhosSensorMinSupportedFrequency Error, sensorTypeId = %{public}d is invalid.", sensorTypeId); + return minFrequency; + } + SensorInfo* sensorInfo = nullptr; + int32_t count; + int ret = GetAllSensors(&sensorInfo, &count); + if (ret != SENSOR_SUCCESS || sensorInfo == nullptr || count < 0) { + WVLOG_E("GetOhosSensorMinSupportedFrequency Error, ret = %{public}d, count = %{public}d.", ret, count); + return minFrequency; + } + for (int i = 0; i < count; i++) { + if (sensorInfo[i].sensorId == ohosSensorTypeId) { + int64_t maxSamplePeriod = sensorInfo[i].maxSamplePeriod; + if (maxSamplePeriod > 0) { + minFrequency = NANOSECONDS_IN_SECOND / static_cast(maxSamplePeriod); + } + break; + } + } + WVLOG_I("GetOhosSensorMinSupportedFrequency sensorTypeId: %{public}d, minFrequency: %{public}f", + sensorTypeId, minFrequency); + return minFrequency; +} + +double SensorAdapterImpl::GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) +{ + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + double maxFrequency = 0.0; + if (ohosSensorTypeId == SENSOR_TYPE_ID_NONE) { + WVLOG_E("GetOhosSensorMaxSupportedFrequency Error, sensorTypeId = %{public}d is invalid.", sensorTypeId); + return maxFrequency; + } + SensorInfo* sensorInfo = nullptr; + int32_t count; + int ret = GetAllSensors(&sensorInfo, &count); + if (ret != SENSOR_SUCCESS || sensorInfo == nullptr || count < 0) { + WVLOG_E("GetOhosSensorMaxSupportedFrequency Error, ret = %{public}d, count = %{public}d.", ret, count); + return maxFrequency; + } + for (int i = 0; i < count; i++) { + if (sensorInfo[i].sensorId == ohosSensorTypeId) { + int64_t minSamplePeriod = sensorInfo[i].minSamplePeriod; + if (minSamplePeriod > 0) { + maxFrequency = NANOSECONDS_IN_SECOND / static_cast(minSamplePeriod); + } + break; + } + } + WVLOG_I("GetOhosSensorMaxSupportedFrequency sensorTypeId: %{public}d, maxFrequency: %{public}f", + sensorTypeId, maxFrequency); + return maxFrequency; +} + +void SensorAdapterImpl::handleAccelerometerData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleAccelerometerData Error."); + return; + } + AccelData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, 0.0f); + } +} + +void SensorAdapterImpl::handleLinearAccelerometerData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleLinearAccelerometerData Error."); + return; + } + LinearAccelData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, 0.0f); + } +} + +void SensorAdapterImpl::handleGravityData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleGravityData Error."); + return; + } + GravityData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, 0.0f); + } +} + +void SensorAdapterImpl::handleCyroscopeData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleCyroscopeData Error."); + return; + } + GyroscopeData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, 0.0f); + } +} + +void SensorAdapterImpl::handleMagnetometerData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleMagnetometerData Error."); + return; + } + MagneticFieldData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, 0.0f); + } +} + +void SensorAdapterImpl::handleOrientationData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleOrientationData Error."); + return; + } + OrientationData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->beta, data->gamma, data->alpha, 0.0f); + } +} + +void SensorAdapterImpl::handleRotationVectorData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleRotationVectorData Error."); + return; + } + RotationVectorData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, data->w); + } +} + +void SensorAdapterImpl::handleGameRotationVectorData(std::shared_ptr callback, + SensorEvent* event) +{ + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("handleGameRotationVectorData Error."); + return; + } + GameRotationVectorData* data = reinterpret_cast(event->data); + if (data != nullptr) { + callback->UpdateOhosSensorData(event->timestamp, data->x, data->y, data->z, data->w); + } +} + +void SensorAdapterImpl::OhosSensorCallback(SensorEvent* event) +{ + std::shared_ptr callback = nullptr; + auto findIter = sensorCallbackMap.find(event->sensorTypeId); + if (findIter != sensorCallbackMap.end()) { + callback = findIter->second; + } + if ((event == nullptr) || (callback == nullptr)) { + WVLOG_E("OhosSensorCallback Error."); + return; + } + switch (event->sensorTypeId) { + case SENSOR_TYPE_ID_ACCELEROMETER: + handleAccelerometerData(callback, event); + break; + case SENSOR_TYPE_ID_GRAVITY: + handleGravityData(callback, event); + break; + case SENSOR_TYPE_ID_LINEAR_ACCELERATION: + handleLinearAccelerometerData(callback, event); + break; + case SENSOR_TYPE_ID_GYROSCOPE: + handleCyroscopeData(callback, event); + break; + case SENSOR_TYPE_ID_MAGNETIC_FIELD: + handleMagnetometerData(callback, event); + break; + case SENSOR_TYPE_ID_ORIENTATION: + handleOrientationData(callback, event); + break; + case SENSOR_TYPE_ID_ROTATION_VECTOR: + handleRotationVectorData(callback, event); + break; + case SENSOR_TYPE_ID_GAME_ROTATION_VECTOR: + handleGameRotationVectorData(callback, event); + break; + default: + break; + } +} + +int32_t SensorAdapterImpl::SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) +{ + WVLOG_I("SubscribeOhosSensor sensorTypeId: %{public}d", sensorTypeId); + if (samplingInterval <= 0) { + WVLOG_E("SubscribeOhosSensor error, samplingInterval is invalid."); + return SENSOR_PARAMETER_ERROR; + } + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + if (ohosSensorTypeId == SENSOR_TYPE_ID_NONE) { + WVLOG_E("SubscribeOhosSensor error, sensorTypeId is invalid."); + return SENSOR_PARAMETER_ERROR; + } + + std::string userName = SensorTypeToSensorUserName(sensorTypeId); + (void)strcpy_s(mSensorUser.name, sizeof(mSensorUser.name), userName.c_str()); + mSensorUser.userData = nullptr; + mSensorUser.callback = OhosSensorCallback; + int32_t ret = SENSOR_SUCCESS; + ret = SubscribeSensor(ohosSensorTypeId, &mSensorUser); + if (ret != SENSOR_SUCCESS) { + WVLOG_E("SubscribeOhosSensor error, call SubscribeSensor ret = %{public}d.", ret); + return ret; + } + ret = SetBatch(ohosSensorTypeId, &mSensorUser, samplingInterval, samplingInterval); + if (ret != SENSOR_SUCCESS) { + WVLOG_E("SubscribeOhosSensor error, call SetBatch ret = %{public}d.", ret); + return ret; + } + ret = ActivateSensor(ohosSensorTypeId, &mSensorUser); + if (ret != SENSOR_SUCCESS) { + WVLOG_E("SubscribeOhosSensor error, call ActivateSensor ret = %{public}d.", ret); + return ret; + } + ret = SetMode(ohosSensorTypeId, &mSensorUser, SENSOR_REALTIME_MODE); + if (ret != SENSOR_SUCCESS) { + WVLOG_E("SubscribeOhosSensor error, call SetMode ret = %{public}d.", ret); + return ret; + } + return SENSOR_SUCCESS; +} + +int32_t SensorAdapterImpl::RegistOhosSensorCallback(int32_t sensorTypeId, + std::shared_ptr callbackAdapter) +{ + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + if (ohosSensorTypeId != SENSOR_TYPE_ID_NONE) { + auto callback = std::make_shared(callbackAdapter); + sensorCallbackMap[ohosSensorTypeId] = callback; + return SENSOR_SUCCESS; + } + WVLOG_E("RegistOhosSensorCallback error, sensorTypeId is invalid."); + return SENSOR_PARAMETER_ERROR; +} + +int32_t SensorAdapterImpl::UnsubscribeOhosSensor(int32_t sensorTypeId) +{ + WVLOG_I("UnsubscribeOhosSensor sensorTypeId: %{public}d.", sensorTypeId); + int32_t ohosSensorTypeId = SensorTypeToOhosSensorType(sensorTypeId); + if (ohosSensorTypeId != SENSOR_TYPE_ID_NONE) { + sensorCallbackMap.erase(ohosSensorTypeId); + int32_t ret = DeactivateSensor(ohosSensorTypeId, &mSensorUser); + if (ret != SENSOR_SUCCESS) { + WVLOG_E("UnsubscribeOhosSensor error, call DeactivateSensor ret = %{public}d.", ret); + return ret; + } + ret = UnsubscribeSensor(ohosSensorTypeId, &mSensorUser); + if (ret != SENSOR_SUCCESS) { + WVLOG_E("UnsubscribeOhosSensor error, call UnsubscribeSensor ret = %{public}d.", ret); + return ret; + } + return SENSOR_SUCCESS; + } + WVLOG_E("UnsubscribeOhosSensor error, sensorTypeId is invalid."); + return SENSOR_PARAMETER_ERROR; +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/ohos_adapter/system_properties_adapter/include/system_properties_adapter_impl.h b/ohos_adapter/system_properties_adapter/include/system_properties_adapter_impl.h index 5374542ad6a309eb4fdb1c9e6f9e84d753c42028..cf6d49621eb28ef88189f046c8256faba9148cf6 100644 --- a/ohos_adapter/system_properties_adapter/include/system_properties_adapter_impl.h +++ b/ohos_adapter/system_properties_adapter/include/system_properties_adapter_impl.h @@ -73,6 +73,8 @@ public: std::vector GetLTPOConfig(const std::string& settingName) override; std::string GetOOPGPUStatus() override; + + bool IsLTPODynamicApp(const std::string& bundleName) override; private: SystemPropertiesAdapterImpl(); diff --git a/ohos_adapter/system_properties_adapter/src/system_properties_adapter_impl.cpp b/ohos_adapter/system_properties_adapter/src/system_properties_adapter_impl.cpp index c5864c0867cf374ce7486d6cca60b7c01d263e9d..705f95eeb3a85175c7a17bb803a83c05b586d8a6 100644 --- a/ohos_adapter/system_properties_adapter/src/system_properties_adapter_impl.cpp +++ b/ohos_adapter/system_properties_adapter/src/system_properties_adapter_impl.cpp @@ -230,7 +230,7 @@ void SystemPropertiesAdapterImpl::AddAllSysPropWatchers() sysPropObserver_[item.second]; sysPropMutex_[item.second]; } else { - WVLOG_E("add watch error result: %{public}d", errNo); + WVLOG_I("add watch error result: %{public}d", errNo); } } } @@ -240,7 +240,7 @@ void SystemPropertiesAdapterImpl::RemoveAllSysPropWatchers() for (auto &item : PROP_KEY_MAP) { auto errNo = RemoveParameterWatcher(item.first.c_str(), nullptr, nullptr); if (errNo != 0) { - WVLOG_E("remove watch error result: %{public}d", errNo); + WVLOG_I("remove watch error result: %{public}d", errNo); } } } @@ -249,7 +249,7 @@ void SystemPropertiesAdapterImpl::DispatchAllWatcherInfo(const char* key, const { auto propKeyIt = PROP_KEY_MAP.find(key); if (propKeyIt == PROP_KEY_MAP.end()) { - WVLOG_E("sys prop change key is invalid: %{public}s", key); + WVLOG_I("sys prop change key is invalid: %{public}s", key); return; } @@ -257,7 +257,7 @@ void SystemPropertiesAdapterImpl::DispatchAllWatcherInfo(const char* key, const auto& keyObservers = sysPropObserver_[propkey]; if (keyObservers.size() == 0) { - WVLOG_E("no observers in this key: %{public}s", key); + WVLOG_I("no observers in this key: %{public}s", key); return; } @@ -271,12 +271,12 @@ void SystemPropertiesAdapterImpl::AttachSysPropObserver(PropertiesKey key, Syste { auto observerIt = sysPropObserver_.find(key); if (observerIt == sysPropObserver_.end()) { - WVLOG_E("properties key invalid in attach"); + WVLOG_I("properties key invalid in attach"); return; } if (observer == nullptr) { - WVLOG_E("properties key observer invalid in attach"); + WVLOG_I("properties key observer invalid in attach"); return; } @@ -289,12 +289,12 @@ void SystemPropertiesAdapterImpl::DetachSysPropObserver(PropertiesKey key, Syste { auto observerIt = sysPropObserver_.find(key); if (observerIt == sysPropObserver_.end()) { - WVLOG_E("properties key invalid in detach"); + WVLOG_I("properties key invalid in detach"); return; } if (observer == nullptr) { - WVLOG_E("properties key observer invalid in detach"); + WVLOG_I("properties key observer invalid in detach"); return; } @@ -316,4 +316,9 @@ std::vector SystemPropertiesAdapterImpl::GetLTPOConfig(const s { return NWebConfigHelper::Instance().GetPerfConfig(settingName); } + +bool SystemPropertiesAdapterImpl::IsLTPODynamicApp(const std::string& bundleName) +{ + return NWebConfigHelper::Instance().IsLTPODynamicApp(bundleName); +} } // namespace OHOS::NWeb diff --git a/ohos_glue/BUILD.gn b/ohos_glue/BUILD.gn index e4386d88b8c475462ecf2b3ed7999f17f0529669..33fcf6fbafdbb3d354ab1f85206f2294cbc090cd 100644 --- a/ohos_glue/BUILD.gn +++ b/ohos_glue/BUILD.gn @@ -229,6 +229,10 @@ action("ohos_glue_nweb_prepare") { "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_web_storage_wrapper.h", "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_adsblock_manager_wrapper.cpp", "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_adsblock_manager_wrapper.h", + "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_array_buffer_value_callback_impl.cpp", + "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_array_buffer_value_callback_impl.h", + "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_pdfconfig_args_impl.cpp", + "${glue_build_gen_dir}/ohos_nweb/bridge/ark_web_pdfconfig_args_impl.h", "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_accessibility_event_callback_cpptoc.cpp", "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_accessibility_event_callback_cpptoc.h", "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_bool_value_callback_cpptoc.cpp", @@ -289,6 +293,10 @@ action("ohos_glue_nweb_prepare") { "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_value_vector_cpptoc.h", "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_web_storage_origin_vector_value_callback_cpptoc.cpp", "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_web_storage_origin_vector_value_callback_cpptoc.h", + "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_array_buffer_value_callback_cpptoc.cpp", + "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_array_buffer_value_callback_cpptoc.h", + "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_pdfconfig_args_cpptoc.cpp", + "${glue_build_gen_dir}/ohos_nweb/cpptoc/ark_web_pdfconfig_args_cpptoc.h", "${glue_build_gen_dir}/ohos_nweb/ctocpp/ark_web_accessibility_node_info_ctocpp.cpp", "${glue_build_gen_dir}/ohos_nweb/ctocpp/ark_web_accessibility_node_info_ctocpp.h", "${glue_build_gen_dir}/ohos_nweb/ctocpp/ark_web_access_request_ctocpp.cpp", @@ -600,10 +608,14 @@ action("ohos_glue_adapter_prepare") { "${glue_build_gen_dir}/ohos_adapter/bridge/ark_mmi_listener_adapter_wrapper.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_native_image_adapter_impl.cpp", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_native_image_adapter_impl.h", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_capabilities_adapter_impl.cpp", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_capabilities_adapter_impl.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_conn_callback_wrapper.cpp", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_conn_callback_wrapper.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_connect_adapter_impl.cpp", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_connect_adapter_impl.h", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_connection_properties_adapter_impl.cpp", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_connection_properties_adapter_impl.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_proxy_adapter_impl.cpp", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_proxy_adapter_impl.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_net_proxy_event_callback_adapter_wrapper.cpp", @@ -655,6 +667,10 @@ action("ohos_glue_adapter_prepare") { "${glue_build_gen_dir}/ohos_adapter/bridge/ark_screen_capture_callback_adapter_wrapper.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_screen_capture_config_adapter_wrapper.cpp", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_screen_capture_config_adapter_wrapper.h", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_sensor_adapter_impl.cpp", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_sensor_adapter_impl.h", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_sensor_callback_adapter_wrapper.cpp", + "${glue_build_gen_dir}/ohos_adapter/bridge/ark_sensor_callback_adapter_wrapper.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_soc_perf_client_adapter_impl.cpp", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_soc_perf_client_adapter_impl.h", "${glue_build_gen_dir}/ohos_adapter/bridge/ark_surface_buffer_adapter_impl.cpp", @@ -773,8 +789,12 @@ action("ohos_glue_adapter_prepare") { "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_mmiadapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_native_image_adapter_cpptoc.cpp", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_native_image_adapter_cpptoc.h", + "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_capabilities_adapter_cpptoc.cpp", + "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_capabilities_adapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_connect_adapter_cpptoc.cpp", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_connect_adapter_cpptoc.h", + "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_connection_properties_adapter_cpptoc.cpp", + "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_connection_properties_adapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_proxy_adapter_cpptoc.cpp", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_net_proxy_adapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_ohos_adapter_helper_cpptoc.cpp", @@ -817,6 +837,8 @@ action("ohos_glue_adapter_prepare") { "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_running_lock_adapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_screen_capture_adapter_cpptoc.cpp", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_screen_capture_adapter_cpptoc.h", + "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_sensor_adapter_cpptoc.cpp", + "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_sensor_adapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_soc_perf_client_adapter_cpptoc.cpp", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_soc_perf_client_adapter_cpptoc.h", "${glue_build_gen_dir}/ohos_adapter/cpptoc/ark_surface_buffer_adapter_cpptoc.cpp", @@ -935,6 +957,8 @@ action("ohos_glue_adapter_prepare") { "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_screen_capture_callback_adapter_ctocpp.h", "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_screen_capture_config_adapter_ctocpp.cpp", "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_screen_capture_config_adapter_ctocpp.h", + "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_sensor_callback_adapter_ctocpp.cpp", + "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_sensor_callback_adapter_ctocpp.h", "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_timezone_event_callback_adapter_ctocpp.cpp", "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_timezone_event_callback_adapter_ctocpp.h", "${glue_build_gen_dir}/ohos_adapter/ctocpp/ark_video_capture_info_adapter_ctocpp.cpp", @@ -964,6 +988,8 @@ config("ohos_glue_config") { } ohos_shared_library("ohos_base_glue_source") { + output_name = "arkweb_glue_base" + branch_protector_frt = "bti" branch_protector_ret = "pac_ret" @@ -988,6 +1014,8 @@ ohos_shared_library("ohos_base_glue_source") { } ohos_shared_library("ohos_nweb_glue_source") { + output_name = "arkweb_core_loader_glue" + branch_protector_frt = "bti" branch_protector_ret = "pac_ret" diff --git a/ohos_interface/include/ohos_adapter/graphic_adapter.h b/ohos_interface/include/ohos_adapter/graphic_adapter.h index 4ce61994ba1a1e891c1220c024406dc45aa644bc..662456abfb8acf9e85458e24b2f7aec25a0dab8c 100644 --- a/ohos_interface/include/ohos_adapter/graphic_adapter.h +++ b/ohos_interface/include/ohos_adapter/graphic_adapter.h @@ -44,6 +44,8 @@ public: virtual void SetOnVsyncCallback(void (*callback)()) = 0; virtual void SetOnVsyncEndCallback(void (*onVsyncEndCallback)()) {} + + virtual void SetScene(const std::string& sceneName, uint32_t state) = 0; }; // be consistent with rom/foundation/graphic/graphic_2d/interfaces/inner_api/common/graphic_common_c.h:GSError @@ -288,7 +290,6 @@ public: virtual int32_t FlushBuffer(std::shared_ptr buffer, int32_t fence, std::shared_ptr config) = 0; }; - } // namespace OHOS::NWeb #endif // GRAPHIC_ADAPTER_H diff --git a/ohos_interface/include/ohos_adapter/hisysevent_adapter.h b/ohos_interface/include/ohos_adapter/hisysevent_adapter.h index 03a9cfb2e9285d8edc8f599297acaeabdbd2ece0..226a5fcfd96e4d8bb2a73e4c9956f36672028ae2 100644 --- a/ohos_interface/include/ohos_adapter/hisysevent_adapter.h +++ b/ohos_interface/include/ohos_adapter/hisysevent_adapter.h @@ -31,36 +31,36 @@ public: }; virtual int Write( - const std::string& eventName, EventType type, const std::tuple& data); + const std::string& eventName, EventType type, const std::tuple& data) = 0; virtual int Write(const std::string& eventName, EventType type, - const std::tuple& data); + const std::tuple& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const std::string>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const std::string, const std::string, const std::string>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const std::string, const std::string, const std::string, const std::string, const std::string>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const std::string, const std::string>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple, const std::string, const int>& data); + const std::vector, const std::string, const int>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& - data); + data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const int64_t, const std::string, const int64_t, const std::string, const int64_t>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const std::string, const std::string, const std::string, const std::string>& data) = 0; virtual int Write(const std::string& eventName, EventType type, const std::tuple& data); + const std::string, const std::string, const std::string>& data) = 0; protected: HiSysEventAdapter() = default; diff --git a/ohos_interface/include/ohos_adapter/imf_adapter.h b/ohos_interface/include/ohos_adapter/imf_adapter.h index 5aa58b694582a2bccc45959d76bfa75d03860320..178ea0367a09bc34f9618ed700f38c3dad22288a 100644 --- a/ohos_interface/include/ohos_adapter/imf_adapter.h +++ b/ohos_interface/include/ohos_adapter/imf_adapter.h @@ -106,6 +106,16 @@ public: virtual std::shared_ptr GetSelectionRange() = 0; virtual uint32_t GetWindowId() = 0; + + virtual double GetPositionY() + { + return 0.0; + } + + virtual double GetHeight() + { + return 0.0; + } }; enum class IMFAdapterKeyboardStatus : int32_t { NONE = 0, HIDE, SHOW }; @@ -158,6 +168,9 @@ public: virtual void FinishTextPreview() = 0; virtual void SetNeedUnderLine(bool isNeedUnderline) = 0; + + virtual void AutoFillWithIMFEvent(bool isUsername, bool isOtherAccount, bool isNewPassword, + const std::string& content) {} }; class IMFAdapter { @@ -180,6 +193,11 @@ public: virtual void OnCursorUpdate(const std::shared_ptr cursorInfo) = 0; virtual void OnSelectionChange(std::u16string text, int start, int end) = 0; + + virtual bool SendPrivateCommand(const std::string& commandKey, const std::string& commandValue) + { + return false; + } }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_adapter/net_connect_adapter.h b/ohos_interface/include/ohos_adapter/net_connect_adapter.h index 64c9f79830f8221ed0ffa89d3c35aa81fa9e5c56..6920cc34e946e7f909ba0b0424d37386d7973cdd 100644 --- a/ohos_interface/include/ohos_adapter/net_connect_adapter.h +++ b/ohos_interface/include/ohos_adapter/net_connect_adapter.h @@ -71,6 +71,24 @@ enum class NetConnectSubtype : uint32_t { SUBTYPE_LAST = SUBTYPE_WIFI_AD }; +class NetCapabilitiesAdapter { +public: + NetCapabilitiesAdapter() = default; + virtual ~NetCapabilitiesAdapter() = default; + + virtual int32_t GetNetId() = 0; + virtual NetConnectType GetConnectType() = 0; + virtual NetConnectSubtype GetConnectSubtype() = 0; +}; + +class NetConnectionPropertiesAdapter { +public: + NetConnectionPropertiesAdapter() = default; + virtual ~NetConnectionPropertiesAdapter() = default; + + virtual int32_t GetNetId() = 0; +}; + class NetConnCallback { public: NetConnCallback() = default; @@ -81,6 +99,10 @@ public: const NetConnectType& netConnectType, const NetConnectSubtype& netConnectSubtype) = 0; virtual int32_t NetConnectionPropertiesChange() = 0; virtual int32_t NetUnavailable() = 0; + virtual int32_t OnNetCapabilitiesChanged( + const std::shared_ptr capabilities) { return 0; } + virtual int32_t OnNetConnectionPropertiesChanged( + const std::shared_ptr properties) { return 0; } }; class NetConnectAdapter { diff --git a/ohos_interface/include/ohos_adapter/ohos_adapter_helper.h b/ohos_interface/include/ohos_adapter/ohos_adapter_helper.h index 6a82adfef8084c98a66a3efa1f3768565e60ed1a..4802666d3bafa44225b648bb459fcf9c08abd079 100644 --- a/ohos_interface/include/ohos_adapter/ohos_adapter_helper.h +++ b/ohos_interface/include/ohos_adapter/ohos_adapter_helper.h @@ -54,6 +54,7 @@ #include "screen_capture_adapter.h" #include "soc_perf_client_adapter.h" #include "system_properties_adapter.h" +#include "sensor_adapter.h" namespace OHOS::NWeb { class OhosAdapterHelper { @@ -143,6 +144,10 @@ public: virtual std::unique_ptr CreateMediaAVSessionAdapter() = 0; virtual std::unique_ptr CreateOhosImageDecoderAdapter() = 0; + + virtual std::unique_ptr CreateSensorAdapter() = 0; + + virtual void SetArkWebCoreHapPathOverride(const std::string& hapPath) = 0; }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_adapter/ohos_resource_adapter.h b/ohos_interface/include/ohos_adapter/ohos_resource_adapter.h index 06f728b5e6ddcbc98207d5cac2bc2130ea5d2a20..02c4595cc15a495fd672066beed026edda1d2d05 100644 --- a/ohos_interface/include/ohos_adapter/ohos_resource_adapter.h +++ b/ohos_interface/include/ohos_adapter/ohos_resource_adapter.h @@ -56,6 +56,8 @@ public: const std::string& rawFile, uint16_t& date, uint16_t& time, bool isSys = false) = 0; virtual bool GetRawFileLastModTime(const std::string& rawFile, time_t& time, bool isSys = false) = 0; + + virtual std::string GetSystemLanguage() = 0; }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_adapter/sensor_adapter.h b/ohos_interface/include/ohos_adapter/sensor_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..c3253b0e079079fa9e31b7483e55a96f21278d3e --- /dev/null +++ b/ohos_interface/include/ohos_adapter/sensor_adapter.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_ADAPTER_H +#define SENSOR_ADAPTER_H + +#include + + +namespace OHOS::NWeb { + +enum { + SENSOR_ERROR = -1, + SENSOR_SUCCESS = 0, + SENSOR_PERMISSION_DENIED = 201, // Use this error code when permission is denied. + SENSOR_PARAMETER_ERROR = 401, // Use this error code when the input parameter type or range does not match. + SENSOR_SERVICE_EXCEPTION = 14500101, // Use this error code when the service is exception. + SENSOR_NO_SUPPORT = 14500102, // Use this error code when the sensor is not supported by the device. + SENSOR_NON_SYSTEM_API = 202 // Permission check failed. A non-system application uses the system API. +}; + +enum { + SENSOR_DATA_REPORT_ON_CHANGE = 0, + SENSOR_DATA_REPORT_CONTINUOUS = 1 +}; + +class SensorCallbackAdapter { +public: + virtual ~SensorCallbackAdapter() = default; + + virtual void UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) = 0; +}; + +class SensorAdapter { +public: + SensorAdapter() = default; + virtual ~SensorAdapter() = default; + + virtual int32_t IsOhosSensorSupported(int32_t sensorTypeId) = 0; + virtual int32_t GetOhosSensorReportingMode(int32_t sensorTypeId) = 0; + virtual double GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) = 0; + virtual double GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) = 0; + virtual double GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) = 0; + virtual int32_t SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) = 0; + virtual int32_t RegistOhosSensorCallback(int32_t sensorTypeId, + std::shared_ptr callbackAdapter) = 0; + virtual int32_t UnsubscribeOhosSensor(int32_t sensorTypeId) = 0; +}; + +} + +#endif // SENSOR_ADAPTER_H \ No newline at end of file diff --git a/ohos_interface/include/ohos_adapter/system_properties_adapter.h b/ohos_interface/include/ohos_adapter/system_properties_adapter.h index 351e3169336c412171c4494299212e7867ff1889..050ac381cdf539a5cb70c698fd39f7a2920971a9 100644 --- a/ohos_interface/include/ohos_adapter/system_properties_adapter.h +++ b/ohos_interface/include/ohos_adapter/system_properties_adapter.h @@ -88,6 +88,8 @@ public: virtual std::vector GetLTPOConfig(const std::string& settingName) = 0; virtual std::string GetOOPGPUStatus() = 0; + + virtual bool IsLTPODynamicApp(const std::string& bundleName) = 0; }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_nweb/nweb.h b/ohos_interface/include/ohos_nweb/nweb.h index 14a9fe83f573416cfd28155034322a8c1c8125f3..5868c05336a20f3a2af986c2cecd6b0c83d1d967 100644 --- a/ohos_interface/include/ohos_nweb/nweb.h +++ b/ohos_interface/include/ohos_nweb/nweb.h @@ -192,6 +192,20 @@ public: virtual std::string GetFormData() = 0; }; +class OHOS_NWEB_EXPORT NWebPDFConfigArgs { +public: + virtual ~NWebPDFConfigArgs() = default; + + virtual double GetWidth() = 0; + virtual double GetHeight() = 0; + virtual double GetScale() = 0; + virtual double GetMarginTop() = 0; + virtual double GetMarginBottom() = 0; + virtual double GetMarginRight() = 0; + virtual double GetMarginLeft() = 0; + virtual bool GetShouldPrintBackground() = 0; +}; + enum class PrecompileError : int32_t { OK = 0, INTERNAL_ERROR = -1 }; class OHOS_NWEB_EXPORT CacheOptions { @@ -1342,7 +1356,7 @@ public: int height, const WebSnapshotCallback callback) { return false; - }; + } /** * Set grant file access dirs. @@ -1430,6 +1444,79 @@ public: */ virtual void RegisterArkJSfunction(const std::string& object_name, const std::vector& method_list, const std::vector& async_method_list, const int32_t object_id, const std::string& permission) {} + + /** + * @brief resize visual viewport. + * + * @param width width. + * @param height height. + * @param iskeyboard from keybord. + */ + virtual void ResizeVisibleViewport(uint32_t width, uint32_t height, bool isKeyboard) {} + + /** + * @brief Set backforward cache options. + * + * @param size The size of the back forward cache could saved. + * @param timeToLive The time of the back forward cache page could stay. + */ + virtual void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) { return; } + + /** + * @brief set the callback of the autofill event. + * @param callback callback. + */ + virtual void SetAutofillCallback(std::shared_ptr callback) {} + + /** + * @brief fill autofill data. + * @param data data. + */ + virtual void FillAutofillData(std::shared_ptr data) {} + + /** + * @brief on autofill cancel. + * @param fillContent fillContent + */ + virtual void OnAutofillCancel(const std::string& fillContent) {} + + /** + * @brief Get the current scroll offset of the webpage. + * @param offset_x The current horizontal scroll offset of the webpage. + * @param offset_y The current vertical scroll offset of the webpage. + */ + virtual void GetScrollOffset(float* offset_x, float* offset_y) {} + + /** + * @brief ExecuteCreatePDFExt + * + * @param pdfConfig The current configuration when creating pdf. + * @param callback NWebArrayBufferValueCallback: CreatePDF running result. + */ + virtual void ExecuteCreatePDFExt(std::shared_ptr pdfConfig, + std::shared_ptr callback) {} + + /** + * Scroll by the delta distance if web is not foucsed. + * + * @param delta_x horizontal offset. + * @param delta_y vertical offset. + * @return false if web is focused. + */ + virtual bool ScrollByWithResult(float delta_x, float delta_y) { + return false; + }; + + /** + * @brief set a popupSurface to draw popup content + * @param popupSurface popupSurface. + */ + virtual void SetPopupSurface(void* popupSurface) {} + + /** + * @brief Called when image analyzer is destory. + */ + virtual void OnDestroyImageAnalyzerOverlay() {} }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_nweb/nweb_access_request.h b/ohos_interface/include/ohos_nweb/nweb_access_request.h index 703f989f3b94cc5e22e86a624d03efaaf3802244..a41853f4687f28b58d9b98e75537de0a8fb927aa 100644 --- a/ohos_interface/include/ohos_nweb/nweb_access_request.h +++ b/ohos_interface/include/ohos_nweb/nweb_access_request.h @@ -35,7 +35,8 @@ public: PROTECTED_MEDIA_ID = 1 << 3, MIDI_SYSEX = 1 << 4, CLIPBOARD_READ_WRITE = 1 << 5, - CLIPBOARD_SANITIZED_WRITE = 1 << 6, + CLIPBOARD_SANITIZED_WRITE = 1 << 6, + SENSORS = 1 << 7, }; /** diff --git a/ohos_interface/include/ohos_nweb/nweb_autofill.h b/ohos_interface/include/ohos_nweb/nweb_autofill.h new file mode 100644 index 0000000000000000000000000000000000000000..1864615c28338cb1d966720fbd987f759adf7bf3 --- /dev/null +++ b/ohos_interface/include/ohos_nweb/nweb_autofill.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NWEB_AUTOFILL_H +#define NWEB_AUTOFILL_H + +#include + +namespace OHOS::NWeb { + +const std::string NWEB_VIEW_DATA_KEY_FOCUS = "focus"; +const std::string NWEB_VIEW_DATA_KEY_RECT_X = "x"; +const std::string NWEB_VIEW_DATA_KEY_RECT_Y = "y"; +const std::string NWEB_VIEW_DATA_KEY_RECT_W = "width"; +const std::string NWEB_VIEW_DATA_KEY_RECT_H = "height"; +const std::string NWEB_VIEW_DATA_KEY_VALUE = "value"; +const std::string NWEB_VIEW_DATA_KEY_PLACEHOLDER = "placeholder"; + +const std::string NWEB_AUTOFILL_EVENT_SAVE = "save"; +const std::string NWEB_AUTOFILL_EVENT_FILL = "fill"; +const std::string NWEB_AUTOFILL_EVENT_UPDATE = "update"; +const std::string NWEB_AUTOFILL_EVENT_CLOSE = "close"; + +const std::string NWEB_AUTOFILL_EVENT_TYPE = "event"; +const std::string NWEB_AUTOFILL_PAGE_URL = "pageUrl"; +const std::string NWEB_AUTOFILL_IS_USER_SELECTED = "isUserSelected"; +const std::string NWEB_AUTOFILL_IS_OTHER_ACCOUNT = "isOtherAccount"; +const std::string NWEB_AUTOFILL_EVENT_SOURCE = "source"; +const std::string NWEB_AUTOFILL_FOR_LOGIN = "login"; + +const std::string NWEB_AUTOFILL_STREET_ADDRESS = "street-address"; +const std::string NWEB_AUTOFILL_ADDRESS_LEVEL_3 = "address-level3"; +const std::string NWEB_AUTOFILL_ADDRESS_LEVEL_2 = "address-level2"; +const std::string NWEB_AUTOFILL_ADDRESS_LEVEL_1 = "address-level1"; +const std::string NWEB_AUTOFILL_COUNTRY = "country"; +const std::string NWEB_AUTOFILL_NAME = "name"; +const std::string NWEB_AUTOFILL_FAMILY_NAME = "family-name"; +const std::string NWEB_AUTOFILL_GIVEN_NAME = "given-name"; +const std::string NWEB_AUTOFILL_TEL_NATIONAL = "tel-national"; +const std::string NWEB_AUTOFILL_TEL = "tel"; +const std::string NWEB_AUTOFILL_TEL_COUNTRY_CODE = "tel-country-code"; +const std::string NWEB_AUTOFILL_EMAIL = "email"; +const std::string NWEB_AUTOFILL_CC_NUMBER = "cc-number"; +const std::string NWEB_AUTOFILL_ID_CARD_NUMBER = "id-card-number"; +const std::string NWEB_AUTOFILL_NICKNAME = "nickname"; +const std::string NWEB_AUTOFILL_USERNAME = "username"; +const std::string NWEB_AUTOFILL_PASSWORD = "password"; +const std::string NWEB_AUTOFILL_NEW_PASSWORD = "new-password"; + +enum NWebAutofillEvent { + UNKNOWN = 0, + SAVE, + FILL, + UPDATE, + CLOSE, +}; + +} // namespace OHOS::NWeb + +#endif // NWEB_AUTOFILL_H \ No newline at end of file diff --git a/ohos_interface/include/ohos_nweb/nweb_cookie_manager.h b/ohos_interface/include/ohos_nweb/nweb_cookie_manager.h index fb91c698c4afa85e65470f02dbc328337d332311..444ea44b8cd5be62e90789eaa8f6ec9b02324f9e 100644 --- a/ohos_interface/include/ohos_nweb/nweb_cookie_manager.h +++ b/ohos_interface/include/ohos_nweb/nweb_cookie_manager.h @@ -167,6 +167,32 @@ public: */ virtual void ConfigCookie( const std::string& url, const std::string& value, std::shared_ptr callback) = 0; + + /** + * @brief Gets all the cookies for the given URL. This is sync method + * + * @param url URL to which the cookie to be obtained belongs. A complete URL is recommended. + * @param incognito True indicates that the memory cookies of the webview in privacy mode are obtained, + * and false indicates that cookies in non-privacy mode are obtained. + * @param includeHttpOnly If true HTTP-only cookies will also be included in the cookieValue. + * @param cookieValue Get the cookie value corresponding to the URL. + * @return the cookie value for given URL. + */ + virtual std::string ReturnCookieWithHttpOnly( + const std::string& url, bool& is_valid, bool incognito_mode, bool includeHttpOnly) { return ""; } + + /** + * @brief Sets a single cookie (key-value pair) for the given URL sync. + * + * @param url Specifies the URL to which the cookie belongs. A complete URL is recommended. + * @param cookieValue The value of the cookie to be set. + * @param incognito True indicates that cookies of the corresponding URL are set in privacy mode, + * and false indicates that cookies of the corresponding URL are set in non-privacy mode. + * @param includeHttpOnly If true, HTTP-only cookies can also be overwritten. + * @return 0 if set cookie success else return error id. + */ + virtual int SetCookieWithHttpOnly( + const std::string& url, const std::string& value, bool incognito_mode, bool includeHttpOnly) { return 0; } }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_nweb/nweb_engine.h b/ohos_interface/include/ohos_nweb/nweb_engine.h index 41853edc059c36f6b63f9a38289eab73fa782bad..dc643adec9a78b45142aaefe99183dc47ec35909 100644 --- a/ohos_interface/include/ohos_nweb/nweb_engine.h +++ b/ohos_interface/include/ohos_nweb/nweb_engine.h @@ -77,11 +77,13 @@ public: virtual void ClearHostIP(const std::string& hostName) = 0; - virtual void EnableWholeWebPageDrawing() {}; + virtual void EnableWholeWebPageDrawing() {} virtual std::shared_ptr GetAdsBlockManager() { return nullptr; - }; + } + + virtual void TrimMemoryByPressureLevel(int32_t memoryLevel) {} }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_nweb/nweb_handler.h b/ohos_interface/include/ohos_nweb/nweb_handler.h index f27bea9b1f83eebc63b058749af15d98fe6ea29b..6620d416318d9d38b5ece885c0690ae9f0251a49 100644 --- a/ohos_interface/include/ohos_nweb/nweb_handler.h +++ b/ohos_interface/include/ohos_nweb/nweb_handler.h @@ -213,6 +213,10 @@ enum class NativeEmbedStatus { CREATE, UPDATE, DESTROY, + ENTER_BFCACHE, + LEAVE_BFCACHE, + VISIBLE, + HIDDEN, }; enum class NWebFocusSource { @@ -964,6 +968,59 @@ public: * */ virtual void OnAdsBlocked(const std::string& url, const std::vector& adsBlocked) {} + + /** + * @brief called when the cursor info is updated. + * + * @param x, y relative coordinates within web components of the cursor + * @param width, height width and height of the cursor + */ + virtual void OnCursorUpdate(double x, double y, double width, double height) {} + + /** + * @brief Called when web occurs frame loss event. + * + * @param sceneId The id of event scene. + * @param isStart True if is start. + */ + virtual void ReportDynamicFrameLossEvent(const std::string& sceneId, bool isStart) {} + + /** + * @brief Called when you need to temporarily hide/restore the handle menu. + * + * @param hide hide. + */ + virtual void HideHandleAndQuickMenuIfNecessary(bool hide) {} + + /** + * @brief Called When you click on the selected area. + * + */ + virtual void ChangeVisibilityOfQuickMenu() {} + + /** + * @brief Called when you need to start vibrator. + */ + virtual void StartVibraFeedback(const std::string& vibratorType) {} + + /** + * @brief Called when a popup is shown with the given size. + * + * @param x The offset of the popup on the x coordinate axis. + * @param y The offset of the popup on the y coordinate axis. + * @param width The width of the popup. + * @param height The height of the popup. + * + */ + virtual void OnPopupSize(int x, int y, int width, int height) {} + + /** + * @brief Called when the popup is shown or hidden. + * + * @param show Whether the popup is shown or hidden. + * + */ + virtual void OnPopupShow(bool show) {} }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_nweb/nweb_native_media_player.h b/ohos_interface/include/ohos_nweb/nweb_native_media_player.h index 4aa810c1bc93345df0b146a1b0547c15a5ed7205..609d9a6bb3cab05af35940ab1d0b03566f99018e 100644 --- a/ohos_interface/include/ohos_nweb/nweb_native_media_player.h +++ b/ohos_interface/include/ohos_nweb/nweb_native_media_player.h @@ -31,7 +31,7 @@ enum class MediaError { NETWORK_ERROR = 1, FORMAT_ERROR, DECODE_ERROR }; enum class ReadyState { HAVE_NOTHING = 0, HAVE_METADATA, HAVE_CURRENT_DATA, HAVE_FUTURE_DATA, HAVE_ENOUGH_DATA }; -enum class SuspendType { EnterBFCache = 0, EnterBackground, PausedOverTime }; +enum class SuspendType { ENTER_BACK_FORWARD_CACHE = 0, ENTER_BACKGROUND, AUTO_CLEANUP }; enum class NetworkState { EMPTY = 0, IDLE, LOADING, NETWORK_ERROR }; diff --git a/ohos_interface/include/ohos_nweb/nweb_preference.h b/ohos_interface/include/ohos_nweb/nweb_preference.h index 6ea0dd95af75a9c64161b4bf2ef02b5d0de8f04c..0a22df9f61de4d4a70cb40389789068bbaee2434 100644 --- a/ohos_interface/include/ohos_nweb/nweb_preference.h +++ b/ohos_interface/include/ohos_nweb/nweb_preference.h @@ -647,6 +647,11 @@ public: * Set whether the scrollbar is displayed. */ virtual void PutOverlayScrollbarEnabled(bool enable) {} + + /** + * Set whether the scroll is enabled. + */ + virtual void SetScrollable(bool enable, int32_t scrollType) {} }; } // namespace OHOS::NWeb diff --git a/ohos_interface/include/ohos_nweb/nweb_value_callback.h b/ohos_interface/include/ohos_nweb/nweb_value_callback.h index 21ad136ddba1333eb9aba0e716150541b2cb3d5f..bac7bb758616fc83114b083be3b774a2fe802ca4 100644 --- a/ohos_interface/include/ohos_nweb/nweb_value_callback.h +++ b/ohos_interface/include/ohos_nweb/nweb_value_callback.h @@ -67,6 +67,12 @@ public: virtual void OnReceiveValue(const std::vector>& value) = 0; }; +class OHOS_NWEB_EXPORT NWebArrayBufferValueCallback { +public: + virtual ~NWebArrayBufferValueCallback() = default; + + virtual void OnReceiveValue(const char* value, const long size) = 0; +}; } // namespace OHOS::NWeb #endif // NWebValueCallback \ No newline at end of file diff --git a/ohos_interface/ohos_glue/BUILD_webcore.gn b/ohos_interface/ohos_glue/BUILD_webcore.gn index 9e56406b808a0e50717a80d499cf26d724b8050f..db706f12a25d683287c34630840a91f3f1bf4de5 100644 --- a/ohos_interface/ohos_glue/BUILD_webcore.gn +++ b/ohos_interface/ohos_glue/BUILD_webcore.gn @@ -17,7 +17,10 @@ import("//build/config/ohos/config.gni") ################################################# config("ohos_glue_config") { - defines = [ "OHOS_NWEB" ] + defines = [ + "OHOS_NWEB", + "OHOS_WEBCORE_GLUE", + ] include_dirs = [ "//ohos_glue" ] @@ -57,6 +60,8 @@ component("ohos_nweb_glue_source") { "ohos_nweb/bridge/ark_web_adsblock_manager_impl.h", "ohos_nweb/bridge/ark_web_applink_callback_impl.cpp", "ohos_nweb/bridge/ark_web_applink_callback_impl.h", + "ohos_nweb/bridge/ark_web_array_buffer_value_callback_wrapper.cpp", + "ohos_nweb/bridge/ark_web_array_buffer_value_callback_wrapper.h", "ohos_nweb/bridge/ark_web_bool_value_callback_wrapper.cpp", "ohos_nweb/bridge/ark_web_bool_value_callback_wrapper.h", "ohos_nweb/bridge/ark_web_cache_options_wrapper.cpp", @@ -171,6 +176,8 @@ component("ohos_nweb_glue_source") { "ohos_nweb/bridge/ark_web_nweb_impl.h", "ohos_nweb/bridge/ark_web_output_frame_callback_wrapper.cpp", "ohos_nweb/bridge/ark_web_output_frame_callback_wrapper.h", + "ohos_nweb/bridge/ark_web_pdfconfig_args_wrapper.cpp", + "ohos_nweb/bridge/ark_web_pdfconfig_args_wrapper.h", "ohos_nweb/bridge/ark_web_preference_impl.cpp", "ohos_nweb/bridge/ark_web_preference_impl.h", "ohos_nweb/bridge/ark_web_quick_menu_callback_impl.cpp", @@ -353,6 +360,8 @@ component("ohos_nweb_glue_source") { "ohos_nweb/cpptoc/ark_web_web_storage_origin_vector_cpptoc.h", "ohos_nweb/ctocpp/ark_web_accessibility_event_callback_ctocpp.cpp", "ohos_nweb/ctocpp/ark_web_accessibility_event_callback_ctocpp.h", + "ohos_nweb/ctocpp/ark_web_array_buffer_value_callback_ctocpp.cpp", + "ohos_nweb/ctocpp/ark_web_array_buffer_value_callback_ctocpp.h", "ohos_nweb/ctocpp/ark_web_bool_value_callback_ctocpp.cpp", "ohos_nweb/ctocpp/ark_web_bool_value_callback_ctocpp.h", "ohos_nweb/ctocpp/ark_web_cache_options_ctocpp.cpp", @@ -389,6 +398,8 @@ component("ohos_nweb_glue_source") { "ohos_nweb/ctocpp/ark_web_nweb_create_info_ctocpp.h", "ohos_nweb/ctocpp/ark_web_output_frame_callback_ctocpp.cpp", "ohos_nweb/ctocpp/ark_web_output_frame_callback_ctocpp.h", + "ohos_nweb/ctocpp/ark_web_pdfconfig_args_ctocpp.cpp", + "ohos_nweb/ctocpp/ark_web_pdfconfig_args_ctocpp.h", "ohos_nweb/ctocpp/ark_web_release_surface_callback_ctocpp.cpp", "ohos_nweb/ctocpp/ark_web_release_surface_callback_ctocpp.h", "ohos_nweb/ctocpp/ark_web_resource_ready_callback_ctocpp.cpp", @@ -592,10 +603,14 @@ component("ohos_adapter_glue_source") { "ohos_adapter/bridge/ark_mmi_listener_adapter_impl.h", "ohos_adapter/bridge/ark_native_image_adapter_wrapper.cpp", "ohos_adapter/bridge/ark_native_image_adapter_wrapper.h", + "ohos_adapter/bridge/ark_net_capabilities_adapter_wrapper.cpp", + "ohos_adapter/bridge/ark_net_capabilities_adapter_wrapper.h", "ohos_adapter/bridge/ark_net_conn_callback_impl.cpp", "ohos_adapter/bridge/ark_net_conn_callback_impl.h", "ohos_adapter/bridge/ark_net_connect_adapter_wrapper.cpp", "ohos_adapter/bridge/ark_net_connect_adapter_wrapper.h", + "ohos_adapter/bridge/ark_net_connection_properties_adapter_wrapper.cpp", + "ohos_adapter/bridge/ark_net_connection_properties_adapter_wrapper.h", "ohos_adapter/bridge/ark_net_proxy_adapter_wrapper.cpp", "ohos_adapter/bridge/ark_net_proxy_adapter_wrapper.h", "ohos_adapter/bridge/ark_net_proxy_event_callback_adapter_impl.cpp", @@ -647,6 +662,10 @@ component("ohos_adapter_glue_source") { "ohos_adapter/bridge/ark_screen_capture_callback_adapter_impl.h", "ohos_adapter/bridge/ark_screen_capture_config_adapter_impl.cpp", "ohos_adapter/bridge/ark_screen_capture_config_adapter_impl.h", + "ohos_adapter/bridge/ark_sensor_adapter_wrapper.cpp", + "ohos_adapter/bridge/ark_sensor_adapter_wrapper.h", + "ohos_adapter/bridge/ark_sensor_callback_adapter_impl.cpp", + "ohos_adapter/bridge/ark_sensor_callback_adapter_impl.h", "ohos_adapter/bridge/ark_soc_perf_client_adapter_wrapper.cpp", "ohos_adapter/bridge/ark_soc_perf_client_adapter_wrapper.h", "ohos_adapter/bridge/ark_surface_buffer_adapter_wrapper.cpp", @@ -775,6 +794,8 @@ component("ohos_adapter_glue_source") { "ohos_adapter/cpptoc/ark_screen_capture_callback_adapter_cpptoc.h", "ohos_adapter/cpptoc/ark_screen_capture_config_adapter_cpptoc.cpp", "ohos_adapter/cpptoc/ark_screen_capture_config_adapter_cpptoc.h", + "ohos_adapter/cpptoc/ark_sensor_callback_adapter_cpptoc.cpp", + "ohos_adapter/cpptoc/ark_sensor_callback_adapter_cpptoc.h", "ohos_adapter/cpptoc/ark_timezone_event_callback_adapter_cpptoc.cpp", "ohos_adapter/cpptoc/ark_timezone_event_callback_adapter_cpptoc.h", "ohos_adapter/cpptoc/ark_video_capture_info_adapter_cpptoc.cpp", @@ -875,8 +896,12 @@ component("ohos_adapter_glue_source") { "ohos_adapter/ctocpp/ark_mmiadapter_ctocpp.h", "ohos_adapter/ctocpp/ark_native_image_adapter_ctocpp.cpp", "ohos_adapter/ctocpp/ark_native_image_adapter_ctocpp.h", + "ohos_adapter/ctocpp/ark_net_capabilities_adapter_ctocpp.cpp", + "ohos_adapter/ctocpp/ark_net_capabilities_adapter_ctocpp.h", "ohos_adapter/ctocpp/ark_net_connect_adapter_ctocpp.cpp", "ohos_adapter/ctocpp/ark_net_connect_adapter_ctocpp.h", + "ohos_adapter/ctocpp/ark_net_connection_properties_adapter_ctocpp.cpp", + "ohos_adapter/ctocpp/ark_net_connection_properties_adapter_ctocpp.h", "ohos_adapter/ctocpp/ark_net_proxy_adapter_ctocpp.cpp", "ohos_adapter/ctocpp/ark_net_proxy_adapter_ctocpp.h", "ohos_adapter/ctocpp/ark_ohos_adapter_helper_ctocpp.cpp", @@ -919,6 +944,8 @@ component("ohos_adapter_glue_source") { "ohos_adapter/ctocpp/ark_running_lock_adapter_ctocpp.h", "ohos_adapter/ctocpp/ark_screen_capture_adapter_ctocpp.cpp", "ohos_adapter/ctocpp/ark_screen_capture_adapter_ctocpp.h", + "ohos_adapter/ctocpp/ark_sensor_adapter_ctocpp.cpp", + "ohos_adapter/ctocpp/ark_sensor_adapter_ctocpp.h", "ohos_adapter/ctocpp/ark_soc_perf_client_adapter_ctocpp.cpp", "ohos_adapter/ctocpp/ark_soc_perf_client_adapter_ctocpp.h", "ohos_adapter/ctocpp/ark_surface_buffer_adapter_ctocpp.cpp", diff --git a/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.cpp b/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.cpp index df9dbaaf79ce571fdf77bde9be909618cf758fae..54d67781da38b867f82eeba3f72b1dbb179afd4a 100644 --- a/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.cpp +++ b/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.cpp @@ -33,16 +33,21 @@ bool ArkWebBridgeHelper::LoadLibFile(int mode, const std::string& libFilePath, b void* libFileHandler = ::dlopen(libFilePath.c_str(), mode); if (!libFileHandler) { if (isPrintLog) { - ARK_WEB_WRAPPER_ERROR_LOG("failed to load lib file,lib file path is %{public}s", libFilePath.c_str()); + ARK_WEB_WRAPPER_ERROR_LOG("failed to load lib file %{public}s", libFilePath.c_str()); } return false; } + if (isPrintLog) { + ARK_WEB_WRAPPER_INFO_LOG("succeed to load lib file %{public}s", libFilePath.c_str()); + } + libFileHandler_ = libFileHandler; return true; } +#if !defined(OHOS_WEBCORE_GLUE) bool ArkWebBridgeHelper::LoadLibFile(int mode, const std::string& libNsName, const std::string& libDirPath, const std::string& libFileName, bool isPrintLog) { @@ -52,23 +57,27 @@ bool ArkWebBridgeHelper::LoadLibFile(int mode, const std::string& libNsName, con Dl_namespace dlns; dlns_init(&dlns, libNsName.c_str()); - dlns_create(&dlns, libDirPath.c_str()); void* libFileHandler = dlopen_ns(&dlns, libFileName.c_str(), mode); if (!libFileHandler) { if (isPrintLog) { - ARK_WEB_WRAPPER_ERROR_LOG("failed to load lib file,lib file name is " - "%{public}s,lib dir name is %{public}s", - libFileName.c_str(), libDirPath.c_str()); + ARK_WEB_WRAPPER_ERROR_LOG( + "failed to load lib file %{public}s/%{public}s", libDirPath.c_str(), libFileName.c_str()); } return false; } + if (isPrintLog) { + ARK_WEB_WRAPPER_INFO_LOG( + "succeed to load lib file %{public}s/%{public}s", libDirPath.c_str(), libFileName.c_str()); + } + libFileHandler_ = libFileHandler; return true; } +#endif void ArkWebBridgeHelper::UnloadLibFile() { diff --git a/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.h b/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.h index 71dbd3abec187085dc69acbe6f494dd78ef2bc66..75f0818a01f9b8035786f0c8c3d414a14a860ec4 100644 --- a/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.h +++ b/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_helper.h @@ -33,8 +33,10 @@ protected: bool LoadLibFile(int mode, const std::string& libFilePath, bool isPrintLog = true); +#if !defined(OHOS_WEBCORE_GLUE) bool LoadLibFile(int mode, const std::string& libNsName, const std::string& libDirPath, const std::string& libFileName, bool isPrintLog = true); +#endif private: void UnloadLibFile(); diff --git a/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_macros.h b/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_macros.h index 95132dbd1033962ae43af28df8f7afd348545ee7..4d918902acb8a519651a764f7d4e7b29ef20db1c 100644 --- a/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_macros.h +++ b/ohos_interface/ohos_glue/base/bridge/ark_web_bridge_macros.h @@ -29,7 +29,7 @@ #define ARK_WEB_IMPL_INFO_LOG(fmt, ...) ARK_WEB_BASE_INFO_LOG(fmt, ##__VA_ARGS__) -#define ARK_WEB_IMPL_WRAN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) +#define ARK_WEB_IMPL_WARN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) #define ARK_WEB_IMPL_ERROR_LOG(fmt, ...) ARK_WEB_BASE_ERROR_LOG(fmt, ##__VA_ARGS__) @@ -39,7 +39,7 @@ #define ARK_WEB_WRAPPER_INFO_LOG(fmt, ...) ARK_WEB_BASE_INFO_LOG(fmt, ##__VA_ARGS__) -#define ARK_WEB_WRAPPER_WRAN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) +#define ARK_WEB_WRAPPER_WARN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) #define ARK_WEB_WRAPPER_ERROR_LOG(fmt, ...) ARK_WEB_BASE_ERROR_LOG(fmt, ##__VA_ARGS__) diff --git a/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_macros.h b/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_macros.h index 51304074a0002efb6caf4173df382d281a46dad8..95fcdd4b69fb23beec977fe246bd79058cbdfe22 100644 --- a/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_macros.h +++ b/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_macros.h @@ -28,7 +28,7 @@ #define ARK_WEB_CPPTOC_INFO_LOG(fmt, ...) ARK_WEB_BASE_INFO_LOG(fmt, ##__VA_ARGS__) -#define ARK_WEB_CPPTOC_WRAN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) +#define ARK_WEB_CPPTOC_WARN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) #define ARK_WEB_CPPTOC_ERROR_LOG(fmt, ...) ARK_WEB_BASE_ERROR_LOG(fmt, ##__VA_ARGS__) @@ -37,7 +37,7 @@ ArkWebSetErrno(RESULT_OK); \ if (!(param)) { \ ArkWebSetErrno(RESULT_CPPTOC_ERROR); \ - ARK_WEB_CPPTOC_WRAN_LOG("param is null"); \ + ARK_WEB_CPPTOC_WARN_LOG("param is null"); \ return result; \ } \ } diff --git a/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_ref_counted.h b/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_ref_counted.h index 73977d612df573fea48bb40cbb6a625ad3cebee6..395151d0c0b7f504dc1d53ea12f0b68ca35e4e3d 100644 --- a/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_ref_counted.h +++ b/ohos_interface/ohos_glue/base/cpptoc/ark_web_cpptoc_ref_counted.h @@ -75,9 +75,11 @@ ArkWebCppToCRefCounted::ArkWebCppToCRefCounted( memset(GetStruct(), 0, sizeof(StructName)); ark_web_base_ref_counted_t* base = reinterpret_cast(GetStruct()); - base->size = sizeof(StructName); - base->incre_ref = StructIncreRef; - base->decre_ref = StructDecreRef; + if (base) { + base->size = sizeof(StructName); + base->incre_ref = StructIncreRef; + base->decre_ref = StructDecreRef; + } } template @@ -101,6 +103,10 @@ StructName* ArkWebCppToCRefCounted::Invert(ArkW } ClassName* bridge = new ClassName(); + if (!bridge) { + ARK_WEB_CPPTOC_WARN_LOG("failed to new class,bridge type is %{public}d", kBridgeType); + return nullptr; + } StructName* capi_struct = bridge->GetStruct(); ARK_WEB_CPPTOC_DV_LOG("bridge type is %{public}d,this is %{public}ld,capi " diff --git a/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_macros.h b/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_macros.h index 2405c9034e9306ec668d0d0eaa289c1fb9abd325..50067f644039cdca4210fbb971779eb7822fd187 100644 --- a/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_macros.h +++ b/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_macros.h @@ -28,7 +28,7 @@ #define ARK_WEB_CTOCPP_INFO_LOG(fmt, ...) ARK_WEB_BASE_INFO_LOG(fmt, ##__VA_ARGS__) -#define ARK_WEB_CTOCPP_WRAN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) +#define ARK_WEB_CTOCPP_WARN_LOG(fmt, ...) ARK_WEB_BASE_WARN_LOG(fmt, ##__VA_ARGS__) #define ARK_WEB_CTOCPP_ERROR_LOG(fmt, ...) ARK_WEB_BASE_ERROR_LOG(fmt, ##__VA_ARGS__) @@ -37,19 +37,19 @@ ArkWebSetErrno(RESULT_OK); \ if (!(param)) { \ ArkWebSetErrno(RESULT_CTOCPP_ERROR); \ - ARK_WEB_CTOCPP_WRAN_LOG("param is null"); \ + ARK_WEB_CTOCPP_WARN_LOG("param is null"); \ return result; \ } \ } -#define ARK_WEB_CTOCPP_CHECK_FUNC_MEMBER(struct, function, result) \ - { \ - ArkWebSetErrno(RESULT_OK); \ - if (ARK_WEB_FUNC_MEMBER_MISSING(struct, function)) { \ - ArkWebSetErrno(RESULT_NOT_IMPL); \ - ARK_WEB_CTOCPP_INFO_LOG("function isn't existing"); \ - return result; \ - } \ +#define ARK_WEB_CTOCPP_CHECK_FUNC_MEMBER(struct, function, result) \ + { \ + ArkWebSetErrno(RESULT_OK); \ + if (ARK_WEB_FUNC_MEMBER_MISSING(struct, function)) { \ + ArkWebSetErrno(RESULT_NOT_IMPL); \ + ARK_WEB_CTOCPP_INFO_LOG("function %{public}s isn't existing", __FUNCTION__); \ + return result; \ + } \ } #endif // ARK_WEB_CTOCPP_MACROS_H_ diff --git a/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_ref_counted.h b/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_ref_counted.h index 172e9463837cce077e11c805e497963a76229f20..1982fb43ce80a6fbfb195c13c0aa0333bace527e 100644 --- a/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_ref_counted.h +++ b/ohos_interface/ohos_glue/base/ctocpp/ark_web_ctocpp_ref_counted.h @@ -72,6 +72,10 @@ ArkWebRefPtr ArkWebCToCppRefCounted:: } BridgeStruct* bridgeStruct = new BridgeStruct; + if (!bridgeStruct) { + ARK_WEB_CTOCPP_WARN_LOG("failed to new struct,bridge type is %{public}d", kBridgeType); + return nullptr; + } ARK_WEB_CTOCPP_DV_LOG("bridge type is %{public}d,this is %{public}ld,capi " "struct is %{public}ld", @@ -166,7 +170,7 @@ ARK_WEB_NO_SANITIZE void ArkWebCToCppRefCounted ARK_WEB_CTOCPP_REF_LOG("bridge type is %{public}d,this is %{public}ld", kBridgeType, (long)this); ark_web_base_ref_counted_t* base = reinterpret_cast(GetStruct()); - if (base->incre_ref) { + if (base && base->incre_ref) { base->incre_ref(base); } } @@ -177,7 +181,7 @@ ARK_WEB_NO_SANITIZE void ArkWebCToCppRefCounted ARK_WEB_CTOCPP_REF_LOG("bridge type is %{public}d,this is %{public}ld", kBridgeType, (long)this); ark_web_base_ref_counted_t* base = reinterpret_cast(GetStruct()); - if (base->decre_ref) { + if (base && base->decre_ref) { base->decre_ref(base); } } diff --git a/ohos_interface/ohos_glue/base/include/ark_web_bridge_types.h b/ohos_interface/ohos_glue/base/include/ark_web_bridge_types.h index 7507c246d1c45eb2c142fd70c2757e0e252d2ddd..640ae09378466e7c420a3a85dd323809173660ba 100644 --- a/ohos_interface/ohos_glue/base/include/ark_web_bridge_types.h +++ b/ohos_interface/ohos_glue/base/include/ark_web_bridge_types.h @@ -111,6 +111,8 @@ enum ArkWebBridgeType { ARK_WEB_SYSTEM_CONFIGURATION = 86, ARK_WEB_ADS_BLOCK_MANAGER = 87, ARK_WEB_SPANSTRING_CONVERT_HTML_CALLBACK = 88, + ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK = 89, + ARK_WEB_PDFCONFIG_ARGS = 90, /*Note: Adapter interface bridge type*/ ARK_AAFWK_APP_MGR_CLIENT_ADAPTER = 10000, @@ -243,6 +245,10 @@ enum ArkWebBridgeType { ARK_AAFWK_BROWSER_CLIENT_ADAPTER = 10127, ARK_AAFWK_BROWSER_HOST_ADAPTER = 10128, ARK_AUDIO_OUTPUT_CHANGE_CALLBACK_ADAPTER = 10129, + ARK_SENSOR_ADAPTER = 10130, + ARK_SENSOR_CALLBACK_ADAPTER = 10131, + ARK_NET_CAPABILITIES_ADAPTER = 10132, + ARK_NET_CONNECTION_PROPERTIES_ADAPTER = 10133, /*Note: Only add an enum value before ARK_WEB_BRIDGE_BUTT*/ ARK_WEB_BRIDGE_BUTT diff --git a/ohos_interface/ohos_glue/base/include/ark_web_log_utils.h b/ohos_interface/ohos_glue/base/include/ark_web_log_utils.h index 164ff908af995a2ad233b3b50265c6e5436339dd..f2bf1b2ea94b6d9ae6af6cb406e78a5510d834e1 100644 --- a/ohos_interface/ohos_glue/base/include/ark_web_log_utils.h +++ b/ohos_interface/ohos_glue/base/include/ark_web_log_utils.h @@ -38,13 +38,15 @@ #define ARK_WEB_BASE_DV_LOG(fmt, ...) WVLOG_D(LOG_FMT_PREFIX fmt, ##__VA_ARGS__) #define ARK_WEB_BASE_REF_LOG(fmt, ...) WVLOG_D(LOG_FMT_PREFIX fmt, ##__VA_ARGS__) + +#define ARK_WEB_BASE_DEBUG_LOG(fmt, ...) WVLOG_D(LOG_FMT_PREFIX fmt, ##__VA_ARGS__) #else #define ARK_WEB_BASE_DV_LOG(fmt, ...) #define ARK_WEB_BASE_REF_LOG(fmt, ...) -#endif -#define ARK_WEB_BASE_DEBUG_LOG(fmt, ...) WVLOG_D(LOG_FMT_PREFIX fmt, ##__VA_ARGS__) +#define ARK_WEB_BASE_DEBUG_LOG(fmt, ...) +#endif #define ARK_WEB_BASE_INFO_LOG(fmt, ...) WVLOG_I(LOG_FMT_PREFIX fmt, ##__VA_ARGS__) diff --git a/ohos_interface/ohos_glue/base/include/ark_web_macros.h b/ohos_interface/ohos_glue/base/include/ark_web_macros.h index fbbe9d95aff454f86f39e57ff68c93664bd18279..955c7dfbcd837be098678ce97d1d7448039e58b7 100644 --- a/ohos_interface/ohos_glue/base/include/ark_web_macros.h +++ b/ohos_interface/ohos_glue/base/include/ark_web_macros.h @@ -28,7 +28,7 @@ #define ARK_WEB_CALLBACK #define ARK_WEB_RETURN_VOID - -#define ARK_WEB_NO_SANITIZE __attribute__((no_sanitize("cfi-icall"))) + +#define ARK_WEB_NO_SANITIZE __attribute__((no_sanitize("cfi-icall", "cfi"))) #endif // ARK_WEB_MACROS_H_ diff --git a/ohos_interface/ohos_glue/base/include/ark_web_memory.cpp b/ohos_interface/ohos_glue/base/include/ark_web_memory.cpp index 944c9013ebd99e0d586b21d463d09a1d81b11f53..fcf2bcdd1d0f4295c27c94841d6c7124b335296c 100644 --- a/ohos_interface/ohos_glue/base/include/ark_web_memory.cpp +++ b/ohos_interface/ohos_glue/base/include/ark_web_memory.cpp @@ -31,9 +31,14 @@ void* ArkWebMemMalloc(int size) void* mem = nullptr; if (size > 0) { mem = malloc(size); + if (mem == nullptr) { + ARK_WEB_BASE_DV_LOG("Memory allocation failed for size: %{public}d", size); + } else { + ARK_WEB_BASE_DV_LOG("address is %{public}ld, size is %{public}d", reinterpret_cast(mem), size); + } + } else { + ARK_WEB_BASE_DV_LOG("Invalid size: %{public}d", size); } - ARK_WEB_BASE_DV_LOG("address is %{public}ld,size is %{public}d", reinterpret_cast(mem), size); - return mem; } diff --git a/ohos_interface/ohos_glue/base/include/ark_web_types.cpp b/ohos_interface/ohos_glue/base/include/ark_web_types.cpp index 4c2ed2dda944544b82eb5f2805840ef3e03b4025..c1fb2b595071c732af874c5e00914ddcdf83e258 100644 --- a/ohos_interface/ohos_glue/base/include/ark_web_types.cpp +++ b/ohos_interface/ohos_glue/base/include/ark_web_types.cpp @@ -22,6 +22,11 @@ ArkWebU16String ArkWebU16StringClassToStruct(const std::u16string& class_value) ArkWebU16String struct_value = { .size = class_value.size(), .ark_web_mem_free_func = ArkWebMemFree }; if (struct_value.size > 0) { struct_value.value = (char16_t*)ArkWebMemMalloc((struct_value.size + 1) * sizeof(char16_t)); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + memcpy((char*)struct_value.value, (char*)class_value.c_str(), struct_value.size * sizeof(char16_t)); struct_value.value[struct_value.size] = 0; } @@ -48,6 +53,11 @@ ArkWebString ArkWebStringClassToStruct(const std::string& class_value) ArkWebString struct_value = { .size = class_value.size(), .ark_web_mem_free_func = ArkWebMemFree }; if (struct_value.size > 0) { struct_value.value = (char*)ArkWebMemMalloc(struct_value.size + 1); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + memcpy(struct_value.value, class_value.c_str(), struct_value.size); struct_value.value[struct_value.size] = 0; } @@ -69,7 +79,7 @@ std::string ArkWebStringStructToClass(const ArkWebString& struct_value) return class_value; } -void ArkWebStringStructRelease(ArkWebString& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebStringStructRelease(ArkWebString& struct_value) { struct_value.size = 0; SAFE_FREE(struct_value.value, struct_value.ark_web_mem_free_func); @@ -87,6 +97,12 @@ ArkWebStringMap ArkWebStringMapClassToStruct(const std::map 0) { struct_value.key = (ArkWebString*)ArkWebMemMalloc(sizeof(ArkWebString) * struct_value.size); struct_value.value = (ArkWebString*)ArkWebMemMalloc(sizeof(ArkWebString) * struct_value.size); + if (struct_value.key == nullptr || struct_value.value == nullptr) { + ArkWebMemFree(struct_value.key); + ArkWebMemFree(struct_value.value); + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -110,7 +126,7 @@ std::map ArkWebStringMapStructToClass(const ArkWebStri return class_value; } -void ArkWebStringMapStructRelease(ArkWebStringMap& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebStringMapStructRelease(ArkWebStringMap& struct_value) { for (int count = 0; count < struct_value.size; count++) { ArkWebStringStructRelease(struct_value.key[count]); @@ -127,6 +143,10 @@ ArkWebStringList ArkWebStringListClassToStruct(const std::list& cla ArkWebStringList struct_value = { .size = class_value.size(), .ark_web_mem_free_func = ArkWebMemFree }; if (struct_value.size > 0) { struct_value.value = (ArkWebString*)ArkWebMemMalloc(sizeof(ArkWebString) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -138,7 +158,7 @@ ArkWebStringList ArkWebStringListClassToStruct(const std::list& cla return struct_value; } -std::list ArkWebStringListStructToClass(const ArkWebStringList& struct_value) +ARK_WEB_NO_SANITIZE std::list ArkWebStringListStructToClass(const ArkWebStringList& struct_value) { std::list class_value; for (int count = 0; count < struct_value.size; count++) { @@ -163,6 +183,10 @@ ArkWebStringVector ArkWebStringVectorClassToStruct(const std::vector 0) { struct_value.value = (ArkWebString*)ArkWebMemMalloc(sizeof(ArkWebString) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -184,7 +208,7 @@ std::vector ArkWebStringVectorStructToClass(const ArkWebStringVecto return class_value; } -void ArkWebStringVectorStructRelease(ArkWebStringVector& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebStringVectorStructRelease(ArkWebStringVector& struct_value) { for (int count = 0; count < struct_value.size; count++) { ArkWebStringStructRelease(struct_value.value[count]); @@ -201,6 +225,12 @@ ArkWebStringVectorMap ArkWebStringVectorMapClassToStruct( if (struct_value.size > 0) { struct_value.key = (ArkWebString*)ArkWebMemMalloc(sizeof(ArkWebString) * struct_value.size); struct_value.value = (ArkWebStringVector*)ArkWebMemMalloc(sizeof(ArkWebStringVector) * struct_value.size); + if (struct_value.key == nullptr || struct_value.value == nullptr) { + ArkWebMemFree(struct_value.key); + ArkWebMemFree(struct_value.value); + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -226,7 +256,7 @@ std::map> ArkWebStringVectorMapStructToCla return class_value; } -void ArkWebStringVectorMapStructRelease(ArkWebStringVectorMap& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebStringVectorMapStructRelease(ArkWebStringVectorMap& struct_value) { for (int count = 0; count < struct_value.size; count++) { ArkWebStringStructRelease(struct_value.key[count]); diff --git a/ohos_interface/ohos_glue/base/include/ark_web_types.h b/ohos_interface/ohos_glue/base/include/ark_web_types.h index 152c2342ae3498a5468da31ddbf80e9d6cafd3dd..d93e726d1d8dff9d785563d4da5c4e10d465ffc9 100644 --- a/ohos_interface/ohos_glue/base/include/ark_web_types.h +++ b/ohos_interface/ohos_glue/base/include/ark_web_types.h @@ -203,6 +203,12 @@ R ArkWebBasicMapClassToStruct(const std::map& class_value) if (struct_value.size > 0) { struct_value.key = (T1*)ArkWebMemMalloc(sizeof(T1) * struct_value.size); struct_value.value = (T2*)ArkWebMemMalloc(sizeof(T2) * struct_value.size); + if (struct_value.key == nullptr || struct_value.value == nullptr) { + ArkWebMemFree(struct_value.key); + ArkWebMemFree(struct_value.value); + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -229,7 +235,7 @@ std::map ArkWebBasicMapStructToClass(const P& struct_value) } template -void ArkWebBasicMapStructRelease(P& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebBasicMapStructRelease(P& struct_value) { struct_value.size = 0; SAFE_FREE(struct_value.key, struct_value.ark_web_mem_free_func); @@ -242,6 +248,10 @@ R ArkWebBasicListClassToStruct(const std::list& class_value) R struct_value = { .size = class_value.size(), .ark_web_mem_free_func = ArkWebMemFree }; if (struct_value.size > 0) { struct_value.value = (T*)ArkWebMemMalloc(sizeof(T) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -267,7 +277,7 @@ std::list ArkWebBasicListStructToClass(const P& struct_value) } template -void ArkWebBasicListStructRelease(P& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebBasicListStructRelease(P& struct_value) { struct_value.size = 0; SAFE_FREE(struct_value.value, struct_value.ark_web_mem_free_func); @@ -279,6 +289,10 @@ R ArkWebBasicVectorClassToStruct(const std::vector& class_value) R struct_value = { .size = class_value.size(), .ark_web_mem_free_func = ArkWebMemFree }; if (struct_value.size > 0) { struct_value.value = (T*)ArkWebMemMalloc(sizeof(T) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { @@ -304,7 +318,7 @@ std::vector ArkWebBasicVectorStructToClass(const P& struct_value) } template -void ArkWebBasicVectorStructRelease(P& struct_value) +ARK_WEB_NO_SANITIZE void ArkWebBasicVectorStructRelease(P& struct_value) { struct_value.size = 0; SAFE_FREE(struct_value.value, struct_value.ark_web_mem_free_func); diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_hilog_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_hilog_adapter_wrapper.cpp index 17893def6c7a2d10aa26b510838bd865a9cdfec7..d75799b7e5715f9b6bf6bb3e07f2bab260548712 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_hilog_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_hilog_adapter_wrapper.cpp @@ -14,12 +14,13 @@ */ #include "hilog_adapter.h" +#include "base/include/ark_web_macros.h" #include "ohos_adapter/bridge/ark_web_adapter_bridge_helper.h" namespace OHOS::NWeb { using HiLogAdapterPrintLogFunc = int (*)(uint32_t level, const char* tag, const char* fmt, va_list ap); -int HiLogAdapter::PrintLog(LogLevelAdapter level, const char* tag, const char* fmt, ...) +ARK_WEB_NO_SANITIZE int HiLogAdapter::PrintLog(LogLevelAdapter level, const char* tag, const char* fmt, ...) { static HiLogAdapterPrintLogFunc hi_log_adapter_print_log = reinterpret_cast( ArkWeb::ArkWebAdapterBridgeHelper::GetInstance(false).LoadFuncSymbol("HiLogAdapterPrintLog", false)); @@ -35,7 +36,7 @@ int HiLogAdapter::PrintLog(LogLevelAdapter level, const char* tag, const char* f return ret; } -int HiLogAdapter::PrintConsoleLog(LogLevelAdapter level, const char* tag, const char* fmt, ...) +ARK_WEB_NO_SANITIZE int HiLogAdapter::PrintConsoleLog(LogLevelAdapter level, const char* tag, const char* fmt, ...) { static HiLogAdapterPrintLogFunc hi_log_adapter_console_log = reinterpret_cast( ArkWeb::ArkWebAdapterBridgeHelper::GetInstance(false).LoadFuncSymbol("HiLogAdapterConsoleLog", false)); diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.cpp index b1fbadd3b3c7b48c998ef326ca8e322b8cd0d8f7..54d23bc9b8a294501344d956bed612f55af201b0 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.cpp @@ -59,4 +59,13 @@ uint32_t ArkIMFTextConfigAdapterImpl::GetWindowId() return real_->GetWindowId(); } +double ArkIMFTextConfigAdapterImpl::GetPositionY() +{ + return real_->GetPositionY(); +} + +double ArkIMFTextConfigAdapterImpl::GetHeight() +{ + return real_->GetHeight(); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.h index 2fa2214252950b955a0df6113a75cd3567ab34c4..1d6762f00cad68277425bdb184259c3cbdc02a25 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_config_adapter_impl.h @@ -34,6 +34,10 @@ public: uint32_t GetWindowId() override; + double GetPositionY() override; + + double GetHeight() override; + private: std::shared_ptr real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.cpp index 35a04369e85d0622873ba910694482ed162c0ccd..d9cedd1477c4541d8c453400a99b577517ced871 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.cpp @@ -117,4 +117,10 @@ void ArkIMFTextListenerAdapterImpl::SetNeedUnderLine(bool isNeedUnderline) { real_->SetNeedUnderLine(isNeedUnderline); } + +void ArkIMFTextListenerAdapterImpl::AutoFillWithIMFEvent(bool isUsername, bool isOtherAccount, bool isNewPassword, + const ArkWebString& content) +{ + real_->AutoFillWithIMFEvent(isUsername, isOtherAccount, isNewPassword, ArkWebStringStructToClass(content)); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.h index 014ab8c487a7d97b0a366e15a780ff1d23615c1d..eb004f8a919df8e42540c324b855eab9b88f478d 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imf_text_listener_adapter_impl.h @@ -60,6 +60,9 @@ public: void SetNeedUnderLine(bool isNeedUnderline) override; + void AutoFillWithIMFEvent(bool isUsername, bool isOtherAccount, bool isNewPassword, + const ArkWebString& content) override; + private: std::shared_ptr real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.cpp index 43a6cbf58411dbbaebaacec70eddacb4eb7c6208..d6c3998c80bacffddd138e4a98c606cb8a88848f 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.cpp @@ -80,4 +80,16 @@ void ArkIMFAdapterWrapper::OnSelectionChange(std::u16string text, int start, int ArkWebU16StringStructRelease(str); } +bool ArkIMFAdapterWrapper::SendPrivateCommand(const std::string& commandKey, const std::string& commandValue) +{ + ArkWebString keyStr = ArkWebStringClassToStruct(commandKey); + ArkWebString valueStr = ArkWebStringClassToStruct(commandValue); + auto result = ctocpp_->SendPrivateCommand(keyStr, valueStr); + + ArkWebStringStructRelease(keyStr); + ArkWebStringStructRelease(valueStr); + + return result; +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.h index fd498977b0286a6853e3fe27d775296113057524..99856159f26778f88e5a8aca0351c965a556ec95 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_imfadapter_wrapper.h @@ -41,6 +41,8 @@ public: void OnSelectionChange(std::u16string text, int start, int end) override; + bool SendPrivateCommand(const std::string& commandKey, const std::string& commandValue) override; + private: ArkWebRefPtr ctocpp_; }; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_capabilities_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_capabilities_adapter_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f3bc6da12ee1df1ad5f4535c02abad0a8e32916 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_capabilities_adapter_wrapper.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_net_capabilities_adapter_wrapper.h" + +namespace OHOS::ArkWeb { + +ArkNetCapabilitiesAdapterWrapper::ArkNetCapabilitiesAdapterWrapper( + ArkWebRefPtr ref) : ctocpp_(ref) {} + +int32_t ArkNetCapabilitiesAdapterWrapper::GetNetId() +{ + return ctocpp_->GetNetId(); +} + +OHOS::NWeb::NetConnectType ArkNetCapabilitiesAdapterWrapper::GetConnectType() +{ + return static_cast(ctocpp_->GetConnectType()); +} + +OHOS::NWeb::NetConnectSubtype ArkNetCapabilitiesAdapterWrapper::GetConnectSubtype() +{ + return static_cast(ctocpp_->GetConnectSubtype()); +} + +} // namespace OHOS::ArkWeb \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_capabilities_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_capabilities_adapter_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..24add50ca2ec4c55a909bf5df0f92773ef560744 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_capabilities_adapter_wrapper.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_NET_CAPABILITIES_ADAPTER_WRAPPER_H +#define ARK_NET_CAPABILITIES_ADAPTER_WRAPPER_H +#pragma once + +#include "net_connect_adapter.h" +#include "ohos_adapter/include/ark_net_connect_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkNetCapabilitiesAdapterWrapper : public NWeb::NetCapabilitiesAdapter { +public: + ArkNetCapabilitiesAdapterWrapper(ArkWebRefPtr); + + int32_t GetNetId() override; + + OHOS::NWeb::NetConnectType GetConnectType() override; + + OHOS::NWeb::NetConnectSubtype GetConnectSubtype() override; + +private: + ArkWebRefPtr ctocpp_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_NET_CAPABILITIES_ADAPTER_WRAPPER_H \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.cpp index 17c2e6bc3d2fa053d28b5943f0810185d2ef58fb..fc76257af1edfc5b6ce2731c7466e4f32025e83d 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.cpp @@ -13,7 +13,11 @@ * limitations under the License. */ +#include "ohos_adapter/bridge/ark_net_capabilities_adapter_wrapper.h" #include "ohos_adapter/bridge/ark_net_conn_callback_impl.h" +#include "ohos_adapter/bridge/ark_net_connection_properties_adapter_wrapper.h" + +#include "base/bridge/ark_web_bridge_macros.h" namespace OHOS::ArkWeb { @@ -40,4 +44,26 @@ int32_t ArkNetConnCallbackImpl::NetUnavailable() return real_->NetUnavailable(); } +int32_t ArkNetConnCallbackImpl::OnNetCapabilitiesChanged( + const ArkWebRefPtr capabilites) +{ + if (CHECK_REF_PTR_IS_NULL(capabilites)) { + return real_->OnNetCapabilitiesChanged(nullptr); + } + + return real_->OnNetCapabilitiesChanged( + std::make_shared(capabilites)); +} + +int32_t ArkNetConnCallbackImpl::OnNetConnectionPropertiesChanged( + const ArkWebRefPtr properties) +{ + if (CHECK_REF_PTR_IS_NULL(properties)) { + return real_->OnNetConnectionPropertiesChanged(nullptr); + } + + return real_->OnNetConnectionPropertiesChanged( + std::make_shared(properties)); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.h index 4287d40fca390210e1b2ffba7facf8702180d75d..7c9bc9f1e0cfa575e652f05dfd056ee75aaa3192 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_conn_callback_impl.h @@ -34,6 +34,12 @@ public: int32_t NetUnavailable() override; + int32_t OnNetCapabilitiesChanged( + const ArkWebRefPtr capabilites) override; + + int32_t OnNetConnectionPropertiesChanged( + const ArkWebRefPtr properties) override; + private: std::shared_ptr real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_connection_properties_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_connection_properties_adapter_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d9f88b201812a365096f3dc90171ebf05d20dab --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_connection_properties_adapter_wrapper.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_net_connection_properties_adapter_wrapper.h" + +namespace OHOS::ArkWeb { + +ArkNetConnectionPropertiesAdapterWrapper::ArkNetConnectionPropertiesAdapterWrapper( + ArkWebRefPtr ref) : ctocpp_(ref) {} + +int32_t ArkNetConnectionPropertiesAdapterWrapper::GetNetId() +{ + return ctocpp_->GetNetId(); +} + +} // namespace OHOS::ArkWeb \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_connection_properties_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_connection_properties_adapter_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..80287efb415733d970b8a9e0f7a25d89ef295777 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_net_connection_properties_adapter_wrapper.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_NET_CONNECTION_PROPERTIES_ADAPTER_WRAPPER_H +#define ARK_NET_CONNECTION_PROPERTIES_ADAPTER_WRAPPER_H +#pragma once + +#include "net_connect_adapter.h" +#include "ohos_adapter/include/ark_net_connect_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkNetConnectionPropertiesAdapterWrapper : public NWeb::NetConnectionPropertiesAdapter { +public: + ArkNetConnectionPropertiesAdapterWrapper(ArkWebRefPtr); + + int32_t GetNetId() override; + +private: + ArkWebRefPtr ctocpp_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_NET_CONNECTION_PROPERTIES_ADAPTER_WRAPPER_H \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.cpp index 45706409c77768ecb3a66e285e0e923160f3c388..4b1f2cdeb7cd028ed5dc667ee197bda22f7442ab 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.cpp @@ -57,6 +57,7 @@ #include "ohos_adapter/bridge/ark_print_manager_adapter_wrapper.h" #include "ohos_adapter/bridge/ark_running_lock_adapter_wrapper.h" #include "ohos_adapter/bridge/ark_screen_capture_adapter_wrapper.h" +#include "ohos_adapter/bridge/ark_sensor_adapter_wrapper.h" #include "ohos_adapter/bridge/ark_soc_perf_client_adapter_wrapper.h" #include "ohos_adapter/bridge/ark_surface_buffer_adapter_wrapper.h" #include "ohos_adapter/bridge/ark_system_properties_adapter_wrapper.h" @@ -448,4 +449,22 @@ std::unique_ptr ArkOhosAdapterHelperWrapper::Crea return std::make_unique(adapter); } +std::unique_ptr ArkOhosAdapterHelperWrapper::CreateSensorAdapter() +{ + ArkWebRefPtr adapter = ctocpp_->CreateSensorAdapter(); + + if (CHECK_REF_PTR_IS_NULL(adapter)) { + return nullptr; + } + + return std::make_unique(adapter); +} + +void ArkOhosAdapterHelperWrapper::SetArkWebCoreHapPathOverride(const std::string& hapPath) +{ + ArkWebString str = ArkWebStringClassToStruct(hapPath); + ctocpp_->SetArkWebCoreHapPathOverride(str); + ArkWebStringStructRelease(str); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.h index 1d11905b6bbfec562c77c5dfa040c43d5be24c69..688209e52ffaf920bcbc7ccfd45eb15cf6a9df8d 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_adapter_helper_wrapper.h @@ -108,6 +108,10 @@ public: std::unique_ptr CreateOhosImageDecoderAdapter() override; + std::unique_ptr CreateSensorAdapter() override; + + void SetArkWebCoreHapPathOverride(const std::string& hapPath) override; + private: ArkWebRefPtr ctocpp_; }; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_init_web_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_init_web_adapter_wrapper.cpp index 3646cc7c88d0ec04d1ea4a87106989bceab0e3a3..c1864085ea2e7cebb7b180c0282bf181d57dd964 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_init_web_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_init_web_adapter_wrapper.cpp @@ -24,7 +24,7 @@ NWeb::WebRunInitedCallback* ArkOhosInitWebAdapterWrapper::GetRunWebInitedCallbac return (NWeb::WebRunInitedCallback*)ctocpp_->GetRunWebInitedCallback(); } -void ArkOhosInitWebAdapterWrapper::SetRunWebInitedCallback(NWeb::WebRunInitedCallback* callback) +ARK_WEB_NO_SANITIZE void ArkOhosInitWebAdapterWrapper::SetRunWebInitedCallback(NWeb::WebRunInitedCallback* callback) { ctocpp_->SetRunWebInitedCallback((void*)callback); } diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.cpp index 4f3d8dd72ab27752515671f825b1938f5b3957d8..f6d3f18466c1119fedac5186c4e7f673be562430 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.cpp @@ -68,4 +68,15 @@ bool ArkOhosResourceAdapterWrapper::GetRawFileLastModTime(const std::string& raw return result; } +std::string ArkOhosResourceAdapterWrapper::GetSystemLanguage() +{ + if (!ctocpp_) { + return ""; + } + + ArkWebString ark_result = ctocpp_->GetSystemLanguage(); + std::string result = ArkWebStringStructToClass(ark_result); + ArkWebStringStructRelease(ark_result); + return result; +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.h index 4a0a66da221a6bb9d261ae24b19f1ca4a95fb1e7..8fe34aacae4cde16fe3af19b6422a375ec8086f1 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_ohos_resource_adapter_wrapper.h @@ -36,6 +36,8 @@ public: bool GetRawFileLastModTime(const std::string& rawFile, time_t& time, bool isSys = false) override; + std::string GetSystemLanguage() override; + private: ArkWebRefPtr ctocpp_; }; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_paste_board_client_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_paste_board_client_adapter_wrapper.cpp index 82ffda0d0e981db055db4af9fb5fb35bee381184..c5f8e1236cc08222ed34a22d482bf7c152c598c6 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_paste_board_client_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_paste_board_client_adapter_wrapper.cpp @@ -30,6 +30,11 @@ static ArkPasteRecordVector ArkPasteRecordVectorClassToStruct(const NWeb::PasteR if (struct_value.size > 0) { struct_value.value = (ark_paste_data_record_adapter_t**)ArkWebMemMalloc( sizeof(ark_paste_data_record_adapter_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { std::shared_ptr data = diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_adapter_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f1765b9b6a0019ed0468f9206c02246b2964391 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_adapter_wrapper.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_sensor_adapter_wrapper.h" + +#include "ohos_adapter/bridge/ark_sensor_callback_adapter_impl.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { + +ArkSensorAdapterWrapper::ArkSensorAdapterWrapper(ArkWebRefPtr ref) + : ctocpp_(ref) +{} + +int32_t ArkSensorAdapterWrapper::IsOhosSensorSupported(int32_t sensorTypeId) +{ + return ctocpp_->IsOhosSensorSupported(sensorTypeId); +} + +int32_t ArkSensorAdapterWrapper::GetOhosSensorReportingMode(int32_t sensorTypeId) +{ + return ctocpp_->GetOhosSensorReportingMode(sensorTypeId); +} + +double ArkSensorAdapterWrapper::GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) +{ + return ctocpp_->GetOhosSensorDefaultSupportedFrequency(sensorTypeId); +} + +double ArkSensorAdapterWrapper::GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) +{ + return ctocpp_->GetOhosSensorMinSupportedFrequency(sensorTypeId); +} + +double ArkSensorAdapterWrapper::GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) +{ + return ctocpp_->GetOhosSensorMaxSupportedFrequency(sensorTypeId); +} + +int32_t ArkSensorAdapterWrapper::SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) +{ + return ctocpp_->SubscribeOhosSensor(sensorTypeId, samplingInterval); +} + +int32_t ArkSensorAdapterWrapper::UnsubscribeOhosSensor(int32_t sensorTypeId) +{ + return ctocpp_->UnsubscribeOhosSensor(sensorTypeId); +} + +int32_t ArkSensorAdapterWrapper::RegistOhosSensorCallback(int32_t sensorTypeId, + std::shared_ptr callbackAdapter) +{ + if (CHECK_SHARED_PTR_IS_NULL(callbackAdapter)) { + return ctocpp_->RegistOhosSensorCallback(-1, nullptr); + } + + return ctocpp_->RegistOhosSensorCallback(sensorTypeId, + new ArkSensorCallbackAdapterImpl(callbackAdapter)); +} +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_adapter_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..8db4f15eb130614a7499632fd531d44c167eb38d --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_adapter_wrapper.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_SENSOR_ADAPTER_WRAPPER_H +#define ARK_SENSOR_ADAPTER_WRAPPER_H +#pragma once + +#include "sensor_adapter.h" +#include "ohos_adapter/include/ark_sensor_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkSensorAdapterWrapper : public OHOS::NWeb::SensorAdapter { +public: + ArkSensorAdapterWrapper(ArkWebRefPtr); + + int32_t IsOhosSensorSupported(int32_t sensorTypeId) override; + int32_t GetOhosSensorReportingMode(int32_t sensorTypeId) override; + double GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) override; + double GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) override; + double GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) override; + int32_t SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) override; + int32_t RegistOhosSensorCallback(int32_t sensorTypeId, + std::shared_ptr callbackAdapter) override; + int32_t UnsubscribeOhosSensor(int32_t sensorTypeId) override; + +private: + ArkWebRefPtr ctocpp_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_SENSOR_ADAPTER_WRAPPER_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_callback_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_callback_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1714e840e88e2b2572c2d86875f940837e697cf6 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_callback_adapter_impl.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_sensor_callback_adapter_impl.h" + +namespace OHOS::ArkWeb { + +ArkSensorCallbackAdapterImpl::ArkSensorCallbackAdapterImpl( + std::shared_ptr ref) + : real_(ref) +{} + +void ArkSensorCallbackAdapterImpl::UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) +{ + real_->UpdateOhosSensorData(timestamp, value1, value2, value3, value4); +} +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_callback_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_callback_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..0bca27d8c719d45fc943d79e2eb7d7111f7b76ed --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_sensor_callback_adapter_impl.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_SENSOR_CALLBACK_ADAPTER_IMPL_H +#define ARK_SENSOR_CALLBACK_ADAPTER_IMPL_H +#pragma once + +#include "sensor_adapter.h" +#include "ohos_adapter/include/ark_sensor_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkSensorCallbackAdapterImpl : public ArkSensorCallbackAdapter { +public: + ArkSensorCallbackAdapterImpl(std::shared_ptr); + + void UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) override; + +private: + std::shared_ptr real_; + + IMPLEMENT_REFCOUNTING(ArkSensorCallbackAdapterImpl); +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_SENSOR_CALLBACK_ADAPTER_IMPL_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.cpp index eb58cd05423dd4b4d6563e8ff742a64cbd2975a3..7e82941ab177d219fae5236ccdec498a5ddc0648 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.cpp @@ -182,6 +182,7 @@ bool ArkSystemPropertiesAdapterWrapper::GetBoolParameter(const std::string& key, return result; } +ARK_WEB_NO_SANITIZE std::vector ArkSystemPropertiesAdapterWrapper::GetLTPOConfig(const std::string& settingName) { if (!ctocpp_) { @@ -211,4 +212,12 @@ std::string ArkSystemPropertiesAdapterWrapper::GetOOPGPUStatus() ArkWebStringStructRelease(str); return result; } + +bool ArkSystemPropertiesAdapterWrapper::IsLTPODynamicApp(const std::string& bundleName) +{ + ArkWebString ark_bundle_name = ArkWebStringClassToStruct(bundleName); + bool result = ctocpp_->IsLTPODynamicApp(ark_bundle_name); + ArkWebStringStructRelease(ark_bundle_name); + return result; +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.h index a3bedcff2a5a948b923a988b99b7e2a49ce410bd..12a363fef1fcc3783e68ba8aa1cc90dafb6e965c 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_system_properties_adapter_wrapper.h @@ -69,6 +69,7 @@ public: std::string GetOOPGPUStatus() override; + bool IsLTPODynamicApp(const std::string& bundleName) override; private: ArkWebRefPtr ctocpp_; }; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.cpp index 7c1c4bf4c7ac93097b0c6c063550b96fad0770fe..60a40a7316fc3a10a5f89db706d80ee992fb509b 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.cpp @@ -67,4 +67,14 @@ void ArkVSyncAdapterWrapper::SetOnVsyncEndCallback(OnVsyncCallback onVsyncEndCal } return ctocpp_->SetOnVsyncEndCallback(onVsyncEndCallback); } + +void ArkVSyncAdapterWrapper::SetScene(const std::string& sceneName, uint32_t state) +{ + if (!ctocpp_) { + return; + } + ArkWebString ark_value = ArkWebStringClassToStruct(sceneName); + ctocpp_->SetScene(ark_value, state); + ArkWebStringStructRelease(ark_value); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.h index 7dac11d88fbf61903730605c091d02efc0e3fb26..970a52cb068b7600a5638a7ec57ad433e180ada1 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_vsync_adapter_wrapper.h @@ -37,10 +37,10 @@ public: void SetOnVsyncEndCallback(OnVsyncCallback onVsyncEndCallback) override; + void SetScene(const std::string& sceneName, uint32_t state) override; private: ArkWebRefPtr ctocpp_; }; - } // namespace OHOS::ArkWeb #endif // ARK_VSYNC_ADAPTER_WRAPPER_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_web_adapter_bridge_helper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_web_adapter_bridge_helper.cpp index bec20dfb8673dd90c7616401557d5155bdc699ab..1180d736db242553f8b6a9a3c79e0aa2c1882955 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_web_adapter_bridge_helper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webcore/ark_web_adapter_bridge_helper.cpp @@ -22,12 +22,6 @@ namespace OHOS::ArkWeb { const std::string LIB_FILE_NAME = "libohos_adapter_glue_source.z.so"; -#if defined(__aarch64__) || defined(__x86_64__) -const std::string LIB_DIR_PATH = "/system/lib64"; -#else -const std::string LIB_DIR_PATH = "/system/lib"; -#endif - ArkWebAdapterBridgeHelper& ArkWebAdapterBridgeHelper::GetInstance(bool isPrintLog) { static ArkWebAdapterBridgeHelper helper; @@ -38,7 +32,7 @@ ArkWebAdapterBridgeHelper& ArkWebAdapterBridgeHelper::GetInstance(bool isPrintLo bool ArkWebAdapterBridgeHelper::Init(bool isPrintLog) { - return LoadLibFile(RTLD_LAZY, LIB_DIR_PATH + "/" + LIB_FILE_NAME, isPrintLog); + return LoadLibFile(RTLD_LAZY, LIB_FILE_NAME, isPrintLog); } } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_camera_manager_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_camera_manager_adapter_impl.cpp index c07b17448353edec26dcd396c68cccdc858b9180..6d62b1c88c4f1efdcbc78f79be4924628fc56ac0 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_camera_manager_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_camera_manager_adapter_impl.cpp @@ -56,6 +56,11 @@ int32_t ArkCameraManagerAdapterImpl::GetExposureModes(ArkWebInt32Vector& exposur exposureModesAdapter.ark_web_mem_free_func = ArkWebMemFree; if (exposureModesAdapter.size > 0) { exposureModesAdapter.value = (int32_t*)ArkWebMemMalloc(sizeof(int32_t) * exposureModesAdapter.size); + if (exposureModesAdapter.value == nullptr) { + exposureModesAdapter.size = 0; + return -1; + } + int count = 0; for (auto it = vec.begin(); it != vec.end(); it++) { exposureModesAdapter.value[count] = (int32_t)(*it); diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.cpp index 470ed65a7109aa4330b49e7afa6a9413eaf835a5..00f601719192d1bef5b045d1774b7d9f0c834ce4 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.cpp @@ -79,4 +79,12 @@ void ArkIMFAdapterImpl::OnSelectionChange(ArkWebU16String& text, int start, int real_->OnSelectionChange(ArkWebU16StringStructToClass(text), start, end); } +bool ArkIMFAdapterImpl::SendPrivateCommand(const ArkWebString& commandKey, const ArkWebString& commandValue) +{ + std::string key = ArkWebStringStructToClass(commandKey); + std::string value = ArkWebStringStructToClass(commandValue); + + return real_->SendPrivateCommand(key, value); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.h index eef6f1b5c06ee8326d1b63606537f3eb30bf7614..a518700cc071d24b6d0983dd7d6530e80d59204c 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imf_adapter_impl.h @@ -41,6 +41,8 @@ public: void OnSelectionChange(ArkWebU16String& text, int start, int end) override; + bool SendPrivateCommand(const ArkWebString& commandKey, const ArkWebString& commandValue) override; + private: std::shared_ptr real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.cpp index 61ef624f8e40ec508d41fe0a48ea172d697fba76..af7aa2310423ebf79578d718ee92e1785b373d13 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.cpp @@ -58,4 +58,13 @@ uint32_t ArkIMFTextConfigAdapterWrapper::GetWindowId() return ctocpp_->GetWindowId(); } +double ArkIMFTextConfigAdapterWrapper::GetPositionY() +{ + return ctocpp_->GetPositionY(); +} + +double ArkIMFTextConfigAdapterWrapper::GetHeight() +{ + return ctocpp_->GetHeight(); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.h index 6f03508c362701680f0db63124134a527bacc25f..b7121b0df402a108916e1e6138df0621dda0dbe3 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_config_adapter_wrapper.h @@ -34,6 +34,10 @@ public: uint32_t GetWindowId() override; + double GetPositionY() override; + + double GetHeight() override; + private: ArkWebRefPtr ctocpp_; }; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.cpp index cb76b9ceb3f85f4c91419e846bbcbd68f57888ee..07a317a6d727a293d78f81a5fb41eccf33e83ec0 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.cpp @@ -129,4 +129,13 @@ void ArkIMFTextListenerAdapterWrapper::SetNeedUnderLine(bool isNeedUnderline) ctocpp_->SetNeedUnderLine(isNeedUnderline); } +void ArkIMFTextListenerAdapterWrapper::AutoFillWithIMFEvent(bool isUsername, bool isOtherAccount, bool isNewPassword, + const std::string& content) +{ + ArkWebString str = ArkWebStringClassToStruct(content); + ctocpp_->AutoFillWithIMFEvent(isUsername, isOtherAccount, isNewPassword, str); + + ArkWebStringStructRelease(str); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.h index 66d657df0ccf3e84fafac7260994b00521948645..2f92c0b7a7ecb38fac707fe3d13ef724dd7d23dc 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_imftext_listener_adapter_wrapper.h @@ -60,6 +60,9 @@ public: void SetNeedUnderLine(bool isNeedUnderline) override; + void AutoFillWithIMFEvent(bool isUsername, bool isOtherAccount, bool isNewPassword, + const std::string& content) override; + private: ArkWebRefPtr ctocpp_; }; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_capabilities_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_capabilities_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..643a0f99a64a241a09d645b6e909094198b6380e --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_capabilities_adapter_impl.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_net_capabilities_adapter_impl.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { +ArkNetCapabilitiesAdapterImpl::ArkNetCapabilitiesAdapterImpl(std::shared_ptr ref) + : real_(ref) {} + +int32_t ArkNetCapabilitiesAdapterImpl::GetNetId() +{ + return real_->GetNetId(); +} + +uint32_t ArkNetCapabilitiesAdapterImpl::GetConnectType() +{ + return (uint32_t)real_->GetConnectType(); +} + +uint32_t ArkNetCapabilitiesAdapterImpl::GetConnectSubtype() +{ + return (uint32_t)real_->GetConnectSubtype(); +} +} // namespace OHOS::ArkWeb \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_capabilities_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_capabilities_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..a9f60efff8fc799e43b1ea89cfd6b6b0e9793607 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_capabilities_adapter_impl.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_NET_CAPABILITIES_ADAPTER_IMPL_H +#define ARK_NET_CAPABILITIES_ADAPTER_IMPL_H +#pragma once + +#include "net_connect_adapter.h" +#include "ohos_adapter/include/ark_net_connect_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkNetCapabilitiesAdapterImpl : public ArkNetCapabilitiesAdapter { +public: + ArkNetCapabilitiesAdapterImpl(std::shared_ptr); + + int32_t GetNetId() override; + + uint32_t GetConnectType() override; + + uint32_t GetConnectSubtype() override; + +private: + std::shared_ptr real_; + + IMPLEMENT_REFCOUNTING(ArkNetCapabilitiesAdapterImpl); +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_NET_CAPABILITIES_ADAPTER_IMPL_H \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.cpp index f23a6c972ff18ccd96da8a3d19ede42202710e81..89ac8d56c3424fc9a8b8519a0e5e0b8786b0b4af 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.cpp @@ -13,7 +13,9 @@ * limitations under the License. */ +#include "ohos_adapter/bridge/ark_net_capabilities_adapter_impl.h" #include "ohos_adapter/bridge/ark_net_conn_callback_wrapper.h" +#include "ohos_adapter/bridge/ark_net_connection_properties_adapter_impl.h" #include "base/bridge/ark_web_bridge_macros.h" @@ -42,4 +44,24 @@ int32_t ArkNetConnCallbackWrapper::NetUnavailable() return ctocpp_->NetUnavailable(); } +int32_t ArkNetConnCallbackWrapper::OnNetCapabilitiesChanged( + const std::shared_ptr capabilities) +{ + if (CHECK_SHARED_PTR_IS_NULL(capabilities)) { + return ctocpp_->OnNetCapabilitiesChanged(nullptr); + } + + return ctocpp_->OnNetCapabilitiesChanged(new ArkNetCapabilitiesAdapterImpl(capabilities)); +} + +int32_t ArkNetConnCallbackWrapper::OnNetConnectionPropertiesChanged( + const std::shared_ptr properties) +{ + if (CHECK_SHARED_PTR_IS_NULL(properties)) { + return ctocpp_->OnNetConnectionPropertiesChanged(nullptr); + } + + return ctocpp_->OnNetConnectionPropertiesChanged(new ArkNetConnectionPropertiesAdapterImpl(properties)); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.h index 78975cec80d7977bacd275145b0bce4b4ead27a8..03539aa9054df553c9f6799d9a53481cf3aef0d8 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_conn_callback_wrapper.h @@ -30,6 +30,10 @@ public: const OHOS::NWeb::NetConnectSubtype& netConnectSubtype) override; int32_t NetConnectionPropertiesChange() override; int32_t NetUnavailable() override; + int32_t OnNetCapabilitiesChanged( + const std::shared_ptr capabilities) override; + int32_t OnNetConnectionPropertiesChanged( + const std::shared_ptr properties) override; private: ArkWebRefPtr ctocpp_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_connection_properties_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_connection_properties_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a80f77d9a19734cd0bd9d25d6b66c2c972360d24 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_connection_properties_adapter_impl.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_net_connection_properties_adapter_impl.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { +ArkNetConnectionPropertiesAdapterImpl::ArkNetConnectionPropertiesAdapterImpl( + std::shared_ptr ref) : real_(ref) {} + +int32_t ArkNetConnectionPropertiesAdapterImpl::GetNetId() +{ + return real_->GetNetId(); +} + +} // namespace OHOS::ArkWeb \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_connection_properties_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_connection_properties_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..fd1d757004753e006443b9d82c03e6ce7f9a8900 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_net_connection_properties_adapter_impl.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_NET_CONNECTION_PROPERTIES_ADAPTER_IMPL_H +#define ARK_NET_CONNECTION_PROPERTIES_ADAPTER_IMPL_H +#pragma once + +#include "net_connect_adapter.h" +#include "ohos_adapter/include/ark_net_connect_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkNetConnectionPropertiesAdapterImpl : public ArkNetConnectionPropertiesAdapter { +public: + ArkNetConnectionPropertiesAdapterImpl(std::shared_ptr); + + int32_t GetNetId() override; + +private: + std::shared_ptr real_; + + IMPLEMENT_REFCOUNTING(ArkNetConnectionPropertiesAdapterImpl); +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_NET_CONNECTION_PROPERTIES_ADAPTER_IMPL_H \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.cpp index fb8d79ff5a34f87eed671e8d68a1ae8daf04caa7..49368063e08bd702ede7da1df9767c7bf7d5cc7f 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.cpp @@ -68,7 +68,7 @@ #include "ohos_adapter/bridge/ark_vsync_adapter_impl.h" #include "ohos_adapter/bridge/ark_web_date_timezone_info_impl.h" #include "ohos_adapter/bridge/ark_window_adapter_impl.h" - +#include "ohos_adapter/bridge/ark_sensor_adapter_impl.h" #include "base/bridge/ark_web_bridge_macros.h" namespace OHOS::ArkWeb { @@ -371,4 +371,16 @@ ArkWebRefPtr ArkOhosAdapterHelperImpl::CreateOhosIma return new ArkOhosImageDecoderAdapterImpl(shared); } +ArkWebRefPtr ArkOhosAdapterHelperImpl::CreateSensorAdapter() +{ + std::unique_ptr adapter = real_.CreateSensorAdapter(); + std::shared_ptr shared = std::move(adapter); + return new ArkSensorAdapterImpl(shared); +} + +void ArkOhosAdapterHelperImpl::SetArkWebCoreHapPathOverride(const ArkWebString& hapPath) +{ + real_.SetArkWebCoreHapPathOverride(ArkWebStringStructToClass(hapPath)); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.h index 5fbe44c4c7d83b95c4399f495e5263f820b4991f..76e238a0359a1201e1f4308f87e0eb46b50e03c8 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_adapter_helper_impl.h @@ -108,6 +108,10 @@ public: ArkWebRefPtr CreateOhosImageDecoderAdapter() override; + ArkWebRefPtr CreateSensorAdapter() override; + + void SetArkWebCoreHapPathOverride(const ArkWebString& hapPath) override; + private: NWeb::OhosAdapterHelper& real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.cpp index cac2d9b13e484eed9deff427f73c29ee58b8d3b9..7b5810e68c74cbe94fe04484abb793c8824511de 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.cpp @@ -57,4 +57,10 @@ bool ArkOhosResourceAdapterImpl::GetRawFileLastModTime(const ArkWebString& rawFi return real_->GetRawFileLastModTime(ArkWebStringStructToClass(rawFile), time, isSys); } +ArkWebString ArkOhosResourceAdapterImpl::GetSystemLanguage() +{ + std::string result = real_->GetSystemLanguage(); + return ArkWebStringClassToStruct(result); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.h index daec519808dd4af8b16f44428bec31588ccd2491..0ac59d78959a0c2149127b0be90a937874211fcc 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_ohos_resource_adapter_impl.h @@ -36,6 +36,8 @@ public: bool GetRawFileLastModTime(const ArkWebString& rawFile, time_t& time, bool isSys) override; + ArkWebString GetSystemLanguage() override; + private: std::shared_ptr real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_adapter_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..472ef827e6b1333dd78c115cf9f77aed3f2d915c --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_adapter_impl.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_sensor_adapter_impl.h" + +#include "ohos_adapter/bridge/ark_sensor_callback_adapter_wrapper.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { + +ArkSensorAdapterImpl::ArkSensorAdapterImpl(std::shared_ptr ref) + : real_(ref) +{} + +int32_t ArkSensorAdapterImpl::IsOhosSensorSupported(int32_t type) +{ + return real_->IsOhosSensorSupported(type); +} + +int32_t ArkSensorAdapterImpl::GetOhosSensorReportingMode(int32_t type) +{ + return real_->GetOhosSensorReportingMode(type); +} + +double ArkSensorAdapterImpl::GetOhosSensorDefaultSupportedFrequency(int32_t type) +{ + return real_->GetOhosSensorDefaultSupportedFrequency(type); +} + +double ArkSensorAdapterImpl::GetOhosSensorMinSupportedFrequency(int32_t type) +{ + return real_->GetOhosSensorMinSupportedFrequency(type); +} + +double ArkSensorAdapterImpl::GetOhosSensorMaxSupportedFrequency(int32_t type) +{ + return real_->GetOhosSensorMaxSupportedFrequency(type); +} + +int32_t ArkSensorAdapterImpl::SubscribeOhosSensor(int32_t type, int64_t samplingInterval) +{ + return real_->SubscribeOhosSensor(type, samplingInterval); +} + +int32_t ArkSensorAdapterImpl::RegistOhosSensorCallback(int32_t sensorTypeId, + ArkWebRefPtr callbackAdapter) +{ + if (!(CHECK_REF_PTR_IS_NULL(callbackAdapter))) { + return real_->RegistOhosSensorCallback(sensorTypeId, + std::make_shared(callbackAdapter)); + } + return false; +} + +int32_t ArkSensorAdapterImpl::UnsubscribeOhosSensor(int32_t type) +{ + return real_->UnsubscribeOhosSensor(type); +} + +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_adapter_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..f11880317611a6aea7ab5140dfbcc8fa93b9a229 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_adapter_impl.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_SENSOR_ADAPTER_IMPL_H +#define ARK_SENSOR_ADAPTER_IMPL_H +#pragma once + +#include "sensor_adapter.h" +#include "ohos_adapter/include/ark_sensor_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkSensorAdapterImpl : public ArkSensorAdapter { +public: + ArkSensorAdapterImpl(std::shared_ptr); + + int32_t IsOhosSensorSupported(int32_t sensorTypeId) override; + + int32_t GetOhosSensorReportingMode(int32_t type) override; + + double GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) override; + + double GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) override; + + double GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) override; + + int32_t SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) override; + + int32_t RegistOhosSensorCallback(int32_t sensorTypeId, + ArkWebRefPtr callbackAdapter) override; + + int32_t UnsubscribeOhosSensor(int32_t sensorTypeId) override; + +private: + std::shared_ptr real_; + + IMPLEMENT_REFCOUNTING(ArkSensorAdapterImpl); +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_SENSOR_ADAPTER_IMPL_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_callback_adapter_wrapper.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_callback_adapter_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d917c67283cf903b40863d0757ebd99eb54fad1 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_callback_adapter_wrapper.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_adapter/bridge/ark_sensor_callback_adapter_wrapper.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { +ArkSensorCallbackAdapterWrapper::ArkSensorCallbackAdapterWrapper( + ArkWebRefPtr ref) + : ctocpp_(ref) +{} + +void ArkSensorCallbackAdapterWrapper::UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) +{ + ctocpp_->UpdateOhosSensorData(timestamp, value1, value2, value3, value4); +} +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_callback_adapter_wrapper.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_callback_adapter_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..a30160c2a80e587e03f8a13e90f85cb4562c0901 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_sensor_callback_adapter_wrapper.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_SENSOR_CALLBACK_ADAPTER_WRAPPER_H +#define ARK_SENSOR_CALLBACK_ADAPTER_WRAPPER_H +#pragma once + +#include "sensor_adapter.h" +#include "ohos_adapter/include/ark_sensor_adapter.h" + +namespace OHOS::ArkWeb { + +class ArkSensorCallbackAdapterWrapper : public OHOS::NWeb::SensorCallbackAdapter { +public: + ArkSensorCallbackAdapterWrapper(ArkWebRefPtr); + + void UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) override; + +private: + ArkWebRefPtr ctocpp_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_SENSOR_CALLBACK_ADAPTER_WRAPPER_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.cpp index 95f3352f9a62437e7d4225a3486250e52eb86585..85403c84c9226315468962ad1ea8db8bfbcb2152 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.cpp @@ -131,6 +131,10 @@ ArkFrameRateSettingAdapterVector ArkSystemPropertiesAdapterImpl::GetLTPOConfig(c .ark_web_mem_free_func = ArkWebMemFree }; if (result.size > 0) { result.value = (ArkFrameRateSettingAdapter*)ArkWebMemMalloc(sizeof(ArkFrameRateSettingAdapter) * result.size); + if (result.value == nullptr) { + result.size = 0; + return result; + } int count = 0; for (auto it = frameRateSettingVector.begin(); it != frameRateSettingVector.end(); it++) { @@ -148,4 +152,8 @@ ArkWebString ArkSystemPropertiesAdapterImpl::GetOOPGPUStatus() return ArkWebStringClassToStruct(str); } +bool ArkSystemPropertiesAdapterImpl::IsLTPODynamicApp(const ArkWebString& bundleName) +{ + return real_.IsLTPODynamicApp(ArkWebStringStructToClass(bundleName)); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.h index b3933306f42654e698bc08753be0748ba5fc729b..c09572c0461d0f85233e27c6f0cc0d033a274e5a 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_system_properties_adapter_impl.h @@ -68,6 +68,7 @@ public: ArkWebString GetOOPGPUStatus() override; + bool IsLTPODynamicApp(const ArkWebString& settingName) override; private: NWeb::SystemPropertiesAdapter& real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.cpp b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.cpp index 94776186c5fa4db05d4ee38de0461bc62ddb91d5..a53628724c081db9e9de99713cd8d304a1afcff7 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.cpp @@ -50,4 +50,10 @@ void ArkVSyncAdapterImpl::SetOnVsyncEndCallback(OnVsyncCallback onVsyncEndCallba { return real_.SetOnVsyncEndCallback(onVsyncEndCallback); } -} // namespace OHOS::ArkWeb + +void ArkVSyncAdapterImpl::SetScene(const ArkWebString& sceneName, uint32_t state) +{ + std::string sceneNameStr = ArkWebStringStructToClass(sceneName); + return real_.SetScene(sceneNameStr, state); +} +} // namespace OHOS::ArkWeb \ No newline at end of file diff --git a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.h b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.h index ffeb602aaec2f1d1c39ca9013c787029ef9df65a..02fcb488fe64be4a8203c6020db04af3f4805a82 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.h +++ b/ohos_interface/ohos_glue/ohos_adapter/bridge/webview/ark_vsync_adapter_impl.h @@ -38,6 +38,7 @@ public: void SetOnVsyncEndCallback(OnVsyncCallback onVsyncEndCallback) override; + void SetScene(const ArkWebString& sceneName, uint32_t state) override; private: NWeb::VSyncAdapter& real_; diff --git a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_audio_device_desc_adapter_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_audio_device_desc_adapter_vector_cpptoc.cpp index 9d99523e5fa1cb837258299be2e7f7b177f63de2..8c25f27f50fa3817bf55507fd6f922fe67a1f76d 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_audio_device_desc_adapter_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_audio_device_desc_adapter_vector_cpptoc.cpp @@ -28,6 +28,11 @@ ArkAudioDeviceDescAdapterVector ArkAudioDeviceDescAdapterVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (_ark_audio_device_desc_adapter_t**)ArkWebMemMalloc( sizeof(_ark_audio_device_desc_adapter_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { if (!(*it)) { diff --git a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_format_adapter_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_format_adapter_vector_cpptoc.cpp index c771dc04819eabaf4884b028233b2c89b845f182..7394671601b3a1e3cae1559d2953c162151e574f 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_format_adapter_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_format_adapter_vector_cpptoc.cpp @@ -27,6 +27,11 @@ ArkFormatAdapterVector ArkFormatAdapterVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (_ark_format_adapter_t**)ArkWebMemMalloc(sizeof(_ark_format_adapter_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { if (!(*it)) { diff --git a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_paste_record_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_paste_record_vector_cpptoc.cpp index 6de819e90a9290a9965706c89c5c9f8b9788b9a7..da29fde5af498b1ac83393a7517098609a403f00 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_paste_record_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_paste_record_vector_cpptoc.cpp @@ -26,6 +26,11 @@ ArkPasteRecordVector ArkPasteRecordVectorClassToStruct(const NWeb::PasteRecordVe if (struct_value.size > 0) { struct_value.value = (ark_paste_data_record_adapter_t**)ArkWebMemMalloc( sizeof(ark_paste_data_record_adapter_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { ArkWebRefPtr adapter = new ArkPasteDataRecordAdapterImpl(*it); diff --git a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_video_device_descriptor_adapter_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_video_device_descriptor_adapter_vector_cpptoc.cpp index 14522fd56e01fc325c4993290b221c6c868d9072..d8a554d062a5d14e2cde392835f47594d16cb129 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_video_device_descriptor_adapter_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_adapter/cpptoc/webview/ark_video_device_descriptor_adapter_vector_cpptoc.cpp @@ -28,6 +28,11 @@ ArkVideoDeviceDescriptorAdapterVector ArkVideoDeviceDescriptorAdapterVectorClass if (struct_value.size > 0) { struct_value.value = (_ark_video_device_descriptor_adapter_t**)ArkWebMemMalloc( sizeof(_ark_video_device_descriptor_adapter_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } + int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { if (!(*it)) { diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_graphic_adapter.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_graphic_adapter.h index ca7f41511d9ebffc08f5750f267f38267ded3fbb..28f8235d7868099680fe564dbddd54ea334bfb8e 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/include/ark_graphic_adapter.h +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_graphic_adapter.h @@ -44,6 +44,9 @@ public: /*--ark web()--*/ virtual void SetOnVsyncEndCallback(OnVsyncCallback onVsyncEndCallback) = 0; + + /*--ark web()--*/ + virtual void SetScene(const ArkWebString& sceneName, uint32_t state) = 0; }; /*--ark web(source=webcore)--*/ @@ -225,7 +228,6 @@ public: virtual int32_t FlushBuffer(ArkWebRefPtr buffer, int32_t fence, ArkWebRefPtr config) = 0; }; - } // namespace OHOS::ArkWeb #endif // Ark_GRAPHIC_ADAPTER_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_imf_adapter.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_imf_adapter.h index 0bd546403484fe2736c0c4984b124be273358ca4..b67353e1266a7d696085584ba2b86678e558863f 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/include/ark_imf_adapter.h +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_imf_adapter.h @@ -72,6 +72,12 @@ public: /*--ark web()--*/ virtual uint32_t GetWindowId() = 0; + + /*--ark web()--*/ + virtual double GetPositionY() = 0; + + /*--ark web()--*/ + virtual double GetHeight() = 0; }; /*--ark web(source=webview)--*/ @@ -134,6 +140,10 @@ public: /*--ark web()--*/ virtual void SetNeedUnderLine(bool isNeedUnderline) = 0; + + /*--ark web()--*/ + virtual void AutoFillWithIMFEvent(bool isUsername, bool isOtherAccount, bool isNewPassword, + const ArkWebString& content) = 0; }; /*--ark web(source=webview)--*/ @@ -160,6 +170,9 @@ public: /*--ark web()--*/ virtual void OnSelectionChange(ArkWebU16String& text, int start, int end) = 0; + + /*--ark web()--*/ + virtual bool SendPrivateCommand(const ArkWebString& commandKey, const ArkWebString& commandValue) = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_net_connect_adapter.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_net_connect_adapter.h index 13c9ae780c0a4fe30832423ed9fe29b333347ef2..295be126f507a0ed3185e2daa1a1a68176ce6421 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/include/ark_net_connect_adapter.h +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_net_connect_adapter.h @@ -22,6 +22,26 @@ namespace OHOS::ArkWeb { +/*--ark web(source=webview)--*/ +class ArkNetCapabilitiesAdapter : public virtual ArkWebBaseRefCounted { +public: + /*--ark web()--*/ + virtual int32_t GetNetId() = 0; + + /*--ark web()--*/ + virtual uint32_t GetConnectType() = 0; + + /*--ark web()--*/ + virtual uint32_t GetConnectSubtype() = 0; +}; + +/*--ark web(source=webview)--*/ +class ArkNetConnectionPropertiesAdapter : public virtual ArkWebBaseRefCounted { +public: + /*--ark web()--*/ + virtual int32_t GetNetId() = 0; +}; + /*--ark web(source=webcore)--*/ class ArkNetConnCallback : public virtual ArkWebBaseRefCounted { public: @@ -36,6 +56,14 @@ public: /*--ark web()--*/ virtual int32_t NetUnavailable() = 0; + + /*--ark web()--*/ + virtual int32_t OnNetCapabilitiesChanged( + const ArkWebRefPtr capabilites) = 0; + + /*--ark web()--*/ + virtual int32_t OnNetConnectionPropertiesChanged( + const ArkWebRefPtr properties) = 0; }; /*--ark web(source=webview)--*/ diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_adapter_helper.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_adapter_helper.h index edd90eff7c4194937ea63848bbe2cd7a37bc144f..c88cecf56a21ce538b8704145cea0c6e21a2d416 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_adapter_helper.h +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_adapter_helper.h @@ -53,6 +53,7 @@ #include "ohos_adapter/include/ark_screen_capture_adapter.h" #include "ohos_adapter/include/ark_soc_perf_client_adapter.h" #include "ohos_adapter/include/ark_system_properties_adapter.h" +#include "ohos_adapter/include/ark_sensor_adapter.h" namespace OHOS::ArkWeb { @@ -184,6 +185,12 @@ public: /*--ark web()--*/ virtual ArkWebRefPtr CreateOhosImageDecoderAdapter() = 0; + + /*--ark web()--*/ + virtual ArkWebRefPtr CreateSensorAdapter() = 0; + + /*--ark web()--*/ + virtual void SetArkWebCoreHapPathOverride(const ArkWebString& hapPath) = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_resource_adapter.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_resource_adapter.h index 9591fed2feebf0a3c545dec94c6d15d3cb460853..302a712a38f952860645434f33a8183731e68ffe 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_resource_adapter.h +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_ohos_resource_adapter.h @@ -64,6 +64,9 @@ public: /*--ark web()--*/ virtual bool GetRawFileLastModTime(const ArkWebString& rawFile, time_t& time, bool isSys) = 0; + + /*--ark web()--*/ + virtual ArkWebString GetSystemLanguage() = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_sensor_adapter.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_sensor_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..32a83406e6dda4a79075922170e023bbe2119e90 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_sensor_adapter.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_SENSOR_ADAPTER_H +#define ARK_SENSOR_ADAPTER_H +#pragma once + +#include "base/include/ark_web_base_ref_counted.h" +#include "base/include/ark_web_types.h" + +namespace OHOS::ArkWeb { + +/*--ark web(source=webcore)--*/ +class ArkSensorCallbackAdapter : public virtual ArkWebBaseRefCounted { +public: + /*--ark web()--*/ + virtual void UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) = 0; +}; + +/*--ark web(source=webview)--*/ +class ArkSensorAdapter : public virtual ArkWebBaseRefCounted { +public: + /*--ark web()--*/ + virtual int32_t IsOhosSensorSupported(int32_t sensorTypeId) = 0; + + /*--ark web()--*/ + virtual int32_t GetOhosSensorReportingMode(int32_t type) = 0; + + /*--ark web()--*/ + virtual double GetOhosSensorDefaultSupportedFrequency(int32_t sensorTypeId) = 0; + + /*--ark web()--*/ + virtual double GetOhosSensorMinSupportedFrequency(int32_t sensorTypeId) = 0; + + /*--ark web()--*/ + virtual double GetOhosSensorMaxSupportedFrequency(int32_t sensorTypeId) = 0; + + /*--ark web()--*/ + virtual int32_t SubscribeOhosSensor(int32_t sensorTypeId, int64_t samplingInterval) = 0; + + /*--ark web()--*/ + virtual int32_t RegistOhosSensorCallback(int32_t sensorTypeId, + ArkWebRefPtr callbackAdapter) = 0; + + /*--ark web()--*/ + virtual int32_t UnsubscribeOhosSensor(int32_t sensorTypeId) = 0; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_SENSOR_ADAPTER_H diff --git a/ohos_interface/ohos_glue/ohos_adapter/include/ark_system_properties_adapter.h b/ohos_interface/ohos_glue/ohos_adapter/include/ark_system_properties_adapter.h index b95ff8e22766ec70d5585fdcac993378c984efa3..cec9e2ec80f4763ef786c07825801bee3e4bd495 100644 --- a/ohos_interface/ohos_glue/ohos_adapter/include/ark_system_properties_adapter.h +++ b/ohos_interface/ohos_glue/ohos_adapter/include/ark_system_properties_adapter.h @@ -89,6 +89,9 @@ public: /*--ark web()--*/ virtual ArkWebString GetOOPGPUStatus() = 0; + + /*--ark web()--*/ + virtual bool IsLTPODynamicApp(const ArkWebString& bundleName) = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_array_buffer_value_callback_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_array_buffer_value_callback_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28d3cc19ab05ece8b66f13d180247d7507d18994 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_array_buffer_value_callback_wrapper.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_nweb/bridge/ark_web_array_buffer_value_callback_wrapper.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { + +ArkWebArrayBufferValueCallbackWrapper::ArkWebArrayBufferValueCallbackWrapper( + ArkWebRefPtr ark_web_array_buffer_value_callback) + : ark_web_array_buffer_value_callback_(ark_web_array_buffer_value_callback) +{} + +void ArkWebArrayBufferValueCallbackWrapper::OnReceiveValue(const char* value, const long size) +{ + ark_web_array_buffer_value_callback_->OnReceiveValue(value, size); +} + +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_array_buffer_value_callback_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_array_buffer_value_callback_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..0fd28ca874701fe631bdf5f07a17e58381ac2d6e --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_array_buffer_value_callback_wrapper.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_WRAPPER_H_ +#define ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_WRAPPER_H_ +#pragma once + +#include "include/nweb_value_callback.h" +#include "ohos_nweb/include/ark_web_array_buffer_value_callback.h" + +#include "base/include/ark_web_types.h" + +namespace OHOS::ArkWeb { + +class ArkWebArrayBufferValueCallbackWrapper : public OHOS::NWeb::NWebArrayBufferValueCallback { +public: + ArkWebArrayBufferValueCallbackWrapper( + ArkWebRefPtr ark_web_array_buffer_value_callback); + ~ArkWebArrayBufferValueCallbackWrapper() = default; + + void OnReceiveValue(const char* value, const long size) override; + +private: + ArkWebRefPtr ark_web_array_buffer_value_callback_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_WRAPPER_H_ diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.cpp index 5b55bcb92b88ad7a56e96c816e64cc5747936763..ecc4dba418eda08f8581faeb73c8c78d180c5763 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.cpp @@ -212,4 +212,9 @@ ArkWebRefPtr ArkWebEngineImpl::GetAdsBlockManager() } return new ArkWebAdsBlockManagerImpl(nweb_adsBlock_manager); } + +void ArkWebEngineImpl::TrimMemoryByPressureLevel(int32_t memoryLevel) +{ + nweb_engine_->TrimMemoryByPressureLevel(memoryLevel); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.h index 28236ab74b6127835de0a4da22f33028b398a124..b883c699477e9f29700872cae82a6745e87f10bc 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_engine_impl.h @@ -79,6 +79,8 @@ public: ArkWebRefPtr GetAdsBlockManager() override; + void TrimMemoryByPressureLevel(int32_t memoryLevel) override; + private: std::shared_ptr nweb_engine_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.cpp index 6e6c298ae4d16ae4fb4f9f35be78261de097aa86..6f861e3c1a551cf21484281cd2654e0666eb2b8f 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.cpp @@ -977,4 +977,43 @@ void ArkWebHandlerWrapper::OnAdsBlocked( ArkWebStringVectorStructRelease(stAdsBlocked); ArkWebStringStructRelease(stUrl); } + +void ArkWebHandlerWrapper::OnCursorUpdate(double x, double y, double width, double height) +{ + ark_web_handler_->OnCursorUpdate(x, y, width, height); +} + +void ArkWebHandlerWrapper::ReportDynamicFrameLossEvent(const std::string& sceneId, bool isStart) +{ + ArkWebString stSceneId = ArkWebStringClassToStruct(sceneId); + ark_web_handler_->ReportDynamicFrameLossEvent(stSceneId, isStart); + ArkWebStringStructRelease(stSceneId); +} + +void ArkWebHandlerWrapper::HideHandleAndQuickMenuIfNecessary(bool hide) +{ + ark_web_handler_->HideHandleAndQuickMenuIfNecessary(hide); +} + +void ArkWebHandlerWrapper::ChangeVisibilityOfQuickMenu() +{ + ark_web_handler_->ChangeVisibilityOfQuickMenu(); +} + +void ArkWebHandlerWrapper::StartVibraFeedback(const std::string& vibratorType) +{ + ArkWebString stVibratorType = ArkWebStringClassToStruct(vibratorType); + + ark_web_handler_->StartVibraFeedback(stVibratorType); + + ArkWebStringStructRelease(stVibratorType); +} + +void ArkWebHandlerWrapper::OnPopupSize(int x, int y, int width, int height) { + ark_web_handler_->OnPopupSize(x, y, width, height); +} + +void ArkWebHandlerWrapper::OnPopupShow(bool show) { + ark_web_handler_->OnPopupShow(show); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.h index 7e5ad0c6a21322a085c08c5f62614dd35eadc26a..1525e21cf9de64f4dfa6a61eabdc874f173b4249 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_handler_wrapper.h @@ -594,6 +594,21 @@ public: void OnCustomKeyboardClose() override; void OnAdsBlocked(const std::string &url, const std::vector &adsBlocked) override; + + void OnCursorUpdate(double x, double y, double width, double height) override; + + void ReportDynamicFrameLossEvent(const std::string& sceneId, bool isStart) override; + + void HideHandleAndQuickMenuIfNecessary(bool hide) override; + + void ChangeVisibilityOfQuickMenu() override; + + void StartVibraFeedback(const std::string& vibratorType) override; + + void OnPopupSize(int x, int y, int width, int height) override; + + void OnPopupShow(bool show) override; + private: ArkWebRefPtr ark_web_handler_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.cpp index 6276b5fd99deedbabd2f0df4f5fc48adc549affa..44a9c88f47e5037e438ca5cf3ae0f906b89b2e0d 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.cpp @@ -17,6 +17,8 @@ #include "ohos_nweb/bridge/ark_web_accessibility_event_callback_wrapper.h" #include "ohos_nweb/bridge/ark_web_accessibility_node_info_impl.h" +#include "ohos_nweb/bridge/ark_web_array_buffer_value_callback_wrapper.h" +#include "ohos_nweb/bridge/ark_web_pdfconfig_args_wrapper.h" #include "ohos_nweb/bridge/ark_web_bool_value_callback_wrapper.h" #include "ohos_nweb/bridge/ark_web_cache_options_wrapper.h" #include "ohos_nweb/bridge/ark_web_core_struct_utils.h" @@ -1095,7 +1097,6 @@ void ArkWebNWebImpl::WebSendTouchpadFlingEvent(double x, ArkWebBasicVectorStructToClass(pressedCodes)); } - void ArkWebNWebImpl::SendAccessibilityHoverEvent(int32_t x, int32_t y) { nweb_nweb_->SendAccessibilityHoverEvent(x, y); @@ -1108,4 +1109,69 @@ void ArkWebNWebImpl::RegisterArkJSfunction(const ArkWebString& object_name, cons ArkWebStringVectorStructToClass(method_list), ArkWebStringVectorStructToClass(async_method_list), object_id, ArkWebStringStructToClass(permission)); } + +void ArkWebNWebImpl::ResizeVisibleViewport(uint32_t width, uint32_t height, bool isKeyboard) +{ + nweb_nweb_->ResizeVisibleViewport(width, height, isKeyboard); +} + +void ArkWebNWebImpl::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) +{ + nweb_nweb_->SetBackForwardCacheOptions(size, timeToLive); +} + +void ArkWebNWebImpl::SetAutofillCallback(ArkWebRefPtr callback) +{ + if (CHECK_REF_PTR_IS_NULL(callback)) { + nweb_nweb_->SetAutofillCallback(nullptr); + return; + } + + nweb_nweb_->SetAutofillCallback(std::make_shared(callback)); +} + +void ArkWebNWebImpl::FillAutofillData(const ArkWebMessage& data) +{ + nweb_nweb_->FillAutofillData(data.nweb_message); +} + +void ArkWebNWebImpl::OnAutofillCancel(const ArkWebString& fillContent) +{ + nweb_nweb_->OnAutofillCancel(ArkWebStringStructToClass(fillContent)); +} + +void ArkWebNWebImpl::GetScrollOffset(float* offset_x, float* offset_y) +{ + nweb_nweb_->GetScrollOffset(offset_x, offset_y); +} + +void ArkWebNWebImpl::ExecuteCreatePDFExt( + ArkWebRefPtr pdfConfig, ArkWebRefPtr callback) +{ + if (CHECK_REF_PTR_IS_NULL(callback)) { + nweb_nweb_->ExecuteCreatePDFExt( + std::make_shared(CHECK_REF_PTR_IS_NULL(pdfConfig) ? nullptr : pdfConfig), + nullptr); + return; + } + + nweb_nweb_->ExecuteCreatePDFExt( + std::make_shared(CHECK_REF_PTR_IS_NULL(pdfConfig) ? nullptr : pdfConfig), + std::make_shared(callback)); +} + +bool ArkWebNWebImpl::ScrollByWithResult(float delta_x, float delta_y) +{ + return nweb_nweb_->ScrollByWithResult(delta_x, delta_y); +} + +void ArkWebNWebImpl::SetPopupSurface(void* popupSurface) +{ + nweb_nweb_->SetPopupSurface(popupSurface); +} + +void ArkWebNWebImpl::OnDestroyImageAnalyzerOverlay() +{ + nweb_nweb_->OnDestroyImageAnalyzerOverlay(); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.h index db22e8e3f9594d608beb7f92ac0c1748d8b9e1dd..e381879062017fe2290e5e49c1672fafc81bea3e 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_nweb_impl.h @@ -1237,6 +1237,7 @@ public: double vx, double vy, const ArkWebInt32Vector& pressedCodes) override; + /** * @brief Set url trust list with error message. * @@ -1266,6 +1267,86 @@ public: */ void RegisterArkJSfunction(const ArkWebString& object_name, const ArkWebStringVector& method_list, const ArkWebStringVector& async_method_list, const int32_t object_id, const ArkWebString& permission) override; + + /** + * @brief resize visual viewport. + * + * @param width width. + * @param height height. + * @param iskeyboard from keybord. + */ + /*--ark web()--*/ + void ResizeVisibleViewport(uint32_t width, uint32_t height, bool isKeyboard) override; + + /** + * @brief set backforward cache options. + * @param size The size of the back forward cache could saved. + * @param timeToLive The time of the back forward cache page could stay. + */ + /*--ark web()--*/ + void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) override; + + /** + * @brief set the callback of the autofill event. + * @param callback callback. + */ + /*--ark web()--*/ + void SetAutofillCallback(ArkWebRefPtr callback) override; + + /** + * @brief fill autofill data. + * @param data data. + */ + /*--ark web()--*/ + void FillAutofillData(const ArkWebMessage& data) override; + + /** + * @brief on autofill cancel. + * @param fillContent fillContent + */ + /*--ark web()--*/ + void OnAutofillCancel(const ArkWebString& fillContent) override; + + /** + * @brief Get the current scroll offset of the webpage. + * @param offset_x The current horizontal scroll offset of the webpage. + * @param offset_y The current vertical scroll offset of the webpage. + */ + /*--ark web()--*/ + void GetScrollOffset(float* offset_x, float* offset_y) override; + + /** + * @brief ExecuteCreatePDF + * + * @param pdfConfig The current configuration when creating pdf. + * @param callback NWebArrayBufferValueCallback: CreatePDF running result. + */ + /*--ark web()--*/ + void ExecuteCreatePDFExt( + ArkWebRefPtr pdfConfig, ArkWebRefPtr callback) override; + + /** + * Scroll by the delta distance if web is not foucsed. + * + * @param delta_x horizontal offset. + * @param delta_y vertical offset. + * @return false if web is focused. + */ + /*--ark web()--*/ + bool ScrollByWithResult(float delta_x, float delta_y) override; + + /** + * @brief set a popupSurface to draw popup content + * @param popupSurface popupSurface. + */ + /*--ark web()--*/ + void SetPopupSurface(void* popupSurface) override; + + /** + * @brief Called when image analyzer is destory. + */ + /*--ark web()--*/ + void OnDestroyImageAnalyzerOverlay() override; private: std::shared_ptr nweb_nweb_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_pdfconfig_args_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_pdfconfig_args_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82367e3d1e9ef605eb37665042ed8ab79e72cf23 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_pdfconfig_args_wrapper.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or wrapperied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_nweb/bridge/ark_web_pdfconfig_args_wrapper.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { + +ArkWebPDFConfigArgsWrapper::ArkWebPDFConfigArgsWrapper( + ArkWebRefPtr ark_web_pdfconfig_args) + : ark_web_pdfconfig_args_(ark_web_pdfconfig_args) +{} + + +double ArkWebPDFConfigArgsWrapper::GetWidth() +{ + return ark_web_pdfconfig_args_->GetWidth(); +} +double ArkWebPDFConfigArgsWrapper::GetHeight() +{ + return ark_web_pdfconfig_args_->GetHeight(); +} +double ArkWebPDFConfigArgsWrapper::GetScale() +{ + return ark_web_pdfconfig_args_->GetScale(); +} +double ArkWebPDFConfigArgsWrapper::GetMarginTop() +{ + return ark_web_pdfconfig_args_->GetMarginTop(); +} +double ArkWebPDFConfigArgsWrapper::GetMarginBottom() +{ + return ark_web_pdfconfig_args_->GetMarginBottom(); +} +double ArkWebPDFConfigArgsWrapper::GetMarginRight() +{ + return ark_web_pdfconfig_args_->GetMarginRight(); +} +double ArkWebPDFConfigArgsWrapper::GetMarginLeft() +{ + return ark_web_pdfconfig_args_->GetMarginLeft(); +} +bool ArkWebPDFConfigArgsWrapper::GetShouldPrintBackground() +{ + return ark_web_pdfconfig_args_->GetShouldPrintBackground(); +} + +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_pdfconfig_args_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_pdfconfig_args_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..5e5c328beef98b74fab834260b6772b3e9130e97 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_pdfconfig_args_wrapper.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or wrapperied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_WEB_PDFCONFIG_ARGS_WRAPPER_H_ +#define ARK_WEB_PDFCONFIG_ARGS_WRAPPER_H_ +#pragma once + +#include "include/nweb.h" +#include "ohos_nweb/include/ark_web_pdfconfig_args.h" + +#include "base/include/ark_web_types.h" + +namespace OHOS::ArkWeb { + +class ArkWebPDFConfigArgsWrapper : public OHOS::NWeb::NWebPDFConfigArgs { +public: + ArkWebPDFConfigArgsWrapper(ArkWebRefPtr ark_web_pdfconfig_args); + ~ArkWebPDFConfigArgsWrapper() = default; + + double GetWidth() override; + double GetHeight() override; + double GetScale() override; + double GetMarginTop() override; + double GetMarginBottom() override; + double GetMarginRight() override; + double GetMarginLeft() override; + bool GetShouldPrintBackground() override; +private: + ArkWebRefPtr ark_web_pdfconfig_args_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_WEB_PDFCONFIG_ARGS_WRAPPER_H_ diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.cpp index 4acceb9a2e00fed50a856d389f75e0529390781a..c41091c9fcc1f78824b4018ea1e57ed34eb43ca7 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.cpp @@ -491,4 +491,9 @@ void ArkWebPreferenceImpl::SetSurfaceId(const ArkWebString& ua) nweb_preference_->SetSurfaceId(ArkWebStringStructToClass(ua)); } +void ArkWebPreferenceImpl::SetScrollable(bool enable, int32_t scrollType) +{ + nweb_preference_->SetScrollable(enable, scrollType); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.h index 11713e477d35ffd25c6e115cedd4911794fd7b44..506360c1b0e6cc823e8bceaaa34c6ff292d8fdbd 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webcore/ark_web_preference_impl.h @@ -652,6 +652,11 @@ public: */ void PutOverlayScrollbarEnabled(bool enable) override; + /** + * @brief Set whether the scroll is enabled. + */ + void SetScrollable(bool enable, int32_t scrollType) override; + private: std::shared_ptr nweb_preference_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_array_buffer_value_callback_impl.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_array_buffer_value_callback_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ab345060d1538daf5fc3a468ed8b4ada4a50a2e --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_array_buffer_value_callback_impl.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_nweb/bridge/ark_web_array_buffer_value_callback_impl.h" + +#include "base/bridge/ark_web_bridge_macros.h" + +namespace OHOS::ArkWeb { + +ArkWebArrayBufferValueCallbackImpl::ArkWebArrayBufferValueCallbackImpl( + std::shared_ptr nweb_array_buffer_value_callback) + : nweb_array_buffer_value_callback_(nweb_array_buffer_value_callback) +{} + +void ArkWebArrayBufferValueCallbackImpl::OnReceiveValue(const char* value, const long size) +{ + nweb_array_buffer_value_callback_->OnReceiveValue(value, size); +} + +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_array_buffer_value_callback_impl.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_array_buffer_value_callback_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..cbca563937ef9ca222fd45cc3a876d20dca2f584 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_array_buffer_value_callback_impl.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_IMPL_H_ +#define ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_IMPL_H_ +#pragma once + +#include "include/nweb_value_callback.h" +#include "ohos_nweb/include/ark_web_array_buffer_value_callback.h" + +namespace OHOS::ArkWeb { + +class ArkWebArrayBufferValueCallbackImpl : public ArkWebArrayBufferValueCallback { + IMPLEMENT_REFCOUNTING(ArkWebArrayBufferValueCallbackImpl); + +public: + ArkWebArrayBufferValueCallbackImpl( + std::shared_ptr nweb_array_buffer_value_callback); + ~ArkWebArrayBufferValueCallbackImpl() = default; + + void OnReceiveValue(const char* value, const long size) override; + +private: + std::shared_ptr nweb_array_buffer_value_callback_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_IMPL_H_ diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.cpp index efafe6b2909b28cc91120025f80a3edfea9d543a..c0043abe73568b1642f24e0e168bda09478acf52 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.cpp @@ -178,4 +178,16 @@ void ArkWebCookieManagerWrapper::PutAcceptFileURLSchemeCookiesEnabled(bool allow ark_web_cookie_manager_->PutAcceptFileURLSchemeCookiesEnabled(allow); } +std::string ArkWebCookieManagerWrapper::ReturnCookieWithHttpOnly( + const std::string& url, bool& is_valid, bool incognito_mode, bool includeHttpOnly) +{ + return ""; +} + +int ArkWebCookieManagerWrapper::SetCookieWithHttpOnly( + const std::string& url, const std::string& value, bool incognito_mode, bool includeHttpOnly) +{ + return 0; +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.h index 59b2dca8b31738146f14231b5ff36c3704bfff18..631bf7678442e155ac37557a717e6924e7e64a88 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_cookie_manager_wrapper.h @@ -183,6 +183,32 @@ public: */ void PutAcceptFileURLSchemeCookiesEnabled(bool allow) override; + /** + * @brief Gets all the cookies for the given URL. This is sync method + * + * @param url URL to which the cookie to be obtained belongs. A complete URL is recommended. + * @param incognito True indicates that the memory cookies of the webview in privacy mode are obtained, + * and false indicates that cookies in non-privacy mode are obtained. + * @param includeHttpOnly If true HTTP-only cookies will also be included in the cookieValue. + * @param cookieValue Get the cookie value corresponding to the URL. + * @return the cookie value for given URL. + */ + std::string ReturnCookieWithHttpOnly( + const std::string& url, bool& is_valid, bool incognito_mode, bool includeHttpOnly) override; + + /** + * @brief Sets a single cookie (key-value pair) for the given URL sync. + * + * @param url Specifies the URL to which the cookie belongs. A complete URL is recommended. + * @param cookieValue The value of the cookie to be set. + * @param incognito True indicates that cookies of the corresponding URL are set in privacy mode, + * and false indicates that cookies of the corresponding URL are set in non-privacy mode. + * @param includeHttpOnly If true, HTTP-only cookies can also be overwritten. + * @return 0 if set cookie success else return error id. + */ + int SetCookieWithHttpOnly( + const std::string& url, const std::string& value, bool incognito_mode, bool includeHttpOnly) override; + private: ArkWebRefPtr ark_web_cookie_manager_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.cpp index c08317fa5aa6bcbbe18306488e88909625b0be68..5c26e07551ae573ccf60a4ed89c7e3856987772e 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.cpp @@ -240,4 +240,9 @@ ArkWebEngineWrapper::GetAdsBlockManager() { return std::make_shared(ark_web_adsblock_manager); } + +void ArkWebEngineWrapper::TrimMemoryByPressureLevel(int32_t memoryLevel) +{ + ark_web_engine_->TrimMemoryByPressureLevel(memoryLevel); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.h index 6400bfcdd2f3ef7da0bf0937f10f8d25ae846066..ec6ea672a5a63dccb6ff51ceeba87ceceeceecd0 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_engine_wrapper.h @@ -76,6 +76,8 @@ public: void EnableWholeWebPageDrawing() override; std::shared_ptr GetAdsBlockManager() override; + + void TrimMemoryByPressureLevel(int32_t memoryLevel) override; private: ArkWebRefPtr ark_web_engine_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.cpp index 580d80a55db3104076aff953a015346ab4c0ee19..865b2c90219f0e581d8adf3a4cf8275cc63c5c66 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.cpp @@ -696,7 +696,7 @@ void ArkWebHandlerImpl::OnSafeBrowsingCheckResult(int threat_type) void ArkWebHandlerImpl::OnFirstMeaningfulPaint(ArkWebRefPtr details) { if (CHECK_REF_PTR_IS_NULL(details)) { - ARK_WEB_IMPL_WRAN_LOG("firstMeaningfulPaint details is null"); + ARK_WEB_IMPL_WARN_LOG("firstMeaningfulPaint details is null"); return; } @@ -706,7 +706,7 @@ void ArkWebHandlerImpl::OnFirstMeaningfulPaint(ArkWebRefPtr details) { if (CHECK_REF_PTR_IS_NULL(details)) { - ARK_WEB_IMPL_WRAN_LOG("largestContentfulPaint details is null"); + ARK_WEB_IMPL_WARN_LOG("largestContentfulPaint details is null"); return; } @@ -867,4 +867,39 @@ void ArkWebHandlerImpl::OnAdsBlocked(const ArkWebString &url, const ArkWebString nweb_handler_->OnAdsBlocked(ArkWebStringStructToClass(url), ArkWebStringVectorStructToClass(adsBlocked)); } + +void ArkWebHandlerImpl::OnCursorUpdate(double x, double y, double width, double height) +{ + nweb_handler_->OnCursorUpdate(x, y, width, height); +} + +void ArkWebHandlerImpl::ReportDynamicFrameLossEvent(const ArkWebString& sceneId, bool isStart) +{ + nweb_handler_->ReportDynamicFrameLossEvent(ArkWebStringStructToClass(sceneId), isStart); +} + +void ArkWebHandlerImpl::HideHandleAndQuickMenuIfNecessary(bool hide) +{ + nweb_handler_->HideHandleAndQuickMenuIfNecessary(hide); +} + +void ArkWebHandlerImpl::ChangeVisibilityOfQuickMenu() +{ + nweb_handler_->ChangeVisibilityOfQuickMenu(); +} + +void ArkWebHandlerImpl::StartVibraFeedback(const ArkWebString& vibratorType) +{ + nweb_handler_->StartVibraFeedback(ArkWebStringStructToClass(vibratorType)); +} + +void ArkWebHandlerImpl::OnPopupSize(int x, int y, int width, int height) +{ + nweb_handler_->OnPopupSize(x, y, width, height); +} + +void ArkWebHandlerImpl::OnPopupShow(bool show) +{ + nweb_handler_->OnPopupShow(show); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.h index c9a0edae044334886b103685e042d128e9d9f9d5..9c6f381eb279c09227cb5868094a19fbb5368df9 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_handler_impl.h @@ -557,6 +557,21 @@ public: void OnCustomKeyboardClose() override; void OnAdsBlocked(const ArkWebString &url, const ArkWebStringVector &adsBlocked) override; + + void OnCursorUpdate(double x, double y, double width, double height) override; + + void ReportDynamicFrameLossEvent(const ArkWebString& sceneId, bool isStart) override; + + void HideHandleAndQuickMenuIfNecessary(bool hide) override; + + void ChangeVisibilityOfQuickMenu() override; + + void StartVibraFeedback(const ArkWebString& vibratorType) override; + + void OnPopupSize(int x, int y, int width, int height) override; + + void OnPopupShow(bool show) override; + private: std::shared_ptr nweb_handler_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.cpp index 5424a2a86ac3be2ecab73c315e83f9036868b84f..751248e2e7b38c0408dc5b87e069091d5db7c725 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.cpp @@ -38,6 +38,22 @@ ArkWebNWebBridgeHelper& ArkWebNWebBridgeHelper::GetInstance() return helper; } +bool ArkWebNWebBridgeHelper::InitArkWeb( + bool runMode, const std::string& baseDir, + const std::string& relativeLibPath, const std::string& arkWebEngineSo) +{ + std::string libDirPath = baseDir + "/" + RELATIVE_PATH_FOR_MOCK; + if (runMode) { + libDirPath = baseDir + "/" + relativeLibPath; + } +#ifdef __MUSL__ + return LoadLibFile(RTLD_NOW | RTLD_GLOBAL, "nweb_ns", libDirPath, arkWebEngineSo); +#else + std::string libFilePath = libDirPath + "/" + arkWebEngineSo; + return LoadLibFile(RTLD_NOW, libFilePath); +#endif +} + bool ArkWebNWebBridgeHelper::Init(bool runMode, const std::string& baseDir) { #ifdef __MUSL__ diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.h index b1c5ab9194fbf16a48d592836143fbee21ec6188..02fe035da2383da67751a74f91c9222bc02ac894 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_bridge_helper.h @@ -27,6 +27,8 @@ public: static ArkWebNWebBridgeHelper& GetInstance(); + bool InitArkWeb(bool runMode, const std::string& baseDir, + const std::string& relativeLibPath, const std::string& arkWebEngineSo); bool Init(bool runMode, const std::string& baseDir); private: diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.cpp index db4de86e522ad3c3c0643a68ec6b0d5ee3f234d3..ec8dfd9e2bb942c57fb780fb98a59c1c691ed7b9 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.cpp @@ -17,6 +17,7 @@ #include "ohos_nweb/bridge/ark_web_accessibility_event_callback_impl.h" #include "ohos_nweb/bridge/ark_web_accessibility_node_info_wrapper.h" +#include "ohos_nweb/bridge/ark_web_array_buffer_value_callback_impl.h" #include "ohos_nweb/bridge/ark_web_bool_value_callback_impl.h" #include "ohos_nweb/bridge/ark_web_cache_options_impl.h" #include "ohos_nweb/bridge/ark_web_create_native_media_player_callback_impl.h" @@ -29,6 +30,7 @@ #include "ohos_nweb/bridge/ark_web_hit_test_result_wrapper.h" #include "ohos_nweb/bridge/ark_web_js_result_callback_impl.h" #include "ohos_nweb/bridge/ark_web_message_value_callback_impl.h" +#include "ohos_nweb/bridge/ark_web_pdfconfig_args_impl.h" #include "ohos_nweb/bridge/ark_web_preference_wrapper.h" #include "ohos_nweb/bridge/ark_web_release_surface_callback_impl.h" #include "ohos_nweb/bridge/ark_web_screen_lock_callback_impl.h" @@ -1304,4 +1306,72 @@ void ArkWebNWebWrapper::RegisterArkJSfunction(const std::string& object_name, ArkWebStringVectorStructRelease(stAsyncMethods); ArkWebStringStructRelease(stPermission); } + +void ArkWebNWebWrapper::ResizeVisibleViewport(uint32_t width, uint32_t height, bool isKeyboard) +{ + ark_web_nweb_->ResizeVisibleViewport(width, height, isKeyboard); +} + +void ArkWebNWebWrapper::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) +{ + ark_web_nweb_->SetBackForwardCacheOptions(size, timeToLive); +} + +void ArkWebNWebWrapper::SetAutofillCallback(std::shared_ptr callback) +{ + if (CHECK_SHARED_PTR_IS_NULL(callback)) { + ark_web_nweb_->SetAutofillCallback(nullptr); + } else { + ark_web_nweb_->SetAutofillCallback(new ArkWebMessageValueCallbackImpl(callback)); + } +} + +void ArkWebNWebWrapper::FillAutofillData(std::shared_ptr data) +{ + ArkWebMessage ark_web_message; + ark_web_message.nweb_message = data; + ark_web_nweb_->FillAutofillData(ark_web_message); +} + +void ArkWebNWebWrapper::OnAutofillCancel(const std::string& fillContent) +{ + ArkWebString stFillContent = ArkWebStringClassToStruct(fillContent); + + ark_web_nweb_->OnAutofillCancel(stFillContent); + + ArkWebStringStructRelease(stFillContent); +} + +void ArkWebNWebWrapper::GetScrollOffset(float* offset_x, float* offset_y) +{ + ark_web_nweb_->GetScrollOffset(offset_x, offset_y); +} + +void ArkWebNWebWrapper::ExecuteCreatePDFExt(std::shared_ptr pdfConfig, + std::shared_ptr callback) +{ + if (CHECK_SHARED_PTR_IS_NULL(callback)) { + ark_web_nweb_->ExecuteCreatePDFExt( + new ArkWebPDFConfigArgsImpl(CHECK_SHARED_PTR_IS_NULL(pdfConfig) ? nullptr : pdfConfig), nullptr); + } else { + ark_web_nweb_->ExecuteCreatePDFExt( + new ArkWebPDFConfigArgsImpl(CHECK_SHARED_PTR_IS_NULL(pdfConfig) ? nullptr : pdfConfig), + new ArkWebArrayBufferValueCallbackImpl(callback)); + } +} + +bool ArkWebNWebWrapper::ScrollByWithResult(float delta_x, float delta_y) +{ + return ark_web_nweb_->ScrollByWithResult(delta_x, delta_y); +} + +void ArkWebNWebWrapper::SetPopupSurface(void* popupSurface) +{ + ark_web_nweb_->SetPopupSurface(popupSurface); +} + +void ArkWebNWebWrapper::OnDestroyImageAnalyzerOverlay() +{ + ark_web_nweb_->OnDestroyImageAnalyzerOverlay(); +} } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.h index 454294bb022a311a569bfd55c99cf0d30087b309..4c7de452fa96978150995c32e0b85d251d378009 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_nweb_wrapper.h @@ -1245,6 +1245,7 @@ public: double vx, double vy, const std::vector& pressedCodes) override; + /** * @brief Set url trust list with error message. */ @@ -1275,6 +1276,85 @@ public: const std::vector& async_method_list, const int32_t object_id, const std::string& permission) override; + + /** + * @brief resize visual viewport. + * + * @param width width. + * @param height height. + * @param iskeyboard from keybord. + */ + /*--ark web()--*/ + void ResizeVisibleViewport(uint32_t width, uint32_t height, bool isKeyboard) override; + + /** + * @brief set backforward cache options. + * @param size The size of the back forward cache could saved. + * @param timeToLive The time of the back forward cache page could stay. + */ + /*--ark web()--*/ + void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) override; + + /** + * @brief set the callback of the autofill event. + * @param callback callback. + */ + /*--ark web()--*/ + void SetAutofillCallback(std::shared_ptr callback) override; + + /** + * @brief fill autofill data. + * @param data data. + */ + /*--ark web()--*/ + void FillAutofillData(std::shared_ptr data) override; + + /** + * @brief on autofill cancel. + * @param fillContent fillContent. + */ + /*--ark web()--*/ + void OnAutofillCancel(const std::string& fillContent) override; + + /** + * @brief Get the current scroll offset of the webpage. + * @param offset_x The current horizontal scroll offset of the webpage. + * @param offset_y The current vertical scroll offset of the webpage. + */ + /*--ark web()--*/ + void GetScrollOffset(float* offset_x, float* offset_y) override; + + /** + * @brief ExecuteCreatePDF + * + * @param pdfConfig The current configuration when creating pdf. + * @param callback NWebArrayBufferValueCallback: CreatePDF running result. + */ + /*--ark web()--*/ + void ExecuteCreatePDFExt(std::shared_ptr pdfConfig, + std::shared_ptr callback) override; + + /** + * @brief Scroll by the delta distance. + * @param delta_x: horizontal offset. + * @param delta_y: vertical offset. + * @return false if web don't scroll by the delta, when web is focused. + */ + /*--ark web()--*/ + bool ScrollByWithResult(float delta_x, float delta_y) override; + + /** + * @brief set a popupSurface to draw popup content + * @param popupSurface popupSurface. + */ + /*--ark web()--*/ + void SetPopupSurface(void* popupSurface) override; + + /** + * @brief Called when image analyzer is destory. + */ + /*--ark web()--*/ + void OnDestroyImageAnalyzerOverlay() override; private: ArkWebRefPtr ark_web_nweb_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_pdfconfig_args_impl.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_pdfconfig_args_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d4e469a52325fe37c2a66e27edeaeb58678b35a --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_pdfconfig_args_impl.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_nweb/bridge/ark_web_pdfconfig_args_impl.h" + +namespace OHOS::ArkWeb { + +ArkWebPDFConfigArgsImpl::ArkWebPDFConfigArgsImpl(std::shared_ptr pdfConfig) + : nweb_pdfconfig_(pdfConfig) +{} + +double ArkWebPDFConfigArgsImpl::GetWidth() +{ + return nweb_pdfconfig_->GetWidth(); +} +double ArkWebPDFConfigArgsImpl::GetHeight() +{ + return nweb_pdfconfig_->GetHeight(); +} +double ArkWebPDFConfigArgsImpl::GetScale() +{ + return nweb_pdfconfig_->GetScale(); +} +double ArkWebPDFConfigArgsImpl::GetMarginTop() +{ + return nweb_pdfconfig_->GetMarginTop(); +} +double ArkWebPDFConfigArgsImpl::GetMarginBottom() +{ + return nweb_pdfconfig_->GetMarginBottom(); +} +double ArkWebPDFConfigArgsImpl::GetMarginRight() +{ + return nweb_pdfconfig_->GetMarginRight(); +} +double ArkWebPDFConfigArgsImpl::GetMarginLeft() +{ + return nweb_pdfconfig_->GetMarginLeft(); +} +bool ArkWebPDFConfigArgsImpl::GetShouldPrintBackground() +{ + return nweb_pdfconfig_->GetShouldPrintBackground(); +} + +} // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_pdfconfig_args_impl.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_pdfconfig_args_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..bfdb969c370919d1d1ce3c6608bf9ea448a6a53c --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_pdfconfig_args_impl.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_WEB_PDFCONFIG_ARGS_IMPL_H_ +#define ARK_WEB_PDFCONFIG_ARGS_IMPL_H_ +#pragma once + +#include "include/nweb.h" +#include "ohos_nweb/include/ark_web_pdfconfig_args.h" + +namespace OHOS::ArkWeb { + +class ArkWebPDFConfigArgsImpl : public ArkWebPDFConfigArgs { + IMPLEMENT_REFCOUNTING(ArkWebPDFConfigArgsImpl); + +public: + ArkWebPDFConfigArgsImpl(std::shared_ptr pdfConfig); + ~ArkWebPDFConfigArgsImpl() = default; + + double GetWidth() override; + double GetHeight() override; + double GetScale() override; + double GetMarginTop() override; + double GetMarginBottom() override; + double GetMarginRight() override; + double GetMarginLeft() override; + bool GetShouldPrintBackground() override; + +private: + std::shared_ptr nweb_pdfconfig_; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_WEB_PDFCONFIG_ARGS_IMPL_H_ diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.cpp b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.cpp index 165f0c33f653af7e98023580a105472fc1b641f6..c5092db1268f6926b4679d30afb983111be05eb0 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.cpp @@ -562,4 +562,9 @@ void ArkWebPreferenceWrapper::SetSurfaceId(const std::string& surfaceId) ArkWebStringStructRelease(stSurfaceId); } +void ArkWebPreferenceWrapper::SetScrollable(bool enable, int32_t scrollType) +{ + ark_web_preference_->SetScrollable(enable, scrollType); +} + } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.h b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.h index dbc604368b51ec9ca951e58e43be9b70d4a426bc..021a9d80c319e0ca91ab93912a35896b99724b3e 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.h +++ b/ohos_interface/ohos_glue/ohos_nweb/bridge/webview/ark_web_preference_wrapper.h @@ -649,6 +649,11 @@ public: */ void PutOverlayScrollbarEnabled(bool enable) override; + /** + * @brief Set whether the scroll is enabled. + */ + void SetScrollable(bool enable, int32_t scrollType) override; + private: ArkWebRefPtr ark_web_preference_; }; diff --git a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_date_time_suggestion_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_date_time_suggestion_vector_cpptoc.cpp index 1ad98c6521ee582d3eae73054987ea6d946266b9..54e73e7bfa1586815ff8610d18cf72d954142396 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_date_time_suggestion_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_date_time_suggestion_vector_cpptoc.cpp @@ -28,6 +28,10 @@ ArkWebDateTimeSuggestionVector ArkWebDateTimeSuggestionVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (ark_web_date_time_suggestion_t**)ArkWebMemMalloc( sizeof(ark_web_date_time_suggestion_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { diff --git a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_media_source_info_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_media_source_info_vector_cpptoc.cpp index 7c3349b081fc9611ebdbb7eae4612f5745197306..c4c7276fe346349662f341ce4dd75c1577dceae0 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_media_source_info_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_media_source_info_vector_cpptoc.cpp @@ -27,6 +27,10 @@ ArkWebMediaSourceInfoVector ArkWebMediaSourceInfoVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (ark_web_media_source_info_t**)ArkWebMemMalloc(sizeof(ark_web_media_source_info_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { diff --git a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_select_popup_menu_item_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_select_popup_menu_item_vector_cpptoc.cpp index 1bcd766e3d543e9a97c0b2422878459e024fa279..2a51fd93f296c3fa4f4a7a53bc2af37da9fd622d 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_select_popup_menu_item_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_select_popup_menu_item_vector_cpptoc.cpp @@ -28,6 +28,10 @@ ArkWebSelectPopupMenuItemVector ArkWebSelectPopupMenuItemVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (ark_web_select_popup_menu_item_t**)ArkWebMemMalloc( sizeof(ark_web_select_popup_menu_item_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { diff --git a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_web_storage_origin_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_web_storage_origin_vector_cpptoc.cpp index aff388d0c6cfadb1d399474c900658973475cbed..a8d6d77ffa00bcecfc85e929aea1b753148dc186 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_web_storage_origin_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webcore/ark_web_web_storage_origin_vector_cpptoc.cpp @@ -27,6 +27,10 @@ ArkWebWebStorageOriginVector ArkWebWebStorageOriginVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (ark_web_web_storage_origin_t**)ArkWebMemMalloc(sizeof(ark_web_web_storage_origin_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { diff --git a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_js_proxy_callback_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_js_proxy_callback_vector_cpptoc.cpp index 984d59c826df153a2d8175f31a9c5062563abe83..c6ca440be6afb410877ef814af33ea63b946ea4c 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_js_proxy_callback_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_js_proxy_callback_vector_cpptoc.cpp @@ -27,6 +27,10 @@ ArkWebJsProxyCallbackVector ArkWebJsProxyCallbackVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (ark_web_js_proxy_callback_t**)ArkWebMemMalloc(sizeof(ark_web_js_proxy_callback_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { diff --git a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_touch_point_info_vector_cpptoc.cpp b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_touch_point_info_vector_cpptoc.cpp index 13a82b0990706702ac3fe371e173bd2bc6e1a586..a4447f18acd6b9a73277796a9551f12d43ef494e 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_touch_point_info_vector_cpptoc.cpp +++ b/ohos_interface/ohos_glue/ohos_nweb/cpptoc/webview/ark_web_touch_point_info_vector_cpptoc.cpp @@ -27,6 +27,10 @@ ArkWebTouchPointInfoVector ArkWebTouchPointInfoVectorClassToStruct( if (struct_value.size > 0) { struct_value.value = (ark_web_touch_point_info_t**)ArkWebMemMalloc(sizeof(ark_web_touch_point_info_t*) * struct_value.size); + if (struct_value.value == nullptr) { + struct_value.size = 0; + return struct_value; + } int count = 0; for (auto it = class_value.begin(); it != class_value.end(); it++) { diff --git a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_array_buffer_value_callback.h b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_array_buffer_value_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..d172aaaafb46ed89773b05cd7b588fd26d195af4 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_array_buffer_value_callback.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_H_ +#define ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_H_ +#pragma once + +#include "base/include/ark_web_base_ref_counted.h" + +namespace OHOS::ArkWeb { + +/*--ark web(source=webview)--*/ +class ArkWebArrayBufferValueCallback : public virtual ArkWebBaseRefCounted { +public: + /*--ark web()--*/ + virtual void OnReceiveValue(const char* value, const long size) = 0; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_WEB_ARRAY_BUFFER_VALUE_CALLBACK_H_ diff --git a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_engine.h b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_engine.h index ab6194dcfbbef777ba036ef3f8afbe3da0545857..3208fffdc786bb7165f4fecb749a92d84162badd 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_engine.h +++ b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_engine.h @@ -108,6 +108,9 @@ public: /*--ark web()--*/ virtual ArkWebRefPtr GetAdsBlockManager() = 0; + + /*--ark web()--*/ + virtual void TrimMemoryByPressureLevel(int32_t memoryLevel) = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_handler.h b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_handler.h index b17fc6b557913db891fa7512c1901a3c934d0feb..2f4ce482056fc490f54109869fbf2c1f5541b4f0 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_handler.h +++ b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_handler.h @@ -744,6 +744,66 @@ public: */ /*--ark web()--*/ virtual void OnAdsBlocked(const ArkWebString &url, const ArkWebStringVector &adsBlocked) = 0; + + /** + * @brief called when the cursor info is updated. + * + * @param x, y relative coordinates within web components of the cursor + * @param width, height width and height of the cursor + */ + /*--ark web()--*/ + virtual void OnCursorUpdate(double x, double y, double width, double height) = 0; + + /** + * @brief Called when web occurs frame loss event. + * + * @param sceneId The id of event scene. + * @param isStart True if is start. + */ + /*--ark web()--*/ + virtual void ReportDynamicFrameLossEvent(const ArkWebString& sceneId, bool isStart) = 0; + + /** + * @brief Called when you need to temporarily hide/restore the handle menu. + * + * @param hide hide. + */ + /*--ark web()--*/ + virtual void HideHandleAndQuickMenuIfNecessary(bool hide) = 0; + + /** + * @brief Called When you click on the selected area. + * + */ + /*--ark web()--*/ + virtual void ChangeVisibilityOfQuickMenu() = 0; + + /** + * @brief Called when you need to start vibrator. + */ + /*--ark web()--*/ + virtual void StartVibraFeedback(const ArkWebString& vibratorType) = 0; + + /** + * @brief Called when a popup is shown with the given size. + * + * @param x The offset of the popup on the x coordinate axis. + * @param y The offset of the popup on the y coordinate axis. + * @param width The width of the popup. + * @param height The height of the popup. + * + */ + /*--ark web()--*/ + virtual void OnPopupSize(int x, int y, int width, int height) = 0; + + /** + * @brief Called when the popup is shown or hidden. + * + * @param show Whether the popup is shown or hidden. + * + */ + /*--ark web()--*/ + virtual void OnPopupShow(bool show) = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_nweb.h b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_nweb.h index 0bba501184ca9d2432574298dabbfcf223fcf7fc..b56dbe142093623442610e24e6cb5a058968bd47 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_nweb.h +++ b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_nweb.h @@ -19,6 +19,7 @@ #include "ohos_nweb/include/ark_web_accessibility_event_callback.h" #include "ohos_nweb/include/ark_web_accessibility_node_info.h" +#include "ohos_nweb/include/ark_web_array_buffer_value_callback.h" #include "ohos_nweb/include/ark_web_bool_value_callback.h" #include "ohos_nweb/include/ark_web_cache_options.h" #include "ohos_nweb/include/ark_web_create_native_media_player_callback.h" @@ -31,6 +32,7 @@ #include "ohos_nweb/include/ark_web_js_proxy_callback_vector.h" #include "ohos_nweb/include/ark_web_js_result_callback.h" #include "ohos_nweb/include/ark_web_message_value_callback.h" +#include "ohos_nweb/include/ark_web_pdfconfig_args.h" #include "ohos_nweb/include/ark_web_preference.h" #include "ohos_nweb/include/ark_web_release_surface_callback.h" #include "ohos_nweb/include/ark_web_screen_lock_callback.h" @@ -1426,6 +1428,86 @@ public: /*--ark web()--*/ virtual void RegisterArkJSfunction(const ArkWebString& object_name, const ArkWebStringVector& method_list, const ArkWebStringVector& async_method_list, const int32_t object_id, const ArkWebString& permission) = 0; + + /** + * @brief resize visual viewport. + * + * @param width width. + * @param height height. + * @param iskeyboard from keybord. + */ + /*--ark web()--*/ + virtual void ResizeVisibleViewport(uint32_t width, uint32_t height, bool isKeyboard) = 0; + + /** + * @brief set backforward cache options. + * @param size The size of the back forward cache could saved. + * @param timeToLive The time of the back forward cache page could stay. + */ + /*--ark web()--*/ + virtual void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) = 0; + + /** + * @brief set the callback of the autofill event. + * @param callback callback. + */ + /*--ark web()--*/ + virtual void SetAutofillCallback(ArkWebRefPtr callback) = 0; + + /** + * @brief fill autofill data. + * @param data data. + */ + /*--ark web()--*/ + virtual void FillAutofillData(const ArkWebMessage& data) = 0; + + /** + * @brief on autofill cancel. + * @param fillContent fillContent + */ + /*--ark web()--*/ + virtual void OnAutofillCancel(const ArkWebString& fillContent) = 0; + + /** + * @brief Get the current scroll offset of the webpage. + * @param offset_x The current horizontal scroll offset of the webpage. + * @param offset_y The current vertical scroll offset of the webpage. + */ + /*--ark web()--*/ + virtual void GetScrollOffset(float* offset_x, float* offset_y) = 0; + + /** + * @brief ExecuteCreatePDFExt + * + * @param pdfConfig The current configuration when creating pdf. + * @param callback NWebArrayBufferValueCallback: CreatePDF running result. + */ + /*--ark web()--*/ + virtual void ExecuteCreatePDFExt(ArkWebRefPtr pdfConfig, + ArkWebRefPtr callback) = 0; + + /** + * Scroll by the delta distance if web is not foucsed. + * + * @param delta_x horizontal offset. + * @param delta_y vertical offset. + * @return false if web is touched down. + */ + /*--ark web()--*/ + virtual bool ScrollByWithResult(float delta_x, float delta_y) = 0; + + /** + * @brief set a popupSurface to draw popup content + * @param popupSurface popupSurface. + */ + /*--ark web()--*/ + virtual void SetPopupSurface(void* popupSurface) = 0; + + /** + * @brief Called when image analyzer is destory. + */ + /*--ark web()--*/ + virtual void OnDestroyImageAnalyzerOverlay() = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_pdfconfig_args.h b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_pdfconfig_args.h new file mode 100644 index 0000000000000000000000000000000000000000..b4397f88d72774bd93e3b610791189750a4768a4 --- /dev/null +++ b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_pdfconfig_args.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_WEB_PDFCONFIG_ARGS_H_ +#define ARK_WEB_PDFCONFIG_ARGS_H_ +#pragma once + +#include "base/include/ark_web_base_ref_counted.h" + +namespace OHOS::ArkWeb { + +/*--ark web(source=webview)--*/ +class ArkWebPDFConfigArgs : public virtual ArkWebBaseRefCounted { +public: + /*--ark web()--*/ + virtual double GetWidth() = 0; + + /*--ark web()--*/ + virtual double GetHeight() = 0; + + /*--ark web()--*/ + virtual double GetScale() = 0; + + /*--ark web()--*/ + virtual double GetMarginTop() = 0; + + /*--ark web()--*/ + virtual double GetMarginBottom() = 0; + + /*--ark web()--*/ + virtual double GetMarginRight() = 0; + + /*--ark web()--*/ + virtual double GetMarginLeft() = 0; + + /*--ark web()--*/ + virtual bool GetShouldPrintBackground() = 0; +}; + +} // namespace OHOS::ArkWeb + +#endif // ARK_WEB_PDFCONFIG_ARGS_H_ diff --git a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_preference.h b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_preference.h index 812f65c38220b47327e7abdf2468cc4ef4885eab..a6e5e84da6e028e5e9b54a2b4450568bf1796c67 100644 --- a/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_preference.h +++ b/ohos_interface/ohos_glue/ohos_nweb/include/ark_web_preference.h @@ -734,6 +734,12 @@ public: */ /*--ark web()--*/ virtual void PutOverlayScrollbarEnabled(bool enable) = 0; + + /** + * @brief Set whether the scroll is enabled. + */ + /*--ark web()--*/ + virtual void SetScrollable(bool enable, int32_t scrollType) = 0; }; } // namespace OHOS::ArkWeb diff --git a/ohos_interface/ohos_glue/scripts/make_ctocpp_impl.py b/ohos_interface/ohos_glue/scripts/make_ctocpp_impl.py index 1fee8da67235cea856b4245654d824c86bb5801d..f18ae6c7eef69355fad5f901c922367fa255c395 100644 --- a/ohos_interface/ohos_glue/scripts/make_ctocpp_impl.py +++ b/ohos_interface/ohos_glue/scripts/make_ctocpp_impl.py @@ -183,7 +183,7 @@ def load_ctocpp_static_func(dir_name, clsname, name, func, suffix): result += 'ArkWebAdapterBridgeHelper' result += '::GetInstance().LoadFuncSymbol("' + static_var_name + '_static"));'\ '\n if(!' + static_var_name + ') {'\ - '\n ARK_WEB_CTOCPP_WRAN_LOG("failed to get static function symbol");'\ + '\n ARK_WEB_CTOCPP_WARN_LOG("failed to get static function symbol");'\ '\n return ' + retval_default + ';'\ '\n }\n }\n' return result diff --git a/ohos_nweb/BUILD.gn b/ohos_nweb/BUILD.gn index e46dbea3c1a32d3fdb794c21d26ad83092bbab52..ca60d4230c929e0cebe4621c98b2281ec5a7b8e4 100644 --- a/ohos_nweb/BUILD.gn +++ b/ohos_nweb/BUILD.gn @@ -12,19 +12,29 @@ # limitations under the License. import("//build/ohos.gni") +import("../config.gni") import("../web_aafwk.gni") webview_root_path = webview_path if (target_cpu == "arm64") { - web_source = "prebuilts/arm64/NWeb.hap" + web_source = "prebuilts/arm64/ArkWebCore.hap" defines = [ "webview_arm64" ] } else if (target_cpu == "arm") { - web_source = "prebuilts/arm/NWeb.hap" + web_source = "prebuilts/arm/ArkWebCore.hap" + defines = [] } else if (target_cpu == "x86_64") { - web_source = "prebuilts/arm64/NWeb.hap" + web_source = "prebuilts/arm64/ArkWebCore.hap" defines = [ "webview_x86_64" ] } +defines += [ + "WEBVIEW_PACKAGE_NAME=\"${webview_package_name}\"", + "WEBVIEW_SANDBOX_LIB_PATH=\"${webview_sandbox_lib_path}\"", + "WEBVIEW_CRASHPAD_HANDLER_SO=\"${webview_crashpad_handler_so}\"", + "WEBVIEW_SANDBOX_RELATIVE_LIB_PATH=\"${webview_sandbox_relative_lib_path}\"", + "WEBVIEW_ENGINE_SO=\"${webview_engine_so}\"", +] + config("nweb_config") { include_dirs = [ "include" ] @@ -64,6 +74,7 @@ ohos_shared_library("web_configs") { } ohos_shared_library("libnweb") { + output_name = "arkweb_core_loader" branch_protector_ret = "pac_ret" branch_protector_frt = "bti" @@ -88,11 +99,13 @@ ohos_shared_library("libnweb") { ":web_configs", "${webview_path}/ohos_glue:ohos_adapter_glue_source", "${webview_path}/ohos_glue:ohos_nweb_glue_source", + "${webview_path}/sa:app_fwk_update", ] external_deps = [ "ability_runtime:ability_manager", "ability_runtime:app_context", + "ability_runtime:app_manager", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", @@ -117,7 +130,7 @@ ohos_shared_library("libnweb") { ohos_prebuilt_etc("nweb_hap") { source = web_source - module_install_dir = "app/com.ohos.nweb" + module_install_dir = "app/${webview_package_name}" part_name = "webview" subsystem_name = "web" license_file = "./prebuilts/NOTICE" @@ -159,6 +172,8 @@ ohos_prebuilt_etc("context-menu") { } ohos_executable("chrome_crashpad_handler") { + output_name = "arkweb_crashpad_handler" + install_enable = true include_dirs = [ "include" ] @@ -167,7 +182,6 @@ ohos_executable("chrome_crashpad_handler") { external_deps = [ "hilog:libhilog" ] - defines = [] if (target_cpu == "arm64") { defines += [ "webview_arm64" ] } else if (target_cpu == "arm") { diff --git a/ohos_nweb/etc/para/web.para b/ohos_nweb/etc/para/web.para index ee6e90dc6884ae9ed470ccc117b30e91fdda8ff4..d6af6a373bd5519a237801b4002a8a76b37ed490 100644 --- a/ohos_nweb/etc/para/web.para +++ b/ohos_nweb/etc/para/web.para @@ -17,4 +17,6 @@ web.debug.netlog = None web.debug.trace = false web.debug.strictsiteIsolation.enable = none web.oop.gpu = None -web.PRPPreload.enable = true \ No newline at end of file +web.PRPPreload.enable = true +persist.arkwebcore.install_path = /system/app/com.ohos.arkwebcore/ArkWebCore.hap +persist.arkwebcore.package_name = com.ohos.arkwebcore \ No newline at end of file diff --git a/ohos_nweb/etc/para/web.para.dac b/ohos_nweb/etc/para/web.para.dac index b040d9629934a87110aa803c0178072995169f7a..1f1b440bcabda2b712fb59bc2d2f8fc23239113a 100644 --- a/ohos_nweb/etc/para/web.para.dac +++ b/ohos_nweb/etc/para/web.para.dac @@ -15,3 +15,5 @@ web.optimization = root:root:0644 web.debug. = root:root:0775 web.debug.trace = root:shell:0775 web.PRPPreload.enable = root:root:0644 +persist.arkwebcore.install_path = root:root:0776 +persist.arkwebcore.package_name = root:root:0776 diff --git a/ohos_nweb/etc/web_config.xml b/ohos_nweb/etc/web_config.xml index c40748bb0d760e5fccef65b927c25a41842138b5..afb862ef2491a6d179aee1eec1c4acb04a9e1d21 100644 --- a/ohos_nweb/etc/web_config.xml +++ b/ohos_nweb/etc/web_config.xml @@ -71,28 +71,13 @@ - - - - - - - - - - - - - - - - - + + diff --git a/ohos_nweb/include/nweb_adapter_helper.h b/ohos_nweb/include/nweb_adapter_helper.h index 3e33fb04b82f60a03f5f06061a2cb704317fea16..b9b4a9ace8271b19d83a05dac1fbd9a435efd1ab 100644 --- a/ohos_nweb/include/nweb_adapter_helper.h +++ b/ohos_nweb/include/nweb_adapter_helper.h @@ -47,6 +47,7 @@ public: void ReadConfigIfNeeded(); std::string ParsePerfConfig(const std::string &configNodeName, const std::string &argsNodeName); std::vector GetPerfConfig(const std::string& settingName); + bool IsLTPODynamicApp(const std::string& bundleName); private: NWebAdapterHelper() = default; diff --git a/ohos_nweb/include/nweb_c_api.h b/ohos_nweb/include/nweb_c_api.h index 91ddad0226688c0209a6b310c4722ed890037a6c..933770ed4ea06cae53b9fd2a02e7b454cec68f56 100644 --- a/ohos_nweb/include/nweb_c_api.h +++ b/ohos_nweb/include/nweb_c_api.h @@ -75,6 +75,8 @@ NWEB_EXPORT void WebDownload_Resume(const WebDownloadItemCallbackWrapper *wrappe NWEB_EXPORT NWebDownloadItemState WebDownload_GetItemState(int32_t nwebId, long downloadItemId); +NWEB_EXPORT NWebDownloadItemState WebDownload_GetItemStateByGuid(const std::string& guid); + NWEB_EXPORT void WebDownloadItem_CreateWebDownloadItem(NWebDownloadItem **downloadItem); NWEB_EXPORT void WebDownloadItem_Destroy(NWebDownloadItem *downloadItem); diff --git a/ohos_nweb/include/nweb_config_helper.h b/ohos_nweb/include/nweb_config_helper.h index e2e77c0c00b0e8e89407b9979962f2e0249691d2..a9d9a92d792317978d20d08264f207c8f7a8585f 100644 --- a/ohos_nweb/include/nweb_config_helper.h +++ b/ohos_nweb/include/nweb_config_helper.h @@ -31,6 +31,7 @@ public: void ReadConfigIfNeeded(); std::string ParsePerfConfig(const std::string &configNodeName, const std::string &argsNodeName); std::vector GetPerfConfig(const std::string& settingName); + bool IsLTPODynamicApp(const std::string& bundleName); private: NWebConfigHelper() = default; @@ -42,8 +43,11 @@ private: void ParseWebConfigXml(const std::string &configFilePath, std::shared_ptr initArgs); void WriteConfigValueToSysPara(const std::string &configName, const std::string &value); void ParseDeleteConfig(const xmlNodePtr &rootPtr, std::shared_ptr initArgs); + void ParseNWebLTPOApp(xmlNodePtr nodePtr); + std::map perfConfig_; std::map> ltpoConfig_; + std::set ltpoAllowedApps_ {}; }; } // namespace OHOS diff --git a/ohos_nweb/include/nweb_helper.h b/ohos_nweb/include/nweb_helper.h index a6fa18a677da3b40a113bcdaf4f566516a29a6f9..e5a9781a909bde647cf6ae23cc6a7f324c440193 100644 --- a/ohos_nweb/include/nweb_helper.h +++ b/ohos_nweb/include/nweb_helper.h @@ -52,7 +52,7 @@ public: void SetWebTag(int32_t nwebId, const char* webTag); void PrepareForPageLoad(std::string url, bool preconnectable, int32_t numSockets); bool LoadNWebSDK(); - void* GetWebEngineHandler(); + void* GetWebEngineHandler(bool shouldRun = false); void SetConnectionTimeout(const int32_t& timeout); void SetCustomSchemeCmdLine(const std::string& cmd) { @@ -86,6 +86,10 @@ public: void EnableWholeWebPageDrawing(); std::shared_ptr GetAdsBlockManager(); + void EnableBackForwardCache(bool enableNativeEmbed, bool enableMediaTakeOver); + + void TrimMemoryByPressureLevel(int32_t memoryLevel); + private: NWebHelper() = default; bool LoadLib(bool from_ark); @@ -97,6 +101,7 @@ private: std::string bundlePath_; std::shared_ptr nwebEngine_ = nullptr; std::string customSchemeCmdLine_; + std::vector backForwardCacheCmdLine_; }; } // namespace OHOS::NWeb diff --git a/ohos_nweb/include/nweb_init_params.h b/ohos_nweb/include/nweb_init_params.h index 8cfe711d2bd5a80d199412acd603bf13066ed753..4e8501562015e0383c9d88fd1593db3a36a709b2 100644 --- a/ohos_nweb/include/nweb_init_params.h +++ b/ohos_nweb/include/nweb_init_params.h @@ -22,201 +22,235 @@ namespace OHOS::NWeb { class NWebDOHConfigImpl : public NWebDOHConfig { public: - NWebDOHConfigImpl() = default; - ~NWebDOHConfigImpl() = default; + NWebDOHConfigImpl() = default; + ~NWebDOHConfigImpl() = default; - void SetMode(int mode) { - mode_ = mode; - } + void SetMode(int mode) + { + mode_ = mode; + } - int GetMode() override { - return mode_; - } + int GetMode() override + { + return mode_; + } - void SetConfig(const std::string &config) { - config_ = config; - } + void SetConfig(const std::string& config) + { + config_ = config; + } - std::string GetConfig() override { - return config_; - } + std::string GetConfig() override + { + return config_; + } private: - int mode_ = -1; - std::string config_; + int mode_ = -1; + std::string config_; }; class NWebCreateInfoImpl : public NWebCreateInfo { public: - NWebCreateInfoImpl() = default; - ~NWebCreateInfoImpl() = default; + NWebCreateInfoImpl() = default; + ~NWebCreateInfoImpl() = default; - void SetWidth(uint32_t width) { - width_ = width; - } + void SetWidth(uint32_t width) + { + width_ = width; + } - uint32_t GetWidth() override { - return width_; - } + uint32_t GetWidth() override + { + return width_; + } - void SetHeight(uint32_t height) { - height_ = height; - } + void SetHeight(uint32_t height) + { + height_ = height; + } - uint32_t GetHeight() override { - return height_; - } + uint32_t GetHeight() override + { + return height_; + } - void SetIsIncognitoMode(bool isIncognitoMode) { - isIncognitoMode_ = isIncognitoMode; - } + void SetIsIncognitoMode(bool isIncognitoMode) + { + isIncognitoMode_ = isIncognitoMode; + } - bool GetIsIncognitoMode() override { - return isIncognitoMode_; - } + bool GetIsIncognitoMode() override + { + return isIncognitoMode_; + } - void SetProducerSurface(void *producerSurface) { - producerSurface_ = producerSurface; - } + void SetProducerSurface(void* producerSurface) + { + producerSurface_ = producerSurface; + } - void *GetProducerSurface() override { - return producerSurface_; - } + void* GetProducerSurface() override + { + return producerSurface_; + } - void SetEnhanceSurfaceInfo(void *enhanceSurfaceInfo) { - enhanceSurfaceInfo_ = enhanceSurfaceInfo; - } + void SetEnhanceSurfaceInfo(void* enhanceSurfaceInfo) + { + enhanceSurfaceInfo_ = enhanceSurfaceInfo; + } - void *GetEnhanceSurfaceInfo() override { - return enhanceSurfaceInfo_; - } + void* GetEnhanceSurfaceInfo() override + { + return enhanceSurfaceInfo_; + } - void SetEngineInitArgs(std::shared_ptr initArgs) { - initArgs_ = initArgs; - } + void SetEngineInitArgs(std::shared_ptr initArgs) + { + initArgs_ = initArgs; + } - std::shared_ptr GetEngineInitArgs() override { - return initArgs_; - } + std::shared_ptr GetEngineInitArgs() override + { + return initArgs_; + } - void SetOutputFrameCallback( - std::shared_ptr outputFrameCallback) { - outputFrameCallback_ = outputFrameCallback; - } + void SetOutputFrameCallback(std::shared_ptr outputFrameCallback) + { + outputFrameCallback_ = outputFrameCallback; + } - std::shared_ptr GetOutputFrameCallback() override { - return outputFrameCallback_; - } + std::shared_ptr GetOutputFrameCallback() override + { + return outputFrameCallback_; + } private: - uint32_t width_ = 0; - uint32_t height_ = 0; + uint32_t width_ = 0; + uint32_t height_ = 0; - bool isIncognitoMode_ = false; + bool isIncognitoMode_ = false; - void *producerSurface_ = nullptr; - void *enhanceSurfaceInfo_ = nullptr; + void* producerSurface_ = nullptr; + void* enhanceSurfaceInfo_ = nullptr; - std::shared_ptr initArgs_ = nullptr; - std::shared_ptr outputFrameCallback_ = nullptr; + std::shared_ptr initArgs_ = nullptr; + std::shared_ptr outputFrameCallback_ = nullptr; }; class NWebEngineInitArgsImpl : public NWebEngineInitArgs { public: - NWebEngineInitArgsImpl() = default; - ~NWebEngineInitArgsImpl() = default; + NWebEngineInitArgsImpl() = default; + ~NWebEngineInitArgsImpl() = default; - void AddArg(const std::string &arg) { - argsToAdd_.emplace_back(arg); - } + void AddArg(const std::string& arg) + { + argsToAdd_.emplace_back(arg); + } - void AddDeleteArg(const std::string &arg) { - argsToDelete_.emplace_back(arg); - } + void AddDeleteArg(const std::string& arg) + { + argsToDelete_.emplace_back(arg); + } - void SetDumpPath(const std::string &dumpPath) { - dumpPath_ = dumpPath; - } + void SetDumpPath(const std::string& dumpPath) + { + dumpPath_ = dumpPath; + } - std::string GetDumpPath() override { - return dumpPath_; - } + std::string GetDumpPath() override + { + return dumpPath_; + } - void SetIsPopup(bool isPopup) { - isPopup_ = isPopup; - } + void SetIsPopup(bool isPopup) + { + isPopup_ = isPopup; + } - bool GetIsPopup() override { - return isPopup_; - } + bool GetIsPopup() override + { + return isPopup_; + } - void SetIsFrameInfoDump(bool isFrameInfoDump) { - isFrameInfoDump_ = isFrameInfoDump; - } + void SetIsFrameInfoDump(bool isFrameInfoDump) + { + isFrameInfoDump_ = isFrameInfoDump; + } - bool GetIsFrameInfoDump() override { - return isFrameInfoDump_; - } + bool GetIsFrameInfoDump() override + { + return isFrameInfoDump_; + } - void SetIsEnhanceSurface(bool isEnhanceSurface) { - isEnhanceSurface_ = isEnhanceSurface; - } + void SetIsEnhanceSurface(bool isEnhanceSurface) + { + isEnhanceSurface_ = isEnhanceSurface; + } - bool GetIsEnhanceSurface() override { - return isEnhanceSurface_; - } + bool GetIsEnhanceSurface() override + { + return isEnhanceSurface_; + } - void SetIsMultiRendererProcess(bool isMultiRendererProcess) { - isMultiRendererProcess_ = isMultiRendererProcess; - } + void SetIsMultiRendererProcess(bool isMultiRendererProcess) + { + isMultiRendererProcess_ = isMultiRendererProcess; + } - bool GetIsMultiRendererProcess() override { - return isMultiRendererProcess_; - } + bool GetIsMultiRendererProcess() override + { + return isMultiRendererProcess_; + } - void SetArgsToAdd(const std::list &argsToAdd) { - argsToAdd_ = argsToAdd; - } + void SetArgsToAdd(const std::list& argsToAdd) + { + argsToAdd_ = argsToAdd; + } - std::list GetArgsToAdd() override { - return argsToAdd_; - } + std::list GetArgsToAdd() override + { + return argsToAdd_; + } - void SetArgsToDelete(const std::list &argsToDelete) { - argsToDelete_ = argsToDelete; - } + void SetArgsToDelete(const std::list& argsToDelete) + { + argsToDelete_ = argsToDelete; + } - std::list GetArgsToDelete() override { - return argsToDelete_; - } + std::list GetArgsToDelete() override + { + return argsToDelete_; + } - void SetSharedRenderProcessToken(const std::string& sharedRenderProcessToken) - { - sharedRenderProcessToken_ = sharedRenderProcessToken; - } + void SetSharedRenderProcessToken(const std::string& sharedRenderProcessToken) + { + sharedRenderProcessToken_ = sharedRenderProcessToken; + } - std::string GetSharedRenderProcessToken() override - { - return sharedRenderProcessToken_; - } + std::string GetSharedRenderProcessToken() override + { + return sharedRenderProcessToken_; + } private: - std::string dumpPath_; + std::string dumpPath_; - bool isPopup_ = false; - bool isFrameInfoDump_ = false; - bool isEnhanceSurface_ = false; - bool isMultiRendererProcess_ = false; + bool isPopup_ = false; + bool isFrameInfoDump_ = false; + bool isEnhanceSurface_ = false; + bool isMultiRendererProcess_ = false; - std::list argsToAdd_; - std::list argsToDelete_; - std::string sharedRenderProcessToken_; + std::list argsToAdd_; + std::list argsToDelete_; + std::string sharedRenderProcessToken_; }; class NWebEnginePrefetchArgsImpl : public NWebEnginePrefetchArgs { public: - NWebEnginePrefetchArgsImpl(const std::string &url, const std::string &method, const std::string &formData) - : url_(url), method_(method), form_data_(formData) {} + NWebEnginePrefetchArgsImpl(const std::string& url, const std::string& method, const std::string& formData) + : url_(url), method_(method), form_data_(formData) + {} ~NWebEnginePrefetchArgsImpl() = default; @@ -241,6 +275,59 @@ private: std::string form_data_; }; +class NWebPDFConfigArgsImpl : public NWebPDFConfigArgs { +public: + NWebPDFConfigArgsImpl(const double width, const double height, const double scale, const double marginTop, + const double marginBottom, const double marginRight, const double marginLeft, const bool shouldPrintBackground) + : width_(width), height_(height), scale_(scale), marginTop_(marginTop), marginBottom_(marginBottom), + marginRight_(marginRight), marginLeft_(marginLeft), shouldPrintBackground_(shouldPrintBackground) + {} + + ~NWebPDFConfigArgsImpl() = default; + + double GetWidth() override + { + return width_; + } + double GetHeight() override + { + return height_; + } + double GetScale() override + { + return scale_; + } + double GetMarginTop() override + { + return marginTop_; + } + double GetMarginBottom() override + { + return marginBottom_; + } + double GetMarginRight() override + { + return marginRight_; + } + double GetMarginLeft() override + { + return marginLeft_; + } + bool GetShouldPrintBackground() override + { + return shouldPrintBackground_; + } + +private: + double width_; + double height_; + double scale_; + double marginTop_; + double marginBottom_; + double marginRight_; + double marginLeft_; + bool shouldPrintBackground_; +}; } // namespace OHOS::NWeb #endif // NWEB_INIT_PARAMS_H diff --git a/ohos_nweb/prebuilts/arm64/NWeb.hap b/ohos_nweb/prebuilts/arm/ArkWebCore.hap similarity index 32% rename from ohos_nweb/prebuilts/arm64/NWeb.hap rename to ohos_nweb/prebuilts/arm/ArkWebCore.hap index 3ea02155baa902570061dccb1679d298449f1477..d13c59212822e462d812abfd2a78758641ae170f 100644 --- a/ohos_nweb/prebuilts/arm64/NWeb.hap +++ b/ohos_nweb/prebuilts/arm/ArkWebCore.hap @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e4ed361a5946db6afb8e9d6b894c7e1e368d483b5f7b083da80469e668788589 -size 90156696 +oid sha256:4b47131bf389a7c9bf17aa10f8889963c0af0af6126b09802d49e37dcef8b554 +size 122226122 diff --git a/ohos_nweb/prebuilts/arm/NWeb.hap b/ohos_nweb/prebuilts/arm64/ArkWebCore.hap similarity index 32% rename from ohos_nweb/prebuilts/arm/NWeb.hap rename to ohos_nweb/prebuilts/arm64/ArkWebCore.hap index ac7f3c56cec071b3cc946e81bf962a17d3656f12..3549075bc5bfbcf5f456a356ff958a66774d6a2b 100644 --- a/ohos_nweb/prebuilts/arm/NWeb.hap +++ b/ohos_nweb/prebuilts/arm64/ArkWebCore.hap @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fd59e132e126e3df85c2b1f6123c46e32c8d60f4093451172fb9d19cef01c7b5 -size 79363768 +oid sha256:e99cc2e16161cefc440b2baf7d91e42059fea2a9ea6019f864e598d297e6b858 +size 189484054 diff --git a/ohos_nweb/src/nweb_config_helper.cpp b/ohos_nweb/src/nweb_config_helper.cpp index eb5444d581e915d38063f10a455996e90dc3f5b4..fcc6322460d9e5788ef99215737c06812c9fd743 100644 --- a/ohos_nweb/src/nweb_config_helper.cpp +++ b/ohos_nweb/src/nweb_config_helper.cpp @@ -36,6 +36,7 @@ const std::string PERFORMANCE_CONFIG = "performanceConfig"; // The config used in base/web/webview const std::string BASE_WEB_CONFIG = "baseWebConfig"; const std::string WEB_ANIMATION_DYNAMIC_SETTING_CONFIG = "property_animation_dynamic_settings"; +const std::string WEB_ANIMATION_DYNAMIC_APP = "DYNAMIC_APPS"; const auto XML_ATTR_NAME = "name"; const auto XML_ATTR_MIN = "min"; const auto XML_ATTR_MAX = "max"; @@ -296,6 +297,10 @@ void NWebConfigHelper::ParseNWebLTPOConfig(xmlNodePtr nodePtr) continue; } std::string settingName = (char *)xmlGetProp(curNodePtr, BAD_CAST(XML_ATTR_NAME)); + if (settingName == WEB_ANIMATION_DYNAMIC_APP) { + ParseNWebLTPOApp(curNodePtr); + continue; + } std::vector frameRateSetting; for (xmlNodePtr curDynamicNodePtr = curNodePtr->xmlChildrenNode; curDynamicNodePtr; curDynamicNodePtr = curDynamicNodePtr->next) { @@ -316,6 +321,25 @@ void NWebConfigHelper::ParseNWebLTPOConfig(xmlNodePtr nodePtr) } } +void NWebConfigHelper::ParseNWebLTPOApp(xmlNodePtr nodePtr) +{ + for (xmlNodePtr curDynamicNodePtr = nodePtr->xmlChildrenNode; curDynamicNodePtr; + curDynamicNodePtr = curDynamicNodePtr->next) { + if (curDynamicNodePtr->name == nullptr || curDynamicNodePtr->type == XML_COMMENT_NODE) { + WVLOG_E("invalid node!"); + continue; + } + std::string bundleName = (char *)xmlGetProp(curDynamicNodePtr, BAD_CAST(XML_ATTR_NAME)); + ltpoAllowedApps_.emplace(bundleName); + WVLOG_D("ltpo dynamic app: %{public}s", bundleName.c_str()); + } +} + +bool NWebConfigHelper::IsLTPODynamicApp(const std::string& bundleName) +{ + return ltpoAllowedApps_.find(bundleName) != ltpoAllowedApps_.end(); +} + std::vector NWebConfigHelper::GetPerfConfig(const std::string& settingName) { if (ltpoConfig_.find(settingName) == ltpoConfig_.end()) { diff --git a/ohos_nweb/src/nweb_crashpad_handler_main.cpp b/ohos_nweb/src/nweb_crashpad_handler_main.cpp index 624befed4126214dbfc483ff1195f40d5510c710..9ff2f6f5425c35142136d64ceacce6bbe1aaf61c 100644 --- a/ohos_nweb/src/nweb_crashpad_handler_main.cpp +++ b/ohos_nweb/src/nweb_crashpad_handler_main.cpp @@ -34,20 +34,33 @@ const std::string LIB_CRASHPAD_HANDLER = "libchrome_crashpad_handler.so"; int main(int argc, char* argv[]) { - const std::string libCrashpadHandler = CRASHPAD_HANDLER_PATH + "/" + LIB_CRASHPAD_HANDLER; + const std::string libCrashpadHandler = std::string(WEBVIEW_SANDBOX_LIB_PATH) + "/" + + std::string(WEBVIEW_CRASHPAD_HANDLER_SO); void *handle = dlopen(libCrashpadHandler.c_str(), RTLD_NOW | RTLD_GLOBAL); if (handle == nullptr) { - WVLOG_E("crashpad, fail to dlopen %{public}s, errmsg=%{public}s", libCrashpadHandler.c_str(), dlerror()); - return -1; + const std::string libCrashpadHandler2 = CRASHPAD_HANDLER_PATH + "/" + LIB_CRASHPAD_HANDLER; + handle = dlopen(libCrashpadHandler2.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (handle == nullptr) { + WVLOG_E("crashpad, fail to dlopen %{public}s, errmsg=%{public}s", libCrashpadHandler2.c_str(), dlerror()); + return -1; + } } using FuncType = int (*)(int argc, char* argv[]); FuncType crashpadHandlerFunc = reinterpret_cast(dlsym(handle, "CrashpadHandlerMain")); if (crashpadHandlerFunc == nullptr) { WVLOG_E("crashpad, fail to dlsym CrashpadHandlerMain, errmsg=%{public}s", dlerror()); + int ret = dlclose(handle); + if (ret != 0) { + WVLOG_E("crashped, fail to dlclose, errmsg=%{public}s", dlerror()); + } return -1; } WVLOG_I("crashpad, success to dlopen and dlsym, enter CrashpadHandlerMain"); + int ret = dlclose(handle); + if (ret != 0) { + WVLOG_E("crashped, fail to dlclose, errmsg=%{public}s", dlerror()); + } return crashpadHandlerFunc(argc, argv); } diff --git a/ohos_nweb/src/nweb_helper.cpp b/ohos_nweb/src/nweb_helper.cpp index f9d4065ffbb77b4544164bc88d9039f02ff78af3..97c36d4c9b902bba2215c81d95998dff7f4c8117 100644 --- a/ohos_nweb/src/nweb_helper.cpp +++ b/ohos_nweb/src/nweb_helper.cpp @@ -18,28 +18,28 @@ #include #include #include +#include #include #include #include #include #include #include -#include +#include "app_mgr_client.h" #include "application_context.h" #include "ark_web_nweb_bridge_helper.h" #include "config_policy_utils.h" #include "locale_config.h" #include "nweb_adapter_helper.h" +#include "nweb_c_api.h" #include "nweb_enhance_surface_adapter.h" +#include "nweb_hisysevent.h" #include "nweb_log.h" #include "nweb_surface_adapter.h" #include "parameter.h" #include "parameters.h" -#include "nweb_hisysevent.h" -#include "nweb_c_api.h" - namespace { const int32_t NS_TO_S = 1000000000; const uint32_t NWEB_SURFACE_MAX_WIDTH = 7680; @@ -73,6 +73,7 @@ static bool g_isFirstTimeStartUp = false; DO(WebDownload_Pause) \ DO(WebDownload_Resume) \ DO(WebDownload_GetItemState) \ + DO(WebDownload_GetItemStateByGuid) \ DO(WebDownloadItem_Guid) \ DO(WebDownloadItem_GetDownloadItemId) \ DO(WebDownloadItem_GetState) \ @@ -138,7 +139,7 @@ void LoadNWebCApi(void *handle, NWebCApi *api) bool LoadNWebSDK(void *handle) { if (g_nwebCApi) { - WVLOG_E("LoadNWebSDK had loaded."); + WVLOG_I("LoadNWebSDK had loaded."); return true; } @@ -279,12 +280,20 @@ extern "C" void WebDownload_Resume(const WebDownloadItemCallbackWrapper *wrapper extern "C" NWebDownloadItemState WebDownload_GetItemState(int32_t nwebId, long downloadItemId) { - if (!g_nwebCApi->impl_WebDownload_GetItemState) { + if (!g_nwebCApi || !g_nwebCApi->impl_WebDownload_GetItemState) { return NWebDownloadItemState::MAX_DOWNLOAD_STATE; } return g_nwebCApi->impl_WebDownload_GetItemState(nwebId, downloadItemId); } +extern "C" NWebDownloadItemState WebDownload_GetItemStateByGuid(const std::string& guid) +{ + if (!g_nwebCApi || !g_nwebCApi->impl_WebDownload_GetItemStateByGuid) { + return NWebDownloadItemState::MAX_DOWNLOAD_STATE; + } + return g_nwebCApi->impl_WebDownload_GetItemStateByGuid(guid); +} + extern "C" char *WebDownloadItem_Guid(const NWebDownloadItem *downloadItem) { if (!g_nwebCApi->impl_WebDownloadItem_Guid) { @@ -599,23 +608,37 @@ bool NWebHelper::LoadLib(bool from_ark) return true; } if (bundlePath_.empty()) { + WVLOG_E("load lib failed, because bundle path is empty"); return false; } std::string loadLibPath; if (from_ark) { - loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_BUNDLE; + loadLibPath = bundlePath_ + "/" + WEBVIEW_SANDBOX_RELATIVE_LIB_PATH; } else { loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_MOCK; } Dl_namespace dlns; dlns_init(&dlns, "nweb_ns"); dlns_create(&dlns, loadLibPath.c_str()); - void *libHandleWebEngine = dlopen_ns(&dlns, LIB_NAME_WEB_ENGINE.c_str(), RTLD_NOW | RTLD_GLOBAL); + void *libHandleWebEngine = dlopen_ns(&dlns, WEBVIEW_ENGINE_SO, RTLD_NOW | RTLD_GLOBAL); if (libHandleWebEngine == nullptr) { - WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", LIB_NAME_WEB_ENGINE.c_str(), dlerror()); - return false; + if (from_ark) { + loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_BUNDLE; + } + dlns_create(&dlns, loadLibPath.c_str()); + libHandleWebEngine = dlopen_ns(&dlns, LIB_NAME_WEB_ENGINE.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (libHandleWebEngine == nullptr) { + WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", LIB_NAME_WEB_ENGINE.c_str(), dlerror()); + return false; + } } libHandleWebEngine_ = libHandleWebEngine; + auto appMgrClient = std::make_unique(); + auto result = appMgrClient->ConnectAppMgrService(); + if (result == OHOS::AppExecFwk::AppMgrResultCode::RESULT_OK) { + auto ret = appMgrClient->NotifyProcessDependedOnWeb(); + WVLOG_I("NotifyProcessDependedOnWeb. %{public}d", ret); + } return true; } #else @@ -630,22 +653,29 @@ bool NWebHelper::LoadLib(bool from_ark) } std::string loadLibPath; if (from_ark) { - loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_BUNDLE; + loadLibPath = bundlePath_ + "/" + WEBVIEW_SANDBOX_RELATIVE_LIB_PATH; } else { loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_MOCK; } - const std::string libPathWebEngine = loadLibPath + "/" + LIB_NAME_WEB_ENGINE; + const std::string libPathWebEngine = loadLibPath + "/" + WEBVIEW_ENGINE_SO; void *libHandleWebEngine = ::dlopen(libPathWebEngine.c_str(), RTLD_NOW); if (libHandleWebEngine == nullptr) { - WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", libPathWebEngine.c_str(), dlerror()); - return false; + if (from_ark) { + loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_BUNDLE; + } + const std::string libPathWebEngine2 = loadLibPath + "/" + LIB_NAME_WEB_ENGINE; + libHandleWebEngine = ::dlopen(libPathWebEngine2.c_str(), RTLD_NOW); + if (libHandleWebEngine == nullptr) { + WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", libPathWebEngine2.c_str(), dlerror()); + return false; + } } libHandleWebEngine_ = libHandleWebEngine; return true; } #endif -void* NWebHelper::GetWebEngineHandler() +void* NWebHelper::GetWebEngineHandler(bool shouldRun) { WVLOG_I("NWebHelper GetWebEngineHandler"); if (libHandleWebEngine_) { @@ -662,10 +692,18 @@ void* NWebHelper::GetWebEngineHandler() // load so const std::string& bundle_path = ctx->GetBundleCodeDir(); SetBundlePath(bundle_path); - if (!Init(true)) { - WVLOG_I("NWebHelper Init failed"); - return nullptr; + if (shouldRun) { + if (!InitAndRun(true)) { + WVLOG_I("NWebHelper Init failed"); + return nullptr; + } + } else { + if (!Init(true)) { + WVLOG_I("NWebHelper Init failed."); + return nullptr; + } } + return libHandleWebEngine_; } @@ -694,18 +732,21 @@ bool NWebHelper::LoadEngine() static void DoPreReadLib(const std::string &bundlePath) { WVLOG_I("NWebHelper PreReadLib"); - std::string libPathWebEngine = bundlePath + "/" + RELATIVE_PATH_FOR_BUNDLE + "/" + LIB_NAME_WEB_ENGINE; + std::string libPathWebEngine = bundlePath + "/" + WEBVIEW_SANDBOX_RELATIVE_LIB_PATH + "/" + WEBVIEW_ENGINE_SO; char tempPath[PATH_MAX] = {0}; if (realpath(libPathWebEngine.c_str(), tempPath) == nullptr) { - WVLOG_E("path to realpath error"); - return; + libPathWebEngine = bundlePath + "/" + RELATIVE_PATH_FOR_BUNDLE + "/" + LIB_NAME_WEB_ENGINE; + if (realpath(libPathWebEngine.c_str(), tempPath) == nullptr) { + WVLOG_E("path to realpath error, errno(%{public}d):%{public}s", errno, strerror(errno)); + return; + } } struct stat stats; int ret = stat(tempPath, &stats); if (ret < 0) { - WVLOG_E("stat web engine library failed, ret = %{public}d", ret); + WVLOG_E("stat web engine library failed, errno(%{public}d):%{public}s", errno, strerror(errno)); return; } @@ -718,7 +759,7 @@ static void DoPreReadLib(const std::string &bundlePath) int fd = open(tempPath, O_RDONLY); if (fd <= 0) { - WVLOG_E("open web engine library failed"); + WVLOG_E("open web engine library failed, errno(%{public}d):%{public}s", errno, strerror(errno)); delete[] buf; return; } @@ -764,8 +805,13 @@ bool NWebHelper::Init(bool from_ark) return false; } - if (!OHOS::ArkWeb::ArkWebNWebBridgeHelper::GetInstance().Init(from_ark, bundlePath_)) { - return false; + std::string relativeLibPath = WEBVIEW_SANDBOX_RELATIVE_LIB_PATH; + std::string arkWebEngineSo = WEBVIEW_ENGINE_SO; + if (!OHOS::ArkWeb::ArkWebNWebBridgeHelper::GetInstance().InitArkWeb( + from_ark, bundlePath_, relativeLibPath, arkWebEngineSo)) { + if (!OHOS::ArkWeb::ArkWebNWebBridgeHelper::GetInstance().Init(from_ark, bundlePath_)) { + return false; + } } return LoadEngine(); @@ -811,6 +857,11 @@ bool NWebHelper::InitAndRun(bool from_ark) std::string simplifiedLocale = baseLanguage + "-" + systemRegion; initArgs->AddArg(std::string("--lang=").append(simplifiedLocale)); + for (auto backForwardCacheCmdLine : backForwardCacheCmdLine_) { + initArgs->AddArg(backForwardCacheCmdLine); + WVLOG_I("Add command line when init web engine: %{public}s", backForwardCacheCmdLine.c_str()); + } + nwebEngine_->InitializeWebEngine(initArgs); return true; } @@ -1077,6 +1128,18 @@ void NWebHelper::ClearHostIP(const std::string& hostName) nwebEngine_->ClearHostIP(hostName); } +void NWebHelper::EnableBackForwardCache(bool enableNativeEmbed, bool enableMediaTakeOver) +{ + this->backForwardCacheCmdLine_.emplace_back("--enable-bfcache"); + if (enableNativeEmbed) { + this->backForwardCacheCmdLine_.emplace_back("--enable-cache-native-embed"); + } + + if (enableMediaTakeOver) { + this->backForwardCacheCmdLine_.emplace_back("--enable-cache-media-take-over"); + } +} + void NWebHelper::EnableWholeWebPageDrawing() { if (nwebEngine_ == nullptr) { @@ -1116,6 +1179,16 @@ std::shared_ptr NWebHelper::GetAdsBlockManager() return nwebEngine_->GetAdsBlockManager(); } +void NWebHelper::TrimMemoryByPressureLevel(int32_t memoryLevel) +{ + if (nwebEngine_ == nullptr) { + WVLOG_E("nweb engine is nullptr"); + return; + } + + nwebEngine_->TrimMemoryByPressureLevel(memoryLevel); +} + NWebAdapterHelper &NWebAdapterHelper::Instance() { static NWebAdapterHelper helper; @@ -1211,4 +1284,9 @@ std::string NWebAdapterHelper::ParsePerfConfig(const std::string &configNodeName std::string config = NWebConfigHelper::Instance().ParsePerfConfig(configNodeName, argsNodeName); return config; } + +bool NWebAdapterHelper::IsLTPODynamicApp(const std::string& bundleName) +{ + return NWebConfigHelper::Instance().IsLTPODynamicApp(bundleName); +} } // namespace OHOS::NWeb \ No newline at end of file diff --git a/prepare.sh b/prepare.sh index dc6141058b50d431c9b0075f9dc46b94d897a8d9..e3b392f98683746df21bdb983f68f9183ee5ad44 100755 --- a/prepare.sh +++ b/prepare.sh @@ -33,7 +33,7 @@ if [ "$os_type" == "Darwin" ]; then CLANG_FORMAT_DIR=${WORK_SPACE}/../../../prebuilts/clang/ohos/darwin-arm64/llvm/bin fi else - CLANG_FORMAT_DIR=${WORK_SPACE}/../../../prebuilts/clang/ohos/linux-x86_64/llvm/bin + CLANG_FORMAT_DIR=${WORK_SPACE}/../../../prebuilts/clang/ohos/linux-${arch_type}/llvm/bin fi handle_copy_dir() { diff --git a/sa/8350.json b/sa/8350.json new file mode 100644 index 0000000000000000000000000000000000000000..6a901a120290d9dfdeff93fe7e237b455395757a --- /dev/null +++ b/sa/8350.json @@ -0,0 +1,22 @@ +{ + "process": "app_fwk_update_service", + "systemability": [ + { + "name": 8350, + "libpath": "libapp_fwk_update_service.z.so", + "run-on-create": false, + "auto-restart": true, + "distributed": false, + "dump-level": 1, + "recycle-strategy": "low-memory", + "start-on-demand": { + "commonevent": [{ + "name": "usual.event.PACKAGE_CHANGED" + }, + { + "name": "usual.event.PACKAGE_ADDED" + }] + } + } + ] +} diff --git a/sa/BUILD.gn b/sa/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..32482cd5fdd8cb1cb70bc906e7ce3ae1206cae55 --- /dev/null +++ b/sa/BUILD.gn @@ -0,0 +1,92 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/config/components/idl_tool/idl.gni") +import("//build/ohos.gni") + +group("app_fwk_update") { + deps = [ + ":app_fwk_update_service", + ":app_fwk_update_service_cfg", + ":app_fwk_update_service_profile", + ] +} + +idl_interface_sources = [ + "${target_gen_dir}/app_fwk_update_servic_proxy.cpp", + "${target_gen_dir}/app_fwk_update_servic_stub.cpp", +] + +idl_gen_interface("app_fwk_update_service_interface") { + src_idl = rebase_path("IAppFwkUpdateService.idl") + dst_file = string_join(",", idl_interface_sources) +} + +ohos_sa_profile("app_fwk_update_service_profile") { + sources = [ "8350.json" ] + part_name = "webview" +} + +ohos_prebuilt_etc("app_fwk_update_service_cfg") { + source = "app_fwk_update_service.cfg" + relative_install_dir = "init" + subsystem_name = "web" + part_name = "webview" +} + +ohos_shared_library("app_fwk_update_service") { + shlib_type = "sa" + defines = [ "HILOG_TAG=\"app_fwk_update_service\"" ] + output_values = get_target_outputs(":app_fwk_update_service_interface") + sources = [ + "../sa/include/app_fwk_update_service.h", + "../sa/src/app_fwk_update_service.cpp", + ] + sources += filter_include(output_values, [ "*.cpp" ]) + deps = [ ":app_fwk_update_service_interface" ] + include_dirs = [ + "../sa/include", + "../ohos_nweb/include", + "${target_gen_dir}", + ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:napi_common", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + #innerapi_tags = [ "platformsdk" ] + subsystem_name = "web" + part_name = "webview" +} diff --git a/sa/IAppFwkUpdateService.idl b/sa/IAppFwkUpdateService.idl new file mode 100644 index 0000000000000000000000000000000000000000..07db428fbb260237ad35252f5b768b5054205ab3 --- /dev/null +++ b/sa/IAppFwkUpdateService.idl @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface OHOS.NWeb.IAppFwkUpdateService { + void RequestUpdateService([in] String bundleName); +} diff --git a/sa/app_fwk_update_service.cfg b/sa/app_fwk_update_service.cfg new file mode 100644 index 0000000000000000000000000000000000000000..25bda126b8a477f4687a29114a318433f03c4803 --- /dev/null +++ b/sa/app_fwk_update_service.cfg @@ -0,0 +1,16 @@ +{ + "services" : [{ + "name" : "app_fwk_update_service", + "path" : ["/system/bin/sa_main", "/system/profile/app_fwk_update_service.json"], + "ondemand" : true, + "uid" : "app_fwk_update", + "gid" : ["app_fwk_update"], + "permission" : [ + "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", + "ohos.permission.GET_BUNDLE_INFO" + ], + "start-mode" : "condition", + "secon" : "u:r:app_fwk_update_service:s0" + } + ] +} \ No newline at end of file diff --git a/sa/include/app_fwk_update_service.h b/sa/include/app_fwk_update_service.h new file mode 100644 index 0000000000000000000000000000000000000000..c91c3d43226271ad3a89fae091ab14df9dd8e00b --- /dev/null +++ b/sa/include/app_fwk_update_service.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APP_FWK_UPDATE_SERVICE_H +#define APP_FWK_UPDATE_SERVICE_H + +#include + +#include "app_fwk_update_service_stub.h" +#include "common_event_manager.h" +#include "event_handler.h" +#include "refbase.h" +#include "system_ability.h" + +namespace OHOS::NWeb { + +struct PackageCommonEventCallback { + std::function OnPackageChangedEvent; +}; + +class PackageChangedReceiver : public EventFwk::CommonEventSubscriber { +public: + explicit PackageChangedReceiver( + const EventFwk::CommonEventSubscribeInfo& subscribeInfo, const PackageCommonEventCallback& callback); + ~PackageChangedReceiver() = default; + void OnReceiveEvent(const EventFwk::CommonEventData& data) override; + +private: + PackageCommonEventCallback callback_; +}; + +class AppFwkUpdateService : public SystemAbility, public AppFwkUpdateServiceStub { + DECLARE_SYSTEM_ABILITY(AppFwkUpdateService); + +public: + AppFwkUpdateService(int32_t saId, bool runOnCreate); + ~AppFwkUpdateService(); + + // add an unused funcation to verify adapting sa IDL template. + ErrCode RequestUpdateService(const std::string& bundleName) override; + void SubscribePackageChangedEvent(); + void OnPackageChangedEvent(const std::string& bunldeName, const std::string& hapPath); + +protected: + void OnStart(const SystemAbilityOnDemandReason& startReason) override; + void OnStop() override; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + void PostDelayUnloadTask(); + +private: + bool Init(const SystemAbilityOnDemandReason& startReason); + void SetWebInstallPath(const std::string& path); + void SetWebCorePackageName(const std::string& packageName); + void SendAppSpawnMessage(const std::string& packageName); + void SendNWebSpawnMesage(const std::string& packageName); + void UpdatePersistParamIfNeed(); + + std::shared_ptr unloadHandler_; + std::shared_ptr runner_; + bool registerToService_ = false; + std::shared_ptr pkgSubscriber_; +}; +} // namespace OHOS::NWeb + +#endif // APP_FWK_UPDATE_SERVICE_H diff --git a/sa/src/app_fwk_update_service.cpp b/sa/src/app_fwk_update_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a180619c047b558e009500dce04a6a2c7cf99936 --- /dev/null +++ b/sa/src/app_fwk_update_service.cpp @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_fwk_update_service.h" + +#include "appspawn.h" +#include "bundle_mgr_client.h" +#include "bundle_mgr_interface.h" +#include "bundle_mgr_proxy.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "event_handler.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "nweb_log.h" +#include "parameter.h" +#include "parameters.h" +#include "system_ability_definition.h" +#include "sysversion.h" + +namespace OHOS::NWeb { + +namespace { +const std::string PACKAGE_CHANGE_EVENT = "usual.event.PACKAGE_CHANGED"; +const std::string ARK_WEB_BUNDLE_NAME = "com.ohos.nweb"; +const int RETRY_COUNT = 2; +REGISTER_SYSTEM_ABILITY_BY_ID(AppFwkUpdateService, SUBSYS_WEBVIEW_SYS_UPDATE_SERVICE_ID, false); + +constexpr int32_t TASK_DELAY_TIME = 60000; // 1min = 1*60*1000 +const std::string TASK_ID = "unload"; +const std::string PERSIST_ARKWEBCORE_PACKAGE_NAME = "persist.arkwebcore.package_name"; +const std::set ARK_WEB_DEFAULT_BUNDLE_NAME_SET = { "com.ohos.nweb", "com.ohos.arkwebcore" }; +const std::string NWEB_HAP_PATH_MODULE_UPDATE = "/module_update/ArkWebCore/app/com.ohos.nweb/NWeb.hap"; +} // namespace + +PackageChangedReceiver::PackageChangedReceiver( + const EventFwk::CommonEventSubscribeInfo& subscribeInfo, const PackageCommonEventCallback& callback) + : EventFwk::CommonEventSubscriber(subscribeInfo), callback_(callback) +{} + +void PackageChangedReceiver::OnReceiveEvent(const EventFwk::CommonEventData& data) +{ + WVLOG_I("PackageChangedReceiver invoked."); + std::string action = data.GetWant().GetAction(); + if (action.empty()) { + WVLOG_I("action is empty"); + return; + } + + std::string bundleName = data.GetWant().GetBundle(); + if (!ARK_WEB_DEFAULT_BUNDLE_NAME_SET.count(bundleName)) { + WVLOG_I("Bundle name is not nweb."); + return; + } + + WVLOG_I("packagechangeReceiver OnReceiveEvent, ret = %{public}s.", action.c_str()); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) { + std::string hapPath; + OHOS::AppExecFwk::BundleInfo bundleInfo; + OHOS::AppExecFwk::BundleMgrClient client; + WVLOG_I("packagechangeReceiver GetBundleInfo, ret = %{public}s.", bundleName.c_str()); + + bool result = client.GetBundleInfo(bundleName, OHOS::AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, + AppExecFwk::Constants::ALL_USERID); + if (result) { + if (bundleInfo.hapModuleInfos.size() > 0) { + hapPath = bundleInfo.hapModuleInfos[0].hapPath; + WVLOG_I("PackagechangeReceiver hapPath is %{public}s.", hapPath.c_str()); + } + callback_.OnPackageChangedEvent(bundleName, hapPath); + } else { + WVLOG_I("Failed to get bundleInfo."); + } + } +} + +AppFwkUpdateService::AppFwkUpdateService(int32_t saId, bool runOnCreate) : SystemAbility(saId, runOnCreate) {} + +AppFwkUpdateService::~AppFwkUpdateService() {} + +ErrCode AppFwkUpdateService::RequestUpdateService(const std::string& bundleName) +{ + WVLOG_I("request update service invoked."); + return ERR_OK; +} + +void AppFwkUpdateService::OnStart(const SystemAbilityOnDemandReason& startReason) +{ + WVLOG_I("Servie on start."); + if (registerToService_) { + WVLOG_I("App fwk update service is running."); + } + if (!Init(startReason)) { + WVLOG_I("failed to init app_fwk_update_service."); + return; + } +} + +bool AppFwkUpdateService::Init(const SystemAbilityOnDemandReason& startReason) +{ + UpdatePersistParamIfNeed(); + std::string reasonName = startReason.GetName(); + std::string reasonValue = startReason.GetValue(); + WVLOG_I("AppFwkUpdateService reasonName: %{public}s", reasonName.c_str()); + PostDelayUnloadTask(); + bool ret = Publish(this); + if (!ret) { + WVLOG_I("Service publish failed."); + return false; + } + AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + + std::string bundleName = ""; + if (startReason.HasExtraData()) { + auto reasonMap = startReason.GetExtraData().GetWant(); + for (auto i = reasonMap.begin(); i != reasonMap.end(); ++i) { + std::string key = std::string(i->first.data()); + std::string value = std::string(i->second.data()); + if (key == "bundleName") { + bundleName = value; + WVLOG_I("AppFwkUpdateService bundleName: %{public}s", bundleName.c_str()); + break; + } + } + } + if (!ARK_WEB_DEFAULT_BUNDLE_NAME_SET.count(bundleName)) { + WVLOG_I("Bundle name is not nweb."); + return false; + } + if (reasonName == PACKAGE_CHANGE_EVENT) { + OHOS::AppExecFwk::BundleInfo bundleInfo; + std::string hapPath; + OHOS::AppExecFwk::BundleMgrClient client; + + bool result = client.GetBundleInfo(bundleName, OHOS::AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, + AppExecFwk::Constants::ALL_USERID); + if (result) { + if (bundleInfo.hapModuleInfos.size() > 0) { + hapPath = bundleInfo.hapModuleInfos[0].hapPath; + WVLOG_I("Hap path is %{public}s.", hapPath.c_str()); + } + } else { + WVLOG_W("Failed to get bundle info."); + } + OnPackageChangedEvent(bundleName, hapPath); + } + registerToService_ = true; + WVLOG_I("Service init success."); + return true; +} + +void AppFwkUpdateService::SendAppSpawnMessage(const std::string& bundleName) +{ + WVLOG_I("Send appspawn message start,uid = %{public}d.", getuid()); + int ret = 0; + int retryCount = 0; + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + if (ret != 0) { + WVLOG_I("Failed to create reqMgr,retry count = %{public}d.", retryCount); + continue; + } + ret = AppSpawnReqMsgCreate(MSG_UPDATE_MOUNT_POINTS, bundleName.c_str(), &reqHandle); + if (ret != 0) { + WVLOG_I("Failed to create req,retry count = %{public}d.", retryCount); + continue; + } + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + } while (++retryCount < RETRY_COUNT && ret != 0); + AppSpawnClientDestroy(clientHandle); + WVLOG_I("Send appspawn message success."); +} + +void AppFwkUpdateService::SendNWebSpawnMesage(const std::string& bundleName) +{ + WVLOG_I("Send nweb spawn messagestart,uid = %{public}d.", getuid()); + int ret = 0; + int retryCount = 0; + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + do { + ret = AppSpawnClientInit(NWEBSPAWN_SERVER_NAME, &clientHandle); + if (ret != 0) { + WVLOG_I("Failed to create reqMgr,retry count = %{public}d.", retryCount); + continue; + } + ret = AppSpawnReqMsgCreate(MSG_RESTART_SPAWNER, bundleName.c_str(), &reqHandle); + if (ret != 0) { + WVLOG_I("Failed to create req,retry count = %{public}d.", retryCount); + continue; + } + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + } while (++retryCount < RETRY_COUNT && ret != 0); + AppSpawnClientDestroy(clientHandle); + WVLOG_I("Send nweb spawn message success."); +} + +void AppFwkUpdateService::SetWebInstallPath(const std::string& path) +{ + OHOS::system::SetParameter("persist.arkwebcore.install_path", path); + return; +} +void AppFwkUpdateService::SetWebCorePackageName(const std::string& packageName) +{ + OHOS::system::SetParameter("persist.arkwebcore.package_name", packageName); + return; +} + +void AppFwkUpdateService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) +{ + WVLOG_I("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId); + if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { + SubscribePackageChangedEvent(); + return; + } +} + +void AppFwkUpdateService::SubscribePackageChangedEvent() +{ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + PackageCommonEventCallback callback = { std::bind( + &AppFwkUpdateService::OnPackageChangedEvent, this, std::placeholders::_1, std::placeholders::_2) }; + pkgSubscriber_ = std::make_shared(subscribeInfo, callback); + if (pkgSubscriber_ == nullptr) { + WVLOG_I("Create package changed subscriber failed"); + return; + } + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(pkgSubscriber_)) { + WVLOG_I("Subscribe package changed event fail"); + } +} + +void AppFwkUpdateService::OnPackageChangedEvent(const std::string& bunldeName, const std::string& hapPath) +{ + if (OHOS::system::GetParameter("persist.arkwebcore.install_path", "") == hapPath) { + WVLOG_I("OnPackageChangedEvent install path not changed."); + return; + } + SetWebInstallPath(hapPath); + SetWebCorePackageName(bunldeName); + SendNWebSpawnMesage(bunldeName); + SendAppSpawnMessage(bunldeName); +} +void AppFwkUpdateService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) +{ + if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { + WVLOG_I("systemAbilityId is not COMMON_EVENT_SERVICE_ID"); + return; + } + if (pkgSubscriber_ == nullptr) { + WVLOG_I("OnRemoveSystemAbility subscribeer is nullptr"); + return; + } + bool result = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(pkgSubscriber_); + WVLOG_I("UnSubscribeCommonEvent subscriber result = %{public}d", result); +} + +void AppFwkUpdateService::OnStop() +{ + WVLOG_I("Ready to stop service."); + registerToService_ = false; +} + +void AppFwkUpdateService::PostDelayUnloadTask() +{ + if (runner_ == nullptr) { + runner_ = AppExecFwk::EventRunner::Create("unload"); + } + if (unloadHandler_ == nullptr) { + unloadHandler_ = std::make_shared(runner_); + } + if (unloadHandler_ == nullptr) { + WVLOG_I("chenxin PostDelayUnloadTask invoke failed return."); + return; + } + + auto task = [this]() { + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + WVLOG_I("Get samgrProxy failed."); + return; + } + int32_t ret = samgrProxy->UnloadSystemAbility(SUBSYS_WEBVIEW_SYS_UPDATE_SERVICE_ID); + if (ret != 0) { + WVLOG_I("Unload sa failed."); + return; + } + WVLOG_I("Do unload task done."); + }; + unloadHandler_->RemoveTask(TASK_ID); + unloadHandler_->PostTask(task, TASK_ID, TASK_DELAY_TIME); +} + +void AppFwkUpdateService::UpdatePersistParamIfNeed() +{ + // Temp code, delte it when bms use idl to notify install web result. + if (access(NWEB_HAP_PATH_MODULE_UPDATE.c_str(), F_OK) != 0) + return; + if (OHOS::system::GetParameter(PERSIST_ARKWEBCORE_PACKAGE_NAME, "") == ARK_WEB_BUNDLE_NAME) + return; + SetWebInstallPath(NWEB_HAP_PATH_MODULE_UPDATE); + SetWebCorePackageName(ARK_WEB_BUNDLE_NAME); + WVLOG_I("Update arkWeb persist param."); +} +} // namespace OHOS::NWeb diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/BUILD.gn index f6e93f681dc298d227dca2a1ac2ca71018625d6f..22dbb4ae568e4d17b908d90847d7560a0e949882 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/BUILD.gn +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/BUILD.gn @@ -31,13 +31,16 @@ ohos_fuzztest("AafwkAttachRenderFuzzTest") { sources = [ "aafwkattachrender_fuzzer.cpp" ] deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] external_deps = [ + "ability_base:want", "ability_runtime:app_manager", + "bundle_framework:appexecfwk_base", "c_utils:utils", "graphic_2d:libcomposer", "graphic_2d:libgraphic_utils", "graphic_2d:libnative_image", "graphic_2d:librender_service_client", "graphic_surface:surface", + "hilog:libhilog", "ipc:ipc_core", ] } diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.cpp b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.cpp index 4b1a2ad509cf0f074b7b9615b5a07424cc1c1678..e615788339c73ed75d822c86293e3e957d0f4a75 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.cpp @@ -18,23 +18,34 @@ #include #include -#include "aafwk_render_scheduler_impl.h" #include "aafwk_app_mgr_client_adapter_impl.h" +#include "aafwk_render_scheduler_impl.h" using namespace OHOS::NWeb; +using namespace OHOS::AppExecFwk; namespace OHOS { - bool AafwkAttachRenderFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - AafwkAppMgrClientAdapterImpl render; - std::shared_ptr adapter = nullptr; - render.AttachRenderProcess(adapter); - return true; +bool AafwkAttachRenderFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + AafwkAppMgrClientAdapterImpl render; + std::shared_ptr adapter = nullptr; + render.AttachRenderProcess(adapter); + std::shared_ptr newadapter = std::make_shared(); + std::string renderParam = "test"; + int32_t ipcFd = 0; + int32_t sharedFd = 0; + int32_t crashFd = 0; + pid_t renderPid = 0; + newadapter->StartRenderProcess(renderParam, ipcFd, sharedFd, crashFd, renderPid); + pid_t red = 1; + int statused = 1; + newadapter->GetRenderProcessTerminationStatus(red, statused); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.h b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.h index fccbd5772e4b76867a8d19dde871744d158ce460..569c41a608d125909ee50353e449b98941745f4f 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.h +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkattachrender_fuzzer/aafwkattachrender_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "aafwkattachrender_fuzzer" #endif /* TEST_FUZZTEST_AAFWK_ATTACH_RENDER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4aeac8e4313973245bd3f07aec939b06cc6ab144 --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AafwkBrowserClientAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer" + + include_dirs = [ "$webview_path/ohos_adapter/aafwk_adapter/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "aafwkbrowserclientadapter_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + external_deps = [ + "ability_runtime:app_manager", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_2d:libgraphic_utils", + "graphic_2d:libnative_image", + "graphic_2d:librender_service_client", + "graphic_surface:surface", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AafwkBrowserClientAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/aafwkbrowserclientadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/aafwkbrowserclientadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d19c51d4d1ab867bd0d40bac0c689c8c93f6047 --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/aafwkbrowserclientadapter_fuzzer.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#define private public +#include "aafwk_app_mgr_client_adapter_impl.h" +#include "aafwk_browser_client_adapter_impl.h" +#include "aafwk_browser_host_impl.h" +#include "aafwk_render_scheduler_impl.h" +#undef private + +#include "aafwk_browser_client_adapter.h" +#include "aafwk_render_scheduler_host_adapter.h" +#include "app_mgr_client.h" +#include "ibrowser.h" +#include "iconsumer_surface.h" +#include "iremote_proxy.h" +#include "irender_scheduler.h" +#include "ohos_adapter_helper.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +class MockBrowserClient : public BrowserClient { + explicit MockBrowserClient(const sptr& impl); + + sptr QueryRenderSurface(int32_t surface_id); + + void ReportThread(int32_t status, int32_t process_id, int32_t thread_id, int32_t role); + + void PassSurface(sptr surface, int64_t surface_id); + + void DestroyRenderSurface(int32_t surface_id); +}; + +sptr MockBrowserClient::QueryRenderSurface(int32_t surface_id) +{ + (void)surface_id; + return nullptr; +} + +void MockBrowserClient::ReportThread(int32_t status, int32_t process_id, int32_t thread_id, int32_t role) +{ + (void)status; + (void)process_id; + (void)thread_id; + (void)role; +} + +void MockBrowserClient::PassSurface(sptr surface, int64_t surface_id) +{ + (void)surface; + (void)surface_id; +} + +void MockBrowserClient::DestroyRenderSurface(int32_t surface_id) +{ + (void)surface_id; +} + +bool AafwkBrowserClientAdapterFuzzTest(const uint8_t* data, size_t size) +{ + sptr impl; + auto client = new BrowserClient(impl); + int32_t surface_id = 0; + client->QueryRenderSurface(surface_id); + int32_t status = 0; + int32_t process_id = 0; + int32_t thread_id = 0; + int32_t role = 0; + sptr surface; + client->ReportThread(status, process_id, thread_id, role); + client->PassSurface(surface, surface_id); + client->DestroyRenderSurface(surface_id); + + std::shared_ptr clientAdapter = std::make_shared(); + clientAdapter->QueryRenderSurface(surface_id); + ResSchedStatusAdapter newstatus = ResSchedStatusAdapter::THREAD_CREATED; + ResSchedRoleAdapter newrole = ResSchedRoleAdapter::USER_INTERACT; + clientAdapter->ReportThread(newstatus, process_id, thread_id, newrole); + clientAdapter->PassSurface(surface_id); + clientAdapter->DestroyRenderSurface(surface_id); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AafwkBrowserClientAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/aafwkbrowserclientadapter_fuzzer.h b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/aafwkbrowserclientadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..b578cc7cddc6a35cc9f2074a434fe20c5d387474 --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/aafwkbrowserclientadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H +#define TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H + +#define FUZZ_PROJECT_NAME "aafwkbrowserclientadapter_fuzzer" +#endif /* TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserclientadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cd6058cbfc72b8f1736fae1b13e9b1f4bcbf1107 --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AafwkBrowserHostFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer" + + include_dirs = [ "$webview_path/ohos_adapter/aafwk_adapter/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "aafwkbrowserhost_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + external_deps = [ + "ability_runtime:app_manager", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_2d:libgraphic_utils", + "graphic_2d:libnative_image", + "graphic_2d:librender_service_client", + "graphic_surface:surface", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AafwkBrowserHostFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/aafwkbrowserhost_fuzzer.cpp b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/aafwkbrowserhost_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cd27b0c1ccef782dcea67b219598a57649488b6 --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/aafwkbrowserhost_fuzzer.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "aafwkbrowserhost_fuzzer.h" + +#include +#include + +#define private public +#include "aafwk_app_mgr_client_adapter_impl.h" +#include "aafwk_browser_host_impl.h" +#include "aafwk_render_scheduler_impl.h" +#undef private + +#include "aafwk_render_scheduler_host_adapter.h" +#include "app_mgr_client.h" +#include "ohos_adapter_helper.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool AafwkBrowserHostFuzzTest(const uint8_t* data, size_t size) +{ + std::shared_ptr hostAdapter = nullptr; + auto host = new AafwkBrowserHostImpl(hostAdapter); + uint32_t code = 0; + int32_t surface_id = 0; + MessageParcel newdata; + MessageParcel reply; + MessageOption option; + host->OnRemoteRequest(code, newdata, reply, option); + code = 0; + host->OnRemoteRequest(code, newdata, reply, option); + host->HandleQueryRenderSurface(newdata, reply); + host->HandleReportThread(newdata, reply); + host->HandlePassSurface(newdata, reply); + host->HandleDestroyRenderSurface(newdata, reply); + sptr surface; + host->PassSurface(surface, surface_id); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AafwkBrowserHostFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/aafwkbrowserhost_fuzzer.h b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/aafwkbrowserhost_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..0d3bef1637c4d511d07e28b1ce2ca95a84a80799 --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/aafwkbrowserhost_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H +#define TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H + +#define FUZZ_PROJECT_NAME "aafwkbrowserhost_fuzzer" +#endif /* TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/project.xml b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkbrowserhost_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/BUILD.gn index 82dfc07e42b0673f73a5a8929c864698670f4bfd..1421a410645fd1e47e2973415a5926b253dff46e 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/BUILD.gn +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/BUILD.gn @@ -30,14 +30,18 @@ ohos_fuzztest("AafwkRenderSchedulerFuzzTest") { ] sources = [ "aafwkrenderscheduler_fuzzer.cpp" ] deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + external_deps = [ + "ability_base:want", "ability_runtime:app_manager", + "bundle_framework:appexecfwk_base", "c_utils:utils", "graphic_2d:libcomposer", "graphic_2d:libgraphic_utils", "graphic_2d:libnative_image", "graphic_2d:librender_service_client", "graphic_surface:surface", + "hilog:libhilog", "ipc:ipc_core", ] } diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.cpp b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.cpp index 2479e5be84326d5343a3487275d9888979f8de85..3d8f74a03d2dd7227555d2c9efad08013f0bcf7e 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.cpp @@ -18,37 +18,46 @@ #include #include +#define private public +#include "aafwk_app_mgr_client_adapter_impl.h" +#include "aafwk_browser_host_impl.h" #include "aafwk_render_scheduler_impl.h" +#undef private + +#include "aafwk_render_scheduler_host_adapter.h" +#include "app_mgr_client.h" +#include "ohos_adapter_helper.h" using namespace OHOS::NWeb; +using namespace OHOS::AppExecFwk; namespace OHOS { - bool AafwkRenderSchedulerFuzzTest(const uint8_t* data, size_t size) - { - constexpr int fdNum = 3; - if ((data == nullptr) || size < fdNum * sizeof(int32_t)) { - return false; - } - std::shared_ptr adapter = nullptr; - AafwkRenderSchedulerImpl render(adapter); - int32_t ipcFd = 0; - int32_t sharedFd = 0; - int32_t crashFd = 0; - if (memcpy_s(&ipcFd, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } - if (memcpy_s(&sharedFd, sizeof(int32_t), data + sizeof(int32_t), sizeof(int32_t)) != 0) { - return false; - } - - if (memcpy_s(&crashFd, sizeof(int32_t), data + sizeof(int32_t) + sizeof(int32_t), sizeof(int32_t)) != 0) { - return false; - } - - render.NotifyBrowserFd(ipcFd, sharedFd, crashFd, nullptr); - return true; +bool AafwkRenderSchedulerFuzzTest(const uint8_t* data, size_t size) +{ + constexpr int fdNum = 3; + if ((data == nullptr) || size < fdNum * sizeof(int32_t)) { + return false; + } + std::shared_ptr adapter = nullptr; + AafwkRenderSchedulerImpl render(adapter); + int32_t ipcFd = 0; + int32_t sharedFd = 0; + int32_t crashFd = 0; + if (memcpy_s(&ipcFd, sizeof(int32_t), data, sizeof(int32_t)) != 0) { + return false; + } + if (memcpy_s(&sharedFd, sizeof(int32_t), data + sizeof(int32_t), sizeof(int32_t)) != 0) { + return false; } + + if (memcpy_s(&crashFd, sizeof(int32_t), data + sizeof(int32_t) + sizeof(int32_t), sizeof(int32_t)) != 0) { + return false; + } + + render.NotifyBrowserFd(ipcFd, sharedFd, crashFd, nullptr); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.h b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.h index 408e6eb4d3247746dc68246b1d2c108dabf6ca23..93bcf9ce2102eebb24405ab6e7ac3a82357af5d4 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.h +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkrenderscheduler_fuzzer/aafwkrenderscheduler_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "aafwkrenderscheduler_fuzzer" #endif /* TEST_FUZZTEST_AAFWK_RENDER_SCHEDULER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.cpp b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.cpp index 20c8690833ec5f708b27c9696baf5bf85348abfa..b952ddd11e6d297b316f24e372109a40a467834b 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.cpp @@ -18,34 +18,34 @@ #include #include -#include "aafwk_render_scheduler_impl.h" #include "aafwk_app_mgr_client_adapter_impl.h" +#include "aafwk_render_scheduler_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool AafwkStartRenderFuzzTest(const uint8_t* data, size_t size) - { - constexpr int fdNum = 2; - if ((data == nullptr) || (size < fdNum * sizeof(int32_t))) { - return false; - } - AafwkAppMgrClientAdapterImpl render; - int32_t ipcFd; - int32_t sharedFd = 0; - int32_t crashFd; - std::string renderParam((const char *)data, size); - pid_t renderPid = 0; - if (memcpy_s(&ipcFd, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } - if (memcpy_s(&crashFd, sizeof(int32_t), data + sizeof(int32_t), sizeof(int32_t)) != 0) { - return false; - } - render.StartRenderProcess(renderParam, ipcFd, sharedFd, crashFd, renderPid); - return true; +bool AafwkStartRenderFuzzTest(const uint8_t* data, size_t size) +{ + constexpr int fdNum = 2; + if ((data == nullptr) || (size < fdNum * sizeof(int32_t))) { + return false; + } + AafwkAppMgrClientAdapterImpl render; + int32_t ipcFd; + int32_t sharedFd = 0; + int32_t crashFd; + std::string renderParam((const char*)data, size); + pid_t renderPid = 0; + if (memcpy_s(&ipcFd, sizeof(int32_t), data, sizeof(int32_t)) != 0) { + return false; + } + if (memcpy_s(&crashFd, sizeof(int32_t), data + sizeof(int32_t), sizeof(int32_t)) != 0) { + return false; } + render.StartRenderProcess(renderParam, ipcFd, sharedFd, crashFd, renderPid); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.h b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.h index 0e7ad881fa8f79a5e238bdf298d9f0eb2e6d687e..5a53010b749fa8d09cfdd14b9c73763fe6ad8575 100644 --- a/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.h +++ b/test/fuzztest/ohos_adapter/aafwk_adapter/aafwkstartrender_fuzzer/aafwkstartrender_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "aafwkstartrender_fuzzer" #endif /* TEST_FUZZTEST_AAFWK_START_RENDER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/accesstoken_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4b0cafc483b3a9c7d8fd5140c59767d1b0605dda --- /dev/null +++ b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AccessTokenFuzzerTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/accesstoken_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/access_token_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "accesstoken_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AccessTokenFuzzerTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/accesstoken_fuzzer/accesstoken_fuzzer.cpp b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/accesstoken_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c5426929de8cc1d0b5fc3ad34555385f9511177 --- /dev/null +++ b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/accesstoken_fuzzer.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_fuzzer.h" +#include "access_token_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + bool AccessTokenAdapterFuzzTest(const uint8_t* data, size_t size) + { + std::string permissionName(reinterpret_cast(data), size); + + auto& instance = AccessTokenAdapterImpl::GetInstance(); + bool result = instance.VerifyAccessToken(permissionName); + + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AccessTokenAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/accesstoken_fuzzer/accesstoken_fuzzer.h b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/accesstoken_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..fd9b0957539b8d61af98459827dbf914aae2a486 --- /dev/null +++ b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/accesstoken_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ACCESSTOKEN_FUZZER_H +#define TEST_FUZZTEST_ACCESSTOKEN_FUZZER_H + +#define FUZZ_PROJECT_NAME "accesstoken_fuzzer" + +#endif /* TEST_FUZZTEST_ACCESSTOKEN_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/accesstoken_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/accesstoken_fuzzer/project.xml b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/accesstoken_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/BUILD.gn b/test/fuzztest/ohos_adapter/audio_adapter/BUILD.gn index 88f5250c934dbc6bd874c328d84a8726974c5ba3..7be642ed28b8ea820d55daa316e38d9498cf7a2b 100644 --- a/test/fuzztest/ohos_adapter/audio_adapter/BUILD.gn +++ b/test/fuzztest/ohos_adapter/audio_adapter/BUILD.gn @@ -30,8 +30,11 @@ group("fuzztest") { deps += [ "audioabandon_fuzzer:AudioAbandonFuzzTest", "audiocreaterender_fuzzer:AudioCreateRenderFuzzTest", + "audiodevicechange_fuzzer:AudioDeviceChangeFuzzTest", + "audiodevicedesc_fuzzer:AudioDeviceDescFuzzTest", "audiogetchannel_fuzzer:AudioGetChannelFuzzTest", "audiogetcontent_fuzzer:AudioGetContentFuzzTest", + "audiogetdevice_fuzzer:AudioGetDeviceFuzzTest", "audiogetformat_fuzzer:AudioGetFormatFuzzTest", "audiogetlatency_fuzzer:AudioGetLatencyFuzzTest", "audiogetsampling_fuzzer:AudioGetSamplingFuzzTest", diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a73ee043200bc340add17a3a471d419f93df280f --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/BUILD.gn @@ -0,0 +1,89 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AudioDeviceChangeFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer" + configs = [ "../:audio_adapter_fuzztest_config" ] + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$webview_path/ohos_adapter/audio_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "audiodevicechange_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + external_deps = [ + "ability_base:extractortool", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_context", + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "app_file_service:fileuri_native", + "background_task_mgr:bgtaskmgr_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "certificate_manager:cert_manager_sdk", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", + "eventhandler:libeventhandler", + "file_api:remote_uri_native", + "graphic_2d:libcomposer", + "graphic_2d:libnative_image", + "graphic_2d:librender_service_client", + "graphic_surface:surface", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "huks:libhukssdk", + "image_framework:image_native", + "imf:inputmethod_client", + "init:libbeget_proxy", + "init:libbegetutil", + "input:libmmi-client", + "ipc:ipc_core", + "napi:ace_napi", + "netmanager_base:net_conn_manager_if", + "pasteboard:pasteboard_client", + "relational_store:native_rdb", + "resource_schedule_service:ressched_client", + "samgr:samgr_proxy", + "time_service:time_client", + "window_manager:libdm", + ] + + if (webview_audio_enable) { + external_deps += [ + "audio_framework:audio_client", + "audio_framework:audio_renderer", + ] + } +} diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/audiodevicechange_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/audiodevicechange_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1c73c92220d19b88dd186618b8f3cd2ad53d695 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/audiodevicechange_fuzzer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "audiodevicechange_fuzzer.h" + +#include +#include + +#include "audio_renderer_adapter_impl.h" +#include "audio_system_manager_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + bool AudioDeviceChangeFuzzTest(const uint8_t* data, size_t size) + { + if ((data == nullptr) || (size == 0)) { + return false; + } + std::shared_ptr cb = nullptr; + AudioManagerDeviceChangeCallbackAdapterImpl adapter(cb); + DeviceChangeAction deviceChangeAction; + adapter.OnDeviceChange(deviceChangeAction); + return true; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AudioDeviceChangeFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/audiodevicechange_fuzzer.h b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/audiodevicechange_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..c3880ec95f62bc78697a56126d446f9e1711e143 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/audiodevicechange_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_AUDIO_DEVICE_CHANGE_FUZZER_H +#define TEST_FUZZTEST_AUDIO_DEVICE_CHANGE_FUZZER_H + +#define FUZZ_PROJECT_NAME "audiodevicechange_fuzzer" +#endif /* TEST_FUZZTEST_AUDIO_DEVICE_CHANGE_FUZZER_H */ + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/project.xml b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicechange_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..787b8dc6cabf8ad6ffbadb845c31ce77333cf6be --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AudioDeviceDescFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer" + configs = [ "../:audio_adapter_fuzztest_config" ] + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$webview_path/ohos_adapter/audio_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "audiodevicedesc_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + if (webview_audio_enable) { + external_deps = [ + "audio_framework:audio_client", + "audio_framework:audio_renderer", + ] + } +} diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/audiodevicedesc_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/audiodevicedesc_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d12eaf4e937246498197363843df6cefd14a1c0c --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/audiodevicedesc_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "audiodevicedesc_fuzzer.h" + +#include +#include + +#include "audio_device_desc_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + bool AudioDeviceDescFuzzTest(const uint8_t* data, size_t size) + { + if ((data == nullptr) || (size == 0)) { + return false; + } + int32_t id = 0; + std::string name((const char*) data, size); + std::shared_ptr deviceAdapterImpl = std::make_shared(); + deviceAdapterImpl->GetDeviceId(); + deviceAdapterImpl->GetDeviceName(); + deviceAdapterImpl->SetDeviceId(id); + deviceAdapterImpl->SetDeviceName(name); + return true; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AudioDeviceDescFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/audiodevicedesc_fuzzer.h b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/audiodevicedesc_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..cb12aaf21a8a58ddfa27b98c5c070a8ce3977087 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/audiodevicedesc_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_AUDIO_DEVICE_DESC_FUZZER_H +#define TEST_FUZZTEST_AUDIO_DEVICE_DESC_FUZZER_H + +#define FUZZ_PROJECT_NAME "audiodevicedesc_fuzzer" +#endif /* TEST_FUZZTEST_AUDIO_DEVICE_DESC_FUZZER_H */ + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/project.xml b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiodevicedesc_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetcontent_fuzzer/audiogetcontent_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiogetcontent_fuzzer/audiogetcontent_fuzzer.cpp index e3e981c36308bbaefe0e8bfcf76257d076b062cf..ff45795d04059272859122c7308c7e0ee1694e00 100644 --- a/test/fuzztest/ohos_adapter/audio_adapter/audiogetcontent_fuzzer/audiogetcontent_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetcontent_fuzzer/audiogetcontent_fuzzer.cpp @@ -17,22 +17,34 @@ #include #include +#include #include "audio_renderer_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool AudioGetContentFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - AudioRendererAdapterImpl adapter; - adapter.GetAudioContentType(AudioAdapterContentType::CONTENT_TYPE_SPEECH); - return true; +bool AudioGetContentFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + constexpr int typenums = 6; + std::array contentArray = { + AudioAdapterContentType::CONTENT_TYPE_UNKNOWN, + AudioAdapterContentType::CONTENT_TYPE_SPEECH, + AudioAdapterContentType::CONTENT_TYPE_MUSIC, + AudioAdapterContentType::CONTENT_TYPE_MOVIE, + AudioAdapterContentType::CONTENT_TYPE_SONIFICATION, + AudioAdapterContentType::CONTENT_TYPE_RINGTONE, + }; + for (auto& content : contentArray) + AudioRendererAdapterImpl::GetAudioContentType(content); + + AudioRendererAdapterImpl::GetAudioContentType(static_cast(-1)); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..dadb9a5915049db6a73aa5d4838ce4b85fe4da99 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AudioGetDeviceFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer" + configs = [ "../:audio_adapter_fuzztest_config" ] + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$webview_path/ohos_adapter/audio_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "audiogetdevice_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + if (webview_audio_enable) { + external_deps = [ + "audio_framework:audio_client", + "audio_framework:audio_renderer", + ] + } +} diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/audiogetdevice_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/audiogetdevice_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9dcc0c1a7d9e6429684fc05e4541d1becdbd068 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/audiogetdevice_fuzzer.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "audiogetdevice_fuzzer.h" + +#include +#include + +#include "audio_renderer_adapter_impl.h" +#include "audio_system_manager_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + bool AudioGetDeviceFuzzTest(const uint8_t* data, size_t size) + { + if ((data == nullptr) || (size == 0)) { + return false; + } + int32_t deviceId = 0; + bool isInput = 0; + std::string language((const char*) data, size); + AudioSystemManagerAdapterImpl::GetInstance().GetDeviceName(DeviceType::DEVICE_TYPE_INVALID); + AudioSystemManagerAdapterImpl::GetInstance().GetDevices(AdapterDeviceFlag::OUTPUT_DEVICES_FLAG); + AudioSystemManagerAdapterImpl::GetInstance().SelectAudioDeviceById(deviceId, isInput); + AudioSystemManagerAdapterImpl::GetInstance().GetDefaultOutputDevice(); + AudioSystemManagerAdapterImpl::GetInstance().GetDefaultInputDevice(); + AudioSystemManagerAdapterImpl::GetInstance().UnsetDeviceChangeCallback(); + AudioSystemManagerAdapterImpl::GetInstance().SetLanguage(language); + std::shared_ptr callback = nullptr; + AudioSystemManagerAdapterImpl::GetInstance().SetAudioManagerInterruptCallback(callback); + AudioSystemManagerAdapterImpl::GetInstance().UnsetDeviceChangeCallback(); + return true; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AudioGetDeviceFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/audiogetdevice_fuzzer.h b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/audiogetdevice_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..6f12b5f931d567ec32e2c9555072651cdb36ac5c --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/audiogetdevice_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_AUDIO_GET_DEVICE_FUZZER_H +#define TEST_FUZZTEST_AUDIO_GET_DEVICE_FUZZER_H + +#define FUZZ_PROJECT_NAME "audiogetdevice_fuzzer" +#endif /* TEST_FUZZTEST_AUDIO_GET_DEVICE_FUZZER_H */ + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/project.xml b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetdevice_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiogetlatency_fuzzer/audiogetlatency_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiogetlatency_fuzzer/audiogetlatency_fuzzer.cpp index 6872df8d090081779928bcc68b52eb79e9f690df..c4955834308525c5773489c425eede5df99ff936 100644 --- a/test/fuzztest/ohos_adapter/audio_adapter/audiogetlatency_fuzzer/audiogetlatency_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiogetlatency_fuzzer/audiogetlatency_fuzzer.cpp @@ -23,17 +23,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool AudioGetLatencyFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - AudioRendererAdapterImpl adapter; - uint64_t latency = 0; - adapter.GetLatency(latency); - return true; +bool AudioGetLatencyFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr adapter = std::make_shared(); + uint64_t latency = 0; + adapter->GetLatency(latency); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiointerrupt_fuzzer/audiointerrupt_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiointerrupt_fuzzer/audiointerrupt_fuzzer.cpp index b451bdf76f6a830f2367d9e955a1a6083853655e..523251f04230699d5775924678cc714b68206ea0 100644 --- a/test/fuzztest/ohos_adapter/audio_adapter/audiointerrupt_fuzzer/audiointerrupt_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiointerrupt_fuzzer/audiointerrupt_fuzzer.cpp @@ -24,18 +24,25 @@ using namespace OHOS::NWeb; namespace OHOS { - bool AudioInterruptFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr cb = nullptr; - AudioManagerCallbackAdapterImpl adapter(cb); - InterruptAction interruptAction; - adapter.OnInterrupt(interruptAction); - return true; +bool AudioInterruptFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr cb = nullptr; + AudioManagerCallbackAdapterImpl adapter(cb); + InterruptAction interruptAction; + interruptAction.interruptHint = InterruptHint::INTERRUPT_HINT_PAUSE; + adapter.OnInterrupt(interruptAction); + interruptAction.interruptHint = InterruptHint::INTERRUPT_HINT_STOP; + adapter.OnInterrupt(interruptAction); + interruptAction.interruptHint = InterruptHint::INTERRUPT_HINT_RESUME; + adapter.OnInterrupt(interruptAction); + interruptAction.interruptHint = static_cast(-1); + adapter.OnInterrupt(interruptAction); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fd51720be5b2be25cc4c18d19a18a1d2f1ec7b43 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/BUILD.gn @@ -0,0 +1,89 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AudioRendererAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer" + configs = [ "../:audio_adapter_fuzztest_config" ] + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$webview_path/ohos_adapter/audio_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "audiorenderadapter_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + external_deps = [ + "ability_base:extractortool", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_context", + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "app_file_service:fileuri_native", + "background_task_mgr:bgtaskmgr_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "certificate_manager:cert_manager_sdk", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", + "eventhandler:libeventhandler", + "file_api:remote_uri_native", + "graphic_2d:libcomposer", + "graphic_2d:libnative_image", + "graphic_2d:librender_service_client", + "graphic_surface:surface", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "huks:libhukssdk", + "image_framework:image_native", + "imf:inputmethod_client", + "init:libbeget_proxy", + "init:libbegetutil", + "input:libmmi-client", + "ipc:ipc_core", + "napi:ace_napi", + "netmanager_base:net_conn_manager_if", + "pasteboard:pasteboard_client", + "relational_store:native_rdb", + "resource_schedule_service:ressched_client", + "samgr:samgr_proxy", + "time_service:time_client", + "window_manager:libdm", + ] + + if (webview_audio_enable) { + external_deps += [ + "audio_framework:audio_client", + "audio_framework:audio_renderer", + ] + } +} diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/audiorenderadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/audiorenderadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68831000404a02612a72f0f7cfb818023e90980b --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/audiorenderadapter_fuzzer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "audiorenderadapter_fuzzer.h" + +#include +#include + +#include "audio_renderer_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + bool AudioRendererAdapterFuzzTest(const uint8_t* data, size_t size) + { + if ((data == nullptr) || (size == 0)) { + return false; + } + AudioRendererAdapterImpl audioRendererAdapterImpl; + uint8_t buffer[100]; + size_t bufferSize = sizeof(buffer); + float volume = 0.5; + AudioAdapterSamplingRate samplingRate = AudioAdapterSamplingRate::SAMPLE_RATE_44100; + AudioAdapterEncodingType encodingType = AudioAdapterEncodingType::ENCODING_PCM; + AudioAdapterSampleFormat sampleFormat = AudioAdapterSampleFormat::SAMPLE_S16LE; + AudioAdapterChannel channel = AudioAdapterChannel::STEREO; + AudioAdapterContentType contentType = AudioAdapterContentType::CONTENT_TYPE_MUSIC; + AudioAdapterStreamUsage streamUsage = AudioAdapterStreamUsage::STREAM_USAGE_MEDIA; + audioRendererAdapterImpl.Create(nullptr, ""); + audioRendererAdapterImpl.Start(); + audioRendererAdapterImpl.Pause(); + audioRendererAdapterImpl.Stop(); + audioRendererAdapterImpl.Release(); + audioRendererAdapterImpl.Write(buffer, bufferSize); + uint64_t latency; + audioRendererAdapterImpl.GetLatency(latency); + audioRendererAdapterImpl.SetVolume(volume); + audioRendererAdapterImpl.GetVolume(); + audioRendererAdapterImpl.SetAudioRendererCallback(nullptr); + audioRendererAdapterImpl.SetAudioOutputChangeCallback(nullptr); + audioRendererAdapterImpl.SetInterruptMode(true); + audioRendererAdapterImpl.IsRendererStateRunning(); + audioRendererAdapterImpl.GetAudioSamplingRate(samplingRate); + audioRendererAdapterImpl.GetAudioEncodingType(encodingType); + audioRendererAdapterImpl.GetAudioSampleFormat(sampleFormat); + audioRendererAdapterImpl.GetAudioChannel(channel); + audioRendererAdapterImpl.GetAudioContentType(contentType); + audioRendererAdapterImpl.GetAudioStreamUsage(streamUsage); + return true; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AudioRendererAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/audiorenderadapter_fuzzer.h b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/audiorenderadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..c3880ec95f62bc78697a56126d446f9e1711e143 --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/audiorenderadapter_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_AUDIO_DEVICE_CHANGE_FUZZER_H +#define TEST_FUZZTEST_AUDIO_DEVICE_CHANGE_FUZZER_H + +#define FUZZ_PROJECT_NAME "audiodevicechange_fuzzer" +#endif /* TEST_FUZZTEST_AUDIO_DEVICE_CHANGE_FUZZER_H */ + diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/audio_adapter/audiorenderadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..359bc230e1585351cb7693f7e0e12bb5a8e80fc2 --- /dev/null +++ b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("BackgroundTaskImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/backgroundtask_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/background_task_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "background_task_impl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":BackgroundTaskImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/background_task_impl_fuzzer.cpp b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/background_task_impl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86725b56bf272176aa20357d8e8be6ec0e49539c --- /dev/null +++ b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/background_task_impl_fuzzer.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "background_task_impl_fuzzer.h" +#include +#include +#include +#include "background_task_adapter.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + bool BackgroundTaskRequestFuzzTest(const uint8_t* data, size_t size) + { + if ((data == nullptr) || (size < sizeof(bool) + sizeof(BackgroundModeAdapter))) { + return false; + } + + bool running = static_cast(data[0]); + BackgroundModeAdapter bgMode = static_cast(data[1]); + std::shared_ptr taskAdapter = std::make_shared(); + + taskAdapter->RequestBackgroundRunning(running, bgMode); + + return true; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::BackgroundTaskRequestFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/background_task_impl_fuzzer.h b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/background_task_impl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..f15a788edfc483172a8e235758fa1387a2cfa7d8 --- /dev/null +++ b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/background_task_impl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_BACKGROUNDTASKREQUEST_FUZZER_H +#define TEST_FUZZTEST_BACKGROUNDTASKREQUEST_FUZZER_H + +#define FUZZ_PROJECT_NAME "backgroundtaskrequest_fuzzer" +#endif /* TEST_FUZZTEST_BACKGROUNDTASKREQUEST_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/project.xml b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/backgroundtask_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ca3bea2715391541353392bedf205915934e9973 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("FormatAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/camera_adapter/include", + "$webview_path/ohos_adapter/camera_adapter/src", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "formatadapter_fuzzer.cpp" ] + + defines = [ "NWEB_CAMERA_ENABLE" ] + + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "camera_framework:camera_framework", + "drivers_interface_camera:metadata", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "webview:libnweb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":FormatAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/formatadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/formatadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6590abcffafa711664a28b07aa9126a1c874969 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/formatadapter_fuzzer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "formatadapter_fuzzer.h" +#define FORMAT_ADAPTER_IMPL +#define private public +#include "camera_manager_adapter_impl.h" +#include "format_adapter_impl.cpp" +#include "format_adapter_impl.h" +#include "nweb_surface_adapter.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + +bool FormatAdapterFuzzTest(const uint8_t* data, size_t size) +{ + OHOS::NWeb::FormatAdapterImpl adapter; + adapter.SetWidth(1); + adapter.SetHeight(1); + adapter.SetFrameRate(1); + adapter.SetPixelFormat(VideoPixelFormatAdapter::FORMAT_UNKNOWN); + + adapter.GetWidth(); + adapter.GetHeight(); + adapter.GetFrameRate(); + adapter.GetPixelFormat(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::FormatAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/formatadapter_fuzzer.h b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/formatadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..9699361208335491ce5a362496b8b144584287b4 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/formatadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H +#define TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H + +#define FUZZ_PROJECT_NAME "formatadapter_fuzzer" +#endif /* TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/formatadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..09378d2204c5ece0e33bc3f9cb471b4871251dab --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("VideoCaptureRangeAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/camera_adapter/include", + "$webview_path/ohos_adapter/camera_adapter/src", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "videocapturerangeadapter_fuzzer.cpp" ] + + defines = [ "NWEB_CAMERA_ENABLE" ] + + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "camera_framework:camera_framework", + "drivers_interface_camera:metadata", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "webview:libnweb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":VideoCaptureRangeAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/videocapturerangeadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/videocapturerangeadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5131afaa504d7e03946d6c09a7d964b75f99a44 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/videocapturerangeadapter_fuzzer.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "videocapturerangeadapter_fuzzer.h" + +#define private public +#include "camera_manager_adapter_impl.h" +#include "video_capture_range_adapter_impl.cpp" +#include "video_capture_range_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + +bool VideoCaptureRangeAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::VideoCaptureRangeAdapterImpl adapter; + adapter.SetMin(0.0); + adapter.SetMax(1.0); + adapter.SetStep(1.0); + adapter.SetCurrent(0.0); + + adapter.GetMin(); + adapter.GetMax(); + adapter.GetStep(); + adapter.GetCurrent(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::VideoCaptureRangeAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/videocapturerangeadapter_fuzzer.h b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/videocapturerangeadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..eafd78272f5fe82b41e11f16c1bc3d66ea3d1067 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocapturerangeadapter_fuzzer/videocapturerangeadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H +#define TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H + +#define FUZZ_PROJECT_NAME "videocapturerangeadapter_fuzzer" +#endif /* TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2659af36cf5a6389535f915fc724e1bcc447a8b6 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("VideoControlSupportAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/camera_adapter/include", + "$webview_path/ohos_adapter/camera_adapter/src", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "videocontrolsupportadapter_fuzzer.cpp" ] + + defines = [ "NWEB_CAMERA_ENABLE" ] + + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "camera_framework:camera_framework", + "drivers_interface_camera:metadata", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "webview:libnweb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":VideoControlSupportAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/videocontrolsupportadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/videocontrolsupportadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53b7f7b281f5d802cc46d55bec640ec07908f1db --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/videocontrolsupportadapter_fuzzer.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "videocontrolsupportadapter_fuzzer.h" + +#define private public +#include "camera_device.h" +#include "camera_manager.h" +#include "camera_manager_adapter_impl.h" +#include "nweb_surface_adapter.h" +#include "video_control_support_adapter_impl.cpp" +#include "video_control_support_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + +bool VideoControlSupportAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::VideoControlSupportAdapterImpl adapter; + adapter.SetPan(true); + adapter.SetTilt(true); + adapter.SetZoom(true); + + // 获取adapter的值并忽略它们 + adapter.GetPan(); + adapter.GetTilt(); + adapter.GetZoom(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::VideoControlSupportAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/videocontrolsupportadapter_fuzzer.h b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/videocontrolsupportadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..bb8e23092d42ce7fb675ada4e592821630db7819 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videocontrolsupportadapter_fuzzer/videocontrolsupportadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H +#define TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H + +#define FUZZ_PROJECT_NAME "videocontrolsupportadapter_fuzzer" +#endif /* TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cf761f3351f9dbbafb85d773172f8203f156112b --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("VideoDeviceDescriptorAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/camera_adapter/include", + "$webview_path/ohos_adapter/camera_adapter/src", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "videodevicedescriptoradapter_fuzzer.cpp" ] + + defines = [ "NWEB_CAMERA_ENABLE" ] + + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "camera_framework:camera_framework", + "drivers_interface_camera:metadata", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "webview:libnweb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":VideoDeviceDescriptorAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/videodevicedescriptoradapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/videodevicedescriptoradapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa1473ebf5948e98df115ed377927b0b8017a0df --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/videodevicedescriptoradapter_fuzzer.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "videodevicedescriptoradapter_fuzzer.h" + +#define private public +#include "camera_manager_adapter_impl.h" +#include "nweb_surface_adapter.h" +#include "video_device_descriptor_adapter_impl.cpp" +#include "video_device_descriptor_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + +bool VideoDeviceDescriptorAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + VideoDeviceDescriptorAdapterImpl adapter; + std::string name((const char*)data, size); + std::string deviceId((const char*)data, size); + std::string modelId((const char*)data, size); + adapter.SetDisplayName(name); + adapter.SetDeviceId(deviceId); + adapter.SetModelId(modelId); + + adapter.SetTransportType(VideoTransportType::VIDEO_TRANS_TYPE_USB); + + adapter.SetFacingMode(VideoFacingModeAdapter::FACING_USER); + + adapter.GetDisplayName(); + adapter.GetDeviceId(); + adapter.GetModelId(); + adapter.GetControlSupport(); + adapter.GetTransportType(); + adapter.GetFacingMode(); + adapter.GetSupportCaptureFormats(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::VideoDeviceDescriptorAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/videodevicedescriptoradapter_fuzzer.h b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/videodevicedescriptoradapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..368b2f2772a3e04387b5ffd3d192df0103c46a69 --- /dev/null +++ b/test/fuzztest/ohos_adapter/camera_adapter/videodevicedescriptoradapter_fuzzer/videodevicedescriptoradapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H +#define TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H + +#define FUZZ_PROJECT_NAME "videodevicedescriptoradapter_fuzzer" +#endif /* TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/cert_mgr_adapter/getcertmaxsize_fuzzer/getcertmaxsize_fuzzer.cpp b/test/fuzztest/ohos_adapter/cert_mgr_adapter/getcertmaxsize_fuzzer/getcertmaxsize_fuzzer.cpp index b46b09cc617ea5ab69eae2e37e9e3861cedd9b22..aeb944ff74621d161a0abc259bd274758ec48887 100644 --- a/test/fuzztest/ohos_adapter/cert_mgr_adapter/getcertmaxsize_fuzzer/getcertmaxsize_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/cert_mgr_adapter/getcertmaxsize_fuzzer/getcertmaxsize_fuzzer.cpp @@ -20,18 +20,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool GetCertMaxSizeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size <= 0)) { - return false; - } - CertManagerAdapterImpl cerImpl; - cerImpl.GetCertMaxSize(); - cerImpl.GetAppCertMaxSize(); - cerImpl.GetSytemRootCertData(0, const_cast(data)); - return true; +bool GetCertMaxSizeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size <= 0)) { + return false; } + CertManagerAdapterImpl cerImpl; + cerImpl.GetCertMaxSize(); + cerImpl.GetAppCertMaxSize(); + cerImpl.GetSytemRootCertData(0, const_cast(data)); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/cert_mgr_adapter/getusercertdata_fuzzer/getusercertdata_fuzzer.cpp b/test/fuzztest/ohos_adapter/cert_mgr_adapter/getusercertdata_fuzzer/getusercertdata_fuzzer.cpp index 0369bafc3626655c3008a343a31e30f2343515f5..fe6ff389f46228c8344a90b51d71c33c3ee99c35 100644 --- a/test/fuzztest/ohos_adapter/cert_mgr_adapter/getusercertdata_fuzzer/getusercertdata_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/cert_mgr_adapter/getusercertdata_fuzzer/getusercertdata_fuzzer.cpp @@ -20,17 +20,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool GetUserCertDataFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size <= 0)) { - return false; - } - CertManagerAdapterImpl cerImpl; - uint32_t certSum = cerImpl.GetUserRootCertSum(); - cerImpl.GetUserRootCertData(certSum, const_cast(data)); - return true; +bool GetUserCertDataFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size <= 0)) { + return false; } + CertManagerAdapterImpl cerImpl; + uint32_t certSum = cerImpl.GetUserRootCertSum(); + cerImpl.GetUserRootCertData(certSum, const_cast(data)); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8271591d2cae6bd2d18e2107fb17fa748252c83b --- /dev/null +++ b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("DataShareAdapterFuzzer") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/datashareadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/datashare_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "datashare_adapter_impl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":DataShareAdapterFuzzer", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/datashare_adapter_impl_fuzzer.cpp b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/datashare_adapter_impl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d55c9a02163e818a40310678daa128dfced06f7 --- /dev/null +++ b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/datashare_adapter_impl_fuzzer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "datashare_adapter_impl_fuzzer.h" + +#include +#include +#include + +#include "base/web/webview/ohos_adapter/datashare_adapter/include/datashare_adapter_impl.h" + +namespace OHOS::NWeb { + +bool DatashareAdapterFuzzTest(const uint8_t* data, size_t size) +{ + std::string uriString(reinterpret_cast(data), size); + + DatashareAdapterImpl& adapter = DatashareAdapterImpl::GetInstance(); + + adapter.GetRealPath(uriString); + + adapter.OpenDataShareUriForRead(uriString); + + adapter.GetFileDisplayName(uriString); + + return true; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::NWeb::DatashareAdapterFuzzTest(data, size); + return 0; +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/datashare_adapter_impl_fuzzer.h b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/datashare_adapter_impl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..725c1636b5af5db89792e66669f857adf682043e --- /dev/null +++ b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/datashare_adapter_impl_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_DATASHAREADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_DATASHAREADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "datashareadapterimpl_fuzzer" + +#endif /* TEST_FUZZTEST_DATASHAREADAPTERIMPL_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/datashareadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b5a94ef3840916d98c71585072f231d9f5d98f71 --- /dev/null +++ b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("DateTimeFormatAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/datetimeformat_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/date_time_format_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "datetimeformatadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "time_service:time_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":DateTimeFormatAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/datetimeformatadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/datetimeformatadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e82ea3e4b10f9f11c6acde267f791e566f049797 --- /dev/null +++ b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/datetimeformatadapterimpl_fuzzer.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "datetimeformatadapterimpl_fuzzer.h" + +#define private public +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscriber.h" +#include "date_time_format_adapter_impl.h" +#include "time_service_client.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +namespace { +bool g_commonEvent = false; +bool g_unCommonEvent = false; +using Want = OHOS::AAFwk::Want; +} // namespace +namespace EventFwk { +bool CommonEventManager::SubscribeCommonEvent(const std::shared_ptr& subscriber) +{ + return g_commonEvent; +} + +bool CommonEventManager::UnSubscribeCommonEvent(const std::shared_ptr& subscriber) +{ + return g_unCommonEvent; +} +} // namespace EventFwk +namespace NWeb { +class MockTimezoneEventCallbackAdapter : public TimezoneEventCallbackAdapter { +public: + MockTimezoneEventCallbackAdapter() = default; + void TimezoneChanged(std::shared_ptr info) {} +}; + +bool DateTimeFormatAdapterFuzzTest(const uint8_t* data, size_t size) +{ + EventFwk::CommonEventSubscribeInfo in; + std::shared_ptr cb = std::make_shared(); + auto adapter = std::make_shared(in, cb); + Want want; + want.SetAction("test"); + EventFwk::CommonEventData newdata(want); + adapter->OnReceiveEvent(newdata); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); + newdata.SetWant(want); + adapter->OnReceiveEvent(newdata); + adapter->eventCallback_ = nullptr; + adapter->OnReceiveEvent(newdata); + + auto newadapter = std::make_shared(); + std::shared_ptr newcb = std::make_shared(); + newadapter->RegTimezoneEvent(std::move(newcb)); + bool newresult = newadapter->StartListen(); + g_commonEvent = true; + newresult = newadapter->StartListen(); + newadapter->StopListen(); + g_unCommonEvent = true; + newadapter->StopListen(); + newadapter->StopListen(); + std::string timeZoneNicosia(""); + OHOS::MiscServices::TimeServiceClient::GetInstance()->SetTimeZone(timeZoneNicosia); + auto timeStr = newadapter->GetTimezone(); + return true; +} +} // namespace NWeb +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::NWeb::DateTimeFormatAdapterFuzzTest(data, size); + return 0; +} +} // namespace OHOS \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/datetimeformatadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/datetimeformatadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..8f7ee8158ac584381f8e58eb1b441c87b066c73b --- /dev/null +++ b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/datetimeformatadapterimpl_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_DATETIMEFORMATADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_DATETIMEFORMATADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "datetimeformatadapterimpl_fuzzer" + +#endif /* TEST_FUZZTEST_DATETIMEFORMATADAPTERIMPL_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/project.xml b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/datetimeformat_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.cpp index 64a632e8f23ebf63f2996738acb6c8bd5d3e2a00..93a679c04a332a37daba565bff9beb744c33acdd 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.cpp @@ -25,17 +25,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool ConvertOrientationFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.ConvertOrientationType(Orientation::UNSPECIFIED); - return true; +bool ConvertOrientationFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.ConvertOrientationType(Orientation::UNSPECIFIED); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.h index ec3220bdae4400562de02f310631610e9e24f835..6c024dd3a2c31280faf1b14ed6989a82fe26ca89 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/convertorientation_fuzzer/convertorientation_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "convertorientation_fuzzer" #endif /* TEST_FUZZTEST_CONVERT_ORIENTATION_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.cpp index 428ff21c4acdbd6f2e44685e1217227b9bcd6dbe..fdd591f6e2056a426c6dfb71bc0262414cb129ed 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.cpp @@ -25,17 +25,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool ConvertRotationFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.ConvertRotationType(Rotation::ROTATION_0); - return true; +bool ConvertRotationFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.ConvertRotationType(Rotation::ROTATION_0); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.h index b9e79993a325ad0f05f6a1e1acc1b0eb4615e55a..6ddbaecfaed7c9ac1deef26061ef1bb4b777f530 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/convertrotation_fuzzer/convertrotation_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "convertrotation_fuzzer" #endif /* TEST_FUZZTEST_CONVERT_ROTATION_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.cpp index 93acf8000b10acf4c287cd3635b6f2e69ac1ebcc..31add66d4518588baa58b1d0a477f40027fb4c5d 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool DisplayChangeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr listener =nullptr; - DisplayListenerAdapterImpl display(listener); - display.OnChange(static_cast(1)); - return true; +bool DisplayChangeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr listener = nullptr; + DisplayListenerAdapterImpl display(listener); + display.OnChange(static_cast(1)); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.h index e140d8fb33d4b4abc98e4a0b9b8703ab61672d86..54ee283899ecca01420fa01ed8e4eb45e935de19 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/displaychange_fuzzer/displaychange_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "displaychange_fuzzer" #endif /* TEST_FUZZTEST_DISPLAY_CHANGE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.cpp index eb544055dc9d58ae37c64ae42f6c07f9d3068590..ee10d906b53062e3e6ca86963903fd8d55823aeb 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool DisplayCreateFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr listener =nullptr; - DisplayListenerAdapterImpl display(listener); - display.OnCreate(static_cast(1)); - return true; +bool DisplayCreateFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr listener = nullptr; + DisplayListenerAdapterImpl display(listener); + display.OnCreate(static_cast(1)); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.h index 4c4d2cf03ce041533ed908b50feed4954f83c13b..5fb0d9e6ad0715ba17a43a18c3c3a0612eddd08f 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/displaycreate_fuzzer/displaycreate_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "displaycreate_fuzzer" #endif /* TEST_FUZZTEST_DISPLAY_CREATE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.cpp index b357955964346ea3f797206dc66ff6be9b82da1b..f32accd5c197be8cc0c0397c8a7a99fc8701541b 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool DisplayDestroyFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr listener =nullptr; - DisplayListenerAdapterImpl display(listener); - display.OnDestroy(static_cast(1)); - return true; +bool DisplayDestroyFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr listener = nullptr; + DisplayListenerAdapterImpl display(listener); + display.OnDestroy(static_cast(1)); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.h index 15859e1f5e8b2238d863b171ea01c8349412cd40..dff4dc859dc1e7f9e0d3aa6467fcec8c7fb0e4a5 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/displaydestroy_fuzzer/displaydestroy_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "displaydestroy_fuzzer" #endif /* TEST_FUZZTEST_DISPLAY_DESTROY_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.cpp index b16e90093004c986c216eb4dddb64e325e873838..39ef08f54556cfa2d5688f2989c82fef39091f92 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.cpp @@ -24,16 +24,16 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetDisplayFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - DisplayManagerAdapterImpl display; - display.GetDefaultDisplay(); - return true; +bool GetDisplayFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + DisplayManagerAdapterImpl display; + display.GetDefaultDisplay(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.h index c78fd8ad8bd47ceff5ae484283aae9ee6847b4d9..02145be119ae9856261dd8fce7d31e1ff3b664a0 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getdisplay_fuzzer/getdisplay_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getdisplay_fuzzer" #endif /* TEST_FUZZTEST_GET_DISPLAY_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.cpp index a57f58cdb09619ff3f3f15d557a2ff19974fdcd3..aaa1dad6e8dd382ab3fe4cf5dfc7f99c611ffeab 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.cpp @@ -24,16 +24,16 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetDisplayIdFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - DisplayManagerAdapterImpl display; - display.GetDefaultDisplayId(); - return true; +bool GetDisplayIdFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + DisplayManagerAdapterImpl display; + display.GetDefaultDisplayId(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.h index 517ffd8d7a5603cab23ae2b81ca491eb7e0afc83..fed53b746cfb53ecfe3a8d429248d06c8d294a61 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getdisplayid_fuzzer/getdisplayid_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getdisplayid_fuzzer" #endif /* TEST_FUZZTEST_GET_DISPLAY_ID_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.cpp index e7d695c564cf036a3efd92b9d62c5adede1f31ef..3059a8ba5e228cc69aca8e729e1c4f723bc5bd6f 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetHeightFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.GetHeight(); - return true; +bool GetHeightFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.GetHeight(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.h index 97a6d9fe2a99d3b684c72c6594cfe6c056e67c72..66f25acc5b7617fc07fd6f2044f8e2b310ad94c6 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getheight_fuzzer/getheight_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getheight_fuzzer" #endif /* TEST_FUZZTEST_GET_HEIGHT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.cpp index bd10d30de638a9bf5f141f14560079a815d750c8..1d1604539d17ddabbe0baff992eee45062132c95 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetOrientationFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.GetOrientation(); - return true; +bool GetOrientationFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.GetOrientation(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.h index b1e32ed82e4e204564ef8585d79d931dd57b6a64..171fdb7a385a64a50bc66fdc67f8072c12651c89 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getorientation_fuzzer/getorientation_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getorientation_fuzzer" #endif /* TEST_FUZZTEST_GET_ORIENTATION_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.cpp index 6297af74758ff5d277d47373d0c553caed1c75db..4d065a0d7f9c3c757ca0919cc63659d629d774ce 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetRotationFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.GetRotation(); - return true; +bool GetRotationFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.GetRotation(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.h index 543de6198ba41dcdf58c7301b07184ac24baa918..cf5266c8725eef956b68f592559d92768e19eda3 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getrotation_fuzzer/getrotation_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getrotation_fuzzer" #endif /* TEST_FUZZTEST_GET_ROTATION_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.cpp index ea90544caac5b10de4f6f850708b2bada0f4a6a4..91cbe6875be5c9cb9d20d0d902c7734d8272656f 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetVirtualFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.GetVirtualPixelRatio(); - return true; +bool GetVirtualFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.GetVirtualPixelRatio(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.h index 104a7df12d8a2fc96e6e48815a3deaafdb0bbd35..fd4a122187cc54eeb593bacbf48adb732f6f7a25 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getvirtual_fuzzer/getvirtual_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getvirtual_fuzzer" #endif /* TEST_FUZZTEST_GET_VIRTUAL_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.cpp index cefc7e32a0a0f097c2a973f564f5449fa0cc35b7..f993299cc34a4de0e3e320e040fa6aeada6c3c09 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.cpp @@ -24,17 +24,17 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool GetWidthFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - sptr listener =nullptr; - DisplayAdapterImpl display(listener); - display.GetWidth(); - return true; +bool GetWidthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + sptr listener = nullptr; + DisplayAdapterImpl display(listener); + display.GetWidth(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.h index 5cdbd5d1621aebb497db7a2234dad1ed87f685fe..a41cc59f0d4fe7d7ebe6c29075aabd83f609b45e 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/getwidth_fuzzer/getwidth_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getwidth_fuzzer" #endif /* TEST_FUZZTEST_GET_WIDTH_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.cpp index 5bfc0614b6385c87a0315361b600b912b961ad07..1cd5f815a734f41b7571bca5dc4c400ffbfc4594 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.cpp @@ -24,18 +24,18 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool RegisterDisplayFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - DisplayManagerAdapterImpl display; - std::shared_ptr listener =nullptr; - uint32_t id = display.RegisterDisplayListener(listener); - display.UnregisterDisplayListener(id); - return true; +bool RegisterDisplayFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + DisplayManagerAdapterImpl display; + std::shared_ptr listener = nullptr; + uint32_t id = display.RegisterDisplayListener(listener); + display.UnregisterDisplayListener(id); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.h index 3cfc5fa48a4147d729eab0b1b6e8e1cf79eb9bbf..16ff46e418d44e2798b17704fb61c5a324378cf7 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/registerdisplay_fuzzer/registerdisplay_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "registerdisplay_fuzzer" #endif /* TEST_FUZZTEST_REGISTER_DISPLAY_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.cpp b/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.cpp index f219d5dd3c8872123824788b84c15e2117b137cc..99d221dd4cac449dd92782c024f4b0e61d7b6a28 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.cpp @@ -24,16 +24,16 @@ using namespace OHOS::NWeb; using namespace OHOS::Rosen; namespace OHOS { - bool UnregisterDisplayFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - DisplayManagerAdapterImpl display; - display.UnregisterDisplayListener(0); - return true; +bool UnregisterDisplayFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + DisplayManagerAdapterImpl display; + display.UnregisterDisplayListener(0); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.h b/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.h index 7f42ac27d9994f1420fedf7d546006964dc66873..7e578462522752228393eea7b0dcd456cc786822 100644 --- a/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.h +++ b/test/fuzztest/ohos_adapter/display_adapter/unregisterdisplay_fuzzer/unregisterdisplay_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "unregisterdisplay_fuzzer" #endif /* TEST_FUZZTEST_UNREGISTER_DISPLAY_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.cpp index 333fcd1cdf49f494e411b029149105269b69a169..bfb3a3e0284edb61250905aee361433413cc0e94 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.cpp @@ -23,16 +23,16 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ClearAllPermissionFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - WebPermissionType key = WebPermissionType::GEOLOCATION; - OhosWebPermissionDataBaseAdapterImpl::GetInstance().ClearAllPermission(key); - return true; +bool ClearAllPermissionFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + WebPermissionType key = WebPermissionType::GEOLOCATION; + OhosWebPermissionDataBaseAdapterImpl::GetInstance().ClearAllPermission(key); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.h index 50c39a809dc25000b88d9af7c15d72cf5be79f35..74700cf38623eb0a1c7a061361fb2cad1dc32b2b 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearallpermission_fuzzer/clearallpermission_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "clearallpermission_fuzzer" #endif /* TEST_FUZZTEST_CLEAR_ALL_PERMISSION_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.cpp index fe6b42e17cac0ebae547c22de2d288c2433a5e2e..a7d3b01dfb2c60727c7c036b67fbcdf521701f83 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.cpp @@ -23,17 +23,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ClearPermissionByOriginFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string origin((const char *)data, size); - WebPermissionType key = WebPermissionType::GEOLOCATION; - OhosWebPermissionDataBaseAdapterImpl::GetInstance().ClearPermissionByOrigin(origin, key); - return true; +bool ClearPermissionByOriginFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string origin((const char*)data, size); + WebPermissionType key = WebPermissionType::GEOLOCATION; + OhosWebPermissionDataBaseAdapterImpl::GetInstance().ClearPermissionByOrigin(origin, key); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.h index cc703c3aa074d1447207b1474ebba721d66698cf..5bb96c37444a21876160b4e940e27ab0ffd0c05d 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/clearpermissionbyorigin_fuzzer/clearpermissionbyorigin_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "clearpermissionbyorigin_fuzzer" #endif /* TEST_FUZZTEST_CLEAR_PERMISSION_BY_ORIGIN_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.cpp index 96978691977e7255804d01d098cb78ea4bb7fe7e..398cfb441010cb5d6e5787409be210756349235f 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.cpp @@ -25,28 +25,28 @@ using namespace OHOS::NWeb; using namespace OHOS::NativeRdb; namespace OHOS { - bool DatabaseOnCreateFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string name = "web_test.db"; - std::string bundleName = "com.example"; - std::string databaseDir = "/data"; - int32_t errorCode = E_OK; - std::string realPath = RdbSqlUtils::GetDefaultDatabasePath(databaseDir, name, errorCode); - RdbStoreConfig config(""); - config.SetPath(std::move(realPath)); - config.SetBundleName(bundleName); - config.SetName(std::move(name)); - config.SetArea(1); - errorCode = NativeRdb::E_OK; - DataBaseRdbOpenCallBack callBack; - auto rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, callBack, errorCode); - callBack.OnCreate(*(rdbStore.get())); - return true; +bool DatabaseOnCreateFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string name = "web_test.db"; + std::string bundleName = "com.example"; + std::string databaseDir = "/data"; + int32_t errorCode = E_OK; + std::string realPath = RdbSqlUtils::GetDefaultDatabasePath(databaseDir, name, errorCode); + RdbStoreConfig config(""); + config.SetPath(std::move(realPath)); + config.SetBundleName(bundleName); + config.SetName(std::move(name)); + config.SetArea(1); + errorCode = NativeRdb::E_OK; + DataBaseRdbOpenCallBack callBack; + auto rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, callBack, errorCode); + callBack.OnCreate(*(rdbStore.get())); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.h index 7c6128861e780b78bc40dd81bb22f874628e280e..dcaec84d4062effd179ba9c8d4c63d690744724a 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/databaseoncreate_fuzzer/databaseoncreate_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "databaseoncreate_fuzzer" #endif /* TEST_FUZZTEST_DATABASE_ON_CREATE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.cpp index be3fe2e5cf1d04a5a47b48df36d8d969434a0c25..10a80021026845e57e16a4ab1eec5c4549b8bcc2 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.cpp @@ -23,15 +23,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool DeleteHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosWebDataBaseAdapterImpl::GetInstance().DeleteHttpAuthCredentials(); - return true; +bool DeleteHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosWebDataBaseAdapterImpl::GetInstance().DeleteHttpAuthCredentials(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.h index 602b8cc1066d7347035a7da7ec719eaa6caef82d..8f6bcf36bf267b186bc1342e5750a43817fa009a 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/deletehttpauthcredentials_fuzzer/deletehttpauthcredentials_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "deletehttpauthcredentials_fuzzer" #endif /* TEST_FUZZTEST_DELETE_HTTP_AUTH_CREDENTIALS_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.cpp index 591ff8f04de6a005869f1c323fd6b712a5d35ddd..b84c3f3b20226836fddd595fc344b469a323daaf 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.cpp @@ -23,15 +23,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ExistHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosWebDataBaseAdapterImpl::GetInstance().ExistHttpAuthCredentials(); - return true; +bool ExistHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosWebDataBaseAdapterImpl::GetInstance().ExistHttpAuthCredentials(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.h index bb2cd9c57d81e6af2b885909523e9fe7d337c81a..165472f1aeef755d16f026d6c6d3166b96631125 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existhttpauthcredentials_fuzzer/existhttpauthcredentials_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "existhttpauthcredentials_fuzzer" #endif /* TEST_FUZZTEST_EXIST_HTTP_AUTH_CREDENTIALS_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.cpp index 3c0e0b3dda9228f359b9df301ec67dc667a8ecd8..9adaf055e24c313085cf962d8675e47c8ce2ecee 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.cpp @@ -23,17 +23,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ExistPermissionByOriginFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string origin((const char *)data, size); - WebPermissionType key = WebPermissionType::GEOLOCATION; - OhosWebPermissionDataBaseAdapterImpl::GetInstance().ExistPermissionByOrigin(origin, key); - return true; +bool ExistPermissionByOriginFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string origin((const char*)data, size); + WebPermissionType key = WebPermissionType::GEOLOCATION; + OhosWebPermissionDataBaseAdapterImpl::GetInstance().ExistPermissionByOrigin(origin, key); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.h index c5d47131febe416b44cfcf29e4c592348f0b4226..9c651b19e404f32073d791d5c1eb594fb1de9247 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/existpermissionbyorigin_fuzzer/existpermissionbyorigin_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "existpermissionbyorigin_fuzzer" #endif /* TEST_FUZZTEST_EXIST_PERMISSION_BY_ORIGIN_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.cpp index dbaaf40679fbb90a28c1c9be8d53b285115e96ed..adea276fca8ce7b137b6df6ff7b0e7be21690d28 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.cpp @@ -23,21 +23,21 @@ using namespace OHOS::NWeb; namespace OHOS { - bool GetHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) - { - constexpr int32_t maxLen = 256; - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string host((const char *)data, size); - std::string realm((const char *)data, size); - std::string username; - char password[maxLen + 1] = {0}; - OhosWebDataBaseAdapterImpl::GetInstance().GetHttpAuthCredentials(host, realm, username, password, maxLen + 1); - (void)memset_s(password, maxLen + 1, 0, maxLen + 1); - return true; +bool GetHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) +{ + constexpr int32_t maxLen = 256; + if ((data == nullptr) || (size == 0)) { + return false; } + std::string host((const char*)data, size); + std::string realm((const char*)data, size); + std::string username; + char password[maxLen + 1] = { 0 }; + OhosWebDataBaseAdapterImpl::GetInstance().GetHttpAuthCredentials(host, realm, username, password, maxLen + 1); + (void)memset_s(password, maxLen + 1, 0, maxLen + 1); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.h index 914e9b419cfaa17f9d57354eed6fc45a017368e1..4334f296b4594cab994f3f9894346396ec1d8664 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/gethttpauthcredentials_fuzzer/gethttpauthcredentials_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "gethttpauthcredentials_fuzzer" #endif /* TEST_FUZZTEST_GET_HTTP_AUTH_CREDENTIALS_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.cpp index b34d74681b9cfc18d66e9fe9a36f6c0ed551391f..d22088d22771b2f14ff0744eff563a83f63ff179 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.cpp @@ -23,21 +23,21 @@ using namespace OHOS::NWeb; namespace OHOS { - bool GetOriginByPermissionFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - WebPermissionType key = WebPermissionType::GEOLOCATION; - std::vector origins; - std::string origin1((const char *)data, size); - std::string origin2((const char *)data, size); - origins.push_back(origin1); - origins.push_back(origin2); - OhosWebPermissionDataBaseAdapterImpl::GetInstance().GetOriginsByPermission(key, origins); - return true; +bool GetOriginByPermissionFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + WebPermissionType key = WebPermissionType::GEOLOCATION; + std::vector origins; + std::string origin1((const char*)data, size); + std::string origin2((const char*)data, size); + origins.push_back(origin1); + origins.push_back(origin2); + OhosWebPermissionDataBaseAdapterImpl::GetInstance().GetOriginsByPermission(key, origins); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.h index 4c7216b2147f3454550045132f73de7b4be1ab30..d2dc37b98f753a44f1e7b50210d44f2ee5609d0a 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getoriginbypermission_fuzzer/getoriginbypermission_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getoriginbypermission_fuzzer" #endif /* TEST_FUZZTEST_GET_ORIGIN_BY_PERMISSION_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.cpp index 4fa2ac033012d3caa0a01c73da74d2267ec25ef3..18e7fd7bf92e9af28f513cb8e6874af241ff7bb4 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.cpp @@ -23,18 +23,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool GetPermissionResultByOriginFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string origin((const char *)data, size); - WebPermissionType key = WebPermissionType::GEOLOCATION; - bool result = true; - OhosWebPermissionDataBaseAdapterImpl::GetInstance().GetPermissionResultByOrigin(origin, key, result); - return true; +bool GetPermissionResultByOriginFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string origin((const char*)data, size); + WebPermissionType key = WebPermissionType::GEOLOCATION; + bool result = true; + OhosWebPermissionDataBaseAdapterImpl::GetInstance().GetPermissionResultByOrigin(origin, key, result); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.h index 55e8fa8b652c8f89fab0760d1fd450388674ef62..3a13732ce86ae84720114e7cf84f581208c66567 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/getpermissionresultbyorigin_fuzzer/getpermissionresultbyorigin_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getpermissionresultbyorigin_fuzzer" #endif /* TEST_FUZZTEST_GET_PERMISSION_RESULT_BY_ORIGIN_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.cpp index c29f92b568e2423aadced5406562f685bbd717ed..68c91d21d8299b52b200d27e525005a468a0ff1b 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.cpp @@ -24,16 +24,16 @@ using namespace OHOS::NWeb; namespace OHOS { - bool KeyToTableNameFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosWebPermissionDataBaseAdapterImpl dataBase; - dataBase.KeyToTableName(WebPermissionType::GEOLOCATION); - return true; +bool KeyToTableNameFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosWebPermissionDataBaseAdapterImpl dataBase; + dataBase.KeyToTableName(WebPermissionType::GEOLOCATION); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.h index c771f113e2d296e38dc54e789af1a221627fb166..b582267e07d1461d1c377944e152ec233c3259d1 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/keytotablename_fuzzer/keytotablename_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "keytotablename_fuzzer" #endif /* TEST_FUZZTEST_KEY_TO_TABLE_NAME_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.cpp index 694b152950a460868e6099ab8ace6b1ba7e10653..6c36c4dcc7548415862edb5891f5a01d407d5f24 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.cpp @@ -24,18 +24,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool PmsCreateDataBaseFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string dataBeseName((const char *)data, size); - PermissionDataBaseRdbOpenCallBack callBack; - OhosWebPermissionDataBaseAdapterImpl dataBase; - dataBase.CreateDataBase(dataBeseName, callBack); - return true; +bool PmsCreateDataBaseFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string dataBeseName(reinterpret_cast(data), size); + PermissionDataBaseRdbOpenCallBack callBack; + OhosWebPermissionDataBaseAdapterImpl dataBase; + dataBase.CreateDataBase(dataBeseName, callBack); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.h index 679be35d2acbaf4684b968edfeb08219ba4a79d6..8c8ae8f2e80ad2a75f5d26d352bb4e79592f8314 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmscreatedatabase_fuzzer/pmscreatedatabase_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "pmscreatedatabase_fuzzer" #endif /* TEST_FUZZTEST_PMS_CREATE_DATABASE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.cpp index 674203706da2029b7fcf15de3d380496ca2ef99b..a482d955576c8be1e94dad139feec7c985c3b4a6 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.cpp @@ -25,28 +25,28 @@ using namespace OHOS::NWeb; using namespace OHOS::NativeRdb; namespace OHOS { - bool PmsDatabaseOnCreateFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string name = "web_test.db"; - std::string bundleName = "com.example"; - std::string databaseDir = "/data"; - int32_t errorCode = E_OK; - std::string realPath = RdbSqlUtils::GetDefaultDatabasePath(databaseDir, name, errorCode); - RdbStoreConfig config(""); - config.SetPath(std::move(realPath)); - config.SetBundleName(bundleName); - config.SetName(std::move(name)); - config.SetArea(1); - errorCode = NativeRdb::E_OK; - PermissionDataBaseRdbOpenCallBack callBack; - auto rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, callBack, errorCode); - callBack.OnCreate(*(rdbStore.get())); - return true; +bool PmsDatabaseOnCreateFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string name = "web_test.db"; + std::string bundleName = "com.example"; + std::string databaseDir = "/data"; + int32_t errorCode = E_OK; + std::string realPath = RdbSqlUtils::GetDefaultDatabasePath(databaseDir, name, errorCode); + RdbStoreConfig config(""); + config.SetPath(std::move(realPath)); + config.SetBundleName(bundleName); + config.SetName(std::move(name)); + config.SetArea(1); + errorCode = NativeRdb::E_OK; + PermissionDataBaseRdbOpenCallBack callBack; + auto rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, callBack, errorCode); + callBack.OnCreate(*(rdbStore.get())); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.h index f1dc282e4a3e6c4ef5c69638d1fddd9950a63007..b7c65510ed8e9b880924e1347892c273e78a0f7e 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseoncreate_fuzzer/pmsdatabaseoncreate_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "pmsdatabaseoncreate_fuzzer" #endif /* TEST_FUZZTEST_PMS_DATABASE_ON_CREATE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.cpp index 74bd597533d3ae680e2fb0562de5a9bd86c4b9c5..73218c129b156962d3f55d93396fe51d3f84fa37 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.cpp @@ -23,21 +23,21 @@ using namespace OHOS::NWeb; namespace OHOS { - bool PmsDatabaseOnUpgradeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - NativeRdb::RdbStoreConfig config(""); - int32_t errorCode = NativeRdb::E_OK; - PermissionDataBaseRdbOpenCallBack callBack; - auto rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, callBack, errorCode); - int32_t currentVersion = static_cast(size); - int32_t targetVersion = static_cast(size); - callBack.OnUpgrade(*(rdbStore.get()), currentVersion, targetVersion); - return true; +bool PmsDatabaseOnUpgradeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + NativeRdb::RdbStoreConfig config(""); + int32_t errorCode = NativeRdb::E_OK; + PermissionDataBaseRdbOpenCallBack callBack; + auto rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, callBack, errorCode); + int32_t currentVersion = static_cast(size); + int32_t targetVersion = static_cast(size); + callBack.OnUpgrade(*(rdbStore.get()), currentVersion, targetVersion); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.h index 3494ad7c4d602a8695cac60558451c7ad65da697..4cb5ee52bbd6947d0eb368bd9e0ac309f2aa1f3b 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/pmsdatabaseonupgrade_fuzzer/pmsdatabaseonupgrade_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "pmsdatabaseonupgrade_fuzzer" #endif /* TEST_FUZZTEST_PMS_DATABASE_ON_UPGRADE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.cpp index cd1f968fb7d55497c94f0bde061e345870970ee4..67ff34600cae8a5fa489341aa51a92b4b720ef42 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.cpp @@ -23,19 +23,19 @@ using namespace OHOS::NWeb; namespace OHOS { - bool SaveHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string host((const char *)data, size); - std::string realm((const char *)data, size); - std::string name((const char *)data, size); - const char* str = (char *)data; - OhosWebDataBaseAdapterImpl::GetInstance().SaveHttpAuthCredentials(host, realm, name, str); - return true; +bool SaveHttpAuthCredentialsFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string host((const char*)data, size); + std::string realm((const char*)data, size); + std::string name((const char*)data, size); + const char* str = (char*)data; + OhosWebDataBaseAdapterImpl::GetInstance().SaveHttpAuthCredentials(host, realm, name, str); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.h index f55326df5564e2dc64e79b2ef3b3cbb21d8cfb71..36127d3447dd07cdcf1589f11e5c473e91c168c0 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/savehttpauthcredentials_fuzzer/savehttpauthcredentials_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "savehttpauthcredentials_fuzzer" #endif /* TEST_FUZZTEST_SAVE_HTTP_AUTH_CREDENTIALS_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.cpp b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.cpp index 30966cf0a8e64632e47919cd1d1ab68e2db22368..fdd416302949311df8e40180ba49c535288d4303 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.cpp @@ -23,18 +23,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool SetPermissionByOriginFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string origin((const char *)data, size); - WebPermissionType key = WebPermissionType::GEOLOCATION; - bool result = true; - OhosWebPermissionDataBaseAdapterImpl::GetInstance().SetPermissionByOrigin(origin, key, result); - return true; +bool SetPermissionByOriginFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string origin((const char*)data, size); + WebPermissionType key = WebPermissionType::GEOLOCATION; + bool result = true; + OhosWebPermissionDataBaseAdapterImpl::GetInstance().SetPermissionByOrigin(origin, key, result); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.h b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.h index 41d561328e2d18fb2e20c4499a742510ca3e0775..fe85e3f70a8714cd5b006b6f79eff50ff07828e5 100644 --- a/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.h +++ b/test/fuzztest/ohos_adapter/distributeddatamgr_adapter/webdatabase/setpermissionbyorigin_fuzzer/setpermissionbyorigin_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "setpermissionbyorigin_fuzzer" #endif /* TEST_FUZZTEST_SET_PERMISSION_BY_ORIGIN_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5898466bce5707259572b378c97969b960ba4d6c --- /dev/null +++ b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("EnterpriseDeviceManagementAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/enterprise_device_management_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "enterprise_device_management_adapter_impl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":EnterpriseDeviceManagementAdapterFuzzTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/enterprise_device_management_adapter_impl_fuzzer.cpp b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/enterprise_device_management_adapter_impl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2b434bfe739a2b7abcb76ee19b42184ef20f9fb --- /dev/null +++ b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/enterprise_device_management_adapter_impl_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "enterprise_device_management_adapter_impl_fuzzer.h" + +#include "enterprise_device_management_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool EnterpriseDeviceManagementAdapterFuzzTest(const uint8_t* data, size_t size) +{ + std::string policies(reinterpret_cast(data), size); + + EnterpriseDeviceManagementAdapterImpl::GetInstance().RegistPolicyChangeEventCallback(nullptr); + + bool startObserveResult = EnterpriseDeviceManagementAdapterImpl::GetInstance().StartObservePolicyChange(); + + (void)startObserveResult; + + bool stopObserveResult = EnterpriseDeviceManagementAdapterImpl::GetInstance().StopObservePolicyChange(); + + (void)stopObserveResult; + + int32_t getPoliciesResult = EnterpriseDeviceManagementAdapterImpl::GetInstance().GetPolicies(policies); + + (void)getPoliciesResult; + + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::EnterpriseDeviceManagementAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/enterprise_device_management_adapter_impl_fuzzer.h b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/enterprise_device_management_adapter_impl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..36cb92b4e50baa625181b90709310529d1748715 --- /dev/null +++ b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/enterprise_device_management_adapter_impl_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ENTERPRISEDEVICEMANAGEMENTADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_ENTERPRISEDEVICEMANAGEMENTADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "enterprisedevicemanagementadapterimpl_fuzzer" + +#endif /* TEST_FUZZTEST_ENTERPRISEDEVICEMANAGEMENTADAPTERIMPL_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/project.xml b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/enterprisedevicemanagement_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/eventhandler_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0be3811d253c536986fdb485d10dc93266d89d80 --- /dev/null +++ b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("EventHandlerFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/eventhandler_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/event_handler_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "event_handler_adapter_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":EventHandlerFuzzTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/eventhandler_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/eventhandler_fuzzer/event_handler_adapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/event_handler_adapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..675cd50e9fa9b5c6be43a952265f5110d22482c7 --- /dev/null +++ b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/event_handler_adapter_fuzzer.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "event_handler_adapter_fuzzer.h" + +#include +#include +#include + +#include "event_handler_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +class EventHandlerFDListenerAdapterTest : public EventHandlerFDListenerAdapter { +public: + void OnReadable(int32_t fileDescriptor) override {} +}; + +bool EventHandlerAdapterFuzzTest(const uint8_t* data, size_t size) +{ + int32_t fileDescriptor = static_cast(size); + uint32_t events = static_cast(size); + + std::shared_ptr listener = std::make_shared(); + + std::shared_ptr eventHandlerAdapter = std::make_shared(); + + eventHandlerAdapter->AddFileDescriptorListener(fileDescriptor, events, listener); + + auto fdListenerImpl = std::make_shared(listener); + fdListenerImpl->OnReadable(fileDescriptor); + + eventHandlerAdapter->RemoveFileDescriptorListener(fileDescriptor); + + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::EventHandlerAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/eventhandler_fuzzer/event_handler_adapter_fuzzer.h b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/event_handler_adapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d853ca8cd070583ee6a0f229da26f037e8c8c790 --- /dev/null +++ b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/event_handler_adapter_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_EVENTHANDLERADAPTER_FUZZER_H +#define TEST_FUZZTEST_EVENTHANDLERADAPTER_FUZZER_H + +#define FUZZ_PROJECT_NAME "eventhandleradapter_fuzzer" + +#endif /* TEST_FUZZTEST_EVENTHANDLERADAPTER_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/eventhandler_fuzzer/project.xml b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/eventhandler_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bc986fc238f8b4e9d83fa4240ff2c4d4933435da --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("FlowBufferAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/interfaces", + "$webview_path/ohos_adapter/flowbuffer_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "flowbufferadapter_fuzzer.cpp" ] + deps = [ + "$webview_path/ohos_adapter:nweb_ohos_adapter", + "$webview_path/ohos_nweb:libnweb", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":FlowBufferAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e72a00430bb8f9326a36b9d75c54edb3d3e953bf --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapter_fuzzer.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "flowbufferadapter_fuzzer.h" + +#include +#include + +#include "ohos_adapter_helper.h" +#define private public +#include "flowbuffer_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool FlowBufferAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; + } + auto flowbufferAdapter = OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter(); + int fd = 0; + size_t scriptLength = 10; + flowbufferAdapter->CreateAshmem(scriptLength, PROT_READ | PROT_WRITE, fd); + flowbufferAdapter->StartPerformanceBoost(); + close(fd); + + auto flowbufferAdapter1 = OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter(); + int fd1 = 1; + size_t scriptLength1 = 10; + flowbufferAdapter1->CreateAshmemWithFd(fd1, scriptLength1, PROT_READ); + flowbufferAdapter1->StartPerformanceBoost(); + close(fd1); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::FlowBufferAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapter_fuzzer.h b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..5e8da15f74d0fc4e9194cece1dd983191cc7c73b --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_FLOWBUFFERADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_FLOWBUFFERADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "flowbufferadapter_fuzzer" +#endif /* TEST_FUZZTEST_FLOWBUFFERADAPTERIMPL_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..921a5867836aca61ed47f9078d6d31e6f9ad5e5c --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapterimpl_fuzzer.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "flowbufferadapterimpl_fuzzer.h" + +#include +#include + +#include "ohos_adapter_helper.h" +#define private public +#include "flowbuffer_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool ApplyFlowBufferAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; + } + auto flowbufferAdapter = OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter(); + int fd = 0; + size_t scriptLength = 10; + auto ashmem = flowbufferAdapter->CreateAshmem(scriptLength, PROT_READ | PROT_WRITE, fd); + (void)ashmem; + flowbufferAdapter->StartPerformanceBoost(); + + auto flowbufferAdapter1 = OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter(); + int fd1; + size_t scriptLength1 = 10; + flowbufferAdapter1->CreateAshmem(scriptLength1, PROT_READ | PROT_WRITE, fd1); + auto ashmem1 = flowbufferAdapter->CreateAshmemWithFd(fd1, scriptLength1, PROT_READ); + (void)ashmem1; + flowbufferAdapter1->StartPerformanceBoost(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::ApplyFlowBufferAdapterImplFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..3f62df3eb2c24d79334cad8ff7c0b5c55c430c5a --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/flowbufferadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_FLOWBUFDFERADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_FLOWBUFDFERADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "flowbufferadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_FLOWBUFDFERADAPTERIMPL_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/flowbufferadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2b8fe7e67e6b9099e7628edfa42860d8e0f7b490 --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("NativeImageAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/graphic_adapter/include", + "$webview_path/ohos_nweb/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "nativeimageadapter_fuzzer.cpp" ] + + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_runtime:app_manager", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_surface:surface", + "hilog:libhilog", + "relational_store:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":NativeImageAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/nativeimageadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/nativeimageadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d48cca8e7ee06f970a0cee5d7f3a641212cbd7b3 --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/nativeimageadapter_fuzzer.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "nativeimageadapter_fuzzer.h" +#define CAMERA_MANAGER_ADAPTER_IMPL + +#define private public +#include "iconsumer_surface.h" +#include "native_image_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { + +bool NativeImageAdapterFuzzTest(const uint8_t* data, size_t size) +{ + std::shared_ptr imagerAdapter = std::make_shared(); + imagerAdapter->UpdateSurfaceImage(); + imagerAdapter->AquireNativeWindowFromNativeImage(); + imagerAdapter->AttachContext(1); + imagerAdapter->DetachContext(); + uint32_t textureId = 1; + uint32_t textureTarget = 1; + imagerAdapter->CreateNativeImage(textureId, textureTarget); + imagerAdapter->UpdateSurfaceImage(); + imagerAdapter->AquireNativeWindowFromNativeImage(); + imagerAdapter->AttachContext(1); + imagerAdapter->DetachContext(); + imagerAdapter->GetTimestamp(); + float matrix[16] = { 0 }; + imagerAdapter->GetTransformMatrix(matrix); + uint64_t surfaceId = 1; + imagerAdapter->GetSurfaceId(&surfaceId); + imagerAdapter->SetOnFrameAvailableListener(nullptr); + imagerAdapter->UnsetOnFrameAvailableListener(); + imagerAdapter->DestroyNativeImage(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::NativeImageAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/nativeimageadapter_fuzzer.h b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/nativeimageadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e998db53b38bfbbe0da8f84ca86f5f839a9f37b3 --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/nativeimageadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H +#define TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H + +#define FUZZ_PROJECT_NAME "nativeimageadapter_fuzzer" +#endif /* TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/nativeimageadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6f29d0bde1439409f3d3635d08b8fb8eec46083b --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("VsyncAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/graphic_adapter/include", + "$webview_path/ohos_nweb/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "vsyncadapter_fuzzer.cpp" ] + + defines = [ "NWEB_CAMERA_ENABLE" ] + + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_runtime:app_manager", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_surface:surface", + "hilog:libhilog", + "relational_store:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":VsyncAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/vsyncadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/vsyncadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03db3cbe39c487c277eb937dee3075b7454be79d --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/vsyncadapter_fuzzer.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "vsyncadapter_fuzzer.h" + +#include + +#define private public +#include "vsync_adapter_impl.h" +#undef private + +using namespace OHOS::NWeb; + +namespace OHOS { +static void OnVsyncCallback() {} + +bool CameraManagerAdapterFuzzTest(const uint8_t* data, size_t size) +{ + VSyncAdapterImpl& adapter = VSyncAdapterImpl::GetInstance(); + adapter.Init(); + adapter.Init(); + + VSyncAdapterImpl vsyncAdapter; + void* client = nullptr; + adapter.OnVsync(1, client); + client = &vsyncAdapter; + adapter.OnVsync(1, client); + adapter.VsyncCallbackInner(1); + adapter.GetVSyncPeriod(); + adapter.SetFrameRateLinkerEnable(true); + adapter.SetFramePreferredRate(0); + adapter.frameRateLinker_ = nullptr; + adapter.SetFrameRateLinkerEnable(true); + adapter.SetFramePreferredRate(0); + adapter.vsyncHandler_ = nullptr; + adapter.SetOnVsyncCallback(OnVsyncCallback); + adapter.SetOnVsyncEndCallback(OnVsyncCallback); + adapter.OnVsync(1, client); + adapter.SetIsGPUProcess(false); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::CameraManagerAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/vsyncadapter_fuzzer.h b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/vsyncadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..ece410e142e574f6b51c2faba5e5f4aa00e980c0 --- /dev/null +++ b/test/fuzztest/ohos_adapter/graphic_adapter/vsyncadapter_fuzzer/vsyncadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H +#define TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H + +#define FUZZ_PROJECT_NAME "cameramanageradapter_fuzzer" +#endif /* TEST_FUZZTEST_GETCERTMASIZE_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.cpp index 4e73d428ab8ecb84ec673c4f407d8441cf25e224..eb0a5cc9cfc667b75f3c7560b919b6f97614f372 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.cpp @@ -22,16 +22,16 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateAafwkFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - auto &helper = OhosAdapterHelper::GetInstance(); - helper.CreateAafwkAdapter(); - return true; +bool CreateAafwkFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + auto& helper = OhosAdapterHelper::GetInstance(); + helper.CreateAafwkAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.h index 773f3d28d4d8cceffec243f29e0d39d1e0d07ce6..a972192d139cff197be4fbbf5d805f6e08841bc7 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createaafwk_fuzzer/createaafwk_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createaafwk_fuzzer" #endif /* TEST_FUZZTEST_CREATE_AAFWK_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.cpp index 2e10dda173850d19b088e71019efe8f21e10b755..5bc412b53f19f5c15f4a51c10c8701d0538fa365 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateAudioRenderFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().CreateAudioRendererAdapter(); - return true; +bool CreateAudioRenderFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().CreateAudioRendererAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.h index 3f1ae4d36967d639d07678420b10cb8fd32a68e4..0cb93c3c5a0b87e5ca8686c10458986db63c8fd5 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createaudiorender_fuzzer/createaudiorender_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createaudiorender_fuzzer" #endif /* TEST_FUZZTEST_CREATE_AUDIO_RENDER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.cpp index b3b67c254869bcac8f84ae6527643658e62b5580..9ba702b5ab1b18ddaacb114d93975658abc76456 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateAudioSystemFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().GetAudioSystemManager(); - return true; +bool CreateAudioSystemFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().GetAudioSystemManager(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.h index 3d3f0f5940c6149de213a4f0a6aa28326b5caf05..701efa2ada0aeea61438571649389b069fbbcacc 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createaudiosystem_fuzzer/createaudiosystem_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createaudiosystem_fuzzer" #endif /* TEST_FUZZTEST_CREATE_AUDIO_SYSTEM_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.cpp index 2da433b69b085e1958464ca508ba11500f30e113..e5c9cb4bc3f8ff61e97238cd4ae43f57ce69a550 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateDisplayMgrFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().CreateDisplayMgrAdapter(); - return true; +bool CreateDisplayMgrFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().CreateDisplayMgrAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.h index b4e20916f4a77dcc902a120d5b5914fa80844973..4cc2fe16ff6614d03f69ced08a2abc8d65710113 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createdisplaymgr_fuzzer/createdisplaymgr_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createdisplaymgr_fuzzer" #endif /* TEST_FUZZTEST_CREATE_DISPLAY_MGR_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.cpp index c6e603e532f498e6421e4e5588e32b6e55b4cbac..6b57568a32e2b8573e23dfd6b9f2b533784d0fb6 100644 --- a/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateGetDataBaseFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().GetOhosWebDataBaseAdapterInstance(); - return true; +bool CreateGetDataBaseFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().GetOhosWebDataBaseAdapterInstance(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.h index ca2a63ea22e0a80265759dadc5bdb3ed564dfe43..f4efaf24190561d5816575057e858a47f56e47b5 100644 --- a/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/creategetdatabase_fuzzer/creategetdatabase_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "creategetdatabase_fuzzer" #endif /* TEST_FUZZTEST_CREATE_GET_DATA_BASE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.cpp index d64b0bb2c721991f4298fca7231a11ca1ae5563c..1edef752822d465dd30c181b5ac73979994c6463 100644 --- a/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateGetPasteBoardFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().GetPasteBoard(); - return true; +bool CreateGetPasteBoardFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().GetPasteBoard(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.h index a571ccbef7dd4be4866326147338ce8616db09b7..514a5889c27f2c097a93c7f1915e662b55a261f3 100644 --- a/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/creategetpasteboard_fuzzer/creategetpasteboard_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "creategetpasteboard_fuzzer" #endif /* TEST_FUZZTEST_CREATE_GET_PASTE_BOARD_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.cpp index 8b6f28eb8d5778962386c5271ee4a8f88a616705..ee5b29cf2e779786f1ff95bb22bd82f1b38578c4 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateMmiAdapterFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().CreateMMIAdapter(); - return true; +bool CreateMmiAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().CreateMMIAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.h index fc96b05cc46be737ed942a034064f4c44cc4c9d7..1372b7b8c46231814788ff638f23d078f138fede 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createmmiadapter_fuzzer/createmmiadapter_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createmmiadapter_fuzzer" #endif /* TEST_FUZZTEST_CREATE_MMI_ADAPTER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.cpp index f38c2a24a8bfa3359123e05f538f117ba22f3ad7..9ec107d7927cf1ae956211de7290c389d2af8622 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateNetConnectFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().CreateNetConnectAdapter(); - return true; +bool CreateNetConnectFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().CreateNetConnectAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.h index 57ec69625891393bd011f2bf61a14cbd999d0de6..62ca793ff6a68b97907a2d504832cc271932a5b2 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createnetconnect_fuzzer/createnetconnect_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createnetconnect_fuzzer" #endif /* TEST_FUZZTEST_CREATE_NET_CONNECT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.cpp index 1476cea341656df6e3935ef3228b297ea79b94f3..9e38f8b1aab695d5da8f3fd7395bf88feca261b6 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreatePowerClientFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().CreatePowerMgrClientAdapter(); - return true; +bool CreatePowerClientFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().CreatePowerMgrClientAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.h index bb28971ab095af55127119e689afc5314319ee31..496da5b5a676f723171a2a8b1972eddb6a768af9 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createpowerclient_fuzzer/createpowerclient_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createpowerclient_fuzzer" #endif /* TEST_FUZZTEST_CREATE_POWER_CLIENT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.cpp b/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.cpp index 753601c8748d410fb30be944ed6d3fab0cf51085..6f765e7c62f92c50a648084e8e4ec7e2bb8df6ab 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.cpp @@ -22,15 +22,15 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateSocperClientFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - OhosAdapterHelper::GetInstance().CreateSocPerfClientAdapter(); - return true; +bool CreateSocperClientFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + OhosAdapterHelper::GetInstance().CreateSocPerfClientAdapter(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.h b/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.h index 15a12f5fac36e88b293506c3eef60ccf9f815e92..546dd2203a3fbcc5b33fdf47ff8b5d3f0df1c278 100644 --- a/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.h +++ b/test/fuzztest/ohos_adapter/interfaces/createsocperclient_fuzzer/createsocperclient_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createsocperclient_fuzzer" #endif /* TEST_FUZZTEST_CREATE_SOCPER_CLIENT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7408aaa32641ca207667268cbdc5fd92e25e6054 --- /dev/null +++ b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("KeyStoreAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/interfaces", + "$webview_path/ohos_adapter/keystore_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "keystoreadapterimpl_fuzzer.cpp" ] + deps = [ + "$webview_path/ohos_adapter:nweb_ohos_adapter", + "$webview_path/ohos_nweb:libnweb", + ] + + external_deps = [ "c_utils:utils" ] + + if (webview_soc_perf_enable) { + external_deps += [ + "huks:libhukssdk", + "soc_perf:socperf_client", + ] + defines = [ "NWEB_SOC_PERF" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":KeyStoreAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/keystoreadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/keystoreadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39fa021b59c324c4b6260d4cd318f0d474d181ed --- /dev/null +++ b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/keystoreadapterimpl_fuzzer.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "keystoreadapterimpl_fuzzer.h" + +#include + +#include "keystore_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool ApplyKeystoreAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; + } + struct HksParamSet* paramSet; + struct HksParam decryptParams[] = { { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_AES }, + { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_DECRYPT }, + { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_AES_KEY_SIZE_256 }, + { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_CBC } }; + int32_t result = KeystoreAdapterImpl::GetInstance().InitParamSet( + nullptr, decryptParams, sizeof(decryptParams) / sizeof(HksParam)); + result = + KeystoreAdapterImpl::GetInstance().InitParamSet(¶mSet, nullptr, sizeof(decryptParams) / sizeof(HksParam)); + result = KeystoreAdapterImpl::GetInstance().InitParamSet( + ¶mSet, decryptParams, sizeof(decryptParams) / sizeof(HksParam)); + std::string alias = "test"; + std::string plainData = "web_test"; + std::string encryptString = KeystoreAdapterImpl::GetInstance().EncryptKey(alias, plainData); + std::string DecryptString = KeystoreAdapterImpl::GetInstance().DecryptKey(alias, encryptString); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::ApplyKeystoreAdapterImplFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/keystoreadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/keystoreadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..1e22f1cf9f24297b8854aead9a76eff22c6b8635 --- /dev/null +++ b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/keystoreadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_KEYSTOREADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_KEYSTOREADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "keystoreadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_KEYSTOREADAPTERIMPL_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/keystore_adapter/keystoreadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d9b83ce2d01ebad6de3972946d29b30ee3583183 --- /dev/null +++ b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("CreateLocationProxyAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/location_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "createlocationproxyadapter_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CreateLocationProxyAdapterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/createlocationproxyadapter_fuzzer.cpp b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/createlocationproxyadapter_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..345d1e31c53635785cb6319639c72e23430bedc3 --- /dev/null +++ b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/createlocationproxyadapter_fuzzer.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "createlocationproxyadapter_fuzzer.h" + +#include "location_instance_impl.h" +#include "location_proxy_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool CreateLocationProxyAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::LocationInstanceImpl locationInstance; + + auto locationProxyAdapter = locationInstance.CreateLocationProxyAdapter(); + + auto locationRequestConfig = locationInstance.CreateLocationRequestConfig(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::CreateLocationProxyAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/createlocationproxyadapter_fuzzer.h b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/createlocationproxyadapter_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e0177b77e9974159bb753c283154d2a5fb733aab --- /dev/null +++ b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/createlocationproxyadapter_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "createlocationproxyadapter_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/location_adapter/createlocationproxyadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5fa04d29d48fa6848efc787f1ce2e779aed8b27d --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("BufferInfoAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "bufferinfoadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":BufferInfoAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/bufferinfoadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/bufferinfoadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..088ec62546a3b039e7230dcebc4613689e0a5745 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/bufferinfoadapterimpl_fuzzer.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bufferinfoadapterimpl_fuzzer.h" + +#include + +#include "buffer_info_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool BufferInfoAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::BufferInfoAdapterImpl bufferInfoAdapterImpl; + int64_t time = 1; + int32_t usesize = static_cast(size); + int32_t offset = static_cast(size); + + bufferInfoAdapterImpl.SetPresentationTimeUs(time); + bufferInfoAdapterImpl.SetSize(usesize); + bufferInfoAdapterImpl.SetOffset(offset); + + bufferInfoAdapterImpl.GetPresentationTimeUs(); + bufferInfoAdapterImpl.GetSize(); + bufferInfoAdapterImpl.GetOffset(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::BufferInfoAdapterImplFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/bufferinfoadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/bufferinfoadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..1a1c71c41209482e573d66f140afeee4647e237d --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/bufferinfoadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "bufferinfoadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/bufferinfoadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..baddce07994201f65e5a3d3d3f9fcd68763f29fb --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("CapabilityDataAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "capabilitydataadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CapabilityDataAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/capabilitydataadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/capabilitydataadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80d96a4c746aa85ece660dfff1de39c7ebc62bad --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/capabilitydataadapterimpl_fuzzer.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "capabilitydataadapterimpl_fuzzer.h" + +#include + +#include "capability_data_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool CapabilityDataAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::CapabilityDataAdapterImpl capabilityDataAdapter; + + int32_t width = static_cast(size); + int32_t height = static_cast(size); + int32_t frameRate = static_cast(size); + + capabilityDataAdapter.SetMaxWidth(width); + capabilityDataAdapter.SetMaxHeight(height); + capabilityDataAdapter.SetMaxframeRate(frameRate); + + capabilityDataAdapter.GetMaxWidth(); + capabilityDataAdapter.GetMaxHeight(); + capabilityDataAdapter.GetMaxframeRate(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::CapabilityDataAdapterImplFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/capabilitydataadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/capabilitydataadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..b4861d85e68c8dfe9bf7b1deee0d4b5f2dcf9fe0 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/capabilitydataadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "capabilitydataadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/capabilitydataadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..65a2447454efceb71db59296795204e1b174dc8f --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("CodecFormatAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "codecformatadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CodecFormatAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/codecformatadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/codecformatadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c51c87199dffde3bb457b1e06ae97983b5b96c4 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/codecformatadapterimpl_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "codecformatadapterimpl_fuzzer.h" + +#include + +#include "codec_format_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool CreateLocationProxyAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::CodecFormatAdapterImpl codecFormatAdapter; + int32_t width = static_cast(size); + int32_t height = static_cast(size); + + codecFormatAdapter.SetWidth(width); + codecFormatAdapter.SetHeight(height); + + codecFormatAdapter.GetWidth(); + codecFormatAdapter.GetHeight(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::CreateLocationProxyAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/codecformatadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/codecformatadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..fc7eb20e0c651fe130d89994fe38af419a790ec1 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/codecformatadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "codecformatadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/codecformatadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a62769cb02e777a726046d48ee8bd560d68bdd12 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("MediaAVSessionAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/ohos_adapter/graphic_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "mediaavsessionadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:want", + "ability_runtime:app_context", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "av_codec:av_codec_client", + "av_session:avsession_client", + "av_session:avsession_client", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_surface:surface", + "graphic_surface:surface", + "input:libmmi-client", + "media_foundation:media_foundation", + "player_framework:media_client", + "relational_store:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":MediaAVSessionAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/mediaavsessionadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/mediaavsessionadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91596398d9cc256f3b35cf453c6cc3e8bd7e41b3 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/mediaavsessionadapterimpl_fuzzer.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mediaavsessionadapterimpl_fuzzer.h" + +#define private public +#include +#include +#include + +#include "media_avsession_adapter.h" +#include "media_avsession_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +class MediaAVSessionCallbackAdapterMock : public MediaAVSessionCallbackAdapter { +public: + MediaAVSessionCallbackAdapterMock() = default; + void Play() {}; + void Pause() {}; + void Stop() {}; + void SeekTo(int64_t millisTime) {}; +}; + +bool MediaAVSessionAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + std::shared_ptr mediaAvSessionCB; + std::shared_ptr callbackImpl = + std::make_shared(mediaAvSessionCB); + + int64_t time = 100; + + callbackImpl->OnPlay(); + callbackImpl->OnPause(); + callbackImpl->OnStop(); + callbackImpl->OnSeek(time); + + std::shared_ptr key = std::make_shared(); + key->Init(); + key->GetPID(); + key->GetElement(); + key->GetType(); + key->ToString(); + + std::shared_ptr avSessionAdapter = std::make_shared(); + auto mediaAVSessionCallbackAdapterMock = std::make_shared(); + auto avSessionKey = std::make_shared(); + avSessionAdapter->avSessionKey_ = avSessionKey; + avSessionAdapter->avSessionKey_->Init(); + avSessionAdapter->avSession_ = nullptr; + auto type = MediaAVSessionType::MEDIA_TYPE_INVALID; + avSessionAdapter->CreateAVSession(type); + type = MediaAVSessionType::MEDIA_TYPE_AUDIO; + avSessionAdapter->CreateAVSession(type); + + avSessionAdapter->DestroyAVSession(); + avSessionAdapter->RegistCallback(mediaAVSessionCallbackAdapterMock); + avSessionAdapter->IsActivated(); + avSessionAdapter->Activate(); + avSessionAdapter->DeActivate(); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::MediaAVSessionAdapterImplFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/mediaavsessionadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/mediaavsessionadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..ddb249c0a5eb964fae1a4c183f4fe8aea93beaf6 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/mediaavsessionadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "mediaavsessionadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediaavsessionadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f9ec2d73f817013a57c4a48e9ad8a69af180b6c0 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("MediaCodecDecoderAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/ohos_adapter/graphic_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "mediacodecdecoderadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "av_codec:av_codec_client", + "av_session:avsession_client", + "c_utils:utils", + "graphic_surface:surface", + "media_foundation:media_foundation", + "player_framework:media_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":MediaCodecDecoderAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/mediacodecdecoderadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/mediacodecdecoderadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3186a26bfaa7de7bc94a6638ed89fb95ad9f95e --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/mediacodecdecoderadapterimpl_fuzzer.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mediacodecdecoderadapterimpl_fuzzer.h" + +#include + +#include "avsharedmemory.h" +#include "avsharedmemorybase.h" +#include "media_codec_decoder_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +class DecoderCallbackAdapterMock : public DecoderCallbackAdapter { +public: + DecoderCallbackAdapterMock() = default; + + ~DecoderCallbackAdapterMock() override = default; + + void OnError(ErrorType errorType, int32_t errorCode) override {} + + void OnStreamChanged(int32_t width, int32_t height, double frameRate) override {} + + void OnNeedInputData(uint32_t index, std::shared_ptr buffer) override {} + + void OnNeedOutputData(uint32_t index, std::shared_ptr info, BufferFlag flag) override {} +}; + +class DecoderFormatAdapterMock : public DecoderFormatAdapter { +public: + DecoderFormatAdapterMock() = default; + + int32_t GetWidth() override + { + return width; + } + + int32_t GetHeight() override + { + return height; + } + + double GetFrameRate() override + { + return frameRate; + } + + void SetWidth(int32_t w) override + { + width = w; + } + + void SetHeight(int32_t h) override + { + height = h; + } + + void SetFrameRate(double fr) override + { + frameRate = fr; + } + + int32_t width; + int32_t height; + double frameRate; +}; + +bool MediaCodecDecoderAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + NWeb::MediaCodecDecoderAdapterImpl mediaCodecDecoderAdapterImpl; + NWeb::DecoderAdapterCode code = mediaCodecDecoderAdapterImpl.CreateVideoDecoderByMime("testmimeType"); + std::shared_ptr format = std::make_unique(); + AVCodecBufferInfo info; + code = mediaCodecDecoderAdapterImpl.CreateVideoDecoderByName("testname"); + code = mediaCodecDecoderAdapterImpl.ConfigureDecoder(format); + code = mediaCodecDecoderAdapterImpl.SetParameterDecoder(format); + + void* window = nullptr; + code = mediaCodecDecoderAdapterImpl.SetOutputSurface(window); + code = mediaCodecDecoderAdapterImpl.PrepareDecoder(); + code = mediaCodecDecoderAdapterImpl.StartDecoder(); + code = mediaCodecDecoderAdapterImpl.StopDecoder(); + code = mediaCodecDecoderAdapterImpl.FlushDecoder(); + code = mediaCodecDecoderAdapterImpl.ResetDecoder(); + code = mediaCodecDecoderAdapterImpl.ReleaseDecoder(); + + code = mediaCodecDecoderAdapterImpl.QueueInputBufferDec(0, 0, 0, 0, BufferFlag::CODEC_BUFFER_FLAG_NONE); + + code = mediaCodecDecoderAdapterImpl.GetOutputFormatDec(format); + + code = mediaCodecDecoderAdapterImpl.ReleaseOutputBufferDec(0, true); + + std::shared_ptr decoderCallback = std::make_shared(nullptr); + + decoderCallback->OnError(OHOS::MediaAVCodec::AVCodecErrorType::AVCODEC_ERROR_INTERNAL, 0); + decoderCallback->OnOutputFormatChanged(OHOS::MediaAVCodec::Format()); + decoderCallback->OnInputBufferAvailable(0, nullptr); + decoderCallback->OnOutputBufferAvailable(0, OHOS::MediaAVCodec::AVCodecBufferInfo(), + OHOS::MediaAVCodec::AVCodecBufferFlag::AVCODEC_BUFFER_FLAG_NONE, nullptr); + + std::shared_ptr callback = std::make_shared(); + std::shared_ptr decoderCallbackNoNull = + std::make_shared(callback); + decoderCallbackNoNull->OnError(OHOS::MediaAVCodec::AVCodecErrorType::AVCODEC_ERROR_INTERNAL, 0); + decoderCallbackNoNull->OnOutputFormatChanged(OHOS::MediaAVCodec::Format()); + decoderCallbackNoNull->OnOutputBufferAvailable( + 0, info, OHOS::MediaAVCodec::AVCodecBufferFlag::AVCODEC_BUFFER_FLAG_NONE, nullptr); + std::shared_ptr memory = std::make_shared(1, 1.0, "test"); + decoderCallbackNoNull->OnInputBufferAvailable(1, memory); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::MediaCodecDecoderAdapterImplFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/mediacodecdecoderadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/mediacodecdecoderadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..c153caeba73bdc41d483b771d971241ef8769b97 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/mediacodecdecoderadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "mediacodecdecoderadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecdecoderadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6d2d4048ea8439830c30d7291c40346255e05f89 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("MediaCodecEncoderAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/ohos_adapter/graphic_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "mediacodecencoderadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_runtime:app_manager", + "av_codec:av_codec_client", + "av_session:avsession_client", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_surface:surface", + "graphic_surface:surface", + "media_foundation:media_foundation", + "player_framework:media_client", + "relational_store:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":MediaCodecEncoderAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/mediacodecencoderadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/mediacodecencoderadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ab86fc91a65599e901ff3c4821f6403cbde1419 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/mediacodecencoderadapterimpl_fuzzer.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mediacodecencoderadapterimpl_fuzzer.h" + +#include "avsharedmemory.h" +#include "avsharedmemorybase.h" +#include "media_codec_encoder_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +class EncoderCallbackAdapterMock : public CodecCallbackAdapter { +public: + EncoderCallbackAdapterMock() = default; + + ~EncoderCallbackAdapterMock() override = default; + + void OnError(ErrorType errorType, int32_t errorCode) override {} + + void OnStreamChanged(const std::shared_ptr formatApadter_) override {} + + void OnNeedInputData(uint32_t index, std::shared_ptr buffer) override {} + + void OnNeedOutputData(uint32_t index, std::shared_ptr info, BufferFlag flag, + std::shared_ptr buffer) override + {} +}; + +class CodecConfigParaAdapterMock : public CodecConfigParaAdapter { +public: + CodecConfigParaAdapterMock() = default; + + int32_t GetWidth() override + { + return width; + } + + int32_t GetHeight() override + { + return height; + } + + int64_t GetBitRate() override + { + return bitRate; + } + + double GetFrameRate() override + { + return frameRate; + } + + int32_t width; + int32_t height; + int64_t bitRate; + double frameRate; +}; + +bool CreateLocationProxyAdapterFuzzTest(const uint8_t* data, size_t size) +{ + NWeb::MediaCodecEncoderAdapterImpl mediaCodecEncoderAdapterImpl; + std::shared_ptr callbackImpl = std::make_shared(); + std::shared_ptr config = std::make_shared(); + + mediaCodecEncoderAdapterImpl.CreateVideoCodecByMime("video/avc"); + mediaCodecEncoderAdapterImpl.SetCodecCallback(nullptr); + mediaCodecEncoderAdapterImpl.SetCodecCallback(callbackImpl); + mediaCodecEncoderAdapterImpl.Configure(nullptr); + mediaCodecEncoderAdapterImpl.Configure(config); + mediaCodecEncoderAdapterImpl.Prepare(); + mediaCodecEncoderAdapterImpl.Start(); + mediaCodecEncoderAdapterImpl.Stop(); + mediaCodecEncoderAdapterImpl.Reset(); + mediaCodecEncoderAdapterImpl.Release(); + mediaCodecEncoderAdapterImpl.CreateInputSurface(); + mediaCodecEncoderAdapterImpl.ReleaseOutputBuffer(0, true); + mediaCodecEncoderAdapterImpl.RequestKeyFrameSoon(); + mediaCodecEncoderAdapterImpl.GetErrorType(AVCodecErrorType::AVCODEC_ERROR_INTERNAL); + mediaCodecEncoderAdapterImpl.GetBufferFlag(AVCodecBufferFlag::AVCODEC_BUFFER_FLAG_NONE); + + std::shared_ptr cb = nullptr; + std::shared_ptr memory = std::make_shared(1, 1.0, "test"); + + NWeb::EncoderCallbackImpl encoderCallback(cb); + + encoderCallback.OnError(OHOS::MediaAVCodec::AVCodecErrorType::AVCODEC_ERROR_INTERNAL, 0); + encoderCallback.OnOutputFormatChanged(OHOS::MediaAVCodec::Format()); + encoderCallback.OnInputBufferAvailable(0, nullptr); + encoderCallback.OnInputBufferAvailable(1, memory); + encoderCallback.OnOutputBufferAvailable(0, OHOS::MediaAVCodec::AVCodecBufferInfo(), + OHOS::MediaAVCodec::AVCodecBufferFlag::AVCODEC_BUFFER_FLAG_NONE, nullptr); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::CreateLocationProxyAdapterFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/mediacodecencoderadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/mediacodecencoderadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..4670ddbe1df175723ffc5569e47351fa6035deff --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/mediacodecencoderadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "mediacodecencoderadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodecencoderadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..eb0e52afa615db914c67ce51d05f99849ab6d249 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("MediaCodecListAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "mediacodeclistadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":MediaCodecListAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/mediacodeclistadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/mediacodeclistadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd0e3f3d58829018b74d3425d577d2e3c4e77824 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/mediacodeclistadapterimpl_fuzzer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mediacodeclistadapterimpl_fuzzer.h" + +#include +#include +#include + +#include "media_codec_list_adapter_impl.h" + +using namespace OHOS::NWeb; +namespace OHOS { +bool MediaCodecListAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size == 0) { + return false; + } + + OHOS::NWeb::MediaCodecListAdapterImpl& mediaCodecListAdapterImpl = + OHOS::NWeb::MediaCodecListAdapterImpl::GetInstance(); + + std::string mime(reinterpret_cast(data), size); + bool isEncoder = true; + + std::shared_ptr capabilityAdapter = + mediaCodecListAdapterImpl.GetCodecCapability(mime, isEncoder); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::MediaCodecListAdapterImplFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/mediacodeclistadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/mediacodeclistadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..c153caeba73bdc41d483b771d971241ef8769b97 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/mediacodeclistadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "mediacodecdecoderadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/mediacodeclistadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..af4774c093f9fca0caa87f79b85b6e6d8f46fa8e --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("OhosBufferAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "ohosbufferadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":OhosBufferAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/ohosbufferadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/ohosbufferadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd220954a2729b6ea5c98dfb68df20fda282a685 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/ohosbufferadapterimpl_fuzzer.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohosbufferadapterimpl_fuzzer.h" + +#include + +#include "ohos_buffer_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool OhosBufferAdapterImplFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + OHOS::NWeb::OhosBufferAdapterImpl ohosBufferAdapterImpl; + + uint8_t* addr = const_cast(data); + uint32_t bufferSize = static_cast(size); + + ohosBufferAdapterImpl.SetAddr(addr); + + ohosBufferAdapterImpl.SetBufferSize(bufferSize); + + ohosBufferAdapterImpl.GetAddr(); + + ohosBufferAdapterImpl.GetBufferSize(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::OhosBufferAdapterImplFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/ohosbufferadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/ohosbufferadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..c153caeba73bdc41d483b771d971241ef8769b97 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/ohosbufferadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "mediacodecdecoderadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/ohosbufferadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4593c0c8f291a250f371c32688c1b09f7ec55f27 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PlayerFrameworkAdapterImpl_fuzzerFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/media_adapter/include", + "$webview_path/ohos_adapter/graphic_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "playerframeworkadapterimpl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_runtime:app_manager", + "av_codec:av_codec_client", + "av_session:avsession_client", + "c_utils:utils", + "graphic_2d:libcomposer", + "graphic_surface:surface", + "graphic_surface:surface", + "media_foundation:media_foundation", + "player_framework:media_client", + "relational_store:native_rdb", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PlayerFrameworkAdapterImpl_fuzzerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/playerframeworkadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/playerframeworkadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40ccb6ebecab9d3a4f61a90f5c10797a54a4c450 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/playerframeworkadapterimpl_fuzzer.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "playerframeworkadapterimpl_fuzzer.h" + +#include "ohos_adapter_helper.h" +#include "player_framework_adapter_impl.h" +using namespace OHOS::NWeb; + +namespace OHOS { +class PlayerCallbackTest : public PlayerCallbackAdapter { +public: + PlayerCallbackTest() = default; + ~PlayerCallbackTest() override = default; + void OnInfo(PlayerOnInfoType type, int32_t extra, int32_t value) override + { + infoType_ = type; + } + void OnError(PlayerAdapterErrorType errorType) override + { + errorType_ = errorType; + } + PlayerOnInfoType infoType_ = PlayerOnInfoType::INFO_TYPE_UNSET; + PlayerAdapterErrorType errorType_ = PlayerAdapterErrorType::INVALID_CODE; +}; + +bool PlayerFrameworkAdapterImpl_fuzzerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + + int32_t currentTime = static_cast(size); + int32_t duration = static_cast(size); + + std::shared_ptr callbackAdapter = nullptr; + PlayerCallbackImpl playerCallback(callbackAdapter); + + playerCallback.OnInfo(Media::PlayerOnInfoType::INFO_TYPE_EOS, 0, Media::Format()); + playerCallback.OnError(0, ""); + PlayerAdapterImpl playerAdapter; + playerAdapter.SetPlayerCallback(nullptr); + playerAdapter.SetSource(""); + playerAdapter.SetSource(0, 0, 0); + playerAdapter.SetVideoSurface(nullptr); + playerAdapter.SetVolume(0.0, 0.0); + playerAdapter.Seek(0, PlayerSeekMode::SEEK_PREVIOUS_SYNC); + playerAdapter.Play(); + playerAdapter.Pause(); + playerAdapter.PrepareAsync(); + playerAdapter.GetCurrentTime(currentTime); + playerAdapter.GetDuration(duration); + playerAdapter.SetPlaybackSpeed(PlaybackRateMode::SPEED_FORWARD_1_00_X); + + auto callbackTest = std::make_unique(); + std::shared_ptr playerCallbackMock = + std::make_shared(std::move(callbackTest)); + std::unique_ptr playerAdapterNormal = std::make_unique(); + ; + playerAdapterNormal->SetPlayerCallback(std::move(callbackTest)); + auto surfaceAdapter = NWeb::OhosAdapterHelper::GetInstance().CreateConsumerSurfaceAdapter(); + playerAdapterNormal->SetVideoSurface(std::move(surfaceAdapter)); + playerAdapterNormal->SetSource(""); + playerAdapterNormal->SetSource(-1, 0, 0); + playerAdapterNormal->SetVolume(0.0, 0.0); + playerAdapterNormal->Seek(0, PlayerSeekMode::SEEK_PREVIOUS_SYNC); + playerAdapterNormal->Play(); + playerAdapterNormal->Pause(); + playerAdapterNormal->PrepareAsync(); + playerAdapterNormal->GetCurrentTime(currentTime); + playerAdapterNormal->GetDuration(duration); + playerAdapter.SetPlaybackSpeed(PlaybackRateMode::SPEED_FORWARD_1_00_X); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::PlayerFrameworkAdapterImpl_fuzzerFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/playerframeworkadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/playerframeworkadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..052f321039551620cc953360b3a0bf2cb45475a3 --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/playerframeworkadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H +#define TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "playerframeworkadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/project.xml b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/media_adapter/playerframeworkadapterimpl_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.cpp b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.cpp old mode 100755 new mode 100644 index f724f7b916b69ac0a37c968ba8704fcd779d1e96..f46deed3845e35d4a4b68026e0db33cfcadc0ca0 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.cpp @@ -20,17 +20,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool GetDeviceIdsFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr AdapterImpl = std::make_shared(); - std::vector devList; - AdapterImpl->GetDeviceIds(devList); - return true; +bool GetDeviceIdsFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr AdapterImpl = std::make_shared(); + std::vector devList; + AdapterImpl->GetDeviceIds(devList); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.h b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.h old mode 100755 new mode 100644 index 1513eb010033e82152ad6ab08f272bb156fd8e68..88e3fe5aa4b8e4807dac8381121330743e120b66 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.h +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/getdeviceids_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getkeyboardtype_fuzzer" #endif /* TEST_FUZZTEST_GETKEYBOARDTYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/project.xml b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getdeviceids_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.cpp b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.cpp old mode 100755 new mode 100644 index 8b8f269167b0502483b62d2b6390f2cbf385e207..13f11085bf7a827b75c42153243decc7f65e192f --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.cpp @@ -16,26 +16,27 @@ #include "getkeyboardtype_fuzzer.h" #include + #include "mmi_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool GetKeyboardTypeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size < sizeof(int32_t))) { - return false; - } - std::shared_ptr AdapterImpl = std::make_shared(); - int32_t deviceId; - if (memcpy_s(&deviceId, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } - int32_t type; - AdapterImpl->GetKeyboardType(deviceId, type); - return true; +bool GetKeyboardTypeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; + } + std::shared_ptr AdapterImpl = std::make_shared(); + int32_t deviceId; + if (memcpy_s(&deviceId, sizeof(int32_t), data, sizeof(int32_t)) != 0) { + return false; } + int32_t type; + AdapterImpl->GetKeyboardType(deviceId, type); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.h b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.h old mode 100755 new mode 100644 index 1513eb010033e82152ad6ab08f272bb156fd8e68..88e3fe5aa4b8e4807dac8381121330743e120b66 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.h +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/getkeyboardtype_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getkeyboardtype_fuzzer" #endif /* TEST_FUZZTEST_GETKEYBOARDTYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/project.xml b/test/fuzztest/ohos_adapter/multimodalinput_adapter/getkeyboardtype_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.cpp b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.cpp old mode 100755 new mode 100644 index 8c42c55822737a8b421a3f1ce428524a2befda98..2da3d17a86d19143ca9b7d2034b8125a2a7a2f28 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.cpp @@ -16,6 +16,7 @@ #include "ondeviceadded_fuzzer.h" #include + #include "mmi_adapter_impl.h" using namespace OHOS::NWeb; @@ -25,25 +26,25 @@ class MMIListenerTest : public MMIListenerAdapter { public: MMIListenerTest() = default; virtual ~MMIListenerTest() = default; - void OnDeviceAdded(int32_t deviceId, const std::string &type) override {}; - void OnDeviceRemoved(int32_t deviceId, const std::string &type) override {}; + void OnDeviceAdded(int32_t deviceId, const std::string& type) override {}; + void OnDeviceRemoved(int32_t deviceId, const std::string& type) override {}; }; - bool OnDeviceAddedFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size < sizeof(int32_t))) { - return false; - } - std::shared_ptr listener = std::make_shared(); - auto listenerAdapterImpl = std::make_shared(listener); - int32_t deviceId; - if (memcpy_s(&deviceId, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } - std::string type((const char*) data, size); - listenerAdapterImpl->OnDeviceAdded(deviceId, type); - return true; +bool OnDeviceAddedFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; + } + std::shared_ptr listener = std::make_shared(); + auto listenerAdapterImpl = std::make_shared(listener); + int32_t deviceId; + if (memcpy_s(&deviceId, sizeof(int32_t), data, sizeof(int32_t)) != 0) { + return false; } + std::string type((const char*)data, size); + listenerAdapterImpl->OnDeviceAdded(deviceId, type); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.h b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.h old mode 100755 new mode 100644 index 05c2a41c05572fbc4c7ce5592c4620840f27ff65..43f33783ada57aeeb4c3e29ba0edc203a1c636b7 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.h +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/ondeviceadded_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "ondeviceadded_fuzzer" #endif /* TEST_FUZZTEST_ONDEVICEADDED_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/project.xml b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceadded_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.cpp b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.cpp old mode 100755 new mode 100644 index 0f2e590c4a3d013321629421e541e28358de5026..a6a128ec323e7040d7e9c03fccdfbbfb9eb5e081 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.cpp @@ -17,6 +17,7 @@ #include #include + #include "mmi_adapter_impl.h" using namespace OHOS::NWeb; @@ -26,25 +27,25 @@ class MMIListenerTest : public MMIListenerAdapter { public: MMIListenerTest() = default; virtual ~MMIListenerTest() = default; - void OnDeviceAdded(int32_t deviceId, const std::string &type) override {}; - void OnDeviceRemoved(int32_t deviceId, const std::string &type) override {}; + void OnDeviceAdded(int32_t deviceId, const std::string& type) override {}; + void OnDeviceRemoved(int32_t deviceId, const std::string& type) override {}; }; - bool OnDeviceRemovedFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size < sizeof(int32_t))) { - return false; - } - std::shared_ptr listener = std::make_shared(); - auto listenerAdapterImpl = std::make_shared(listener); - int32_t deviceId; - if (memcpy_s(&deviceId, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } - std::string type((const char*) data, size); - listenerAdapterImpl->OnDeviceRemoved(deviceId, type); - return true; +bool OnDeviceRemovedFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; + } + std::shared_ptr listener = std::make_shared(); + auto listenerAdapterImpl = std::make_shared(listener); + int32_t deviceId; + if (memcpy_s(&deviceId, sizeof(int32_t), data, sizeof(int32_t)) != 0) { + return false; } + std::string type((const char*)data, size); + listenerAdapterImpl->OnDeviceRemoved(deviceId, type); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.h b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.h old mode 100755 new mode 100644 index b485ad8d22018ff31a5d4af162e6f3b33e1eda76..a80a3b66f1a4365d3a95d2ef2edc5811dae4554b --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.h +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/ondeviceremoved_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "ondeviceremoved_fuzzer" #endif /* TEST_FUZZTEST_ONDEVICEREMOVED_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/project.xml b/test/fuzztest/ohos_adapter/multimodalinput_adapter/ondeviceremoved_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/project.xml b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.cpp b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.cpp old mode 100755 new mode 100644 index fe12dfffbd808acaca19836cdd2fd972840fe88e..3769feb5f56e0cf58c3d98627ad38ab248f643e9 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.cpp @@ -23,21 +23,21 @@ class MMIListenerTest : public MMIListenerAdapter { public: MMIListenerTest() = default; virtual ~MMIListenerTest() = default; - void OnDeviceAdded(int32_t deviceId, const std::string &type) override {}; - void OnDeviceRemoved(int32_t deviceId, const std::string &type) override {}; + void OnDeviceAdded(int32_t deviceId, const std::string& type) override {}; + void OnDeviceRemoved(int32_t deviceId, const std::string& type) override {}; }; - bool RegisterDevListenerFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr listener = std::make_shared(); - std::shared_ptr AdapterImpl = std::make_shared(); - std::string type((const char*) data, size); - AdapterImpl->RegisterDevListener(type, listener); - return true; +bool RegisterDevListenerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr listener = std::make_shared(); + std::shared_ptr AdapterImpl = std::make_shared(); + std::string type((const char*)data, size); + AdapterImpl->RegisterDevListener(type, listener); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.h b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.h old mode 100755 new mode 100644 index 05c2a41c05572fbc4c7ce5592c4620840f27ff65..43f33783ada57aeeb4c3e29ba0edc203a1c636b7 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.h +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/registerdevlistener_fuzzer/registerdevlistener_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "ondeviceadded_fuzzer" #endif /* TEST_FUZZTEST_ONDEVICEADDED_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/project.xml b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.cpp b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.cpp old mode 100755 new mode 100644 index 2c55b744ff4ddd5c903c2d6bbe3685544c477c0e..fcd0cb29beb7d5268ccc79de809b937ef32f8d11 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.cpp @@ -16,22 +16,23 @@ #include "unregisterdevlistener_fuzzer.h" #include + #include "mmi_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool UnregisterDevListenerFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr AdapterImpl = std::make_shared(); - std::string type((const char*) data, size); - AdapterImpl->UnregisterDevListener(type); - return true; +bool UnregisterDevListenerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr AdapterImpl = std::make_shared(); + std::string type((const char*)data, size); + AdapterImpl->UnregisterDevListener(type); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.h b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.h old mode 100755 new mode 100644 index 290728d5d48fd959c4f842b9792c10d3acd4a951..5b6db8be8249f6e137fa15a9607d8bd60e00cf21 --- a/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.h +++ b/test/fuzztest/ohos_adapter/multimodalinput_adapter/unregisterdevlistener_fuzzer/unregisterdevlistener_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "unregisterdevlistener_fuzzer" #endif /* TEST_FUZZTEST_UNREGISTERDEVLISTENER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..56e4a1772b5df1396ad24fd90c37d6c08aececd8 --- /dev/null +++ b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/BUILD.gn @@ -0,0 +1,96 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") +import("$webview_path/config.gni") + +##############################fuzztest########################################## +ohos_fuzztest("OhosImageDecoderAdapterImplFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/interfaces", + "$webview_path/ohos_adapter/ohos_image_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + include_dirs += [ + "../ohos_nweb/include", + "aafwk_adapter/include", + "access_token_adapter/include", + "audio_adapter/include", + "battery_mgr_adapter/include", + "camera_adapter/include", + "cert_mgr_adapter/include", + "datashare_adapter/include", + "date_time_format_adapter/include", + "display_manager_adapter/include", + "distributeddatamgr_adapter/webdatabase/include", + "enterprise_device_management_adapter/include", + "event_handler_adapter/include", + "flowbuffer_adapter/include", + "graphic_adapter/include", + "hiviewdfx_adapter/include", + "inputmethodframework_adapter/include", + "keystore_adapter/include", + "location_adapter/include", + "media_adapter/include", + "multimodalinput_adapter/include", + "net_connect_adapter/include", + "net_proxy_adapter/include", + "ohos_adapter_helper/include", + "ohos_image_adapter/include", + "ohos_init_web_adapter/include", + "ohos_resource_adapter/include", + "pasteboard_adapter/include", + "power_mgr_adapter/include", + "print_manager_adapter/include", + "screen_capture_adapter/include", + "soc_perf_adapter/include", + "system_properties_adapter/include", + ] + + sources = [ "ohosimagedecoderadapterimpl_fuzzer.cpp" ] + deps = [ + "$webview_path/ohos_adapter:nweb_ohos_adapter", + "$webview_path/ohos_nweb:libnweb", + ] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "image_framework:image", + "image_framework:image_native", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":OhosImageDecoderAdapterImplFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/ohosimagedecoderadapterimpl_fuzzer.cpp b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/ohosimagedecoderadapterimpl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d70a68222eb3a36123e4c12a626aec83e9cc3bac --- /dev/null +++ b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/ohosimagedecoderadapterimpl_fuzzer.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohosimagedecoderadapterimpl_fuzzer.h" + +#include +#include + +#include "image_source.h" +#include "image_type.h" +#include "media_errors.h" +#include "ohos_adapter_helper.h" + +using namespace OHOS::NWeb; +const std::string DEFAULT_MOUSE_DRAG_IMAGE { "/system/etc/device_status/drag_icon/Copy_Drag.svg" }; + +namespace OHOS { + +bool ValidateInput(const uint8_t* data, size_t size) +{ + return (data != nullptr) && (size >= sizeof(int32_t)); +} + +std::shared_ptr CreateDecoderAdapter() +{ + return OhosAdapterHelper::GetInstance().CreateOhosImageDecoderAdapter(); +} + +void HandleAbnormalCase(const std::shared_ptr& adapter) +{ + size_t len = 0; + std::unique_ptr rawData; + + adapter->ParseImageInfo(rawData.get(), len); + adapter->DecodeToPixelMap(rawData.get(), len); +} + +bool ProcessImageSource(std::shared_ptr& adapter) +{ + uint32_t errorCode = 0; + OHOS::Media::SourceOptions opts; + auto imageSource = OHOS::Media::ImageSource::CreateImageSource(DEFAULT_MOUSE_DRAG_IMAGE, opts, errorCode); + if (!imageSource || errorCode != Media::SUCCESS) { + return false; + } + + OHOS::Media::DecodeOptions decodeOpts; + auto pixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode); + if (!pixelMap || errorCode != OHOS::Media::SUCCESS) { + return false; + } + + const uint8_t* imageData = pixelMap->GetPixels(); + if (!imageData) { + return false; + } + + size_t len = pixelMap->GetPixelBytes(); + adapter->ParseImageInfo(imageData, len); + adapter->DecodeToPixelMap(imageData, len); + return true; +} + +bool ApplyOhosImageDecoderAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if (!ValidateInput(data, size)) { + return false; + } + + auto adapter = CreateDecoderAdapter(); + if (!adapter) { + return false; + } + + HandleAbnormalCase(adapter); + return ProcessImageSource(adapter); +} + +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::ApplyOhosImageDecoderAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/ohosimagedecoderadapterimpl_fuzzer.h b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/ohosimagedecoderadapterimpl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..32621fcf9bfb14a1f43025a0f96ce49212cffa55 --- /dev/null +++ b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/ohosimagedecoderadapterimpl_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_OHOSIMAGEDECODERADAPTERIMPL_FUZZER_H +#define TEST_FUZZTEST_OHOSIMAGEDECODERADAPTERIMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "ohosimagedecoderadapterimpl_fuzzer" +#endif /* TEST_FUZZTEST_OHOSIMAGEDECODERADAPTERIMPL_FUZZER_H */ diff --git a/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/ohosimageadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.cpp old mode 100755 new mode 100644 index 4e758fed17c070479fe24f8e19eea0e82305d5c3..291d3174022fb9d838ca784c10116eb22b20288c --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.cpp @@ -14,27 +14,28 @@ */ #include "addhtmlrecord_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool AddHtmlRecordFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string html((const char*) data, size); - std::shared_ptr dataAdapterImpl = std::make_shared(); - dataAdapterImpl->AddHtmlRecord(html); - dataAdapterImpl->AddTextRecord(html); - dataAdapterImpl->GetMimeTypes(); - dataAdapterImpl->GetPrimaryHtml(); - dataAdapterImpl->GetPrimaryText(); - dataAdapterImpl->GetPrimaryMimeType(); - return true; +bool AddHtmlRecordFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string html((const char*)data, size); + std::shared_ptr dataAdapterImpl = std::make_shared(); + dataAdapterImpl->AddHtmlRecord(html); + dataAdapterImpl->AddTextRecord(html); + dataAdapterImpl->GetMimeTypes(); + dataAdapterImpl->GetPrimaryHtml(); + dataAdapterImpl->GetPrimaryText(); + dataAdapterImpl->GetPrimaryMimeType(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.h old mode 100755 new mode 100644 index 08719896e9da4126bc17473c34867200bf9464ce..1719c024148680f79b76259e6f7643c7c2e7aaa7 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/addhtmlrecord_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "addhtmlrecord_fuzzer" #endif /* TEST_FUZZTEST_ADDHTMLRECORD_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/addhtmlrecord_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.cpp old mode 100755 new mode 100644 index ef89ad7eaaaaeb38a952e90cb6086cde5c120241..a1f933e69cf505fe1a00fcbd26e382eb7d75bf64 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.cpp @@ -21,18 +21,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ClipboardToImageAlphaTypeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr dataRecordAdapterImpl = - std::make_shared("pixelMap"); - ClipBoardImageAlphaType alphaType = ClipBoardImageAlphaType::ALPHA_TYPE_UNKNOWN; - dataRecordAdapterImpl->ClipboardToImageAlphaType(alphaType); - return true; +bool ClipboardToImageAlphaTypeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr dataRecordAdapterImpl = + std::make_shared("pixelMap"); + ClipBoardImageAlphaType alphaType = ClipBoardImageAlphaType::ALPHA_TYPE_UNKNOWN; + dataRecordAdapterImpl->ClipboardToImageAlphaType(alphaType); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.h old mode 100755 new mode 100644 index 8fecaf291761523e65077195bedcb4e828ab702e..706ac86e337718048a04f296ac7e11187004bbe0 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/clipboardtoimagealphatype_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "clipboardtoimagealphatype_fuzzer" #endif /* TEST_FUZZTEST_CLIPBOARDTOIMAGEALPHATYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagealphatype_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.cpp old mode 100755 new mode 100644 index ff9db11521ab413233946e08b004609d3b28e92f..0a7a6afb125d21e3a96c1e3883a1fa134805ed41 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.cpp @@ -21,18 +21,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ClipboardToImageColorTypeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr dataRecordAdapterImpl = - std::make_shared("pixelMap"); - ClipBoardImageColorType colorType = ClipBoardImageColorType::COLOR_TYPE_RGBA_8888; - dataRecordAdapterImpl->ClipboardToImageColorType(colorType); - return true; +bool ClipboardToImageColorTypeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr dataRecordAdapterImpl = + std::make_shared("pixelMap"); + ClipBoardImageColorType colorType = ClipBoardImageColorType::COLOR_TYPE_RGBA_8888; + dataRecordAdapterImpl->ClipboardToImageColorType(colorType); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.h old mode 100755 new mode 100644 index 6e49543102715a5cc86693faba9e7fbc75e1d641..db85872ab4d665c0b87c33d2605c5502d360aced --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/clipboardtoimagecolortype_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "clipboardtoimagecolortype_fuzzer" #endif /* TEST_FUZZTEST_CLIPBOARDTOIMAGECOLORTYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/clipboardtoimagecolortype_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/getimgdata_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/getimgdata_fuzzer.h old mode 100755 new mode 100644 index 24d72ddab736bbda60e2df1246f769022be6062d..d6f02b503fe0c9fac8492e0dddd74a76c1e86ee5 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/getimgdata_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/getimgdata_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getimgdata_fuzzer" #endif /* TEST_FUZZTEST_GETIMGDATA_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/getimgdata_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.cpp old mode 100755 new mode 100644 index 0699183f77419c3bad4b8c01e3044efc842c290c..9976d28c9a78f3929195b0af0e22fe532327a1bd --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.cpp @@ -14,27 +14,28 @@ */ #include "getmimetype_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool GetMimeTypeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string text((const char*) data, size); - std::shared_ptr plainText = std::make_shared(text); - std::shared_ptr htmlText = std::make_shared(text); - std::shared_ptr dataRecordAdapterImpl = - std::make_shared(text, htmlText, plainText); - dataRecordAdapterImpl->GetMimeType(); - dataRecordAdapterImpl->GetHtmlText(); - dataRecordAdapterImpl->GetPlainText(); - return true; +bool GetMimeTypeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string text((const char*)data, size); + std::shared_ptr plainText = std::make_shared(text); + std::shared_ptr htmlText = std::make_shared(text); + std::shared_ptr dataRecordAdapterImpl = + std::make_shared(text, htmlText, plainText); + dataRecordAdapterImpl->GetMimeType(); + dataRecordAdapterImpl->GetHtmlText(); + dataRecordAdapterImpl->GetPlainText(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.h old mode 100755 new mode 100644 index d67bb2b3a9c5a5b642fc20b1ac903fe64704ad61..6849cf716c614f0aaf14293f7e9891d9f1d23136 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/getmimetype_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getmimetype_fuzzer" #endif /* TEST_FUZZTEST_GETMIMETYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/getmimetype_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.cpp old mode 100755 new mode 100644 index d49b56e762492ad92ced60e21f244e4803ed6787..78ab577f404f0fcdb3ca351145d79f3f840e1bb7 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.cpp @@ -14,28 +14,30 @@ */ #include "getrecordat_fuzzer.h" -#include "pasteboard_client_adapter_impl.h" + #include + +#include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; using namespace OHOS::MiscServices; namespace OHOS { - bool GetRecordAtFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size < sizeof(size_t))) { - return false; - } - std::size_t index = 0; - if (memcpy_s(&index, sizeof(size_t), data, sizeof(size_t)) != 0) { - return false; - } - std::shared_ptr dataName = std::make_shared(); - std::shared_ptr dataAdapterImpl = std::make_shared(dataName); - dataAdapterImpl->GetRecordAt(index); - dataAdapterImpl->GetRecordCount(); - dataAdapterImpl->AllRecords(); - return true; +bool GetRecordAtFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(size_t))) { + return false; + } + std::size_t index = 0; + if (memcpy_s(&index, sizeof(size_t), data, sizeof(size_t)) != 0) { + return false; } + std::shared_ptr dataName = std::make_shared(); + std::shared_ptr dataAdapterImpl = std::make_shared(dataName); + dataAdapterImpl->GetRecordAt(index); + dataAdapterImpl->GetRecordCount(); + dataAdapterImpl->AllRecords(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.h old mode 100755 new mode 100644 index b36060ba3291b6f00aebb36b52cb79201a4c2fca..876fd5f9501dfa7b358d1c0ebb279a9718ee257d --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/getrecordat_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getrecordat_fuzzer" #endif /* TEST_FUZZTEST_GETRECORDAT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/getrecordat_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.cpp old mode 100755 new mode 100644 index 1f5de9c35014d5854a5505bebfc044ab1c7049cb..4acc8f99cf256e4d5517851e321e9053f655ff5b --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.cpp @@ -19,20 +19,28 @@ #undef private using namespace OHOS::NWeb; +using namespace OHOS::Media; namespace OHOS { - bool ImageToClipboardAlphaTypeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr dataRecordAdapterImpl = - std::make_shared("pixelMap"); - Media::ImageInfo imgInfo; - dataRecordAdapterImpl->ImageToClipboardAlphaType(imgInfo); - return true; +bool ImageToClipboardAlphaTypeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr dataRecordAdapterImpl = + std::make_shared("pixelMap"); + Media::ImageInfo imgInfo; + imgInfo.alphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN; + dataRecordAdapterImpl->ImageToClipboardAlphaType(imgInfo); + imgInfo.alphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_OPAQUE; + dataRecordAdapterImpl->ImageToClipboardAlphaType(imgInfo); + imgInfo.alphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_PREMUL; + dataRecordAdapterImpl->ImageToClipboardAlphaType(imgInfo); + imgInfo.alphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL; + dataRecordAdapterImpl->ImageToClipboardAlphaType(imgInfo); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.h old mode 100755 new mode 100644 index 1eb1929a4ab67b60cd95f964e9f9f00227128829..882e3f6d8e5aff9009355188519c9e9aeae80b75 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/imagetoclipboardalphatype_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "imagetoclipboardalphatype_fuzzer" #endif /* TEST_FUZZTEST_IMAGETOCLIPBOARDALPHATYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardalphatype_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.cpp old mode 100755 new mode 100644 index 4af931bf860360b747b77702d0df3f925fabf3b9..1bce3c0e3e1475fb4aa6dcbd6b6677d27f52c9fd --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.cpp @@ -21,18 +21,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool ImageToClipboardColorTypeFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr dataRecordAdapterImpl = - std::make_shared("pixelMap"); - Media::ImageInfo imgInfo; - dataRecordAdapterImpl->ImageToClipboardColorType(imgInfo); - return true; +bool ImageToClipboardColorTypeFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr dataRecordAdapterImpl = + std::make_shared("pixelMap"); + Media::ImageInfo imgInfo; + dataRecordAdapterImpl->ImageToClipboardColorType(imgInfo); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.h old mode 100755 new mode 100644 index 00671ceefe6ee5bb921b2961fa1c5e8ffa9936c1..f731ed56641f8340c19bc077b29ed4fd448a81ba --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/imagetoclipboardcolortype_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "imagetoclipboardcolortype_fuzzer" #endif /* TEST_FUZZTEST_IMAGETOCLIPBOARDCOLORTYPE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/imagetoclipboardcolortype_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.cpp old mode 100755 new mode 100644 index 5634f1f59cdae66bbfb4c88483ec9ec1c0d38c58..fea1053dff918c30cecdab9332e22a5a7582c196 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.cpp @@ -14,6 +14,7 @@ */ #include "onpasteboardchanged_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; @@ -24,17 +25,17 @@ public: MockPasteboardObserver() = default; void OnPasteboardChanged() override {} }; - bool OnPasteboardChangedFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr observer = std::make_shared(); - PasteboardObserverAdapterImpl observerImpl(observer); - observerImpl.OnPasteboardChanged(); - return true; +bool OnPasteboardChangedFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr observer = std::make_shared(); + PasteboardObserverAdapterImpl observerImpl(observer); + observerImpl.OnPasteboardChanged(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.h old mode 100755 new mode 100644 index 3f53ba2d8e48703ae9239b27a2593830b527a6cd..81fa5411f8fc4fb02a972e04b9a6787ccef8c081 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/onpasteboardchanged_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "onpasteboardchanged_fuzzer" #endif /* TEST_FUZZTEST_ONPASTEBOARDCHANGED_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/onpasteboardchanged_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.cpp old mode 100755 new mode 100644 index 922b281027b6771f239bae6dc0949231644a82fa..c9e93f0c258bce0e98573c96b3dc44fb0c10cea5 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.cpp @@ -14,23 +14,24 @@ */ #include "openremoteuri_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool OpenRemoteUriFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string path((const char*) data, size); - PasteBoardClientAdapterImpl::GetInstance().OpenRemoteUri(path); - PasteBoardClientAdapterImpl::GetInstance().IsLocalPaste(); - PasteBoardClientAdapterImpl::GetInstance().GetTokenId(); - return true; +bool OpenRemoteUriFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string path((const char*)data, size); + PasteBoardClientAdapterImpl::GetInstance().OpenRemoteUri(path); + PasteBoardClientAdapterImpl::GetInstance().IsLocalPaste(); + PasteBoardClientAdapterImpl::GetInstance().GetTokenId(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.h old mode 100755 new mode 100644 index 842ae1b1c0970aa598e099b3dfa060a88b086145..c2cd30f7f50ee3ecf1d92c829da740aa5f6e11a6 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/openremoteuri_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "openremoteuri_fuzzer" #endif /* TEST_FUZZTEST_OPENREMOTEURI_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/openremoteuri_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.cpp old mode 100755 new mode 100644 index 3b8af8dcbba6c489ef982b0fed5339642e3d50a1..151f158f3cc1929062e02e6baa419307d51ae05b --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.cpp @@ -14,6 +14,7 @@ */ #include "removepasteboardchangedobserver_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; @@ -24,15 +25,16 @@ public: MockPasteboardObserver() = default; void OnPasteboardChanged() override {} }; - bool RemovePasteboardChangedObserverFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - PasteBoardClientAdapterImpl::GetInstance().RemovePasteboardChangedObserver(-1); - return true; +bool RemovePasteboardChangedObserverFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + int32_t callbackId = static_cast(size); + PasteBoardClientAdapterImpl::GetInstance().RemovePasteboardChangedObserver(callbackId); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.h old mode 100755 new mode 100644 index 760a97674bc14853e6912c270d34cb38ba05a68e..dae4d331564271c415f34922bad56d01e7c023b5 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/removepasteboardchangedobserver_fuzzer/removepasteboardchangedobserver_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "removepasteboardchangedobserver_fuzzer" #endif /* TEST_FUZZTEST_REMOVEPASTEBOARDCHANGEDOBSERVER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.cpp old mode 100755 new mode 100644 index ea0e4ad1c50fcfea4267b3541748148c1006feb2..320b0d7dfc56c409beeb4036cdeae8a153f122de --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.cpp @@ -14,23 +14,24 @@ */ #include "setcustomdata_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool SetCustomDataFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr dataRecordAdapterImpl = - std::make_shared("pixelMap"); - PasteCustomData testData; - dataRecordAdapterImpl->SetCustomData(testData); - return true; +bool SetCustomDataFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr dataRecordAdapterImpl = + std::make_shared("pixelMap"); + PasteCustomData testData; + dataRecordAdapterImpl->SetCustomData(testData); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.h old mode 100755 new mode 100644 index c61fd755b18a461473ed6088118df5192f8994d5..b81d976e3ce5e7e73ea9148ebeda24ba4dc949e0 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/setcustomdata_fuzzer/setcustomdata_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "setcustomdata_fuzzer" #endif /* TEST_FUZZTEST_SETCUSTOMDATA_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.cpp old mode 100755 new mode 100644 index 071dc1a2e1a34d5964b26d76be730d061dc5b27e..02f642e522081f586eac7ebd0a632d6b8043f072 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.cpp @@ -22,22 +22,22 @@ using namespace OHOS::NWeb; using namespace OHOS::MiscServices; namespace OHOS { - bool SetHtmlTextFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr record = std::make_shared(); - std::shared_ptr dataRecordAdapterImpl = - std::make_shared(record); - dataRecordAdapterImpl->record_=nullptr; - std::string text((const char*) data, size); - std::shared_ptr dataRecordAdapter = PasteDataRecordAdapter::NewRecord(text); - std::shared_ptr htmlText = std::make_shared(text); - dataRecordAdapter->SetHtmlText(htmlText); - return true; +bool SetHtmlTextFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr record = std::make_shared(); + std::shared_ptr dataRecordAdapterImpl = + std::make_shared(record); + dataRecordAdapterImpl->record_ = nullptr; + std::string text((const char*)data, size); + std::shared_ptr dataRecordAdapter = PasteDataRecordAdapter::NewRecord(text); + std::shared_ptr htmlText = std::make_shared(text); + dataRecordAdapter->SetHtmlText(htmlText); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.h old mode 100755 new mode 100644 index 7584422813fb597bcaa8917517d72e9abd2f9fbb..25b7699cc9e22e8ff53ea94fe88e4438b62a5ef1 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/sethtmltext_fuzzer/sethtmltext_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "sethtmltext_fuzzer" #endif /* TEST_FUZZTEST_SETHTMLTEXT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.cpp old mode 100755 new mode 100644 index 809c0ef57df0b810ad6cbb572fbf0303a9329409..d3d6c843cf8b3de52b834394e7f851028ece4212 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.cpp @@ -14,24 +14,25 @@ */ #include "setplaintext_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool SetPlainTextFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string text((const char*) data, size); - std::shared_ptr dataRecordAdapterImpl = - std::make_shared(text); - std::shared_ptr plainText = std::make_shared(text); - dataRecordAdapterImpl->SetPlainText(plainText); - return true; +bool SetPlainTextFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string text((const char*)data, size); + std::shared_ptr dataRecordAdapterImpl = + std::make_shared(text); + std::shared_ptr plainText = std::make_shared(text); + dataRecordAdapterImpl->SetPlainText(plainText); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.h old mode 100755 new mode 100644 index b9684cb3d35a1c51690bd8df84ee0e8829da8466..962c251eef0379ea09ee8e7db390bf073c302be6 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/setplaintext_fuzzer/setplaintext_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "setplaintext_fuzzer" #endif /* TEST_FUZZTEST_SETPLAINTEXT_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/project.xml b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.cpp b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.cpp old mode 100755 new mode 100644 index 7ff035274285075e145426edfa223757fa3c0889..3b9b2cc3e4d1b96c1ff5c2e9388888019329dd07 --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.cpp @@ -14,26 +14,27 @@ */ #include "seturi_fuzzer.h" + #include "pasteboard_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool SetUriFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string text((const char*) data, size); - std::shared_ptr plainText = std::make_shared(text); - std::shared_ptr htmlText = std::make_shared(text); - std::shared_ptr dataRecordAdapterImpl = - PasteDataRecordAdapter::NewRecord(text, htmlText, plainText); - std::string uriString((const char*) data, size); - dataRecordAdapterImpl->SetUri(uriString); - return true; +bool SetUriFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string text((const char*)data, size); + std::shared_ptr plainText = std::make_shared(text); + std::shared_ptr htmlText = std::make_shared(text); + std::shared_ptr dataRecordAdapterImpl = + PasteDataRecordAdapter::NewRecord(text, htmlText, plainText); + std::string uriString((const char*)data, size); + dataRecordAdapterImpl->SetUri(uriString); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.h b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.h old mode 100755 new mode 100644 index b49a05e86aff66d4ab4ae974b30fb05c22420b02..540b1204488009cd99bcd703330653b5c4f1c10f --- a/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.h +++ b/test/fuzztest/ohos_adapter/pasteboard_adapter/seturi_fuzzer/seturi_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "seturi_fuzzer" #endif /* TEST_FUZZTEST_SETURL_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.cpp b/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.cpp index 9b6f95406af21f130fe088b4b27b0247e1f2f493..50b052e68cb6cafe7a871e8378ff1f879778ef64 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.cpp @@ -23,17 +23,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool CreateRunningLockFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::string name((const char *)data, size); - PowerMgrClientAdapterImpl powerMgrClientAdapter; - powerMgrClientAdapter.CreateRunningLock(name, RunningLockAdapterType::SCREEN); - return true; +bool CreateRunningLockFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::string name((const char*)data, size); + PowerMgrClientAdapterImpl powerMgrClientAdapter; + powerMgrClientAdapter.CreateRunningLock(name, RunningLockAdapterType::SCREEN); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.h b/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.h index b67d8cbd109d347260b6b2709b18ffe4d21984a1..9172b2b0184d5980157084cf39f694d7261347d0 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.h +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/createrunninglock_fuzzer/createrunninglock_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "createrunninglock_fuzzer" #endif /* TEST_FUZZTEST_CREATE_RUNNIG_LOCK_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.cpp b/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.cpp index b6dbf09fdac6791a3199bdbfa465a406dbbbd8f8..58b97505e36a33aff15bc603da1933047c54bd09 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.cpp @@ -23,17 +23,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool IsUsedFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr lock; - RunningLockAdapterImpl runningLockAdapter(lock); - runningLockAdapter.IsUsed(); - return true; +bool IsUsedFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr lock; + RunningLockAdapterImpl runningLockAdapter(lock); + runningLockAdapter.IsUsed(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.h b/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.h index 0a384abe3f7fbb1bbd0610c0df8e13f929c6521f..edeabda53c0dc1e753ea5059781c5be90281fe36 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.h +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/isused_fuzzer/isused_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "isused_fuzzer" #endif /* TEST_FUZZTEST_IS_USED_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.cpp b/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.cpp index e7e085f402828810f87de377e0ce87a980fe727d..60f9a317136cff657c80735122c33d44ca369075 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.cpp @@ -23,18 +23,18 @@ using namespace OHOS::NWeb; namespace OHOS { - bool LockFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - uint32_t timeOutMs = static_cast(size); - std::shared_ptr lock; - RunningLockAdapterImpl runningLockAdapter(lock); - runningLockAdapter.Lock(timeOutMs); - return true; +bool LockFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + uint32_t timeOutMs = static_cast(size); + std::shared_ptr lock; + RunningLockAdapterImpl runningLockAdapter(lock); + runningLockAdapter.Lock(timeOutMs); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.h b/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.h index 4b901b4b1070ee7a13a026927973a60edc84de01..93855940db8f7e6178e3b51e70e2d0f1bb806978 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.h +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/lock_fuzzer/lock_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "lock_fuzzer" #endif /* TEST_FUZZTEST_LOCK_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.cpp b/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.cpp index 6ed2b7b1a669f4b9a678f08519780d2c93da91f8..42883ab266a265f29b03b62b6f7c8792db57f23a 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.cpp @@ -23,17 +23,17 @@ using namespace OHOS::NWeb; namespace OHOS { - bool UnLockFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size == 0)) { - return false; - } - std::shared_ptr lock; - RunningLockAdapterImpl runningLockAdapter(lock); - runningLockAdapter.UnLock(); - return true; +bool UnLockFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; } + std::shared_ptr lock; + RunningLockAdapterImpl runningLockAdapter(lock); + runningLockAdapter.UnLock(); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.h b/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.h index 782d3c30f609cfd344039e7cab163d1bbae25ede..82eb9482ba8580cff235aa23c170ecdc168b8b42 100644 --- a/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.h +++ b/test/fuzztest/ohos_adapter/power_mgr_adapter/unlock_fuzzer/unlock_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "unlock_fuzzer" #endif /* TEST_FUZZTEST_UNLOCK_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/printmanager_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/printmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..72d62f9592ed62630297bdc28da0c2fb770791c2 --- /dev/null +++ b/test/fuzztest/ohos_adapter/printmanager_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PrintmanagerFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/printmanager_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/print_manager_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "printmanager_adapter_fuzz.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PrintmanagerFuzzTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/printmanager_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/printmanager_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/printmanager_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/printmanager_fuzzer/printmanager_adapter_fuzz.cpp b/test/fuzztest/ohos_adapter/printmanager_fuzzer/printmanager_adapter_fuzz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d02ceca8098ec0431f21d751e564bf5b221b4747 --- /dev/null +++ b/test/fuzztest/ohos_adapter/printmanager_fuzzer/printmanager_adapter_fuzz.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "printmanager_adapter_fuzz.h" + +#include +#include +#include +#include +#include + +#include "print_manager_adapter_impl.h" + +namespace OHOS::NWeb { + +const size_t MAX_LEN_STRING = 256; +const size_t MAX_FD_LIST_SIZE = 10; + +bool StartPrintFuzzTest(PrintManagerAdapterImpl& adapter, const uint8_t* data, size_t size) +{ + std::vector fileList; + std::vector fdList; + + for (size_t i = 0; i < (size % MAX_FD_LIST_SIZE + 1); ++i) { + std::string fileName(reinterpret_cast(data), std::min(size, MAX_LEN_STRING - 1)); + fileList.push_back(fileName); + fdList.push_back(i); + } + + std::string taskId; + + adapter.StartPrint(fileList, fdList, taskId); + return true; +} + +bool PrintFuzzTest(PrintManagerAdapterImpl& adapter, const uint8_t* data, size_t size) +{ + std::string printJobName(reinterpret_cast(data), std::min(size, MAX_LEN_STRING - 1)); + std::shared_ptr listener = nullptr; + PrintAttributesAdapter printAttributes; + + adapter.Print(printJobName, listener, printAttributes); + return true; +} + +bool PrintWithContextFuzzTest(PrintManagerAdapterImpl& adapter, const uint8_t* data, size_t size) +{ + std::string printJobName(reinterpret_cast(data), std::min(size, MAX_LEN_STRING - 1)); + std::shared_ptr listener = nullptr; + PrintAttributesAdapter printAttributes; + void* contextToken = nullptr; + + adapter.Print(printJobName, listener, printAttributes, contextToken); + + return true; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + if (size == 0) { + return 0; + } + + PrintManagerAdapterImpl& adapter = PrintManagerAdapterImpl::GetInstance(); + + enum PrintFuzzOperation { START_PRINT, PRINT, PRINT_WITH_CONTEXT, MAX_PRINT_OPERATION }; + + PrintFuzzOperation operation = static_cast(data[0] % MAX_PRINT_OPERATION); + + switch (operation) { + case START_PRINT: + return StartPrintFuzzTest(adapter, data + 1, size - 1); + case PRINT: + return PrintFuzzTest(adapter, data + 1, size - 1); + case PRINT_WITH_CONTEXT: + return PrintWithContextFuzzTest(adapter, data + 1, size - 1); + default: + return 0; + } + + return 0; +} + +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/printmanager_fuzzer/printmanager_adapter_fuzz.h b/test/fuzztest/ohos_adapter/printmanager_fuzzer/printmanager_adapter_fuzz.h new file mode 100644 index 0000000000000000000000000000000000000000..4713e91ccb16c6a72ea64f38819b6c2c61636ef6 --- /dev/null +++ b/test/fuzztest/ohos_adapter/printmanager_fuzzer/printmanager_adapter_fuzz.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINTMANAGER_ADAPTER_FUZZ_TEST_H +#define PRINTMANAGER_ADAPTER_FUZZ_TEST_H + +#define FUZZ_PROJECT_NAME "printmanageradapter_fuzzer" + +#endif // PRINTMANAGER_ADAPTER_FUZZ_TEST_H \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/printmanager_fuzzer/project.xml b/test/fuzztest/ohos_adapter/printmanager_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/printmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a602042c8e989484e0f93979a1685e5a29c26feb --- /dev/null +++ b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("ResSchedAdapterFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/resschedadapter_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/res_sched_adapter/src", + "$webview_path/ohos_interface/include/ohos_adapter", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "resschedadapter_fuzz.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ResSchedAdapterFuzzTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/project.xml b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/resschedadapter_fuzz.cpp b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/resschedadapter_fuzz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0fd7a7a8650cf4ba168e270f2e6b7efd98c6dc2 --- /dev/null +++ b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/resschedadapter_fuzz.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "resschedadapter_fuzz.h" + +#include +#include +#include +#include +#include +#include + +#include "res_sched_client_adapter.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +namespace NWeb { + +bool ResSchedAdapterFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return false; + } + + pid_t pid = 1; + pid_t tid = 1; + int32_t nwebId = static_cast(size); + uint32_t windowId = static_cast(size); + + std::vector statuses = { ResSchedStatusAdapter::WEB_ACTIVE, + ResSchedStatusAdapter::WEB_INACTIVE, ResSchedStatusAdapter::THREAD_CREATED, + ResSchedStatusAdapter::THREAD_DESTROYED, ResSchedStatusAdapter::VIDEO_PLAYING_START, + ResSchedStatusAdapter::VIDEO_PLAYING_STOP, ResSchedStatusAdapter::SCREEN_CAPTURE_START, + ResSchedStatusAdapter::SCREEN_CAPTURE_STOP, ResSchedStatusAdapter::AUDIO_STATUS_START, + ResSchedStatusAdapter::AUDIO_STATUS_STOP, ResSchedStatusAdapter::WEB_SCENE_ENTER, + ResSchedStatusAdapter::WEB_SCENE_EXIT }; + + std::vector roles = { ResSchedRoleAdapter::USER_INTERACT, ResSchedRoleAdapter::NORMAL_DISPLAY, + ResSchedRoleAdapter::IMPORTANT_DISPLAY, ResSchedRoleAdapter::NORMAL_AUDIO, ResSchedRoleAdapter::IMPORTANT_AUDIO, + ResSchedRoleAdapter::IMAGE_DECODE }; + + ResSchedClientAdapter adapter; + + for (auto status : statuses) { + adapter.ReportVideoPlaying(status, pid); + adapter.ReportScreenCapture(status, pid); + adapter.ReportRenderProcessStatus(status, pid); + adapter.ReportNWebInit(status, nwebId); + adapter.ReportWindowId(windowId, nwebId); + + for (auto role : roles) { + adapter.ReportKeyThread(status, pid, tid, role); + } + + adapter.ReportAudioData(status, pid, tid); + adapter.ReportProcessInUse(pid); + adapter.ReportSiteIsolationMode(true); + adapter.ReportWindowStatus(status, pid, windowId, nwebId); + adapter.ReportScene(status, ResSchedSceneAdapter::CLICK, nwebId); + adapter.ReportScene(status, ResSchedSceneAdapter::LOAD_URL, nwebId); + } + + adapter.ReportProcessInUse(0); + adapter.ReportWindowId(0, nwebId); + adapter.ReportKeyThread(statuses[0], pid, tid, static_cast(-1)); + adapter.ReportAudioData(statuses[0], pid, 0); + adapter.ReportSiteIsolationMode(true); + + adapter.ReportWindowId(0, nwebId); + adapter.ReportKeyThread(statuses[0], -1, tid, ResSchedRoleAdapter::USER_INTERACT); + adapter.ReportAudioData(statuses[0], pid, -1); + adapter.ReportWindowStatus(statuses[0], pid, windowId, -1); + adapter.ReportNWebInit(ResSchedStatusAdapter::WEB_SCENE_EXIT, -1); + + return true; +} +} // namespace NWeb +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::NWeb::ResSchedAdapterFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/resschedadapter_fuzz.h b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/resschedadapter_fuzz.h new file mode 100644 index 0000000000000000000000000000000000000000..e76feeffc228632d2fcfedc29c4fd06ac3dded61 --- /dev/null +++ b/test/fuzztest/ohos_adapter/resschedadapter_fuzzer/resschedadapter_fuzz.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_RES_SCHED_ADAPTER_FUZZ_H +#define TEST_FUZZTEST_RES_SCHED_ADAPTER_FUZZ_H + +#define FUZZ_PROJECT_NAME "resschedadapter_fuzzer" +#endif /* TEST_FUZZTEST_RES_SCHED_ADAPTER_FUZZ_H */ diff --git a/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3c43b2c7997f413428cb983293e267b339d9bef6 --- /dev/null +++ b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("SetAndGetRunWebInitCallBackFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/ohos_init_web_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "setandgetrunwebinitcallback_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SetAndGetRunWebInitCallBackFuzzTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..6248ced8998b9ad42ba75fe60592b2044dd9446a --- /dev/null +++ b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/project.xml b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..7133b2b92440904a5ed04b838733acea0f97486a --- /dev/null +++ b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/setandgetrunwebinitcallback_fuzzer.cpp b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/setandgetrunwebinitcallback_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9dcf956fac37222caad07aaddd04408fe6a23193 --- /dev/null +++ b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/setandgetrunwebinitcallback_fuzzer.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "setandgetrunwebinitcallback_fuzzer.h" + +#include "ohos_init_web_adapter_impl.h" + +using namespace OHOS::NWeb; + +namespace OHOS::NWeb { +bool SetAndGetCallbackFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(WebRunInitedCallback*))) { + return false; + } + + // Assuming data is a pointer to a valid WebRunInitedCallback if not nullptr + WebRunInitedCallback* callback = reinterpret_cast(const_cast(data)); + + // Create instance of OhosInitWebAdapterImpl + std::shared_ptr webAdapterImpl = std::make_shared(); + + // Set and get the callback + webAdapterImpl->SetRunWebInitedCallback(callback); + webAdapterImpl->GetRunWebInitedCallback(); + + // Optionally if returnedCallback is callable, call its run method. + + return true; +} +} // namespace OHOS::NWeb + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + // Run your code on data + OHOS::NWeb::SetAndGetCallbackFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/setandgetrunwebinitcallback_fuzzer.h b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/setandgetrunwebinitcallback_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..61fd030db9379159a93a13d41189a9d0faeb1b45 --- /dev/null +++ b/test/fuzztest/ohos_adapter/setandgetrunwebinitedcallback_fuzzer/setandgetrunwebinitcallback_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_SETANDGETCALLBACK_FUZZER_H +#define TEST_FUZZTEST_SETANDGETCALLBACK_FUZZER_H + +#define FUZZ_PROJECT_NAME "setandgetcallback_fuzzer" + +#endif /* TEST_FUZZTEST_SETANDGETCALLBACK_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.cpp b/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.cpp old mode 100755 new mode 100644 index f9439c30c98bfc05217df0f1f3028b9e2f8026c2..30e29fe5432a83b1008b469844995b1c4c09aaa5 --- a/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.cpp +++ b/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.cpp @@ -16,25 +16,24 @@ #include "applysocperfconfigbyid_fuzzer.h" #include + #include "soc_perf_client_adapter_impl.h" using namespace OHOS::NWeb; namespace OHOS { - bool ApplySocPerfConfigByIdFuzzTest(const uint8_t* data, size_t size) - { - if ((data == nullptr) || (size < sizeof(int32_t))) { - return false; - } - int32_t id; - if (memcpy_s(&id, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } - SocPerfClientAdapterImpl perfClientAdapterImpl; - perfClientAdapterImpl.ApplySocPerfConfigById(id); - return true; +bool ApplySocPerfConfigByIdFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return false; } + int32_t id = static_cast(size); + + SocPerfClientAdapterImpl perfClientAdapterImpl; + perfClientAdapterImpl.ApplySocPerfConfigById(id); + return true; } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.h b/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.h old mode 100755 new mode 100644 index 5d2c9b17241f41e0e232042a8878873e514d2728..0f59a7424a052cef93b524cbc4cc387938c6673a --- a/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.h +++ b/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/applysocperfconfigbyid_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "applysocperfconfigbyid_fuzzer" #endif /* TEST_FUZZTEST_APPLYSOCPERFCONFIGBYID_FUZZER_H */ - diff --git a/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/corpus/init old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/project.xml b/test/fuzztest/ohos_adapter/soc_perf_adapter/applysocperfconfigbyid_fuzzer/project.xml old mode 100755 new mode 100644 diff --git a/test/fuzztest/ohos_adapter/systemproperties_fuzzer/BUILD.gn b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c9667146f5adbc2c2c4c8caebc59f680f2d6e8e7 --- /dev/null +++ b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("SystemPropertiesFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = + "$webview_path/test/fuzztest/ohos_adapter/systemproperties_fuzzer" + include_dirs = [ + "$webview_path/ohos_adapter/system_properties_adapter/include", + "$webview_path/test/fuzztest", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "system_properties_adapter_impl_fuzzer.cpp" ] + deps = [ "$webview_path/ohos_adapter:nweb_ohos_adapter" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "c_utils:utils", + "image_framework:image_native", + "pasteboard:pasteboard_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SystemPropertiesFuzzTest", + ] +} diff --git a/test/fuzztest/ohos_adapter/systemproperties_fuzzer/corpus/init b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_adapter/systemproperties_fuzzer/project.xml b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_adapter/systemproperties_fuzzer/system_properties_adapter_impl_fuzzer.cpp b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/system_properties_adapter_impl_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd589fbce3ace948612f48d09a217f1b5ca00090 --- /dev/null +++ b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/system_properties_adapter_impl_fuzzer.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "system_properties_adapter_impl_fuzzer.h" + +#include +#include +#include + +#include "system_properties_adapter_impl.h" + +namespace OHOS { + +bool SystemPropertiesAdapterFuzzTest(const uint8_t* data, size_t size) +{ + size_t keySize = std::min(size, static_cast(32)); + std::string key(reinterpret_cast(data), keySize); + + size_t valueSize = size > keySize ? size - keySize : 0; + std::string value(reinterpret_cast(data + keySize), valueSize); + + bool boolResult = NWeb::SystemPropertiesAdapterImpl::GetInstance().GetBoolParameter(key, false); + std::string productModel = NWeb::SystemPropertiesAdapterImpl::GetInstance().GetDeviceInfoProductModel(); + std::string brand = NWeb::SystemPropertiesAdapterImpl::GetInstance().GetDeviceInfoBrand(); + int32_t majorVersion = NWeb::SystemPropertiesAdapterImpl::GetInstance().GetSoftwareMajorVersion(); + int32_t seniorVersion = NWeb::SystemPropertiesAdapterImpl::GetInstance().GetSoftwareSeniorVersion(); + + (void)boolResult; + (void)productModel; + (void)brand; + (void)majorVersion; + (void)seniorVersion; + + return true; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + return OHOS::SystemPropertiesAdapterFuzzTest(data, size) ? 0 : 1; +} + +} // namespace OHOS \ No newline at end of file diff --git a/test/fuzztest/ohos_adapter/systemproperties_fuzzer/system_properties_adapter_impl_fuzzer.h b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/system_properties_adapter_impl_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..7306a15b4ea9d2bea85963184cd534c625129c3b --- /dev/null +++ b/test/fuzztest/ohos_adapter/systemproperties_fuzzer/system_properties_adapter_impl_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_SYSTEM_PROPERTIES_ADAPTER_IMPL_FUZZER_H +#define TEST_FUZZTEST_SYSTEM_PROPERTIES_ADAPTER_IMPL_FUZZER_H + +#define FUZZ_PROJECT_NAME "system_properties_adapter_impl_fuzzer" + +#endif /* TEST_FUZZTEST_SYSTEM_PROPERTIES_ADAPTER_IMPL_FUZZER_H */ \ No newline at end of file diff --git a/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.cpp b/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.cpp index d9ba3d19cc330c11fb5bfb3f976ab299de753f9b..7f2e146e1f83c0052808ef8bcfb113aac5adbda9 100644 --- a/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.cpp @@ -48,7 +48,7 @@ bool CopyFrameFuzzTest(const uint8_t* data, size_t size) if (width == 0 || height == 0) { return false; } - char *src = new char[BITS_PER_PIXEL] {0}; + char* src = new char[BITS_PER_PIXEL] { 0 }; if (src == nullptr) { return false; } @@ -56,7 +56,7 @@ bool CopyFrameFuzzTest(const uint8_t* data, size_t size) delete[] src; return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.h b/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.h index 0ca40a9f29b2312cb9d95bdc42e3ab9b45f5878a..a30c41a98c0d3187cac82a5d9c5faaceb528706c 100644 --- a/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.h +++ b/test/fuzztest/ohos_nweb/copyframe_fuzzer/copyframe_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "copyframe_fuzzer" #endif /* TEST_FUZZTEST_COPYFRAME_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.cpp b/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.cpp index 36967be531225602bedcaf6eb6fa3e175b5d7455..2dda4a8ca811fe62ad0f3dcd89c014cdf5eea0eb 100644 --- a/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.cpp @@ -56,15 +56,15 @@ bool FlushBufferFuzzTest(const uint8_t* data, size_t size) return false; } g_surface = surfaceNode->GetSurface(); - if (g_surface== nullptr) { + if (g_surface == nullptr) { return false; } } - std::string result(reinterpret_cast(data), size); + std::string result(reinterpret_cast(data), size); surfaceAdapter.FlushBuffer(g_surface, surfaceBuffer, width, height); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.h b/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.h index 8f6c48e08b53dd3bb53f0fe6eb4a53eb43183b10..47089a3adee49e911d55170e0e9deebccd2b4ba9 100644 --- a/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.h +++ b/test/fuzztest/ohos_nweb/flushbuffer_fuzzer/flushbuffer_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "flushbuffer_fuzzer" #endif /* TEST_FUZZTEST_FLUSHBUFFER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.cpp b/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.cpp index c7ca6734a4a7172537adaae655750fc1422b0855..fd5acd38d00dcf742be2a2b1f02d286dfbcec37c 100644 --- a/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.cpp @@ -31,7 +31,7 @@ bool GetCookieManagerFuzzTest(const uint8_t* data, size_t size) NWebHelper::Instance().GetCookieManager(); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.h b/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.h index e2b775176af80f474528cc89f58a22855bfeb999..8a6a134b57606c861dfef2e1fd19076ba92c3cd2 100644 --- a/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.h +++ b/test/fuzztest/ohos_nweb/getcookiemanager_fuzzer/getcookiemanager_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getcookiemanager_fuzzer" #endif /* TEST_FUZZTEST_GETCOOKIEMANAGER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.cpp b/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.cpp index 55b58c069960b6081af7cfad446c7ed1fe3653f7..bcf2271e71b947278494ee9cca171e538aecd772 100644 --- a/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.cpp @@ -31,7 +31,7 @@ bool GetDataBaseFuzzTest(const uint8_t* data, size_t size) NWebHelper::Instance().GetDataBase(); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.h b/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.h index b15ab060ab4c22168040a5ecc96f032d3f50c487..7b74961fde8b7a309e02dbcbe440da8137643858 100644 --- a/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.h +++ b/test/fuzztest/ohos_nweb/getdatabase_fuzzer/getdatabase_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getdatabase_fuzzer" #endif /* TEST_FUZZTEST_GETDATABASE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.cpp b/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.cpp index f29cf027f3bc4ba7cd4400df258b9e496eb2d063..d330b430623fdd86fb05126cb4f13f7bad2c5dde 100644 --- a/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.cpp @@ -25,17 +25,16 @@ using namespace OHOS::NWeb; namespace OHOS { bool GetNwebFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(int32_t))) { - return false; - } - int32_t nweb_id; - if (memcpy_s(&nweb_id, sizeof(int32_t), data, sizeof(int32_t)) != 0) { - return false; - } + int32_t nweb_id = static_cast(size); + NWebHelper::Instance().GetNWeb(nweb_id); + + NWebHelper::Instance().SetWebTag(nweb_id, "NWeb"); + + NWebHelper::Instance().PrepareForPageLoad("", true, size); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.h b/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.h index d33eb20124e27a63549d875cc1bda754f4db7d83..747f4bf31b9d914b3fc740eda66aafeaf197a77f 100644 --- a/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.h +++ b/test/fuzztest/ohos_nweb/getnweb_fuzzer/getnweb_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getnweb_fuzzer" #endif /* TEST_FUZZTEST_GETNWEB_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.cpp b/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.cpp index 27ac46eeb3cba6a6d896306ad29cb17f1b9d577d..20760370e7d0dfeb978b2495098aca97fadc2229 100644 --- a/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.cpp @@ -31,7 +31,7 @@ bool GetWebStorageFuzzTest(const uint8_t* data, size_t size) NWebHelper::Instance().GetWebStorage(); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.h b/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.h index ce5874611004a9c8d5c8004922d5eba5d7903d42..8112f36dad2a121d5acb8d7deb42655601aba07f 100644 --- a/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.h +++ b/test/fuzztest/ohos_nweb/getwebstorage_fuzzer/getwebstorage_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "getwebstorage_fuzzer" #endif /* TEST_FUZZTEST_GETWEBSTORAGE_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/hisysevent_fuzzer/BUILD.gn b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2c9a428afa168fd343e63eef626e67481fad2baa --- /dev/null +++ b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("HiSysEventFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_nweb/hisysevent_fuzzer" + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$window_manager_path/interfaces/innerkits/wm", + "$webview_path/test/fuzztest", + "$webview_path/ohos_nweb/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "hisysevent_fuzzer.cpp" ] + deps = [ "$graphic2d_path/rosen/modules/render_service_client:librender_service_client" ] + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "webview:libnweb", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":HiSysEventFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_nweb/hisysevent_fuzzer/corpus/init b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_nweb/hisysevent_fuzzer/hisysevent_fuzzer.cpp b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/hisysevent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c23cde730b9c1a37bfef10ce7a6d6e20b290f157 --- /dev/null +++ b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/hisysevent_fuzzer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hisysevent_fuzzer.h" + +#include +#include + +#include "nweb_hisysevent.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool HiSysEventFuzzTest(const uint8_t* data, size_t size) +{ + if (data == nullptr || size < sizeof(int32_t)) { + return false; + } + int32_t nwebId; + if (memcpy_s(&nwebId, sizeof(int32_t), data, sizeof(int32_t)) != EOK) { + return false; + } + EventReport::ReportCreateWebInstanceTime(nwebId, nwebId); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::HiSysEventFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_nweb/hisysevent_fuzzer/hisysevent_fuzzer.h b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/hisysevent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..58a3b2a8f2bee5022231607c76995dc5e20cc6b9 --- /dev/null +++ b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/hisysevent_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_HISYSEVENT_FUZZER_H +#define TEST_FUZZTEST_HISYSEVENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "hisysevent_fuzzer" +#endif /* TEST_FUZZTEST_HISYSEVENT_FUZZER_H */ diff --git a/test/fuzztest/ohos_nweb/hisysevent_fuzzer/project.xml b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_nweb/hisysevent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_nweb/initandrun_fuzzer/BUILD.gn b/test/fuzztest/ohos_nweb/initandrun_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3ae88826a9c20055cca4dfe92a2221b7d04d998c --- /dev/null +++ b/test/fuzztest/ohos_nweb/initandrun_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("InitAndRunFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_nweb/initandrun_fuzzer" + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$window_manager_path/interfaces/innerkits/wm", + "$webview_path/test/fuzztest", + "$webview_path/ohos_nweb/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "initandrun_fuzzer.cpp" ] + deps = [ "$graphic2d_path/rosen/modules/render_service_client:librender_service_client" ] + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "webview:libnweb", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":InitAndRunFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_nweb/initandrun_fuzzer/corpus/init b/test/fuzztest/ohos_nweb/initandrun_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_nweb/initandrun_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_nweb/initandrun_fuzzer/initandrun_fuzzer.cpp b/test/fuzztest/ohos_nweb/initandrun_fuzzer/initandrun_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc6fdf41b88bfefd9c8e8179a6d1119f86e2f9ce --- /dev/null +++ b/test/fuzztest/ohos_nweb/initandrun_fuzzer/initandrun_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "initandrun_fuzzer.h" + +#include +#include + +#include "nweb_helper.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool InitAndRunFuzzTest(const uint8_t* data, size_t size) +{ + const std::string path("/data/app/el1/bundle/public/com.ohos.nweb"); + NWebHelper::Instance().SetBundlePath(path); + + NWebHelper::Instance().InitAndRun(false); + + if (data == nullptr) { + return false; + } + std::string pathTmp(reinterpret_cast(data), size); + NWebHelper::Instance().SetBundlePath(pathTmp); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::InitAndRunFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_nweb/initandrun_fuzzer/initandrun_fuzzer.h b/test/fuzztest/ohos_nweb/initandrun_fuzzer/initandrun_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..0704b3f49a9cc6a4217bc524b62035374176a3b3 --- /dev/null +++ b/test/fuzztest/ohos_nweb/initandrun_fuzzer/initandrun_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_INIT_AND_RUN_FUZZER_H +#define TEST_FUZZTEST_INIT_AND_RUN_FUZZER_H + +#define FUZZ_PROJECT_NAME "initandrun_fuzzer" +#endif /* TEST_FUZZTEST_INIT_AND_RUN_FUZZER_H */ diff --git a/test/fuzztest/ohos_nweb/initandrun_fuzzer/project.xml b/test/fuzztest/ohos_nweb/initandrun_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_nweb/initandrun_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.cpp b/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.cpp index 86515d924bbb9277c5a95d51934dd1a428b88c6b..ddda1227ec346239ee248a20e482c29fe2d5f8f0 100644 --- a/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.cpp @@ -29,10 +29,17 @@ bool LoadLibFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size == 0)) { return false; } + + const std::string path("/data/app/el1/bundle/public/com.ohos.nweb"); + NWebHelper::Instance().SetBundlePath(path); + NWebAdapterHelper::Instance().Init(true); + + NWebAdapterHelper::Instance().Init(false); + return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.h b/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.h index ea926e43cdfaa21639d75a66b0834d57a70aceed..cff41d948ff3b17962db38359b09d884d608f474 100644 --- a/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.h +++ b/test/fuzztest/ohos_nweb/loadlib_fuzzer/loadlib_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "loadlib_fuzzer" #endif /* TEST_FUZZTEST_LOADLIB_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/napi_fuzzer/BUILD.gn b/test/fuzztest/ohos_nweb/napi_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..36f778a40b43380ef7d6eed7fbc0b08b34a06222 --- /dev/null +++ b/test/fuzztest/ohos_nweb/napi_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("NapiFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_nweb/napi_fuzzer" + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$window_manager_path/interfaces/innerkits/wm", + "$webview_path/test/fuzztest", + "$webview_path/ohos_nweb/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "napi_fuzzer.cpp" ] + deps = [ "$graphic2d_path/rosen/modules/render_service_client:librender_service_client" ] + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "webview:libnweb", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":NapiFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_nweb/napi_fuzzer/corpus/init b/test/fuzztest/ohos_nweb/napi_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_nweb/napi_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_nweb/napi_fuzzer/napi_fuzzer.cpp b/test/fuzztest/ohos_nweb/napi_fuzzer/napi_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71319b9ca429e02399c223620b5365c526685bbf --- /dev/null +++ b/test/fuzztest/ohos_nweb/napi_fuzzer/napi_fuzzer.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_fuzzer.h" + +#include +#include + +#include "nweb_c_api.h" +#include "nweb_helper.h" + +using namespace OHOS::NWeb; + +namespace OHOS { +bool NapiFuzzTest(const uint8_t* data, size_t size) +{ + const std::string path("/data/app/el1/bundle/public/com.ohos.nweb"); + NWebHelper::Instance().SetBundlePath(path); + + NWebHelper::Instance().Init(false); + + if (NWebHelper::Instance().LoadNWebSDK()) { + WebDownloadManager_PutDownloadCallback(nullptr); + WebDownloader_SetDownloadBeforeStart(nullptr, nullptr); + WebDownloader_SetDownloadDidUpdate(nullptr, nullptr); + WebDownloader_ResumeDownloadStatic(nullptr); + WebDownloader_StartDownload(size, NULL); + WebDownloader_CreateDownloadDelegateCallback(nullptr); + WebDownload_Continue(nullptr, nullptr); + WebDownload_CancelBeforeDownload(nullptr); + WebDownload_PauseBeforeDownload(nullptr); + WebDownload_ResumeBeforeDownload(nullptr); + WebDownload_Cancel(nullptr); + WebDownload_Pause(nullptr); + WebDownload_Resume(nullptr); + + WebDownload_GetItemState(size, size); + if (data != nullptr && size != 0) { + std::string dataTmp(reinterpret_cast(data), size); + WebDownload_GetItemStateByGuid(dataTmp); + } + WebDownloadItem_Guid(nullptr); + WebDownloadItem_GetDownloadItemId(nullptr); + WebDownloadItem_GetState(nullptr); + WebDownloadItem_CurrentSpeed(nullptr); + WebDownloadItem_PercentComplete(nullptr); + WebDownloadItem_TotalBytes(nullptr); + WebDownloadItem_ReceivedBytes(nullptr); + WebDownloadItem_FullPath(nullptr); + WebDownloadItem_Url(nullptr); + WebDownloadItem_OriginalUrl(nullptr); + WebDownloadItem_SuggestedFileName(nullptr); + WebDownloadItem_ContentDisposition(nullptr); + WebDownloadItem_ETag(nullptr); + WebDownloadItem_MimeType(nullptr); + WebDownloadItem_IsPaused(nullptr); + WebDownloadItem_Method(nullptr); + WebDownloadItem_LastErrorCode(nullptr); + WebDownloadItem_ReceivedSlices(nullptr); + WebDownloadItem_LastModified(nullptr); + WebDownloadItem_NWebId(nullptr); + WebDownloadItem_CreateWebDownloadItem(nullptr); + WebDownloadItem_Destroy(nullptr); + DestroyBeforeDownloadCallbackWrapper(nullptr); + DestroyDownloadItemCallbackWrapper(nullptr); + WebDownloadItem_SetGuid(nullptr, nullptr); + WebDownloadItem_SetUrl(nullptr, nullptr); + WebDownloadItem_SetFullPath(nullptr, nullptr); + WebDownloadItem_SetETag(nullptr, nullptr); + WebDownloadItem_SetLastModified(nullptr, nullptr); + WebDownloadItem_SetMimeType(nullptr, nullptr); + WebDownloadItem_SetReceivedBytes(nullptr, size); + WebDownloadItem_SetTotalBytes(nullptr, size); + WebDownloadItem_SetReceivedSlices(nullptr, nullptr); + } + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::NapiFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_nweb/napi_fuzzer/napi_fuzzer.h b/test/fuzztest/ohos_nweb/napi_fuzzer/napi_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..bfb1090e7a85938f75575888f2cfaa2e386bc289 --- /dev/null +++ b/test/fuzztest/ohos_nweb/napi_fuzzer/napi_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_NAPI_FUZZER_H +#define TEST_FUZZTEST_NAPI_FUZZER_H + +#define FUZZ_PROJECT_NAME "napi_fuzzer" +#endif /* TEST_FUZZTEST_GETNWEB_FUZZER_H */ diff --git a/test/fuzztest/ohos_nweb/napi_fuzzer/project.xml b/test/fuzztest/ohos_nweb/napi_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_nweb/napi_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/BUILD.gn b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..19708d95d9197f0c7f45c4b415e75af42942accc --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//base/web/webview/web_aafwk.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("NWebHelperFuzzTest") { + module_out_path = webview_fuzz_test_path + fuzz_config_file = "$webview_path/test/fuzztest/ohos_nweb/nwebhelper_fuzzer" + + include_dirs = [ + "$webview_path/test/ohos_nweb", + "$window_manager_path/interfaces/innerkits/wm", + "$webview_path/test/fuzztest", + "$webview_path/ohos_nweb/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "nweb_create_window.cpp", + "nwebhelper_fuzzer.cpp", + ] + + deps = [ + "$graphic2d_path/rosen/modules/render_service_client:librender_service_client", + "$webview_path/ohos_nweb:web_configs", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_runtime:app_context", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "webview:libnweb", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":NWebHelperFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/corpus/init b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e03503f8636d71b44a2fe2f57c5bed2701a0cf3f --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/corpus/init @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +FUZZ diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nweb_create_window.cpp b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nweb_create_window.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3796ba62c36fb4fca8d0ffa894468deb66b21c0e --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nweb_create_window.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "nweb_create_window.h" + +#include +#include +#include +#include + +#include "nweb_adapter_helper.h" + +using namespace OHOS; +namespace OHOS::NWeb { +namespace { +const std::string ARG_URL = "--url"; +const std::string ARG_DUMP = "--dump-path"; +const std::string ARG_FRAME_INFO = "--frame-info"; +const std::string ARG_ADD_WEB_ENGINE_ARG = "--add-args"; +const std::string ARG_DELETE_WEB_ENGINE_ARG = "--delete-args"; +const std::string ARG_MULTI_RENDER_PROCESS = "--multi-renderer-process"; +const std::string ARG_NWEB_TEST_MOCK_BUNDLEPATH = "--bundle-installation-dir"; +const std::string MOCK_INSTALLATION_DIR = "/data/app/el1/bundle/public/com.ohos.nweb"; +const std::string ARG_WIDTH = "--width"; +const std::string ARG_HEIGHT = "--height"; +std::unordered_map g_argsMap; +sptr g_surface = nullptr; +} // namespace + +static bool HasArg(const std::string& arg) +{ + return (!g_argsMap.empty()) && (g_argsMap.find(arg) != g_argsMap.end()); +} + +static std::string GetArgValue(const std::string& arg) +{ + if (!HasArg(arg)) { + return ""; + } + return g_argsMap.at(arg); +} + +static std::list GetWebEngineArgs(const std::string& arg) +{ + std::string webEngineArgValue = GetArgValue(arg); + std::list webEngineArgList; + if (webEngineArgValue.empty()) { + return webEngineArgList; + } + uint32_t start = 0; + uint32_t pos = 0; + while (pos < webEngineArgValue.size()) { + if (webEngineArgValue[pos] == ',') { + webEngineArgList.emplace_back(webEngineArgValue.substr(start, pos - start)); + pos++; + start = pos; + } else { + pos++; + } + } + webEngineArgList.emplace_back(webEngineArgValue.substr(start, pos - start)); + webEngineArgList.emplace_back(ARG_NWEB_TEST_MOCK_BUNDLEPATH + "=" + MOCK_INSTALLATION_DIR); + return webEngineArgList; +} + +std::shared_ptr GetInitArgs(void) +{ + std::shared_ptr initArgs = std::make_shared(); + initArgs->SetDumpPath(GetArgValue(ARG_DUMP)); + initArgs->SetIsFrameInfoDump(HasArg(ARG_FRAME_INFO) ? true : false); + initArgs->SetIsMultiRendererProcess(HasArg(ARG_MULTI_RENDER_PROCESS) ? true : false); + initArgs->SetArgsToAdd(GetWebEngineArgs(ARG_ADD_WEB_ENGINE_ARG)); + initArgs->SetArgsToDelete(GetWebEngineArgs(ARG_DELETE_WEB_ENGINE_ARG)); + return initArgs; +} + +std::shared_ptr GetNwebForTest() +{ + if (!g_surface) { + Rosen::RSSurfaceNodeConfig config; + config.SurfaceNodeName = "webTestSurfaceName"; + auto surfaceNode = Rosen::RSSurfaceNode::Create(config, false); + if (surfaceNode == nullptr) { + return nullptr; + } + g_surface = surfaceNode->GetSurface(); + if (g_surface == nullptr) { + return nullptr; + } + } + return NWebAdapterHelper::Instance().CreateNWeb(g_surface, GetInitArgs()); +} +} // namespace OHOS::NWeb diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nweb_create_window.h b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nweb_create_window.h new file mode 100644 index 0000000000000000000000000000000000000000..d60d60d0e560690b949ad0d08abb58808061630d --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nweb_create_window.h @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NWEB_CREAT_WINDOW_H +#define NWEB_CREAT_WINDOW_H + +#include "nweb.h" +#include "nweb_init_params.h" + +#define private public +#include "ui/rs_surface_node.h" +#undef private + +namespace OHOS::NWeb { +std::shared_ptr GetInitArgs(void); +std::shared_ptr GetNwebForTest(); + +class NWebMock : public NWeb { +public: + void Resize(uint32_t width, uint32_t height, bool isKeyboard = false) override {} + void OnPause() override {} + void OnContinue() override {} + void OnDestroy() override {} + void OnFocus(const FocusReason& focusReason = FocusReason::FOCUS_DEFAULT) override {} + void OnBlur(const BlurReason& blurReason) override {} + void OnTouchPress(int32_t id, double x, double y, bool fromOverlay = false) override {} + void OnTouchRelease(int32_t id, double x = 0, double y = 0, bool fromOverlay = false) override {} + void OnTouchMove(int32_t id, double x, double y, bool fromOverlay = false) override {} + void OnTouchMove( + const std::vector>& touch_point_infos, bool fromOverlay = false) override + {} + void OnTouchCancel() override {} + void OnNavigateBack() override {} + bool SendKeyEvent(int32_t keyCode, int32_t keyAction) override + { + return true; + } + void SendMouseWheelEvent(double x, double y, double deltaX, double deltaY) override {} + void SendMouseEvent(int x, int y, int button, int action, int count) override {} + int Load(const std::string& url) override + { + return 0; + } + bool IsNavigatebackwardAllowed() override + { + return true; + } + bool IsNavigateForwardAllowed() override + { + return true; + } + bool CanNavigateBackOrForward(int numSteps) override + { + return true; + } + void NavigateBack() override {} + void NavigateForward() override {} + void NavigateBackOrForward(int step) override {} + void DeleteNavigateHistory() override {} + void Reload() override {} + int Zoom(float zoomFactor) override + { + return 0; + } + int ZoomIn() override + { + return 0; + } + int ZoomOut() override + { + return 0; + } + void Stop() override {} + void ExecuteJavaScript(const std::string& code) override {} + void ExecuteJavaScript( + const std::string& code, std::shared_ptr callback, bool extention) override + {} + std::shared_ptr GetPreference() override + { + return nullptr; + } + unsigned int GetWebId() override + { + return 0; + } + std::shared_ptr GetHitTestResult() override + { + std::shared_ptr test; + return test; + } + void PutBackgroundColor(int color) override {} + void InitialScale(float scale) override {} + void PutDownloadCallback(std::shared_ptr downloadListener) override {} + void PutReleaseSurfaceCallback(std::shared_ptr releaseSurfaceListener) override {} + void SetNWebHandler(std::shared_ptr handler) override {} + std::string Title() override + { + return nullptr; + } + int PageLoadProgress() override + { + return 0; + } + int ContentHeight() override + { + return 0; + } + float Scale() override + { + return 0; + } + int Load(const std::string& url, const std::map& additionalHttpHeaders) override + { + return 0; + } + int LoadWithDataAndBaseUrl(const std::string& baseUrl, const std::string& data, const std::string& mimeType, + const std::string& encoding, const std::string& historyUrl) override + { + return 0; + } + int LoadWithData(const std::string& data, const std::string& mimeType, const std::string& encoding) override + { + return 0; + } + void RegisterArkJSfunction( + const std::string& object_name, const std::vector& method_list, const int32_t object_id) override + {} + void UnregisterArkJSfunction(const std::string& object_name, const std::vector& method_list) override + {} + void SetNWebJavaScriptResultCallBack(std::shared_ptr callback) override {} + void PutFindCallback(std::shared_ptr findListener) override {} + void FindAllAsync(const std::string& searchStr) override {} + void ClearMatches() override {} + void FindNext(const bool forward) override {} + void StoreWebArchive( + const std::string& baseName, bool autoName, std::shared_ptr callback) override + {} + std::vector CreateWebMessagePorts() override + { + std::vector empty; + return empty; + } + void PostWebMessage( + const std::string& message, const std::vector& ports, const std::string& targetUri) override + {} + void ClosePort(const std::string& handle) override {} + void PostPortMessage(const std::string& handle, std::shared_ptr data) override {} + void SetPortMessageCallback(const std::string& handle, std::shared_ptr callback) override + {} + void SendDragEvent(std::shared_ptr dragEvent) override {} + void ClearSslCache() override {} + std::string GetUrl() override + { + return "/data"; + } + void ClearClientAuthenticationCache() override {} + void UpdateLocale(const std::string& language, const std::string& region) override {} + + const std::string GetOriginalUrl() override + { + return ""; + } + bool GetFavicon( + const void** data, size_t& width, size_t& height, ImageColorType& colorType, ImageAlphaType& alphaType) override + { + return false; + } + void PutNetworkAvailable(bool available) override {} + + void HasImages(std::shared_ptr callback) override {} + + void RemoveCache(bool include_disk_files) override {} + std::shared_ptr GetHistoryList() override + { + return nullptr; + } + std::vector SerializeWebState() override + { + std::vector empty; + return empty; + } + bool RestoreWebState(const std::vector& state) override + { + return false; + } + void PageUp(bool top) override {} + void PageDown(bool bottom) override {} + void ScrollTo(float x, float y) override {} + void ScrollBy(float deltaX, float deltaY) override {} + void SlideScroll(float vx, float vy) override {} + bool GetCertChainDerData(std::vector& certChainData, bool isSingleCert) override + { + return false; + } + void SetScreenOffSet(double x, double y) override {} + void SetAudioMuted(bool muted) override {} + void SetShouldFrameSubmissionBeforeDraw(bool should) override {} + void NotifyPopupWindowResult(bool result) override {} + void SetAudioResumeInterval(int32_t resumeInterval) override {} + void SetAudioExclusive(bool audioExclusive) override {} + void RegisterScreenLockFunction(int32_t windowId, std::shared_ptr callback) override {} + void UnRegisterScreenLockFunction(int32_t windowId) override {} + std::shared_ptr GetOrCreateDragData() override + { + return nullptr; + } + void SendTouchpadFlingEvent(double x, double y, double vx, double vy) override {} + int SetUrlTrustList(const std::string& urlTrustList) override + { + return 0; + } + int SetUrlTrustListWithErrMsg(const std::string& urlTrustList, std::string& detailErrMsg) override + { + return 0; + } +}; +} // namespace OHOS::NWeb +#endif diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nwebhelper_fuzzer.cpp b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nwebhelper_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5e22ae9b63c47c473c2eb43665816bdeb39604c --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nwebhelper_fuzzer.cpp @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#define private public +#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/application_context.h" +#include "nweb.h" +#include "nweb_adapter_helper.h" +#include "nweb_c_api.h" +#include "nweb_create_window.h" +#include "nweb_helper.h" +#include "nweb_init_params.h" +#include "nweb_log.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Rosen; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +sptr g_surface = nullptr; +const int DEFAULT_WIDTH = 2560; +const int DEFAULT_HEIGHT = 1396; +const int32_t NWEB_MAX_WIDTH = 7681; +const std::string MOCK_INSTALLATION_DIR = "/data/app/el1/bundle/public/com.ohos.nweb"; +std::shared_ptr g_applicationContext = nullptr; +} // namespace + +namespace AbilityRuntime { +std::shared_ptr Context::GetApplicationContext() +{ + return g_applicationContext; +} +} // namespace AbilityRuntime + +namespace NWeb { + +class NwebHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class ApplicationContextMock : public ApplicationContext { +public: + MOCK_CONST_METHOD0(GetBaseDir, std::string()); +}; + +class MockNWebEngine : public OHOS::NWeb::NWebEngine { +public: + std::shared_ptr CreateNWeb(std::shared_ptr create_info) + { + return nullptr; + } + + std::shared_ptr GetNWeb(int32_t nweb_id) + { + return nullptr; + } + + std::shared_ptr GetDataBase() + { + return nullptr; + } + + std::shared_ptr GetWebStorage() + { + return nullptr; + } + + std::shared_ptr GetCookieManager() + { + return nullptr; + } + + std::shared_ptr GetDownloadManager() + { + return nullptr; + } + + void SetWebTag(int32_t nweb_id, const char* web_tag) {} + + void InitializeWebEngine(std::shared_ptr init_args) {} + + void PrepareForPageLoad(const std::string& url, bool preconnectable, int32_t num_sockets) {} + + void SetWebDebuggingAccess(bool isEnableDebug) {} + + void AddIntelligentTrackingPreventionBypassingList(const std::vector& hosts) {} + + void RemoveIntelligentTrackingPreventionBypassingList(const std::vector& hosts) {} + void ClearIntelligentTrackingPreventionBypassingList() {} + + void PauseAllTimers() {} + + void ResumeAllTimers() {} + + void PrefetchResource(const std::shared_ptr& pre_args, + const std::map& additional_http_headers, const std::string& cache_key, + const uint32_t& cache_valid_time) + {} + + void SetRenderProcessMode(RenderProcessMode mode) {} + + RenderProcessMode GetRenderProcessMode() + { + return RenderProcessMode::SINGLE_MODE; + } + + void ClearPrefetchedResource(const std::vector& cache_key_list) {} + + void WarmupServiceWorker(const std::string& url) {} + + void SetHostIP(const std::string& hostName, const std::string& address, int32_t aliveTime) {} + + void ClearHostIP(const std::string& hostName) {} + + std::shared_ptr GetAdsBlockManager() + { + return nullptr; + } + + void EnableBackForwardCache(bool nativeEmbed, bool mediaTakeOver) {} +}; + +void NwebHelperTest::SetUpTestCase(void) +{ + RSSurfaceNodeConfig config; + config.SurfaceNodeName = "webTestSurfaceName"; + auto surfaceNode = RSSurfaceNode::Create(config, false); + g_surface = surfaceNode->GetSurface(); +} + +void NwebHelperTest::TearDownTestCase(void) {} + +void NwebHelperTest::SetUp(void) {} + +void NwebHelperTest::TearDown(void) {} + +std::unordered_map g_argsMap; + +bool NWebHelperFuzzTest(const uint8_t* data, size_t size) +{ + int32_t nweb_id = 1; + bool result = NWebHelper::Instance().LoadNWebSDK(); + (void)result; + NWebHelper::Instance().SetBundlePath(MOCK_INSTALLATION_DIR); + result = NWebAdapterHelper::Instance().Init(false); + (void)result; + std::shared_ptr create_info = std::make_shared(); + std::shared_ptr nweb = NWebHelper::Instance().CreateNWeb(create_info); + (void)nweb; + std::shared_ptr config = std::make_shared(); + NWebHelper::Instance().SetHttpDns(config); + auto nwebHelper = NWebHelper::Instance().GetNWeb(nweb_id); + (void)nwebHelper; + NWebHelper::Instance().PrepareForPageLoad("web_test", true, 0); + NWebHelper::Instance().WarmupServiceWorker("web_test"); + NWebHelper::Instance().PrefetchResource(nullptr, {}, "web_test", 0); + NWebHelper::Instance().ClearPrefetchedResource({ "web_test" }); + NWebAdapterHelper::Instance().ReadConfigIfNeeded(); + result = NWebHelper::Instance().InitAndRun(false); + (void)result; + ApplicationContextMock* contextMock = new ApplicationContextMock(); + g_applicationContext.reset(contextMock); + result = NWebHelper::Instance().InitAndRun(false); + (void)result; + NWebAdapterHelper::Instance().CreateNWeb(g_surface, GetInitArgs(), DEFAULT_WIDTH, DEFAULT_HEIGHT); + result = NWebHelper::Instance().InitAndRun(false); + (void)result; + NWebAdapterHelper::Instance().CreateNWeb(g_surface, GetInitArgs(), DEFAULT_WIDTH, DEFAULT_HEIGHT); + result = NWebHelper::Instance().LoadNWebSDK(); + (void)result; + result = NWebHelper::Instance().LoadNWebSDK(); + (void)result; + WebDownloadManager_PutDownloadCallback(nullptr); + g_applicationContext.reset(); + return true; +} + +bool NWebHelperFuzzTest_002(const uint8_t* data, size_t size) +{ + auto web_storage = NWebHelper::Instance().GetWebStorage(); + bool result = false; + if (web_storage != nullptr) { + result = true; + } + (void)result; + std::string config = NWebAdapterHelper::Instance().ParsePerfConfig("web", "test"); + (void)config; + NWebConfigHelper::Instance().perfConfig_.emplace("web/test", "web_test"); + config = NWebAdapterHelper::Instance().ParsePerfConfig("web", "test"); + (void)config; + return true; +} + +bool NWebHelperFuzzTest_003(const uint8_t* data, size_t size) +{ + auto dataBase = NWebHelper::Instance().GetDataBase(); + bool result = false; + if (dataBase != nullptr) { + result = true; + } + (void)result; + + NWebHelper::Instance().libHandleWebEngine_ = nullptr; + std::shared_ptr cook = NWebHelper::Instance().GetCookieManager(); + (void)cook; + + void* enhanceSurfaceInfo = nullptr; + int32_t temp = 1; + std::shared_ptr nweb = + NWebAdapterHelper::Instance().CreateNWeb(enhanceSurfaceInfo, GetInitArgs(), DEFAULT_WIDTH, DEFAULT_HEIGHT); + (void)nweb; + enhanceSurfaceInfo = static_cast(&temp); + nweb = NWebAdapterHelper::Instance().CreateNWeb(enhanceSurfaceInfo, GetInitArgs(), DEFAULT_WIDTH, DEFAULT_HEIGHT); + (void)nweb; + nweb = NWebAdapterHelper::Instance().CreateNWeb(enhanceSurfaceInfo, GetInitArgs(), DEFAULT_WIDTH, NWEB_MAX_WIDTH); + (void)nweb; + nweb = NWebAdapterHelper::Instance().CreateNWeb(enhanceSurfaceInfo, GetInitArgs(), NWEB_MAX_WIDTH, DEFAULT_HEIGHT); + (void)nweb; + std::shared_ptr create_info = std::make_shared(); + nweb = NWebHelper::Instance().CreateNWeb(create_info); + (void)nweb; + return true; +} + +} // namespace NWeb +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::NWeb::NWebHelperFuzzTest(data, size); + OHOS::NWeb::NWebHelperFuzzTest_002(data, size); + OHOS::NWeb::NWebHelperFuzzTest_003(data, size); + return 0; +} diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nwebhelper_fuzzer.h b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nwebhelper_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..3d473aeadf5b75188915598092bc2f489eaca722 --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/nwebhelper_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_NWEB_HELPER_FUZZER_H +#define TEST_FUZZTEST_NWEB_HELPER_FUZZER_H + +#define FUZZ_PROJECT_NAME "nwebhelper_fuzzer" +#endif /* TEST_FUZZTEST_NWEB_HELPER_FUZZER_H */ diff --git a/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/project.xml b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..85e7ef2c1cc6471e288306f6e3dcea5287a78b0e --- /dev/null +++ b/test/fuzztest/ohos_nweb/nwebhelper_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.cpp b/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.cpp index 6f53af0ed51704a3cb3d90b38d38271a6f343e79..0a09777f8ad1b705fab9d547ac3022f319ec91c1 100644 --- a/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.cpp @@ -56,14 +56,14 @@ bool RequestBufferFuzzTest(const uint8_t* data, size_t size) return false; } g_surface = surfaceNode->GetSurface(); - if (g_surface== nullptr) { + if (g_surface == nullptr) { return false; } } surfaceAdapter.RequestBuffer(g_surface, width, height); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.h b/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.h index 4753266f0c80423ba2e051d7f964cc29ae1faad7..9db0c309aeb83911c08b3afec9235c963ff036a0 100644 --- a/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.h +++ b/test/fuzztest/ohos_nweb/requestbuffer_fuzzer/requestbuffer_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "requestbuffer_fuzzer" #endif /* TEST_FUZZTEST_REQUESTBUFFER_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.cpp b/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.cpp index 3527a09112dd79e571b29807e20960a256c21fdc..558079e95967b1ea9f5b8e198908d64add38dd5e 100644 --- a/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.cpp @@ -19,9 +19,9 @@ #include #include "nweb.h" +#include "nweb_adapter_helper.h" #include "nweb_handler.h" #include "nweb_helper.h" -#include "nweb_adapter_helper.h" #include "nweb_js_ssl_select_cert_result.h" using namespace OHOS::NWeb; @@ -34,17 +34,17 @@ bool SelectCertRequestFuzzTest(const uint8_t* data, size_t size) } OHOS::NWeb::NWebHandler handler; std::shared_ptr result = nullptr; - std::string host((const char *)data, size); + std::string host((const char*)data, size); int port; if (memcpy_s(&port, sizeof(int), data, sizeof(int)) != 0) { return false; } - std::vector keyTypes = {host}; - std::vector issuers = {host}; + std::vector keyTypes = { host }; + std::vector issuers = { host }; handler.OnSslSelectCertRequestByJS(result, host, port, keyTypes, issuers); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.h b/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.h index aa9ea7513193a8cb1b6fcce0e32c17abdbaf2f78..25668f85692da3829427c29cc92562a678f079b7 100644 --- a/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.h +++ b/test/fuzztest/ohos_nweb/selectcertrequest_fuzzer/selectcertrequest_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "selectcertrequest_fuzzer" #endif /* TEST_FUZZTEST_SELECTCERTREQUEST_FUZZER_H */ - diff --git a/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.cpp b/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.cpp index 3121dd2986b584697dc7b44460ce6ba7dae40ab3..ba8828d4bec126bfb46c098f63253e9f6755a72f 100644 --- a/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.cpp +++ b/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.cpp @@ -19,9 +19,9 @@ #include #include "nweb.h" +#include "nweb_adapter_helper.h" #include "nweb_handler.h" #include "nweb_helper.h" -#include "nweb_adapter_helper.h" #include "nweb_init_params.h" using namespace OHOS::NWeb; @@ -32,7 +32,7 @@ bool SetHttpDnsFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size < sizeof(int))) { return false; } - std::string dohConfig((const char *)data, size); + std::string dohConfig((const char*)data, size); int mode; if (memcpy_s(&mode, sizeof(int), data, sizeof(int)) != 0) { return false; @@ -44,7 +44,7 @@ bool SetHttpDnsFuzzTest(const uint8_t* data, size_t size) NWebHelper::Instance().SetHttpDns(config); return true; } -} +} // namespace OHOS /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) diff --git a/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.h b/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.h index 592a74909fa6def53cbc71d9417444f598022c9a..b35e6675f43e7af9b07ba0e25d655983c85ccb23 100644 --- a/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.h +++ b/test/fuzztest/ohos_nweb/sethttpdns_fuzzer/sethttpdns_fuzzer.h @@ -18,4 +18,3 @@ #define FUZZ_PROJECT_NAME "sethttpdns_fuzzer" #endif /* TEST_FUZZTEST_SETHTTPDNS_FUZZER_H */ - diff --git a/test/resource/image/images/test.heic b/test/resource/image/images/test.heic new file mode 100644 index 0000000000000000000000000000000000000000..01e1ebb1627ec1a133b227e8f25d3fb4b82a87e8 Binary files /dev/null and b/test/resource/image/images/test.heic differ diff --git a/test/resource/image/ohos_test.xml b/test/resource/image/ohos_test.xml new file mode 100644 index 0000000000000000000000000000000000000000..ef51afd02fa90a564496e881b2ab610812af65fc --- /dev/null +++ b/test/resource/image/ohos_test.xml @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/test/unittest/aafwk_app_client_adapter/nweb_aafwk_adapter_test.cpp b/test/unittest/aafwk_app_client_adapter/nweb_aafwk_adapter_test.cpp index 6cc55f1dc8abbde434cae4a3472326ed6f31b4cc..abddfdb86b1bae790109ca9e0a3f3fe571c09afd 100644 --- a/test/unittest/aafwk_app_client_adapter/nweb_aafwk_adapter_test.cpp +++ b/test/unittest/aafwk_app_client_adapter/nweb_aafwk_adapter_test.cpp @@ -490,6 +490,8 @@ HWTEST_F(NWebAafwkAdapterTest, NWebAafwkAdapter_browserHost_020, TestSize.Level1 MessageParcel reply; MessageOption option; host->OnRemoteRequest(code, data, reply, option); + code = 100; + host->OnRemoteRequest(code, data, reply, option); } /** diff --git a/test/unittest/audio_adapter_impl_test/audio_adapter_impl_test.cpp b/test/unittest/audio_adapter_impl_test/audio_adapter_impl_test.cpp index 82f7083b74057c8c2bd305db1931ec7ddfb39026..e7efa391624dfcc57a26822b81ebf52b71e1b1c5 100644 --- a/test/unittest/audio_adapter_impl_test/audio_adapter_impl_test.cpp +++ b/test/unittest/audio_adapter_impl_test/audio_adapter_impl_test.cpp @@ -255,6 +255,15 @@ public: void OnResume() override {}; }; +class AudioOutputChangeCallbackMock : public AudioOutputChangeCallbackAdapter { +public: + AudioOutputChangeCallbackMock() = default; + + virtual ~AudioOutputChangeCallbackMock() = default; + + void OnOutputDeviceChange(int32_t reason) override {}; +}; + class AudioCapturerCallbackMock : public AudioCapturerReadCallbackAdapter { public: AudioCapturerCallbackMock() = default; @@ -1094,5 +1103,101 @@ HWTEST_F(NWebAudioAdapterTest, NWebAudioAdapterTest_AudioAdapterImpl_028, TestSi deviceName = AudioSystemManagerAdapterImpl::GetInstance().GetDeviceName(DeviceType::DEVICE_TYPE_NONE); EXPECT_EQ(deviceName, DEVICE_TYPE_NONE_TEST); } + +/** + * @tc.name: NWebAudioAdapterTest_AudioAdapterImpl_029. + * @tc.desc: Audio adapter unittest. + * @tc.type: FUNC. + * @tc.require:I5HRX9 + */ +HWTEST_F(NWebAudioAdapterTest, NWebAudioAdapterTest_GetChangeReason_029, TestSize.Level1) +{ + std::array reasonArray = { + AudioStreamDeviceChangeReason::UNKNOWN, + AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE, + AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE, + AudioStreamDeviceChangeReason::OVERRODE, + }; + + std::shared_ptr cb = std::make_shared(); + EXPECT_NE(cb, nullptr); + auto callBack = std::make_shared(cb); + EXPECT_NE(callBack, nullptr); + + for (auto& reason : reasonArray) + callBack->GetChangeReason(reason); + + AudioAdapterDeviceChangeReason testReason = callBack->GetChangeReason( + static_cast(-1) + ); + EXPECT_EQ(testReason, AudioAdapterDeviceChangeReason::UNKNOWN); +} + +/** + * @tc.name: NWebAudioAdapterTest_GetChangeReason_030. + * @tc.desc: Audio adapter unittest. + * @tc.type: FUNC. + * @tc.require:I5HRX9 + */ +HWTEST_F(NWebAudioAdapterTest, NWebAudioAdapterTest_OnOutputDeviceChange_030, TestSize.Level1) +{ + std::shared_ptr cb = std::make_shared(); + EXPECT_NE(cb, nullptr); + auto callBack = std::make_shared(cb); + ASSERT_NE(callBack, nullptr); + + DeviceInfo deviceInfo; + + AudioStreamDeviceChangeReason reason = AudioStreamDeviceChangeReason::UNKNOWN; + callBack->OnOutputDeviceChange(deviceInfo, reason); + + reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE; + callBack->OnOutputDeviceChange(deviceInfo, reason); + + reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; + callBack->OnOutputDeviceChange(deviceInfo, reason); + + reason = AudioStreamDeviceChangeReason::OVERRODE; + callBack->OnOutputDeviceChange(deviceInfo, reason); + + reason = static_cast(-1); + callBack->OnOutputDeviceChange(deviceInfo, reason); + + callBack->cb_ = nullptr; + callBack->OnOutputDeviceChange(deviceInfo, reason); +} + +/** + * @tc.name: NWebAudioAdapterTest_SetAudioOutputChangeCallback_031. + * @tc.desc: Audio adapter unittest. + * @tc.type: FUNC. + * @tc.require:I5HRX9 + */ +HWTEST_F(NWebAudioAdapterTest, NWebAudioAdapterTest_SetAudioOutputChangeCallback_031, TestSize.Level1) +{ + auto audioOutputChange = std::make_shared(); + ASSERT_NE(audioOutputChange, nullptr); + int32_t retNum = audioOutputChange->SetAudioOutputChangeCallback(nullptr); + EXPECT_NE(retNum, 0); + + std::shared_ptr callback = std::make_shared(); + ASSERT_NE(callback, nullptr); + retNum = audioOutputChange->SetAudioOutputChangeCallback(callback); + EXPECT_NE(retNum, 0); + + AudioRendererOptions rendererOptions; + AudioRendererInfo renderInfo; + rendererOptions.streamInfo.samplingRate = AudioSamplingRate::SAMPLE_RATE_44100; + rendererOptions.streamInfo.encoding = AudioEncodingType::ENCODING_PCM; + rendererOptions.streamInfo.format = AudioSampleFormat::SAMPLE_S16LE; + rendererOptions.streamInfo.channels = AudioChannel::STEREO; + rendererOptions.rendererInfo = renderInfo; + audioOutputChange->audio_renderer_ = AudioRenderer::Create(rendererOptions); + ASSERT_NE(audioOutputChange->audio_renderer_, nullptr); + + retNum = audioOutputChange->SetAudioOutputChangeCallback(callback); + EXPECT_EQ(retNum, 0); +} + } // namespace NWeb } // namespace OHOS diff --git a/test/unittest/inner_api_test/clipboard_controller_test/clipboard_controller_test.cpp b/test/unittest/inner_api_test/clipboard_controller_test/clipboard_controller_test.cpp deleted file mode 100644 index f38426ca53e69a17f0a61f40aeed9fbf90e959ee..0000000000000000000000000000000000000000 --- a/test/unittest/inner_api_test/clipboard_controller_test/clipboard_controller_test.cpp +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "web_clipboard_controller.h" - -using namespace testing; -using namespace testing::ext; -using namespace OHOS; -using namespace OHOS::NWeb; - -namespace OHOS::NWeb { - -class ClipboardControllerTest : public testing::Test { -public: - ClipboardControllerTest() {}; - ~ClipboardControllerTest() {}; - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void ClipboardControllerTest::SetUpTestCase(void) {} - -void ClipboardControllerTest::TearDownTestCase(void) {} - -void ClipboardControllerTest::SetUp(void) {} - -void ClipboardControllerTest::TearDown(void) {} - -/** - * @tc.name: SplitHtmlTest_001. - * @tc.desc: Test did not use local image address HTML with SplitHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, SplitHtmlTest_001, TestSize.Level1) -{ - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_EQ(pasteData->GetRecordCount(), 1); - std::vector> pasteDataRecords = pasteData->AllRecords(); - EXPECT_EQ(*(pasteDataRecords[0]->GetHtmlText()), *html); -} - -/** - * @tc.name: SplitHtmlTest_002. - * @tc.desc: Test contains a local image address HTML with SplitHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, SplitHtmlTest_002, TestSize.Level1) -{ - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_NE(pasteData, nullptr); - std::vector> pasteDataRecords = pasteData->AllRecords(); - EXPECT_FALSE(pasteDataRecords.empty()); -} - -/** - * @tc.name: SplitHtmlTest_003. - * @tc.desc: Test contains multiple local image addresses HTML with SplitHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, SplitHtmlTest_003, TestSize.Level1) -{ - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_NE(pasteData, nullptr); - std::vector> pasteDataRecords = pasteData->AllRecords(); - EXPECT_FALSE(pasteDataRecords.empty()); -} - -/** - * @tc.name: RebuildHtmlTest_004. - * @tc.desc: Test does not include local image address HTML with RebuildHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, RebuildHtmlTest_004, TestSize.Level1) -{ - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_EQ(pasteData->GetRecordCount(), 1); - std::shared_ptr newHtml = webClipboardController.RebuildHtml(pasteData); - EXPECT_EQ(*newHtml, *html); -} - -/** - * @tc.name: RebuildHtmlTest_005. - * @tc.desc: Test contains a local image address HTML with RebuildHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, RebuildHtmlTest_005, TestSize.Level1) -{ - const int32_t splitRecordCount = 2; - const std::string uri = "file:///data/storage/el2/distributedfiles/temp.png"; - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - const char* execptHtml = - ""; - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_NE(pasteData, nullptr); - EXPECT_EQ(pasteData->GetRecordCount(), splitRecordCount); - std::shared_ptr newPasteData = std::make_shared(); - std::vector> pasteDataRecords = pasteData->AllRecords(); - EXPECT_EQ(*(pasteDataRecords[pasteData->GetRecordCount() - 1]->GetHtmlText()), *html); - - newPasteData->AddHtmlRecord(*html); - for (auto i = 0; i < pasteData->GetRecordCount() - 1; i++) { - MiscServices::PasteDataRecord::Builder builder(MiscServices::MIMETYPE_TEXT_URI); - auto newUri = std::make_shared(uri); - builder.SetUri(newUri); - builder.SetCustomData(pasteDataRecords[i]->GetCustomData()); - auto record = builder.Build(); - newPasteData->AddRecord(record); - } - EXPECT_EQ(newPasteData->GetRecordCount(), splitRecordCount); - std::shared_ptr newHtml = webClipboardController.RebuildHtml(newPasteData); - EXPECT_EQ(newPasteData->GetRecordCount(), 1); - const char* newHtmlStr = newHtml.get()->c_str(); - EXPECT_STREQ(newHtmlStr, execptHtml); -} - -/** - * @tc.name: RebuildHtmlTest_006. - * @tc.desc: Test contains a multiple image address HTML with RebuildHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, RebuildHtmlTest_006, TestSize.Level1) -{ - const int32_t splitRecordCount = 3; - const std::string uri = "file:///data/storage/el2/distributedfiles/temp.png"; - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - const char* execptHtml = - ""; - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_NE(pasteData, nullptr); - EXPECT_EQ(pasteData->GetRecordCount(), splitRecordCount); - std::shared_ptr newPasteData = std::make_shared(); - std::vector> pasteDataRecords = pasteData->AllRecords(); - EXPECT_EQ(*(pasteDataRecords[pasteData->GetRecordCount() - 1]->GetHtmlText()), *html); - - newPasteData->AddHtmlRecord(*html); - for (auto i = 0; i < pasteData->GetRecordCount() - 1; i++) { - MiscServices::PasteDataRecord::Builder builder(MiscServices::MIMETYPE_TEXT_URI); - auto newUri = std::make_shared(uri); - builder.SetUri(newUri); - builder.SetCustomData(pasteDataRecords[i]->GetCustomData()); - auto record = builder.Build(); - newPasteData->AddRecord(record); - } - EXPECT_EQ(newPasteData->GetRecordCount(), splitRecordCount); - std::shared_ptr newHtml = webClipboardController.RebuildHtml(newPasteData); - EXPECT_EQ(newPasteData->GetRecordCount(), 1); - const char* newHtmlStr = newHtml.get()->c_str(); - EXPECT_STREQ(newHtmlStr, execptHtml); -} - -/** - * @tc.name: SplitHtmlTest_007. - * @tc.desc: Test contains invalid protocol image link HTML with SplitHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, SplitHtmlTest_007, TestSize.Level1) -{ - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_EQ(pasteData->GetRecordCount(), 1); - std::vector> pasteDataRecords = pasteData->AllRecords(); - EXPECT_EQ(*(pasteDataRecords[0]->GetHtmlText()), *html); -} - -/** - * @tc.name: RebuildHtmlTest_008. - * @tc.desc: Test contains invalid protocol image link HTML with RebuildHtml. - * @tc.type: FUNC. - * @tc.require: - */ -HWTEST_F(ClipboardControllerTest, RebuildHtmlTest_008, TestSize.Level1) -{ - auto webClipboardController = WebClipboardController::GetInstance(); - std::shared_ptr html( - new std::string("")); - auto pasteData = webClipboardController.SplitHtml(html); - EXPECT_EQ(pasteData->GetRecordCount(), 1); - std::shared_ptr newHtml = webClipboardController.RebuildHtml(pasteData); - EXPECT_EQ(*newHtml, *html); -} -} // namespace OHOS::NWeb diff --git a/test/unittest/napi_web_cookie_manager_test/napi_web_cookie_manager_test.cpp b/test/unittest/napi_web_cookie_manager_test/napi_web_cookie_manager_test.cpp index fc3b1877881854dbffc7121b3f9da742bb7878c0..dca50fba20051e2418ed2b941766460f45ee57c9 100644 --- a/test/unittest/napi_web_cookie_manager_test/napi_web_cookie_manager_test.cpp +++ b/test/unittest/napi_web_cookie_manager_test/napi_web_cookie_manager_test.cpp @@ -61,7 +61,7 @@ HWTEST_F(NapiWebCookieManagerTest, NapiWebCookieManagerTest_001, TestSize.Level1 NWebHelper::Instance().SetBundlePath(MOCK_INSTALLATION_DIR); NWebAdapterHelper::Instance().Init(false); std::shared_ptr cookieManager = NWebHelper::Instance().GetCookieManager(); - EXPECT_NE(cookieManager, nullptr); + EXPECT_EQ(cookieManager, nullptr); NWebHelper::Instance().libHandleWebEngine_ = nullptr; } } // namespace OHOS::NWeb diff --git a/test/unittest/net_connect_adapter_impl_test/net_connect_adapter_impl_test.cpp b/test/unittest/net_connect_adapter_impl_test/net_connect_adapter_impl_test.cpp index 6c7d65a98ee6ec3b01445e94b58355db93c36d4c..0f06a309c35a954a712dc7d5eb86d856ba3e458d 100644 --- a/test/unittest/net_connect_adapter_impl_test/net_connect_adapter_impl_test.cpp +++ b/test/unittest/net_connect_adapter_impl_test/net_connect_adapter_impl_test.cpp @@ -140,6 +140,16 @@ public: { return 0; } + int32_t OnNetCapabilitiesChanged( + const std::shared_ptr capabilities) override + { + return 0; + } + int32_t OnNetConnectionPropertiesChanged( + const std::shared_ptr properties) override + { + return 0; + } }; /** diff --git a/test/unittest/net_connect_callback_impl_test/net_connect_callback_impl_test.cpp b/test/unittest/net_connect_callback_impl_test/net_connect_callback_impl_test.cpp index 65cb471281906b6ab82edc4f086540dce317992f..878cfdd912f97563aed1a561874b8eb8157c3604 100644 --- a/test/unittest/net_connect_callback_impl_test/net_connect_callback_impl_test.cpp +++ b/test/unittest/net_connect_callback_impl_test/net_connect_callback_impl_test.cpp @@ -81,6 +81,16 @@ public: { return 0; } + int32_t OnNetCapabilitiesChanged( + const std::shared_ptr capabilities) override + { + return 0; + } + int32_t OnNetConnectionPropertiesChanged( + const std::shared_ptr properties) override + { + return 0; + } }; /** diff --git a/interfaces/inner_api/BUILD.gn b/test/unittest/nweb_config_helper_test/BUILD.gn similarity index 42% rename from interfaces/inner_api/BUILD.gn rename to test/unittest/nweb_config_helper_test/BUILD.gn index 41b1ca862fe773ef03a9862e33b83fc51122eb2b..3ca61d9e83925aea02d0739a665645a3685f6350 100644 --- a/interfaces/inner_api/BUILD.gn +++ b/test/unittest/nweb_config_helper_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,36 +11,43 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") +import("//build/test.gni") +import("../../../web_aafwk.gni") -config("web_inner_kit_config") { - include_dirs = [ "include" ] -} +module_output_path = "web/webview" -ohos_shared_library("web_inner_kit") { - branch_protector_ret = "pac_ret" - branch_protector_frt = "bti" +ohos_unittest("nweb_config_helper_test") { + module_out_path = module_output_path - include_dirs = [ "../../ohos_nweb/include" ] + sources = [ + "../common/nweb_create_window.cpp", + "nweb_config_helper_test.cpp", + "nweb_helper_test.cpp", + ] - public_configs = [ ":web_inner_kit_config" ] + include_dirs = [ "../common" ] - sources = [ "src/web_clipboard_controller.cpp" ] + deps = [ + "$webview_path/ohos_nweb:web_configs", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] external_deps = [ - "ability_base:zuri", + "ability_runtime:app_context", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", + "graphic_2d:librender_service_client", "hilog:libhilog", - "image_framework:image_native", - "pasteboard:pasteboard_client", - ] - - cflags = [ - "-Wall", - "-Werror", - "-g3", + "webview:libnweb", + "window_manager:libwm", ] + cflags_cc = [ "--coverage" ] + ldflags = [ "--coverage" ] +} - part_name = "webview" - subsystem_name = "web" +group("unittest") { + testonly = true + deps = [ ":nweb_config_helper_test" ] } diff --git a/test/unittest/nweb_config_helper_test/nweb_config_helper_test.cpp b/test/unittest/nweb_config_helper_test/nweb_config_helper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43592f6c1409d64d34064bd9b5c60877640f92c7 --- /dev/null +++ b/test/unittest/nweb_config_helper_test/nweb_config_helper_test.cpp @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "nweb_config_helper.h" +#include "nweb_init_params.h" + +using namespace testing; + +namespace OHOS { +namespace NWebConfig { + +class NWebConfigHelperTest : public ::testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void TearDown(); + +protected: + std::shared_ptr initArgs; + NWebConfigHelper nWebConfigHelper; + void SetUp() override + { + initArgs = std::make_shared(); + } +}; + +/** + * @tc.name: ParseWebConfigXml_FileNotFound + * @tc.desc: ParseWebConfigXml. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseWebConfigXml_FileNotFound, TestSize.Level0) +{ + std::string configFilePath = "nonexistent.xml"; + EXPECT_NO_THROW(NWebConfigHelper::Instance().ParseWebConfigXml(configFilePath, initArgs)); +} + +/** + * @tc.name: ParseWebConfigXml_InvalidRootElement + * @tc.desc: ParseWebConfigXml. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseWebConfigXml_InvalidRootElement, TestSize.Level0) +{ + std::string configFilePath = "invalid_root.xml"; + EXPECT_NO_THROW(NWebConfigHelper::Instance().ParseWebConfigXml(configFilePath, initArgs)); +} + +/** + * @tc.name: ParseWebConfigXml_ValidInitConfig + * @tc.desc: ParseWebConfigXml. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseWebConfigXml_ValidInitConfig, TestSize.Level0) +{ + std::string configFilePath = "valid_init.xml"; + EXPECT_NO_THROW(NWebConfigHelper::Instance().ParseWebConfigXml(configFilePath, initArgs)); +} + +/** + * @tc.name: ParseWebConfigXml_ValidDeleteConfig + * @tc.desc: ParseWebConfigXml. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseWebConfigXml_ValidDeleteConfig, TestSize.Level0) +{ + std::string configFilePath = "valid_delete.xml"; + EXPECT_NO_THROW(NWebConfigHelper::Instance().ParseWebConfigXml(configFilePath, initArgs)); +} + +/** + * @tc.name: ParseWebConfigXml_ValidPerformanceConfig + * @tc.desc:ParseWebConfigXml. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseWebConfigXml_ValidPerformanceConfig, TestSize.Level0) +{ + std::string configFilePath = "valid_performance.xml"; + EXPECT_NO_THROW(NWebConfigHelper::Instance().ParseWebConfigXml(configFilePath, initArgs)); +} + +/** + * @tc.name: ParseWebConfigXml_ValidLTPOConfig + * @tc.desc: ParseWebConfigXml. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseWebConfigXml_ValidLTPOConfig, TestSize.Level0) +{ + std::string configFilePath = "valid_ltpo.xml"; + EXPECT_NO_THROW(NWebConfigHelper::Instance().ParseWebConfigXml(configFilePath, initArgs)); +} + +/** + * @tc.name: GetPerfConfig_ShouldReturnEmptyVector_WhenSettingNameNotExist + * @tc.desc: GetPerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, GetPerfConfig_ShouldReturnEmptyVector_WhenSettingNameNotExist, TestSize.Level0) +{ + std::string settingName = "NonExistentSetting"; + std::vector result = NWebConfigHelper::Instance().GetPerfConfig(settingName); + EXPECT_TRUE(result.empty()); +} + +/** + * @tc.name: GetPerfConfig_ShouldReturnNonEmptyVector_WhenSettingNameExist + * @tc.desc: GetPerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, GetPerfConfig_ShouldReturnNonEmptyVector_WhenSettingNameExist, TestSize.Level0) +{ + std::string settingName = "ExistentSetting"; + NWebConfigHelper::Instance().ltpoConfig_[settingName] = {FrameRateSetting(30)}; + std::vector result = NWebConfigHelper::Instance().GetPerfConfig(settingName); + EXPECT_FALSE(result.empty()); + EXPECT_EQ(result[0].frameRate, 30); +} + +/** + * @tc.name: ParsePerfConfig_ShouldReturnEmptyString_WhenConfigNotFound + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_ShouldReturnEmptyString_WhenConfigNotFound, TestSize.Level0) +{ + std::string configNodeName = "non_existent_config"; + std::string argsNodeName = "non_existent_args"; + std::string result = NWebConfigHelper::Instance().ParsePerfConfig(configNodeName, argsNodeName); + EXPECT_EQ(result, ""); +} + +/** + * @tc.name: ParsePerfConfig_ShouldReturnValue_WhenConfigFound + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_ShouldReturnValue_WhenConfigFound, TestSize.Level0) +{ + std::string configNodeName = "existent_config"; + std::string argsNodeName = "existent_args"; + std::string expectedValue = "expected_value"; + NWebConfigHelper::Instance().perfConfig_[configNodeName + "/" + argsNodeName] = expectedValue; + std::string result = NWebConfigHelper::Instance().ParsePerfConfig(configNodeName, argsNodeName); + EXPECT_EQ(result, expectedValue); +} + +/** + * @tc.name: ParsePerfConfig_NullNode + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_NullNode, TestSize.Level0) +{ + xmlNodePtr node = nullptr; + NWebConfigHelper::Instance().ParsePerfConfig(node); + EXPECT_TRUE(NWebConfigHelper::Instance().perfConfig_.empty()); +} + +/** + * @tc.name: ParsePerfConfig_CommentNode + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_CommentNode, TestSize.Level0) +{ + xmlNodePtr node = xmlNewNode(nullptr, "comment"); + NWebConfigHelper::Instance().ParsePerfConfig(node); + EXPECT_TRUE(NWebConfigHelper::Instance().perfConfig_.empty()); + xmlFreeNode(node); +} + +/** + * @tc.name: ParsePerfConfig_ValidNode + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_ValidNode, TestSize.Level0) + { + xmlNodePtr node = xmlNewNode(nullptr, "node"); + xmlNodePtr childNode = xmlNewNode(nullptr, "childNode"); + EXPECT_NE(node, nullptr); + EXPECT_NE(childNode, nullptr); + xmlNodeAddContent(childNode, "value"); + xmlAddChild(node, childNode); + NWebConfigHelper::Instance().ParsePerfConfig(node); + EXPECT_EQ(hNWebConfigHelper::Instance().perfConfig_["node/childNode"], "value"); + xmlFreeNode(childNode); + xmlFreeNode(node); +} + +/** + * @tc.name: ParsePerfConfig_InvalidChildNode + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_InvalidChildNode, TestSize.Level0) + { + xmlNodePtr node = xmlNewNode(nullptr, "node"); + xmlNodePtr childNode = xmlNewNode(nullptr, "comment"); + EXPECT_NE(node, nullptr); + EXPECT_NE(childNode, nullptr); + xmlAddChild(node, childNode); + NWebConfigHelper::Instance().ParsePerfConfig(node); + EXPECT_TRUE(NWebConfigHelper::Instance().perfConfig_.empty()); + xmlFreeNode(childNode); + xmlFreeNode(node); +} + +/** + * @tc.name: ParsePerfConfig_NullContent + * @tc.desc: ParsePerfConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParsePerfConfig_NullContent, TestSize.Level0) + { + xmlNodePtr node = xmlNewNode(nullptr, "node"); + xmlNodePtr childNode = xmlNewNode(nullptr, "childNode"); + EXPECT_NE(node, nullptr); + EXPECT_NE(childNode, nullptr); + xmlAddChild(node, childNode); + NWebConfigHelper::Instance().ParsePerfConfig(node); + EXPECT_TRUE(NWebConfigHelper::Instance().perfConfig_.empty()); + xmlFreeNode(childNode); + xmlFreeNode(node); + } + +/** + * @tc.name: ParseDeleteConfig_NullRootPtr + * @tc.desc: ParseDeleteConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseDeleteConfig_NullRootPtr, TestSize.Level0) +{ + xmlNodePtr rootPtr = nullptr; + std::string result = NWebConfigHelper::Instance().ParseDeleteConfig(rootPtr, initArgs); + EXPECT_EQ(result, ""); +} + +/** + * @tc.name: ParseDeleteConfig_ValidNode + * @tc.desc: ParseDeleteConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseDeleteConfig_ValidNode, TestSize.Level0) +{ + xmlNodePtr rootPtr = xmlNewNode(nullptr, "valid"); + xmlNodePtr childNodePtr = xmlNewNode(nullptr, "child"); + EXPECT_NE(rootPtr, nullptr); + EXPECT_NE(childNodePtr, nullptr); + xmlAddChild(rootPtr, childNodePtr); + xmlChar *content = xmlNodeGetContent(childNodePtr); + xmlNodeSetContent(childNodePtr, content); + xmlFree(content); + NWebConfigHelper::Instance().ParseDeleteConfig(rootPtr, initArgs); +} + +/** + * @tc.name: ParseDeleteConfig_InvalidChildNode + * @tc.desc: ParseDeleteConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseDeleteConfig_InvalidChildNode, TestSize.Level0) +{ + xmlNodePtr rootPtr = xmlNewNode(nullptr, "valid"); + xmlNodePtr childNodePtr = xmlNewNode(nullptr, "invalid"); + EXPECT_NE(rootPtr, nullptr); + EXPECT_NE(childNodePtr, nullptr); + xmlAddChild(rootPtr, childNodePtr); + NWebConfigHelper::Instance().ParseDeleteConfig(rootPtr, initArgs); +} + +/** + * @tc.name: ParseDeleteConfig_NullContent + * @tc.desc: ParseDeleteConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseDeleteConfig_NullContent, TestSize.Level0) +{ + xmlNodePtr rootPtr = xmlNewNode(nullptr, "valid"); + xmlNodePtr childNodePtr = xmlNewNode(nullptr, "child"); + EXPECT_NE(rootPtr, nullptr); + EXPECT_NE(childNodePtr, nullptr); + xmlAddChild(rootPtr, childNodePtr); + NWebConfigHelper::Instance().ParseDeleteConfig(rootPtr, initArgs); +} + +/** + * @tc.name: ParseDeleteConfig_NotFoundConfig + * @tc.desc: ParseDeleteConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseDeleteConfig_NotFoundConfig, TestSize.Level0) +{ + xmlNodePtr rootPtr = xmlNewNode(nullptr, "valid"); + xmlNodePtr childNodePtr = xmlNewNode(nullptr, "child"); + EXPECT_NE(rootPtr, nullptr); + EXPECT_NE(childNodePtr, nullptr); + xmlAddChild(rootPtr, childNodePtr); + xmlChar *content = xmlNodeGetContent(childNodePtr); + xmlNodeSetContent(childNodePtr, content); + xmlFree(content); + NWebConfigHelper::Instance().ParseDeleteConfig(rootPtr, initArgs); +} + +/** + * @tc.name: ParseDeleteConfig_EmptyParam + * @tc.desc: ParseDeleteConfig. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NWebConfigHelperTest, ParseDeleteConfig_EmptyParam, TestSize.Level0) +{ + xmlNodePtr rootPtr = xmlNewNode(nullptr, "valid"); + xmlNodePtr childNodePtr = xmlNewNode(nullptr, "child"); + EXPECT_NE(rootPtr, nullptr); + EXPECT_NE(childNodePtr, nullptr); + xmlAddChild(rootPtr, childNodePtr); + xmlChar *content = xmlNodeGetContent(childNodePtr); + xmlNodeSetContent(childNodePtr, content); + xmlFree(content); + NWebConfigHelper::Instance().ParseDeleteConfig(rootPtr, initArgs); +} + +} // NWebConfig +} // OHOS``` \ No newline at end of file diff --git a/test/unittest/nweb_helper_test/nweb_helper_test.cpp b/test/unittest/nweb_helper_test/nweb_helper_test.cpp index 33fcc2acc27c138399b54e2bcb6d6dd1c0270410..3ae0543edbb697c13f8dc9ddfa60a3f82256793e 100644 --- a/test/unittest/nweb_helper_test/nweb_helper_test.cpp +++ b/test/unittest/nweb_helper_test/nweb_helper_test.cpp @@ -143,6 +143,8 @@ public: { return nullptr; } + + void EnableBackForwardCache(bool nativeEmbed, bool mediaTakeOver) {} }; void NwebHelperTest::SetUpTestCase(void) @@ -179,7 +181,7 @@ HWTEST_F(NwebHelperTest, NWebHelper_SetBundlePath_001, TestSize.Level1) EXPECT_FALSE(result); NWebHelper::Instance().SetBundlePath(MOCK_INSTALLATION_DIR); result = NWebAdapterHelper::Instance().Init(false); - EXPECT_EQ(RESULT_OK, result); + EXPECT_NE(RESULT_OK, result); std::shared_ptr create_info = std::make_shared(); std::shared_ptr nweb = NWebHelper::Instance().CreateNWeb(create_info); EXPECT_EQ(nweb, nullptr); @@ -192,6 +194,7 @@ HWTEST_F(NwebHelperTest, NWebHelper_SetBundlePath_001, TestSize.Level1) NWebHelper::Instance().PrefetchResource(nullptr, {}, "web_test", 0); NWebHelper::Instance().ClearPrefetchedResource({"web_test"}); NWebAdapterHelper::Instance().ReadConfigIfNeeded(); + NWebHelper::Instance().EnableBackForwardCache(true, true); result = NWebHelper::Instance().InitAndRun(false); EXPECT_FALSE(result); ApplicationContextMock *contextMock = new ApplicationContextMock(); @@ -209,13 +212,13 @@ HWTEST_F(NwebHelperTest, NWebHelper_SetBundlePath_001, TestSize.Level1) .Times(2) .WillRepeatedly(::testing::Return("test_web")); result = NWebHelper::Instance().InitAndRun(false); - EXPECT_TRUE(result); + EXPECT_FALSE(result); NWebAdapterHelper::Instance().CreateNWeb(g_surface, GetInitArgs(), DEFAULT_WIDTH, DEFAULT_HEIGHT); result = NWebHelper::Instance().LoadNWebSDK(); - EXPECT_TRUE(result); + EXPECT_FALSE(result); result = NWebHelper::Instance().LoadNWebSDK(); - EXPECT_TRUE(result); + EXPECT_FALSE(result); WebDownloadManager_PutDownloadCallback(nullptr); g_applicationContext.reset(); } @@ -325,6 +328,7 @@ HWTEST_F(NwebHelperTest, NWebHelper_GetConfigPath_005, TestSize.Level1) NWebHelper::Instance().PrefetchResource(nullptr, {}, "web_test", 0); NWebHelper::Instance().ClearPrefetchedResource({"web_test"}); NWebHelper::Instance().bundlePath_.clear(); + NWebHelper::Instance().EnableBackForwardCache(true, true); bool result = NWebHelper::Instance().InitAndRun(false); EXPECT_FALSE(result); NWebHelper::Instance().SetConnectionTimeout(1); @@ -438,7 +442,6 @@ HWTEST_F(NwebHelperTest, NWebHelper_WebDownloadItem_IsPaused_007, TestSize.Level WebDownloadItem_SetReceivedBytes(downloadItem, 1); WebDownloadItem_SetTotalBytes(downloadItem, 1); WebDownloadItem_SetReceivedSlices(downloadItem, "test_web"); - char* guid = WebDownloadItem_Guid(downloadItem); EXPECT_NE(guid, nullptr); int64_t totalBytes = WebDownloadItem_TotalBytes(downloadItem); @@ -453,6 +456,10 @@ HWTEST_F(NwebHelperTest, NWebHelper_WebDownloadItem_IsPaused_007, TestSize.Level EXPECT_NE(eTag, nullptr); char* mimeType = WebDownloadItem_MimeType(downloadItem); EXPECT_NE(mimeType, nullptr); + long itemId = WebDownloadItem_GetDownloadItemId(downloadItem); + auto state1 = WebDownload_GetItemState(nWebId, itemId); + auto state2 = WebDownload_GetItemStateByGuid("test_web"); + EXPECT_EQ(state1, state2); } /** @@ -471,6 +478,8 @@ HWTEST_F(NwebHelperTest, NWebHelper_GetWebEngineHandler_008, TestSize.Level1) EXPECT_EQ(nweb, nullptr); std::shared_ptr cook = NWebHelper::Instance().GetCookieManager(); EXPECT_EQ(cook, nullptr); + auto manager = NWebHelper::Instance().GetAdsBlockManager(); + EXPECT_EQ(manager, nullptr); std::shared_ptr config = std::make_shared(); NWebHelper::Instance().SetHttpDns(config); NWebHelper::Instance().PrepareForPageLoad("web_test", true, 0); @@ -493,6 +502,8 @@ HWTEST_F(NwebHelperTest, NWebHelper_GetWebEngineHandler_008, TestSize.Level1) EXPECT_TRUE(result); cook = NWebHelper::Instance().GetCookieManager(); EXPECT_NE(cook, nullptr); + manager = NWebHelper::Instance().GetAdsBlockManager(); + EXPECT_NE(manager, nullptr); NWebHelper::Instance().SetWebTag(1, "webtag"); NWebHelper::Instance().libHandleWebEngine_ = nullptr; @@ -600,12 +611,55 @@ HWTEST_F(NwebHelperTest, NWebHelper_EnableWholeWebPageDrawing_001, TestSize.Leve */ HWTEST_F(NwebHelperTest, NWebHelper_GetAdsBlockManager_001, TestSize.Level1) { + NWebHelper::Instance().nwebEngine_ = nullptr; + std::shared_ptr create_info = std::make_shared(); + std::shared_ptr nweb = NWebHelper::Instance().CreateNWeb(create_info); + EXPECT_EQ(nweb, nullptr); + nweb = NWebHelper::Instance().GetNWeb(1); + EXPECT_EQ(nweb, nullptr); auto manager = NWebHelper::Instance().GetAdsBlockManager(); - bool result = false; - if (manager != nullptr) { - result = true; - } - EXPECT_EQ(RESULT_OK, result); + EXPECT_EQ(manager, nullptr); +} + +/** + * @tc.name: NWebHelper_TrimMemoryByPressureLevel_001 + * @tc.desc: TrimMemoryByPressureLevel. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NwebHelperTest, NWebHelper_TrimMemoryByPressureLevel_001, TestSize.Level1) +{ + int32_t nweb_id = 1; + auto nwebHelper = NWebHelper::Instance().GetNWeb(nweb_id); + EXPECT_EQ(nwebHelper, nullptr); + + int32_t memoryLevel = 1; + NWebHelper::Instance().nwebEngine_ = nullptr; + NWebHelper::Instance().TrimMemoryByPressureLevel(memoryLevel); + EXPECT_EQ(NWebHelper::Instance().nwebEngine_, nullptr); + + auto nwebengineMock = std::make_shared(); + NWebHelper::Instance().nwebEngine_ = nwebengineMock; + NWebHelper::Instance().TrimMemoryByPressureLevel(memoryLevel); + EXPECT_NE(NWebHelper::Instance().nwebEngine_, nullptr); + + NWebHelper::Instance().nwebEngine_ = nullptr; +} + +/** + * @tc.name: NWebHelper_ParseNWebLTPOApp_001 + * @tc.desc: ParseNWebLTPOApp. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(NwebHelperTest, NWebHelper_ParseNWebLTPOApp_001, TestSize.Level1) +{ + EXPECT_TRUE(NWebConfigHelper::Instance().ltpoAllowedApps_.empty()); + EXPECT_FALSE(NWebConfigHelper::Instance().IsLTPODynamicApp("")); + std::shared_ptr initArgs = std::make_shared(); + NWebAdapterHelper::Instance().ParseConfig(initArgs); + EXPECT_TRUE(NWebConfigHelper::Instance().ltpoAllowedApps_.empty()); + EXPECT_FALSE(NWebConfigHelper::Instance().IsLTPODynamicApp("")); } } // namespace OHOS::NWeb } diff --git a/test/unittest/ohos_adapter/camera_adapter_impl_test/camera_adapter_impl_test.cpp b/test/unittest/ohos_adapter/camera_adapter_impl_test/camera_adapter_impl_test.cpp index e482d18ba6af85df34c68f29d3e4f1e4b5affbb7..9757a332970b4532c3924bdef8cf7d81fd85d530 100644 --- a/test/unittest/ohos_adapter/camera_adapter_impl_test/camera_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/camera_adapter_impl_test/camera_adapter_impl_test.cpp @@ -343,7 +343,7 @@ HWTEST_F(CameraAdapterImplTest, CameraAdapterImplTest_GetOriFocusMode_006, TestS sptr cameraInput = g_cameraManager->CreateCameraInput(cameras[0]); adapter.cameraInput_ = cameraInput; result = adapter.InitCameraInput(deviceId); - EXPECT_EQ(result, 0); + EXPECT_NE(result, 0); std::shared_ptr captureParams = std::make_shared(); EXPECT_NE(captureParams, nullptr); captureParams->width = 1; @@ -536,6 +536,8 @@ HWTEST_F(CameraAdapterImplTest, CameraAdapterImplTest_InitCameraInput_010, TestS adapter.isCapturing_ = true; bool isExist = adapter.IsExistCaptureTask(); EXPECT_TRUE(isExist); + result = adapter.StartStream(deviceId, nullptr, nullptr); + EXPECT_NE(result, 0); result = adapter.StartStream(deviceId, captureParams, nullptr); EXPECT_NE(result, 0); adapter.status_ = CameraStatusAdapter::AVAILABLE; @@ -591,4 +593,20 @@ HWTEST_F(CameraAdapterImplTest, CameraAdapterImplTest_CameraManagerAdapterCallba adapter.statusCallback_ = nullptr; adapter.OnCameraStatusChanged(cameraStatusInfo); } + +/** + * @tc.name: CameraAdapterImplTest_CameraStatus_012 + * @tc.desc: CameraManagerAdapterCallback. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CameraAdapterImplTest, CameraAdapterImplTest_CameraStatus_012, TestSize.Level1) +{ + auto callback = std::make_shared(); + CameraManagerAdapterImpl& adapter = CameraManagerAdapterImpl::GetInstance(); + CameraStatusAdapter status = adapter.GetCameraStatus(); + EXPECT_EQ(status, CameraStatusAdapter::AVAILABLE); + adapter.SetCameraStatus(status); +} + } // namespace OHOS::NWeb diff --git a/test/unittest/ohos_adapter/flowbuffer_adapter_impl_test/flowbuffer_adapter_impl_test.cpp b/test/unittest/ohos_adapter/flowbuffer_adapter_impl_test/flowbuffer_adapter_impl_test.cpp index 89bbc6181473049181320e6d1e6ceaf74b579b17..597798967aa3872470b7c644618fd2228adac6b6 100644 --- a/test/unittest/ohos_adapter/flowbuffer_adapter_impl_test/flowbuffer_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/flowbuffer_adapter_impl_test/flowbuffer_adapter_impl_test.cpp @@ -20,12 +20,18 @@ #define private public #include "flowbuffer_adapter_impl.h" +#include +#include using namespace testing; using namespace testing::ext; namespace OHOS { namespace NWeb { +namespace { + const int64_t PERFORMANCE_PERIOD_MS = 300; +} + class FlowbufferAdapterImplTest : public testing::Test { public: static void SetUpTestCase(); @@ -93,5 +99,75 @@ HWTEST_F(FlowbufferAdapterImplTest, FlowbufferAdapterImplTest_003, TestSize.Leve ashmem = flowbufferAdapter->CreateAshmemWithFd(-1, scriptLength, PROT_READ); EXPECT_EQ(ashmem, nullptr); } + +/** + * @tc.name: FlowbufferAdapterImplTest_004. + * @tc.desc: test FlowbufferAdapterImpl NeedReportScene. + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(FlowbufferAdapterImplTest, FlowbufferAdapterImplTest_004, TestSize.Level1) +{ + auto flowbufferAdapter = std::make_shared(); + bool needReportScene = flowbufferAdapter->NeedReportScene(); + EXPECT_FALSE(needReportScene); + std::this_thread::sleep_for(std::chrono::milliseconds(PERFORMANCE_PERIOD_MS)); + needReportScene = flowbufferAdapter->NeedReportScene(); + EXPECT_TRUE(needReportScene); +} + +/** + * @tc.name: FlowbufferAdapterImplTest_005. + * @tc.desc: test FlowbufferAdapterImpl StartPerformanceBoost. + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(FlowbufferAdapterImplTest, FlowbufferAdapterImplTest_005, TestSize.Level1) +{ + auto flowbufferAdapter = std::make_shared(); + bool needReportScene = flowbufferAdapter->NeedReportScene(); + flowbufferAdapter->StartPerformanceBoost(); + std::this_thread::sleep_for(std::chrono::milliseconds(PERFORMANCE_PERIOD_MS)); + flowbufferAdapter->StartPerformanceBoost(); + EXPECT_FALSE(needReportScene); +} + +/** + * @tc.name: FlowbufferAdapterImplTest_006. + * @tc.desc: test FlowbufferAdapterImpl CreateAshmem. + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(FlowbufferAdapterImplTest, FlowbufferAdapterImplTest_006, TestSize.Level1) +{ + int fd = -1; + size_t scriptLength = 10; + auto flowbufferAdapter = std::make_shared(); + flowbufferAdapter->CreateAshmem(scriptLength, PROT_READ | PROT_WRITE, fd); + fd = 1; + flowbufferAdapter->CreateAshmem(scriptLength, PROT_READ | PROT_WRITE, fd); + scriptLength = 1024; + auto ashmem = flowbufferAdapter->CreateAshmem(scriptLength, PROT_READ | PROT_WRITE, fd); + EXPECT_TRUE(ashmem != nullptr); +} + +/** + * @tc.name: FlowbufferAdapterImplTest_007. + * @tc.desc: test FlowbufferAdapterImpl CreateAshmemWithFd. + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(FlowbufferAdapterImplTest, FlowbufferAdapterImplTest_007, TestSize.Level1) +{ + int fd = -1; + size_t scriptLength = 10; + auto flowbufferAdapter = std::make_shared(); + flowbufferAdapter->CreateAshmemWithFd(fd, scriptLength, PROT_READ); + fd = 1; + flowbufferAdapter->CreateAshmemWithFd(fd, scriptLength, PROT_READ); + scriptLength = 1024; + auto ashmem = flowbufferAdapter->CreateAshmemWithFd(fd, scriptLength, PROT_READ); + EXPECT_TRUE(ashmem == nullptr); +} } // namespace NWeb } // namespace OHOS diff --git a/test/unittest/ohos_adapter/graphic_adapter_test/graphic_adapter_test.cpp b/test/unittest/ohos_adapter/graphic_adapter_test/graphic_adapter_test.cpp index 685e7390f43d1ed19a2502eba980854d9947eae9..d8e6eb0f65a3f3b34b1cee3638505c010356fccf 100644 --- a/test/unittest/ohos_adapter/graphic_adapter_test/graphic_adapter_test.cpp +++ b/test/unittest/ohos_adapter/graphic_adapter_test/graphic_adapter_test.cpp @@ -85,5 +85,10 @@ HWTEST_F(GraphicAdapterTest, GraphicAdapterTest_RequestVsync_001, TestSize.Level adapter.SetOnVsyncEndCallback(OnVsyncCallback); adapter.OnVsync(1, client); adapter.SetIsGPUProcess(false); + + adapter.pkgName_ = ""; + adapter.SetScene("", 0); + adapter.pkgName_ = "test"; + adapter.SetScene("", 0); } } // namespace NWeb diff --git a/test/unittest/ohos_adapter/graphic_adapter_test/native_image_adapter_impl_test.cpp b/test/unittest/ohos_adapter/graphic_adapter_test/native_image_adapter_impl_test.cpp index 11e6240af3c82fa9bd477ead0671a9f5f67d1e13..cdde17a402b674c7350d6ad992adb6f487c66f71 100644 --- a/test/unittest/ohos_adapter/graphic_adapter_test/native_image_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/graphic_adapter_test/native_image_adapter_impl_test.cpp @@ -63,7 +63,7 @@ HWTEST_F(NativeImageAdapterImplTest, NativeImageAdapterImplTest_UpdateSurfaceIma uint32_t textureTarget = 1; imagerAdapter->CreateNativeImage(textureId, textureTarget); result = imagerAdapter->UpdateSurfaceImage(); - EXPECT_EQ(result, SURFACE_ERROR_ERROR); + EXPECT_EQ(result, 0); window = imagerAdapter->AquireNativeWindowFromNativeImage(); EXPECT_NE(window, nullptr); imagerAdapter->AttachContext(1); diff --git a/test/unittest/ohos_adapter/hiviewdfx_adapter_test/BUILD.gn b/test/unittest/ohos_adapter/hiviewdfx_adapter_test/BUILD.gn index e36c4bced23a98577d29a5f3c9ed1b5c028d44cb..b9331569829dc9e2f6c9d513e4cfe7ceec84d832 100644 --- a/test/unittest/ohos_adapter/hiviewdfx_adapter_test/BUILD.gn +++ b/test/unittest/ohos_adapter/hiviewdfx_adapter_test/BUILD.gn @@ -19,7 +19,10 @@ module_output_path = "web/webview" config("module_private_config") { visibility = [ ":*" ] - include_dirs = [ "$webview_path/ohos_adapter/hiviewdfx_adapter/include" ] + include_dirs = [ + "$webview_path/ohos_adapter/hiviewdfx_adapter/include", + "$webview_path/ohos_nweb/include", + ] } ohos_unittest("nweb_hiviewdfx_adapter_test") { @@ -39,6 +42,8 @@ ohos_unittest("nweb_hiviewdfx_adapter_test") { "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", + "init:libbegetutil", + "webview:libnweb", ] } diff --git a/test/unittest/ohos_adapter/hiviewdfx_adapter_test/hiviewdfx_adapter_test.cpp b/test/unittest/ohos_adapter/hiviewdfx_adapter_test/hiviewdfx_adapter_test.cpp index 8b27bc9c657a3826f9a506de481a412d3ed5dcca..40d4002b13729252aec916b819cdd4f710802740 100644 --- a/test/unittest/ohos_adapter/hiviewdfx_adapter_test/hiviewdfx_adapter_test.cpp +++ b/test/unittest/ohos_adapter/hiviewdfx_adapter_test/hiviewdfx_adapter_test.cpp @@ -17,6 +17,10 @@ #include "hilog_adapter.h" #include "ohos_adapter_helper.h" #include "hitrace_adapter_impl.h" +#include "nweb_hisysevent.h" + +#include "parameters.h" +using namespace OHOS; using testing::ext::TestSize; @@ -88,18 +92,16 @@ HWTEST(HiViewDFXAdapterTest, NormalScene, TestSize.Level1) */ HWTEST(HiViewDFXAdapterTest, NormalScene_01, TestSize.Level1) { - uint64_t val = (1ULL << 24); - std::string value = std::to_string(val); - HiTraceAdapterImpl::GetInstance().UpdateOHOSTraceTag(value.c_str()); OhosAdapterHelper::GetInstance().GetHiTraceAdapterInstance().StartOHOSTrace("test"); OhosAdapterHelper::GetInstance().GetHiTraceAdapterInstance().CountOHOSTrace("test", 1); OhosAdapterHelper::GetInstance().GetHiTraceAdapterInstance().FinishOHOSTrace(); - val = (1ULL << 39); - value = std::to_string(val); - HiTraceAdapterImpl::GetInstance().UpdateOHOSTraceTag(value.c_str()); + uint64_t val = (1ULL << 24); + std::string value = std::to_string(val); + OHOS::system::SetParameter("debug.hitrace.tags.enableflags", value); OhosAdapterHelper::GetInstance().GetHiTraceAdapterInstance().StartOHOSTrace("test"); OhosAdapterHelper::GetInstance().GetHiTraceAdapterInstance().CountOHOSTrace("test", 1); OhosAdapterHelper::GetInstance().GetHiTraceAdapterInstance().FinishOHOSTrace(); HiTraceAdapterImpl::GetInstance().IsACETraceEnable(); + EventReport::ReportCreateWebInstanceTime(1, 1); } } // namespace OHOS::NWeb diff --git a/test/unittest/ohos_adapter/imf_adapter_test/imf_adapter_impl_test.cpp b/test/unittest/ohos_adapter/imf_adapter_test/imf_adapter_impl_test.cpp index 756f43563a53ccdff9537f1f5fab6af014e023bf..9ae50f22c316f775a2b38721fb0df1442a7fde61 100644 --- a/test/unittest/ohos_adapter/imf_adapter_test/imf_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/imf_adapter_test/imf_adapter_impl_test.cpp @@ -65,6 +65,82 @@ public: } }; +class IMFInputAttributeAdapterMock : public IMFInputAttributeAdapter { +public: + IMFInputAttributeAdapterMock() = default; + + ~IMFInputAttributeAdapterMock() override = default; + + int32_t GetInputPattern() override + { + return 0; + } + + int32_t GetEnterKeyType() override + { + return 0; + } +}; + +class IMFSelectionRangeAdapterMock : public IMFSelectionRangeAdapter { +public: + IMFSelectionRangeAdapterMock() = default; + + ~IMFSelectionRangeAdapterMock() override = default; + + int32_t GetStart() override + { + return 0; + } + + int32_t GetEnd() override + { + return 0; + } +}; + +class IMFTextConfigTest : public IMFTextConfigAdapter { +public: + IMFTextConfigTest() = default; + ~IMFTextConfigTest() override = default; + + std::shared_ptr GetInputAttribute() + { + auto mock = std::make_shared(); + return mock; + } + + std::shared_ptr GetCursorInfo() + { + auto mock = std::make_shared(); + return mock; + } + + std::shared_ptr GetSelectionRange() + { + auto mock = std::make_shared(); + return mock; + } + + uint32_t GetWindowId() + { + WVLOG_I("test GetWindowId"); + return 0; + } + + double GetPositionY() + { + WVLOG_I("test GetPositionY"); + return 0.0; + } + + double GetHeight() + { + WVLOG_I("test GetHeight"); + return 0.0; + } +}; + class IMFTextListenerTest : public IMFTextListenerAdapter { public: IMFTextListenerTest() = default; @@ -303,7 +379,6 @@ HWTEST_F(NWebIMFAdapterTest, NWebIMFAdapterTest_IMFAdapterImpl_005, TestSize.Lev listenerTest->FinishTextPreview(); const std::unordered_map privateCommand; listenerTest->ReceivePrivateCommand(privateCommand); - EXPECT_EQ(listener->VerifyAllSuccess(), true); } /** @@ -410,5 +485,45 @@ HWTEST_F(NWebIMFAdapterTest, NWebIMFAdapterTest_IMFAdapterImpl_009, TestSize.Lev listenerTest->ReceivePrivateCommand(privateCommand); privateCommand = { { "previewTextStyle", "underline" } }; listenerTest->ReceivePrivateCommand(privateCommand); + privateCommand = { { "com.autofill.params.userName", "test" } }; + listenerTest->ReceivePrivateCommand(privateCommand); + privateCommand = { { "com.autofill.params.otherAccount", true } }; + listenerTest->ReceivePrivateCommand(privateCommand); } + +/** + * @tc.name: NWebIMFAdapterTest_InsertText_010. + * @tc.desc: IMF adapter unittest. + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(NWebIMFAdapterTest, NWebIMFAdapterTest_InsertText_010, TestSize.Level1) +{ + auto listener = std::make_shared(); + auto config = std::make_shared(); + bool result = g_imf->Attach(listener, true, nullptr, false); + EXPECT_FALSE(result); + + result = g_imf->Attach(listener, true, config, false); + EXPECT_FALSE(result); + EXPECT_NE(g_imf->textListener_, nullptr); + g_imf->HideTextInput(); +} + +/** + * @tc.name: NWebIMFAdapterTest_InsertText_011. + * @tc.desc: IMF adapter unittest. + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(NWebIMFAdapterTest, NWebIMFAdapterTest_InsertText_011, TestSize.Level1) +{ + EXPECT_NE(g_imf, nullptr); + std::string commandKey = "autofill.cancel"; + std::string commandValue = "{\"userName\":\"test\",\"hasAccount\":\"test\"}"; + g_imf->SendPrivateCommand(commandKey, commandValue); + commandKey = "test"; + g_imf->SendPrivateCommand(commandKey, commandValue); +} + } // namespace OHOS::NWeb diff --git a/test/unittest/ohos_adapter/media_adapter_test/BUILD.gn b/test/unittest/ohos_adapter/media_adapter_test/BUILD.gn index 0405bf2e71d9df35a80ada2a362ab4d05d724e84..8f0cc572e1bf85c655b4d3063ea7032dcbfeb3a8 100644 --- a/test/unittest/ohos_adapter/media_adapter_test/BUILD.gn +++ b/test/unittest/ohos_adapter/media_adapter_test/BUILD.gn @@ -23,6 +23,8 @@ config("module_private_config") { "../../../../ohos_adapter/media_adapter/include", "../../../../ohos_adapter/graphic_adapter/include", ] + cflags_cc = [ "--coverage" ] + ldflags = [ "--coverage" ] } ohos_unittest("nweb_media_adapter_test") { diff --git a/test/unittest/ohos_adapter/media_adapter_test/media_avsession_adapter_impl_test.cpp b/test/unittest/ohos_adapter/media_adapter_test/media_avsession_adapter_impl_test.cpp index af8b4fb58e199d864b595deebd38ebf43fffbe30..70be003db04767941ff995ba7490d18f7eae10c7 100644 --- a/test/unittest/ohos_adapter/media_adapter_test/media_avsession_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/media_adapter_test/media_avsession_adapter_impl_test.cpp @@ -167,6 +167,15 @@ public: MOCK_CONST_METHOD0(GetState, int32_t()); }; +class MediaAVSessionKeyMock : public MediaAVSessionKey { +public: + MediaAVSessionKeyMock() = default; + + ~MediaAVSessionKeyMock() = default; + + MOCK_METHOD0(GetElement, std::shared_ptr()); +}; + class MediaAVSessionCallbackImplTest : public testing::Test { public: static void SetUpTestCase(void); @@ -406,27 +415,50 @@ HWTEST_F(MediaAVSessionKeyTest, NWebMediaAdapterTest_MediaAVSessionKey_006, Test */ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapterImpl_001, TestSize.Level1) { + auto type = MediaAVSessionType::MEDIA_TYPE_INVALID; auto avSessionKey = std::make_shared(); g_adapter->avSessionKey_ = avSessionKey; g_adapter->avSessionKey_->Init(); auto avSessionMock = std::make_shared(); - g_adapter->avSession_ = nullptr; - auto type = MediaAVSessionType::MEDIA_TYPE_INVALID; + auto avSessionMock_dummy = std::make_shared(); + g_adapter->avSession_ = avSessionMock; + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + g_adapter->avSession_)); + bool ret = g_adapter->CreateAVSession(type); EXPECT_EQ(ret, false); - g_adapter->avSession_ = avSessionMock; - EXPECT_CALL(*avSessionMock, Destroy()).WillRepeatedly(::testing::Return(RET_SUCCESS)); type = MediaAVSessionType::MEDIA_TYPE_AUDIO; - g_adapter->avSessionKey_->SetType(type); + g_adapter->avSessionKey_->SetType(MediaAVSessionType::MEDIA_TYPE_VIDEO); ret = g_adapter->CreateAVSession(type); - EXPECT_EQ(ret, false); - g_adapter->avSessionKey_->SetType(MediaAVSessionType::MEDIA_TYPE_INVALID); + g_adapter->avSession_ = nullptr; ret = g_adapter->CreateAVSession(type); EXPECT_EQ(ret, true); - g_adapter->avSession_ = nullptr; + g_adapter->avSession_ = avSessionMock; + type = MediaAVSessionType::MEDIA_TYPE_VIDEO; + g_adapter->avSessionMap.clear(); + ret = g_adapter->CreateAVSession(type); + EXPECT_EQ(ret, true); + + g_adapter->avSession_ = avSessionMock; + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + avSessionMock_dummy)); + ret = g_adapter->CreateAVSession(type); + EXPECT_EQ(ret, true); + + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + g_adapter->avSession_)); + ret = g_adapter->CreateAVSession(type); + EXPECT_EQ(ret, false); + + g_adapter->avSession_ = avSessionMock; + g_adapter->avSessionMap.clear(); + type = MediaAVSessionType::MEDIA_TYPE_VIDEO; ret = g_adapter->CreateAVSession(type); EXPECT_EQ(ret, true); } @@ -453,6 +485,15 @@ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapt EXPECT_CALL(*avSessionMock, Destroy()).WillOnce(::testing::Return(RET_SUCCESS)); g_adapter->DestroyAVSession(); EXPECT_EQ(g_adapter->avSession_, nullptr); + + g_adapter->avSession_ = nullptr; + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + g_adapter->avSession_)); + g_adapter->DestroyAVSession(); + + g_adapter->avSessionMap.clear(); + g_adapter->DestroyAVSession(); } /** @@ -614,48 +655,20 @@ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapt */ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapterImpl_007, TestSize.Level1) { - std::string str1 = "q"; - std::string str2 = "w"; - auto metadataMock = std::make_shared(); - auto avmetadata = std::make_shared(); - g_adapter->avSession_ = nullptr; - g_adapter->avMetadata_ = avmetadata; - g_adapter->avMetadata_->SetTitle(str1); - g_adapter->avMetadata_->SetArtist(str1); - g_adapter->avMetadata_->SetAlbum(str1); - - EXPECT_CALL(*metadataMock, GetTitle()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*metadataMock, GetArtist()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*metadataMock, GetAlbum()).WillRepeatedly(::testing::Return(str1)); - g_adapter->SetMetadata(metadataMock); - EXPECT_EQ(g_adapter->avSession_, nullptr); - auto avSessionMock = std::make_shared(); + auto metadataMock = std::make_shared(); g_adapter->avSession_ = avSessionMock; - g_adapter->avMetadata_->SetTitle(str1); - EXPECT_CALL(*avSessionMock, IsActive()).WillRepeatedly(::testing::Return(true)); - EXPECT_CALL(*metadataMock, GetTitle()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*metadataMock, GetArtist()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*metadataMock, GetAlbum()).WillRepeatedly(::testing::Return(str1)); - g_adapter->SetMetadata(metadataMock); - EXPECT_NE(g_adapter->avSession_, nullptr); - g_adapter->avMetadata_->SetTitle(str1); - EXPECT_CALL(*metadataMock, GetTitle()).WillRepeatedly(::testing::Return(str2)); - EXPECT_CALL(*metadataMock, GetArtist()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*metadataMock, GetAlbum()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*avSessionMock, SetAVMetaData(_)).WillOnce(::testing::Return(RET_SUCCESS)); + EXPECT_CALL(*avSessionMock, SetAVMetaData(_)).WillOnce( + ::testing::Return(RET_ERROR)); g_adapter->SetMetadata(metadataMock); - EXPECT_NE(g_adapter->avSession_, nullptr); - g_adapter->avMetadata_->SetTitle(str1); - EXPECT_CALL(*metadataMock, GetTitle()).WillRepeatedly(::testing::Return(str2)); - EXPECT_CALL(*metadataMock, GetArtist()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*metadataMock, GetAlbum()).WillRepeatedly(::testing::Return(str1)); - EXPECT_CALL(*avSessionMock, SetAVMetaData(_)).WillOnce(::testing::Return(RET_ERROR)); + EXPECT_CALL(*avSessionMock, SetAVMetaData(_)).WillOnce( + ::testing::Return(RET_SUCCESS)); g_adapter->SetMetadata(metadataMock); - EXPECT_NE(g_adapter->avSession_, nullptr); + g_adapter->avSession_ = nullptr; + g_adapter->SetMetadata(metadataMock); } /** @@ -697,7 +710,7 @@ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapt /** * @tc.name: MediaAVSessionAdapterImplTest_MediaAVSessionAdapterImpl_009. - * @tc.desc: test of MediaAVSessionAdapterImpl :: SetPlaybackPosition() + * @tc.desc: test of MediaAVSessionAdapterImpl :: SetPlaybackPosition()_1 * @tc.type: FUNC. * @tc.require: */ @@ -720,17 +733,52 @@ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapt g_adapter->SetPlaybackPosition(positionMock); EXPECT_EQ(g_adapter->avSession_, nullptr); + g_adapter->avSession_ = nullptr; + g_adapter->avMetadata_->SetDuration(temp2); + EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly( + ::testing::Return(temp2)); + g_adapter->SetPlaybackPosition(positionMock); + auto avSessionMock = std::make_shared(); g_adapter->avSession_ = avSessionMock; g_adapter->avMetadata_->SetDuration(temp1); g_adapter->avPlaybackState_->SetDuration(temp1); g_adapter->avPlaybackState_->SetPosition({ temp1, temp1 }); - EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly(::testing::Return(temp1)); - EXPECT_CALL(*positionMock, GetElapsedTime()).WillRepeatedly(::testing::Return(temp1)); - EXPECT_CALL(*positionMock, GetUpdateTime()).WillRepeatedly(::testing::Return(temp1)); + EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly( + ::testing::Return(temp1)); + EXPECT_CALL(*positionMock, GetElapsedTime()).WillRepeatedly( + ::testing::Return(temp1)); + EXPECT_CALL(*positionMock, GetUpdateTime()).WillRepeatedly( + ::testing::Return(temp1)); g_adapter->SetPlaybackPosition(positionMock); EXPECT_NE(g_adapter->avSession_, nullptr); + g_adapter->avSession_ = avSessionMock; + g_adapter->avMetadata_->SetDuration(temp1); + EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly( + ::testing::Return(temp2)); + g_adapter->SetPlaybackPosition(positionMock); +} + +/** + * @tc.name: MediaAVSessionAdapterImplTest_MediaAVSessionAdapterImpl_016. + * @tc.desc: test of MediaAVSessionAdapterImpl :: SetPlaybackPosition()_2 + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapterImpl_016, TestSize.Level1) +{ + int64_t temp1 = 1; + int64_t temp2 = 2; + auto positionMock = std::make_shared(); + auto avPlaybackState = std::make_shared(); + auto avmetadata = std::make_shared(); + g_adapter->avMetadata_ = avmetadata; + g_adapter->avPlaybackState_ = avPlaybackState; + auto avSessionMock = std::make_shared(); + + g_adapter->avMetadata_->SetDuration(temp1); + g_adapter->avSession_ = avSessionMock; EXPECT_CALL(*avSessionMock, IsActive()).WillRepeatedly(::testing::Return(true)); EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly(::testing::Return(temp2)); EXPECT_CALL(*positionMock, GetElapsedTime()).WillRepeatedly(::testing::Return(temp2)); @@ -743,6 +791,7 @@ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapt g_adapter->avMetadata_->SetDuration(temp1); g_adapter->avPlaybackState_->SetDuration(temp1); g_adapter->avPlaybackState_->SetPosition({ temp1, temp1 }); + g_adapter->avSession_ = avSessionMock; EXPECT_CALL(*avSessionMock, IsActive()).WillRepeatedly(::testing::Return(true)); EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly(::testing::Return(temp2)); EXPECT_CALL(*positionMock, GetElapsedTime()).WillRepeatedly(::testing::Return(temp2)); @@ -900,5 +949,77 @@ HWTEST_F(MediaAVSessionAdapterImplTest, NWebMediaAdapterTest_MediaAVSessionAdapt EXPECT_CALL(*positionMock, GetUpdateTime()).WillRepeatedly(::testing::Return(temp1)); ret = g_adapter->UpdatePlaybackStateCache(positionMock); EXPECT_EQ(ret, true); + + g_adapter->avPlaybackState_->SetDuration(temp1); + g_adapter->avPlaybackState_->SetPosition({ temp1, temp1 }); + EXPECT_CALL(*positionMock, GetDuration()).WillRepeatedly( + ::testing::Return(temp1)); + EXPECT_CALL(*positionMock, GetElapsedTime()).WillRepeatedly( + ::testing::Return(temp1)); + EXPECT_CALL(*positionMock, GetUpdateTime()).WillRepeatedly( + ::testing::Return(temp2)); + ret = g_adapter->UpdatePlaybackStateCache(positionMock); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: MediaAVSessionAdapterImplTest_MediaAVSessionAdapterImpl_0014. + * @tc.desc: test of MediaAVSessionAdapterImpl :: DestroyAndEraseSession(); + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(MediaAVSessionAdapterImplTest, + NWebMediaAdapterTest_MediaAVSessionAdapterImpl_0014, + TestSize.Level1) +{ + auto avSessionKey = std::make_shared(); + g_adapter->avSessionKey_ = avSessionKey; + g_adapter->avSessionKey_->Init(); + auto avSessionMock = std::make_shared(); + g_adapter->avSession_ = avSessionMock; + + g_adapter->avSessionMap.clear(); + g_adapter->DestroyAndEraseSession(); + + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + nullptr)); + g_adapter->DestroyAndEraseSession(); + + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + g_adapter->avSession_)); + g_adapter->DestroyAndEraseSession(); + + g_adapter->avSessionMap.insert( + std::make_pair(g_adapter->avSessionKey_->ToString(), + g_adapter->avSession_)); + EXPECT_CALL(*avSessionMock, Destroy()).WillRepeatedly( + ::testing::Return(RET_ERROR)); + g_adapter->DestroyAndEraseSession(); +} + +/** + * @tc.name: MediaAVSessionAdapterImplTest_MediaAVSessionAdapterImpl_0015. + * @tc.desc: test of MediaAVSessionAdapterImpl :: CreateNewSession(); + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(MediaAVSessionAdapterImplTest, + NWebMediaAdapterTest_MediaAVSessionAdapterImpl_0015, + TestSize.Level1) +{ + auto avSessionKeyMock = std::make_shared(); + g_adapter->avSessionKey_ = avSessionKeyMock; + g_adapter->avSessionKey_->Init(); + auto type = MediaAVSessionType::MEDIA_TYPE_AUDIO; + + bool ret = g_adapter->CreateNewSession(type); + EXPECT_EQ(ret, true); + + EXPECT_CALL(*avSessionKeyMock, GetElement()).WillRepeatedly( + ::testing::Return(nullptr)); + ret = g_adapter->CreateNewSession(type); + EXPECT_EQ(ret, false); } } // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/unittest/ohos_adapter/media_adapter_test/media_codec_decoder_adapter_impl_test.cpp b/test/unittest/ohos_adapter/media_adapter_test/media_codec_decoder_adapter_impl_test.cpp index 91eb2c5b3c735d5dded0639e3a9421d6beed1648..e12a7dc5d7c8a702885562f2c48df78ac56cc1ab 100644 --- a/test/unittest/ohos_adapter/media_adapter_test/media_codec_decoder_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/media_adapter_test/media_codec_decoder_adapter_impl_test.cpp @@ -189,7 +189,7 @@ HWTEST_F(MediaCodecDecoderAdapterImplTest, MediaCodecDecoderAdapterImpl_NormalTe EXPECT_EQ(mediaCodecDecoderAdapterImpl_->SetOutputSurface(nullptr), DecoderAdapterCode::DECODER_ERROR); std::shared_ptr callback = std::make_shared(); EXPECT_EQ(mediaCodecDecoderAdapterImpl_->SetCallbackDec(callback), DecoderAdapterCode::DECODER_ERROR); - EXPECT_EQ(mediaCodecDecoderAdapterImpl_->PrepareDecoder(), DecoderAdapterCode::DECODER_OK); + EXPECT_EQ(mediaCodecDecoderAdapterImpl_->PrepareDecoder(), DecoderAdapterCode::DECODER_ERROR); EXPECT_EQ(mediaCodecDecoderAdapterImpl_->StartDecoder(), DecoderAdapterCode::DECODER_ERROR); EXPECT_EQ(mediaCodecDecoderAdapterImpl_->StopDecoder(), DecoderAdapterCode::DECODER_ERROR); EXPECT_EQ(mediaCodecDecoderAdapterImpl_->FlushDecoder(), DecoderAdapterCode::DECODER_ERROR); diff --git a/test/unittest/ohos_adapter/net_proxy_adapter_test/net_proxy_adapter_test.cpp b/test/unittest/ohos_adapter/net_proxy_adapter_test/net_proxy_adapter_test.cpp index e9750999fc2d8e34ee25f9c750eeb3e232b1a7f5..ca82d148b55dfe65bc55ca05cbc0d7c44a93f964 100644 --- a/test/unittest/ohos_adapter/net_proxy_adapter_test/net_proxy_adapter_test.cpp +++ b/test/unittest/ohos_adapter/net_proxy_adapter_test/net_proxy_adapter_test.cpp @@ -202,7 +202,7 @@ HWTEST_F(NetProxyAdapterTest, NetProxyAdapterTest_OnReceiveEvent_001, TestSize.L AccessToken token; HttpProxy httpProxy = {"tes.web.com", 0, {}}; int32_t ret = NetConnClient::GetInstance().SetGlobalHttpProxy(httpProxy); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); criber.OnReceiveEvent(data); Want want; want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HTTP_PROXY_CHANGE); diff --git a/test/unittest/inner_api_test/clipboard_controller_test/BUILD.gn b/test/unittest/ohos_adapter/ohos_image_adapter/BUILD.gn similarity index 61% rename from test/unittest/inner_api_test/clipboard_controller_test/BUILD.gn rename to test/unittest/ohos_adapter/ohos_image_adapter/BUILD.gn index dab01d7773c7dbceb2036e89706fc13798f2fa86..1b66fbd83f446daad7d92db50d848409f3627e68 100644 --- a/test/unittest/inner_api_test/clipboard_controller_test/BUILD.gn +++ b/test/unittest/ohos_adapter/ohos_image_adapter/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -19,34 +19,36 @@ config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "../../../../interfaces/inner_api/include", - "../../../../interfaces/inner_api/src", + "../../../../ohos_adapter/ohos_image_adapter/include", + "../../../../ohos_interface/include/ohos_adpter/ohos_image_decoder_adapter.h", ] } -ohos_unittest("web_clipboard_controller_test") { +ohos_unittest("ohos_image_decoder_adapter_test") { module_out_path = module_output_path - sources = [ "clipboard_controller_test.cpp" ] + sources = [ "ohos_image_decoder_adapter_test.cpp" ] configs = [ ":module_private_config" ] deps = [ - "../../../../interfaces/inner_api:web_inner_kit", + "../../../../ohos_adapter:nweb_ohos_adapter", + "../../../../ohos_nweb:libnweb", + "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] external_deps = [ - "ability_base:zuri", "c_utils:utils", + "graphic_2d:libnative_image", "hilog:libhilog", "image_framework:image_native", - "pasteboard:pasteboard_client", - "webview:libnweb", + "image_framework:image_utils", ] + resource_config_file = "../../../resource/image/ohos_test.xml" } group("unittest") { testonly = true - deps = [ ":web_clipboard_controller_test" ] + deps = [ ":ohos_image_decoder_adapter_test" ] } diff --git a/test/unittest/ohos_adapter/ohos_image_adapter/ohos_image_decoder_adapter_test.cpp b/test/unittest/ohos_adapter/ohos_image_adapter/ohos_image_decoder_adapter_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..609fc1eb069b14c44b6be7a5f8c57c56fbc79f52 --- /dev/null +++ b/test/unittest/ohos_adapter/ohos_image_adapter/ohos_image_decoder_adapter_test.cpp @@ -0,0 +1,497 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#define private public +#include "pixel_map.h" +#include "directory_ex.h" +#include "image_source.h" +#include "image_utils.h" +#include "ohos_image_decoder_adapter_impl.h" +#undef private + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { + +namespace NWeb { +namespace { + +static const std::string IMAGE_FILE_PATH = "/data/local/tmp/image/test.heic"; + +bool ReadFileToBuffer(const std::string &filePath, uint8_t *buffer, size_t bufferSize) +{ + std::string realPath; + if (!OHOS::PathToRealPath(filePath, realPath)) { + return false; + } + + if (buffer == nullptr) { + return false; + } + + FILE *fp = fopen(realPath.c_str(), "rb"); + if (fp == nullptr) { + return false; + } + if (fseek(fp, 0, SEEK_END) != 0) { + fclose(fp); + return false; + } + size_t fileSize = ftell(fp); + if (fseek(fp, 0, SEEK_SET) != 0) { + fclose(fp); + return false; + } + if (bufferSize < fileSize) { + fclose(fp); + return false; + } + size_t retSize = fread(buffer, 1, fileSize, fp); + if (retSize != fileSize) { + fclose(fp); + return false; + } + int ret = fclose(fp); + if (ret != 0) { + return true; + } + return true; +} + +bool TestInitImage(OhosImageDecoderAdapterImpl &imageDecoderAdapterImpl, uint8_t *buffer) +{ + size_t bufferSize = 0; + bool boolRes = Media::ImageUtils::GetFileSize(IMAGE_FILE_PATH, bufferSize); + if (!boolRes) { + return false; + } + + buffer = static_cast(malloc(bufferSize)); + if (buffer == nullptr) { + return false; + } + + boolRes = ReadFileToBuffer(IMAGE_FILE_PATH, buffer, bufferSize); + if (!boolRes) { + free(buffer); + return false; + } + + boolRes = imageDecoderAdapterImpl.ParseImageInfo(buffer, bufferSize); + if (!boolRes) { + free(buffer); + return false; + } + return true; +} + +bool TestDecodeImage(OhosImageDecoderAdapterImpl &imageDecoderAdapterImpl, uint8_t *buffer) +{ + size_t bufferSize = 0; + bool boolRes = Media::ImageUtils::GetFileSize(IMAGE_FILE_PATH, bufferSize); + if (!boolRes) { + return false; + } + + buffer = static_cast(malloc(bufferSize)); + if (buffer == nullptr) { + return false; + } + + boolRes = ReadFileToBuffer(IMAGE_FILE_PATH, buffer, bufferSize); + if (!boolRes) { + free(buffer); + return false; + } + + boolRes = imageDecoderAdapterImpl.DecodeToPixelMap(buffer, bufferSize); + if (!boolRes) { + free(buffer); + return false; + } + return true; +} +} // namespace + +class OhosImageAdapterTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void OhosImageAdapterTest::SetUpTestCase(void) +{} + +void OhosImageAdapterTest::TearDownTestCase(void) +{} + +void OhosImageAdapterTest::SetUp(void) +{} + +void OhosImageAdapterTest::TearDown(void) +{} + +/** + * @tc.name: OhosImageAdapterTest_ParseImageInfo_001 + * @tc.desc: ParseImageInfo. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_ParseImageInfo_001, TestSize.Level1) +{ + uint8_t data[32] = {0}; + uint32_t size = sizeof(data); + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + bool result = imageDecoderAdapterImpl.ParseImageInfo(nullptr, size); + EXPECT_FALSE(result); + + result = imageDecoderAdapterImpl.ParseImageInfo(data, 0); + EXPECT_FALSE(result); + + result = imageDecoderAdapterImpl.ParseImageInfo(data, size); + EXPECT_FALSE(result); + + size_t bufferSize = 0; + bool boolRes = Media::ImageUtils::GetFileSize(IMAGE_FILE_PATH, bufferSize); + EXPECT_TRUE(boolRes); + + uint8_t *buffer = static_cast(malloc(bufferSize)); + EXPECT_NE(buffer, nullptr); + + boolRes = ReadFileToBuffer(IMAGE_FILE_PATH, buffer, bufferSize); + EXPECT_TRUE(boolRes); + + boolRes = imageDecoderAdapterImpl.ParseImageInfo(buffer, (uint32_t)bufferSize); + EXPECT_TRUE(boolRes); + + free(buffer); +} + +/** + * @tc.name: OhosImageAdapterTest_GetEncodedFormat_002 + * @tc.desc: GetEncodedFormat. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetEncodedFormat_002, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + bool ret = TestInitImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + std::string format = imageDecoderAdapterImpl.GetEncodedFormat(); + EXPECT_NE(format, ""); + + free(buffer); +} + +/** + * @tc.name: OhosImageAdapterTest_GetImageWidth_003 + * @tc.desc: GetImageWidth. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetImageWidth_003, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + bool ret = TestInitImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + int32_t width = imageDecoderAdapterImpl.GetImageWidth(); + EXPECT_NE(width, 0); + + free(buffer); +} + +/** + * @tc.name: OhosImageAdapterTest_GetImageHeight_004 + * @tc.desc: GetImageHeight. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetImageHeight_004, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + bool ret = TestInitImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + int32_t heigth = imageDecoderAdapterImpl.GetImageHeight(); + EXPECT_NE(heigth, 0); + + free(buffer); +} + +/** + * @tc.name: OhosImageAdapterTest_DecodeToPixelMap_005 + * @tc.desc: DecodeToPixelMap. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_DecodeToPixelMap_005, TestSize.Level1) +{ + size_t bufferSize = 0; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + bool ret = imageDecoderAdapterImpl.DecodeToPixelMap(nullptr, bufferSize); + EXPECT_FALSE(ret); + + bool boolRes = Media::ImageUtils::GetFileSize(IMAGE_FILE_PATH, bufferSize); + + uint8_t *buffer = static_cast(malloc(bufferSize)); + + boolRes = ReadFileToBuffer(IMAGE_FILE_PATH, buffer, bufferSize); + EXPECT_TRUE(boolRes); + + ret = imageDecoderAdapterImpl.DecodeToPixelMap(buffer, bufferSize); + EXPECT_TRUE(ret); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +/** + * @tc.name: OhosImageAdapterTest_GetFd_006 + * @tc.desc: GetFd. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetFd_006, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + int32_t fd = imageDecoderAdapterImpl.GetFd(); + EXPECT_EQ(fd, -1); + + bool ret = TestDecodeImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + + fd = imageDecoderAdapterImpl.GetFd(); + EXPECT_NE(fd, -1); + + auto* pixelMap = imageDecoderAdapterImpl.GetPixelMap(); + pixelMap->FreePixelMap(); + fd = imageDecoderAdapterImpl.GetFd(); + EXPECT_EQ(fd, -1); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +/** + * @tc.name: OhosImageAdapterTest_GetStride_007 + * @tc.desc: GetStride. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetStride_007, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + int32_t stride = imageDecoderAdapterImpl.GetStride(); + EXPECT_EQ(stride, 0); + + bool ret = TestDecodeImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + + stride = imageDecoderAdapterImpl.GetStride(); + EXPECT_NE(stride, 0); + + auto* pixelMap = imageDecoderAdapterImpl.GetPixelMap(); + pixelMap->FreePixelMap(); + stride = imageDecoderAdapterImpl.GetStride(); + EXPECT_EQ(stride, 0); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +/** + * @tc.name: OhosImageAdapterTest_GetOffset_008 + * @tc.desc: GetOffset. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetOffset_008, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + int32_t offset = imageDecoderAdapterImpl.GetOffset(); + EXPECT_EQ(offset, 0); + + bool ret = TestDecodeImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + + offset = imageDecoderAdapterImpl.GetOffset(); + EXPECT_EQ(offset, 0); + + auto* pixelMap = imageDecoderAdapterImpl.GetPixelMap(); + pixelMap->FreePixelMap(); + offset = imageDecoderAdapterImpl.GetOffset(); + EXPECT_EQ(offset, 0); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +/** + * @tc.name: OhosImageAdapterTest_GetSize_009 + * @tc.desc: GetSize. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetSize_009, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + uint64_t size = imageDecoderAdapterImpl.GetSize(); + EXPECT_EQ(size, 0); + + bool ret = TestDecodeImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + + size = imageDecoderAdapterImpl.GetSize(); + EXPECT_NE(size, 0); + + auto* pixelMap = imageDecoderAdapterImpl.GetPixelMap(); + pixelMap->FreePixelMap(); + size = imageDecoderAdapterImpl.GetSize(); + EXPECT_EQ(size, 0); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +/** + * @tc.name: OhosImageAdapterTest_GetNativeWindowBuffer_010 + * @tc.desc: GetNativeWindowBuffer. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetNativeWindowBuffer_010, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + void* windowBuffer = imageDecoderAdapterImpl.GetNativeWindowBuffer(); + EXPECT_EQ(windowBuffer, nullptr); + + bool ret = TestDecodeImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + + windowBuffer = imageDecoderAdapterImpl.GetNativeWindowBuffer(); + EXPECT_NE(windowBuffer, nullptr); + + auto* pixelMap = imageDecoderAdapterImpl.GetPixelMap(); + pixelMap->FreePixelMap(); + windowBuffer = imageDecoderAdapterImpl.GetNativeWindowBuffer(); + EXPECT_NE(windowBuffer, nullptr); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + + +/** + * @tc.name: OhosImageAdapterTest_GetPlanesCount_011 + * @tc.desc: GetPlanesCount. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_GetPlanesCount_011, TestSize.Level1) +{ + uint8_t *buffer = nullptr; + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + + int32_t planesCount = imageDecoderAdapterImpl.GetPlanesCount(); + EXPECT_EQ(planesCount, 0); + + bool ret = TestDecodeImage(imageDecoderAdapterImpl, buffer); + EXPECT_TRUE(ret); + + planesCount = imageDecoderAdapterImpl.GetPlanesCount(); + EXPECT_EQ(planesCount, 0); + + auto* pixelMap = imageDecoderAdapterImpl.GetPixelMap(); + pixelMap->FreePixelMap(); + planesCount = imageDecoderAdapterImpl.GetPlanesCount(); + EXPECT_EQ(planesCount, 0); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +/** + * @tc.name: OhosImageAdapterTest_Decode_012 + * @tc.desc: Decode. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(OhosImageAdapterTest, OhosImageAdapterTest_Decode_012, TestSize.Level1) +{ + OhosImageDecoderAdapterImpl imageDecoderAdapterImpl; + uint8_t data[32] = {0}; + uint32_t size = sizeof(data); + bool ret = imageDecoderAdapterImpl.Decode(data, size, AllocatorType::kDmaAlloc, false); + EXPECT_FALSE(ret); + + ret = imageDecoderAdapterImpl.Decode(nullptr, size, AllocatorType::kDmaAlloc, false); + EXPECT_FALSE(ret); + + ret = imageDecoderAdapterImpl.Decode(data, 0, AllocatorType::kDmaAlloc, false); + EXPECT_FALSE(ret); + + size_t bufferSize = 0; + bool boolRes = Media::ImageUtils::GetFileSize(IMAGE_FILE_PATH, bufferSize); + uint8_t *buffer = static_cast(malloc(bufferSize)); + boolRes = ReadFileToBuffer(IMAGE_FILE_PATH, buffer, bufferSize); + EXPECT_TRUE(boolRes); + + ret = imageDecoderAdapterImpl.Decode(buffer, bufferSize, AllocatorType::kDmaAlloc, true); + EXPECT_TRUE(ret); + + ret = imageDecoderAdapterImpl.Decode(buffer, bufferSize, AllocatorType::kDmaAlloc, false); + EXPECT_TRUE(ret); + + free(buffer); + + imageDecoderAdapterImpl.ReleasePixelMap(); +} + +} // namespace NWeb +} // namespace OHOS diff --git a/test/unittest/ohos_adapter/ohos_resource_adapter_test/ohos_resource_adapter_test.cpp b/test/unittest/ohos_adapter/ohos_resource_adapter_test/ohos_resource_adapter_test.cpp index 65fab38d66b4b04891d1985eeb16bf935516a1b8..f7a89e9111c6588dc72b2e9fd4a9b0ba0dd83e46 100644 --- a/test/unittest/ohos_adapter/ohos_resource_adapter_test/ohos_resource_adapter_test.cpp +++ b/test/unittest/ohos_adapter/ohos_resource_adapter_test/ohos_resource_adapter_test.cpp @@ -37,6 +37,8 @@ namespace { constexpr uint32_t MODULE_NAME_SIZE = 32; const std::string NWEB_HAP_PATH = "/system/app/com.ohos.nweb/NWeb.hap"; const std::string NWEB_HAP_PATH_1 = "/system/app/NWeb/NWeb.hap"; +const std::string NWEB_HAP_PATH_MODULE_UPDATE = "/module_update/ArkWebCore/app/com.ohos.nweb/NWeb.hap"; + std::shared_ptr g_applicationContext = nullptr; } @@ -168,11 +170,16 @@ HWTEST_F(OhosResourceAdapterTest, OhosResourceAdapterTest_OhosFileMapperImpl_003 if (access(NWEB_HAP_PATH_1.c_str(), F_OK) == 0) { hapPath = NWEB_HAP_PATH_1; } + + if (access(NWEB_HAP_PATH_MODULE_UPDATE.c_str(), F_OK) == 0) { + hapPath = NWEB_HAP_PATH_MODULE_UPDATE; + } + std::shared_ptr extractor = std::make_shared(hapPath); EXPECT_NE(extractor, nullptr); std::shared_ptr fileReader = OHOS::AbilityBase::ZipFileReader::CreateZipFileReader(hapPath); - EXPECT_NE(fileReader, nullptr); + EXPECT_EQ(fileReader, nullptr); std::unique_ptr fileMap = std::make_unique(); EXPECT_NE(fileMap, nullptr); fileMap->CreateFileMapper(fileReader, hapPath, 0, hapPath.size(), true); @@ -212,10 +219,13 @@ HWTEST_F(OhosResourceAdapterTest, OhosResourceAdapterTest_ParseModuleName_004, T if (access(NWEB_HAP_PATH_1.c_str(), F_OK) == 0) { hapPath = NWEB_HAP_PATH_1; } + if (access(NWEB_HAP_PATH_MODULE_UPDATE.c_str(), F_OK) == 0) { + hapPath = NWEB_HAP_PATH_MODULE_UPDATE; + } OhosResourceAdapterImpl adapterImpl(hapPath); bool newCreate = false; std::shared_ptr extractor = ExtractorUtil::GetExtractor(hapPath, newCreate); - EXPECT_NE(extractor, nullptr); + EXPECT_EQ(extractor, nullptr); std::string result = adapterImpl.GetModuleName(nullptr, 0); EXPECT_EQ(result, ""); char *configStr = static_cast(malloc(MODULE_NAME_SIZE)); @@ -267,6 +277,9 @@ HWTEST_F(OhosResourceAdapterTest, OhosResourceAdapterTest_GetResourceMgr_005, Te if (access(NWEB_HAP_PATH_1.c_str(), F_OK) == 0) { hapPath = NWEB_HAP_PATH_1; } + if (access(NWEB_HAP_PATH_MODULE_UPDATE.c_str(), F_OK) == 0) { + hapPath = NWEB_HAP_PATH_MODULE_UPDATE; + } OhosResourceAdapterImpl adapterImpl(hapPath); uint8_t* dest; std::string rawFile = "test"; @@ -321,6 +334,10 @@ HWTEST_F(OhosResourceAdapterTest, OhosResourceAdapterTest_GetResourceString_006, if (access(NWEB_HAP_PATH_1.c_str(), F_OK) == 0) { hapPath = NWEB_HAP_PATH_1; } + if (access(NWEB_HAP_PATH_MODULE_UPDATE.c_str(), F_OK) == 0) { + hapPath = NWEB_HAP_PATH_MODULE_UPDATE; + } + OhosResourceAdapterImpl adapterImpl(hapPath); std::string res; diff --git a/test/unittest/ohos_adapter/screen_capture_adapter_impl_test/screen_capture_adapter_impl_test.cpp b/test/unittest/ohos_adapter/screen_capture_adapter_impl_test/screen_capture_adapter_impl_test.cpp index 9312b5675c90657326edf80a2be58b18ceff29a9..be15be85b496e862620d6ade9257345819fd461d 100644 --- a/test/unittest/ohos_adapter/screen_capture_adapter_impl_test/screen_capture_adapter_impl_test.cpp +++ b/test/unittest/ohos_adapter/screen_capture_adapter_impl_test/screen_capture_adapter_impl_test.cpp @@ -45,6 +45,8 @@ public: MOCK_METHOD1(Init, int32_t(AVScreenCaptureConfig)); MOCK_METHOD1(SetMicrophoneEnabled, int32_t(bool)); MOCK_METHOD1(SetCanvasRotation, int32_t(bool)); + MOCK_METHOD2(ResizeCanvas, int32_t(int32_t, int32_t)); + MOCK_METHOD1(SkipPrivacyMode, int32_t(std::vector&)); MOCK_METHOD0(StartScreenCapture, int32_t()); MOCK_METHOD1(StartScreenCaptureWithSurface, int32_t(sptr)); MOCK_METHOD0(StopScreenCapture, int32_t()); diff --git a/test/unittest/ohos_adapter/sensor_adapter_impl_test/BUILD.gn b/test/unittest/ohos_adapter/sensor_adapter_impl_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..50dfe4fca4437bd35ecc341fac6d229e5b561604 --- /dev/null +++ b/test/unittest/ohos_adapter/sensor_adapter_impl_test/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/web/webview/web_aafwk.gni") +import("//build/test.gni") +import("../../../../config.gni") + +module_output_path = "web/webview" + +config("module_private_config") { + visibility = [ ":*" ] + cflags_cc = [ "--coverage" ] + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + include_dirs = [ "$webview_path/ohos_adapter/sensor_adapter/include" ] +} + +ohos_unittest("sensor_adapter_impl_test") { + module_out_path = module_output_path + + sources = [ "sensor_adapter_impl_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "$webview_path/ohos_adapter:nweb_ohos_adapter", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "graphic_surface:surface", + "hilog:libhilog", + ] + + if (webview_sensors_sensor_enable) { + external_deps += [ "sensor:sensor_interface_native" ] + } +} + +group("unittest") { + testonly = true + deps = [] + if (webview_sensors_sensor_enable) { + deps += [ ":sensor_adapter_impl_test" ] + } +} diff --git a/test/unittest/ohos_adapter/sensor_adapter_impl_test/sensor_adapter_impl_test.cpp b/test/unittest/ohos_adapter/sensor_adapter_impl_test/sensor_adapter_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44b3a058051a01e818deb65a03cc97c961356aad --- /dev/null +++ b/test/unittest/ohos_adapter/sensor_adapter_impl_test/sensor_adapter_impl_test.cpp @@ -0,0 +1,584 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#define private public +#include "sensor_adapter.h" +#include "sensor_adapter_impl.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS::NWeb { +namespace { +std::shared_ptr g_sensoCallback; +std::shared_ptr g_sensorAdapter; +} +constexpr double NANOSECONDS_IN_SECOND = 1000000000.0; +constexpr double DEFAULT_SAMPLE_PERIOD = 200000000.0; + +class SensorCallbackImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class SensorAdapterImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class SensorCallbackAdapterMock : public SensorCallbackAdapter { +public: + ~SensorCallbackAdapterMock() = default; + void UpdateOhosSensorData(double timestamp, + double value1, double value2, double value3, double value4) {} +}; + +void SensorCallbackImplTest::SetUpTestCase(void) {} + +void SensorCallbackImplTest::TearDownTestCase(void) {} + +void SensorCallbackImplTest::SetUp(void) +{ + auto callbackAdapter = std::make_shared(); + g_sensoCallback = std::make_shared(callbackAdapter); + ASSERT_NE(g_sensoCallback, nullptr); +} + +void SensorCallbackImplTest::TearDown(void) +{ + g_sensoCallback = nullptr; +} + +void SensorAdapterImplTest::SetUpTestCase(void) {} + +void SensorAdapterImplTest::TearDownTestCase(void) {} + +void SensorAdapterImplTest::SetUp(void) +{ + g_sensorAdapter = std::make_shared(); + ASSERT_NE(g_sensorAdapter, nullptr); +} + +void SensorAdapterImplTest::TearDown(void) +{ + g_sensorAdapter = nullptr; +} + +/** + * @tc.name: SensorAdapterImplTest_SensorCallbackImpl_001. + * @tc.desc: test of SensorCallbackImpl :: UpdateOhosSensorData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorCallbackImplTest, SensorAdapterImplTest_SensorCallbackImplTest_001, TestSize.Level1) +{ + double temp = 1.1; + g_sensoCallback->callbackAdapter_ = nullptr; + g_sensoCallback->UpdateOhosSensorData(temp, temp, temp, temp, temp); + EXPECT_EQ(g_sensoCallback->callbackAdapter_, nullptr); + + auto callbackAdapter = std::make_shared(); + g_sensoCallback->callbackAdapter_ = callbackAdapter; + g_sensoCallback->UpdateOhosSensorData(temp, temp, temp, temp, temp); + EXPECT_NE(g_sensoCallback->callbackAdapter_, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_001. + * @tc.desc: test of SensorAdapterImpl :: IsOhosSensorSupported() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_001, TestSize.Level1) +{ + int32_t temp = 1; + auto number = g_sensorAdapter->IsOhosSensorSupported(temp); + EXPECT_EQ(number, SENSOR_ERROR); + + temp = 9; + number = g_sensorAdapter->IsOhosSensorSupported(temp); + EXPECT_EQ(number, SENSOR_SUCCESS); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_002. + * @tc.desc: test of SensorAdapterImpl :: GetOhosSensorReportingMode() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_002, TestSize.Level1) +{ + int32_t temp = 11; + int32_t temp1 = SENSOR_DATA_REPORT_CONTINUOUS; + auto mode = g_sensorAdapter->GetOhosSensorReportingMode(temp); + EXPECT_EQ(mode, temp1); + + temp = 1; + temp1 = -1; + mode = g_sensorAdapter->GetOhosSensorReportingMode(temp); + EXPECT_EQ(mode, temp1); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_003. + * @tc.desc: test of SensorAdapterImpl :: GetOhosSensorDefaultSupportedFrequency() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_003, TestSize.Level1) +{ + int32_t temp = 1; + double temp1 = 0.0; + auto mode = g_sensorAdapter->GetOhosSensorDefaultSupportedFrequency(temp); + EXPECT_EQ(mode, temp1); + + temp = 2; + temp1 = NANOSECONDS_IN_SECOND / DEFAULT_SAMPLE_PERIOD; + mode = g_sensorAdapter->GetOhosSensorDefaultSupportedFrequency(temp); + EXPECT_EQ(mode, temp1); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_004. + * @tc.desc: test of SensorAdapterImpl :: GetOhosSensorMinSupportedFrequency() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_004, TestSize.Level1) +{ + int32_t temp = 1; + double temp1 = 0.0; + auto mode = g_sensorAdapter->GetOhosSensorMinSupportedFrequency(temp); + EXPECT_EQ(mode, temp1); + + temp = 2; + mode = g_sensorAdapter->GetOhosSensorMinSupportedFrequency(temp); + EXPECT_NE(mode, temp1); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_005. + * @tc.desc: test of SensorAdapterImpl :: GetOhosSensorMaxSupportedFrequency() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_005, TestSize.Level1) +{ + int32_t temp = 1; + double temp1 = 0.0; + auto mode = g_sensorAdapter->GetOhosSensorMaxSupportedFrequency(temp); + EXPECT_EQ(mode, temp1); + + temp = 2; + mode = g_sensorAdapter->GetOhosSensorMaxSupportedFrequency(temp); + EXPECT_NE(mode, temp1); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_006. + * @tc.desc: test of SensorAdapterImpl :: SubscribeOhosSensor() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_006, TestSize.Level1) +{ + int32_t id = 1; + int64_t temp = 0; + auto status = g_sensorAdapter->SubscribeOhosSensor(id, temp); + EXPECT_EQ(status, SENSOR_PARAMETER_ERROR); + + temp = 1; + status = g_sensorAdapter->SubscribeOhosSensor(id, temp); + EXPECT_EQ(status, SENSOR_PARAMETER_ERROR); + + id = 2; + status = g_sensorAdapter->SubscribeOhosSensor(id, temp); + EXPECT_EQ(status, SENSOR_SUCCESS); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_007. + * @tc.desc: test of SensorAdapterImpl :: RegistOhosSensorCallback() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_007, TestSize.Level1) +{ + int32_t id = 1; + auto callbackAdapter = std::make_shared(); + auto status = g_sensorAdapter->RegistOhosSensorCallback(id, callbackAdapter); + EXPECT_EQ(status, SENSOR_PARAMETER_ERROR); + + id = 2; + status = g_sensorAdapter->RegistOhosSensorCallback(id, callbackAdapter); + EXPECT_EQ(status, SENSOR_SUCCESS); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_008. + * @tc.desc: test of SensorAdapterImpl :: UnsubscribeOhosSensor() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_008, TestSize.Level1) +{ + int32_t id = 1; + auto status = g_sensorAdapter->UnsubscribeOhosSensor(id); + EXPECT_EQ(status, SENSOR_PARAMETER_ERROR); + + id = 2; + status = g_sensorAdapter->UnsubscribeOhosSensor(id); + EXPECT_NE(status, SENSOR_SUCCESS); +} + + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_009. + * @tc.desc: test of SensorAdapterImpl :: OhosSensorCallback() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_009, TestSize.Level1) +{ + std::vector> callback(9); + for(int32_t i=0; i<9; i++) { + auto callbackAdapter = std::make_shared(); + callback[i] = std::make_shared(callbackAdapter); + SensorAdapterImpl::sensorCallbackMap.emplace(i+2,callback[i]); + } + + SensorEvent* event = new SensorEvent; + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 7; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 2; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 3; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 4; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 5; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 6; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 8; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 9; + g_sensorAdapter->OhosSensorCallback(event); + event->sensorTypeId = 11; + g_sensorAdapter->OhosSensorCallback(event); + EXPECT_NE(g_sensorAdapter, nullptr); + delete event; + SensorAdapterImpl::sensorCallbackMap.clear(); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_010. + * @tc.desc: test of SensorAdapterImpl :: handleAccelerometerData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_010, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleAccelerometerData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_011. + * @tc.desc: test of SensorAdapterImpl :: handleLinearAccelerometerData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_011, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleLinearAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleLinearAccelerometerData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleLinearAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleLinearAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleLinearAccelerometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_012. + * @tc.desc: test of SensorAdapterImpl :: handleGravityData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_012, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleGravityData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleGravityData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleGravityData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleGravityData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleGravityData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_013. + * @tc.desc: test of SensorAdapterImpl :: handleCyroscopeData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_013, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleCyroscopeData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleCyroscopeData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleCyroscopeData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleCyroscopeData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleCyroscopeData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_014. + * @tc.desc: test of SensorAdapterImpl :: handleMagnetometerData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_014, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleMagnetometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleMagnetometerData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleMagnetometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleMagnetometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleMagnetometerData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_015. + * @tc.desc: test of SensorAdapterImpl :: handleOrientationData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_015, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleOrientationData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleOrientationData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleOrientationData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleOrientationData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleOrientationData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_016. + * @tc.desc: test of SensorAdapterImpl :: handleRotationVectorData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_016, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleRotationVectorData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} + +/** + * @tc.name: SensorAdapterImplTest_SensorAdapterImpl_017. + * @tc.desc: test of SensorAdapterImpl :: handleGameRotationVectorData() + * @tc.type: FUNC. + * @tc.require: + */ +HWTEST_F(SensorAdapterImplTest, SensorAdapterImplTest_SensorAdapterImpl_017, TestSize.Level1) +{ + auto callbackAdapter = std::make_shared(); + auto callback = std::make_shared(callbackAdapter); + SensorEvent* event = new SensorEvent; + g_sensorAdapter->handleGameRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + uint8_t *data = new uint8_t[10]; + event->data = data; + g_sensorAdapter->handleGameRotationVectorData(callback, event); + delete event->data; + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleGameRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + event = new SensorEvent; + callback = nullptr; + g_sensorAdapter->handleGameRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); + + delete event; + event =nullptr; + g_sensorAdapter->handleGameRotationVectorData(callback, event); + EXPECT_NE(g_sensorAdapter, nullptr); +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/unittest/ohos_adapter_helper/ohos_adapter_helper_test.cpp b/test/unittest/ohos_adapter_helper/ohos_adapter_helper_test.cpp index ccce2a1c287818b7b6839f296b752e83e8536241..65d40b35f4f3ea6f5a22423929a8d32b063f4bef 100644 --- a/test/unittest/ohos_adapter_helper/ohos_adapter_helper_test.cpp +++ b/test/unittest/ohos_adapter_helper/ohos_adapter_helper_test.cpp @@ -92,7 +92,7 @@ HWTEST_F(OhosAdapterHelperTest, OhosAdapterHelper_GetCookieManager_001, TestSize helper.SetBundlePath(MOCK_INSTALLATION_DIR); helper.Init(false); auto cook = helper.GetCookieManager(); - EXPECT_NE(cook, nullptr); + EXPECT_EQ(cook, nullptr); auto base = helper.GetDataBase(); EXPECT_NE(base, nullptr); auto storage = helper.GetWebStorage(); @@ -184,7 +184,7 @@ HWTEST_F(OhosAdapterHelperTest, OhosAdapterHelper_GetDataBase_003, TestSize.Leve auto cook = helper.GetCookieManager(); EXPECT_EQ(cook, nullptr); auto base = helper.GetDataBase(); - EXPECT_NE(base, nullptr); + EXPECT_EQ(base, nullptr); auto storage = helper.GetWebStorage(); EXPECT_NE(storage, nullptr); auto nweb = helper.GetNWeb(nweb_id);