diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4947287f7b5ccb5d1e8b7b2d3aa5d89f322c160d --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 0000000000000000000000000000000000000000..12fdc207ed1f08523dde2aafe60ad04bab4031d4 --- /dev/null +++ b/OAT.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.en.md b/README.en.md deleted file mode 100644 index f33aca0d2469651b14886e4933d815a4a6bd8ef9..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# web_webview - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md deleted file mode 100644 index 127bbce33b21dc5d572a7259b0743817b0dde31b..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# web_webview - -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} - -#### 软件架构 -软件架构说明 - - -#### 安装教程 - -1. xxxx -2. xxxx -3. xxxx - -#### 使用说明 - -1. xxxx -2. xxxx -3. xxxx - -#### 参与贡献 - -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request - - -#### 特技 - -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README_ZH.md b/README_ZH.md new file mode 100644 index 0000000000000000000000000000000000000000..2215ee03073221d04fa03373e95825861194c50a --- /dev/null +++ b/README_ZH.md @@ -0,0 +1,47 @@ +# web_webview + +#### 介绍 +webview是Openharmony web组件的Native引擎,基于Chromium和CEF构建。 + +#### 软件架构 +软件架构说明 + + ----------------------- + | web组件 | + ----------------------- + | webview | + ----------------------- + | CEF | + ----------------------- + | Chromium | + ----------------------- + | Openharmony基础库 | + ----------------------- + + web组件:Openharmony的UI组件 + webview: 基于CEF构建的Openharmony web Native引擎 + CEF:CEF全称Chromium Embedded Framework,是一个基于Google Chromium 的开源项目 + Chromium: Chromium是一个由Google主导开发的网页浏览器。以BSD许可证等多重自由版权发行并开放源代码 + + #### 目录结构 +. +├── interfaces # 提供给组件调用的接口层 +│   └── innerkits +│   └── ohos_nweb +├── ohos_nweb # 适配Openharmony的框架层 +│   ├── include +│   └── src +└── test # 单元测试代码 + └── ohos_nweb + + + +#### 相关仓 +ace_ace_engine + +third_party_cef + +web_webview + +third_party_chromium + diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..7ddfc3d10f7ca5e724db41909074927a678d41e1 --- /dev/null +++ b/bundle.json @@ -0,0 +1,59 @@ +{ + "name": "@ohos/web", + "description": "library for webview", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "base/web/webview" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "webview", + "subsystem": "web", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "~85MB", + "ram": "~150MB", + "deps": { + "components": [ + "libvsync_client", + "libsurface", + "librender_service_client", + "libwm" + ], + "third_party": [] + }, + "build": { + "sub_component": [ + "//base/web/webview/ohos_nweb:libnweb", + "//base/web/webview/ohos_nweb:nweb_hap" + ], + "inner_kits": [ + { + "header": { + "header_files": [ + "nweb_export.h", + "nweb_url_resource_response.h", + "nweb_handler.h", + "nweb_javascript_result_callback.h", + "nweb_url_resource_error.h", + "nweb_preference.h", + "nweb.h", + "nweb_value.h", + "nweb_url_resource_request.h", + "nweb_adapter_helper.h", + "nweb_helper.h" + ], + "header_base": "//base/web/webview/interfaces/innerkits/ohos_nweb" + }, + "name": "//base/web/webview/ohos_nweb:libnweb" + } + ] + } + } +} diff --git a/interfaces/innerkits/ohos_nweb/nweb.h b/interfaces/innerkits/ohos_nweb/nweb.h new file mode 100644 index 0000000000000000000000000000000000000000..007c62467681af1087f9639fa30a4ca607d73e79 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb.h @@ -0,0 +1,295 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_H +#define NWEB_H + +#include +#include +#include +#include +#include "nweb_export.h" + +#include "nweb_download_callback.h" +#include "nweb_javascript_result_callback.h" +#include "nweb_preference.h" +#include "nweb_value_callback.h" +#include "nweb_hit_testresult.h" + +namespace OHOS::NWeb { +class NWebHandler; + +struct OHOS_NWEB_EXPORT NWebInitArgs { + std::string dump_path = ""; + bool frame_info_dump = false; + std::list web_engine_args_to_add; + std::list web_engine_args_to_delete; + bool multi_renderer_process = false; +}; + +struct OHOS_NWEB_EXPORT NWebCreateInfo { + /* size info */ + uint32_t width = 0; + uint32_t height = 0; + + /* output frame cb */ + std::function output_render_frame = + nullptr; + + /* init args */ + NWebInitArgs init_args; +}; + +class OHOS_NWEB_EXPORT NWeb : public std::enable_shared_from_this { + public: + NWeb() = default; + virtual ~NWeb() = default; + + virtual void Resize(uint32_t width, uint32_t height) = 0; + + /* lifecycle interface */ + virtual void OnPause() const = 0; + virtual void OnContinue() const = 0; + virtual void OnDestroy() = 0; + + /* event interface */ + virtual void OnTouchPress(int32_t id, double x, double y) = 0; + virtual void OnTouchRelease(int32_t id, double x = 0, double y = 0) = 0; + virtual void OnTouchMove(int32_t id, double x, double y) = 0; + virtual void OnTouchCancel() = 0; + virtual void OnNavigateBack() = 0; + + /** + * Loads the given URL. + * + * @param url String: the URL of the resource to load This value cannot be + * null. + * + * @return title string for the current page. + */ + virtual void Load(const std::string& url) const = 0; + /** + * Gets whether this NWeb has a back history item. + * + * @return true if this NWeb has a back history item + */ + virtual bool IsNavigatebackwardAllowed() const = 0; + /** + * Gets whether this NWeb has a forward history item. + * + * @return true if this NWeb has a forward history item + */ + virtual bool IsNavigateForwardAllowed() const = 0; + /** + * Gets whether this NWeb has a back or forward history item for number of + * steps. + * + * @param numSteps int: the negative or positive number of steps to move the + * history + * @return true if this NWeb has a forward history item + */ + virtual bool CanNavigateBackOrForward(int numSteps) const = 0; + /** + * Goes back in the history of this NWeb. + * + */ + virtual void NavigateBack() const = 0; + /** + * Goes forward in the history of this NWeb. + * + */ + virtual void NavigateForward() const = 0; + /** + * Reloads the current URL. + * + */ + virtual void Reload() const = 0; + /** + * Performs a zoom operation in this NWeb. + * + * @param zoomFactor float: the zoom factor to apply. The zoom factor will be + * clamped to the NWeb's zoom limits. This value must be in the range 0.01 + * to 100.0 inclusive. + * + */ + virtual void Zoom(float zoomFactor) const = 0; + + /** + * Stops the current load. + * + * @param code string: javascript code + */ + virtual void Stop() const = 0; + /** + * ExecuteJavaScript + * + */ + virtual void ExecuteJavaScript(const std::string& code) const = 0; + /** + * ExecuteJavaScript plus + * + * @param code string: javascript code + * + * @param callback NWebValueCallback: javascript running result + * + */ + virtual void ExecuteJavaScript( + const std::string& code, + std::shared_ptr> callback) const = 0; + /** + * Gets the NWebPreference object used to control the settings for this + * NWeb. + * + * @return a NWebPreference object that can be used to control this NWeb's + * settings This value cannot be null. + */ + virtual const std::shared_ptr GetPreference() const = 0; + /** + * Gets the last hit test result. + * + * @return the last HitTestResult + */ + virtual HitTestResult GetHitTestResult() const = 0; + + /** + * Sets the background color for this view. + * + * @param color int: the color of the background + * + */ + virtual void PutBackgroundColor(int color) const = 0; + /** + * Sets the NWebDownloadCallback that will receive download event. + * This will replace the current handler. + * + * @param downloadListener NWebDownloadCallback: + * + */ + virtual void PutDownloadCallback( + std::shared_ptr downloadListener) = 0; + /** + * Sets the NWebHandler that will receive various notifications and + * requests. This will replace the current handler. + * + * @param client NWebHandler: an implementation of NWebHandler This value + * cannot be null. + * + */ + virtual void SetNWebHandler(std::shared_ptr handler) = 0; + /** + * Gets the NWebHandler. + * + * @return Gets the NWebHandler. + */ + virtual const std::shared_ptr GetNWebHandler() const = 0; + /** + * Gets the title for the current page. + * + * @return title string for the current page. + */ + virtual std::string Title() = 0; + /** + * Gets the progress for the current page. + * + * @return progress for the current page. + */ + virtual int PageLoadProgress() = 0; + + /** + * Gets the height of the HTML content. + * + * @return the height of the HTML content. + */ + virtual int ContentHeight() = 0; + + /** + * Gets the current scale of this NWeb. + * + * @return the current scale + */ + virtual float Scale() = 0; + + /** + * Loads the given URL with additional HTTP headers, specified as a map + * from name to value. Note that if this map contains any of the headers that + * are set by default by this NWeb, such as those controlling caching, + * accept types or the User-Agent, their values may be overridden by this + * NWeb's defaults. + * + * @param url String: the URL of the resource to load This value cannot be + * null. + * + * @param additionalHttpHeaders additionalHttpHeaders + */ + virtual void Load( + std::string& url, + std::map additionalHttpHeaders) = 0; + + /** + * Loads the given data into this NWeb, using baseUrl as the base URL for + * the content. The base URL is used both to resolve relative URLs and when + * applying JavaScript's same origin policy. The historyUrl is used for the + * history entry. + * + * @param baseUrl String: the URL to use as the page's base URL. If null + * defaults to 'about:blank'. This value may be null. + * @param data String: the URL to use as the page's base URL. If null defaults + * to 'about:blank'. This value may be null. + * @param mimeType String: the MIME type of the data, e.g. 'text/html'. This + * value may be null. + * @param encoding String: the encoding of the data This value may be null. + * @param historyUrl String: the URL to use as the history entry. If null + * defaults to 'about:blank'. If non-null, this must be a valid URL. This + * value may be null. + */ + virtual void LoadWithDataAndBaseUrl(const std::string& baseUrl, + const std::string& data, + const std::string& mimeType, + const std::string& encoding, + const std::string& historyUrl) = 0; + + /** + * Loads the given data into this NWeb. + * + * @param data String: the URL to use as the page's base URL. If null defaults + * to 'about:blank'. This value may be null. + * @param mimeType String: the MIME type of the data, e.g. 'text/html'. This + * value may be null. + * @param encoding String: the encoding of the data This value may be null. + */ + virtual void LoadWithData(const std::string& data, + const std::string& mimeType, + const std::string& encoding) = 0; + + /** + * RegisterArkJSfunction + * + * @param object_name String: objector name + * @param method_list vector: vector list ,method list + */ + virtual void RegisterArkJSfunction( + const std::string& object_name, + const std::vector& method_list) = 0; + + /** + * UnregisterArkJSfunction + * + * @param object_name String: objector name + * @param method_list vector: vector list ,method list + */ + virtual void UnregisterArkJSfunction( + const std::string& object_name, + const std::vector& method_list) = 0; + + /** + * SetNWebJavaScriptResultCallBack + * + * @param callback NWebJavaScriptResultCallBack: callback client + */ + virtual void SetNWebJavaScriptResultCallBack( + std::shared_ptr callback) = 0; +}; +} // namespace OHOS::NWeb + +#endif diff --git a/interfaces/innerkits/ohos_nweb/nweb_access_request.h b/interfaces/innerkits/ohos_nweb/nweb_access_request.h new file mode 100644 index 0000000000000000000000000000000000000000..6592ba26ee9614a7b51851f3d1fd12bd21346aa2 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_access_request.h @@ -0,0 +1,58 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_ACCESS_REQUEST_H +#define NWEB_ACCESS_REQUEST_H + +#include + +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebAccessRequest { +public: + NWebAccessRequest() = default; + + virtual ~NWebAccessRequest() = default; + + enum Resources { + GEOLOCATION = 1 << 0, + VIDEO_CAPTURE = 1 << 1, + AUDIO_CAPTURE = 1 << 2, + PROTECTED_MEDIA_ID = 1 << 3, + MIDI_SYSEX = 1 << 4, + }; + + /** + * Get the origin of the web page which is trying to access the resource. + * + * @return the origin of the web page which is trying to access the resource. + */ + virtual std::string Origin() = 0; + + /** + * Get the resource id the web page is trying to access. + * + * @return the resource id the web page is trying to access. + */ + virtual int ResourceAcessId() = 0; + + /** + * Agree the origin to access the given resources. + * The granted access is only valid for this WebView. + * + * @param resourceId id of the resource agreed to be accessed by origin. It + * must be equal to requested resource id returned by {@link + * #GetResourceAcessId()}. + */ + virtual void Agree(int resourceId) = 0; + + /** + * Refuse the request. + */ + virtual void Refuse() = 0; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_ACCESS_REQUEST_H \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_adapter_helper.h b/interfaces/innerkits/ohos_nweb/nweb_adapter_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..6e56ba1d915537537cde61cd898619548fa13c1f --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_adapter_helper.h @@ -0,0 +1,43 @@ +/* + * 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_ADAPTER_HELPER_H +#define NWEB_ADAPTER_HELPER_H + +#include "window.h" +#include "nweb_helper.h" + +namespace OHOS { +class Surface; +} + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebAdapterHelper { +public: + static NWebAdapterHelper &Instance(); + ~NWebAdapterHelper() = default; + bool Init(); + std::shared_ptr CreateNWeb(Rosen::Window *window, const NWebInitArgs &initArgs); + std::shared_ptr CreateNWeb(sptr surface, + const NWebInitArgs &initArgs, + uint32_t width = 0, + uint32_t height = 0); + +private: + NWebAdapterHelper() = default; +}; +} // namespace OHOS + +#endif // NWEB_ADAPTER_HELPER_H \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_console_log.h b/interfaces/innerkits/ohos_nweb/nweb_console_log.h new file mode 100644 index 0000000000000000000000000000000000000000..b0a8d6bbd9f45742167e1d465259186656327dd9 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_console_log.h @@ -0,0 +1,79 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_CONSOLE_LOG_H +#define NWEB_CONSOLE_LOG_H + +#include +#include + +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebConsoleLog { +public: + enum NWebConsoleLogLevel { + DEBUG = 1, + INFO, + WARNING, + ERROR, + UNKNOWN + }; + + NWebConsoleLog(int line_number, + std::string message, + NWebConsoleLogLevel log_level, + std::string sourceId) + : line_number_(line_number), + log_(message), + log_level_(log_level), + sourceId_(sourceId) {} + + ~NWebConsoleLog() = default; + + /** + * @brief Get console log line number + * + * @retval line number + */ + int LineNumer() const { + return line_number_; + } + + /** + * @brief Get console log message + * + * @retval message + */ + const std::string& Log() const { + return log_; + } + + /** + * @brief Get console log message level + * + * @retval message level + */ + NWebConsoleLogLevel LogLevel() const { + return log_level_; + } + + /** + * @brief Get console log source id + * + * @retval source id + */ + const std::string& SourceId() const { + return sourceId_; + } + +private: + int line_number_; + std::string log_; + NWebConsoleLogLevel log_level_; + std::string sourceId_; +}; +} + +#endif // NWEB_CONSOLE_LOG_H \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_cookie_manager.h b/interfaces/innerkits/ohos_nweb/nweb_cookie_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4e2c33aaf974ef67a77a3ee5f68292b2c7be58ba --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_cookie_manager.h @@ -0,0 +1,99 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_COOKIE_MANAGER_H +#define NWEB_COOKIE_MANAGER_H + +#include +#include + +#include "nweb_export.h" +#include "nweb_value_callback.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebCookieManager { +public: + NWebCookieManager() = default; + + virtual ~NWebCookieManager() = default; + + /** + * @brief Gets the singleton NWebCookieManager instance. + * + * @return the singleton NWebCookieManager instance. + */ + static NWebCookieManager* GetInstance(); + + /** + * @brief Get whether the instance can send and accept cookies. + * + * @return true if the instance send and accept cookies. + */ + virtual bool IsAcceptCookieAllowed() const = 0; + /** + * @brief Sets whether the instance should send and accept cookies. + * By default this is set to true and the nweb accepts cookies. + * + * @param accept whether the instance should send and accept cookies. + */ + virtual void PutAcceptCookieEnabled(bool accept) = 0; + /** + * @brief Get whether instances can send and accept cookies for file scheme URLs. + * + * @return true if instances send and accept cookies for file scheme URLs. + */ + virtual bool IsFileURLSchemeCookiesAllowed() const = 0; + /** + * @brief Sets whether the instance should send and accept cookies for file scheme URLs. + * + * @param allow whether the instance should send and accept cookies for file scheme URLs. + */ + virtual void PutAcceptFileURLSchemeCookiesEnabled(bool allow) = 0; + /** + * @brief Gets all the cookies for the given URL. + * + * @param url the URL for which the cookies are requested. + * @param callback a callback which is executed when the cookies have been gotten. + */ + virtual void ReturnCookie(const std::string &url, + std::shared_ptr> callback) = 0; + /** + * @brief GSets a single cookie (key-value pair) for the given URL. + * + * @param url the URL for which the cookie is to be set. + * @param value the cookie as a string, using the format of the 'Set-Cookie' HTTP response header. + * @param callback a callback to be executed when the cookie has been set. + */ + virtual void SetCookie(const std::string &url, + const std::string &value, + std::shared_ptr> callback) = 0; + /** + * @brief Gets whether there are stored cookies. + * + * @param callback a callback to be executed when the cookie has checked. + */ + virtual void ExistCookies(std::shared_ptr> callback) = 0; + /** + * @brief Ensures all cookies currently accessible through the ReturnCookie API are written to + * persistent storage. + * + * @param callback a callback to be executed when cookies has Stored. + */ + virtual void Store(std::shared_ptr> callback) = 0; + /** + * @brief Removes all session cookies, which are cookies without an expiration date. + * + * @param callback a callback to be executed when all session cookies has removed. + */ + virtual void DeleteSessionCookies(std::shared_ptr> callback) = 0; + /** + * @brief Removes all cookies. + * + * @param callback a callback to be executed when all cookies has removed. + */ + virtual void DeleteCookieEntirely(std::shared_ptr> callback) = 0; +}; +} + +#endif // NWebCookieManager \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_download_callback.h b/interfaces/innerkits/ohos_nweb/nweb_download_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5ce16d93b431868aa4a4b8c3f13bc76b65c47d1c --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_download_callback.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_DOWNLOAD_CALLBACK_H +#define NWEB_DOWNLOAD_CALLBACK_H + +#include + +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebDownloadCallback { +public: + NWebDownloadCallback() = default; + + virtual ~NWebDownloadCallback() = default; + /** + * @brief Notify the host application that a file should be downloaded + * + * @param url The full url to the content that should be downloaded. + * @param userAgent The user agent to be used for the download. + * @param contentDisposition Content-disposition http header, if present. + * @param mimetype The mimetype of the content reported by the server. + * @param contentLength The file size reported by the server. + */ + virtual void OnDownloadStart(const std::string& url, + const std::string& userAgent, + const std::string& contentDisposition, + const std::string& mimetype, + long contentLength) = 0; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_DOWNLOAD_CALLBACK_H \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_export.h b/interfaces/innerkits/ohos_nweb/nweb_export.h new file mode 100644 index 0000000000000000000000000000000000000000..e4ebd385d7254c43d1d26d02bf3208fb8246727e --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_export.h @@ -0,0 +1,18 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef OHOS_NWEB_EXPORT_H +#define OHOS_NWEB_EXPORT_H + +#if defined(OHOS_NWEB) + +#define OHOS_NWEB_EXPORT __attribute__((visibility("default"))) + +#else + +#define OHOS_NWEB_EXPORT + +#endif + +#endif // OHOS_NWEB_EXPORT_H diff --git a/interfaces/innerkits/ohos_nweb/nweb_geolocation_callback_interface.h b/interfaces/innerkits/ohos_nweb/nweb_geolocation_callback_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..5fe586d606ddbbe327047f3cf089679ad255c4d3 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_geolocation_callback_interface.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_GEOLOCATION_CALLBACK_INTERFACE_H +#define NWEB_GEOLOCATION_CALLBACK_INTERFACE_H + +#include + +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebGeolocationCallbackInterface { +public: + NWebGeolocationCallbackInterface() = default; + + virtual ~NWebGeolocationCallbackInterface() = default; + /** + * @brief Report the geolocation permission status from usrs. + * + * @param origin The origin that ask for the geolocation permission. + * @param allow The geolocation permission status. + * @param retain Whether to allow the geolocation permission status to be + * saved to the system. + */ + virtual void GeolocationCallbackInvoke(const std::string& origin, + bool allow, + bool retain) = 0; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_GEOLOCATION_CALLBACK_INTERFACE_H diff --git a/interfaces/innerkits/ohos_nweb/nweb_handler.h b/interfaces/innerkits/ohos_nweb/nweb_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..ce72bc958026af7620d0825b51ab5c468042114c --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_handler.h @@ -0,0 +1,307 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_HANDLER_H +#define NWEB_HANDLER_H + +#include +#include +#include +#include + +#include "nweb_access_request.h" +#include "nweb.h" +#include "nweb_console_log.h" +#include "nweb_geolocation_callback_interface.h" +#include "nweb_js_dialog_result.h" +#include "nweb_url_resource_error.h" +#include "nweb_url_resource_request.h" +#include "nweb_url_resource_response.h" + +namespace OHOS::NWeb { +/** + * @brief Describes how pixel bits encoder color data. + */ +enum class ImageColorType { + // Unknown color type. + COLOR_TYPE_UNKNOWN = -1, + + // RGBA with 8 bits per pixel (32bits total). + COLOR_TYPE_RGBA_8888 = 0, + + // BGRA with 8 bits per pixel (32bits total). + COLOR_TYPE_BGRA_8888 = 1, +}; + +/** + * @brief Describes how to interpret the alpha value of a pixel. + */ +enum class ImageAlphaType { + // Unknown alpha type. + ALPHA_TYPE_UNKNOWN = -1, + + // No transparency. The alpha component is ignored. + ALPHA_TYPE_OPAQUE = 0, + + // Transparency with pre-multiplied alpha component. + ALPHA_TYPE_PREMULTIPLIED = 1, + + // Transparency with post-multiplied alpha component. + ALPHA_TYPE_POSTMULTIPLIED = 2, +}; + +class OHOS_NWEB_EXPORT NWebHandler { +public: + NWebHandler() = default; + + virtual ~NWebHandler() = default; + + virtual void SetNWeb(std::shared_ptr nweb) {} + + virtual void OnProxyDied() {} + + virtual void OnRouterPush(const std::string& param) {} + + virtual void OnMessage(const std::string& param) {} + + /** + * @brief Notify the SDK that a web site has finished loading. This method is + * called only for main frame. + * + * @param httpStatusCode The status code for the http request. + * @param url The url of the web site. + */ + virtual void OnPageLoadEnd(int httpStatusCode, const std::string& url) {} + + /** + * @brief Notify the SDK that a web site has started loading. This method is + * called once for each main frame load. + * + * @param url The url to be loaded. + */ + virtual void OnPageLoadBegin(const std::string& url) {} + + /** + * @brief Report a load error to the SDK. + * + * @param errorCode The error code. + * @param description The error description. + * @param failingUrl The failed url. + */ + virtual void OnPageLoadError(int errorCode, + const std::string& description, + const std::string& failingUrl) {} + + /** + * @brief Give the SDK a chance to decide wheather to continue loading the + * url. + * + * @param url The url to be loaded. + * @return true to cancel the loading, false to continue the loading. + */ + virtual bool OnHandleInterceptUrlLoading(const std::string& url) { + return false; + } + + /** + * @brief Notify the SDK that the nweb will load the resource specified by + * the given url. + * + * @param url The url of the resource. + */ + virtual void OnResource(const std::string& url) {} + + /** + * @brief Notify the SDK of the changed document title. + * + * @param title The document title. + */ + virtual void OnPageTitle(const std::string& title) {} + + /** + * @brief Notify the SDK the current progress of loading a web site. + * + * @param newProgress Loading progress, an integer between 0 and 100. + */ + virtual void OnLoadingProgress(int newProgress) {} + + /** + * @brief Request display and focus for a new nweb. + * + */ + virtual void OnFocus() {} + + /** + * @brief Obtains a list of all visited history items, used for link coloring + * + * @retval visited history + */ + virtual const std::vector VisitedUrlHistory() { + return std::vector(); + } + + /** + * @brief Notify the host application of a resource request and allow the + * application to return the data. + * + * @param request the resource response's MIME type, for example { + * "text/html"}. + * + * @retval if NWebUrlResourceResponse is null ,No interception. + */ + virtual std::shared_ptr OnHandleInterceptRequest( + std::shared_ptr request) { + return nullptr; + } + + /** + * @brief Report web resource loading error to the SDK. These errors usually + * indicate inability to connect to the server. + * + * @param request The request information. + * @param error The error information. + */ + virtual void OnResourceLoadError(std::shared_ptr request, + std::shared_ptr error) {} + + /** + * @brief Notify the SDK that an HTTP error has been received from the server + * while loading a resource. + * + * @param request The request information. + * @param errorResponse The error occurred. + */ + virtual void OnHttpError(std::shared_ptr request, + std::shared_ptr errorResponse) {} + + /** + * @brief Notify the SDK of a new favicon for the current web site. + * + * @param data The raw image data for the icon. + * @param width The width of the icon in pixel. + * @param height The height of the icon in pixel. + * @param color_type The color data encoding type. + * @param alpha_type The alpha value of any pixel. + */ + virtual void OnPageIcon(const void* data, + size_t width, + size_t height, + ImageColorType color_type, + ImageAlphaType alpha_type) {} + + /** + * @brief Notify the SDK of the url for an touch icon. + * + * @param icon_url The icon url. + * @param precomposed The touch icon type. + */ + virtual void OnDesktopIconUrl(const std::string& icon_url, bool precomposed) { + } + + /** + * @brief Report a JavaScript console message to the host application. + * + * @param message Details of the console message. + * @return Return true to stop the message from being output to the console. + */ + virtual bool OnConsoleLog(const NWebConsoleLog& message) { return false; } + + /** + * @brief Show prompt to ask for the geolocation permission. + * + * @param origin String: the origin of the resource to get geolocation + * @param callback GeolocationCallbackInterface: callback to report + * geolocation + */ + virtual void OnGeolocationShow(const std::string& origin, + NWebGeolocationCallbackInterface* callback) {} + + /** + * @brief Notify the host application that the web page wants to display a + * JavaScript alert() dialog. + * + * @param url String: The url of the page requesting the dialog. + * @param message String: The message of the dialog. + * @param result std::shared_ptr: A NWebJSDialogResult to + * confirm that the user closed the window. + * @return To show a custom dialog, the app should return true. + */ + virtual bool OnAlertDialogByJS(const std::string& url, + const std::string& message, + std::shared_ptr result) { + return false; + } + + /** + * @brief Notify the host application that the web page wants to handle + * JavaScript onbeforeunload. + * + * @param url String: The url of the page requesting. + * @param message String: The message of the dialog. + * @param result std::shared_ptr: A NWebJSDialogResult to + * confirm that the user closed the window. + * @return To show a custom dialog, the app should return true. + */ + virtual bool OnBeforeUnloadByJS(const std::string& url, + const std::string& message, + std::shared_ptr result) { + return false; + } + + /** + * @brief Notify the host application that the web page wants to display a + * JavaScript prompt() dialog. + * + * @param url String: The url of the page requesting the dialog. + * @param message String: The message of the dialog. + * @param defaultValue String: The default value of the input message. + * @param result std::shared_ptr: A NWebJSDialogResult to + * confirm that the user closed the window. + * @return To show a custom dialog, the app should return true. + */ + virtual bool OnPromptDialogByJs(const std::string& url, + const std::string& message, + const std::string& defaultValue, + std::shared_ptr result) { + return false; + } + + /** + * @brief Notify the host application that the web page wants to display a + * JavaScript Confirm() dialog. + * + * @param url String: The url of the page requesting the dialog. + * @param message String: The message of the dialog. + * @param result std::shared_ptr: A NWebJSDialogResult to + * confirm that the user closed the window. + * @return To show a custom dialog, the app should return true. + */ + virtual bool OnConfirmDialogByJS(const std::string& url, + const std::string& message, + std::shared_ptr result) { + return false; + } + + /** + * @brief Hide prompt to ask for the geolocation permission. + */ + virtual void OnGeolocationHide() {} + + /** + * @brief + * + * @param request String: + */ + virtual void OnPermissionRequest(std::shared_ptr request) {} + + /** + * @brief + * + * @param request String: + */ + virtual void OnPermissionRequestCanceled(std::shared_ptr request) {} +}; +} // namespace OHOS::NWeb + +#endif // NWEB_HANDLER_H diff --git a/interfaces/innerkits/ohos_nweb/nweb_helper.h b/interfaces/innerkits/ohos_nweb/nweb_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..091b419553ee141b2d4f01dd4e981627ac13c0db --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_helper.h @@ -0,0 +1,43 @@ +/* + * 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_HELPER_H +#define NWEB_HELPER_H + +#include +#include +#include "nweb.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebHelper { +public: + static NWebHelper &Instance(); + ~NWebHelper(); + bool Init(); + + std::shared_ptr CreateNWeb(const NWebCreateInfo &create_info); + +private: + NWebHelper() = default; + bool LoadLib(); + void UnloadLib(); + +private: + void *libHandleNWebAdapter_ = nullptr; + void *libHandleWebEngine_ = nullptr; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_HELPER_H diff --git a/interfaces/innerkits/ohos_nweb/nweb_hit_testresult.h b/interfaces/innerkits/ohos_nweb/nweb_hit_testresult.h new file mode 100644 index 0000000000000000000000000000000000000000..510e47128034fb3b57e2d2e77af2a1efc933b861 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_hit_testresult.h @@ -0,0 +1,81 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef WEB_HIT_TESTRESULT_H +#define WEB_HIT_TESTRESULT_H + +#include + +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT HitTestResult { +public: + HitTestResult() { + type_ = UNKNOWN_TYPE; + } + virtual ~HitTestResult() = default; + /** + * Default HitTestResult, where the target is unknown. + */ + static const int UNKNOWN_TYPE = 0; + /** + * This type is no longer used. + */ + static const int ANCHOR_TYPE = 1; + /** + * HitTestResult for hitting a phone number. + */ + static const int PHONE_TYPE = 2; + /** + * HitTestResult for hitting a map address. + */ + static const int GEO_TYPE = 3; + /** + * HitTestResult for hitting an email address. + */ + static const int EMAIL_TYPE = 4; + /** + * HitTestResult for hitting an HTML::img tag. + */ + static const int IMAGE_TYPE = 5; + /** + * This type is no longer used. + */ + static const int IMAGE_ANCHOR_TYPE = 6; + /** + * HitTestResult for hitting a HTML::a tag with src=http. + */ + static const int SRC_ANCHOR_TYPE = 7; + /** + * HitTestResult for hitting a HTML::a tag with src=http + HTML::img. + */ + static const int SRC_IMAGE_ANCHOR_TYPE = 8; + /** + * HitTestResult for hitting an edit text area. + */ + static const int EDIT_TEXT_TYPE = 9; + + void SetType(int type) { + type_ = type; + } + + void SetExtra(std::string extra) { + extra_ = extra; + } + + int GetType() { + return type_; + } + + std::string GetExtra() { + return extra_; + } +private: + int type_; + std::string extra_; +}; +} + +#endif // WEB_HIT_TESTRESULT_H diff --git a/interfaces/innerkits/ohos_nweb/nweb_javascript_result_callback.h b/interfaces/innerkits/ohos_nweb/nweb_javascript_result_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..2faeb6495db718ec4ca76034de4b56d86132c51c --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_javascript_result_callback.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_JAVASCRIPT_RESULT_CALLBACK_H +#define NWEB_JAVASCRIPT_RESULT_CALLBACK_H + +#include +#include +#include "nweb_export.h" +#include "nweb_value.h" + +namespace OHOS::NWeb { + class OHOS_NWEB_EXPORT NWebJavaScriptResultCallBack { + public: + NWebJavaScriptResultCallBack() = default; + + virtual ~NWebJavaScriptResultCallBack() = default; + + virtual std::shared_ptr GetJavaScriptResult( + std::vector> args, + const std::string &method, + const std::string &object_name) = 0; + }; +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_js_dialog_result.h b/interfaces/innerkits/ohos_nweb/nweb_js_dialog_result.h new file mode 100644 index 0000000000000000000000000000000000000000..693a050f4aeb0aa2f3f08d08a537debde57eca93 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_js_dialog_result.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_JS_DISLOG_RESULT_H +#define NWEB_JS_DISLOG_RESULT_H + +#include +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebJSDialogResult { +public: + virtual ~NWebJSDialogResult() = default; + /** + * @brief Handle a confirmation response from the user. + */ + virtual void Confirm() = 0; + /** + * @brief Handle a confirmation response from the user with input message. + * + * @param message confirm message. + */ + virtual void Confirm(const std::string &message) = 0; + /** + * @brief Handle the result if the user cancelled the dialog. + */ + virtual void Cancel() = 0; +}; +} + +#endif \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_preference.h b/interfaces/innerkits/ohos_nweb/nweb_preference.h new file mode 100644 index 0000000000000000000000000000000000000000..cd9f3b430a6594708275ac704fd88078080d05c5 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_preference.h @@ -0,0 +1,78 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_PREFERENCE_H +#define NWEB_PREFERENCE_H + +#include +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebPreference { +public: + NWebPreference() = default; + virtual ~NWebPreference() = default; + enum AccessMode { ALWAYS_ALLOW = 0, NEVER_ALLOW = 1, COMPATIBILITY_MODE = 2 }; + /* synchronous set NWebPreference and web preferences */ + virtual void PutEnableContentAccess(bool flag) = 0; + virtual void PutEnableRawFileAccess(bool flag) = 0; + virtual void PutEnableRawFileAccessFromFileURLs(bool flag) = 0; + virtual void PutEnableUniversalAccessFromFileURLs(bool flag) = 0; + virtual void PutLoadImageFromNetworkDisabled(bool flag) = 0; + virtual void PutCursiveFontFamilyName(std::string font) = 0; + virtual void PutDatabaseAllowed(bool flag) = 0; + virtual void PutDefaultFixedFontSize(int size) = 0; + virtual void PutDefaultFontSize(int size) = 0; + virtual void PutDefaultTextEncodingFormat(std::string encoding) = 0; + virtual void PutDomStorageEnabled(bool flag) = 0; + virtual void PutFantasyFontFamilyName(std::string font) = 0; + virtual void PutFixedFontFamilyName(std::string font) = 0; + virtual void PutDarkModeEnabled(int forceDark) = 0; + virtual void PutIsCreateWindowsByJavaScriptAllowed(bool flag) = 0; + virtual void PutJavaScriptEnabled(bool flag) = 0; + virtual void PutImageLoadingAllowed(bool flag) = 0; + virtual void PutFontSizeLowerLimit(int size) = 0; + virtual void PutLogicalFontSizeLowerLimit(int size) = 0; + virtual void PutSansSerifFontFamilyName(std::string font) = 0; + virtual void PutSerifFontFamilyName(std::string font) = 0; + virtual void PutStandardFontFamilyName(std::string font) = 0; + virtual void PutUserAgent(std::string ua) = 0; + virtual void PutZoomingForTextFactor(int textZoom) = 0; + virtual void PutGeolocationAllowed(bool flag) = 0; + virtual void PutAccessModeForSecureOriginLoadFromInsecure( + AccessMode mode) = 0; + virtual void PutZoomingFunctionEnabled(bool flag) = 0; + + /* get methods */ + virtual bool EnableContentAccess() = 0; + virtual bool EnableRawFileAccess() = 0; + virtual bool EnableRawFileAccessFromFileURLs() = 0; + virtual bool EnableUniversalAccessFromFileURLs() = 0; + virtual bool IsLoadImageFromNetworkDisabled() = 0; + virtual std::string CursiveFontFamilyName() = 0; + virtual bool IsDataBaseEnabled() = 0; + virtual int DefaultFixedFontSize() = 0; + virtual int DefaultFontSize() = 0; + virtual std::string DefaultTextEncodingFormat() = 0; + virtual std::string DefaultUserAgent() = 0; + virtual bool IsDomStorageEnabled() = 0; + virtual std::string FantasyFontFamilyName() = 0; + virtual std::string FixedFontFamilyName() = 0; + virtual int DarkModeEnabled() = 0; + virtual bool IsCreateWindowsByJavaScriptAllowed() = 0; + virtual bool IsJavaScriptAllowed() = 0; + virtual bool IsImageLoadingAllowed() = 0; + virtual int FontSizeLowerLimit() = 0; + virtual int LogicalFontSizeLowerLimit() = 0; + virtual std::string SansSerifFontFamilyName() = 0; + virtual std::string SerifFontFamilyName() = 0; + virtual std::string StandardFontFamilyName() = 0; + virtual std::string UserAgent() = 0; + virtual int ZoomingForTextFactor() = 0; + virtual bool GeolocationAllowed() = 0; + virtual int AccessModeForSecureOriginLoadFromInsecure() = 0; + virtual bool ZoomingfunctionEnabled() = 0; +}; +} // namespace OHOS::NWeb +#endif // NWEB_PREFERENCE_H diff --git a/interfaces/innerkits/ohos_nweb/nweb_url_resource_error.h b/interfaces/innerkits/ohos_nweb/nweb_url_resource_error.h new file mode 100644 index 0000000000000000000000000000000000000000..dafc31299459ba2e8cf3068dfcb80f2b367a32b1 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_url_resource_error.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_URL_RESOURCE_ERROR_H +#define NWEB_URL_RESOURCE_ERROR_H + +#include + +#include "nweb_export.h" +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebUrlResourceError { +public: + NWebUrlResourceError() = default; + + virtual ~NWebUrlResourceError() = default; + + /** + * @brief Gets the error description. + * + * @brief Gets the ErrorInfo. + * + * @return The description of the error. + */ + virtual const std::string &ErrorInfo() const = 0; + + /** + * @brief Get the Error Code. + * + * @return The error code. + */ + virtual int ErrorCode() const = 0; +}; +} + +#endif // NWEB_URL_RESOURCE_ERROR_H \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_url_resource_request.h b/interfaces/innerkits/ohos_nweb/nweb_url_resource_request.h new file mode 100644 index 0000000000000000000000000000000000000000..48e91d03ec7683d42e3d9129446a3b805603acc1 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_url_resource_request.h @@ -0,0 +1,64 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#ifndef NWEB_URL_RESOURCE_REQUEST_H +#define NWEB_URL_RESOURCE_REQUEST_H +#include +#include + +#include "nweb_export.h" + +namespace OHOS::NWeb { +class OHOS_NWEB_EXPORT NWebUrlResourceRequest { +public: + NWebUrlResourceRequest() = default; + + virtual ~NWebUrlResourceRequest() = default; + + /** + * @brief Gets the method associated with the request, for example "GET". + * + * @retval method the method associated with the request. + */ + virtual const std::string &Method() = 0; + + /** + * @brief Gets the headers associated with the request. + * + * @retval the headers associated with the request. + */ + virtual const std::map &RequestHeaders() = 0; + + /** + * @brief Gets the URL for which the resource request was made. + * + * @retval URL url string + */ + virtual const std::string &Url() = 0; + + /** + * @brief Gets whether a gesture (such as a click) was associated with the + * request. + * + * @retval gesture + */ + virtual bool FromGesture() = 0; + + /** + * @brief Gets whether the request was made in order to fetch the main frame's + * document. + * + * @retval Is main frame + */ + virtual bool IsAboutMainFrame() = 0; + + /** + * @brief Gets whether the request was a result of a server-side redirect. + * + * @retval is redirect + */ + virtual bool IsRequestRedirect() = 0; +}; +} + +#endif \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_url_resource_response.h b/interfaces/innerkits/ohos_nweb/nweb_url_resource_response.h new file mode 100644 index 0000000000000000000000000000000000000000..0efc5cd930c0893f383760dd9cce8a071809c1ba --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_url_resource_response.h @@ -0,0 +1,174 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_URL_RESOURCE_RESPONSE_H +#define NWEB_URL_RESOURCE_RESPONSE_H + +#include +#include + +namespace OHOS::NWeb { +class NWebUrlResourceResponse { +public: + /** + * @brief Constructs a resource response with the given parameters. + * + * @param mime_type the resource response's MIME type, for example { + * "text/html"}. + * @param encoding the resource response's character encoding, for example + * {"utf-8"}. + * @param status_code the status code needs to be in the ranges [100, 299], + * [400, 599]. Causing a redirect by specifying a 3xx code is not supported. + * @param reason_phrase the phrase describing the status code, for example + * "OK". Must be non-empty. + * @param request_headers the resource response's headers represented as a + * mapping of header name -> header value. + * @param input_stream the input stream that provides the resource response's + * data. + */ + NWebUrlResourceResponse(const std::string& mime_type, + const std::string& encoding, + const int status_code, + const std::string& reason_phrase, + const std::map& request_headers, + std::string& input_stream) + : mime_type_(mime_type), + encoding_(encoding), + status_code_(status_code), + reason_phrase_(reason_phrase), + request_headers_(request_headers), + input_stream_(input_stream) {} + + NWebUrlResourceResponse(const std::string& mime_type, + const std::string& encoding, + std::string& input_stream) + : mime_type_(mime_type), + encoding_(encoding), + input_stream_(input_stream) {} + + ~NWebUrlResourceResponse() = default; + + /** + * @brief get input stream + * + * @retval inputstream string + */ + const std::string& ResponseData() + { + return input_stream_; + } + + /** + * @brief set input stream + * + * @param input_stream set inputstream for example: fread(buf, 1, sizeof(buf), + * file) + */ + void PutResponseData(std::string& input_stream) + { + input_stream_ = input_stream; + } + + /** + * @brief Constructs a resource response with the given parameters. + * + * @param encoding encoding { "utf-8" } + */ + void PutResponseEncoding(const std::string& encoding) + { + encoding_ = encoding; + } + + /** + * @brief get encoding + * + * @retval encoding the resource response's encoding + */ + std::string ResponseEncoding() + { + return encoding_; + } + + /** + * @brief Constructs a resource response with the given parameters. + * + * @param mime_type mime_type{ "text/html" } + */ + void PutResponseMimeType(const std::string& mime_type) + { + mime_type_ = mime_type; + } + + /** + * @brief get mimetype + * + * @retval mimetype The resource response's MIME type + */ + std::string ResponseMimeType() + { + return mime_type_; + } + + /** + * @brief Set ResponseHeaders + * + * @param request_headers request header + */ + void PutResponseHeaders(const std::map& request_headers) + { + request_headers_ = request_headers; + } + + /** + * @brief Get ResponseHeaders + * + * @retval request headers + */ + const std::map& ResponseHeaders() + { + return request_headers_; + } + + /** + * @brief Set StatusCode And ReasonPhrase + * + * @param status_code status code + * @param reasonphrase reason phrase + */ + void PutResponseStateAndStatuscode(int status_code, + std::string reason_phrase) + { + status_code_ = status_code; + reason_phrase_ = reason_phrase; + } + + /** + * @brief get status code + * + * @retval status code + */ + int ResponseStatusCode() + { + return status_code_; + } + + /** + * @brief Get ReasonPhrase + * + * @retval errorcode reason + */ + std::string ResponseStatus() + { + return reason_phrase_; + } +private: + std::string mime_type_; + std::string encoding_; + int status_code_ = 200; + std::string reason_phrase_; + std::map request_headers_; + std::string& input_stream_; +}; +} +#endif \ No newline at end of file diff --git a/interfaces/innerkits/ohos_nweb/nweb_value.h b/interfaces/innerkits/ohos_nweb/nweb_value.h new file mode 100644 index 0000000000000000000000000000000000000000..e08d162fe97984e0d45b30e4269737fa03f2a048 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_value.h @@ -0,0 +1,70 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_VALUE_H_ +#define NWEB_VALUE_H_ + +#include +#include +#include "nweb_export.h" + +namespace OHOS::NWeb { + union data_union { + int n; + double f; + bool b; + }; + +class OHOS_NWEB_EXPORT NWebValue { +public: + enum class Type : unsigned char { + NONE = 0, + BOOLEAN, + INTEGER, + DOUBLE, + STRING, + BINARY, + DICTIONARY, + LIST + }; + + NWebValue(Type type) : type_(type) {} + + ~NWebValue() = default; + + bool GetBoolean() { return data_.b; } + + void SetBoolean(bool b) { data_.b = b; } + + void SetString(std::string str) { str_ = str; } + + std::string GetString() { return str_; } + + void SetDouble(double dou) { data_.f = dou; } + + double GetDouble() { return data_.f; } + + void SetInt(int num) { data_.n = num; } + + int GetInt() { return data_.n; } + + void SetJsonString(std::string json_string) { str_json_ = json_string; } + + std::string GetJsonString() { return str_json_; } + + Type GetType() { return type_; } + + void SetType(Type type) { type_ = type; } + + int error_ = 0; + +private: + Type type_ = Type::NONE; + data_union data_; + std::string str_; + std::string str_json_; +}; +} + +#endif // NWEB_VALUE_H_ diff --git a/interfaces/innerkits/ohos_nweb/nweb_value_callback.h b/interfaces/innerkits/ohos_nweb/nweb_value_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..4f521b423282c343c5c54aece900fd8de6297856 --- /dev/null +++ b/interfaces/innerkits/ohos_nweb/nweb_value_callback.h @@ -0,0 +1,22 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef VALUE_CALLBACK_H +#define VALUE_CALLBACK_H + +#include "nweb_export.h" + +namespace OHOS::NWeb { +template +class OHOS_NWEB_EXPORT NWebValueCallback { +public: + NWebValueCallback() = default; + + virtual ~NWebValueCallback() = default; + + virtual void OnReceiveValue(T value) = 0; +}; +} + +#endif // NWebValueCallback \ No newline at end of file diff --git a/ohos_nweb/BUILD.gn b/ohos_nweb/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a7d21c529fd8af39b795b7c74db0b1663a96b59b --- /dev/null +++ b/ohos_nweb/BUILD.gn @@ -0,0 +1,67 @@ +# 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. + +import("//build/ohos.gni") + +config("nweb_config") { + include_dirs = [ + "include", + "//base/web/webview/interfaces/innerkits/ohos_nweb", + "//utils/native/base/include", + "//foundation/windowmanager/interfaces/innerkits/wm", + "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", + "//foundation/graphic/standard/frameworks/surface/include", + "//foundation/graphic/standard/interfaces/innerkits/surface", + ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + ] +} + +ohos_shared_library("libnweb") { + configs = [ ":nweb_config" ] + + sources = [ + "src/nweb_window_adapter.cpp", + "src/nweb_surface_adapter.cpp", + "src/nweb_input_event_consumer.cpp", + "src/nweb_helper.cpp", + ] + + public_deps = [ + "//foundation/graphic/standard:libvsync_client", + "//foundation/graphic/standard:libsurface", + "//foundation/graphic/standard/rosen/modules/render_service_client:librender_service_client", + "//foundation/windowmanager/wm:libwm", + ] + + external_deps = [ + "multimodalinput_base:libmmi-client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + part_name = "webview" + subsystem_name = "web" +} + +ohos_prebuilt_etc("nweb_hap") { + source = "prebuilts/arm/NWeb.hap" + module_install_dir = "app" + part_name = "webview" + subsystem_name = "web" +} diff --git a/ohos_nweb/include/nweb_adapter_common.h b/ohos_nweb/include/nweb_adapter_common.h new file mode 100644 index 0000000000000000000000000000000000000000..511865a02622dce0676d92ea78197ab6750da7b0 --- /dev/null +++ b/ohos_nweb/include/nweb_adapter_common.h @@ -0,0 +1,24 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_ADAPTER_COMMON_H +#define NWEB_ADAPTER_COMMON_H + +#include +#include +#include "nweb.h" + +namespace OHOS::NWeb { +struct NWebWindowInfo { + uint32_t width = 0; + uint32_t height = 0; + sptr cachedSurfaceBuffer = nullptr; +}; + +struct VsyncCbInfo { + std::weak_ptr nwebWeak; +}; +} // namespace OHOS + +#endif // NWEB_ADAPTER_COMMON_H \ No newline at end of file diff --git a/ohos_nweb/include/nweb_input_event_consumer.h b/ohos_nweb/include/nweb_input_event_consumer.h new file mode 100644 index 0000000000000000000000000000000000000000..0c29562b5c4a0caa5829b67a5166f7f16222dea4 --- /dev/null +++ b/ohos_nweb/include/nweb_input_event_consumer.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_INPUT_EVENT_CONSUMER_H +#define NWEB_INPUT_EVENT_CONSUMER_H + +#include +#include "i_input_event_consumer.h" +#include "nweb.h" + +namespace OHOS::NWeb { +class NWebInputEventConsumer : public MMI::IInputEventConsumer { +public: + explicit NWebInputEventConsumer(std::shared_ptr nweb); + void OnInputEvent(std::shared_ptr pointerEvent) const override; + void OnInputEvent(std::shared_ptr keyEvent) const override; + void OnInputEvent(std::shared_ptr axisEvent) const override {} + +private: + void DispatchPointerEvent(std::shared_ptr pointerEvent) const; + void DispatchKeyEvent(std::shared_ptr keyEvent) const; + +private: + std::weak_ptr nwebweak_; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_INPUT_EVENT_CONSUMER_H \ No newline at end of file diff --git a/ohos_nweb/include/nweb_log.h b/ohos_nweb/include/nweb_log.h new file mode 100644 index 0000000000000000000000000000000000000000..ddeeae5bef28042907df4b34947135f392eee724 --- /dev/null +++ b/ohos_nweb/include/nweb_log.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_HILOG_H +#define NWEB_HILOG_H + +#include +#include + +namespace OHOS { +constexpr HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0, "NWEB" }; + +#define FUNC_LINE_FMT " %{public}s<%{public}d>: " + +#define WVLOG_D(fmt, ...) \ + HiviewDFX::HiLog::Debug(LOG_LABEL, FUNC_LINE_FMT fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define WVLOG_I(fmt, ...) \ + HiviewDFX::HiLog::Info(LOG_LABEL, FUNC_LINE_FMT fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define WVLOG_W(fmt, ...) \ + HiviewDFX::HiLog::Warn(LOG_LABEL, FUNC_LINE_FMT fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define WVLOG_E(fmt, ...) \ + HiviewDFX::HiLog::Error(LOG_LABEL, FUNC_LINE_FMT fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define WVLOG_F(fmt, ...) \ + HiviewDFX::HiLog::Fatal(LOG_LABEL, FUNC_LINE_FMT fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +} // namespace OHOS + +#endif // NWEB_HILOG_H \ No newline at end of file diff --git a/ohos_nweb/include/nweb_surface_adapter.h b/ohos_nweb/include/nweb_surface_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..c01530bf37e0dba50830ae3f0af1f5ecbf6e2956 --- /dev/null +++ b/ohos_nweb/include/nweb_surface_adapter.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_SURFACE_ADAPTER_H +#define NWEB_SURFACE_ADAPTER_H + +#include +#include "nweb_adapter_common.h" + +namespace OHOS { +class Surface; +} + +namespace OHOS::NWeb { +class NWebSurfaceAdapter { +public: + static NWebSurfaceAdapter &Instance(); + NWebCreateInfo GetCreateInfo(sptr surface, + const NWebInitArgs &initArgs, + uint32_t width, + uint32_t height); + +private: + void GetSize(sptr surface, NWebCreateInfo &createInfo, uint32_t width, uint32_t height) const; + void GetRenderInterface(sptr surface, NWebCreateInfo &createInfo); + sptr RequestBuffer(sptr surface, uint32_t width, uint32_t height); + bool CopyFrame(sptr surfaceBuffer, const char *src, uint32_t width, uint32_t height); + bool FlushBuffer(sptr surface, sptr surfaceBuffer, uint32_t width, uint32_t height); +}; +} // namespace OHOS::NWeb + +#endif // NWEB_SURFACE_ADAPTER_H \ No newline at end of file diff --git a/ohos_nweb/include/nweb_window_adapter.h b/ohos_nweb/include/nweb_window_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..d56d8a3e8ee7630677202b4055bd647d08f9749a --- /dev/null +++ b/ohos_nweb/include/nweb_window_adapter.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_WINDOW_ADAPTER_H +#define NWEB_WINDOW_ADAPTER_H + +#include +#include "nweb_adapter_common.h" +#include "window.h" + +namespace OHOS::NWeb { +class NWebWindowAdapter { +public: + static NWebWindowAdapter &Instance(); + NWebCreateInfo GetCreateInfo(Rosen::Window *window, const NWebInitArgs &initArgs); + void RegistEventCb(Rosen::Window *window, std::shared_ptr nweb); + void RequestVsync(Rosen::Window *window, std::shared_ptr nweb); + +private: + void GetSize(Rosen::Window *window, NWebCreateInfo &createInfo); + void GetRenderInterface(Rosen::Window *window, NWebCreateInfo &createInfo); + void VsyncCb(Rosen::Window *window, std::shared_ptr nweb); + +private: + std::unordered_map windowInfoMap_; +}; +} // namespace OHOS + +#endif // NWEB_WINDOW_ADAPTER_H \ No newline at end of file diff --git a/ohos_nweb/src/nweb_helper.cpp b/ohos_nweb/src/nweb_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f22b3ed3e49346cb1b0f81c647044e54ae9dc01 --- /dev/null +++ b/ohos_nweb/src/nweb_helper.cpp @@ -0,0 +1,144 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_helper.h" + +#include +#include +#include +#include "nweb_log.h" +#include "nweb_adapter_helper.h" +#include "nweb_window_adapter.h" +#include "nweb_surface_adapter.h" + +namespace { +const uint32_t NWEB_SURFACE_MAX_WIDTH = 7680; +const uint32_t NWEB_SURFACE_MAX_HEIGHT = 7680; +} + +namespace OHOS::NWeb { +NWebHelper &NWebHelper::Instance() +{ + static NWebHelper helper; + return helper; +} + +bool NWebHelper::LoadLib() +{ + if (libHandleNWebAdapter_ != nullptr && libHandleWebEngine_ != nullptr) { + return true; + } + const std::string LOAD_LIB_DIR = "/data/storage/el1/bundle/nweb/entry/libs/armeabi"; + const std::string LIB_PATH_NWEB_ADAPTER = LOAD_LIB_DIR + "/libnweb_adapter.so"; + const std::string LIB_PATH_WEB_ENGINE = LOAD_LIB_DIR + "/libweb_engine.so"; + void *libHandleWebEngine = ::dlopen(LIB_PATH_WEB_ENGINE.c_str(), RTLD_NOW); + if (libHandleWebEngine == nullptr) { + WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", LIB_PATH_WEB_ENGINE.c_str(), dlerror()); + return false; + } + libHandleWebEngine_ = libHandleWebEngine; + void *libHandleNWebAdapter = ::dlopen(LIB_PATH_NWEB_ADAPTER.c_str(), RTLD_NOW); + if (libHandleNWebAdapter == nullptr) { + WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", LIB_PATH_NWEB_ADAPTER.c_str(), dlerror()); + return false; + } + libHandleNWebAdapter_ = libHandleNWebAdapter; + return true; +} + +void NWebHelper::UnloadLib() +{ + if (libHandleNWebAdapter_ != nullptr) { + ::dlclose(libHandleNWebAdapter_); + libHandleNWebAdapter_ = nullptr; + } + if (libHandleWebEngine_ != nullptr) { + ::dlclose(libHandleWebEngine_); + libHandleWebEngine_ = nullptr; + } +} + +bool NWebHelper::Init() +{ + return LoadLib(); +} + +NWebHelper::~NWebHelper() +{ + UnloadLib(); +} + +using CreateNWebFuncType = NWeb *(*)(const NWebCreateInfo &); +std::shared_ptr NWebHelper::CreateNWeb(const NWebCreateInfo &create_info) +{ + if (libHandleNWebAdapter_ == nullptr) { + return nullptr; + } + + const std::string CREATE_NWEB_FUNC_NAME = "CreateNWeb"; + CreateNWebFuncType funcCreateNWeb = + reinterpret_cast(dlsym(libHandleNWebAdapter_, CREATE_NWEB_FUNC_NAME.c_str())); + if (funcCreateNWeb == nullptr) { + WVLOG_E("fail to dlsym %{public}s from libohoswebview.so", CREATE_NWEB_FUNC_NAME.c_str()); + return nullptr; + } + + std::shared_ptr nweb(funcCreateNWeb(create_info)); + if (nweb == nullptr) { + WVLOG_E("fail to create nweb"); + return nullptr; + } + + return nweb; +} + +NWebAdapterHelper &NWebAdapterHelper::Instance() +{ + static NWebAdapterHelper helper; + return helper; +} + +bool NWebAdapterHelper::Init() +{ + return NWebHelper::Instance().Init(); +} + +std::shared_ptr NWebAdapterHelper::CreateNWeb(Rosen::Window *window, const NWebInitArgs &initArgs) +{ + if (window == nullptr) { + WVLOG_E("fail to create nweb, input window is nullptr"); + return nullptr; + } + auto createInfo = NWebWindowAdapter::Instance().GetCreateInfo(window, initArgs); + auto nweb = NWebHelper::Instance().CreateNWeb(createInfo); + if (nweb == nullptr) { + WVLOG_E("fail to create nweb instance"); + return nullptr; + } + NWebWindowAdapter::Instance().RegistEventCb(window, nweb); + NWebWindowAdapter::Instance().RequestVsync(window, nweb); + return nweb; +} + +std::shared_ptr NWebAdapterHelper::CreateNWeb(sptr surface, + const NWebInitArgs &initArgs, + uint32_t width, + uint32_t height) +{ + if (surface == nullptr) { + WVLOG_E("fail to create nweb, input surface is nullptr"); + return nullptr; + } + if (width > NWEB_SURFACE_MAX_WIDTH || height > NWEB_SURFACE_MAX_HEIGHT) { + WVLOG_E("input size %{public}u*%{public}u is invalid.", width, height); + return nullptr; + } + auto createInfo = NWebSurfaceAdapter::Instance().GetCreateInfo(surface, initArgs, width, height); + auto nweb = NWebHelper::Instance().CreateNWeb(createInfo); + if (nweb == nullptr) { + WVLOG_E("fail to create nweb instance"); + } + return nweb; +} +} // namespace OHOS::NWeb diff --git a/ohos_nweb/src/nweb_input_event_consumer.cpp b/ohos_nweb/src/nweb_input_event_consumer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..558b47dec26183b314417935a6b67fa7079924c3 --- /dev/null +++ b/ohos_nweb/src/nweb_input_event_consumer.cpp @@ -0,0 +1,88 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_input_event_consumer.h" +#include "nweb_log.h" + +namespace OHOS::NWeb { +NWebInputEventConsumer::NWebInputEventConsumer(std::shared_ptr nweb) + : nwebweak_(nweb) {} + +void NWebInputEventConsumer::OnInputEvent(std::shared_ptr pointerEvent) const +{ + DispatchPointerEvent(pointerEvent); +} + +void NWebInputEventConsumer::OnInputEvent(std::shared_ptr keyEvent) const +{ + DispatchKeyEvent(keyEvent); +} + +void NWebInputEventConsumer::DispatchPointerEvent(std::shared_ptr pointerEvent) const +{ + if (nwebweak_.expired()) { + WVLOG_W("nweb instance has expired"); + return; + } + auto nweb = nwebweak_.lock(); + if (pointerEvent == nullptr) { + WVLOG_E("pointerEvent is invaild."); + return; + } + int32_t pointerID = pointerEvent->GetPointerId(); + MMI::PointerEvent::PointerItem item; + bool ret = pointerEvent->GetPointerItem(pointerID, item); + if (!ret) { + WVLOG_E("get pointer item failed."); + return; + } + int32_t action = pointerEvent->GetPointerAction(); + switch (action) { + case MMI::PointerEvent::POINTER_ACTION_DOWN: { + WVLOG_I("nweb receive pointer touch down event"); + nweb->OnTouchPress(pointerID, item.GetLocalX(), item.GetLocalY()); + break; + } + case MMI::PointerEvent::POINTER_ACTION_UP: { + WVLOG_I("nweb receive pointer touch up event"); + nweb->OnTouchRelease(pointerID); + break; + } + case MMI::PointerEvent::POINTER_ACTION_MOVE: { + WVLOG_I("nweb receive pointer touch move event"); + nweb->OnTouchMove(pointerID, item.GetLocalX(), item.GetLocalY()); + break; + } + case MMI::PointerEvent::POINTER_ACTION_CANCEL: { + WVLOG_I("nweb receive pointer touch cancel event"); + nweb->OnTouchCancel(); + break; + } + default: { + WVLOG_W("unsupported PointerEvent action[%{public}d] received", action); + break; + } + } +} + +void NWebInputEventConsumer::DispatchKeyEvent(std::shared_ptr keyEvent) const +{ + if (nwebweak_.expired()) { + WVLOG_W("nweb instance has expired"); + return; + } + auto nweb = nwebweak_.lock(); + if (keyEvent == nullptr) { + WVLOG_E("keyEvent is invaild."); + return; + } + int32_t keyCode = keyEvent->GetKeyCode(); + if (keyCode == MMI::KeyEvent::KEYCODE_BACK) { + WVLOG_I("nweb receive key back event"); + nweb->OnNavigateBack(); + } else { + WVLOG_W("unsupported KeyEvent code[%{public}d] received", keyCode); + } +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/ohos_nweb/src/nweb_surface_adapter.cpp b/ohos_nweb/src/nweb_surface_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8ea5bb8af359e8dad80ae641fed68b4d6a3a5ce --- /dev/null +++ b/ohos_nweb/src/nweb_surface_adapter.cpp @@ -0,0 +1,163 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_surface_adapter.h" + +#include +#include +#include +#include +#include "nweb_log.h" + +namespace { +constexpr int BITS_PER_PIXEL = 4; +} + +namespace OHOS::NWeb { +NWebSurfaceAdapter &NWebSurfaceAdapter::Instance() +{ + static NWebSurfaceAdapter surfaceAdapter; + return surfaceAdapter; +} + +NWebCreateInfo NWebSurfaceAdapter::GetCreateInfo(sptr surface, + const NWebInitArgs &initArgs, + uint32_t width, + uint32_t height) +{ + NWebCreateInfo createInfo = { + .init_args = initArgs, + }; + if (surface == nullptr) { + return createInfo; + } + GetSize(surface, createInfo, width, height); + GetRenderInterface(surface, createInfo); + return createInfo; +} + +void NWebSurfaceAdapter::GetSize(sptr surface, + NWebCreateInfo &createInfo, + uint32_t width, + uint32_t height) const +{ + if (surface == nullptr) { + return; + } + createInfo.width = (width == 0) ? surface->GetDefaultWidth() : width; + createInfo.height = (height == 0) ? surface->GetDefaultHeight() : height; +} + +void NWebSurfaceAdapter::GetRenderInterface(sptr surface, NWebCreateInfo &createInfo) +{ + wptr surfaceWeak(surface); + createInfo.output_render_frame = [surfaceWeak, this] (const char *buffer, uint32_t width, uint32_t height) -> bool { + sptr surface = surfaceWeak.promote(); + if (surface == nullptr) { + WVLOG_E("surface is nullptr or has expired"); + return false; + } + + sptr surfaceBuffer = this->RequestBuffer(surface, width, height); + if (surfaceBuffer == nullptr) { + return false; + } + + if (!this->CopyFrame(surfaceBuffer, buffer, width, height)) { + surface->CancelBuffer(surfaceBuffer); + return false; + } + + return this->FlushBuffer(surface, surfaceBuffer, width, height); + }; +} + +sptr NWebSurfaceAdapter::RequestBuffer(sptr surface, uint32_t width, uint32_t height) +{ + if (surface == nullptr) { + return nullptr; + } + + BufferRequestConfig config = { + .width = width, + .height = height, + .strideAlignment = sizeof(void *), + .format = PIXEL_FMT_RGBA_8888, + .usage = HBM_USE_CPU_READ | HBM_USE_CPU_WRITE | HBM_USE_MEM_DMA, + .timeout = 0, + }; + + sptr surfaceBuffer = nullptr; + int32_t releaseFence = -1; + SurfaceError ret = surface->RequestBuffer(surfaceBuffer, releaseFence, config); + if (ret != SURFACE_ERROR_OK) { + WVLOG_E("fail to request buffer from surface, errorcode=%{public}d", ret); + return nullptr; + } + + sptr tempFence = new SyncFence(releaseFence); + tempFence->Wait(100); // 100 ms + + return surfaceBuffer; +} + +bool NWebSurfaceAdapter::CopyFrame( + sptr surfaceBuffer, const char *src, uint32_t width, uint32_t height) +{ + if (surfaceBuffer == nullptr) { + return false; + } + + char *dst = reinterpret_cast(surfaceBuffer->GetVirAddr()); + if (dst == nullptr) { + WVLOG_E("fail to get buffer addr"); + return false; + } + + uint32_t srcStride = width * BITS_PER_PIXEL; + uint32_t dstStride = surfaceBuffer->GetStride(); + uint32_t copiedSize = 0; + + for (uint32_t currHeight = 0; currHeight < height; ++currHeight) { + if (copiedSize + dstStride > surfaceBuffer->GetSize()) { + WVLOG_E("copy size overflow, drop this frame(%{public}u*%{public}u)", width, height); + return false; + } + errno_t ret = memcpy_s(dst, static_cast(srcStride), src, static_cast(srcStride)); + if (ret != EOK) { + WVLOG_E("memcpy_s failed"); + return false; + } + src += srcStride; + dst += dstStride; + copiedSize += dstStride; + } + + return true; +} + +bool NWebSurfaceAdapter::FlushBuffer( + sptr surface, sptr surfaceBuffer, uint32_t width, uint32_t height) +{ + if (surface == nullptr) { + return false; + } + + BufferFlushConfig flushConfig = { + .damage = { + .w = width, + .h = height, + }, + .timestamp = 0, + }; + + SurfaceError ret = surface->FlushBuffer(surfaceBuffer, -1, flushConfig); + if (ret != SURFACE_ERROR_OK) { + WVLOG_E("FAIL flush nweb render frame, ret=%{public}d", ret); + return false; + } + + return true; +} +} // namespace OHOS::NWeb diff --git a/ohos_nweb/src/nweb_window_adapter.cpp b/ohos_nweb/src/nweb_window_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bdf9cf5e37fe3f4f983ec2073f6c8b00b7a6c79 --- /dev/null +++ b/ohos_nweb/src/nweb_window_adapter.cpp @@ -0,0 +1,186 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_window_adapter.h" + +#include +#include +#include +#include +#include +#include "nweb_log.h" +#include "nweb_input_event_consumer.h" + +namespace OHOS::NWeb { +// static +NWebWindowAdapter &NWebWindowAdapter::Instance() +{ + static NWebWindowAdapter windowAdapter; + return windowAdapter; +} + +NWebCreateInfo NWebWindowAdapter::GetCreateInfo(Rosen::Window *window, const NWebInitArgs &initArgs) +{ + NWebCreateInfo createInfo = { + .init_args = initArgs, + }; + if (window == nullptr) { + return createInfo; + } + GetSize(window, createInfo); + GetRenderInterface(window, createInfo); + return createInfo; +} + +void NWebWindowAdapter::GetSize(Rosen::Window *window, NWebCreateInfo &createInfo) +{ + createInfo.width = window->GetRect().width_; + createInfo.height = window->GetRect().height_; + windowInfoMap_[window].width = createInfo.width; + windowInfoMap_[window].height = createInfo.height; +} + +void NWebWindowAdapter::GetRenderInterface(Rosen::Window *window, NWebCreateInfo &createInfo) +{ + createInfo.output_render_frame = [window, this] (const char *buffer, uint32_t width, uint32_t height) -> bool { + if (windowInfoMap_[window].cachedSurfaceBuffer != nullptr) { + WVLOG_I("last cached frame is not consumed, skip this frame output"); + return false; + } + + sptr surface = window->GetSurfaceNode()->GetSurface(); + if (surface == nullptr) { + WVLOG_E("surface get from window is nullptr"); + return false; + } + + BufferRequestConfig config = { + .width = window->GetRect().width_, + .height = window->GetRect().height_, + .strideAlignment = sizeof(void *), + .format = PIXEL_FMT_RGBA_8888, + .usage = HBM_USE_CPU_READ | HBM_USE_CPU_WRITE | HBM_USE_MEM_DMA, + .timeout = 0, + }; + + sptr surfaceBuffer; + int32_t releaseFence = -1; + SurfaceError ret = surface->RequestBuffer(surfaceBuffer, releaseFence, config); + if (ret != SURFACE_ERROR_OK) { + WVLOG_E("fail to request buffer from surface, errorcode=%{public}d", ret); + return false; + } + + char *addr = reinterpret_cast(surfaceBuffer->GetVirAddr()); + if (addr == nullptr) { + WVLOG_E("fail to get buffer addr"); + surface->CancelBuffer(surfaceBuffer); + return false; + } + + constexpr uint32_t BITS_PER_PIXEL = 4; + uint32_t frameSize = windowInfoMap_[window].width * windowInfoMap_[window].height * BITS_PER_PIXEL; + if (windowInfoMap_[window].width != window->GetRect().width_ || + windowInfoMap_[window].height != window->GetRect().height_) { + WVLOG_W("nweb output frame size (%{public}u*%{public}u) is different from " + "window surface buffer size (%{public}u*%{public}u)", + windowInfoMap_[window].width, windowInfoMap_[window].height, + window->GetRect().width_, window->GetRect().height_); + uint32_t surfaceBufferSize = window->GetRect().width_ * window->GetRect().height_ * BITS_PER_PIXEL; + if (surfaceBufferSize < frameSize) { + frameSize = surfaceBufferSize; + } + } + if (memcpy_s(addr, frameSize, buffer, frameSize) != EOK) { + WVLOG_E("memcpy_s fail, errorcode=%{public}d", ret); + return false; + } + + windowInfoMap_[window].cachedSurfaceBuffer = surfaceBuffer; + + return true; + }; +} + +void NWebWindowAdapter::RequestVsync(Rosen::Window *window, std::shared_ptr nweb) +{ + if (window == nullptr) { + return; + } + + std::weak_ptr nwebWeak(nweb); + VsyncCbInfo *info = new(std::nothrow) VsyncCbInfo { nwebWeak }; + if (info == nullptr) { + return; + } + FrameCallback frameCb = { + .timestamp_ = 0, + .userdata_ = reinterpret_cast(info), + .callback_ = [window, this] (int64_t time, void *userdata) -> void { + VsyncCbInfo *info = reinterpret_cast(userdata); + std::weak_ptr nwebWeak = info->nwebWeak; + delete info; + info = nullptr; + if (nwebWeak.expired()) { + WVLOG_I("nweb instance has expired, stop request vsync"); + return; + } + this->VsyncCb(window, nwebWeak.lock()); + }, + }; + + VsyncError ret = VsyncHelper::Current()->RequestFrameCallback(frameCb); + if (ret != VSYNC_ERROR_OK) { + WVLOG_E("FAIL to request frame callback for nweb render, ret=%{public}d", ret); + } +} + +void NWebWindowAdapter::VsyncCb(Rosen::Window *window, std::shared_ptr nweb) +{ + if (window == nullptr) { + return; + } + + if (windowInfoMap_[window].cachedSurfaceBuffer == nullptr) { + RequestVsync(window, nweb); + return; + } + + sptr surface = window->GetSurfaceNode()->GetSurface(); + if (surface == nullptr) { + WVLOG_E("surface get from window is nullptr"); + RequestVsync(window, nweb); + return; + } + + BufferFlushConfig flushConfig = { + .damage = { + .w = window->GetRect().width_, + .h = window->GetRect().height_, + }, + .timestamp = 0, + }; + + SurfaceError ret = surface->FlushBuffer(windowInfoMap_[window].cachedSurfaceBuffer, -1, flushConfig); + if (ret == SURFACE_ERROR_OK) { + windowInfoMap_[window].cachedSurfaceBuffer = nullptr; + } else { + WVLOG_E("FAIL flush nweb render frame to window surface, ret=%{public}d", ret); + } + + RequestVsync(window, nweb); +} + +void NWebWindowAdapter::RegistEventCb(Rosen::Window *window, std::shared_ptr nweb) +{ + if (window == nullptr) { + return; + } + + std::shared_ptr inputEventListener = + std::make_shared(nweb); + + window->AddInputEventListener(inputEventListener); +} +} // namespace OHOS::NWeb diff --git a/test/BUILD.gn b/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0a47857391da518b19aed53a09846fa8ed50c4e8 --- /dev/null +++ b/test/BUILD.gn @@ -0,0 +1,64 @@ +# 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. + +import("//build/ohos.gni") + +config("nweb_test_config") { + include_dirs = [ + "ohos_nweb", + "//base/web/webview/interfaces/innerkits/ohos_nweb", + "//foundation/windowmanager/interfaces/innerkits/wm", + "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", + ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + ] +} + +ohos_executable("nweb_test") { + install_enable = false + + sources = [ + "ohos_nweb/ohos_nweb_test.cpp", + "ohos_nweb/nweb_client_impl_test.cpp", + "ohos_nweb/nweb_downloadlistener_impl_test.cpp", + "ohos_nweb/nweb_input_event_consumer_test.cpp", + "ohos_nweb/nweb_javascript_result_callback_test.cpp", + "ohos_nweb/nweb_client_impl_test_for_intercept.cpp", + "ohos_nweb/nweb_js_dialog_impl_test.cpp" + ] + + configs = [ + ":nweb_test_config", + ] + + deps = [ + "//base/web/webview/ohos_nweb:libnweb", + "//third_party/zlib:libz", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/windowmanager/wm:libwm", + ] + + external_deps = [ + "ipc:ipc_core", + "hiviewdfx_hilog_native:libhilog", + "samgr_standard:samgr_proxy", + "multimodalinput_base:libmmi-client", + ] + + part_name = "webview" + subsystem_name = "web" +} diff --git a/test/ohos_nweb/nweb_client_impl_test.cpp b/test/ohos_nweb/nweb_client_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7f1df8a40693e1b38248a154ca6358a00e9a536 --- /dev/null +++ b/test/ohos_nweb/nweb_client_impl_test.cpp @@ -0,0 +1,168 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_client_impl_test.h" + +#include "nweb_test_log.h" +#include +#include +#include "nweb_url_resource_request.h" +#include "nweb_url_resource_response.h" +#include "utils.h" +#include "securec.h" + +namespace OHOS::NWeb { +class JavaScriptResultCb : public NWebValueCallback { + void OnReceiveValue(std::string result) override + { + TESTLOG_I("JavaScript execute result = %{public}s", result.c_str()); + } +}; +void NWebHandlerImplTest::OnProxyDied() +{ + TESTLOG_I("NWebHandlerImplTest::OnProxyDied called"); +} + +void NWebHandlerImplTest::SetNWeb(std::shared_ptr nweb) +{ + nwebweak_ = nweb; +} + +void NWebHandlerImplTest::OnPageLoadEnd(int httpStatusCode, const std::string& url) +{ + TESTLOG_I("NWebHandlerImplTest::OnPageLoadend called, url=%{public}s", url.c_str()); + auto nwebShared = nwebweak_.lock(); + if (nwebShared == nullptr) { + TESTLOG_E("nwebShared is nullptr"); + return; + } + + if (url.find(EXECUTE_JAVASCRIPT_CALLBACK_HTML) != std::string::npos) { + // invoke js function which is defined in html, test case 106 + std::string ss = "javascript:ExecuteJavaScriptTest()"; + std::shared_ptr> callback = std::make_shared(); + nwebShared->ExecuteJavaScript(ss, callback); + } +} + +void NWebHandlerImplTest::OnPageLoadBegin(const std::string& url) +{ + TESTLOG_I("NWebHandlerImplTest::OnPageLoadBegin called, url=%{public}s", url.c_str()); +} + +void NWebHandlerImplTest::OnPageLoadError(int errorCode, + const std::string& description, + const std::string& failingUrl) +{ + TESTLOG_I("NWebHandlerImplTest::OnPageLoadError called, url=%{public}s", failingUrl.c_str()); +} + +bool NWebHandlerImplTest::OnHandleInterceptUrlLoading(const std::string& url) +{ + TESTLOG_I("NWebHandlerImplTest::OnHandleInterceptUrlLoading called, url=%{public}s", url.c_str()); + return false; +} + +void NWebHandlerImplTest::OnRouterPush(const std::string& param) +{ + TESTLOG_I("NWebHandlerImplTest::OnRouterPush called, url=%{public}s", param.c_str()); +} + +void NWebHandlerImplTest::OnMessage(const std::string& param) +{ + TESTLOG_I("NWebHandlerImplTest::OnMessage called, message=%{public}s", param.c_str()); +} + +const std::vector NWebHandlerImplTest::VisitedUrlHistory() +{ + std::vector vector_string; + vector_string.push_back("https://www.qq.com"); + vector_string.push_back("file:///data/local/cef/cef_user_data/jingtai.html"); + return vector_string; +} + +void NWebHandlerImplTest::OnResourceLoadError(std::shared_ptr request, + std::shared_ptr error) +{ + TESTLOG_I("OnPageLoadError, url=%{public}s, errorCode=%{public}d, desc=%{public}s", request->Url().c_str(), + error->ErrorCode(), error->ErrorInfo().c_str()); +} +void NWebHandlerImplTest::OnHttpError(std::shared_ptr request, + std::shared_ptr errorResponse) +{ + TESTLOG_I("OnHttpError, url=%{public}s, mimeType=%{public}s, is_main_frame=%{public}d," \ + "has_user_gesture=%{public}d", request->Url().c_str(), + errorResponse->ResponseMimeType().c_str(), request->IsAboutMainFrame(), request->FromGesture()); +} +void NWebHandlerImplTest::OnPageIcon(const void* data, + size_t width, + size_t height, + ImageColorType colorType, + ImageAlphaType alphaType) +{ + TESTLOG_I("OnPageIcon, width=%{public}d, height=%{public}d", width, height); + size_t len = width * height * BITS_PER_PIXEL; + char* data_temp = new char[len]; + if (memcpy_s(data_temp, len, data, len) != 0) { + delete []data_temp; + return; + } + DumpToBmp("/system/etc/webview/icon.bmp", data_temp, width, height); + delete []data_temp; + data_temp = nullptr; +} + +void NWebHandlerImplTest::OnDesktopIconUrl(const std::string& iconUrl, bool precomposed) +{ + TESTLOG_I("OnDesktopIconUrl, iconUrl=%{public}s, precomposed=%{public}d", iconUrl.c_str(), precomposed); +} + +void NWebHandlerImplTest::OnFocus() +{ + TESTLOG_I("NWebHandlerImplTest::OnFocus"); +} + +void NWebHandlerImplTest::OnLoadingProgress(int newProgress) +{ + TESTLOG_I("NWebHandlerImplTest::OnLoadingProgress progress=%{public}d", newProgress); +} + +void NWebHandlerImplTest::OnPageTitle(const std::string &title) +{ + TESTLOG_I("NWebHandlerImplTest::OnTitle title=%{public}s", title.c_str()); +} + +void NWebHandlerImplTest::OnResource(const std::string &url) +{ + TESTLOG_I("NWebHandlerImplTest::OnResource url=%{public}s", url.c_str()); +} + +void NWebHandlerImplTest::OnGeolocationShow(const std::string& origin, + NWebGeolocationCallbackInterface* callback) +{ + TESTLOG_I("NWebHandlerImplTest::OnGeolocationShow called, origin=%{public}s", origin.c_str()); + callback->GeolocationCallbackInvoke(origin, true, true); +} + +void NWebHandlerImplTest::OnGeolocationHide() +{ + TESTLOG_I("NWebHandlerImplTest::OnGeolocationHide called"); +} + +void NWebHandlerImplTest::OnPermissionRequest(std::shared_ptr request) +{ + int id = request->ResourceAcessId(); + TESTLOG_I("NWebHandlerImplTest::OnPermissionRequest called, origin=%{public}s, resourceId=%{public}d", + request->Origin().c_str(), id); + request->Agree(id); +} + +void NWebHandlerImplTest::OnPermissionRequestCanceled(std::shared_ptr request) +{ + int id = request->ResourceAcessId(); + TESTLOG_I("NWebHandlerImplTest::OnPermissionRequestCanceled called, origin=%{public}s, resourceId=%{public}d", + request->Origin().c_str(), id); + request->Refuse(); +} +} // namespace OHOS::NWeb diff --git a/test/ohos_nweb/nweb_client_impl_test.h b/test/ohos_nweb/nweb_client_impl_test.h new file mode 100644 index 0000000000000000000000000000000000000000..1ac2ca704ad0202d840c8f32c9c39f50d117e098 --- /dev/null +++ b/test/ohos_nweb/nweb_client_impl_test.h @@ -0,0 +1,51 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_HANDLER_IMPL_TEST_H +#define NWEB_HANDLER_IMPL_TEST_H + +#include "nweb_handler.h" + +namespace OHOS::NWeb { +class NWebHandlerImplTest : public NWebHandler { +public: + NWebHandlerImplTest() = default; + ~NWebHandlerImplTest() = default; + virtual void SetNWeb(std::shared_ptr nweb) override; + void OnProxyDied() override; + void OnRouterPush(const std::string& param) override; + void OnMessage(const std::string& param) override; + + void OnPageLoadEnd(int httpStatusCode, const std::string& url) override; + void OnPageLoadBegin(const std::string& url) override; + void OnPageLoadError(int errorCode, + const std::string& description, + const std::string& failingUrl) override; + bool OnHandleInterceptUrlLoading(const std::string& url) override; + const std::vector VisitedUrlHistory() override; + void OnResourceLoadError(std::shared_ptr request, + std::shared_ptr error) override; + void OnHttpError(std::shared_ptr request, + std::shared_ptr errorResponse) override; + void OnPageIcon(const void* data, + size_t width, + size_t height, + ImageColorType colorType, + ImageAlphaType alphaType) override; + void OnDesktopIconUrl(const std::string& iconUrl, bool precomposed) override; + void OnFocus() override; + void OnLoadingProgress(int newProgress) override; + void OnPageTitle(const std::string &title) override; + void OnResource(const std::string &url) override; + void OnGeolocationShow(const std::string& origin, + NWebGeolocationCallbackInterface* callback) override; + void OnGeolocationHide() override; + void OnPermissionRequest(std::shared_ptr request) override; + void OnPermissionRequestCanceled(std::shared_ptr request) override; +private: + std::weak_ptr nwebweak_; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_HANDLER_IMPL_TEST_H diff --git a/test/ohos_nweb/nweb_client_impl_test_for_intercept.cpp b/test/ohos_nweb/nweb_client_impl_test_for_intercept.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b9429e86b90daa5ccacab491e7b0df5c7ae3f1b --- /dev/null +++ b/test/ohos_nweb/nweb_client_impl_test_for_intercept.cpp @@ -0,0 +1,90 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_client_impl_test_for_intercept.h" + +#include +#include +#include +#include +#include +#include +#include +#include "nweb_test_log.h" +#include "nweb_url_resource_request.h" +#include "nweb_url_resource_response.h" +#include "utils.h" +#include "securec.h" + +namespace OHOS::NWeb { +std::string g_data; +void NWebHandlerImplTestForIntercept::SetNWeb(std::shared_ptr nweb) +{ + nwebweak_ = nweb; +} + +bool ReadFileToString(const char* path, std::string& data) +{ + TESTLOG_I(" ReadFileToString-1111%{public}s", path); + // Implementation adapted from base/file_util.cc + FILE* file = fopen(path, "rb"); + if (!file) { + return false; + } + char buf[1 << 16]; + size_t len; + while ((len = fread(buf, 1, sizeof(buf), file)) > 0) { + data.append(buf, len); + } + fclose(file); + return true; +} + +bool GetResourceDir(std::string& dir) +{ + char buff[1024]; // 1024 size + ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff) - 1); + if (len == -1) { + return false; + } + + buff[len] = 0; + char* pos = strrchr(buff, '/'); + if (!pos) { + return false; + } + + if (strcpy_s(pos + 1, len, "files") != 0) { + TESTLOG_I(" strcpy_s error"); + return false; + } + dir = std::string(buff); + return true; +} + +bool LoadBinaryResource(const char* resource_name, std::string& resource_data) +{ + std::string path; + if (!GetResourceDir(path)) { + return false; + } + path.append("/"); + path.append(resource_name); + return ReadFileToString(path.c_str(), resource_data); +} + +std::shared_ptr NWebHandlerImplTestForIntercept::OnHandleInterceptRequest( + std::shared_ptr request) +{ + std::string url = request->Url(); + if (strstr(url.c_str(), ".png") != nullptr) { + // system/bin/files + LoadBinaryResource("2.png", g_data); // define 2.png name image + std::shared_ptr response = + std::make_shared("text/html", "UTF-8", g_data); + return response; + } + return nullptr; +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/ohos_nweb/nweb_client_impl_test_for_intercept.h b/test/ohos_nweb/nweb_client_impl_test_for_intercept.h new file mode 100644 index 0000000000000000000000000000000000000000..82c99772a6d2ab75f52902b288d06d6ee8c3e3f6 --- /dev/null +++ b/test/ohos_nweb/nweb_client_impl_test_for_intercept.h @@ -0,0 +1,23 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_HANDLER_IMPL_TEST_FOR_INTERCEPT_H +#define NWEB_HANDLER_IMPL_TEST_FOR_INTERCEPT_H + +#include "nweb_handler.h" + +namespace OHOS::NWeb { +class NWebHandlerImplTestForIntercept : public NWebHandler { +public: + NWebHandlerImplTestForIntercept() = default; + ~NWebHandlerImplTestForIntercept() = default; + void SetNWeb(std::shared_ptr nweb) override; + std::shared_ptr OnHandleInterceptRequest( + std::shared_ptr request) override; +private: + std::weak_ptr nwebweak_; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_HANDLER_IMPL_TEST_FOR_INTERCEPT_H \ No newline at end of file diff --git a/test/ohos_nweb/nweb_cookie_test_callback.h b/test/ohos_nweb/nweb_cookie_test_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..b476fcb9208b9c8fe8e57de3076cdb67325bb541 --- /dev/null +++ b/test/ohos_nweb/nweb_cookie_test_callback.h @@ -0,0 +1,52 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_COOKIE_TEST_CALLBACK_H +#define NWEB_COOKIE_TEST_CALLBACK_H + +#include "nweb_cookie_manager.h" +#include "nweb_test_log.h" + +namespace OHOS::NWeb { +class SetCookieTestCallback : public NWebValueCallback { +public: + void OnReceiveValue(bool value) + { + TESTLOG_I("SetCookieTestCallback result:%{public}d", value); + } +}; + +class ExistCookieTestCallback : public NWebValueCallback { +public: + void OnReceiveValue(bool value) + { + TESTLOG_I("ExistCookieTestCallback result:%{public}d", value); + } +}; + +class StoreCookieTestCallback : public NWebValueCallback { +public: + void OnReceiveValue(bool value) + { + TESTLOG_I("StoreCookieTestCallback result:%{public}d", value); + } +}; + +class DeleteCookieTestCallback : public NWebValueCallback { +public: + void OnReceiveValue(bool value) + { + TESTLOG_I("DeleteCookieTestCallback result:%{public}d", value); + } +}; + +class ReturnCookieTestCallback : public NWebValueCallback { + void OnReceiveValue(std::string value) + { + TESTLOG_I("ReturnCookieTestCallback result:%{public}s", value.c_str()); + } +}; +} // namespace OHOS::NWeb + +#endif // NWEB_COOKIE_TEST_CALLBACK_H \ No newline at end of file diff --git a/test/ohos_nweb/nweb_downloadlistener_impl_test.cpp b/test/ohos_nweb/nweb_downloadlistener_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f5d547037f132437dc1acb033e3d9defbfb521f --- /dev/null +++ b/test/ohos_nweb/nweb_downloadlistener_impl_test.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_downloadlistener_impl_test.h" + +#include +#include "nweb_test_log.h" + +namespace OHOS::NWeb { +void NWebDownloadListenerImplTest::OnDownloadStart(const std::string &url, const std::string &userAgent, + const std::string &contentDisposition, + const std::string &mimetype, + long contentLength) +{ + TESTLOG_I("NWebDownloadListenerImplTest::onDownloadStart"); + TESTLOG_I("url=%{public}s", url.c_str()); + TESTLOG_I("userAgent=%{public}s", userAgent.c_str()); + TESTLOG_I("contentDisposition=%{public}s", contentDisposition.c_str()); + TESTLOG_I("mimetype=%{public}s", mimetype.c_str()); + TESTLOG_I("contentLength=%{public}ld", contentLength); +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/ohos_nweb/nweb_downloadlistener_impl_test.h b/test/ohos_nweb/nweb_downloadlistener_impl_test.h new file mode 100644 index 0000000000000000000000000000000000000000..487b6d3695ab9eba6bf9069f8a206d9bc0194d83 --- /dev/null +++ b/test/ohos_nweb/nweb_downloadlistener_impl_test.h @@ -0,0 +1,22 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_DOWNLOADLISTENER_IMPL_TEST_H +#define NWEB_DOWNLOADLISTENER_IMPL_TEST_H + +#include "nweb_download_callback.h" + +namespace OHOS::NWeb { +class NWebDownloadListenerImplTest : public NWebDownloadCallback { +public: + NWebDownloadListenerImplTest() = default; + ~NWebDownloadListenerImplTest() = default; + void OnDownloadStart(const std::string &url, const std::string &userAgent, + const std::string &contentDisposition, + const std::string &mimetype, + long contentLength) override; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_DOWNLOADLISTENER_IMPL_TEST_H \ No newline at end of file diff --git a/test/ohos_nweb/nweb_input_event_consumer_test.cpp b/test/ohos_nweb/nweb_input_event_consumer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c0a0b2f5a50905a7d9a42d2906795ffbb2d1da0 --- /dev/null +++ b/test/ohos_nweb/nweb_input_event_consumer_test.cpp @@ -0,0 +1,88 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "nweb_input_event_consumer_test.h" +#include "nweb_test_log.h" + +namespace OHOS::NWeb { +NWebInputEventConsumerTest::NWebInputEventConsumerTest(std::shared_ptr nweb) + : nwebweak_(nweb) {} + +void NWebInputEventConsumerTest::OnInputEvent(std::shared_ptr pointerEvent) const +{ + DispatchPointerEvent(pointerEvent); +} + +void NWebInputEventConsumerTest::OnInputEvent(std::shared_ptr keyEvent) const +{ + DispatchKeyEvent(keyEvent); +} + +void NWebInputEventConsumerTest::DispatchPointerEvent(std::shared_ptr pointerEvent) const +{ + if (nwebweak_.expired()) { + TESTLOG_W("nweb instance has expired"); + return; + } + auto nweb = nwebweak_.lock(); + if (pointerEvent == nullptr) { + TESTLOG_E("pointerEvent is invaild."); + return; + } + int32_t pointerID = pointerEvent->GetPointerId(); + MMI::PointerEvent::PointerItem item; + bool ret = pointerEvent->GetPointerItem(pointerID, item); + if (!ret) { + TESTLOG_E("get pointer item failed."); + return; + } + int32_t action = pointerEvent->GetPointerAction(); + switch (action) { + case MMI::PointerEvent::POINTER_ACTION_DOWN: { + TESTLOG_I("nweb receive pointer touch down event"); + nweb->OnTouchPress(pointerID, item.GetLocalX(), item.GetLocalY()); + break; + } + case MMI::PointerEvent::POINTER_ACTION_UP: { + TESTLOG_I("nweb receive pointer touch up event"); + nweb->OnTouchRelease(pointerID); + break; + } + case MMI::PointerEvent::POINTER_ACTION_MOVE: { + TESTLOG_I("nweb receive pointer touch move event"); + nweb->OnTouchMove(pointerID, item.GetLocalX(), item.GetLocalY()); + break; + } + case MMI::PointerEvent::POINTER_ACTION_CANCEL: { + TESTLOG_I("nweb receive pointer touch cancel event"); + nweb->OnTouchCancel(); + break; + } + default: { + TESTLOG_W("unsupport PointerEvent action[%{public}d] received", action); + break; + } + } +} + +void NWebInputEventConsumerTest::DispatchKeyEvent(std::shared_ptr keyEvent) const +{ + if (nwebweak_.expired()) { + TESTLOG_W("nweb instance has expired"); + return; + } + auto nweb = nwebweak_.lock(); + if (keyEvent == nullptr) { + TESTLOG_E("keyEvent is invaild."); + return; + } + int32_t keyCode = keyEvent->GetKeyCode(); + if (keyCode == MMI::KeyEvent::KEYCODE_BACK) { + TESTLOG_I("nweb receive key back event"); + nweb->OnNavigateBack(); + } else { + TESTLOG_W("unsupport KeyEvent code[%{public}d] received", keyCode); + } +} +} // namespace OHOS::NWeb \ No newline at end of file diff --git a/test/ohos_nweb/nweb_input_event_consumer_test.h b/test/ohos_nweb/nweb_input_event_consumer_test.h new file mode 100644 index 0000000000000000000000000000000000000000..f73ef91e0fbfb577938a5e9dc93f1d8a77972297 --- /dev/null +++ b/test/ohos_nweb/nweb_input_event_consumer_test.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_INPUT_EVENT_CONSUMER_TEST_H +#define NWEB_INPUT_EVENT_CONSUMER_TEST_H + +#include +#include "i_input_event_consumer.h" +#include "nweb.h" + +namespace OHOS::NWeb { +class NWebInputEventConsumerTest : public MMI::IInputEventConsumer { +public: + explicit NWebInputEventConsumerTest(std::shared_ptr nweb); + ~NWebInputEventConsumerTest() = default; + void OnInputEvent(std::shared_ptr pointerEvent) const override; + void OnInputEvent(std::shared_ptr keyEvent) const override; + void OnInputEvent(std::shared_ptr axisEvent) const override {} + +private: + void DispatchPointerEvent(std::shared_ptr pointerEvent) const; + void DispatchKeyEvent(std::shared_ptr keyEvent) const; + +private: + std::weak_ptr nwebweak_; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_INPUT_EVENT_CONSUMER_TEST_H \ No newline at end of file diff --git a/test/ohos_nweb/nweb_javascript_result_callback_test.cpp b/test/ohos_nweb/nweb_javascript_result_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e0c67e5483a8bba2bf7ffb79aece1f9bb9557ce --- /dev/null +++ b/test/ohos_nweb/nweb_javascript_result_callback_test.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include "nweb_javascript_result_callback_test.h" + +#include +#include "nweb_test_log.h" + +namespace OHOS::NWeb { +std::shared_ptr WebJavaScriptResultCallBackTest::GetJavaScriptResult( + std::vector> args, const std::string &method, const std::string &object_name) +{ + TESTLOG_I("GetJavaScriptResult=%{public}s", object_name.c_str()); + TESTLOG_I("GetJavaScriptResult=%{public}s", method.c_str()); + std::shared_ptr value = std::make_shared(NWebValue::Type::NONE); + return value; +} +void WebJavaScriptResultCallBackTest::RegisterArkJSfunction(const std::string &objectname) +{ + std::unique_lock lk(object_mtx_); + if (objector_map_.find(objectname) != objector_map_.end()) { + return; + } + objector_map_[objectname] = "method"; +} +void WebJavaScriptResultCallBackTest::UnregisterArkJSfunction(const std::string &objectname) +{ + std::unique_lock lk(object_mtx_); + if (objector_map_.find(objectname) == objector_map_.end()) { + return; + } + objector_map_.erase(objectname); +} +} diff --git a/test/ohos_nweb/nweb_javascript_result_callback_test.h b/test/ohos_nweb/nweb_javascript_result_callback_test.h new file mode 100644 index 0000000000000000000000000000000000000000..2a4771dafacd2d5385fcf694983a4acab959ff15 --- /dev/null +++ b/test/ohos_nweb/nweb_javascript_result_callback_test.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef WEB_JAVASCRIPT_RESULT_CALLBACK_TEST_H +#define WEB_JAVASCRIPT_RESULT_CALLBACK_TEST_H + +#include "nweb_javascript_result_callback.h" + +#include +#include +#include +#include +#include +#include "nweb_value.h" + +namespace OHOS::NWeb { +class WebJavaScriptResultCallBackTest : public OHOS::NWeb::NWebJavaScriptResultCallBack { +public: + WebJavaScriptResultCallBackTest() {} + ~WebJavaScriptResultCallBackTest() = default; + std::shared_ptr + GetJavaScriptResult(std::vector> args, + const std::string& method, + const std::string& objectname) override; + void RegisterArkJSfunction(const std::string& objectname); + void UnregisterArkJSfunction(const std::string& objectname); +private: + std::mutex int_mtx_; + using ObjectClassMap = std::map; + ObjectClassMap objector_map_; + std::mutex object_mtx_; +}; +} +#endif // WEB_JAVASCRIPT_RESULT_CALLBACK_TEST_H diff --git a/test/ohos_nweb/nweb_js_dialog_impl_test.cpp b/test/ohos_nweb/nweb_js_dialog_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db5569533eb039ae8b5e90b4147533c578ff087a --- /dev/null +++ b/test/ohos_nweb/nweb_js_dialog_impl_test.cpp @@ -0,0 +1,70 @@ +/* + * 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_js_dialog_impl_test.h" +#include "nweb_test_log.h" + +namespace OHOS::NWeb { +void NWebJSDialogImplTest::SetNWeb(std::shared_ptr nweb) +{ + nwebweak_ = nweb; +} + +bool NWebJSDialogImplTest::OnAlertDialogByJS(const std::string &url, + const std::string &message, + std::shared_ptr result) +{ + TESTLOG_I("OnAlertDialogByJS message:%{public}s", message.c_str()); + type_ == CONFIRM ? result->Confirm() : result->Cancel(); + return true; +} + +bool NWebJSDialogImplTest::OnBeforeUnloadByJS(const std::string &url, + const std::string &message, + std::shared_ptr result) +{ + TESTLOG_I("OnBeforeUnloadByJS message:%{public}s", message.c_str()); + type_ == CONFIRM ? result->Confirm() : result->Cancel(); + return true; +} + +bool NWebJSDialogImplTest::OnPromptDialogByJs(const std::string &url, + const std::string &message, + const std::string &defaultValue, + std::shared_ptr result) +{ + TESTLOG_I("OnPromptDialogByJs message:%{public}s", message.c_str()); + TESTLOG_I("OnPromptDialogByJs defaultValue:%{public}s", defaultValue.c_str()); + type_ == CONFIRM ? result->Confirm("my input") : result->Cancel(); + return true; +} + +bool NWebJSDialogImplTest::OnConfirmDialogByJS(const std::string &url, + const std::string &message, + std::shared_ptr result) +{ + TESTLOG_I("OnConfirmDialogByJS message:%{public}s", message.c_str()); + type_ == CONFIRM ? result->Confirm() : result->Cancel(); + return true; +} + +bool NWebJSDialogImplTest::OnConsoleLog(const NWebConsoleLog& message) +{ + TESTLOG_I("message:%{public}s", message.Log().c_str()); + TESTLOG_I("lineNumer:%{public}d", message.LineNumer()); + TESTLOG_I("messageLevel:%{public}d", message.LogLevel()); + TESTLOG_I("sourceId:%{public}s", message.SourceId().c_str()); + return true; +} +} \ No newline at end of file diff --git a/test/ohos_nweb/nweb_js_dialog_impl_test.h b/test/ohos_nweb/nweb_js_dialog_impl_test.h new file mode 100644 index 0000000000000000000000000000000000000000..1f1e120fc58f426cd9313634d8fe02a0dee2cea8 --- /dev/null +++ b/test/ohos_nweb/nweb_js_dialog_impl_test.h @@ -0,0 +1,41 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_JS_DIALOG_IMPL_TEST_H +#define NWEB_JS_DIALOG_IMPL_TEST_H + +#include "nweb_handler.h" + +namespace OHOS::NWeb { +class NWebJSDialogImplTest : public NWebHandler { +public: + enum { + CONFIRM, + CANCEL + }; + NWebJSDialogImplTest() = default; + explicit NWebJSDialogImplTest(int type) : type_(type) {} + ~NWebJSDialogImplTest() = default; + void SetNWeb(std::shared_ptr nweb) override; + bool OnAlertDialogByJS(const std::string &url, + const std::string &message, + std::shared_ptr result) override; + bool OnBeforeUnloadByJS(const std::string &url, + const std::string &message, + std::shared_ptr result) override; + bool OnPromptDialogByJs(const std::string &url, + const std::string &message, + const std::string &defaultValue, + std::shared_ptr result) override; + bool OnConfirmDialogByJS(const std::string &url, + const std::string &message, + std::shared_ptr result) override; + bool OnConsoleLog(const NWebConsoleLog& message) override; +private: + std::weak_ptr nwebweak_; + int type_; +}; +} // namespace OHOS::NWeb + +#endif // NWEB_JS_DIALOG_IMPL_TEST_H \ No newline at end of file diff --git a/test/ohos_nweb/nweb_test_log.h b/test/ohos_nweb/nweb_test_log.h new file mode 100644 index 0000000000000000000000000000000000000000..eaffb2d4aa957cfec58295eabb1a6a7cffe06c8d --- /dev/null +++ b/test/ohos_nweb/nweb_test_log.h @@ -0,0 +1,23 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_TEST_LOG_H +#define NWEB_TEST_LOG_H + +#include + +namespace OHOS { +constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0, "NWEB_TEST" }; + +#define TESTLOG(func, fmt, ...) \ + (void)func(LOG_LABEL, "%{public}s<%{public}d>: " fmt, __func__, __LINE__, ##__VA_ARGS__) + +#define TESTLOG_F(fmt, ...) TESTLOG(HiviewDFX::HiLog::Fatal, fmt, ##__VA_ARGS__) +#define TESTLOG_E(fmt, ...) TESTLOG(HiviewDFX::HiLog::Error, fmt, ##__VA_ARGS__) +#define TESTLOG_W(fmt, ...) TESTLOG(HiviewDFX::HiLog::Warn, fmt, ##__VA_ARGS__) +#define TESTLOG_I(fmt, ...) TESTLOG(HiviewDFX::HiLog::Info, fmt, ##__VA_ARGS__) +#define TESTLOG_D(fmt, ...) TESTLOG(HiviewDFX::HiLog::Debug, fmt, ##__VA_ARGS__) +} // namespace OHOS + +#endif // NWEB_TEST_LOG_H \ No newline at end of file diff --git a/test/ohos_nweb/ohos_nweb_test.cpp b/test/ohos_nweb/ohos_nweb_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3c5617d19f577c18bbd0b17ce000cac57576d13 --- /dev/null +++ b/test/ohos_nweb/ohos_nweb_test.cpp @@ -0,0 +1,1864 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "window.h" +#include +#include "nweb_test_log.h" +#include "nweb.h" +#include "nweb_client_impl_test.h" +#include "nweb_client_impl_test_for_intercept.h" +#include "nweb_cookie_manager.h" +#include "nweb_downloadlistener_impl_test.h" +#include "nweb_adapter_helper.h" +#include "nweb_hit_testresult.h" +#include "nweb_preference.h" +#include "nweb_input_event_consumer_test.h" +#include "nweb_javascript_result_callback_test.h" +#include "nweb_js_dialog_impl_test.h" +#include "nweb_cookie_test_callback.h" + +using namespace OHOS; + +namespace { +sptr g_window = nullptr; +sptr g_window2 = nullptr; +std::shared_ptr g_nweb = nullptr; +std::shared_ptr g_nweb2 = nullptr; +std::shared_ptr g_webSettings = nullptr; +std::shared_ptr g_handler = nullptr; +std::string g_url = "www.baidu.com"; + +std::unordered_map g_argsMap; +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 int DEFAULT_FONT_SIZE = 13; +const int DEFAULT_FONT_SIZE_TWO = 16; +const int DEFAULT_FONT_SIZE_MAX = 72; +const int MINI_LOGICAL_FONT_SIZE = 8; +const int TEXT_SIZE_PERCENT_MIN = 100; +const int TEXT_SIZE_PERCENT_MAX = 500; +const int TIME_SECONDS_FIVE = 5; +const int TIME_SECONDS_THREE = 3; +const int MINI_FONT_SIZE = 8; +const int STEP_TWO = 2; +const std::string ARG_WIDTH = "--width"; +const std::string ARG_HEIGHT = "--height"; + +const int DEFAULT_WIDTH = 2560; +const int DEFAULT_HEIGHT = 1396; + +void InitArgs(int32_t argc, const char * const argv[]) +{ + constexpr int leastArgsCount = 2; + if (argc <= leastArgsCount) { + return; + } + for (auto i = leastArgsCount; i < argc; ++i) { + std::string arg = argv[i]; + uint64_t pos = 0; + while (pos < arg.size()) { + if (arg[pos] == '=') { + break; + } + ++pos; + } + if (pos == arg.size()) { + g_argsMap.emplace(std::make_pair(arg, "")); + } else { + g_argsMap.emplace(std::make_pair(arg.substr(0, pos), arg.substr(pos + 1))); + } + } +} + +bool HasArg(const std::string &arg) +{ + return (!g_argsMap.empty()) && (g_argsMap.find(arg) != g_argsMap.end()); +} + +std::string GetArgValue(const std::string &arg) +{ + if (!HasArg(arg)) { + return ""; + } + return g_argsMap.at(arg); +} + +uint32_t GetNumFromArgs(const std::string &arg) +{ + if (!HasArg(arg)) { + return 0; + } + return std::stoi(GetArgValue(arg)); +} + +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)); + return webEngineArgList; +} + +OHOS::NWeb::NWebInitArgs GetInitArgs() +{ + OHOS::NWeb::NWebInitArgs initArgs = { + .dump_path = GetArgValue(ARG_DUMP), + .frame_info_dump = HasArg(ARG_FRAME_INFO) ? true : false, + .web_engine_args_to_add = GetWebEngineArgs(ARG_ADD_WEB_ENGINE_ARG), + .web_engine_args_to_delete = GetWebEngineArgs(ARG_DELETE_WEB_ENGINE_ARG), + .multi_renderer_process = HasArg(ARG_MULTI_RENDER_PROCESS) ? true : false, + }; + return initArgs; +} + +sptr CreateWindow() +{ + sptr option = new Rosen::WindowOption(); + int width = HasArg(ARG_WIDTH) ? GetNumFromArgs(ARG_WIDTH) : DEFAULT_WIDTH; + int height = HasArg(ARG_HEIGHT) ? GetNumFromArgs(ARG_HEIGHT) : DEFAULT_HEIGHT; + option->SetWindowRect({0, 0, width, height}); + auto window = Rosen::Window::Create("nweb_test_window", option); + return window; +} + +void RegistEventCb(sptr window, std::shared_ptr nweb) +{ + if (window == nullptr) { + return; + } + + std::shared_ptr inputEventListener = + std::make_shared(nweb); + + window->AddInputEventListener(inputEventListener); +} + +void TestPrepare() +{ + TESTLOG_I("TestPrepare"); + if (!OHOS::NWeb::NWebAdapterHelper::Instance().Init()) { + TESTLOG_E("fail to init NWebAdapterHelper, test end"); + return; + } + + g_window = CreateWindow(); + if (g_window == nullptr) { + return; + } + + g_nweb = NWeb::NWebAdapterHelper::Instance().CreateNWeb( + g_window->GetSurfaceNode()->GetSurface(), GetInitArgs()); + if (g_nweb == nullptr) { + g_window = nullptr; + TESTLOG_E("fail to get nweb instance, test end"); + return; + } + g_nweb->Resize(g_window->GetRect().width_, g_window->GetRect().height_); + RegistEventCb(g_window, g_nweb); + + TESTLOG_I("CreateNWeb SUCCESS"); + auto nwebHandler = std::make_shared(); + if (nwebHandler == nullptr) { + TESTLOG_E("fail to new NWeb Handler, test end"); + return; + } + g_nweb->SetNWebHandler(nwebHandler); + g_url = HasArg(ARG_URL) ? GetArgValue(ARG_URL) : "www.baidu.com"; // load www.baidu.com by default + TESTLOG_I("ready to load url=%{public}s", g_url.c_str()); + + g_webSettings = g_nweb->GetPreference(); +} + +void TestPrepareWithClient(std::shared_ptr client) +{ + TESTLOG_I("TestPrepare"); + if (!OHOS::NWeb::NWebAdapterHelper::Instance().Init()) { + TESTLOG_E("fail to init NWebAdapterHelper, test end"); + return; + } + + g_window = CreateWindow(); + if (g_window == nullptr) { + return; + } + + g_nweb = NWeb::NWebAdapterHelper::Instance().CreateNWeb( + g_window->GetSurfaceNode()->GetSurface(), GetInitArgs()); + if (g_nweb == nullptr) { + g_window = nullptr; + TESTLOG_E("fail to get nweb instance, test end"); + return; + } + g_nweb->Resize(g_window->GetRect().width_, g_window->GetRect().height_); + RegistEventCb(g_window, g_nweb); + + TESTLOG_I("CreateNWeb SUCCESS"); + g_nweb->SetNWebHandler(client); + g_url = HasArg(ARG_URL) ? GetArgValue(ARG_URL) : "www.baidu.com"; // load www.baidu.com by default + TESTLOG_I("ready to load url=%{public}s", g_url.c_str()); + + g_webSettings = g_nweb->GetPreference(); +} + +void TestWebSettingsForNormalWeb() +{ + if (g_webSettings != nullptr) { + g_webSettings->PutJavaScriptEnabled(true); + g_webSettings->PutIsCreateWindowsByJavaScriptAllowed(true); + g_webSettings->PutDomStorageEnabled(true); + } +} + +// create nweb and load url with fullscreen +void Test1() +{ + TESTLOG_I("Test1 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("end"); +} + +void Test200() +{ + TESTLOG_I("Test200 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool content_access = g_webSettings->EnableContentAccess(); + if (!content_access) { + TESTLOG_E("Error! content_access default value:%{public}d != true.", content_access); + } else { + TESTLOG_I("content_access default value: %{public}d", content_access); + } + + TESTLOG_I("Set content_access to false."); + g_webSettings->PutEnableContentAccess(false); + content_access = g_webSettings->EnableContentAccess(); + if (content_access) { + TESTLOG_E("Error! content_access :%{public}d != false.", content_access); + } else { + TESTLOG_I("content_access=%{public}d", content_access); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test200 end"); +} + +void Test201() +{ + TESTLOG_I("Test201 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool file_access = g_webSettings->EnableRawFileAccess(); + if (file_access) { + TESTLOG_E("Error! file_access default value:%{public}d != false.", file_access); + } else { + TESTLOG_I("file_access default value: %{public}d", file_access); + } + + TESTLOG_I("Set file_access to true."); + g_webSettings->PutEnableRawFileAccess(true); + file_access = g_webSettings->EnableRawFileAccess(); + if (!file_access) { + TESTLOG_E("Error! file_access :%{public}d != true.", file_access); + } else { + TESTLOG_I("file_access=%{public}d", file_access); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test201 end"); +} + +void Test202() +{ + TESTLOG_I("Test202 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool file_access_from_file_urls = g_webSettings->EnableRawFileAccessFromFileURLs(); + if (file_access_from_file_urls) { + TESTLOG_E("Error! file_access_from_file_urls default value:%{public}d != false.", + file_access_from_file_urls); + } else { + TESTLOG_I("file_access_from_file_urls default value: %{public}d", file_access_from_file_urls); + } + + TESTLOG_I("Set file_access_from_file_urls to true."); + g_webSettings->PutEnableRawFileAccessFromFileURLs(true); + file_access_from_file_urls = g_webSettings->EnableRawFileAccessFromFileURLs(); + if (!file_access_from_file_urls) { + TESTLOG_E("Error! file_access_from_file_urls :%{public}d != true.", file_access_from_file_urls); + } else { + TESTLOG_I("file_access_from_file_urls=%{public}d", file_access_from_file_urls); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test202 end"); +} + +void Test203() +{ + TESTLOG_I("Test203 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool universal_access_from_file_urls = g_webSettings->EnableUniversalAccessFromFileURLs(); + if (universal_access_from_file_urls) { + TESTLOG_E("Error! universal_access_from_file_urls default value:%{public}d != false.", + universal_access_from_file_urls); + } else { + TESTLOG_I("universal_access_from_file_urls default value: %{public}d", universal_access_from_file_urls); + } + + TESTLOG_I("Set universal_access_from_file_urls to true."); + g_webSettings->PutEnableUniversalAccessFromFileURLs(true); + universal_access_from_file_urls = g_webSettings->EnableUniversalAccessFromFileURLs(); + if (!universal_access_from_file_urls) { + TESTLOG_E("Error! universal_access_from_file_urls :%{public}d != true.", universal_access_from_file_urls); + } else { + TESTLOG_I("universal_access_from_file_urls=%{public}d", universal_access_from_file_urls); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test203 end"); +} + +void Test204() +{ + TESTLOG_I("Test204 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool images_enabled_ = !g_webSettings->IsLoadImageFromNetworkDisabled(); + if (!images_enabled_) { + TESTLOG_E("Error! images_enabled_ default value:%{public}d != true.", images_enabled_); + } else { + TESTLOG_I("images_enabled_ default value: %{public}d", images_enabled_); + } + + TESTLOG_I("Set images_enabled_ to false."); + g_webSettings->PutLoadImageFromNetworkDisabled(true); + images_enabled_ = !g_webSettings->IsLoadImageFromNetworkDisabled(); + if (images_enabled_) { + TESTLOG_E("Error! images_enabled_ :%{public}d != false.", images_enabled_); + } else { + TESTLOG_I("images_enabled_=%{public}d", images_enabled_); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test204 end"); +} + +void Test205() +{ + TESTLOG_I("Test205 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string cursive_font_family = g_webSettings->CursiveFontFamilyName(); + if (cursive_font_family != "cursive") { + TESTLOG_E("Error! cursive_font_family default value:%{public}s != cursive.", cursive_font_family.c_str()); + } else { + TESTLOG_I("cursive_font_family default value: %{public}s", cursive_font_family.c_str()); + } + + TESTLOG_I("Set cursive_font_family to cursive."); + g_webSettings->PutCursiveFontFamilyName("fantasy"); + cursive_font_family = g_webSettings->CursiveFontFamilyName(); + if (cursive_font_family != "cursive") { + TESTLOG_E("Error! cursive_font_family :%{public}s != cursive.", cursive_font_family.c_str()); + } else { + TESTLOG_I("cursive_font_family=%{public}s", cursive_font_family.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test205 end"); +} + +void Test206() +{ + TESTLOG_I("Test206 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool databases_enabled = g_webSettings->IsDataBaseEnabled(); + if (databases_enabled) { + TESTLOG_E("Error! databases_enabled default value:%{public}d != false.", databases_enabled); + } else { + TESTLOG_I("databases_enabled default value: %{public}d", databases_enabled); + } + + TESTLOG_I("Set databases_enabled to true."); + g_webSettings->PutDatabaseAllowed(true); + databases_enabled = g_webSettings->IsDataBaseEnabled(); + if (!databases_enabled) { + TESTLOG_E("Error! databases_enabled :%{public}d != true.", databases_enabled); + } else { + TESTLOG_I("databases_enabled=%{public}d", databases_enabled); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test206 end"); +} + +void Test207() +{ + TESTLOG_I("Test207 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int default_fixed_font_size = g_webSettings->DefaultFixedFontSize(); + if (default_fixed_font_size != DEFAULT_FONT_SIZE) { + TESTLOG_E("Error! default_fixed_font_size default value:%{public}d != 13.", default_fixed_font_size); + } else { + TESTLOG_I("default_fixed_font_size default value: %{public}d", default_fixed_font_size); + } + + TESTLOG_I("Set default_fixed_font_size to 72."); + g_webSettings->PutDefaultFixedFontSize(DEFAULT_FONT_SIZE_MAX); + default_fixed_font_size = g_webSettings->DefaultFixedFontSize(); + if (default_fixed_font_size != DEFAULT_FONT_SIZE_MAX) { + TESTLOG_E("Error! default_fixed_font_size :%{public}d != 72.", default_fixed_font_size); + } else { + TESTLOG_I("default_fixed_font_size=%{public}d", default_fixed_font_size); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test207 end"); +} + +void Test208() +{ + TESTLOG_I("Test208 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int default_font_size = g_webSettings->DefaultFontSize(); + if (default_font_size != DEFAULT_FONT_SIZE_TWO) { + TESTLOG_E("Error! default_font_size default value:%{public}d != 16.", default_font_size); + } else { + TESTLOG_I("default_font_size default value: %{public}d", default_font_size); + } + + TESTLOG_I("Set default_font_size to 72."); + g_webSettings->PutDefaultFontSize(DEFAULT_FONT_SIZE_MAX); + default_font_size = g_webSettings->DefaultFontSize(); + if (default_font_size != DEFAULT_FONT_SIZE_MAX) { + TESTLOG_E("Error! default_font_size :%{public}d != 72.", default_font_size); + } else { + TESTLOG_I("default_font_size=%{public}d", default_font_size); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test208 end"); +} + +void Test209() +{ + TESTLOG_I("Test209 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string default_encoding = g_webSettings->DefaultTextEncodingFormat(); + if (default_encoding != "UTF-8") { + TESTLOG_E("Error! default_encoding default value:%{public}s != UTF-8.", default_encoding.c_str()); + } else { + TESTLOG_I("default_encoding default value: %{public}s", default_encoding.c_str()); + } + + TESTLOG_I("Set default_encoding to gb2312."); + g_webSettings->PutDefaultTextEncodingFormat("gb2312"); + default_encoding = g_webSettings->DefaultTextEncodingFormat(); + if (default_encoding != "gb2312") { + TESTLOG_E("Error! default_encoding :%{public}s != gb2312.", default_encoding.c_str()); + } else { + TESTLOG_I("default_encoding=%{public}s", default_encoding.c_str()); + } + } + + std::stringstream ss; + ss << "编码格式"; + + g_nweb->LoadWithDataAndBaseUrl("", ss.str(), "text/html", "", ""); + g_window->Show(); + + TESTLOG_I("Test209 end"); +} + +void Test231() +{ + TESTLOG_I("Test231 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string default_encoding = g_webSettings->DefaultTextEncodingFormat(); + if (default_encoding != "UTF-8") { + TESTLOG_E("Error! default_encoding default value:%{public}s != UTF-8.", default_encoding.c_str()); + } else { + TESTLOG_I("default_encoding default value: %{public}s", default_encoding.c_str()); + } + } + + std::stringstream ss; + ss << "编码格式"; + + g_nweb->LoadWithDataAndBaseUrl("", ss.str(), "text/html", "", ""); + g_window->Show(); + + TESTLOG_I("Test231 end"); +} + +void Test210() +{ + TESTLOG_I("Test210 start"); + + TestPrepare(); + + if (g_webSettings != nullptr) { + g_webSettings->PutJavaScriptEnabled(true); + g_webSettings->PutIsCreateWindowsByJavaScriptAllowed(true); + + bool dom_storage = g_webSettings->IsDomStorageEnabled(); + if (dom_storage) { + TESTLOG_E("Error! dom_storage default value:%{public}d != false.", dom_storage); + } else { + TESTLOG_I("dom_storage default value: %{public}d", dom_storage); + } + + TESTLOG_I("Set dom_storage to true."); + g_webSettings->PutDomStorageEnabled(true); + dom_storage = g_webSettings->IsDomStorageEnabled(); + if (!dom_storage) { + TESTLOG_E("Error! dom_storage :%{public}d != true.", dom_storage); + } else { + TESTLOG_I("dom_storage=%{public}d", dom_storage); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test210 end"); +} + +void Test228() +{ + TESTLOG_I("Test228 start"); + + TestPrepare(); + + if (g_webSettings != nullptr) { + g_webSettings->PutJavaScriptEnabled(true); + g_webSettings->PutIsCreateWindowsByJavaScriptAllowed(true); + + bool dom_storage = g_webSettings->IsDomStorageEnabled(); + if (dom_storage) { + TESTLOG_E("Error! dom_storage default value:%{public}d != false.", dom_storage); + } else { + TESTLOG_I("dom_storage default value: %{public}d", dom_storage); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test228 end"); +} + +void Test211() +{ + TESTLOG_I("Test211 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string fantasy_font_family = g_webSettings->FantasyFontFamilyName(); + if (fantasy_font_family != "fantasy") { + TESTLOG_E("Error! fantasy_font_family default value:%{public}s != fantasy.", fantasy_font_family.c_str()); + } else { + TESTLOG_I("fantasy_font_family default value: %{public}s", fantasy_font_family.c_str()); + } + + TESTLOG_I("Set fantasy_font_family to fantasy."); + g_webSettings->PutFantasyFontFamilyName("fantasy"); + fantasy_font_family = g_webSettings->FantasyFontFamilyName(); + if (fantasy_font_family != "fantasy") { + TESTLOG_E("Error! fantasy_font_family :%{public}s != fantasy.", fantasy_font_family.c_str()); + } else { + TESTLOG_I("fantasy_font_family=%{public}s", fantasy_font_family.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test211 end"); +} + +void Test212() +{ + TESTLOG_I("Test212 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string fixed_font_family = g_webSettings->FixedFontFamilyName(); + if (fixed_font_family != "monospace") { + TESTLOG_E("Error! fixed_font_family default value:%{public}s != monospace.", fixed_font_family.c_str()); + } else { + TESTLOG_I("fixed_font_family default value: %{public}s", fixed_font_family.c_str()); + } + + TESTLOG_I("Set fixed_font_family to monospace."); + g_webSettings->PutFixedFontFamilyName("monospace"); + fixed_font_family = g_webSettings->FixedFontFamilyName(); + if (fixed_font_family != "monospace") { + TESTLOG_E("Error! fixed_font_family :%{public}s != monospace.", fixed_font_family.c_str()); + } else { + TESTLOG_I("fixed_font_family=%{public}s", fixed_font_family.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test212 end"); +} + +void Test213() +{ + TESTLOG_I("Test213 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool force_dark_mode_enabled = g_webSettings->DarkModeEnabled(); + if (force_dark_mode_enabled) { + TESTLOG_E("Error! force_dark_mode_enabled default value:%{public}d != false.", force_dark_mode_enabled); + } else { + TESTLOG_I("force_dark_mode_enabled default value: %{public}d", force_dark_mode_enabled); + } + + TESTLOG_I("Set force_dark_mode_enabled to true."); + g_webSettings->PutDarkModeEnabled(true); + force_dark_mode_enabled = g_webSettings->DarkModeEnabled(); + if (!force_dark_mode_enabled) { + TESTLOG_E("Error! force_dark_mode_enabled :%{public}d != true.", force_dark_mode_enabled); + } else { + TESTLOG_I("force_dark_mode_enabled=%{public}d", force_dark_mode_enabled); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test213 end"); +} + +void Test214() +{ + TESTLOG_I("Test214 start"); + + TestPrepare(); + + if (g_webSettings != nullptr) { + g_webSettings->PutJavaScriptEnabled(true); + g_webSettings->PutDomStorageEnabled(true); + + bool javascript_can_open_windows_automatically = g_webSettings->IsCreateWindowsByJavaScriptAllowed(); + if (javascript_can_open_windows_automatically) { + TESTLOG_E("Error! javascript_can_open_windows_automatically default value:%{public}d != false.", + javascript_can_open_windows_automatically); + } else { + TESTLOG_I("javascript_can_open_windows_automatically default value: %{public}d", + javascript_can_open_windows_automatically); + } + + TESTLOG_I("Set javascript_can_open_windows_automatically to true."); + g_webSettings->PutIsCreateWindowsByJavaScriptAllowed(true); + javascript_can_open_windows_automatically = g_webSettings->IsCreateWindowsByJavaScriptAllowed(); + if (!javascript_can_open_windows_automatically) { + TESTLOG_E("Error! javascript_can_open_windows_automatically :%{public}d != true.", + javascript_can_open_windows_automatically); + } else { + TESTLOG_I("javascript_can_open_windows_automatically=%{public}d", + javascript_can_open_windows_automatically); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test214 end"); +} +void Test229() +{ + TESTLOG_I("Test229 start"); + + TestPrepare(); + + if (g_webSettings != nullptr) { + g_webSettings->PutJavaScriptEnabled(true); + g_webSettings->PutDomStorageEnabled(true); + + bool javascript_can_open_windows_automatically = g_webSettings->IsCreateWindowsByJavaScriptAllowed(); + if (javascript_can_open_windows_automatically) { + TESTLOG_E("Error! javascript_can_open_windows_automatically default value:%{public}d != false.", + javascript_can_open_windows_automatically); + } else { + TESTLOG_I("javascript_can_open_windows_automatically default value: %{public}d", + javascript_can_open_windows_automatically); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test229 end"); +} + +void Test215() +{ + TESTLOG_I("Test215 start"); + + TestPrepare(); + + if (g_webSettings != nullptr) { + g_webSettings->PutIsCreateWindowsByJavaScriptAllowed(true); + g_webSettings->PutDomStorageEnabled(true); + + bool javascript_enabled = g_webSettings->IsJavaScriptAllowed(); + if (javascript_enabled) { + TESTLOG_E("Error! javascript_enabled default value:%{public}d != false.", javascript_enabled); + } else { + TESTLOG_I("javascript_enabled default value: %{public}d", javascript_enabled); + } + + TESTLOG_I("Set javascript_enabled to true."); + g_webSettings->PutJavaScriptEnabled(true); + javascript_enabled = g_webSettings->IsJavaScriptAllowed(); + if (!javascript_enabled) { + TESTLOG_E("Error! javascript_enabled :%{public}d != true.", javascript_enabled); + } else { + TESTLOG_I("javascript_enabled=%{public}d", javascript_enabled); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test215 end"); +} + +void Test230() +{ + TESTLOG_I("Test230 start"); + + TestPrepare(); + + if (g_webSettings != nullptr) { + g_webSettings->PutIsCreateWindowsByJavaScriptAllowed(true); + g_webSettings->PutDomStorageEnabled(true); + + bool javascript_enabled = g_webSettings->IsJavaScriptAllowed(); + if (javascript_enabled) { + TESTLOG_E("Error! javascript_enabled default value:%{public}d != false.", javascript_enabled); + } else { + TESTLOG_I("javascript_enabled default value: %{public}d", javascript_enabled); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test230 end"); +} + +void Test216() +{ + TESTLOG_I("Test216 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool loads_images_automatically = g_webSettings->IsImageLoadingAllowed(); + if (!loads_images_automatically) { + TESTLOG_E("Error! loads_images_automatically default value:%{public}d != true.", + loads_images_automatically); + } else { + TESTLOG_I("loads_images_automatically default value: %{public}d", loads_images_automatically); + } + + TESTLOG_I("Set loads_images_automatically to false."); + g_webSettings->PutImageLoadingAllowed(false); + loads_images_automatically = g_webSettings->IsImageLoadingAllowed(); + if (loads_images_automatically) { + TESTLOG_E("Error! loads_images_automatically :%{public}d != false.", loads_images_automatically); + } else { + TESTLOG_I("loads_images_automatically=%{public}d", loads_images_automatically); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test216 end"); +} + +void Test217() +{ + TESTLOG_I("Test217 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int minimum_font_size = g_webSettings->FontSizeLowerLimit(); + if (minimum_font_size != MINI_LOGICAL_FONT_SIZE) { + TESTLOG_E("Error! minimum_font_size default value:%{public}d != 8.", minimum_font_size); + } else { + TESTLOG_I("minimum_font_size default value: %{public}d", minimum_font_size); + } + + TESTLOG_I("Set minimum_font_size to 72."); + g_webSettings->PutFontSizeLowerLimit(DEFAULT_FONT_SIZE_MAX); + minimum_font_size = g_webSettings->FontSizeLowerLimit(); + if (minimum_font_size != DEFAULT_FONT_SIZE_MAX) { + TESTLOG_E("Error! minimum_font_size :%{public}d != 72.", minimum_font_size); + } else { + TESTLOG_I("minimum_font_size=%{public}d", minimum_font_size); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test217 end"); +} + +void Test218() +{ + TESTLOG_I("Test218 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int minimum_logical_font_size = g_webSettings->LogicalFontSizeLowerLimit(); + if (minimum_logical_font_size != MINI_FONT_SIZE) { + TESTLOG_E("Error! minimum_logical_font_size default value:%{public}d != 8.", minimum_logical_font_size); + } else { + TESTLOG_I("minimum_logical_font_size default value: %{public}d", minimum_logical_font_size); + } + + TESTLOG_I("Set minimum_logical_font_size to 72."); + g_webSettings->PutLogicalFontSizeLowerLimit(DEFAULT_FONT_SIZE_MAX); + minimum_logical_font_size = g_webSettings->LogicalFontSizeLowerLimit(); + if (minimum_logical_font_size != DEFAULT_FONT_SIZE_MAX) { + TESTLOG_E("Error! minimum_logical_font_size :%{public}d != 72.", minimum_logical_font_size); + } else { + TESTLOG_I("minimum_logical_font_size=%{public}d", minimum_logical_font_size); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test218 end"); +} + +void Test219() +{ + TESTLOG_I("Test219 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string sans_serif_font_family = g_webSettings->SansSerifFontFamilyName(); + if (sans_serif_font_family != "sans-serif") { + TESTLOG_E("Error! sans_serif_font_family default value:%{public}s != sans-serif.", + sans_serif_font_family.c_str()); + } else { + TESTLOG_I("sans_serif_font_family default value: %{public}s", sans_serif_font_family.c_str()); + } + + TESTLOG_I("Set sans_serif_font_family to sans-serif."); + g_webSettings->PutSansSerifFontFamilyName("sans-serif"); + sans_serif_font_family = g_webSettings->SansSerifFontFamilyName(); + if (sans_serif_font_family != "sans-serif") { + TESTLOG_E("Error! sans_serif_font_family :%{public}s != sans-serif.", sans_serif_font_family.c_str()); + } else { + TESTLOG_I("sans_serif_font_family=%{public}s", sans_serif_font_family.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test219 end"); +} + +void Test220() +{ + TESTLOG_I("Test220 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string serif_font_family = g_webSettings->SerifFontFamilyName(); + if (serif_font_family != "serif") { + TESTLOG_E("Error! serif_font_family default value:%{public}s != serif.", serif_font_family.c_str()); + } else { + TESTLOG_I("serif_font_family default value: %{public}s", serif_font_family.c_str()); + } + + TESTLOG_I("Set serif_font_family to serif."); + g_webSettings->PutSerifFontFamilyName("serif"); + serif_font_family = g_webSettings->SerifFontFamilyName(); + if (serif_font_family != "serif") { + TESTLOG_E("Error! serif_font_family :%{public}s != serif.", serif_font_family.c_str()); + } else { + TESTLOG_I("serif_font_family=%{public}s", serif_font_family.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test220 end"); +} + +void Test221() +{ + TESTLOG_I("Test221 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string standard_font_family = g_webSettings->StandardFontFamilyName(); + if (standard_font_family != "sans-serif") { + TESTLOG_E("Error! standard_font_family default value:%{public}s != sans-serif.", + standard_font_family.c_str()); + } else { + TESTLOG_I("standard_font_family default value: %{public}s", standard_font_family.c_str()); + } + + TESTLOG_I("Set standard_font_family to Times New Roman."); + g_webSettings->PutStandardFontFamilyName("Times New Roman"); + standard_font_family = g_webSettings->StandardFontFamilyName(); + if (standard_font_family != "Times New Roman") { + TESTLOG_E("Error! standard_font_family :%{public}s != Times New Roman.", standard_font_family.c_str()); + } else { + TESTLOG_I("standard_font_family=%{public}s", standard_font_family.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test221 end"); +} + +void Test222() +{ + TESTLOG_I("Test222 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + std::string user_agent = g_webSettings->UserAgent(); + std::string default_user_agent = g_webSettings->DefaultUserAgent(); + if (user_agent != default_user_agent) { + TESTLOG_E("Error! user_agent default value:%{public}s != %{public}s.", user_agent.c_str(), + default_user_agent.c_str()); + } else { + TESTLOG_I("user_agent default value: %{public}s", user_agent.c_str()); + } + + std::string new_user_agent = "Mozilla/5.0 (Linux; LIO-AL00 Build/HUAWEILIO-AL00; wv) " \ + "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.91 Mobile Safari/537.36"; + TESTLOG_I("Set user_agent to %{public}s.", new_user_agent.c_str()); + g_webSettings->PutUserAgent(new_user_agent); + user_agent = g_webSettings->UserAgent(); + if (user_agent != new_user_agent) { + TESTLOG_E("Error! user_agent :%{public}s != %{public}s.", user_agent.c_str(), new_user_agent.c_str()); + } else { + TESTLOG_I("user_agent=%{public}s", user_agent.c_str()); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test222 end"); +} + +void Test223() +{ + TESTLOG_I("Test223 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int text_size_percent = g_webSettings->ZoomingForTextFactor(); + if (text_size_percent != TEXT_SIZE_PERCENT_MIN) { + TESTLOG_E("Error! text_size_percent default value:%{public}d != 100.", text_size_percent); + } else { + TESTLOG_I("text_size_percent default value: %{public}d", text_size_percent); + } + + TESTLOG_I("Set text_size_percent to 500."); + g_webSettings->PutZoomingForTextFactor(TEXT_SIZE_PERCENT_MAX); + text_size_percent = g_webSettings->ZoomingForTextFactor(); + if (text_size_percent != TEXT_SIZE_PERCENT_MAX) { + TESTLOG_E("Error! text_size_percent :%{public}d != 500.", text_size_percent); + } else { + TESTLOG_I("text_size_percent=%{public}d", text_size_percent); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test223 end"); +} + +void Test224() +{ + TESTLOG_I("Test224 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool geolocation_enabled = g_webSettings->GeolocationAllowed(); + if (!geolocation_enabled) { + TESTLOG_E("Error! geolocation_enabled default value:%{public}d != true.", geolocation_enabled); + } else { + TESTLOG_I("geolocation_enabled default value: %{public}d", geolocation_enabled); + } + + TESTLOG_I("Set geolocation_enabled to false."); + g_webSettings->PutGeolocationAllowed(false); + geolocation_enabled = g_webSettings->GeolocationAllowed(); + if (geolocation_enabled) { + TESTLOG_E("Error! geolocation_enabled :%{public}d != false.", geolocation_enabled); + } else { + TESTLOG_I("geolocation_enabled=%{public}d", geolocation_enabled); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test224 end"); +} + +void Test225() +{ + TESTLOG_I("Test225 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int mixed_content_mode = g_webSettings->AccessModeForSecureOriginLoadFromInsecure(); + if (mixed_content_mode != OHOS::NWeb::NWebPreference::AccessMode::NEVER_ALLOW) { + TESTLOG_E("Error! mixed_content_mode default value:%{public}d != %{public}d.", mixed_content_mode, + OHOS::NWeb::NWebPreference::AccessMode::NEVER_ALLOW); + } else { + TESTLOG_I("mixed_content_mode default value: %{public}d", mixed_content_mode); + } + + TESTLOG_I("Set mixed_content_mode to ALWAYS_ALLOW."); + g_webSettings->PutAccessModeForSecureOriginLoadFromInsecure( + OHOS::NWeb::NWebPreference::AccessMode::ALWAYS_ALLOW); + mixed_content_mode = g_webSettings->AccessModeForSecureOriginLoadFromInsecure(); + if (mixed_content_mode != OHOS::NWeb::NWebPreference::AccessMode::ALWAYS_ALLOW) { + TESTLOG_E("Error! mixed_content_mode :%{public}d != %{public}d.", mixed_content_mode, + OHOS::NWeb::NWebPreference::AccessMode::ALWAYS_ALLOW); + } else { + TESTLOG_I("mixed_content_mode=%{public}d", mixed_content_mode); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test225 end"); +} + +void Test226() +{ + TESTLOG_I("Test226 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + int mixed_content_mode = g_webSettings->AccessModeForSecureOriginLoadFromInsecure(); + if (mixed_content_mode != OHOS::NWeb::NWebPreference::AccessMode::NEVER_ALLOW) { + TESTLOG_E("Error! mixed_content_mode default value:%{public}d != %{public}d.", mixed_content_mode, + OHOS::NWeb::NWebPreference::AccessMode::NEVER_ALLOW); + } else { + TESTLOG_I("mixed_content_mode default value: %{public}d", mixed_content_mode); + } + + TESTLOG_I("Set mixed_content_mode to COMPATIBILITY_MODE."); + g_webSettings->PutAccessModeForSecureOriginLoadFromInsecure( + OHOS::NWeb::NWebPreference::AccessMode::COMPATIBILITY_MODE); + mixed_content_mode = g_webSettings->AccessModeForSecureOriginLoadFromInsecure(); + if (mixed_content_mode != OHOS::NWeb::NWebPreference::AccessMode::COMPATIBILITY_MODE) { + TESTLOG_E("Error! mixed_content_mode :%{public}d != %{public}d.", mixed_content_mode, + OHOS::NWeb::NWebPreference::AccessMode::COMPATIBILITY_MODE); + } else { + TESTLOG_I("mixed_content_mode=%{public}d", mixed_content_mode); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test226 end"); +} + +void Test227() +{ + TESTLOG_I("Test227 start"); + + TestPrepare(); + TestWebSettingsForNormalWeb(); + + if (g_webSettings != nullptr) { + bool support_zoom = g_webSettings->ZoomingfunctionEnabled(); + if (!support_zoom) { + TESTLOG_E("Error! support_zoom default value:%{public}d != true.", support_zoom); + } else { + TESTLOG_I("support_zoom default value: %{public}d", support_zoom); + } + + TESTLOG_I("Set support_zoom to false."); + g_webSettings->PutZoomingFunctionEnabled(false); + support_zoom = g_webSettings->ZoomingfunctionEnabled(); + if (support_zoom) { + TESTLOG_E("Error! support_zoom :%{public}d != false.", support_zoom); + } else { + TESTLOG_I("support_zoom=%{public}d", support_zoom); + } + } + + g_nweb->Load(g_url); + g_window->Show(); + + TESTLOG_I("Test227 end"); +} + +void Test90() +{ + TESTLOG_I("start90"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + std::thread dump_thread([]() { + std::stringstream ss; + ss << "change_test()"; + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_FIVE)); + g_nweb->ExecuteJavaScript(ss.str()); + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end90"); +} + +void Test91() +{ + TESTLOG_I("start91"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->PutBackgroundColor(0xFFFFFF33); + g_nweb->Load(g_url); + g_window->Show(); + TESTLOG_I("end91"); +} + +void Test92() +{ + TESTLOG_I("start92"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + g_window->Show(); + TESTLOG_I("end"); +} + +void Test93() +{ + TESTLOG_I("start93"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + std::thread dump_thread([]() { + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_FIVE)); + std::string title = g_nweb->Title(); + TESTLOG_I("url tilte =%{public}s", title.c_str()); + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end93"); +} + +void Test94() +{ + TESTLOG_I("start94"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + int progress = g_nweb->PageLoadProgress(); + TESTLOG_I("progress is =%{public}d", progress); + g_window->Show(); + TESTLOG_I("end94"); +} + +void Test95() +{ + TESTLOG_I("start95"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + + std::thread dump_thread([]() { + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_FIVE)); + int content_height = g_nweb->ContentHeight(); + TESTLOG_I("Content height is =%{public}d", content_height); + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end95"); +} + +void Test96() +{ + TESTLOG_I("start96"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + float scale = g_nweb->Scale(); + TESTLOG_I("Scale is =%{public}f", scale); + g_window->Show(); + TESTLOG_I("end96"); +} + +void Test97() +{ + TESTLOG_I("start97"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + std::map extraHeaders; + extraHeaders["Authorization"] = "user-token-here"; + extraHeaders["diy"] = "diy"; + g_nweb->Load(g_url, extraHeaders); + g_window->Show(); + TESTLOG_I("end97"); +} + +void Test98() +{ + TESTLOG_I("start98"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + std::stringstream ss; + ss << "Source:
" << "source"
+        << "
"; + + g_nweb->LoadWithDataAndBaseUrl("", ss.str(), "text/html", "UTF-8", ""); + g_window->Show(); + TESTLOG_I("end98"); +} + +void Test99() +{ + TESTLOG_I("start99"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + std::stringstream ss; + ss << "Source:
" << "source"
+        << "
"; + + g_nweb->LoadWithDataAndBaseUrl("", "", "text/html", "UTF-8", "http://www.baidu.com"); + float scale = g_nweb->Scale(); + TESTLOG_I("Scale is =%{public}f", scale); + g_window->Show(); + TESTLOG_I("end99"); +} + +void Test100() +{ + TESTLOG_I("start100"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + std::shared_ptr result_callback + = std::make_shared(); + g_nweb->SetNWebJavaScriptResultCallBack(result_callback); + g_nweb->Load(g_url); + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_FIVE)); + std::string object_name = "methodtest"; + std::string object_name2 = "ohoh"; + std::vector list; + list.emplace_back("toString"); + g_nweb->RegisterArkJSfunction(object_name, list); + result_callback->RegisterArkJSfunction(object_name); + g_nweb->RegisterArkJSfunction(object_name2, list); + result_callback->RegisterArkJSfunction(object_name2); + std::thread ppthread([result_callback]() { + std::stringstream ss; + ss << "methodtest.toString()"; + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_FIVE)); + g_nweb->ExecuteJavaScript(ss.str()); + }); + ppthread.detach(); + g_window->Show(); + TESTLOG_I("end100"); +} + +void Test101() +{ + TESTLOG_I("start101"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + g_nweb->Zoom(0.1f); + g_window->Show(); + TESTLOG_I("end101"); +} + +void Test102() +{ + TESTLOG_I("start102"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + std::thread dump_thread([]() { + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_FIVE)); + g_nweb->Reload(); + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end102"); +} + +void Test103() +{ + TESTLOG_I("start103"); + if (!OHOS::NWeb::NWebAdapterHelper::Instance().Init()) { + TESTLOG_E("fail to init NWebAdapterHelper, test end"); + return; + } + + g_window = CreateWindow(); + if (g_window == nullptr) { + return; + } + g_nweb = OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(g_window.GetRefPtr(), GetInitArgs()); + if (g_nweb == nullptr) { + g_window = nullptr; + TESTLOG_E("fail to get nweb instance, test end"); + return; + } + + TESTLOG_I("Createnweb SUCCESS"); + g_nweb->SetNWebHandler(std::make_shared()); + std::string url = HasArg(ARG_URL) ? GetArgValue(ARG_URL) : "www.baidu.com"; // load www.baidu.com by default + TESTLOG_I("ready to load url=%{public}s", url.c_str()); + + TestWebSettingsForNormalWeb(); + g_nweb->Load(url); + g_window->Show(); + TESTLOG_I("end103"); +} + +void Test104() +{ + TESTLOG_I("start104"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + std::string data = "

LoadData test 104

"; + + g_nweb->LoadWithData(data, "text/html", "UTF-8"); + g_window->Show(); + TESTLOG_I("end104"); +} + +class JavaScriptResultCb : public OHOS::NWeb::NWebValueCallback { + void OnReceiveValue(std::string result) override + { + TESTLOG_I("JavaScript execute result = %{public}s", result.c_str()); + } +}; + +void Test105() +{ + TESTLOG_I("start105"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + g_window->Show(); + std::string ss = "(function() { console.log('ExecuteJavaScript'); return 'ExecuteJavaScript'; })()"; + std::shared_ptr> callback = std::make_shared(); + g_nweb->ExecuteJavaScript(ss, callback); + TESTLOG_I("end105"); +} + +void Test106() +{ + TESTLOG_I("start106"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + g_window->Show(); + // load execute_javaScript_test.html, and will invoke ExecuteJavaScript when NWebHandlerImplTest::OnPageFinished + TESTLOG_I("end106"); +} + +void Test107() +{ + TESTLOG_I("Test107 start"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + std::string testUrl = "https://image.baidu.com/search/down?tn=download&word=download&ie" + "=utf8&fr=detail&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252" + "F%252Fimgm3.cnmo.com%252Fuser%252Farticle%252F147422%252Forigin%252Farad9U4eIRFo.jpeg%" + "26refer%3Dhttp%253A%252F%252Fimgm3.cnmo.com%26app%3D2002%26size%3Df9999%2C10000%26q%3D" + "a80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1647499762%26t%3Dee4725de24c35d3a273abb8bcfc" + "157e7&thumburl=https%3A%2F%2Fimg1.baidu.com%2Fit%2Fu%3D2016552768%2C2104120132%26fm%3D" + "253%26fmt%3Dauto%26app%3D120%26f%3DJPEG%3Fw%3D683%26h%3D393"; + TESTLOG_I("Test107 SetDownloadListener begin"); + g_nweb->PutDownloadCallback(std::make_shared()); + TESTLOG_I("Test107 SetDownloadListener end"); + g_nweb->Load(testUrl); + g_window->Show(); + TESTLOG_I("end"); +} + +void Test108() +{ + TESTLOG_I("start108"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + g_window->Show(); + std::thread test_thread([]() { + int cmd; + while (std::cin >> cmd) { + switch (cmd) { + case 0: + TESTLOG_I("IsNavigatebackwardAllowed:%{public}d", g_nweb->IsNavigatebackwardAllowed()); + break; + case 1: + TESTLOG_I("IsNavigateForwardAllowed:%{public}d", g_nweb->IsNavigateForwardAllowed()); + break; + case STEP_TWO: + int steps; + std::cin >> steps; + TESTLOG_I("CanNavigateBackOrForward:%{public}d", g_nweb->CanNavigateBackOrForward(steps)); + break; + default: + return; + } + } + }); + test_thread.detach(); + TESTLOG_I("end108"); +} + +void Test109() +{ + TESTLOG_I("start109"); + TestPrepareWithClient(std::make_shared( + OHOS::NWeb::NWebJSDialogImplTest::CONFIRM + )); + TestWebSettingsForNormalWeb(); + g_nweb->Load("file:///data/local/cef/cef_user_data/JsDiaTest.html"); + g_window->Show(); + TESTLOG_I("end109"); +} + +void Test110() +{ + TESTLOG_I("start110"); + TestPrepareWithClient(std::make_shared( + OHOS::NWeb::NWebJSDialogImplTest::CANCEL + )); + TestWebSettingsForNormalWeb(); + g_nweb->Load("file:///data/local/cef/cef_user_data/JsDiaTest.html"); + g_window->Show(); + TESTLOG_I("end110"); +} + +void Test111() +{ + TESTLOG_I("start111"); + TestPrepareWithClient(std::make_shared( + OHOS::NWeb::NWebJSDialogImplTest::CONFIRM + )); + TestWebSettingsForNormalWeb(); + g_nweb->Load("file:///data/local/cef/cef_user_data/JsBeforeUnloadTest.html"); + std::thread dump_thread([]() { + std::this_thread::sleep_for(std::chrono::seconds(STEP_TWO)); + g_nweb->Reload(); + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end111"); +} + +void Test112() +{ + TESTLOG_I("start112"); + TestPrepareWithClient(std::make_shared( + OHOS::NWeb::NWebJSDialogImplTest::CANCEL + )); + TestWebSettingsForNormalWeb(); + g_nweb->Load("file:///data/local/cef/cef_user_data/JsBeforeUnloadTest.html"); + std::thread dump_thread([]() { + std::this_thread::sleep_for(std::chrono::seconds(STEP_TWO)); + g_nweb->Reload(); + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end112"); +} + +void Test113() +{ + TESTLOG_I("start113"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + + g_nweb->Load(g_url); + std::thread dump_thread([]() { + for (int i = 0; i < TEXT_SIZE_PERCENT_MIN; i++) { + std::this_thread::sleep_for(std::chrono::seconds(TIME_SECONDS_THREE)); + OHOS::NWeb::HitTestResult data = g_nweb->GetHitTestResult(); + TESTLOG_I("type = %{public}d", data.GetType()); + TESTLOG_I("extra = %{public}s", data.GetExtra().c_str()); + } + }); + dump_thread.detach(); + g_window->Show(); + TESTLOG_I("end113"); +} + +void Test301() +{ + TESTLOG_I("start301"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + g_window->Show(); + std::shared_ptr setCookieCallback = + std::make_shared(); + std::shared_ptr existCookieCallback = + std::make_shared(); + std::shared_ptr storeCookieCallback = + std::make_shared(); + std::shared_ptr deleteCookieCallback = + std::make_shared(); + std::shared_ptr returnCookieCallback = + std::make_shared(); + OHOS::NWeb::NWebCookieManager::GetInstance()->DeleteCookieEntirely(deleteCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->ExistCookies(existCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->SetCookie( + "http://www.baidu.com", + "a=b", + setCookieCallback); + OHOS::NWeb::NWebCookieManager::GetInstance()->SetCookie( + "http://www.baidu.com", + "c=d", + setCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->ExistCookies(existCookieCallback); + OHOS::NWeb::NWebCookieManager::GetInstance()->ReturnCookie( + "http://www.baidu.com", + returnCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->DeleteCookieEntirely(deleteCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->ExistCookies(existCookieCallback); + TESTLOG_I("end301"); +} + +void Test302() +{ + TESTLOG_I("start302"); + TestPrepare(); + TestWebSettingsForNormalWeb(); + g_nweb->Load(g_url); + g_window->Show(); + std::shared_ptr setCookieCallback = + std::make_shared(); + std::shared_ptr existCookieCallback = + std::make_shared(); + std::shared_ptr storeCookieCallback = + std::make_shared(); + std::shared_ptr deleteCookieCallback = + std::make_shared(); + std::shared_ptr returnCookieCallback = + std::make_shared(); + OHOS::NWeb::NWebCookieManager::GetInstance()->DeleteCookieEntirely(deleteCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->ExistCookies(existCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->SetCookie( + "http://www.baidu.com", + "a=b; Expires=Wed, 5 Oct 2022 07:28:00 GMT; path=/; domain=www.baidu.com", + setCookieCallback); + OHOS::NWeb::NWebCookieManager::GetInstance()->SetCookie( + "http://www.baidu.com", + "c=d; path=/; domain=www.baidu.com", + setCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->ExistCookies(existCookieCallback); + OHOS::NWeb::NWebCookieManager::GetInstance()->ReturnCookie( + "http://www.baidu.com", + returnCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->DeleteSessionCookies(deleteCookieCallback); + std::this_thread::sleep_for(std::chrono::seconds(1)); + OHOS::NWeb::NWebCookieManager::GetInstance()->ReturnCookie( + "http://www.baidu.com", + returnCookieCallback); + OHOS::NWeb::NWebCookieManager::GetInstance()->ExistCookies(existCookieCallback); + TESTLOG_I("end302"); +} + +struct OhosNWebTest { + int32_t id; + const char *desc; + void (*func)(); +}; + +#define ADD_TEST(tests, id_, desc_) \ + tests.push_back({ \ + .id = id_, \ + .desc = desc_, \ + .func = Test##id_ }) + +void InitTest(std::vector &tests) +{ + ADD_TEST(tests, 1, "nweb use window"); + ADD_TEST(tests, 90, "ExecuteJavaScript"); + ADD_TEST(tests, 91, "SetBackgroundColor(0xFFFFFF33)"); + ADD_TEST(tests, 92, "nweb handle"); + ADD_TEST(tests, 93, "gettitle"); + ADD_TEST(tests, 94, "getprogress"); + ADD_TEST(tests, 95, "GetContentHeight"); + ADD_TEST(tests, 96, "GetScale"); + ADD_TEST(tests, 97, "LoadUrl(url,extraHeaders)"); + ADD_TEST(tests, 98, "LoadWithDataAndBaseUrl"); + ADD_TEST(tests, 99, "LoadWithDataAndBaseUrl history"); + ADD_TEST(tests, 100, "ark js"); + ADD_TEST(tests, 101, "Zoomby"); + ADD_TEST(tests, 102, "reload"); + ADD_TEST(tests, 103, "nweb client ShouldInterceptRequest"); + ADD_TEST(tests, 104, "LoadwithData test"); + ADD_TEST(tests, 105, "ExecuteJavaScript with result callback, console output"); + ADD_TEST(tests, 106, "ExecuteJavaScript with result callback, change html item by js function"); + ADD_TEST(tests, 107, "Test websettings api:SetDownloadlistener"); + ADD_TEST(tests, 108, "CanGoBackOrForward"); + ADD_TEST(tests, 109, "js dialog confirm"); + ADD_TEST(tests, 110, "js dialog cancel"); + ADD_TEST(tests, 111, "js beforeUnload confirm"); + ADD_TEST(tests, 112, "js beforeUnload cancel"); + ADD_TEST(tests, 113, "GetHitTestResult"); + ADD_TEST(tests, 200, "Test websettings api:PutEnableContentAccess and EnableContentAccess"); + ADD_TEST(tests, 201, "Test websettings api:PutEnableRawFileAccess and EnableRawFileAccess"); + ADD_TEST(tests, 202, "Test websettings api:PutEnableRawFileAccessFromFileURLs and EnableRawFileAccessFromFileURLs"); + ADD_TEST(tests, 203, "Test websettings api:PutEnableUniversalAccessFromFileURLs and " \ + "EnableUniversalAccessFromFileURLs"); + ADD_TEST(tests, 204, "Test websettings api:PutLoadImageFromNetworkDisabled and IsLoadImageFromNetworkDisabled"); + ADD_TEST(tests, 205, "Test websettings api:PutCursiveFontFamilyName and CursiveFontFamilyName"); + ADD_TEST(tests, 206, "Test websettings api:PutDatabaseAllowed and IsDataBaseEnabled"); + ADD_TEST(tests, 207, "Test websettings api:PutDefaultFixedFontSize and DefaultFixedFontSize"); + ADD_TEST(tests, 208, "Test websettings api:PutDefaultFontSize and DefaultFontSize"); + ADD_TEST(tests, 209, "Test websettings api:PutDefaultTextEncodingFormat and DefaultTextEncodingFormat"); + ADD_TEST(tests, 210, "Test websettings api:PutDomStorageEnabled and IsDomStorageEnabled"); + ADD_TEST(tests, 211, "Test websettings api:PutFantasyFontFamilyName and FantasyFontFamilyName"); + ADD_TEST(tests, 212, "Test websettings api:PutFixedFontFamilyName and FixedFontFamilyName"); + ADD_TEST(tests, 213, "Test websettings api:PutDarkModeEnabled and DarkModeEnabled"); + ADD_TEST(tests, 214, "Test websettings api:PutIsCreateWindowsByJavaScriptAllowed and " \ + "IsCreateWindowsByJavaScriptAllowed"); + ADD_TEST(tests, 215, "Test websettings api:PutJavaScriptEnabled and IsJavaScriptAllowed"); + ADD_TEST(tests, 216, "Test websettings api:PutImageLoadingAllowed and IsImageLoadingAllowed"); + ADD_TEST(tests, 217, "Test websettings api:PutFontSizeLowerLimit and FontSizeLowerLimit"); + ADD_TEST(tests, 218, "Test websettings api:PutLogicalFontSizeLowerLimit and LogicalFontSizeLowerLimit"); + ADD_TEST(tests, 219, "Test websettings api:PutSansSerifFontFamilyName and SansSerifFontFamilyName"); + ADD_TEST(tests, 220, "Test websettings api:PutSerifFontFamilyName and SerifFontFamilyName"); + ADD_TEST(tests, 221, "Test websettings api:PutStandardFontFamilyName and StandardFontFamilyName"); + ADD_TEST(tests, 222, "Test websettings api:PutUserAgent and UserAgent"); + ADD_TEST(tests, 223, "Test websettings api:PutZoomingForTextFactor and ZoomingForTextFactor"); + ADD_TEST(tests, 224, "Test websettings api:PutGeolocationAllowed and GeolocationAllowed"); + ADD_TEST(tests, 225, "Test websettings api:PutAccessModeForSecureOriginLoadFromInsecure and " \ + "AccessModeForSecureOriginLoadFromInsecure"); + ADD_TEST(tests, 226, "Test websettings api:PutAccessModeForSecureOriginLoadFromInsecure and " \ + "AccessModeForSecureOriginLoadFromInsecure"); + ADD_TEST(tests, 227, "Test websettings api:PutZoomingFunctionEnabled and ZoomingfunctionEnabled"); + ADD_TEST(tests, 228, "Test websettings api:PutDomStorageEnabled and IsDomStorageEnabled"); + ADD_TEST(tests, 229, "Test websettings api:PutIsCreateWindowsByJavaScriptAllowed and " \ + "IsCreateWindowsByJavaScriptAllowed"); + ADD_TEST(tests, 230, "Test websettings api:PutJavaScriptEnabled and IsJavaScriptAllowed"); + ADD_TEST(tests, 231, "Test websettings api:PutDefaultTextEncodingFormat and DefaultTextEncodingFormat"); + ADD_TEST(tests, 301, "Test cookieManager session cookie"); + ADD_TEST(tests, 302, "Test cookieManager has expire cookie"); +} + +void Usage(const char *argv0, const std::vector &tests) +{ + TESTLOG_I("Usage: %{public}s test_id", argv0); + for (auto it = tests.begin(); it != tests.end(); it++) { + TESTLOG_I("test %{public}d: %{public}s", it->id, it->desc); + } +} +} // anonymous namespace + +int32_t main(int32_t argc, const char * const argv[]) +{ + TESTLOG_I("ohos nweb test start"); + + std::vector tests; + InitTest(tests); + + if (argc <= 1) { + Usage(argv[0], tests); + return 0; + } + + int32_t testcase = -1; + int ret = sscanf_s(argv[1], "%d", &testcase); + if (ret == 0) { + Usage(argv[0], tests); + return 1; + } + + InitArgs(argc, argv); + + auto runner = AppExecFwk::EventRunner::Create(false); + g_handler = std::make_shared(runner); + auto condition = [testcase] (auto &item) { return item.id == testcase; }; + auto test = std::find_if(tests.begin(), tests.end(), condition); + if (test != tests.end()) { + g_handler->PostTask(test->func); + TESTLOG_I("%{public}d %{public}s run!", test->id, test->desc); + } else { + TESTLOG_E("not found test %{public}d", testcase); + return 0; + } + + runner->Run(); + return 0; +} diff --git a/test/ohos_nweb/utils.h b/test/ohos_nweb/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..782c5c2c4fe8eaf98703da72de4ee629e8ca0871 --- /dev/null +++ b/test/ohos_nweb/utils.h @@ -0,0 +1,95 @@ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NWEB_UTILS_H +#define NWEB_UTILS_H + +#include +#include "hilog/log.h" + +namespace OHOS::NWeb { + const std::string EXECUTE_JAVASCRIPT_CALLBACK_HTML = "execute_javaScript_test.html"; + + constexpr uint8_t BITS_PER_PIXEL = 4; /* 4 bits per pixel */ + constexpr uint8_t LAST_FIRST_CHANNEL_OF_PIXEL = 1; + constexpr uint8_t LAST_SECOND_CHANNEL_OF_PIXEL = 2; + constexpr uint8_t LAST_THIRD_CHANNEL_OF_PIXEL = 3; + struct BmpFileHeader { + unsigned int bf_size; /* Size of file */ + unsigned short bf_reserved_1 = 0; /* Reserved */ + unsigned short bf_reserved_2 = 0; /* ... */ + unsigned int bf_offbits = 0x36; /* Offset to bitmap data */ + }; + /**** BMP file info structure ****/ + struct BmpInfoHeader { + unsigned int bi_size; /* Size of info header */ + int bi_width; /* Width of image */ + int bi_height; /* Height of image */ + unsigned short bi_planes = 1; /* Number of color planes */ + unsigned short bi_bit_count = 24; /* 24 Number of bits per pixel */ + unsigned int bi_compression = 0; /* Type of compression to use */ + unsigned int bi_size_image = 0; /* Size of image data */ + int bi_x_pixels_per_meter = 5000; /* 5000 X pixels per meter */ + int bi_y_pixels_per_meter = 5000; /* 5000 Y pixels per meter */ + unsigned int bi_colors_used = 0; /* Number of colors used */ + unsigned int bi_colors_important = 0; /* Number of important colors */ + }; + + inline void RgbaToRgb(char* buf, int width, int height) + { + char* p_rgba = buf; + char* p_rgb = buf; + uint64_t len = width * height * BITS_PER_PIXEL; + for (uint64_t i = 0; i < len; i++, p_rgba++) { + if (i % BITS_PER_PIXEL == LAST_THIRD_CHANNEL_OF_PIXEL) { + // check alpha value, if 0, set related color to white + if (buf[i] == 0) { + *(p_rgb - LAST_THIRD_CHANNEL_OF_PIXEL) = 0xff; + *(p_rgb - LAST_SECOND_CHANNEL_OF_PIXEL) = 0xff; + *(p_rgb - 1) = 0xff; + } + continue; + } + *p_rgb++ = *p_rgba; + if (i % BITS_PER_PIXEL == LAST_SECOND_CHANNEL_OF_PIXEL) { + char tmp = *(p_rgb - 1); + *(p_rgb - 1) = *(p_rgb - LAST_THIRD_CHANNEL_OF_PIXEL); + *(p_rgb - LAST_THIRD_CHANNEL_OF_PIXEL) = tmp; + } + } + } + + inline void WriteToBmp(const std::string& filename, char* buf, int width, int height) + { + BmpFileHeader bmp_file_header; + BmpInfoHeader bmp_info_header; + // Magic number for file. It does not fit in the header structure + // due to alignment requirements, so put it outside + unsigned short bmp_file_type = 0x4d42; + constexpr int rgb_bits_per_pixel = LAST_THIRD_CHANNEL_OF_PIXEL; + int rgb_buf_size = width * height * rgb_bits_per_pixel; + bmp_file_header.bf_size = + sizeof(BmpFileHeader) + sizeof(BmpInfoHeader) + rgb_buf_size; + bmp_info_header.bi_size = sizeof(BmpInfoHeader); + bmp_info_header.bi_width = width; + bmp_info_header.bi_height = -height; + FILE* file = fopen(filename.c_str(), "wb"); + if (!file) { + return; + } + // Write headers + (void)fwrite(&bmp_file_type, sizeof(bmp_file_type), 1, file); + (void)fwrite(&bmp_file_header, sizeof(bmp_file_header), 1, file); + (void)fwrite(&bmp_info_header, sizeof(bmp_info_header), 1, file); + (void)fwrite(buf, rgb_buf_size, 1, file); + (void)fclose(file); + } + + inline void DumpToBmp(const std::string& filename, char* buf, int width, int height) + { + RgbaToRgb(buf, width, height); + WriteToBmp(filename, buf, width, height); + } +} +#endif // NWEB_UTILS_H \ No newline at end of file