Add 9th 0907 code

Signed-off-by: @chuangda_1 <fangwanning@huawei.com>
This commit is contained in:
@chuangda_1 2022-09-07 21:43:33 +08:00
parent 9367436bc8
commit 53876efc14
119 changed files with 91 additions and 13449 deletions

View File

@ -38,8 +38,7 @@ PrintPageSize PrintPageSize::GetPageSize(PageSizeId id)
{
uint32_t pageSizeId = (uint32_t)id;
if (pageSizeId < (uint32_t)sizeof(PAGE_SIZE_TABLE)) {
std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>>::iterator iter;
iter = pageSize_.find(PAGE_SIZE_TABLE[pageSizeId]);
auto iter = pageSize_.find(PAGE_SIZE_TABLE[pageSizeId]);
if (iter != pageSize_.end()) {
return *(iter->second);
}

View File

@ -36,6 +36,7 @@ public:
~JsPrintCallback() = default;
NativeValue *Exec(NativeValue *jsObj, const std::string &name, NativeValue *const *argv = nullptr, size_t argc = 0,
bool isSync = true);
void SetContainer(uv_work_t& jsWorker,JsPrintCallback::Container container);
private:
struct Container {

View File

@ -109,7 +109,8 @@ public:
private:
NativeValue *CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0);
void RegisterAllCallback();
void RegisterAllCallbackSecond();
void RegisterAllCallbackThird()
void GetSrcPath(std::string &srcPath);
JsRuntime &jsRuntime_;

View File

@ -52,8 +52,6 @@ NativeValue *JsPrintCallback::Exec(
return nullptr;
}
PRINT_HILOGD("%{public}s callback in", name.c_str());
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(reinterpret_cast<napi_env>(nativeEngine), &loop);
@ -66,18 +64,7 @@ NativeValue *JsPrintCallback::Exec(
PRINT_HILOGE("Failed to create uv work");
return nullptr;
}
container_.self = shared_from_this();
container_.nativeEngine = nativeEngine;
container_.jsObj = jsObj;
container_.jsMethod = method;
container_.argv = argv;
container_.argc = argc;
container_.jsResult = nullptr;
container_.isSync = isSync;
container_.isCompleted = false;
jsWorker_->data = &container_;
SetContainer(jsWorker_, container_);
uv_queue_work(
loop, jsWorker_, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
@ -106,5 +93,18 @@ NativeValue *JsPrintCallback::Exec(
}
return nullptr;
}
void JsPrintCallback::SetContainer(uv_work_t& jsWorker,JsPrintCallback::Container container)
{
container.self = shared_from_this();
container.nativeEngine = nativeEngine;
container.jsObj = jsObj;
container.jsMethod = method;
container.argv = argv;
container.argc = argc;
container.jsResult = nullptr;
container.isSync = isSync;
container.isCompleted = false;
jsWorker_->data = &container;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -66,7 +66,7 @@ void JsPrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
HandleScope handleScope(jsRuntime_);
auto &engine = jsRuntime_.GetNativeEngine();
jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath);
jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath, abilityInfo_->hapPath);
if (jsObj_ == nullptr) {
PRINT_HILOGE("Failed to get jsObj_");
return;
@ -87,7 +87,6 @@ void JsPrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
NativeValue *contextObj = CreateJsPrintExtensionContext(engine, context);
auto shellContextRef = jsRuntime_.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE);
contextObj = shellContextRef->Get();
PRINT_HILOGD("JsPrintExtension::Init Bind.");
context->Bind(jsRuntime_, shellContextRef.release());
PRINT_HILOGD("JsPrintExtension::SetProperty.");
obj->SetProperty("context", contextObj);
@ -300,6 +299,11 @@ void JsPrintExtension::RegisterAllCallback()
callback->Exec(value, "onConnectPrinter", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
RegisterAllCallbackSecond();
RegisterAllCallbackThird();
}
void JsPrintExtension::RegisterAllCallbackSecond()
{
PrintManagerClient::GetInstance()->RegisterExtCallback(
PRINT_EXTCB_DISCONNECT_PRINTER, [](uint32_t printId) -> bool {
PRINT_HILOGD("Disconnect Printer");
@ -334,12 +338,14 @@ void JsPrintExtension::RegisterAllCallback()
napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(jobObject);
NativeValue *arg[] = { nativeJob };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onCancelPrintJob", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
}
void JsPrintExtension::RegisterAllCallbackThird()
{
PrintManagerClient::GetInstance()->RegisterExtCallback(
PRINT_EXTCB_REQUEST_CAP, [](uint32_t printId, PrinterCapability &cap) -> bool {
PRINT_HILOGD("Request Capability");
@ -368,7 +374,6 @@ void JsPrintExtension::RegisterAllCallback()
napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(jobObject);
NativeValue *arg[] = { nativeJob };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onRequestPreview", arg, NapiPrintUtils::ARGC_ONE);

View File

@ -160,7 +160,6 @@ private:
PRINT_HILOGD("%{public}s called, the second parameter is invalid.", __func__);
return engine.CreateUndefined();
}
PRINT_HILOGD("%{public}d accountId:", accountId);
unwrapArgc++;
AAFwk::StartOptions startOptions;
@ -176,7 +175,6 @@ private:
PRINT_HILOGD("startAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
@ -466,7 +464,6 @@ NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine, std::shared_ptr
// make handler
handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
#if 0
const char *moduleName = "JsPrintExtensionContext";
BindNativeFunction(engine, *object, "startAbility", moduleName, JsPrintExtensionContext::StartAbility);
BindNativeFunction(engine, *object, "terminateSelf", moduleName, JsPrintExtensionContext::TerminateAbility);
@ -476,15 +473,7 @@ NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine, std::shared_ptr
engine, *object, "startAbilityWithAccount", moduleName, JsPrintExtensionContext::StartAbilityWithAccount);
BindNativeFunction(
engine, *object, "connectAbilityWithAccount", moduleName, JsPrintExtensionContext::ConnectAbilityWithAccount);
#else
BindNativeFunction(engine, *object, "startAbility", JsPrintExtensionContext::StartAbility);
BindNativeFunction(engine, *object, "terminateSelf", JsPrintExtensionContext::TerminateAbility);
BindNativeFunction(engine, *object, "connectAbility", JsPrintExtensionContext::ConnectAbility);
BindNativeFunction(engine, *object, "disconnectAbility", JsPrintExtensionContext::DisconnectAbility);
BindNativeFunction(engine, *object, "startAbilityWithAccount", JsPrintExtensionContext::StartAbilityWithAccount);
BindNativeFunction(
engine, *object, "connectAbilityWithAccount", JsPrintExtensionContext::ConnectAbilityWithAccount);
#endif
if (context) {
PRINT_HILOGD("Set ExtensionAbilityInfo Property");
auto abilityInfo = context->GetAbilityInfo();

View File

@ -13,13 +13,67 @@
import("//build/ohos.gni")
################################################################################
group("print_packages") {
if (is_standard_system) {
deps = [
"etc/init:printservice.rc",
"profile:print_sa_profiles",
"services:print_service",
]
}
config("print_service_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
]
cflags_cc = [ "-fexceptions" ]
}
ohos_shared_library("print_service") {
sources = [
"src/print_service_ability.cpp",
"src/print_service_stub.cpp",
"src/print_callback_proxy.cpp",
"src/print_service_manager.cpp",
"src/print_extension_callback_proxy.cpp",
]
public_configs = [
"//commonlibrary/c_utils/base:utils_config",
":print_service_config",
]
include_dirs = [
"//commonlibrary/c_utils/base/include",
"//utils/system/safwk/native/include",
"//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient/include",
"//base/notification/distributed_notification_service/interfaces/inner_api",
"//base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include",
"//base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter",
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/utils/include",
]
deps = [
"//base/notification/distributed_notification_service/frameworks/ans:ans_innerkits",
"//base/telephony/core_service/interfaces/innerkits:tel_core_service_api",
"//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient:net_conn_manager_if",
"//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//base/print/print/frameworks/innerkitsimpl:print_client",
]
external_deps = [
"ability_base:base",
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"drivers_interface_ril:hril_innerkits",
"eventhandler:libeventhandler",
"hisysevent_native:libhisysevent",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
"init:libbegetutil",
"ipc:ipc_core",
"multimedia_image_standard:image_native",
"os_account:os_account_innerkits",
"relational_store:native_rdb",
]
subsystem_name = "print"
part_name = "print"
}

View File

@ -1,177 +0,0 @@
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

View File

@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<licensefile>LICENSE</licensefile>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files that do not need to be scanned">
<filteritem type="filename" name="*.cfg" desc="cfg no need to add policy"/>
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies" >
<filteritem type="filename" name="*.png" desc="png for hap"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

View File

@ -1,63 +0,0 @@
{
"name": "@ohos/print",
"description": "Provide printer management and print ability for 3rd party app",
"version": "3.1",
"license": "Apache License 2.0",
"publishAs": "code-segment",
"segment": {
"destPath": "base/print/print"
},
"dirs": {},
"scripts": {},
"component": {
"name": "print",
"subsystem": "print",
"syscap": [
"SystemCapability.Print.Print"
],
"features": [
],
"adapted_system_type": [
"standard"
],
"rom":"2MB",
"ram":"10MB",
"deps": {
"components": [
"ability_manager",
"aafwk_standard",
"appexecfwk_standard",
"common_event_service",
"distributeddatamgr",
"hisysevent_native",
"hiviewdfx_hilog_native",
"ipc",
"safwk",
"samgr_standard",
"startup_l2",
"utils_base"
],
"third_party": [
]
},
"build": {
"sub_component": [
"//base/print/print/interfaces/kits/napi:print_napi",
"//base/print/print/interfaces/kits/jsnapi/extension:printextension_napi",
"//base/print/print/interfaces/kits/jsnapi/extensionctx:printextensioncontext_napi",
"//base/print/print/frameworks/innerkitsimpl:print_client",
"//base/print/print/frameworks/kits/extension:print_extension",
"//base/print/print/frameworks/kits/extension:print_extension_module",
"//base/print/print/services:print_service",
"//base/print/print/etc/init:printservice.rc",
"//base/print/print/profile:print_sa_profiles"
],
"test": [
"//base/print/print/interfaces/kits/napi/test:unittest"
]
},
"hisysevent_config": [
"//base/print/print/hisysevent.yaml"
]
}
}

View File

@ -1,23 +0,0 @@
# 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")
################################################################################
ohos_prebuilt_etc("printservice.rc") {
source = "printservice.cfg"
relative_install_dir = "init"
part_name = "print"
subsystem_name = "print"
}

View File

@ -1,10 +0,0 @@
{
"services" : [{
"name" : "print_service",
"path" : ["/system/bin/sa_main", "/system/profile/print_service.xml"],
"uid" : "print",
"gid" : ["print", "shell"],
"secon" : "u:r:print_service:s0"
}
]
}

View File

@ -1,20 +0,0 @@
# 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.
on boot
start print_service
service print_service /system/bin/sa_main /system/profile/print_service.xml
class z_core
user system
group system shell
seclabel u:r:print_service:s0

View File

@ -1,87 +0,0 @@
# 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("//base/request/request/request_aafwk.gni")
import("//build/ohos.gni")
config("print_interfaces_kits_napi_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags_cc = [ "-fexceptions" ]
}
ohos_shared_library("print_client") {
include_dirs = [
"//foundation/arkui/ace_engine/frameworks/base/utils",
"//foundation/arkui/napi",
"//foundation/arkui/napi/interfaces/kits",
"//foundation/arkui/napi/interfaces/inner_api",
"//third_party/node/src",
"//third_party/curl/include",
"${ability_runtime_services_path}/common/include",
"//utils/system/safwk/native/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/app/",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_services_path}/abilitymgr/include",
"${ability_runtime_inner_api_path}/ability_manager/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/Isamgr",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//base/print/print/utils/include",
]
public_configs = [ ":print_interfaces_kits_napi_config" ]
sources = [
"src/napi_print_utils.cpp",
"src/print_base_notify.cpp",
"src/print_callback_stub.cpp",
"src/print_extension_callback_stub.cpp",
"src/print_extension_info.cpp",
"src/print_fail_notify.cpp",
"src/print_job.cpp",
"src/print_manager_client.cpp",
"src/print_margin.cpp",
"src/print_notify.cpp",
"src/print_page_size.cpp",
"src/print_preview_attribute.cpp",
"src/print_progress_notify.cpp",
"src/print_range.cpp",
"src/print_resolution.cpp",
"src/print_sa_death_recipient.cpp",
"src/print_service_proxy.cpp",
"src/print_sync_load_callback.cpp",
"src/printer_capability.cpp",
"src/printer_info.cpp",
]
deps = [
"//foundation/arkui/napi:ace_napi",
"//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"ability_runtime:data_ability_helper",
"ability_runtime:napi_base_context",
"c_utils:utils",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"preferences:native_preferences",
"relational_store:native_appdatafwk",
"relational_store:native_dataability",
"relational_store:native_rdb",
]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -1,33 +0,0 @@
/*
* 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 IPRINT_CALLBACK_H
#define IPRINT_CALLBACK_H
#include "iremote_broker.h"
#include "iremote_object.h"
namespace OHOS::Print {
class IPrintCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print.IPrintCallback");
virtual void OnCallBack(MessageParcel &data) = 0;
};
enum {
PRINT_NOTIFY,
};
} // namespace OHOS::Print
#endif // IPRINT_CALLBACK_H

View File

@ -1,52 +0,0 @@
/*
* 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 IPRINT_EXTENSION_CALLBACK_H
#define IPRINT_EXTENSION_CALLBACK_H
#include "iremote_broker.h"
#include "iremote_object.h"
#include "print_job.h"
namespace OHOS::Print {
class IPrintExtensionCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print.IPrintExtensionCallback");
virtual bool OnCallback() = 0;
virtual bool OnCallback(uint32_t printerId) = 0;
virtual bool OnCallback(const PrintJob &job) = 0;
virtual bool OnCallback(uint32_t printerId, MessageParcel &reply) = 0;
};
enum {
PRINT_EXTCB,
PRINT_EXTCB_PRINTER,
PRINT_EXTCB_PRINTJOB,
PRINT_EXTCB_PRINTCAPABILITY,
};
enum {
PRINT_EXTCB_START_DISCOVERY,
PRINT_EXTCB_STOP_DISCOVERY,
PRINT_EXTCB_CONNECT_PRINTER,
PRINT_EXTCB_DISCONNECT_PRINTER,
PRINT_EXTCB_START_PRINT,
PRINT_EXTCB_CANCEL_PRINT,
PRINT_EXTCB_REQUEST_CAP,
PRINT_EXTCB_REQUEST_PREVIEW,
PRINT_EXTCB_MAX,
};
} // namespace OHOS::Print
#endif // IPRINT_EXTCB_H

View File

@ -1,76 +0,0 @@
/*
* 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 PRINT_SERVICE_INTERFACE_H
#define PRINT_SERVICE_INTERFACE_H
#include <string>
#include "iprint_callback.h"
#include "iprint_extension_callback.h"
#include "iremote_broker.h"
#include "print_extension_info.h"
#include "print_job.h"
#include "printer_info.h"
namespace OHOS::Print {
class IPrintService : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print. IPrintService");
virtual int32_t StartPrint() = 0;
virtual bool ConnectPrinter(uint32_t printerId) = 0;
virtual bool DisconnectPrinter(uint32_t printerId) = 0;
virtual bool StartDiscoverPrinter(const std::vector<uint32_t> &extensionList) = 0;
virtual bool StopDiscoverPrinter() = 0;
virtual bool QueryAllExtension(std::vector<PrintExtensionInfo> &arrayExtensionInfo) = 0;
virtual bool StartPrintJob(const PrintJob &jobinfo) = 0;
virtual bool CancelPrintJob(const PrintJob &jobinfo) = 0;
virtual bool AddPrinters(const std::vector<PrinterInfo> &arrayPrintInfo) = 0;
virtual bool RemovePrinters(const std::vector<PrinterInfo> &arrayPrintInfo) = 0;
virtual bool UpdatePrinterState(uint32_t printerId, uint32_t state) = 0;
virtual bool UpdatePrinterJobState(uint32_t jobId, uint32_t state) = 0;
virtual bool RequestPreview(const PrintJob &jobinfo, std::string &previewResult) = 0;
virtual bool QueryPrinterCapability(uint32_t printerId, PrinterCapability &printerCapability) = 0;
virtual bool CheckPermission() = 0;
virtual bool On(
const std::string &type, uint32_t &state, PrinterInfo &info, const sptr<IPrintCallback> &listener) = 0;
virtual bool Off(const std::string &type) = 0;
virtual bool RegisterExtCallback(uint32_t callbackId, const sptr<IPrintExtensionCallback> &listener) = 0;
virtual bool UnregisterAllExtCallback() = 0;
};
enum {
CMD_START_PRINT,
CMD_CONNECTPRINTER,
CMD_DISCONNECTPRINTER,
CMD_STARTDISCOVERPRINTER,
CMD_STOPDISCOVERPRINTER,
CMD_QUERYALLEXTENSION,
CMD_STARTPRINTJOB,
CMD_CANCELPRINTJOB,
CMD_ADDPRINTERS,
CMD_REMOVEPRINTERS,
CMD_UPDATEPRINTERSTATE,
CMD_UPDATEPRINTERJOBSTATE,
CMD_REQUESTPREVIEW,
CMD_QUERYPRINTERCAPABILITY,
CMD_CHECKPERMISSION,
CMD_ON,
CMD_OFF,
CMD_REG_EXT_CB,
CMD_UNREG_EXT_CB,
};
} // namespace OHOS::Print
#endif // PRINT_SERVICE_INTERFACE_H

View File

@ -1,92 +0,0 @@
/*
* 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 NAPI_PRINT_UTILS_H
#define NAPI_PRINT_UTILS_H
#include <string>
#include <vector>
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "print_job.h"
#include "print_resolution.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
class NapiPrintUtils {
public:
static constexpr size_t MAX_ARGC = 6;
static constexpr size_t ARGC_ZERO = 0;
static constexpr size_t ARGC_ONE = 1;
static constexpr size_t ARGC_TWO = 2;
static constexpr size_t ARGC_THREE = 3;
static constexpr size_t ARGC_FOUR = 4;
static constexpr size_t ARGC_FIVE = 5;
static constexpr size_t ARGC_SIX = 6;
static constexpr int32_t INDEX_ZERO = 0;
static constexpr int32_t INDEX_ONE = 1;
static constexpr int32_t INDEX_TWO = 2;
static constexpr int32_t INDEX_TRHEE = 3;
static constexpr int32_t INDEX_FOUR = 4;
static constexpr int32_t INDEX_FIVE = 5;
static constexpr int32_t ERROR_CODE_ONE = 1;
static constexpr int32_t ERROR_CODE_TWO = 2;
static constexpr int32_t MAX_NUMBER_BYTES = 8;
static constexpr int32_t MAX_LEN = 4096;
static napi_valuetype GetValueType(napi_env env, napi_value value);
static bool HasNamedProperty(napi_env env, napi_value object, const std::string &propertyName);
static napi_value GetNamedProperty(napi_env env, napi_value object, const std::string &propertyName);
static void SetNamedProperty(napi_env env, napi_value object, const std::string &name, napi_value value);
static std::vector<std::string> GetPropertyNames(napi_env env, napi_value object);
static napi_value CreateUint32(napi_env env, uint32_t code);
static uint32_t GetUint32FromValue(napi_env env, napi_value value);
static uint32_t GetUint32Property(napi_env env, napi_value object, const std::string &propertyName);
static void SetUint32Property(napi_env env, napi_value object, const std::string &name, uint32_t value);
static napi_value CreateInt32(napi_env env, int32_t code);
static int32_t GetInt32FromValue(napi_env env, napi_value value);
static int32_t GetInt32Property(napi_env env, napi_value object, const std::string &propertyName);
static void SetInt32Property(napi_env env, napi_value object, const std::string &name, int32_t value);
static napi_value CreateStringUtf8(napi_env env, const std::string &str);
static std::string GetStringFromValueUtf8(napi_env env, napi_value value);
static std::string GetStringPropertyUtf8(napi_env env, napi_value object, const std::string &propertyName);
static void SetStringPropertyUtf8(
napi_env env, napi_value object, const std::string &name, const std::string &value);
static std::string GetValueString(napi_env env, napi_value value);
static bool ValueIsArrayBuffer(napi_env env, napi_value value);
static void *GetInfoFromArrayBufferValue(napi_env env, napi_value value, size_t *length);
static napi_value CreateArrayBuffer(napi_env env, size_t length, void **data);
static napi_value CreateObject(napi_env env);
static napi_value GetUndefined(napi_env env);
static napi_value CallFunction(napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value *argv);
static napi_value CreateFunction(napi_env env, const std::string &name, napi_callback func, void *arg);
static napi_ref CreateReference(napi_env env, napi_value callback);
static napi_value GetReference(napi_env env, napi_ref callbackRef);
static void DeleteReference(napi_env env, napi_ref callbackRef);
static bool GetBooleanProperty(napi_env env, napi_value object, const std::string &propertyName);
static void SetBooleanProperty(napi_env env, napi_value object, const std::string &name, bool value);
static void DefineProperties(
napi_env env, napi_value object, const std::initializer_list<napi_property_descriptor> &properties);
static std::string ToLower(const std::string &s);
static void CovertPageSize(napi_env env, napi_value &pageSize, const PrintJob &job);
static napi_value Convert2JsObj(napi_env env, const PrintJob &job);
};
} // namespace OHOS::Print
#endif /* NAPI_PRINT_UTILS_H */

View File

@ -1,55 +0,0 @@
/*
* 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 PRINT_BASE_NOTIFY_H
#define PRINT_BASE_NOTIFY_H
#include <string>
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_callback_stub.h"
#include "print_job.h"
#include "printer_info.h"
namespace OHOS::Print {
struct NotifyData {
napi_env env;
napi_ref ref;
std::string objectType;
std::string type;
uint32_t firstArgv;
PrinterInfo secondArgv;
PrintJob thirdArgv;
};
class PrintBaseNotify : public PrintCallbackStub {
public:
ACE_DISALLOW_COPY_AND_MOVE(PrintBaseNotify);
explicit PrintBaseNotify(napi_env env, const std::string &type, napi_ref ref);
virtual ~PrintBaseNotify();
void OnCallBack(MessageParcel &data) override;
protected:
NotifyData *GetNotifyData();
protected:
napi_env env_;
std::string type_;
napi_ref ref_;
};
} // namespace OHOS::Print
#endif // PRINT_BASE_NOTIFY_H

View File

@ -1,32 +0,0 @@
/*
* 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 PRINT_CALLBACK_STUB_H
#define PRINT_CALLBACK_STUB_H
#include <memory>
#include "iprint_callback.h"
#include "iremote_stub.h"
namespace OHOS::Print {
class PrintCallbackStub : public IRemoteStub<IPrintCallback> {
public:
PrintCallbackStub() = default;
virtual ~PrintCallbackStub() {}
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
};
} // namespace OHOS::Print
#endif // PRINT_CALLBACK_STUB_H

View File

@ -1,63 +0,0 @@
/*
* 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 PRINT_EXTENSION_CALLBACK_STUB_H
#define PRINT_EXTENSION_CALLBACK_STUB_H
#include <memory>
#include "iprint_extension_callback.h"
#include "iremote_stub.h"
#include "print_job.h"
#include "printer_capability.h"
namespace OHOS::Print {
using PrintExtCallback = bool (*)();
using PrintJobCallback = bool (*)(const PrintJob &);
using PrinterCallback = bool (*)(uint32_t);
using PrinterCapabilityCallback = bool (*)(uint32_t, PrinterCapability &cap);
class PrintExtensionCallbackStub : public IRemoteStub<IPrintExtensionCallback> {
public:
explicit PrintExtensionCallbackStub();
virtual ~PrintExtensionCallbackStub() = default;
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
bool OnCallback() override;
bool OnCallback(uint32_t printerId) override;
bool OnCallback(const PrintJob &job) override;
bool OnCallback(uint32_t printerId, MessageParcel &reply) override;
void SetExtCallback(PrintExtCallback cb);
void SetPrintJobCallback(PrintJobCallback cb);
void SetPrinterCallback(PrinterCallback cb);
void SetCapabilityCallback(PrinterCapabilityCallback cb);
private:
bool HandleExtCallback(MessageParcel &data, MessageParcel &reply);
bool HandlePrinterCallback(MessageParcel &data, MessageParcel &reply);
bool HandlePrintJobCallback(MessageParcel &data, MessageParcel &reply);
bool HandleCapabilityCallback(MessageParcel &data, MessageParcel &reply);
void dataReadJob(MessageParcel &data, PrintJob &job);
private:
using PRINT_EXT_HANDLER = bool (PrintExtensionCallbackStub::*)(MessageParcel &, MessageParcel &);
PrintExtCallback extCb_;
PrintJobCallback jobCb_;
PrinterCallback cb_;
PrinterCapabilityCallback capability_;
std::map<uint32_t, PRINT_EXT_HANDLER> cmdMap_;
};
} // namespace OHOS::Print
#endif // PRINT_EXTCB_STUB_H

View File

@ -1,59 +0,0 @@
/*
* 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 PRINT_EXTENSION_INFO_H
#define PRINT_EXTENSION_INFO_H
#include <map>
#include <string>
namespace OHOS::Print {
class PrintExtensionInfo {
public:
PrintExtensionInfo();
void SetExtensionId(uint32_t extensionId);
void SetVendorId(uint32_t vendorId);
void SetVendorName(const std::string &vendorName);
void SetVendorIcon(uint32_t vendorIcon);
void SetVersion(const std::string &version);
[[nodiscard]] uint32_t GetExtensionId() const;
[[nodiscard]] uint32_t GetVendorId() const;
[[nodiscard]] const std::string &GetVendorName() const;
[[nodiscard]] uint32_t GetVendorIcon() const;
[[nodiscard]] const std::string &GetVersion() const;
void Dump();
~PrintExtensionInfo();
private:
uint32_t extensionId_;
uint32_t vendorId_;
std::string vendorName_;
uint32_t vendorIcon_;
std::string version_;
};
} // namespace OHOS::Print
#endif // PRINT_EXTENSION_INFO_H

View File

@ -1,35 +0,0 @@
/*
* 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 PRINT_FAIL_NOTIFY_H
#define PRINT_FAIL_NOTIFY_H
#include <string>
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_base_notify.h"
namespace OHOS::Print {
class PrintFailNotify final : public PrintBaseNotify {
public:
ACE_DISALLOW_COPY_AND_MOVE(PrintFailNotify);
explicit PrintFailNotify(napi_env env, const std::string &type, napi_ref ref);
virtual ~PrintFailNotify();
void OnCallBack(MessageParcel &data) override;
};
} // namespace OHOS::Print
#endif // PRINT_FAIL_NOTIFY_H

View File

@ -1,120 +0,0 @@
/*
* 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 PRINT_PRINT_JOB_H
#define PRINT_PRINT_JOB_H
#include <map>
#include <string>
#include <vector>
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "napi/native_api.h"
#include "print_margin.h"
#include "print_page_size.h"
#include "print_preview_attribute.h"
#include "print_range.h"
namespace OHOS::Print {
class PrintJob {
public:
explicit PrintJob();
PrintJob(const PrintJob &right);
PrintJob &operator=(PrintJob &right);
~PrintJob();
void SetFiles(const std::vector<std::string> &files);
void SetJobId(uint32_t jobId);
void SetPrintId(uint32_t printerid);
void SetJobState(uint32_t jobState);
void SetCopyNumber(uint32_t copyNumber);
void SetPageRange(const PrintRange &pageRange);
void SetIsSequential(bool isSequential);
void SetPageSize(const PrintPageSize &pageSize);
void SetIsLandscape(bool isLandscape);
void SetColorMode(uint32_t colorMode);
void SetDuplexMode(uint32_t duplexmode);
void SetMargin(const PrintMargin &margin);
void SetPreview(const PreviewAttribute &preview);
void GetFiles(std::vector<std::string> &fileList) const;
[[nodiscard]] uint32_t GetJobId() const;
[[nodiscard]] uint32_t GetPrinterId() const;
[[nodiscard]] uint32_t GetJobState() const;
[[nodiscard]] uint32_t GetCopyNumber() const;
void GetPageRange(PrintRange &range) const;
[[nodiscard]] bool GetIsSequential() const;
void GetPageSize(PrintPageSize &printPageSize) const;
[[nodiscard]] bool GetIsLandscape() const;
[[nodiscard]] uint32_t GetColorMode() const;
[[nodiscard]] uint32_t GetDuplexMode() const;
void GetMargin(PrintMargin &printMargin) const;
void GetPreview(PreviewAttribute &previewAttr) const;
void ConvertToParcel(MessageParcel &reply) const;
void BuildFromParcel(MessageParcel &data);
void ConvertToJs(napi_env env, napi_value *result) const;
void BuildFromJs(napi_env env, napi_value capValue);
void Dump();
private:
bool ParseJob(napi_env env, napi_value jobValue, PrintJob &printJob);
bool ParseJobParam(napi_env env, napi_value jobValue, PrintJob &printJob);
private:
std::vector<std::string> files_;
uint32_t jobId_;
uint32_t printerId_;
uint32_t jobState_;
uint32_t copyNumber_;
PrintRange pageRange_;
bool isSequential_;
PrintPageSize pageSize_;
bool isLandscape_;
int32_t colorMode_;
int32_t duplexMode_;
PrintMargin margin_;
PreviewAttribute preview_;
};
} // namespace OHOS::Print
#endif /* PRINT_PRINT_JOB_H */

View File

@ -1,89 +0,0 @@
/*
* 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 PRINT_MANAGER_CLIENT_H
#define PRINT_MANAGER_CLIENT_H
#include <condition_variable>
#include <map>
#include <mutex>
#include "iprint_callback.h"
#include "iprint_service.h"
#include "iremote_object.h"
#include "print_extension_callback_stub.h"
#include "print_extension_info.h"
#include "print_job.h"
#include "print_sa_death_recipient.h"
#include "printer_info.h"
#include "refbase.h"
namespace OHOS::Print {
class PrintManagerClient : public RefBase {
public:
PrintManagerClient();
~PrintManagerClient();
static sptr<PrintManagerClient> GetInstance();
bool CheckPermission();
void OnRemoteSaDied(const wptr<IRemoteObject> &object);
// Client Napi
int32_t StartPrint();
bool QueryAllExtension(std::vector<PrintExtensionInfo> &arrayExtensionInfo);
bool StartDiscoverPrinter(std::vector<uint32_t> extensionList);
bool StopDiscoverPrinter();
bool AddPrinters(std::vector<PrinterInfo> arrayPrintInfo);
bool RemovePrinters(std::vector<PrinterInfo> arrayPrintInfo);
bool ConnectPrinter(uint32_t printerId);
bool DisconnectPrinter(uint32_t printerId);
bool StartPrintJob(const PrintJob &jobinfo);
bool CancelPrintJob(const PrintJob &jobinfo);
bool UpdatePrinterState(uint32_t printerId, uint32_t state);
bool UpdatePrinterJobState(uint32_t jobId, uint32_t state);
bool RequestPreview(const PrintJob &jobinfo, std::string &previewResult);
bool QueryPrinterCapability(uint32_t printerId, PrinterCapability &printerCapability);
bool On(const std::string &type, uint32_t &state, PrinterInfo &info, const sptr<IPrintCallback> &listener);
bool Off(const std::string &type);
bool RegisterExtCallback(uint32_t callbackId, PrintExtCallback cb);
bool RegisterExtCallback(uint32_t callbackId, PrintJobCallback cb);
bool RegisterExtCallback(uint32_t callbackId, PrinterCallback cb);
bool RegisterExtCallback(uint32_t callbackId, PrinterCapabilityCallback cb);
bool UnregisterAllExtCallback();
bool LoadServer();
void LoadServerSuccess();
void LoadServerFail();
private:
sptr<IPrintService> GetPrintServiceProxy();
private:
static std::mutex instanceLock_;
static sptr<PrintManagerClient> instance_;
sptr<IPrintService> printServiceProxy_;
sptr<PrintSaDeathRecipient> deathRecipient_;
std::map<uint32_t, sptr<PrintExtensionCallbackStub>> extCallbackMap_;
std::mutex loadMutex_;
std::mutex conditionMutex_;
std::condition_variable syncCon_;
bool ready_ = false;
static constexpr int LOAD_SA_TIMEOUT_MS = 15000;
};
} // namespace OHOS::Print
#endif // PRINT_MANAGER_CLIENT_H

View File

@ -1,52 +0,0 @@
/*
* 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 PRINT_MARGIN_H
#define PRINT_MARGIN_H
namespace OHOS::Print {
class PrintMargin {
public:
explicit PrintMargin();
PrintMargin(const PrintMargin &right);
PrintMargin &operator=(const PrintMargin &right);
~PrintMargin();
void SetTop(uint32_t top);
void SetBottom(uint32_t bottom);
void SetLeft(uint32_t left);
void SetRight(uint32_t right);
[[nodiscard]] uint32_t GetTop() const;
[[nodiscard]] uint32_t GetBottom() const;
[[nodiscard]] uint32_t GetLeft() const;
[[nodiscard]] uint32_t GetRight() const;
void Dump();
private:
uint32_t top_;
uint32_t bottom_;
uint32_t left_;
uint32_t right_;
};
} // namespace OHOS::Print
#endif // PRINT_MARGIN_H

View File

@ -1,35 +0,0 @@
/*
* 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 PRINT_NOTIFY_H
#define PRINT_NOTIFY_H
#include <string>
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_callback_stub.h"
namespace OHOS::Print {
class PrintNotify final : public PrintCallbackStub {
public:
ACE_DISALLOW_COPY_AND_MOVE(PrintNotify);
explicit PrintNotify();
virtual ~PrintNotify();
void OnCallBack(MessageParcel &data) override;
};
} // namespace OHOS::Print
#endif // PRINT_NOTIFY_H

View File

@ -1,242 +0,0 @@
/*
* 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 PRINT_PAGESIZE_H
#define PRINT_PAGESIZE_H
#include <map>
#include <string>
namespace OHOS::Print {
enum PageSizeId {
ISO_A0,
ISO_A1,
ISO_A2,
ISO_A3,
ISO_A4,
ISO_A5,
ISO_A6,
ISO_A7,
ISO_A8,
ISO_A9,
ISO_A10,
ISO_B0,
ISO_B1,
ISO_B2,
ISO_B3,
ISO_B4,
ISO_B5,
ISO_B6,
ISO_B7,
ISO_B8,
ISO_B9,
ISO_B10,
ISO_C0,
ISO_C1,
ISO_C2,
ISO_C3,
ISO_C4,
ISO_C5,
ISO_C6,
ISO_C7,
ISO_C8,
ISO_C9,
ISO_C10,
NA_LETTER,
NA_GOVT_LETTER,
NA_LEGAL,
NA_JUNIOR_LEGAL,
NA_LEDGER,
NA_TABLOID,
NA_INDEX_3X5,
NA_INDEX_4X6,
NA_INDEX_5X8,
NA_MONARCH,
NA_QUARTO,
NA_FOOLSCAP,
ROC_8K,
ROC_16K,
PRC_1,
PRC_2,
PRC_3,
PRC_4,
PRC_5,
PRC_6,
PRC_7,
PRC_8,
PRC_9,
PRC_10,
PRC_16K,
OM_PA_KAI,
OM_DAI_PA_KAI,
OM_JUURO_KU_KAI,
JIS_B10,
JIS_B9,
JIS_B8,
JIS_B7,
JIS_B6,
JIS_B5,
JIS_B4,
JIS_B3,
JIS_B2,
JIS_B1,
JIS_B0,
JIS_EXEC,
JPN_CHOU4,
JPN_CHOU3,
JPN_CHOU2,
JPN_HAGAKI,
JPN_OUFUKU,
JPN_KAHU,
JPN_KAKU2,
JPN_YOU4,
};
const std::string PAGE_SIZE_TABLE[] = {
"ISO_A0",
"ISO_A1",
"ISO_A2",
"ISO_A3",
"ISO_A4",
"ISO_A5",
"ISO_A6",
"ISO_A7",
"ISO_A8",
"ISO_A9",
"ISO_A10",
"ISO_B0",
"ISO_B1",
"ISO_B2",
"ISO_B3",
"ISO_B4",
"ISO_B5",
"ISO_B6",
"ISO_B7",
"ISO_B8",
"ISO_B9",
"ISO_B10",
"ISO_C0",
"ISO_C1",
"ISO_C2",
"ISO_C3",
"ISO_C4",
"ISO_C5",
"ISO_C6",
"ISO_C7",
"ISO_C8",
"ISO_C9",
"ISO_C10",
"NA_LETTER",
"NA_GOVT_LETTER",
"NA_LEGAL",
"NA_JUNIOR_LEGAL",
"NA_LEDGER",
"NA_TABLOID",
"NA_INDEX_3X5",
"NA_INDEX_4X6",
"NA_INDEX_5X8",
"NA_MONARCH",
"NA_QUARTO",
"NA_FOOLSCAP",
"ROC_8K",
"ROC_16K",
"PRC_1",
"PRC_2",
"PRC_3",
"PRC_4",
"PRC_5",
"PRC_6",
"PRC_7",
"PRC_8",
"PRC_9",
"PRC_10",
"PRC_16K",
"OM_PA_KAI",
"OM_DAI_PA_KAI",
"OM_JUURO_KU_KAI",
"JIS_B10",
"JIS_B9",
"JIS_B8",
"JIS_B7",
"JIS_B6",
"JIS_B5",
"JIS_B4",
"JIS_B3",
"JIS_B2",
"JIS_B1",
"JIS_B0",
"JIS_EXEC",
"JPN_CHOU4",
"JPN_CHOU3",
"JPN_CHOU2",
"JPN_HAGAKI",
"JPN_OUFUKU",
"JPN_KAHU",
"JPN_KAKU2",
"JPN_YOU4",
};
using DiscreteId = std::string;
using DiscretePageName = std::string;
using PAGE_SIZE_ID = std::string;
class PrintPageSize {
public:
static void BuildPageSizeMap();
static PrintPageSize GetPageSize(PageSizeId id);
explicit PrintPageSize();
PrintPageSize(PAGE_SIZE_ID id, DiscretePageName name, uint32_t width, uint32_t height);
PrintPageSize(const PrintPageSize &right);
PrintPageSize &operator=(const PrintPageSize &right);
~PrintPageSize();
void SetId(const std::string &id);
void SetName(const std::string &name);
void SetWidth(uint32_t width);
void SetHeight(uint32_t height);
[[nodiscard]] const std::string &GetId() const;
[[nodiscard]] const std::string &GetName() const;
[[nodiscard]] uint32_t GetWidth() const;
[[nodiscard]] uint32_t GetHeight() const;
void Dump();
private:
std::string id_;
std::string name_;
uint32_t width_;
uint32_t height_;
static std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> pageSize_;
};
} // namespace OHOS::Print
#endif // PRINT_PAGESIZE_H

View File

@ -1,45 +0,0 @@
/*
* 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 PRINT_PREVIEW_ATTRIBUTE_H
#define PRINT_PREVIEW_ATTRIBUTE_H
#include <cstdint>
#include <string>
#include "print_range.h"
namespace OHOS::Print {
class PreviewAttribute {
public:
explicit PreviewAttribute();
PreviewAttribute(const PreviewAttribute &right);
PreviewAttribute &operator=(const PreviewAttribute &previewAttribute);
~PreviewAttribute();
void SetResult(const std::string &result);
void SetPreviewRange(const PrintRange &previewRange);
[[nodiscard]] const std::string &GetResult() const;
void GetPreviewRange(PrintRange &range) const;
void Dump();
private:
std::string result_;
PrintRange previewRange_;
};
} // namespace OHOS::Print
#endif // PRINT_PREVIEW_ATTRIBUTE_H

View File

@ -1,40 +0,0 @@
/*
* 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 PRINT_PROGRESS_NOTIFY_H
#define PRINT_PROGRESS_NOTIFY_H
#include <string>
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_base_notify.h"
namespace OHOS::Print {
class PrintProgressNotify final : public PrintBaseNotify {
public:
ACE_DISALLOW_COPY_AND_MOVE(PrintProgressNotify);
explicit PrintProgressNotify(napi_env env, const std::string &type, napi_ref ref);
virtual ~PrintProgressNotify();
static void DataReadInfo(PrinterInfo &info, MessageParcel &data);
static void DataReadJob(PrintJob &job, MessageParcel &data);
static void WriteInfoJsObject(napi_env env, PrinterInfo info, napi_value *result);
static void WriteJobJsObject(napi_env env, PrintJob job, napi_value *result);
void OnCallBack(MessageParcel &data) override;
};
} // namespace OHOS::Print
#endif // PRINT_PROGRESS_NOTIFY_H

View File

@ -1,52 +0,0 @@
/*
* 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 PRINT_RANGE_H
#define PRINT_RANGE_H
#include <string>
#include <vector>
namespace OHOS::Print {
class PrintRange {
public:
explicit PrintRange();
PrintRange(const PrintRange &right);
PrintRange &operator=(const PrintRange &right);
~PrintRange();
void SetStartPage(uint32_t startPage);
void SetEndPage(uint32_t endPage);
void SetPages(const std::vector<uint32_t> &pages);
void Reset();
[[nodiscard]] uint32_t GetStartPage() const;
[[nodiscard]] uint32_t GetEndPage() const;
void GetPages(std::vector<uint32_t> &pages) const;
void Dump();
private:
uint32_t startPage_;
uint32_t endPage_;
std::vector<uint32_t> pages_;
};
} // namespace OHOS::Print
#endif // PRINT_RANGE_H

View File

@ -1,47 +0,0 @@
/*
* 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 PRINT_RESOLUTION_H
#define PRINT_RESOLUTION_H
namespace OHOS::Print {
class PrintResolution {
public:
explicit PrintResolution();
PrintResolution(const PrintResolution &right);
PrintResolution &operator=(const PrintResolution &right);
~PrintResolution();
void SetId(uint32_t id);
void SetHorizontalDpi(uint32_t horizontalDpi);
void SetVerticalDpi(uint32_t verticalDpi);
[[nodiscard]] uint32_t GetId() const;
[[nodiscard]] uint32_t GetHorizontalDpi() const;
[[nodiscard]] uint32_t GetVerticalDpi() const;
void Dump();
private:
uint32_t id_;
uint32_t horizontalDpi_;
uint32_t verticalDpi_;
};
} // namespace OHOS::Print
#endif // PRINT_RESOLUTION_H

View File

@ -1,30 +0,0 @@
/*
* 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 PRINT_SA_DEATH_RECIPIENT_H
#define PRINT_SA_DEATH_RECIPIENT_H
#include "iremote_object.h"
#include "refbase.h"
namespace OHOS::Print {
class PrintSaDeathRecipient : public IRemoteObject::DeathRecipient {
public:
explicit PrintSaDeathRecipient();
~PrintSaDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
};
} // namespace OHOS::Print
#endif // PRINT_SA_DEATH_RECIPIENT_H

View File

@ -1,56 +0,0 @@
/*
* 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 PRINT_SERVICE_PROXY_H
#define PRINT_SERVICE_PROXY_H
#include "iprint_service.h"
#include "iremote_proxy.h"
namespace OHOS::Print {
class PrintServiceProxy : public IRemoteProxy<IPrintService> {
public:
explicit PrintServiceProxy(const sptr<IRemoteObject> &object);
~PrintServiceProxy() = default;
DISALLOW_COPY_AND_MOVE(PrintServiceProxy);
int32_t StartPrint() override;
bool ConnectPrinter(uint32_t printerId) override;
bool DisconnectPrinter(uint32_t printerId) override;
bool QueryAllExtension(std::vector<PrintExtensionInfo> &arrayExtensionInfo) override;
bool StartDiscoverPrinter(const std::vector<uint32_t> &extensionList) override;
bool StopDiscoverPrinter() override;
bool StartPrintJob(const PrintJob &jobinfo) override;
bool CancelPrintJob(const PrintJob &jobinfo) override;
bool AddPrinters(const std::vector<PrinterInfo> &arrayPrintInfo) override;
bool RemovePrinters(const std::vector<PrinterInfo> &arrayPrintInfo) override;
bool UpdatePrinterState(uint32_t printerId, uint32_t state) override;
bool UpdatePrinterJobState(uint32_t jobId, uint32_t state) override;
bool RequestPreview(const PrintJob &jobinfo, std::string &previewResult) override;
bool QueryPrinterCapability(uint32_t printerId, PrinterCapability &printerCapability) override;
bool CheckPermission() override;
bool On(const std::string &type, uint32_t &state, PrinterInfo &info, const sptr<IPrintCallback> &listener) override;
bool Off(const std::string &type) override;
bool RegisterExtCallback(uint32_t callbackId, const sptr<IPrintExtensionCallback> &listener) override;
bool UnregisterAllExtCallback() override;
private:
void BuildParcelFromPrintJob(MessageParcel &data, const PrintJob &jobinfo);
void BuildParcelFromPrinterInfo(MessageParcel &data, const PrinterInfo &printerInfo);
private:
static inline BrokerDelegator<PrintServiceProxy> delegator_;
};
} // namespace OHOS::Print
#endif // PRINT_SERVICE_PROXY_H

View File

@ -1,28 +0,0 @@
/*
* 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 PRINT_SYNC_LOAD_CALLBACK_H
#define PRINT_SYNC_LOAD_CALLBACK_H
#include "system_ability_load_callback_stub.h"
namespace OHOS::Print {
class PrintSyncLoadCallback : public SystemAbilityLoadCallbackStub {
public:
void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject> &remoteObject) override;
void OnLoadSystemAbilityFail(int32_t systemAbilityId) override;
};
} // namespace OHOS::Print
#endif // PRINT_SYNC_LOAD_CALLBACK_H

View File

@ -1,94 +0,0 @@
/*
* 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 PRINTER_CAPABILITY_H
#define PRINTER_CAPABILITY_H
#include <mutex>
#include <string>
#include <vector>
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "napi/native_api.h"
#include "print_margin.h"
#include "print_page_size.h"
#include "print_resolution.h"
namespace OHOS::Print {
class PrinterCapability {
public:
explicit PrinterCapability();
PrinterCapability(const PrinterCapability &right);
PrinterCapability &operator=(const PrinterCapability &right);
~PrinterCapability();
void SetMinMargin(const PrintMargin &minMargin);
void SetPageSize(const std::vector<PrintPageSize> &pageSizeList);
void SetResolution(const std::vector<PrintResolution> &resolutionList);
void SetColorMode(uint32_t colorMode);
void SetDuplexMode(uint32_t duplexMode);
void GetMinMargin(PrintMargin &margin) const;
void GetPageSize(std::vector<PrintPageSize> &pageSizeList) const;
void GetResolution(std::vector<PrintResolution> &resolutionList) const;
[[nodiscard]] uint32_t GetColorMode() const;
[[nodiscard]] uint32_t GetDuplexMode() const;
void ConvertToParcel(MessageParcel &reply) const;
void BuildFromParcel(MessageParcel &data);
void ConvertToJs(napi_env env, napi_value *result) const;
void BuildFromJs(napi_env env, napi_value capValue);
void Dump();
private:
bool ParseResolution(napi_env env, napi_value reValue, PrintResolution &resolution);
bool ParseResolutionParam(napi_env env, napi_value reValue, PrintResolution &resolution);
bool ParsePageSize(napi_env env, napi_value capValue, PrintPageSize &pageSize);
bool ParseMargin(napi_env env, napi_value marginValue, PrintMargin &margin);
bool ParseMarginParam(napi_env env, napi_value marginValue, PrintMargin &margin);
void ParseCapabilityObject(napi_env env, napi_value capValue);
bool ParseCapabilityParam(napi_env env, napi_value capValue);
bool ParseCapability(napi_env env, napi_value capValue);
bool ParsePageSizeParam(napi_env env, napi_value capValue, PrintPageSize &pageSize);
private:
PrintMargin minMargin_;
std::vector<PrintPageSize> pageSizeList_;
std::vector<PrintResolution> resolutionList_;
uint32_t colorMode_;
uint32_t duplexMode_;
};
} // namespace OHOS::Print
#endif // PRINTER_CAPABILITY_H

View File

@ -1,78 +0,0 @@
/*
* 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 PRINT_INFO_H
#define PRINT_INFO_H
#include <iosfwd>
#include <stdint.h>
#include <string>
#include "print_constant.h"
#include "printer_capability.h"
namespace OHOS::Print {
class PrinterInfo final {
public:
explicit PrinterInfo();
PrinterInfo(const PrinterInfo &right);
PrinterInfo &operator=(PrinterInfo &PrinterInfo);
~PrinterInfo();
void SetPrinterId(uint32_t printerId);
void SetPrinterName(std::string printerName);
void SetPrinterIcon(uint32_t printIcon);
void SetPrinterState(uint32_t printerState);
void SetDescription(std::string description);
void SetCapability(PrinterCapability capability);
[[nodiscard]] uint32_t GetPrintId() const;
[[nodiscard]] const std::string &GetPrinterName() const;
[[nodiscard]] uint32_t GetPrinterIcon() const;
[[nodiscard]] uint32_t GetPrinterState() const;
[[nodiscard]] const std::string &GetDescription() const;
void GetCapability(PrinterCapability &cap) const;
void Dump();
private:
bool ParseInfo(napi_env env, napi_value InfoValue, PrinterInfo &Info);
bool ParseInfoParam(napi_env env, napi_value InfoValue, PrinterInfo &info);
private:
uint32_t printerId_;
std::string printerName_;
uint32_t printerIcon_;
uint32_t printerState_;
std::string description_;
PrinterCapability capability_;
};
} // namespace OHOS::Print
#endif /* PRINT_INFO_H */

View File

@ -1,411 +0,0 @@
/*
* 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 "napi_print_utils.h"
#include "print_log.h"
#include "securec.h"
namespace OHOS::Print {
static constexpr const int MAX_STRING_LENGTH = 65536;
napi_valuetype NapiPrintUtils::GetValueType(napi_env env, napi_value value)
{
if (value == nullptr) {
return napi_undefined;
}
napi_valuetype valueType = napi_undefined;
NAPI_CALL_BASE(env, napi_typeof(env, value, &valueType), napi_undefined);
return valueType;
}
/* named property */
bool NapiPrintUtils::HasNamedProperty(napi_env env, napi_value object, const std::string &propertyName)
{
bool hasProperty = false;
NAPI_CALL_BASE(env, napi_has_named_property(env, object, propertyName.c_str(), &hasProperty), false);
return hasProperty;
}
napi_value NapiPrintUtils::GetNamedProperty(napi_env env, napi_value object, const std::string &propertyName)
{
napi_value value = nullptr;
bool hasProperty = false;
NAPI_CALL(env, napi_has_named_property(env, object, propertyName.c_str(), &hasProperty));
if (!hasProperty) {
return value;
}
NAPI_CALL(env, napi_get_named_property(env, object, propertyName.c_str(), &value));
return value;
}
void NapiPrintUtils::SetNamedProperty(napi_env env, napi_value object, const std::string &name, napi_value value)
{
(void)napi_set_named_property(env, object, name.c_str(), value);
}
std::vector<std::string> NapiPrintUtils::GetPropertyNames(napi_env env, napi_value object)
{
std::vector<std::string> ret;
napi_value names = nullptr;
NAPI_CALL_BASE(env, napi_get_property_names(env, object, &names), ret);
uint32_t length = 0;
NAPI_CALL_BASE(env, napi_get_array_length(env, names, &length), ret);
for (uint32_t index = 0; index < length; ++index) {
napi_value name = nullptr;
if (napi_get_element(env, names, index, &name) != napi_ok) {
continue;
}
if (GetValueType(env, name) != napi_string) {
continue;
}
ret.emplace_back(GetStringFromValueUtf8(env, name));
}
return ret;
}
/* UINT32 */
napi_value NapiPrintUtils::CreateUint32(napi_env env, uint32_t code)
{
napi_value value = nullptr;
if (napi_create_uint32(env, code, &value) != napi_ok) {
return nullptr;
}
return value;
}
uint32_t NapiPrintUtils::GetUint32FromValue(napi_env env, napi_value value)
{
uint32_t ret = 0;
NAPI_CALL_BASE(env, napi_get_value_uint32(env, value, &ret), 0);
return ret;
}
uint32_t NapiPrintUtils::GetUint32Property(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return 0;
}
napi_value value = GetNamedProperty(env, object, propertyName);
return GetUint32FromValue(env, value);
}
void NapiPrintUtils::SetUint32Property(napi_env env, napi_value object, const std::string &name, uint32_t value)
{
napi_value jsValue = CreateUint32(env, value);
if (GetValueType(env, jsValue) != napi_number) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* INT32 */
napi_value NapiPrintUtils::CreateInt32(napi_env env, int32_t code)
{
napi_value value = nullptr;
if (napi_create_int32(env, code, &value) != napi_ok) {
return nullptr;
}
return value;
}
int32_t NapiPrintUtils::GetInt32FromValue(napi_env env, napi_value value)
{
int32_t ret = 0;
NAPI_CALL_BASE(env, napi_get_value_int32(env, value, &ret), 0);
return ret;
}
int32_t NapiPrintUtils::GetInt32Property(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return 0;
}
napi_value value = GetNamedProperty(env, object, propertyName);
return GetInt32FromValue(env, value);
}
void NapiPrintUtils::SetInt32Property(napi_env env, napi_value object, const std::string &name, int32_t value)
{
napi_value jsValue = CreateInt32(env, value);
if (GetValueType(env, jsValue) != napi_number) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* String UTF8 */
napi_value NapiPrintUtils::CreateStringUtf8(napi_env env, const std::string &str)
{
napi_value value = nullptr;
if (napi_create_string_utf8(env, str.c_str(), strlen(str.c_str()), &value) != napi_ok) {
return nullptr;
}
return value;
}
std::string NapiPrintUtils::GetStringFromValueUtf8(napi_env env, napi_value value)
{
std::string result;
std::vector<char> str(MAX_STRING_LENGTH + 1, '\0');
size_t length = 0;
NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, value, &str[0], MAX_STRING_LENGTH, &length), result);
if (length > 0) {
return result.append(&str[0], length);
}
return result;
}
std::string NapiPrintUtils::GetStringPropertyUtf8(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return "";
}
napi_value value = GetNamedProperty(env, object, propertyName);
return GetStringFromValueUtf8(env, value);
}
void NapiPrintUtils::SetStringPropertyUtf8(
napi_env env, napi_value object, const std::string &name, const std::string &value)
{
napi_value jsValue = CreateStringUtf8(env, value);
if (GetValueType(env, jsValue) != napi_string) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* array buffer */
bool NapiPrintUtils::ValueIsArrayBuffer(napi_env env, napi_value value)
{
bool isArrayBuffer = false;
NAPI_CALL_BASE(env, napi_is_arraybuffer(env, value, &isArrayBuffer), false);
return isArrayBuffer;
}
void *NapiPrintUtils::GetInfoFromArrayBufferValue(napi_env env, napi_value value, size_t *length)
{
if (length == nullptr) {
return nullptr;
}
void *data = nullptr;
NAPI_CALL(env, napi_get_arraybuffer_info(env, value, &data, length));
return data;
}
/* object */
napi_value NapiPrintUtils::CreateObject(napi_env env)
{
napi_value object = nullptr;
NAPI_CALL(env, napi_create_object(env, &object));
return object;
}
/* undefined */
napi_value NapiPrintUtils::GetUndefined(napi_env env)
{
napi_value undefined = nullptr;
NAPI_CALL(env, napi_get_undefined(env, &undefined));
return undefined;
}
/* function */
napi_value NapiPrintUtils::CallFunction(
napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value *argv)
{
napi_value res = nullptr;
NAPI_CALL(env, napi_call_function(env, recv, func, argc, argv, &res));
return res;
}
/* reference */
napi_ref NapiPrintUtils::CreateReference(napi_env env, napi_value callback)
{
napi_ref callbackRef = nullptr;
NAPI_CALL(env, napi_create_reference(env, callback, 1, &callbackRef));
return callbackRef;
}
napi_value NapiPrintUtils::GetReference(napi_env env, napi_ref callbackRef)
{
napi_value callback = nullptr;
NAPI_CALL(env, napi_get_reference_value(env, callbackRef, &callback));
return callback;
}
void NapiPrintUtils::DeleteReference(napi_env env, napi_ref callbackRef)
{
(void)napi_delete_reference(env, callbackRef);
}
/* boolean */
bool NapiPrintUtils::GetBooleanProperty(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return false;
}
napi_value value = GetNamedProperty(env, object, propertyName);
bool ret = false;
NAPI_CALL_BASE(env, napi_get_value_bool(env, value, &ret), false);
return ret;
}
void NapiPrintUtils::SetBooleanProperty(napi_env env, napi_value object, const std::string &name, bool value)
{
napi_value jsValue = nullptr;
NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, value, &jsValue));
if (GetValueType(env, jsValue) != napi_boolean) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* define properties */
void NapiPrintUtils::DefineProperties(
napi_env env, napi_value object, const std::initializer_list<napi_property_descriptor> &properties)
{
napi_property_descriptor descriptors[properties.size()];
std::copy(properties.begin(), properties.end(), descriptors);
(void)napi_define_properties(env, object, properties.size(), descriptors);
}
std::string NapiPrintUtils::ToLower(const std::string &s)
{
std::string res = s;
std::transform(res.begin(), res.end(), res.begin(), tolower);
return res;
}
std::string NapiPrintUtils::GetValueString(napi_env env, napi_value value)
{
std::string resultValue = "";
char value_string[256];
size_t value_size = 256;
size_t result;
napi_get_value_string_utf8(env, value, value_string, value_size, &result);
resultValue = value_string;
return resultValue;
}
void NapiPrintUtils::CovertPageSize(napi_env env, napi_value &pageSize, const PrintJob &job)
{
PrintPageSize nativePageSize;
job.GetPageSize(nativePageSize);
SetStringPropertyUtf8(env, pageSize, "id", nativePageSize.GetId().c_str());
SetStringPropertyUtf8(env, pageSize, "name", nativePageSize.GetName().c_str());
SetUint32Property(env, pageSize, "width", nativePageSize.GetWidth());
SetUint32Property(env, pageSize, "height", nativePageSize.GetHeight());
}
napi_value NapiPrintUtils::Convert2JsObj(napi_env env, const PrintJob &job)
{
napi_value result;
NAPI_CALL(env, napi_create_object(env, &result));
std::vector<std::string> files;
job.GetFiles(files);
uint32_t arrFilesLength = files.size();
napi_value arrFiles;
NAPI_CALL(env, napi_create_array(env, &arrFiles));
for (uint32_t i = 0; i < arrFilesLength; i++) {
napi_value value;
NAPI_CALL(env, napi_create_string_utf8(env, files[i].c_str(), NAPI_AUTO_LENGTH, &value));
NAPI_CALL(env, napi_set_element(env, arrFiles, i, value));
}
NAPI_CALL(env, napi_set_named_property(env, result, "files", arrFiles));
SetUint32Property(env, result, "jobId", job.GetJobId());
SetUint32Property(env, result, "printerId", job.GetPrinterId());
SetUint32Property(env, result, "jobState", job.GetJobState());
SetUint32Property(env, result, "copyNumber", job.GetCopyNumber());
PrintRange nativeRange;
job.GetPageRange(nativeRange);
std::vector<uint32_t> pages;
nativeRange.GetPages(pages);
napi_value pageRange;
NAPI_CALL(env, napi_create_object(env, &pageRange));
SetUint32Property(env, pageRange, "startPage", nativeRange.GetStartPage());
SetUint32Property(env, pageRange, "endPage", nativeRange.GetEndPage());
napi_value arrPages;
NAPI_CALL(env, napi_create_array(env, &arrPages));
uint32_t arrPagesLength = pages.size();
for (uint32_t i = 0; i < arrPagesLength; i++) {
napi_value value;
NAPI_CALL(env, napi_create_uint32(env, pages[i], &value));
NAPI_CALL(env, napi_set_element(env, arrPages, i, value));
}
NAPI_CALL(env, napi_set_named_property(env, pageRange, "pages", arrPages));
NAPI_CALL(env, napi_set_named_property(env, result, "pageRange", pageRange));
SetUint32Property(env, result, "isSequential", job.GetIsSequential());
napi_value pageSize;
NAPI_CALL(env, napi_create_object(env, &pageSize));
CovertPageSize(env, pageSize, job);
NAPI_CALL(env, napi_set_named_property(env, result, "pageSize", pageSize));
SetUint32Property(env, result, "isLandscape", job.GetIsLandscape());
SetUint32Property(env, result, "colorMode", job.GetColorMode());
SetUint32Property(env, result, "duplexMode", job.GetDuplexMode());
PrintMargin nativeMargin;
job.GetMargin(nativeMargin);
napi_value margin;
NAPI_CALL(env, napi_create_object(env, &margin));
SetUint32Property(env, margin, "top", nativeMargin.GetTop());
SetUint32Property(env, margin, "bottom", nativeMargin.GetBottom());
SetUint32Property(env, margin, "left", nativeMargin.GetLeft());
SetUint32Property(env, margin, "right", nativeMargin.GetRight());
NAPI_CALL(env, napi_set_named_property(env, result, "margin", margin));
PreviewAttribute previewAttr;
job.GetPreview(previewAttr);
previewAttr.GetPreviewRange(nativeRange);
nativeRange.GetPages(pages);
napi_value preview;
NAPI_CALL(env, napi_create_object(env, &preview));
SetStringPropertyUtf8(env, preview, "result", previewAttr.GetResult().c_str());
napi_value subPageRange;
NAPI_CALL(env, napi_create_object(env, &subPageRange));
SetUint32Property(env, subPageRange, "startPage", nativeRange.GetStartPage());
SetUint32Property(env, subPageRange, "endPage", nativeRange.GetEndPage());
napi_value arrPreviewPages;
NAPI_CALL(env, napi_create_array(env, &arrPreviewPages));
uint32_t arrPreviewPagesLength = pages.size();
for (uint32_t i = 0; i < arrPreviewPagesLength; i++) {
napi_value value;
NAPI_CALL(env, napi_create_uint32(env, pages[i], &value));
NAPI_CALL(env, napi_set_element(env, arrPreviewPages, i, value));
}
NAPI_CALL(env, napi_set_named_property(env, subPageRange, "pages", arrPreviewPages));
NAPI_CALL(env, napi_set_named_property(env, preview, "pageRange", subPageRange));
NAPI_CALL(env, napi_set_named_property(env, result, "preview", preview));
return result;
}
} // namespace OHOS::Print

View File

@ -1,82 +0,0 @@
/*
* 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 "print_base_notify.h"
#include <uv.h>
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
PrintBaseNotify::PrintBaseNotify(napi_env env, const std::string &type, napi_ref ref)
: PrintCallbackStub(), env_(env), type_(type), ref_(ref)
{}
PrintBaseNotify::~PrintBaseNotify()
{
PRINT_HILOGD("");
}
void PrintBaseNotify::OnCallBack(MessageParcel &data)
{
PRINT_HILOGD("Pause callback in");
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(env_, &loop);
if (loop == nullptr) {
PRINT_HILOGE("Failed to get uv event loop");
return;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return;
}
NotifyData *notifyData = GetNotifyData();
notifyData->env = env_;
notifyData->ref = ref_;
notifyData->type = type_;
work->data = notifyData;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
NotifyData *notifyData = static_cast<NotifyData *>(work->data);
if (notifyData != nullptr) {
napi_value undefined = 0;
napi_get_undefined(notifyData->env, &undefined);
napi_value callbackFunc = nullptr;
napi_get_reference_value(notifyData->env, notifyData->ref, &callbackFunc);
napi_value callbackResult = nullptr;
napi_value callbackValues[NapiPrintUtils::ARGC_ONE] = { 0 };
napi_get_undefined(notifyData->env, &callbackValues[NapiPrintUtils::INDEX_ZERO]);
napi_call_function(
notifyData->env, nullptr, callbackFunc, NapiPrintUtils::ARGC_ONE, callbackValues, &callbackResult);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete notifyData;
notifyData = nullptr;
}
});
}
NotifyData *PrintBaseNotify::GetNotifyData()
{
return new (std::nothrow) NotifyData;
}
} // namespace OHOS::Print

View File

@ -1,42 +0,0 @@
/*
* 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 "print_callback_stub.h"
#include "print_common.h"
#include "print_log.h"
namespace OHOS::Print {
int32_t PrintCallbackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
auto descriptorToken = data.ReadInterfaceToken();
if (descriptorToken != GetDescriptor()) {
PRINT_HILOGE("Remote descriptor not the same as local descriptor.");
return E_PRINT_IPC_ERROR;
}
PRINT_HILOGD("PrintCallbackStub code----> %{public}u", code);
switch (code) {
case PRINT_NOTIFY: {
OnCallBack(data);
break;
}
default: {
return OHOS::UNKNOWN_TRANSACTION;
}
}
return E_PRINT_OK;
}
} // namespace OHOS::Print

View File

@ -1,188 +0,0 @@
/*
* 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 "print_extension_callback_stub.h"
#include "print_common.h"
#include "print_log.h"
#include "print_resolution.h"
namespace OHOS::Print {
PrintExtensionCallbackStub::PrintExtensionCallbackStub() : extCb_(nullptr), jobCb_(nullptr), cb_(nullptr)
{
cmdMap_[PRINT_EXTCB] = &PrintExtensionCallbackStub::HandleExtCallback;
cmdMap_[PRINT_EXTCB_PRINTER] = &PrintExtensionCallbackStub::HandlePrinterCallback;
cmdMap_[PRINT_EXTCB_PRINTJOB] = &PrintExtensionCallbackStub::HandlePrintJobCallback;
cmdMap_[PRINT_EXTCB_PRINTCAPABILITY] = &PrintExtensionCallbackStub::HandleCapabilityCallback;
}
int32_t PrintExtensionCallbackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
PRINT_HILOGD("OnRemoteRequest started, code = %{public}d", code);
auto descriptorToken = data.ReadInterfaceToken();
if (descriptorToken != GetDescriptor()) {
PRINT_HILOGE("Remote descriptor not the same as local descriptor.");
return E_PRINT_IPC_ERROR;
}
auto itFunc = cmdMap_.find(code);
if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second;
if (requestFunc != nullptr) {
return (this->*requestFunc)(data, reply);
}
}
PRINT_HILOGW("default case, need check.");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
bool PrintExtensionCallbackStub::OnCallback()
{
if (extCb_ != nullptr) {
return extCb_();
}
return false;
}
bool PrintExtensionCallbackStub::OnCallback(uint32_t printerId)
{
if (cb_ != nullptr) {
return cb_(printerId);
}
return false;
}
bool PrintExtensionCallbackStub::OnCallback(const PrintJob &job)
{
if (jobCb_ != nullptr) {
return jobCb_(job);
}
return false;
}
bool PrintExtensionCallbackStub::OnCallback(uint32_t printerId, MessageParcel &reply) // PrinterCapability& reply
{
if (capability_ != nullptr) {
PrinterCapability capability;
if (capability_(printerId, capability)) {
capability.ConvertToParcel(reply);
return true;
}
}
return false;
}
void PrintExtensionCallbackStub::SetExtCallback(PrintExtCallback cb)
{
extCb_ = cb;
}
void PrintExtensionCallbackStub::SetPrintJobCallback(PrintJobCallback cb)
{
jobCb_ = cb;
}
void PrintExtensionCallbackStub::SetPrinterCallback(PrinterCallback cb)
{
cb_ = cb;
}
void PrintExtensionCallbackStub::SetCapabilityCallback(PrinterCapabilityCallback cb)
{
capability_ = cb;
}
bool PrintExtensionCallbackStub::HandleExtCallback(MessageParcel &data, MessageParcel &reply)
{
return OnCallback();
}
bool PrintExtensionCallbackStub::HandlePrinterCallback(MessageParcel &data, MessageParcel &reply)
{
uint32_t printerId = data.ReadUint32();
return OnCallback(printerId);
}
void PrintExtensionCallbackStub::dataReadJob(MessageParcel &data, PrintJob &job)
{
uint32_t fileLength = data.ReadUint32();
std::vector<std::string> files;
for (uint32_t i = 0; i < fileLength; i++) {
files.push_back(data.ReadString());
}
job.SetFiles(files);
job.SetJobId(data.ReadUint32());
job.SetPrintId(data.ReadUint32());
job.SetJobState(data.ReadUint32());
job.SetCopyNumber(data.ReadUint32());
PrintRange range;
std::vector<uint32_t> pages;
range.SetStartPage(data.ReadUint32());
range.SetEndPage(data.ReadUint32());
uint32_t pageLength = data.ReadUint32();
for (uint32_t i = 0; i < pageLength; i++) {
pages.push_back(data.ReadUint32());
}
range.SetPages(pages);
job.SetPageRange(range);
job.SetIsSequential(data.ReadUint32());
PrintPageSize pageSize;
pageSize.SetId(data.ReadString());
pageSize.SetName(data.ReadString());
pageSize.SetWidth(data.ReadUint32());
pageSize.SetHeight(data.ReadUint32());
job.SetPageSize(pageSize);
job.SetIsLandscape(data.ReadUint32());
job.SetColorMode(data.ReadUint32());
job.SetDuplexMode(data.ReadUint32());
PrintMargin margin;
margin.SetTop(data.ReadUint32());
margin.SetBottom(data.ReadUint32());
margin.SetLeft(data.ReadUint32());
margin.SetRight(data.ReadUint32());
job.SetMargin(margin);
PreviewAttribute previewAttr;
PrintRange previewRange;
previewAttr.SetResult(data.ReadString());
previewRange.SetStartPage(data.ReadUint32());
previewRange.SetEndPage(data.ReadUint32());
uint32_t previewPageLength = data.ReadUint32();
std::vector<uint32_t> arrayPages;
for (uint32_t i = 0; i < previewPageLength; i++) {
arrayPages.push_back(data.ReadUint32());
}
previewRange.SetPages(arrayPages);
previewAttr.SetPreviewRange(previewRange);
job.SetPreview(previewAttr);
}
bool PrintExtensionCallbackStub::HandlePrintJobCallback(MessageParcel &data, MessageParcel &reply)
{
PrintJob job;
job.BuildFromParcel(data);
return OnCallback(job);
}
bool PrintExtensionCallbackStub::HandleCapabilityCallback(MessageParcel &data, MessageParcel &reply)
{
uint32_t printerId = data.ReadUint32();
return OnCallback(printerId, reply);
}
} // namespace OHOS::Print

View File

@ -1,85 +0,0 @@
/*
* 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 "print_extension_info.h"
#include "print_log.h"
namespace OHOS::Print {
PrintExtensionInfo::PrintExtensionInfo()
: extensionId_(0), vendorId_(0), vendorName_("PrintExtensionInfo"), vendorIcon_(0), version_("PrintExtensionInfo")
{}
void PrintExtensionInfo::SetExtensionId(uint32_t extensionId)
{
extensionId_ = extensionId;
}
void PrintExtensionInfo::SetVendorId(uint32_t vendorId)
{
vendorId_ = vendorId;
}
void PrintExtensionInfo::SetVendorName(const std::string &vendorName)
{
vendorName_ = vendorName;
}
void PrintExtensionInfo::SetVendorIcon(uint32_t vendorIcon)
{
vendorIcon_ = vendorIcon;
}
void PrintExtensionInfo::SetVersion(const std::string &version)
{
version_ = version;
}
uint32_t PrintExtensionInfo::GetExtensionId() const
{
return extensionId_;
}
uint32_t PrintExtensionInfo::GetVendorId() const
{
return vendorId_;
}
const std::string &PrintExtensionInfo::GetVendorName() const
{
return vendorName_;
}
uint32_t PrintExtensionInfo::GetVendorIcon() const
{
return vendorIcon_;
}
const std::string &PrintExtensionInfo::GetVersion() const
{
return version_;
}
void PrintExtensionInfo::Dump()
{
PRINT_HILOGD("extensionId = %{public}d", extensionId_);
PRINT_HILOGD("vendorId_ = %{public}d", vendorId_);
PRINT_HILOGD("vendorName_ = %{public}s", vendorName_.c_str());
PRINT_HILOGD("vendorIcon_ = %{public}d", vendorIcon_);
PRINT_HILOGD("version_ = %{public}s", version_.c_str());
}
PrintExtensionInfo::~PrintExtensionInfo() {}
} // namespace OHOS::Print

View File

@ -1,77 +0,0 @@
/*
* 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 "print_fail_notify.h"
#include <uv.h>
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
PrintFailNotify::PrintFailNotify(napi_env env, const std::string &type, napi_ref ref) : PrintBaseNotify(env, type, ref)
{}
PrintFailNotify::~PrintFailNotify()
{
PRINT_HILOGD("");
}
void PrintFailNotify::OnCallBack(MessageParcel &data)
{
PRINT_HILOGD("Failed callback in");
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(env_, &loop);
if (loop == nullptr) {
PRINT_HILOGE("Failed to get uv event loop");
return;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return;
}
NotifyData *notifyData = GetNotifyData();
notifyData->env = env_;
notifyData->ref = ref_;
notifyData->type = type_;
notifyData->firstArgv = data.ReadUint32();
PRINT_HILOGD("recv error code is %{public}d", notifyData->firstArgv);
work->data = notifyData;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
PRINT_HILOGD("this is new fail callback");
NotifyData *notifyData = static_cast<NotifyData *>(work->data);
napi_value undefined = 0;
napi_get_undefined(notifyData->env, &undefined);
napi_value callbackFunc = nullptr;
napi_get_reference_value(notifyData->env, notifyData->ref, &callbackFunc);
napi_value result = nullptr;
napi_value callbackValue;
napi_create_uint32(notifyData->env, notifyData->firstArgv, &callbackValue);
napi_call_function(
notifyData->env, nullptr, callbackFunc, NapiPrintUtils::ARGC_ONE, &callbackValue, &result);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete notifyData;
notifyData = nullptr;
});
}
} // namespace OHOS::Print

View File

@ -1,448 +0,0 @@
/*
* 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 "print_job.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
PrintJob::PrintJob()
: jobId_(0), jobState_(1), copyNumber_(1), isSequential_(true), isLandscape_(1), colorMode_(1), duplexMode_(1)
{}
PrintJob::PrintJob(const PrintJob &right)
{
files_.clear();
files_.assign(right.files_.begin(), right.files_.end());
printerId_ = right.printerId_;
jobId_ = right.jobId_;
jobState_ = right.jobState_;
copyNumber_ = right.copyNumber_;
pageRange_ = right.pageRange_;
isSequential_ = right.isSequential_;
pageSize_ = right.pageSize_;
isLandscape_ = right.isLandscape_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
margin_ = right.margin_;
preview_ = right.preview_;
}
PrintJob &PrintJob::operator=(PrintJob &right)
{
if (this != &right) {
files_.clear();
files_.assign(right.files_.begin(), right.files_.end());
printerId_ = right.printerId_;
jobId_ = right.jobId_;
jobState_ = right.jobState_;
copyNumber_ = right.copyNumber_;
pageRange_ = right.pageRange_;
isSequential_ = right.isSequential_;
pageSize_ = right.pageSize_;
isLandscape_ = right.isLandscape_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
margin_ = right.margin_;
preview_ = right.preview_;
}
return *this;
}
PrintJob::~PrintJob() {}
void PrintJob::SetFiles(const std::vector<std::string> &files)
{
files_.clear();
files_.assign(files.begin(), files.end());
}
void PrintJob::SetJobId(uint32_t jobId)
{
jobId_ = jobId;
}
void PrintJob::SetPrintId(uint32_t printerid)
{
printerId_ = printerid;
}
void PrintJob::SetJobState(uint32_t jobState)
{
jobState_ = jobState;
}
void PrintJob::SetCopyNumber(uint32_t copyNumber)
{
copyNumber_ = copyNumber;
}
void PrintJob::SetPageRange(const PrintRange &pageRange)
{
pageRange_ = pageRange;
}
void PrintJob::SetIsSequential(bool isSequential)
{
isSequential_ = isSequential;
}
void PrintJob::SetPageSize(const PrintPageSize &pageSize)
{
pageSize_ = pageSize;
}
void PrintJob::SetIsLandscape(bool isLandscape)
{
isLandscape_ = isLandscape;
}
void PrintJob::SetColorMode(uint32_t colorMode)
{
colorMode_ = colorMode;
}
void PrintJob::SetDuplexMode(uint32_t duplexmode)
{
duplexMode_ = duplexmode;
}
void PrintJob::SetMargin(const PrintMargin &margin)
{
margin_ = margin;
}
void PrintJob::SetPreview(const PreviewAttribute &preview)
{
preview_ = preview;
}
void PrintJob::GetFiles(std::vector<std::string> &files) const
{
files.clear();
files.assign(files_.begin(), files_.end());
}
uint32_t PrintJob::GetJobId() const
{
return jobId_;
}
uint32_t PrintJob::GetPrinterId() const
{
return printerId_;
}
uint32_t PrintJob::GetJobState() const
{
return jobState_;
}
uint32_t PrintJob::GetCopyNumber() const
{
return copyNumber_;
}
void PrintJob::GetPageRange(PrintRange &range) const
{
range = pageRange_;
}
bool PrintJob::GetIsSequential() const
{
return isSequential_;
}
void PrintJob::GetPageSize(PrintPageSize &pageSize) const
{
pageSize = pageSize_;
}
bool PrintJob::GetIsLandscape() const
{
return isLandscape_;
}
uint32_t PrintJob::GetColorMode() const
{
return colorMode_;
}
uint32_t PrintJob::GetDuplexMode() const
{
return duplexMode_;
}
void PrintJob::GetMargin(PrintMargin &margin) const
{
margin = margin_;
}
void PrintJob::GetPreview(PreviewAttribute &previewAttr) const
{
previewAttr = preview_;
}
void PrintJob::ConvertToParcel(MessageParcel &reply) const
{
std::vector<std::string> files;
GetFiles(files);
reply.WriteUint32((uint32_t)files.size());
for (uint32_t i = 0; i < (uint32_t)files.size(); i++) {
reply.WriteString(files[i]);
}
reply.WriteUint32(GetJobId());
reply.WriteUint32(GetPrinterId());
reply.WriteUint32(GetJobState());
reply.WriteUint32(GetCopyNumber());
PrintRange range;
GetPageRange(range);
reply.WriteUint32(range.GetStartPage());
reply.WriteUint32(range.GetEndPage());
std::vector<uint32_t> pages;
range.GetPages(pages);
reply.WriteUint32((uint32_t)pages.size());
for (uint32_t i = 0; i < (uint32_t)pages.size(); i++) {
reply.WriteUint32(pages[i]);
}
reply.WriteUint32(GetIsSequential());
PrintPageSize pageSize;
GetPageSize(pageSize);
reply.WriteString(pageSize.GetId());
reply.WriteString(pageSize.GetName());
reply.WriteUint32(pageSize.GetWidth());
reply.WriteUint32(pageSize.GetHeight());
reply.WriteUint32(GetIsLandscape());
reply.WriteUint32(GetColorMode());
reply.WriteUint32(GetDuplexMode());
PrintMargin margin;
GetMargin(margin);
reply.WriteUint32(margin.GetTop());
reply.WriteUint32(margin.GetBottom());
reply.WriteUint32(margin.GetLeft());
reply.WriteUint32(margin.GetRight());
PreviewAttribute preview;
GetPreview(preview);
reply.WriteString(preview.GetResult());
range.Reset();
preview.GetPreviewRange(range);
reply.WriteUint32(range.GetStartPage());
reply.WriteUint32(range.GetEndPage());
range.GetPages(pages);
reply.WriteUint32((uint32_t)pages.size());
for (uint32_t i = 0; i < (uint32_t)pages.size(); i++) {
reply.WriteUint32(pages[i]);
}
}
void PrintJob::SetBuild(MessageParcel &data)
{
PrintPageSize pageSize;
pageSize.SetId(data.ReadString());
pageSize.SetName(data.ReadString());
pageSize.SetWidth(data.ReadUint32());
pageSize.SetHeight(data.ReadUint32());
SetPageSize(pageSize);
SetIsLandscape(data.ReadUint32());
SetColorMode(data.ReadUint32());
SetDuplexMode(data.ReadUint32());
PrintMargin minMargin;
minMargin.SetTop(data.ReadUint32());
minMargin.SetBottom(data.ReadUint32());
minMargin.SetLeft(data.ReadUint32());
minMargin.SetRight(data.ReadUint32());
SetMargin(minMargin);
}
void PrintJob::BuildFromParcel(MessageParcel &data)
{
uint32_t fileLength = data.ReadUint32();
std::vector<std::string> files;
uint32_t index = 0;
for (index = 0; index < fileLength; index++) {
files.push_back(data.ReadString());
}
SetFiles(files);
SetJobId(data.ReadUint32());
SetPrintId(data.ReadUint32());
SetJobState(data.ReadUint32());
SetCopyNumber(data.ReadUint32());
PrintRange range;
range.SetStartPage(data.ReadUint32());
range.SetEndPage(data.ReadUint32());
uint32_t pageLength = data.ReadUint32();
std::vector<uint32_t> rangePages;
for (index = 0; index < pageLength; index++) {
rangePages.push_back(data.ReadUint32());
}
range.SetPages(rangePages);
SetPageRange(range);
SetIsSequential(data.ReadUint32());
SetBuild(data);
PreviewAttribute previewAttr;
previewAttr.SetResult(data.ReadString());
range.Reset();
range.SetStartPage(data.ReadUint32());
range.SetEndPage(data.ReadUint32());
uint32_t previewPageLength = data.ReadUint32();
std::vector<uint32_t> previewRangePages;
for (index = 0; index < previewPageLength; index++) {
previewRangePages.push_back(data.ReadUint32());
}
range.SetPages(previewRangePages);
previewAttr.SetPreviewRange(range);
SetPreview(previewAttr);
Dump();
}
void PrintJob::SetSubPageRange(napi_env env, napi_value &subPageRange)
{
napi_create_object(env, &subPageRange);
NapiPrintUtils::SetUint32Property(env, subPageRange, "startPage", pageRange_.GetStartPage());
NapiPrintUtils::SetUint32Property(env, subPageRange, "endPage", pageRange_.GetEndPage());
napi_value arrPreviewPages;
status = napi_create_array(env, &arrPreviewPages);
PrintRange previewPrintRange;
std::vector<uint32_t> previewRangePages;
preview_.GetPreviewRange(previewPrintRange);
previewPrintRange.GetPages(previewRangePages);
uint32_t arrPreviewPagesLength = previewRangePages.size();
for (uint32_t i = 0; i < arrPreviewPagesLength; i++) {
napi_value value;
napi_create_uint32(env, previewRangePages[i], &value);
status = napi_set_element(env, arrPreviewPages, i, value);
}
napi_set_named_property(env, subPageRange, "files", arrPreviewPages);
}
void PrintJob::SetPageSize(napi_env env, napi_value &pageSize)
{
NapiPrintUtils::SetStringPropertyUtf8(env, pageSize, "id", pageSize_.GetId());
NapiPrintUtils::SetStringPropertyUtf8(env, pageSize, "name", pageSize_.GetName().c_str());
NapiPrintUtils::SetUint32Property(env, pageSize, "width", pageSize_.GetWidth());
NapiPrintUtils::SetUint32Property(env, pageSize, "height", pageSize_.GetHeight());
}
void PrintJob::SetMargin(napi_env env, napi_value &margin)
{
NapiPrintUtils::SetUint32Property(env, margin, "top", margin_.GetTop());
NapiPrintUtils::SetUint32Property(env, margin, "bottom", margin_.GetBottom());
NapiPrintUtils::SetUint32Property(env, margin, "left", margin_.GetLeft());
NapiPrintUtils::SetUint32Property(env, margin, "right", margin_.GetRight());
}
void PrintJob::ConvertToJs(napi_env env, napi_value *result) const
{
napi_create_object(env, result);
napi_value arrFiles;
napi_status status = napi_create_array(env, &arrFiles);
uint32_t arrFilesLength = files_.size();
for (uint32_t i = 0; i < arrFilesLength; i++) {
napi_value value;
status = napi_create_string_utf8(env, files_[i].c_str(), NAPI_AUTO_LENGTH, &value);
status = napi_set_element(env, arrFiles, i, value);
}
napi_set_named_property(env, *result, "files", arrFiles);
NapiPrintUtils::SetUint32Property(env, *result, "jobId", GetJobId());
NapiPrintUtils::SetUint32Property(env, *result, "printerId", GetPrinterId());
NapiPrintUtils::SetUint32Property(env, *result, "jobState", GetJobState());
NapiPrintUtils::SetUint32Property(env, *result, "copyNumber", GetCopyNumber());
napi_value pageRange;
napi_create_object(env, &pageRange);
NapiPrintUtils::SetUint32Property(env, pageRange, "startPage", pageRange_.GetStartPage());
NapiPrintUtils::SetUint32Property(env, pageRange, "endPage", pageRange_.GetEndPage());
napi_value arrPages;
status = napi_create_array(env, &arrPages);
std::vector<uint32_t> pages;
pageRange_.GetPages(pages);
uint32_t arrPagesLength = pages.size();
for (uint32_t i = 0; i < arrPagesLength; i++) {
napi_value value;
napi_create_uint32(env, pages[i], &value);
status = napi_set_element(env, arrPages, i, value);
}
napi_set_named_property(env, pageRange, "files", arrPages);
NapiPrintUtils::SetUint32Property(env, *result, "isSequential", GetIsSequential());
napi_value pageSize;
napi_create_object(env, &pageSize);
SetPageSize(env, pageSize);
NapiPrintUtils::SetUint32Property(env, *result, "isLandscape", GetIsLandscape());
NapiPrintUtils::SetUint32Property(env, *result, "colorMode", GetColorMode());
NapiPrintUtils::SetUint32Property(env, *result, "duplexMode", GetDuplexMode());
napi_value margin;
napi_create_object(env, &margin);
SetMargin(env, margin);
napi_value preview;
napi_create_object(env, &preview);
NapiPrintUtils::SetStringPropertyUtf8(env, preview, "result", preview_.GetResult().c_str());
napi_value subPageRange;
napi_create_object(env, &subPageRange);
SetSubPageRange(env, subPageRange);
napi_set_named_property(env, preview, "pageRange", subPageRange);
napi_set_named_property(env, *result, "pageRange", pageRange);
napi_set_named_property(env, *result, "pageSize", pageSize);
napi_set_named_property(env, *result, "margin", margin);
napi_set_named_property(env, *result, "preview", preview);
}
void PrintJob::BuildFromJs(napi_env env, napi_value capValue) {}
void PrintJob::Dump()
{
uint32_t fileLength = files_.size();
for (uint32_t i = 0; i < fileLength; i++) {
PRINT_HILOGD("files_ = %{public}s", files_[i].c_str());
}
PRINT_HILOGD("jobId_ = %{public}d", jobId_);
PRINT_HILOGD("printerId_ = %{public}d", printerId_);
PRINT_HILOGD("jobState_ = %{public}d", jobState_);
PRINT_HILOGD("copyNumber_ = %{public}d", copyNumber_);
PRINT_HILOGD("isSequential_ = %{public}d", isSequential_);
PRINT_HILOGD("isLandscape_ = %{public}d", isLandscape_);
PRINT_HILOGD("colorMode_ = %{public}d", colorMode_);
PRINT_HILOGD("duplexMode_ = %{public}d", duplexMode_);
pageRange_.Dump();
pageSize_.Dump();
margin_.Dump();
preview_.Dump();
}
} // namespace OHOS::Print

View File

@ -1,526 +0,0 @@
/*
* 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 "print_manager_client.h"
#include "iservice_registry.h"
#include "print_extension_callback_stub.h"
#include "print_log.h"
#include "print_sync_load_callback.h"
#include "system_ability_definition.h"
namespace OHOS::Print {
std::mutex PrintManagerClient::instanceLock_;
sptr<PrintManagerClient> PrintManagerClient::instance_ = nullptr;
PrintManagerClient::PrintManagerClient() : printServiceProxy_(nullptr), deathRecipient_(nullptr) {}
PrintManagerClient::~PrintManagerClient() {}
sptr<PrintManagerClient> PrintManagerClient::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> autoLock(instanceLock_);
if (instance_ == nullptr) {
instance_ = new PrintManagerClient;
}
}
return instance_;
}
bool PrintManagerClient::On(
const std::string &type, uint32_t &state, PrinterInfo &info, const sptr<IPrintCallback> &listener)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient On succeeded.");
return true;
}
bool PrintManagerClient::Off(const std::string &type)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient Off succeeded.");
return printServiceProxy_->Off(type);
}
bool PrintManagerClient::RegisterExtCallback(uint32_t callbackId, PrintExtCallback cb)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return false;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
auto it = extCallbackMap_.find(callbackId);
if (it == extCallbackMap_.end()) {
callbackStub = new PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return false;
}
callbackStub->SetExtCallback(cb);
extCallbackMap_.insert(std::make_pair(callbackId, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetExtCallback(cb);
}
bool ret = printServiceProxy_->RegisterExtCallback(callbackId, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback %{public}s.", ret ? "success" : "failed");
return ret;
}
bool PrintManagerClient::RegisterExtCallback(uint32_t callbackId, PrintJobCallback cb)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return false;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
auto it = extCallbackMap_.find(callbackId);
if (it == extCallbackMap_.end()) {
callbackStub = new PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return false;
}
callbackStub->SetPrintJobCallback(cb);
extCallbackMap_.insert(std::make_pair(callbackId, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetPrintJobCallback(cb);
}
bool ret = printServiceProxy_->RegisterExtCallback(callbackId, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback %{public}s.", ret ? "success" : "failed");
return ret;
}
bool PrintManagerClient::RegisterExtCallback(uint32_t callbackId, PrinterCapabilityCallback cb)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return false;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
auto it = extCallbackMap_.find(callbackId);
if (it == extCallbackMap_.end()) {
callbackStub = new PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return false;
}
callbackStub->SetCapabilityCallback(cb);
extCallbackMap_.insert(std::make_pair(callbackId, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetCapabilityCallback(cb);
}
bool ret = printServiceProxy_->RegisterExtCallback(callbackId, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback %{public}s.", ret ? "success" : "failed");
return ret;
}
bool PrintManagerClient::RegisterExtCallback(uint32_t callbackId, PrinterCallback cb)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return false;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
auto it = extCallbackMap_.find(callbackId);
if (it == extCallbackMap_.end()) {
callbackStub = new PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return false;
}
callbackStub->SetPrinterCallback(cb);
extCallbackMap_.insert(std::make_pair(callbackId, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetPrinterCallback(cb);
}
bool ret = printServiceProxy_->RegisterExtCallback(callbackId, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback %{public}s.", ret ? "success" : "failed");
return ret;
}
bool PrintManagerClient::UnregisterAllExtCallback()
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
bool ret = printServiceProxy_->UnregisterAllExtCallback();
PRINT_HILOGD("PrintManagerClient UnregisterAllExtCallback %{public}s.", ret ? "success" : "fail");
if (ret) {
extCallbackMap_.clear();
}
return ret;
}
sptr<IPrintService> PrintManagerClient::GetPrintServiceProxy()
{
sptr<ISystemAbilityManager> systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (systemAbilityManager == nullptr) {
PRINT_HILOGE("Getting SystemAbilityManager failed.");
return nullptr;
}
auto systemAbility = systemAbilityManager->GetSystemAbility(PRINT_SERVICE_ID, "");
if (systemAbility == nullptr) {
PRINT_HILOGE("Get SystemAbility failed.");
return nullptr;
}
deathRecipient_ = new PrintSaDeathRecipient();
systemAbility->AddDeathRecipient(deathRecipient_);
sptr<IPrintService> serviceProxy = iface_cast<IPrintService>(systemAbility);
if (serviceProxy == nullptr) {
PRINT_HILOGE("Get PrintManagerClientProxy from SA failed.");
return nullptr;
}
PRINT_HILOGD("Getting PrintManagerClientProxy succeeded.");
return serviceProxy;
}
void PrintManagerClient::OnRemoteSaDied(const wptr<IRemoteObject> &remote)
{
printServiceProxy_ = GetPrintServiceProxy();
}
int32_t PrintManagerClient::StartPrint()
{
PRINT_HILOGD("PrintManagerClient EnqueueTask start.");
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StartPrint quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient StartPrint succeeded.");
return printServiceProxy_->StartPrint();
}
bool PrintManagerClient::ConnectPrinter(uint32_t printerId)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("AddPrinters quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient AddPrinters succeeded.");
return printServiceProxy_->ConnectPrinter(printerId);
}
bool PrintManagerClient::DisconnectPrinter(uint32_t printerId)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("DisconnectPrinter quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient DisconnectPrinter succeeded.");
return printServiceProxy_->DisconnectPrinter(printerId);
}
bool PrintManagerClient::QueryAllExtension(std::vector<PrintExtensionInfo> &arrayExtensionInfo)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("QueryAllExtension quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient QueryAllExtension succeeded.");
return printServiceProxy_->QueryAllExtension(arrayExtensionInfo);
}
bool PrintManagerClient::StartDiscoverPrinter(std::vector<uint32_t> extensionList)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StartDiscoverPrinter quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient StartDiscoverPrinter succeeded.");
return printServiceProxy_->StartDiscoverPrinter(extensionList);
}
bool PrintManagerClient::StopDiscoverPrinter()
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StopDiscoverPrinter quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient StopDiscoverPrint succeeded.");
return printServiceProxy_->StopDiscoverPrinter();
}
bool PrintManagerClient::StartPrintJob(const PrintJob &jobinfo)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StartPrintJob quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient StartPrintJob succeeded.");
return printServiceProxy_->StartPrintJob(jobinfo);
}
bool PrintManagerClient::CancelPrintJob(const PrintJob &jobinfo)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("CancelPrintJob quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient CancelPrintJob succeeded.");
return printServiceProxy_->CancelPrintJob(jobinfo);
}
bool PrintManagerClient::AddPrinters(std::vector<PrinterInfo> arrayPrintInfo)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("AddPrinters quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient AddPrinters succeeded.");
return printServiceProxy_->AddPrinters(arrayPrintInfo);
}
bool PrintManagerClient::RemovePrinters(std::vector<PrinterInfo> arrayPrintInfo)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RemovePrinters quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient RemovePrinters succeeded.");
return printServiceProxy_->RemovePrinters(arrayPrintInfo);
}
bool PrintManagerClient::UpdatePrinterState(uint32_t printerId, uint32_t state)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("UpdatePrinterState quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient UpdatePrinterState succeeded.");
return printServiceProxy_->UpdatePrinterState(printerId, state);
}
bool PrintManagerClient::UpdatePrinterJobState(uint32_t jobId, uint32_t state)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("UpdatePrinterJobState quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient UpdatePrinterJobState succeeded.");
return printServiceProxy_->UpdatePrinterJobState(jobId, state);
}
bool PrintManagerClient::RequestPreview(const PrintJob &jobinfo, std::string &previewResult)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RequestPreview quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient RequestPreview succeeded.");
return printServiceProxy_->RequestPreview(jobinfo, previewResult);
}
bool PrintManagerClient::QueryPrinterCapability(uint32_t printerId, PrinterCapability &printerCapability)
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("QueryPrinterCapability quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient QueryPrinterCapability succeeded.");
return printServiceProxy_->QueryPrinterCapability(printerId, printerCapability);
}
bool PrintManagerClient::CheckPermission()
{
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return false;
}
PRINT_HILOGD("PrintManagerClient CheckPermission succeeded.");
PRINT_HILOGD("Check Permission enable");
return printServiceProxy_->CheckPermission();
}
bool PrintManagerClient::LoadServer()
{
if (ready_) {
return true;
}
std::lock_guard<std::mutex> lock(loadMutex_);
if (ready_) {
return true;
}
auto sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sm == nullptr) {
PRINT_HILOGE("GetSystemAbilityManager return null");
return false;
}
sptr<PrintSyncLoadCallback> loadCallback_ = new (std::nothrow) PrintSyncLoadCallback();
if (loadCallback_ == nullptr) {
PRINT_HILOGE("new PrintSyncLoadCallback fail");
return false;
}
int32_t result = sm->LoadSystemAbility(PRINT_SERVICE_ID, loadCallback_);
if (result != ERR_OK) {
PRINT_HILOGE("LoadSystemAbility %{public}d failed, result: %{public}d", PRINT_SERVICE_ID, result);
return false;
}
{
std::unique_lock<std::mutex> conditionLock(conditionMutex_);
auto waitStatus = syncCon_.wait_for(
conditionLock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), [this]() { return ready_; });
if (!waitStatus) {
PRINT_HILOGE("print server load sa timeout");
return false;
}
}
return true;
}
void PrintManagerClient::LoadServerSuccess()
{
std::unique_lock<std::mutex> lock(conditionMutex_);
ready_ = true;
syncCon_.notify_one();
PRINT_HILOGE("load print server success");
}
void PrintManagerClient::LoadServerFail()
{
ready_ = false;
PRINT_HILOGE("load print server fail");
}
} // namespace OHOS::Print

View File

@ -1,91 +0,0 @@
/*
* 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 "print_margin.h"
#include "print_log.h"
namespace OHOS::Print {
PrintMargin::PrintMargin() : top_(0), bottom_(0), left_(0), right_(0) {}
PrintMargin::PrintMargin(const PrintMargin &right)
{
top_ = right.top_;
bottom_ = right.bottom_;
left_ = right.left_;
right_ = right.right_;
}
PrintMargin &PrintMargin::operator=(const PrintMargin &right)
{
if (this != &right) {
top_ = right.top_;
bottom_ = right.bottom_;
left_ = right.left_;
right_ = right.right_;
}
return *this;
}
PrintMargin::~PrintMargin() {}
void PrintMargin::SetTop(uint32_t top)
{
top_ = top;
}
void PrintMargin::SetBottom(uint32_t bottom)
{
bottom_ = bottom;
}
void PrintMargin::SetLeft(uint32_t left)
{
left_ = left;
}
void PrintMargin::SetRight(uint32_t right)
{
right_ = right;
}
uint32_t PrintMargin::GetTop() const
{
return top_;
}
uint32_t PrintMargin::GetBottom() const
{
return bottom_;
}
uint32_t PrintMargin::GetLeft() const
{
return left_;
}
uint32_t PrintMargin::GetRight() const
{
return right_;
}
void PrintMargin::Dump()
{
PRINT_HILOGD("top_ = %{public}d", top_);
PRINT_HILOGD("bottom_ = %{public}d", bottom_);
PRINT_HILOGD("left_ = %{public}d", left_);
PRINT_HILOGD("right_ = %{public}d", right_);
}
} // namespace OHOS::Print

View File

@ -1,35 +0,0 @@
/*
* 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 "print_notify.h"
#include <uv.h>
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
PrintNotify::PrintNotify() {}
PrintNotify::~PrintNotify()
{
PRINT_HILOGD("");
}
void PrintNotify::OnCallBack(MessageParcel &data)
{
PRINT_HILOGD("Failed callback in");
}
} // namespace OHOS::Print

View File

@ -1,119 +0,0 @@
/*
* 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 "print_page_size.h"
#include "print_log.h"
namespace OHOS::Print {
std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> PrintPageSize::pageSize_;
void PrintPageSize::BuildPageSizeMap()
{
PRINT_HILOGD("");
}
PrintPageSize::PrintPageSize() : id_(""), name_("PrintPageSize"), width_(0), height_(0) {}
PrintPageSize::PrintPageSize(PAGE_SIZE_ID id, DiscretePageName name, uint32_t width, uint32_t height)
{
id_ = id;
name_ = name;
width_ = width;
height_ = height;
}
PrintPageSize PrintPageSize::GetPageSize(PageSizeId id)
{
uint32_t pageSizeId = (uint32_t)id;
if (pageSizeId < (uint32_t)sizeof(PAGE_SIZE_TABLE)) {
std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>>::iterator iter;
iter = pageSize_.find(PAGE_SIZE_TABLE[pageSizeId]);
if (iter != pageSize_.end()) {
return *(iter->second);
}
}
PrintPageSize printPageSize;
return printPageSize;
}
PrintPageSize::PrintPageSize(const PrintPageSize &right)
{
id_ = right.id_;
name_ = right.name_;
width_ = right.width_;
height_ = right.height_;
}
PrintPageSize &PrintPageSize::operator=(const PrintPageSize &right)
{
if (this != &right) {
id_ = right.id_;
name_ = right.name_;
width_ = right.width_;
height_ = right.height_;
}
return *this;
}
PrintPageSize::~PrintPageSize() {}
void PrintPageSize::SetId(const std::string &id)
{
id_ = id;
}
void PrintPageSize::SetName(const std::string &name)
{
name_ = name;
}
void PrintPageSize::SetWidth(uint32_t width)
{
width_ = width;
}
void PrintPageSize::SetHeight(uint32_t height)
{
height_ = height;
}
const std::string &PrintPageSize::GetId() const
{
return id_;
}
const std::string &PrintPageSize::GetName() const
{
return name_;
}
uint32_t PrintPageSize::GetWidth() const
{
return width_;
}
uint32_t PrintPageSize::GetHeight() const
{
return height_;
}
void PrintPageSize::Dump()
{
PRINT_HILOGD("top_ = %{public}s", id_.c_str());
PRINT_HILOGD("name_ = %{public}s", name_.c_str());
PRINT_HILOGD("width_ = %{public}d", width_);
PRINT_HILOGD("height_ = %{public}d", height_);
}
} // namespace OHOS::Print

View File

@ -1,45 +0,0 @@
#include "print_preview_attribute.h"
#include "print_log.h"
namespace OHOS::Print {
PreviewAttribute::PreviewAttribute() : result_("") {}
PreviewAttribute::PreviewAttribute(const PreviewAttribute &right) {}
PreviewAttribute &PreviewAttribute::operator=(const PreviewAttribute &right)
{
if (this != &right) {
result_ = right.result_;
previewRange_ = right.previewRange_;
}
return *this;
}
PreviewAttribute::~PreviewAttribute() {}
void PreviewAttribute::SetResult(const std::string &result)
{
result_ = result;
}
void PreviewAttribute::SetPreviewRange(const PrintRange &previewRange)
{
previewRange_ = previewRange;
}
const std::string &PreviewAttribute::GetResult() const
{
return result_;
}
void PreviewAttribute::GetPreviewRange(PrintRange &range) const
{
range = previewRange_;
}
void PreviewAttribute::Dump()
{
PRINT_HILOGD("result_: %{public}s", result_.c_str());
previewRange_.Dump();
}
} // namespace OHOS::Print

View File

@ -1,115 +0,0 @@
/*
* 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 "print_progress_notify.h"
#include <uv.h>
#include "napi_print_utils.h"
#include "print_job.h"
#include "print_log.h"
#include "print_page_size.h"
#include "print_resolution.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
PrintProgressNotify::PrintProgressNotify(napi_env env, const std::string &type, napi_ref ref)
: PrintBaseNotify(env, type, ref)
{}
PrintProgressNotify::~PrintProgressNotify()
{
PRINT_HILOGD("");
}
void PrintProgressNotify::DataReadInfo(PrinterInfo &info, MessageParcel &data)
{
PRINT_HILOGD("");
}
void PrintProgressNotify::DataReadJob(PrintJob &job, MessageParcel &data)
{
PRINT_HILOGD("");
}
void PrintProgressNotify::WriteInfoJsObject(napi_env env, PrinterInfo info, napi_value *result)
{
PRINT_HILOGD("");
}
void PrintProgressNotify::notifyDataBase(NotifyData *notifyData, MessageParcel &data)
{
PRINT_HILOGD("Progress callback in");
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(env_, &loop);
if (loop == nullptr) {
PRINT_HILOGE("Failed to get uv event loop");
return;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return;
}
notifyData = GetNotifyData();
notifyData->env = env_;
notifyData->ref = ref_;
notifyData->type = type_;
notifyData->objectType = data.ReadString();
notifyData->firstArgv = data.ReadUint32();
if (notifyData->objectType == "PrinterInfo") {
DataReadInfo(notifyData->secondArgv, data);
} else if (notifyData->objectType == "PrintJob") {
DataReadJob(notifyData->thirdArgv, data);
}
}
void PrintProgressNotify::OnCallBack(MessageParcel &data)
{
NotifyData *notifyData = nullptr;
notifyDataBase(notifyData, data);
work->data = notifyData;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
NotifyData *notifyData = static_cast<NotifyData *>(work->data);
if (notifyData != nullptr) {
napi_value undefined = 0;
napi_get_undefined(notifyData->env, &undefined);
napi_value callbackFunc = nullptr;
napi_get_reference_value(notifyData->env, notifyData->ref, &callbackFunc);
napi_value result = nullptr;
napi_value callbackVal[NapiPrintUtils::TWO_ARG] = { 0 };
napi_create_uint32(notifyData->env, notifyData->firstArgv, &callbackVal[NapiPrintUtils::FIRST_ARGV]);
if (notifyData->objectType == "PrinterInfo") {
WriteInfoJsObject(
notifyData->env, notifyData->secondArgv, &callbackVal[NapiPrintUtils::SECOND_ARGV]);
} else if (notifyData->objectType == "PrintJob") {
WriteJobJsObject(notifyData->env, notifyData->thirdArgv, &callbackVal[NapiPrintUtils::SECOND_ARGV]);
}
napi_call_function(
notifyData->env, nullptr, callbackFunc, NapiPrintUtils::TWO_ARG, callbackVal, &result);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete notifyData;
notifyData = nullptr;
}
});
}
} // namespace OHOS::Print

View File

@ -1,98 +0,0 @@
/*
* 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 "print_range.h"
#include "print_log.h"
namespace OHOS::Print {
PrintRange::PrintRange() : startPage_(0), endPage_(0)
{
pages_.clear();
}
PrintRange::PrintRange(const PrintRange &right)
{
startPage_ = right.startPage_;
endPage_ = right.endPage_;
pages_.clear();
pages_.assign(right.pages_.begin(), right.pages_.end());
}
PrintRange &PrintRange::operator=(const PrintRange &right)
{
if (this != &right) {
startPage_ = right.startPage_;
endPage_ = right.endPage_;
pages_.clear();
pages_.assign(right.pages_.begin(), right.pages_.end());
}
return *this;
}
PrintRange::~PrintRange()
{
pages_.clear();
}
void PrintRange::SetStartPage(uint32_t startpage)
{
startPage_ = startpage;
}
void PrintRange::SetEndPage(uint32_t endpage)
{
endPage_ = endpage;
}
void PrintRange::SetPages(const std::vector<uint32_t> &pages)
{
pages_.clear();
pages_.assign(pages.begin(), pages.end());
}
void PrintRange::Reset()
{
startPage_ = 0;
endPage_ = 0;
pages_.clear();
}
uint32_t PrintRange::GetStartPage() const
{
return startPage_;
}
uint32_t PrintRange::GetEndPage() const
{
return endPage_;
}
void PrintRange::GetPages(std::vector<uint32_t> &pages) const
{
pages.clear();
pages.assign(pages_.begin(), pages_.end());
}
void PrintRange::Dump()
{
PRINT_HILOGD("startPage_ = %{public}d", startPage_);
PRINT_HILOGD("endPage_ = %{public}d", endPage_);
uint32_t pageLength = pages_.size();
for (uint32_t i = 0; i < pageLength; i++) {
PRINT_HILOGD("pages_ = %{public}d", pages_[i]);
}
}
} // namespace OHOS::Print

View File

@ -1,78 +0,0 @@
/*
* 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 "print_resolution.h"
#include "print_log.h"
namespace OHOS::Print {
PrintResolution::PrintResolution() : id_(0), horizontalDpi_(0), verticalDpi_(0) {}
PrintResolution::PrintResolution(const PrintResolution &right)
{
id_ = right.id_;
horizontalDpi_ = right.horizontalDpi_;
verticalDpi_ = right.verticalDpi_;
}
PrintResolution &PrintResolution::operator=(const PrintResolution &right)
{
if (this != &right) {
id_ = right.id_;
horizontalDpi_ = right.horizontalDpi_;
verticalDpi_ = right.verticalDpi_;
}
return *this;
}
PrintResolution::~PrintResolution() {}
void PrintResolution::SetId(uint32_t id)
{
id_ = id;
}
void PrintResolution::SetHorizontalDpi(uint32_t horizontalDpi)
{
horizontalDpi_ = horizontalDpi;
}
void PrintResolution::SetVerticalDpi(uint32_t verticalDpi)
{
verticalDpi_ = verticalDpi;
}
uint32_t PrintResolution::GetId() const
{
return id_;
}
uint32_t PrintResolution::GetHorizontalDpi() const
{
return horizontalDpi_;
}
uint32_t PrintResolution::GetVerticalDpi() const
{
return verticalDpi_;
}
void PrintResolution::Dump()
{
PRINT_HILOGD("id_ = %{public}d", id_);
PRINT_HILOGD("horizontalDpi_ = %{public}d", horizontalDpi_);
PRINT_HILOGD("verticalDpi_ = %{public}d", verticalDpi_);
}
} // namespace OHOS::Print

View File

@ -1,29 +0,0 @@
/*
* 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 "print_sa_death_recipient.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS::Print {
PrintSaDeathRecipient::PrintSaDeathRecipient() {}
void PrintSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
{
PRINT_HILOGE("PrintSaDeathRecipient on remote systemAbility died.");
PrintManagerClient::GetInstance()->OnRemoteSaDied(object);
}
} // namespace OHOS::Print

View File

@ -1,514 +0,0 @@
/*
* 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 "print_service_proxy.h"
#include "iremote_broker.h"
#include "napi_print_utils.h"
#include "print_common.h"
#include "print_job.h"
#include "print_log.h"
#include "printer_info.h"
namespace OHOS::Print {
using namespace OHOS::HiviewDFX;
PrintServiceProxy::PrintServiceProxy(const sptr<IRemoteObject> &object) : IRemoteProxy<IPrintService>(object) {}
int32_t PrintServiceProxy::StartPrint()
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
PRINT_HILOGD("PrintServiceProxy StartPrint started.");
bool ret = Remote()->SendRequest(CMD_START_PRINT, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("StartPrint, ret = %{public}d", ret);
return -1;
}
int32_t taskId = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy StartPrint succeeded. TaskId = %{public}d", taskId);
return taskId;
}
bool PrintServiceProxy::ConnectPrinter(uint32_t printerId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(printerId);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_CONNECTPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy ConnectPrinter succeeded.");
return true;
}
bool PrintServiceProxy::DisconnectPrinter(uint32_t printerId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(printerId);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_DISCONNECTPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy DisconnectPrinter succeeded.");
return true;
}
bool PrintServiceProxy::QueryAllExtension(std::vector<PrintExtensionInfo> &arrayExtensionInfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(NapiPrintUtil::ARGC_FIVE);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_QUERYALLEXTENSION, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
uint32_t replyArrayLength = reply.ReadUint32();
for (uint32_t i = 0; i < replyArrayLength; i++) {
PrintExtensionInfo printeExtensionInfo;
printeExtensionInfo.SetExtensionId(reply.ReadUint32());
printeExtensionInfo.SetVendorId(reply.ReadUint32());
printeExtensionInfo.SetVendorName(reply.ReadString());
printeExtensionInfo.SetVendorIcon(reply.ReadUint32());
printeExtensionInfo.SetVersion(reply.ReadString());
arrayExtensionInfo.push_back(printeExtensionInfo);
arrayExtensionInfo[i].Dump();
}
return true;
}
bool PrintServiceProxy::StartDiscoverPrinter(const std::vector<uint32_t> &extensionList)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(extensionList.size());
PRINT_HILOGD("OnStartDiscoverPrinter extensionList.size() = %{public}lu", extensionList.size());
for (uint32_t i = 0; i < extensionList.size(); i++) {
data.WriteUint32(extensionList[i]);
}
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_STARTDISCOVERPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy StartDiscoverPrinter succeeded.");
return true;
}
bool PrintServiceProxy::StopDiscoverPrinter()
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_STOPDISCOVERPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy StopDiscoverPrinter succeeded.");
return true;
}
bool PrintServiceProxy::StartPrintJob(const PrintJob &jobinfo)
{
MessageParcel data, reply;
MessageOption option;
BuildParcelFromPrintJob(data, jobinfo);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_STARTPRINTJOB, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy StartPrintJob succeeded.");
return true;
}
bool PrintServiceProxy::CancelPrintJob(const PrintJob &jobinfo)
{
MessageParcel data, reply;
MessageOption option;
BuildParcelFromPrintJob(data, jobinfo);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_CANCELPRINTJOB, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy CancelPrintJob succeeded.");
return true;
}
bool PrintServiceProxy::AddPrinters(const std::vector<PrinterInfo> &arrayPrintInfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(arrayPrintInfo.size());
PRINT_HILOGD("OnStartDiscoverPrinter arrayPrintInfo.size() = %{public}lu", arrayPrintInfo.size());
for (uint32_t i = 0; i < arrayPrintInfo.size(); i++) {
BuildParcelFromPrinterInfo(data, arrayPrintInfo[i]);
}
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_ADDPRINTERS, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy AddPrinters succeeded.");
return true;
}
bool PrintServiceProxy::RemovePrinters(const std::vector<PrinterInfo> &arrayPrintInfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(arrayPrintInfo.size());
PRINT_HILOGD("OnStartDiscoverPrinter arrayPrintInfo.size() = %{public}lu", arrayPrintInfo.size());
for (uint32_t i = 0; i < arrayPrintInfo.size(); i++) {
BuildParcelFromPrinterInfo(data, arrayPrintInfo[i]);
}
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_REMOVEPRINTERS, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy RemovePrinters succeeded.");
return true;
}
bool PrintServiceProxy::UpdatePrinterState(uint32_t printerId, uint32_t state)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(printerId);
data.WriteUint32(state);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_UPDATEPRINTERSTATE, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy UpdatePrinterState succeeded.");
return true;
}
bool PrintServiceProxy::UpdatePrinterJobState(uint32_t jobId, uint32_t state)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
data.WriteUint32(jobId);
data.WriteUint32(state);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_UPDATEPRINTERJOBSTATE, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
PRINT_HILOGD("PrintServiceProxy UpdatePrinterJobState succeeded.");
return true;
}
bool PrintServiceProxy::RequestPreview(const PrintJob &jobinfo, std::string &previewResult)
{
MessageParcel data, reply;
MessageOption option;
BuildParcelFromPrintJob(data, jobinfo);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_REQUESTPREVIEW, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
previewResult = reply.ReadString();
PRINT_HILOGD("PrintServiceProxy RequestPreview succeeded.");
return true;
}
bool PrintServiceProxy::QueryPrinterCapability(uint32_t printerId, PrinterCapability &printerCapability)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor());
PRINT_HILOGD("printerId : %{public}d", printerId);
data.WriteUint32(printerId);
PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started.");
bool ret = Remote()->SendRequest(CMD_QUERYPRINTERCAPABILITY, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGD("PrintServiceProxy, ret = %{public}d", ret);
return false;
}
uint32_t arraypageSizeLength = reply.ReadUint32();
uint32_t resolutionLength = reply.ReadUint32();
PRINT_HILOGD("PrintServiceProxy, arraypageSizeLength = %{public}d", arraypageSizeLength);
PRINT_HILOGD("PrintServiceProxy, resolutionLength = %{public}d", resolutionLength);
PrintMargin margin;
margin.SetTop(reply.ReadUint32());
margin.SetBottom(reply.ReadUint32());
margin.SetLeft(reply.ReadUint32());
margin.SetRight(reply.ReadUint32());
printerCapability.SetMinMargin(margin);
if (arraypageSizeLength > 0) {
std::vector<PrintPageSize> pageSizeList;
for (uint32_t i = 0; i < arraypageSizeLength; i++) {
PrintPageSize pageSize;
pageSize.SetId(reply.ReadString());
pageSize.SetName(reply.ReadString());
pageSize.SetWidth(reply.ReadUint32());
pageSize.SetHeight(reply.ReadUint32());
pageSizeList.push_back(pageSize);
}
printerCapability.SetPageSize(pageSizeList);
}
if (resolutionLength > 0) {
std::vector<PrintResolution> resolutionList;
for (uint32_t i = 0; i < resolutionLength; i++) {
PrintResolution res;
res.SetId(reply.ReadUint32());
res.SetHorizontalDpi(reply.ReadUint32());
res.SetVerticalDpi(reply.ReadUint32());
resolutionList.push_back(res);
}
printerCapability.SetResolution(resolutionList);
}
printerCapability.SetColorMode(reply.ReadUint32());
printerCapability.SetDuplexMode(reply.ReadUint32());
printerCapability.Dump();
PRINT_HILOGD("PrintServiceProxy QueryPrinterCapability succeeded.");
return true;
}
bool PrintServiceProxy::CheckPermission()
{
PRINT_HILOGD("PrintServiceProxy::CheckPermission in");
MessageParcel data, reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE(" Failed to write parcelable ");
return false;
}
int32_t result = Remote()->SendRequest(CMD_CHECKPERMISSION, data, reply, option);
if (result != ERR_NONE) {
PRINT_HILOGE(" PrintServiceProxy::CheckPermission fail, ret = %{public}d ", result);
return false;
}
bool ret = reply.ReadBool();
PRINT_HILOGD("PrintServiceProxy::CheckPermission out [ret: %{public}d]", ret);
return ret;
}
bool PrintServiceProxy::On(
const std::string &type, uint32_t &state, PrinterInfo &info, const sptr<IPrintCallback> &listener)
{
PRINT_HILOGD("PrintServiceProxy::On listener=%{public}p", listener.GetRefPtr());
MessageParcel data, reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE(" Failed to write parcelable ");
return false;
}
return true;
}
bool PrintServiceProxy::Off(const std::string &type)
{
PRINT_HILOGD("PrintServiceProxy::Off in");
MessageParcel data, reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE(" Failed to write parcelable ");
return false;
}
return true;
}
bool PrintServiceProxy::RegisterExtCallback(uint32_t callbackId, const sptr<IPrintExtensionCallback> &listener)
{
PRINT_HILOGD("PrintServiceProxy::RegisterExtCallback in");
MessageParcel data, reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE("Failed to write parcelable");
return false;
}
if (!data.WriteUint32(callbackId)) {
PRINT_HILOGE("Failed to write callbackId=%{public}d", callbackId);
return false;
}
if (!data.WriteRemoteObject(listener->AsObject().GetRefPtr())) {
PRINT_HILOGE("write parcel failed.");
return false;
}
int32_t result = Remote()->SendRequest(CMD_REG_EXT_CB, data, reply, option);
if (result != ERR_NONE) {
PRINT_HILOGE("PrintServiceProxy::RegisterExtCallback fail, ret = %{public}d", result);
return false;
}
bool ret = reply.ReadBool();
PRINT_HILOGD("PrintServiceProxy::RegisterExtCallback out [ret: %{public}d]", ret);
return ret;
}
bool PrintServiceProxy::UnregisterAllExtCallback()
{
PRINT_HILOGD("PrintServiceProxy::UnregisterAllExtCallback in");
MessageParcel data, reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE(" Failed to write parcelable ");
return false;
}
int32_t result = Remote()->SendRequest(CMD_UNREG_EXT_CB, data, reply, option);
if (result != ERR_NONE) {
PRINT_HILOGE(" PrintServiceProxy::UnregisterAllExtCallback fail, ret = %{public}d ", result);
return false;
}
bool ret = reply.ReadBool();
PRINT_HILOGD("PrintServiceProxy::UnregisterAllExtCallback out [ret: %{public}d]", ret);
return ret;
}
void PrintServiceProxy::BuildParcelFromPrintJob(MessageParcel &data, const PrintJob &jobinfo)
{
data.WriteInterfaceToken(GetDescriptor());
std::vector<std::string> files;
jobinfo.GetFiles(files);
data.WriteUint32(files.size());
for (uint32_t i = 0; i < files.size(); i++) {
data.WriteString(files[i]);
}
data.WriteUint32(jobinfo.GetJobId());
data.WriteUint32(jobinfo.GetPrinterId());
data.WriteUint32(jobinfo.GetJobState());
data.WriteUint32(jobinfo.GetCopyNumber());
PrintRange range;
jobinfo.GetPageRange(range);
data.WriteUint32(range.GetStartPage());
data.WriteUint32(range.GetEndPage());
std::vector<uint32_t> pages;
range.GetPages(pages);
data.WriteUint32(pages.size());
for (uint32_t i = 0; i < pageLength; i++) {
data.WriteUint32(pages[i]);
}
data.WriteUint32(jobinfo.GetIsSequential());
PrintPageSize pageSize;
jobinfo.GetPageSize(pageSize);
data.WriteString(pageSize.GetId());
data.WriteString(pageSize.GetName());
data.WriteUint32(pageSize.GetWidth());
data.WriteUint32(pageSize.GetHeight());
data.WriteUint32(jobinfo.GetIsLandscape());
data.WriteUint32(jobinfo.GetColorMode());
data.WriteUint32(jobinfo.GetDuplexMode());
PrintMargin margin;
jobinfo.GetMargin(margin);
data.WriteUint32(margin.GetTop());
data.WriteUint32(margin.GetBottom());
data.WriteUint32(margin.GetLeft());
data.WriteUint32(margin.GetRight());
PreviewAttribute preview;
jobinfo.GetPreview(preview);
data.WriteString(preview.GetResult());
range.Reset();
preview.GetPreviewRange(range);
data.WriteUint32(range.GetStartPage());
data.WriteUint32(range.GetEndPage());
range.GetPages(pages);
data.WriteUint32(pages.size());
for (uint32_t i = 0; i < pages.size(); i++) {
data.WriteUint32(pages[i]);
}
}
void PrintServiceProxy::BuildParcelFromPrinterInfo(MessageParcel &data, const PrinterInfo &printerInfo)
{
data.WriteUint32(printerInfo.GetPrintId());
data.WriteString(printerInfo.GetPrinterName());
data.WriteUint32(printerInfo.GetPrinterIcon());
data.WriteUint32(printerInfo.GetPrinterState());
data.WriteString(printerInfo.GetDescription());
PrinterCapability cap;
printerInfo.GetCapability(cap);
std::vector<PrintPageSize> pageSizeList;
cap.GetPageSize(pageSizeList);
std::vector<PrintResolution> resolutionList;
cap.GetResolution(resolutionList);
uint32_t pageSizeLength = pageSizeList.size();
uint32_t resolutionLength = resolutionList.size();
data.WriteUint32(pageSizeLength);
data.WriteUint32(resolutionLength);
PrintMargin margin;
cap.GetMinMargin(margin);
data.WriteUint32(margin.GetTop());
data.WriteUint32(margin.GetBottom());
data.WriteUint32(margin.GetLeft());
data.WriteUint32(margin.GetRight());
for (uint32_t i = 0; i < pageSizeLength; i++) {
data.WriteString(pageSizeList[i].GetId());
data.WriteString(pageSizeList[i].GetName());
data.WriteUint32(pageSizeList[i].GetWidth());
data.WriteUint32(pageSizeList[i].GetHeight());
}
for (uint32_t i = 0; i < resolutionLength; i++) {
data.WriteUint32(resolutionList[i].GetId());
data.WriteUint32(resolutionList[i].GetHorizontalDpi());
data.WriteUint32(resolutionList[i].GetVerticalDpi());
}
data.WriteUint32(cap.GetColorMode());
data.WriteUint32(cap.GetDuplexMode());
}
} // namespace OHOS::Print

View File

@ -1,42 +0,0 @@
/*
* 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 "print_sync_load_callback.h"
#include "iservice_registry.h"
#include "isystem_ability_load_callback.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "system_ability_definition.h"
namespace OHOS::Print {
void PrintSyncLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject> &remoteObject)
{
if (systemAbilityId != PRINT_SERVICE_ID) {
PRINT_HILOGE("start systemAbilityId is not print server");
return;
}
PrintManagerClient::GetInstance()->LoadServerSuccess();
}
void PrintSyncLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId)
{
if (systemAbilityId != PRINT_SERVICE_ID) {
PRINT_HILOGE("start systemAbilityId is not print server");
return;
}
PrintManagerClient::GetInstance()->LoadServerFail();
}
} // namespace OHOS::Print

View File

@ -1,508 +0,0 @@
/*
* 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 "printer_capability.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_CAPABILITY_MINMARGIN = "minMargin";
static constexpr const char *PARAM_CAPABILITY_PAGESIZE = "pageSize";
static constexpr const char *PARAM_CAPABILITY_RESOLUTION = "resolution";
static constexpr const char *PARAM_CAPABILITY_COLORMODE = "colorMode";
static constexpr const char *PARAM_CAPABILITY_DUPLEXMODE = "duplexMode";
static constexpr const char *PARAM_PAGESIZE_ID = "id";
static constexpr const char *PARAM_PAGESIZE_NAME = "name";
static constexpr const char *PARAM_PAGESIZE_WIDTH = "width";
static constexpr const char *PARAM_PAGESIZE_HEIGHT = "height";
static constexpr const char *PARAM_RESOLUTION_ID = "id";
static constexpr const char *PARAM_RESOLUTION_HORIZONTALDPI = "horizontalDpi";
static constexpr const char *PARAM_RESOLUTION_VERTICALDPI = "verticalDpi";
static constexpr const char *PARAM_MARGIN_TOP = "top";
static constexpr const char *PARAM_MARGIN_BOTTOM = "bottom";
static constexpr const char *PARAM_MARGIN_LEFT = "left";
static constexpr const char *PARAM_MARGIN_RIGHT = "right";
PrinterCapability::PrinterCapability() : minMargin_(), colorMode_(0), duplexMode_(0)
{
pageSizeList_.clear();
resolutionList_.clear();
}
PrinterCapability::PrinterCapability(const PrinterCapability &right)
{
minMargin_ = right.minMargin_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
SetPageSize(right.pageSizeList_);
SetResolution(right.resolutionList_);
}
PrinterCapability &PrinterCapability::operator=(const PrinterCapability &right)
{
if (this != &right) {
minMargin_ = right.minMargin_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
SetPageSize(right.pageSizeList_);
SetResolution(right.resolutionList_);
}
return *this;
}
PrinterCapability::~PrinterCapability() {}
void PrinterCapability::SetMinMargin(const PrintMargin &minMargin)
{
minMargin_ = minMargin;
}
void PrinterCapability::SetPageSize(const std::vector<PrintPageSize> &pageSizeList)
{
pageSizeList_.clear();
pageSizeList_.assign(pageSizeList.begin(), pageSizeList.end());
}
void PrinterCapability::SetResolution(const std::vector<PrintResolution> &resolutionList)
{
resolutionList_.clear();
resolutionList_.assign(resolutionList.begin(), resolutionList.end());
}
void PrinterCapability::SetColorMode(uint32_t colorMode)
{
colorMode_ = colorMode;
}
void PrinterCapability::SetDuplexMode(uint32_t duplexMode)
{
duplexMode_ = duplexMode;
}
void PrinterCapability::GetMinMargin(PrintMargin &margin) const
{
margin = minMargin_;
}
void PrinterCapability::GetPageSize(std::vector<PrintPageSize> &pageSizeList) const
{
pageSizeList.clear();
pageSizeList.assign(pageSizeList_.begin(), pageSizeList_.end());
}
void PrinterCapability::GetResolution(std::vector<PrintResolution> &resolutionList) const
{
resolutionList.clear();
resolutionList.assign(resolutionList_.begin(), resolutionList_.end());
}
uint32_t PrinterCapability::GetColorMode() const
{
return colorMode_;
}
uint32_t PrinterCapability::GetDuplexMode() const
{
return duplexMode_;
}
void PrinterCapability::ConvertToParcel(MessageParcel &reply) const
{
std::vector<PrintPageSize> pageSizeList;
std::vector<PrintResolution> resolutionList;
GetPageSize(pageSizeList);
GetResolution(resolutionList);
uint32_t arraypageSizeLength = pageSizeList.size();
reply.WriteUint32(arraypageSizeLength);
uint32_t resolutionLength = resolutionList.size();
reply.WriteUint32(resolutionLength);
PrintMargin minMargin;
GetMinMargin(minMargin);
reply.WriteUint32(minMargin.GetTop());
reply.WriteUint32(minMargin.GetBottom());
reply.WriteUint32(minMargin.GetLeft());
reply.WriteUint32(minMargin.GetRight());
for (uint32_t i = 0; i < arraypageSizeLength; i++) {
reply.WriteString(pageSizeList[i].GetId());
reply.WriteString(pageSizeList[i].GetName());
reply.WriteUint32(pageSizeList[i].GetWidth());
reply.WriteUint32(pageSizeList[i].GetHeight());
}
for (uint32_t i = 0; i < resolutionLength; i++) {
reply.WriteUint32(resolutionList[i].GetId());
reply.WriteUint32(resolutionList[i].GetHorizontalDpi());
reply.WriteUint32(resolutionList[i].GetVerticalDpi());
}
reply.WriteUint32(GetColorMode());
reply.WriteUint32(GetDuplexMode());
}
void PrinterCapability::BuildFromParcel(MessageParcel &data)
{
uint32_t arraypageSizeLength = data.ReadUint32();
uint32_t resolutionLength = data.ReadUint32();
PRINT_HILOGD("PrintServiceProxy, arraypageSizeLength = %{public}d", arraypageSizeLength);
PRINT_HILOGD("PrintServiceProxy, resolutionLength = %{public}d", resolutionLength);
PrintMargin margin;
margin.SetTop(data.ReadUint32());
margin.SetBottom(data.ReadUint32());
margin.SetLeft(data.ReadUint32());
margin.SetRight(data.ReadUint32());
SetMinMargin(margin);
if (arraypageSizeLength > 0) {
std::vector<PrintPageSize> pageSizeList;
for (uint32_t i = 0; i < arraypageSizeLength; i++) {
PrintPageSize pageSize;
pageSize.SetId(data.ReadString());
pageSize.SetName(data.ReadString());
pageSize.SetWidth(data.ReadUint32());
pageSize.SetHeight(data.ReadUint32());
pageSizeList.push_back(pageSize);
}
SetPageSize(pageSizeList);
}
if (resolutionLength > 0) {
std::vector<PrintResolution> resolutionList;
for (uint32_t i = 0; i < resolutionLength; i++) {
PrintResolution res;
res.SetId(data.ReadUint32());
res.SetHorizontalDpi(data.ReadUint32());
res.SetVerticalDpi(data.ReadUint32());
resolutionList.push_back(res);
}
SetResolution(resolutionList);
}
SetColorMode(data.ReadUint32());
SetDuplexMode(data.ReadUint32());
Dump();
}
void PrinterCapability::ConvertToJs(napi_env env, napi_value *result) const
{
PRINT_HILOGD("Enter ConvertToJs---->");
napi_value resultPrintMargin;
napi_create_object(env, result);
napi_create_object(env, &resultPrintMargin);
napi_value arrPageSize, arrResolution;
napi_status status = napi_create_array(env, &arrPageSize);
status = napi_create_array(env, &arrResolution);
NapiPrintUtils::SetUint32Property(env, *result, "colorMode", GetColorMode());
NapiPrintUtils::SetUint32Property(env, *result, "duplexMode", GetDuplexMode());
PrintMargin margin;
GetMinMargin(margin);
NapiPrintUtils::SetUint32Property(env, resultPrintMargin, "top", margin.GetTop());
NapiPrintUtils::SetUint32Property(env, resultPrintMargin, "bottom", margin.GetBottom());
NapiPrintUtils::SetUint32Property(env, resultPrintMargin, "left", margin.GetLeft());
NapiPrintUtils::SetUint32Property(env, resultPrintMargin, "right", margin.GetRight());
std::vector<PrintPageSize> pageSize;
GetPageSize(pageSize);
uint32_t printerCapabilityLength = pageSize.size();
for (uint32_t i = 0; i < printerCapabilityLength; i++) {
napi_value resultPrinterPageSize;
napi_create_object(env, &resultPrinterPageSize);
NapiPrintUtils::SetStringPropertyUtf8(env, resultPrinterPageSize, "id", pageSize[i].GetId().c_str());
NapiPrintUtils::SetStringPropertyUtf8(env, resultPrinterPageSize, "name", pageSize[i].GetName().c_str());
NapiPrintUtils::SetUint32Property(env, resultPrinterPageSize, "width", pageSize[i].GetWidth());
NapiPrintUtils::SetUint32Property(env, resultPrinterPageSize, "height", pageSize[i].GetHeight());
status = napi_set_element(env, arrPageSize, i, resultPrinterPageSize);
}
std::vector<PrintResolution> resolutionList;
GetResolution(resolutionList);
uint32_t printerCapabilityresolutionLength = resolutionList.size();
for (uint32_t i = 0; i < printerCapabilityresolutionLength; i++) {
napi_value resultPrinterResolution;
napi_create_object(env, &resultPrinterResolution);
NapiPrintUtils::SetUint32Property(env, resultPrinterResolution, "id", resolutionList[i].GetId());
NapiPrintUtils::SetUint32Property(
env, resultPrinterResolution, "horizontalDpi", resolutionList[i].GetHorizontalDpi());
NapiPrintUtils::SetUint32Property(
env, resultPrinterResolution, "verticalDpi", resolutionList[i].GetVerticalDpi());
status = napi_set_element(env, arrResolution, i, resultPrinterResolution);
}
status = napi_set_named_property(env, *result, "minMargin", resultPrintMargin);
PRINT_HILOGD("output ---- status[%{public}d]", status);
napi_set_named_property(env, *result, "pageSize", arrPageSize);
napi_set_named_property(env, *result, "resolution", arrResolution);
PRINT_HILOGD("ouput over---->");
}
void PrinterCapability::BuildFromJs(napi_env env, napi_value capValue)
{
ParseCapability(env, capValue);
}
bool PrinterCapability::ParseCapability(napi_env env, napi_value capValue)
{
if (!ParseCapabilityParam(env, capValue)) {
PRINT_HILOGD("ParseCapParam is error!");
return false;
}
SetColorMode(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_CAPABILITY_COLORMODE));
SetDuplexMode(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_CAPABILITY_DUPLEXMODE));
PRINT_HILOGD("capability_value colorMode value is %{public}d", GetColorMode());
PRINT_HILOGD("capability_value duplexMode value is %{public}d", GetDuplexMode());
return true;
}
void PrinterCapability::ParseCapabilityObject(napi_env env, napi_value capValue)
{
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_RESOLUTION);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_object) {
PRINT_HILOGD("error param_three");
return false;
} else {
bool isReArray = false;
napi_is_array(env, param_three, &isReArray);
if (!isReArray) {
PRINT_HILOGD("PrintResolution type error!");
return false;
}
std::vector<PrintResolution> resolutionList;
uint32_t arrayReLength = 0;
napi_get_array_length(env, param_three, &arrayReLength);
for (uint32_t i = 0; i < arrayReLength; i++) {
napi_value reValue;
PrintResolution resolution;
napi_get_element(env, param_three, i, &reValue);
if (!ParseResolution(env, reValue, resolution)) {
PRINT_HILOGD("PrintResolution type error!");
return false;
}
resolutionList.push_back(resolution);
}
SetResolution(resolutionList);
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_COLORMODE);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
napi_value param_five = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_DUPLEXMODE);
if (NapiPrintUtils::GetValueType(env, param_five) != napi_number) {
PRINT_HILOGD("error param_five");
return false;
}
}
bool PrinterCapability::ParseCapabilityParam(napi_env env, napi_value capValue)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_MINMARGIN);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_object) {
PRINT_HILOGD("error param_one");
return false;
} else {
PrintMargin margin;
if (!ParseMargin(env, param_one, margin)) {
PRINT_HILOGD("ParseCapability type error!");
return false;
}
SetMinMargin(margin);
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_PAGESIZE);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_object) {
PRINT_HILOGD("error param_two");
return false;
} else {
bool isArray = false;
napi_is_array(env, param_two, &isArray);
if (!isArray) {
PRINT_HILOGD("ParsePageSize type error!");
return false;
}
std::vector<PrintPageSize> pageSizeList;
uint32_t arrayLength = 0;
napi_get_array_length(env, param_two, &arrayLength);
for (uint32_t i = 0; i < arrayLength; i++) {
napi_value pageSizeValue;
PrintPageSize pageSize;
napi_get_element(env, param_two, i, &pageSizeValue);
if (!ParsePageSize(env, pageSizeValue, pageSize)) {
PRINT_HILOGD("ParsePageSize type error!");
return false;
}
pageSizeList.push_back(pageSize);
}
SetPageSize(pageSizeList);
}
ParseCapabilityObject(env, capValue);
auto names = NapiPrintUtils::GetPropertyNames(env, capValue);
return true;
}
bool PrinterCapability::ParseMargin(napi_env env, napi_value marginValue, PrintMargin &margin)
{
if (!ParseMarginParam(env, marginValue, margin)) {
PRINT_HILOGD("ParseResolutionParam is error!");
return false;
}
margin.SetTop(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_TOP));
margin.SetBottom(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_BOTTOM));
margin.SetLeft(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_LEFT));
margin.SetRight(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_RIGHT));
PRINT_HILOGD("printerMargin_value GetTop value is %{public}d", margin.GetTop());
PRINT_HILOGD("printerMargin_value GetBottom value is %{public}d", margin.GetBottom());
PRINT_HILOGD("printerMargin_value GetLeft value is %{public}d", margin.GetLeft());
PRINT_HILOGD("printerMargin_value GetRight value is %{public}d", margin.GetRight());
return true;
}
bool PrinterCapability::ParseMarginParam(napi_env env, napi_value marginValue, PrintMargin &margin)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_TOP);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_BOTTOM);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_number) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_LEFT);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_RIGHT);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
auto names = NapiPrintUtils::GetPropertyNames(env, marginValue);
PRINT_HILOGD("current margin paramster name list size = %{public}zu", names.size());
return true;
}
bool PrinterCapability::ParsePageSize(napi_env env, napi_value capValue, PrintPageSize &pageSize)
{
if (!ParsePageSizeParam(env, capValue, pageSize)) {
PRINT_HILOGD("ParsePageSizeParam is error!");
return false;
}
pageSize.SetId(NapiPrintUtils::GetStringPropertyUtf8(env, capValue, PARAM_PAGESIZE_ID));
pageSize.SetName(NapiPrintUtils::GetStringPropertyUtf8(env, capValue, PARAM_PAGESIZE_NAME));
pageSize.SetWidth(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_PAGESIZE_WIDTH));
pageSize.SetHeight(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_PAGESIZE_HEIGHT));
PRINT_HILOGD("printerPageSize_value GetId value is %{public}s", pageSize.GetId().c_str());
PRINT_HILOGD("printerPageSize_value GetName value is %{public}s", pageSize.GetName().c_str());
PRINT_HILOGD("printerPageSize_value GetWidth value is %{public}d", pageSize.GetWidth());
PRINT_HILOGD("printerPageSize_value GetHeight value is %{public}d", pageSize.GetHeight());
return true;
}
bool PrinterCapability::ParsePageSizeParam(napi_env env, napi_value capValue, PrintPageSize &pageSize)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_ID);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_NAME);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_string) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_WIDTH);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_HEIGHT);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
return true;
}
bool PrinterCapability::ParseResolution(napi_env env, napi_value reValue, PrintResolution &resolution)
{
if (!ParseResolutionParam(env, reValue, resolution)) {
PRINT_HILOGD("ParseResolutionParam is error!");
return false;
}
resolution.SetId(NapiPrintUtils::GetUint32Property(env, reValue, PARAM_RESOLUTION_ID));
resolution.SetHorizontalDpi(NapiPrintUtils::GetUint32Property(env, reValue, PARAM_RESOLUTION_HORIZONTALDPI));
resolution.SetVerticalDpi(NapiPrintUtils::GetUint32Property(env, reValue, PARAM_RESOLUTION_VERTICALDPI));
PRINT_HILOGD("printerResolution_value GetId value is %{public}d", resolution.GetId());
PRINT_HILOGD("printerResolution_value GetHorizontalDpi value is %{public}d", resolution.GetHorizontalDpi());
PRINT_HILOGD("printerResolution_value GetVerticalDpi value is %{public}d", resolution.GetVerticalDpi());
return true;
}
bool PrinterCapability::ParseResolutionParam(napi_env env, napi_value reValue, PrintResolution &resolution)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, reValue, PARAM_RESOLUTION_ID);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, reValue, PARAM_RESOLUTION_HORIZONTALDPI);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_number) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, reValue, PARAM_RESOLUTION_VERTICALDPI);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
return true;
}
void PrinterCapability::Dump()
{
PRINT_HILOGD("colorMode_ = %{public}d", colorMode_);
PRINT_HILOGD("duplexMode_ = %{public}d", duplexMode_);
minMargin_.Dump();
auto pageIt = pageSizeList_.begin();
while (pageIt != pageSizeList_.end()) {
pageIt->Dump();
pageIt++;
}
auto resIt = resolutionList_.begin();
while (resIt != resolutionList_.end()) {
resIt->Dump();
resIt++;
}
}
} // namespace OHOS::Print

View File

@ -1,113 +0,0 @@
/*
* 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 "printer_info.h"
#include "print_constant.h"
#include "print_log.h"
namespace OHOS::Print {
PrinterInfo::PrinterInfo()
: printerId_(0), printerName_(""), printerIcon_(0), printerState_(PRINTER_UNKNOWN), description_("")
{}
PrinterInfo::PrinterInfo(const PrinterInfo &right)
{
printerId_ = right.printerId_;
printerName_ = right.printerName_;
printerState_ = right.printerState_;
description_ = right.description_;
capability_ = right.capability_;
}
PrinterInfo &PrinterInfo::operator=(PrinterInfo &right)
{
if (this != &right) {
printerId_ = right.printerId_;
printerName_ = right.printerName_;
printerState_ = right.printerState_;
description_ = right.description_;
capability_ = right.capability_;
}
return *this;
}
PrinterInfo::~PrinterInfo() {}
void PrinterInfo::SetPrinterId(uint32_t printerId)
{
printerId_ = printerId;
}
void PrinterInfo::SetPrinterName(std::string printerName)
{
printerName_ = printerName;
}
void PrinterInfo::SetPrinterIcon(uint32_t printIcon)
{
printerIcon_ = printIcon;
}
void PrinterInfo::SetPrinterState(uint32_t printerState)
{
printerState_ = printerState;
}
void PrinterInfo::SetDescription(std::string description)
{
description_ = description;
}
void PrinterInfo::SetCapability(PrinterCapability capability)
{
capability_ = capability;
}
uint32_t PrinterInfo::GetPrintId() const
{
return printerId_;
}
const std::string &PrinterInfo::GetPrinterName() const
{
return printerName_;
}
uint32_t PrinterInfo::GetPrinterIcon() const
{
return printerIcon_;
}
uint32_t PrinterInfo::GetPrinterState() const
{
return printerState_;
}
const std::string &PrinterInfo::GetDescription() const
{
return description_;
}
void PrinterInfo::GetCapability(PrinterCapability &cap) const
{
cap = capability_;
}
void PrinterInfo::Dump()
{
PRINT_HILOGD("printerId: %{public}d", printerId_);
PRINT_HILOGD("printerName: %{public}s", printerName_.c_str());
PRINT_HILOGD("printerIcon: %{public}d", printerIcon_);
PRINT_HILOGD("printerState: %{public}d", printerState_);
PRINT_HILOGD("description: %{public}s", description_.c_str());
capability_.Dump();
}
} // namespace OHOS::Print

View File

@ -1,165 +0,0 @@
# 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("//base/print/print/print.gni")
import("//build/ohos.gni")
ABILITY_RUNTIME_INNERKITS_PATH = "${ability_runtime_inner_api_path}"
config("ability_config") {
visibility = [ ":*" ]
include_dirs = [
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/frameworks/kits/extension/include",
"//base/print/print/utils/include",
"//commonlibrary/c_utils/base/include",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ABILITY_RUNTIME_INNERKITS_PATH}/app_manager/include/appmgr",
"${ABILITY_RUNTIME_INNERKITS_PATH}/ability_manager/include",
"${ability_runtime_services_path}/abilitymgr/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ability_runtime_kits_path}/fmskit/native/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ability_runtime_services_path}/common/include",
#"//foundation/systemabilitymgr/dmsfwk/services/dtbschedmgr/include",
"//base/global/resource_management/interfaces/inner_api/include",
"${ability_runtime_napi_path}/featureAbility",
"//foundation/arkui/napi/interfaces/kits",
"//third_party/node/src",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core/include",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/remote_register_service",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed",
"${ability_runtime_path}/interfaces/kits/native/ability/native/distributed_ability_runtime",
"${ABILITY_RUNTIME_INNERKITS_PATH}/ability_manager/include/continuation",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits",
"${ability_runtime_path}/interfaces/kits/native/appkit/app/task",
"${ability_runtime_napi_path}/inner/napi_common",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"Ability\"",
"LOG_DOMAIN = 0xD002200",
]
}
config("ability_public_config") {
visibility = [ ":*" ]
include_dirs = [
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/frameworks/kits/extension/include",
"${ABILITY_RUNTIME_INNERKITS_PATH}/base/include",
"${ability_runtime_path}/interfaces/kits/native",
"${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ability_runtime_path}/interfaces/kits/native/ability_runtime",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"//third_party/libuv/include",
"${ability_runtime_path}/interfaces/kits/native/ability_runtime/context",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/remote_register_service",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed",
"${ability_runtime_path}/interfaces/kits/native/ability/native/distributed_ability_runtime",
"${ABILITY_RUNTIME_INNERKITS_PATH}/ability_manager/include/continuation",
"//base/global/resource_management/interfaces/inner_api/include",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits",
"${ability_runtime_kits_path}/fmskit/native/include",
"//third_party/jsoncpp/include",
"//third_party/json/include",
]
}
ohos_shared_library("print_extension") {
include_dirs = [
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/frameworks/kits/extension/include",
"//base/global/i18n/frameworks/intl/include",
]
sources = [
"src/js_print_extension.cpp",
"src/js_print_extension_context.cpp",
"src/print_extension.cpp",
"src/print_extension_context.cpp",
"src/js_print_callback.cpp",
"src/js_print_extension_connection.cpp",
]
configs = [ ":ability_config" ]
public_configs = [
":ability_public_config",
"${ability_runtime_path}/frameworks/native/ability:ability_context_public_config",
]
deps = [
"${ability_runtime_path}/frameworks/native/appkit:app_context",
"//base/print/print/frameworks/innerkitsimpl:print_client",
]
external_deps = [
"ability_base:want",
"ability_runtime:ability_context_native",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"ability_runtime:runtime",
"c_utils:utils",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
"ipc_js:rpc",
]
public_deps = [
"//base/global/i18n/frameworks/intl:intl_util",
"//base/global/resource_management/frameworks/resmgr:global_resmgr",
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//foundation/arkui/napi:ace_napi",
]
subsystem_name = "print"
part_name = "print"
}
ohos_shared_library("print_extension_module") {
include_dirs = [
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime",
]
sources = [ "//base/print/print/frameworks/kits/extension/src/print_extension_module_loader.cpp" ]
configs = [ ":ability_config" ]
public_configs = [ ":ability_public_config" ]
deps = [
":print_extension",
"${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native",
]
external_deps = [
"ability_base:base",
"ability_base:want",
"ability_base:zuri",
"ability_runtime:runtime",
"c_utils:utils",
"hisysevent_native:libhisysevent",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
]
subsystem_name = "print"
part_name = "print"
}

View File

@ -1,63 +0,0 @@
/*
* 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 JS_PRINT_CALLBACK_H
#define JS_PRINT_CALLBACK_H
#include <memory>
#include <mutex>
#include <uv.h>
#include <vector>
#include "napi/native_api.h"
class NativeValue;
class NativeEngine;
namespace OHOS {
namespace AbilityRuntime {
class JsRuntime;
class JsPrintCallback : public std::enable_shared_from_this<JsPrintCallback> {
public:
explicit JsPrintCallback(JsRuntime &jsRutime);
~JsPrintCallback() = default;
NativeValue *Exec(NativeValue *jsObj, const std::string &name, NativeValue *const *argv = nullptr, size_t argc = 0,
bool isSync = true);
private:
struct Container {
std::shared_ptr<JsPrintCallback> self;
NativeEngine *nativeEngine;
NativeValue *jsObj;
NativeValue *jsMethod;
NativeValue *const *argv;
size_t argc;
NativeValue *jsResult;
bool isSync;
bool isCompleted;
};
JsRuntime &jsRuntime_;
uv_work_t *jsWorker_;
JsPrintCallback::Container container_;
std::mutex conditionMutex_;
std::condition_variable syncCon_;
static constexpr int SYNC_TIME_OUT = 1000;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_CALLBACK_H

View File

@ -1,121 +0,0 @@
/*
* 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 JS_PRINT_EXTENSION_H
#define JS_PRINT_EXTENSION_H
#include "napi/native_api.h"
#include "print_extension.h"
#include "print_job.h"
class NativeReference;
class NativeValue;
namespace OHOS {
namespace AbilityRuntime {
class PrintExtension;
class JsRuntime;
/**
* @brief Basic Print components.
*/
class JsPrintExtension : public PrintExtension, public std::enable_shared_from_this<JsPrintExtension> {
public:
JsPrintExtension(JsRuntime &jsRuntime);
virtual ~JsPrintExtension() override;
/**
* @brief Create JsPrintExtension.
*
* @param runtime The runtime.
* @return The JsPrintExtension instance.
*/
static JsPrintExtension *Create(const std::unique_ptr<Runtime> &runtime);
/**
* @brief Init the extension.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
*/
virtual void Init(const std::shared_ptr<AppExecFwk::AbilityLocalRecord> &record,
const std::shared_ptr<AppExecFwk::OHOSApplication> &application,
std::shared_ptr<AppExecFwk::AbilityHandler> &handler, const sptr<IRemoteObject> &token) override;
/**
* @brief Called when this extension is started. You must override this function if you want to perform some
* initialization operations during extension startup.
*
* This function can be called only once in the entire lifecycle of an extension.
* @param Want Indicates the {@link Want} structure containing startup information about the extension.
*/
virtual void OnStart(const AAFwk::Want &want) override;
/**
* @brief Called when this Print extension is connected for the first time.
*
* You can override this function to implement your own processing logic.
*
* @param want Indicates the {@link Want} structure containing connection information about the Print extension.
* @return Returns a pointer to the <b>sid</b> of the connected Print extension.
*/
virtual sptr<IRemoteObject> OnConnect(const AAFwk::Want &want) override;
/**
* @brief Called when all abilities connected to this Print extension are disconnected.
*
* You can override this function to implement your own processing logic.
*
*/
virtual void OnDisconnect(const AAFwk::Want &want) override;
/**
* @brief Called back when Print is started.
* This method can be called only by Print. You can use the StartAbility(ohos.aafwk.content.Want) method
* to start Print. Then the system calls back the current method to use the transferred want parameter
* to execute its own logic.
*
* @param want Indicates the want of Print to start.
* @param restart Indicates the startup mode. The value true indicates that Print is restarted after being
* destroyed, and the value false indicates a normal startup.
* @param startId Indicates the number of times the Print extension has been started. The startId is incremented
* by 1 every time the extension is started. For example, if the extension has been started for six times, the
* value of startId is 6.
*/
virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override;
/**
* @brief Called when this extension enters the <b>STATE_STOP</b> state.
*
* The extension in the <b>STATE_STOP</b> is being destroyed.
* You can override this function to implement your own processing logic.
*/
virtual void OnStop() override;
private:
NativeValue *CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0);
void RegisterAllCallback();
void GetSrcPath(std::string &srcPath);
JsRuntime &jsRuntime_;
std::unique_ptr<NativeReference> jsObj_;
static JsPrintExtension *jsExtension_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_EXTENSION_H

View File

@ -1,68 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JS_PRINT_EXTENSION_CONNECTION_H
#define JS_PRINT_EXTENSION_CONNECTION_H
#include <memory>
#include "ability_connect_callback.h"
#include "print_extension_context.h"
#include "event_handler.h"
class NativeEngine;
class NativeValue;
class NativeReference;
namespace OHOS {
namespace AbilityRuntime {
class JSPrintExtensionConnection : public AbilityConnectCallback {
public:
explicit JSPrintExtensionConnection(NativeEngine& engine);
~JSPrintExtensionConnection();
void OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override;
void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override;
void HandleOnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode);
void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode);
void SetJsConnectionObject(NativeValue* jsConnectionObject);
void CallJsFailed(int32_t errorCode);
private:
NativeEngine& engine_;
std::unique_ptr<NativeReference> jsConnectionObject_ = nullptr;
};
struct ConnecttionKey {
AAFwk::Want want;
int64_t id;
};
struct key_compare {
bool operator()(const ConnecttionKey &key1, const ConnecttionKey &key2) const
{
if (key1.id < key2.id) {
return true;
}
return false;
}
};
static std::map<ConnecttionKey, sptr<JSPrintExtensionConnection>, key_compare> connects_;
static int64_t serialNumber_ = 0;
static std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_EXTENSION_CONNECTION_H

View File

@ -1,34 +0,0 @@
/*
* 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 JS_PRINT_EXTENSION_CONTEXT_H
#define JS_PRINT_EXTENSION_CONTEXT_H
#include <memory>
#include "ability_connect_callback.h"
#include "event_handler.h"
#include "print_extension_context.h"
class NativeEngine;
class NativeValue;
class NativeReference;
namespace OHOS {
namespace AbilityRuntime {
NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine, std::shared_ptr<PrintExtensionContext> context);
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_EXTENSION_CONTEXT_H

View File

@ -1,69 +0,0 @@
/*
* 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 PRINT_EXTENSION_H
#define PRINT_EXTENSION_H
#include "extension_base.h"
namespace OHOS {
namespace AbilityRuntime {
class PrintExtensionContext;
class Runtime;
/**
* @brief Basic Print components.
*/
class PrintExtension : public ExtensionBase<PrintExtensionContext>,
public std::enable_shared_from_this<PrintExtension> {
public:
PrintExtension() = default;
virtual ~PrintExtension() = default;
/**
* @brief Create and init context.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
* @return The created context.
*/
virtual std::shared_ptr<PrintExtensionContext> CreateAndInitContext(
const std::shared_ptr<AbilityLocalRecord> &record, const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token) override;
/**
* @brief Init the extension.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
*/
virtual void Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token) override;
/**
* @brief Create Extension.
*
* @param runtime The runtime.
* @return The PrintExtension instance.
*/
static PrintExtension *Create(const std::unique_ptr<Runtime> &runtime);
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // PRINT_EXTENSION_H

View File

@ -1,129 +0,0 @@
/*
* 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 PRINT_EXTENSION_CONTEXT_H
#define PRINT_EXTENSION_CONTEXT_H
#include "ability_connect_callback.h"
#include "connection_manager.h"
#include "extension_context.h"
#include "start_options.h"
#include "want.h"
namespace OHOS {
namespace AbilityRuntime {
/**
* @brief context supply for Print
*
*/
class PrintExtensionContext : public ExtensionContext {
public:
PrintExtensionContext() = default;
virtual ~PrintExtensionContext() = default;
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.Print or AbilityInfo.AbilityType.PAGE template uses this method
* to start a specific ability. The system locates the target ability from installed abilities based on the value
* of the want parameter and then starts it. You can specify the ability to start using the want parameter.
*
* @param want Indicates the Want containing information about the target ability to start.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode StartAbility(const AAFwk::Want &want) const;
ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const;
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.Print template.
*
* @param want Indicates the want containing information about the ability to connect
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure
*/
bool ConnectAbility(const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const;
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.Print or AbilityInfo.AbilityType.PAGE template uses this method
* to start a specific ability. The system locates the target ability from installed abilities based on the value
* of the want parameter and then starts it. You can specify the ability to start using the want parameter.
*
* @param want Indicates the Want containing information about the target ability to start.
* @param accountId caller user.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode StartAbilityWithAccount(const AAFwk::Want &want, int accountId) const;
ErrCode StartAbilityWithAccount(
const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions) const;
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.Print template.
*
* @param want Indicates the want containing information about the ability to connect.
*
* @param accountId caller user.
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure.
*/
bool ConnectAbilityWithAccount(
const AAFwk::Want &want, int accountId, const sptr<AbilityConnectCallback> &connectCallback) const;
/**
* @brief Disconnects the current ability from an ability.
*
* @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
* is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode DisconnectAbility(const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const;
/**
* @brief Destroys the current ability.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode TerminateAbility();
using SelfType = PrintExtensionContext;
static const size_t CONTEXT_TYPE_ID;
protected:
bool IsContext(size_t contextTypeId) override
{
return contextTypeId == CONTEXT_TYPE_ID || ExtensionContext::IsContext(contextTypeId);
}
private:
static int ILLEGAL_REQUEST_CODE;
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // PRINT_EXTENSION_CONTEXT_H

View File

@ -1,36 +0,0 @@
/*
* 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 PRINT_EXTENSION_MODULE_LOADER_H
#define PRINT_EXTENSION_MODULE_LOADER_H
#include "extension_module_loader.h"
namespace OHOS::AbilityRuntime {
class PrintExtensionModuleLoader : public ExtensionModuleLoader, public Singleton<PrintExtensionModuleLoader> {
DECLARE_SINGLETON(PrintExtensionModuleLoader);
public:
/**
* @brief Create Extension.
*
* @param runtime The runtime.
* @return The Extension instance.
*/
virtual Extension *Create(const std::unique_ptr<Runtime> &runtime) const override;
virtual std::map<std::string, std::string> GetParams() override;
};
} // namespace OHOS::AbilityRuntime
#endif // PRINT_EXTENSION_MODULE_LOADER_H

View File

@ -1,110 +0,0 @@
/*
* 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 "js_print_callback.h"
#include "ability_info.h"
#include "iprint_extension_callback.h"
#include "js_print_extension_context.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_print_utils.h"
#include "napi_remote_object.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS {
namespace AbilityRuntime {
using namespace OHOS::AppExecFwk;
using namespace OHOS::Print;
JsPrintCallback::JsPrintCallback(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {}
NativeValue *JsPrintCallback::Exec(
NativeValue *jsObj, const std::string &name, NativeValue *const *argv, size_t argc, bool isSync)
{
HandleScope handleScope(jsRuntime_);
NativeObject *obj = ConvertNativeValueTo<NativeObject>(jsObj);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return nullptr;
}
NativeValue *method = obj->GetProperty(name.c_str());
if (method == nullptr) {
PRINT_HILOGE("Failed to get '%{public}s' from PrintExtension object", name.c_str());
return nullptr;
}
PRINT_HILOGD("%{public}s callback in", name.c_str());
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(reinterpret_cast<napi_env>(nativeEngine), &loop);
if (loop == nullptr) {
PRINT_HILOGE("Failed to get uv event loop");
return nullptr;
}
jsWorker_ = new (std::nothrow) uv_work_t;
if (jsWorker_ == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return nullptr;
}
container_.self = shared_from_this();
container_.nativeEngine = nativeEngine;
container_.jsObj = jsObj;
container_.jsMethod = method;
container_.argv = argv;
container_.argc = argc;
container_.jsResult = nullptr;
container_.isSync = isSync;
container_.isCompleted = false;
jsWorker_->data = &container_;
uv_queue_work(
loop, jsWorker_, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
auto container = reinterpret_cast<JsPrintCallback::Container *>(work->data);
if (container != nullptr) {
container->jsResult = container->nativeEngine->CallFunction(
container->jsObj, container->jsMethod, container->argv, container->argc);
container->isCompleted = true;
if (container->isSync) {
container->self = nullptr;
} else {
std::unique_lock<std::mutex> lock(container->self->conditionMutex_);
container->self->syncCon_.notify_one();
}
}
});
if (isSync) {
std::unique_lock<std::mutex> conditionLock(conditionMutex_);
auto waitStatus = syncCon_.wait_for(
conditionLock, std::chrono::milliseconds(SYNC_TIME_OUT), [this]() { return container_.isCompleted; });
if (!waitStatus) {
PRINT_HILOGE("print server load sa timeout");
return nullptr;
}
return container_.jsResult;
}
return nullptr;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -1,379 +0,0 @@
/*
* 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 "js_print_extension.h"
#include "ability_info.h"
#include "iprint_extension_callback.h"
#include "js_print_callback.h"
#include "js_print_extension_context.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_print_utils.h"
#include "napi_remote_object.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "printer_capability.h"
namespace OHOS {
namespace AbilityRuntime {
JsPrintExtension *JsPrintExtension::jsExtension_ = nullptr;
using namespace OHOS::AppExecFwk;
using namespace OHOS::Print;
JsPrintExtension *JsPrintExtension::Create(const std::unique_ptr<Runtime> &runtime)
{
PRINT_HILOGD("jws JsPrintExtension begin Create");
jsExtension_ = new JsPrintExtension(static_cast<JsRuntime &>(*runtime));
return jsExtension_;
}
JsPrintExtension::JsPrintExtension(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {}
JsPrintExtension::~JsPrintExtension() = default;
void JsPrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
PRINT_HILOGD("jws JsPrintExtension begin Init");
PrintExtension::Init(record, application, handler, token);
std::string srcPath = "";
GetSrcPath(srcPath);
if (srcPath.empty()) {
PRINT_HILOGE("Failed to get srcPath");
return;
}
std::string moduleName(Extension::abilityInfo_->moduleName);
moduleName.append("::").append(abilityInfo_->name);
PRINT_HILOGD("JsPrintExtension::Init module:%{public}s,srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str());
HandleScope handleScope(jsRuntime_);
auto &engine = jsRuntime_.GetNativeEngine();
jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath);
if (jsObj_ == nullptr) {
PRINT_HILOGE("Failed to get jsObj_");
return;
}
PRINT_HILOGD("JsPrintExtension::Init ConvertNativeValueTo.");
NativeObject *obj = ConvertNativeValueTo<NativeObject>(jsObj_->Get());
if (obj == nullptr) {
PRINT_HILOGE("Failed to get JsPrintExtension object");
return;
}
auto context = GetContext();
if (context == nullptr) {
PRINT_HILOGE("Failed to get context");
return;
}
PRINT_HILOGD("JsPrintExtension::Init CreateJsPrintExtensionContext.");
NativeValue *contextObj = CreateJsPrintExtensionContext(engine, context);
auto shellContextRef = jsRuntime_.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE);
contextObj = shellContextRef->Get();
PRINT_HILOGD("JsPrintExtension::Init Bind.");
context->Bind(jsRuntime_, shellContextRef.release());
PRINT_HILOGD("JsPrintExtension::SetProperty.");
obj->SetProperty("context", contextObj);
auto nativeObj = ConvertNativeValueTo<NativeObject>(contextObj);
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to get Print extension native object");
return;
}
PRINT_HILOGD("Set Print extension context pointer: %{public}p", context.get());
nativeObj->SetNativePointer(
new std::weak_ptr<AbilityRuntime::Context>(context),
[](NativeEngine *, void *data, void *) {
PRINT_HILOGD("Finalizer for weak_ptr Print extension context is called");
delete static_cast<std::weak_ptr<AbilityRuntime::Context> *>(data);
},
nullptr);
PRINT_HILOGD("JsPrintExtension::Init end.");
}
void JsPrintExtension::OnStart(const AAFwk::Want &want)
{
Extension::OnStart(want);
PRINT_HILOGD("jws JsPrintExtension OnStart begin..");
HandleScope handleScope(jsRuntime_);
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(nativeEngine), want);
NativeValue *nativeWant = reinterpret_cast<NativeValue *>(napiWant);
NativeValue *argv[] = { nativeWant };
CallObjectMethod("onCreated", argv, NapiPrintUtils::ARGC_ONE);
PRINT_HILOGD("%{public}s end.", __func__);
RegisterAllCallback();
}
void JsPrintExtension::OnStop()
{
PrintExtension::OnStop();
PRINT_HILOGD("jws JsPrintExtension OnStop begin.");
CallObjectMethod("onDestroy");
bool ret = ConnectionManager::GetInstance().DisconnectCaller(GetContext()->GetToken());
if (ret) {
PRINT_HILOGD("The Print extension connection is not disconnected.");
}
PRINT_HILOGD("%{public}s end.", __func__);
RegisterAllCallback();
}
sptr<IRemoteObject> JsPrintExtension::OnConnect(const AAFwk::Want &want)
{
PRINT_HILOGD("jws JsPrintExtension OnConnect begin.");
Extension::OnConnect(want);
PRINT_HILOGD("%{public}s begin.", __func__);
HandleScope handleScope(jsRuntime_);
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(nativeEngine), want);
NativeValue *nativeWant = reinterpret_cast<NativeValue *>(napiWant);
NativeValue *argv[] = { nativeWant };
if (!jsObj_) {
PRINT_HILOGW("Not found PrintExtension.js");
return nullptr;
}
NativeValue *value = jsObj_->Get();
NativeObject *obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return nullptr;
}
NativeValue *method = obj->GetProperty("onConnect");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onConnect from PrintExtension object");
return nullptr;
}
PRINT_HILOGD("JsPrintExtension::CallFunction onConnect, success");
NativeValue *remoteNative = nativeEngine->CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
if (remoteNative == nullptr) {
PRINT_HILOGE("remoteNative nullptr.");
}
auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject(
reinterpret_cast<napi_env>(nativeEngine), reinterpret_cast<napi_value>(remoteNative));
if (remoteObj == nullptr) {
PRINT_HILOGE("remoteObj nullptr.");
}
return remoteObj;
}
void JsPrintExtension::OnDisconnect(const AAFwk::Want &want)
{
PRINT_HILOGD("jws JsPrintExtension OnDisconnect begin.");
Extension::OnDisconnect(want);
PRINT_HILOGD("%{public}s begin.", __func__);
HandleScope handleScope(jsRuntime_);
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(nativeEngine), want);
NativeValue *nativeWant = reinterpret_cast<NativeValue *>(napiWant);
NativeValue *argv[] = { nativeWant };
if (!jsObj_) {
PRINT_HILOGW("Not found PrintExtension.js");
return;
}
NativeValue *value = jsObj_->Get();
NativeObject *obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return;
}
NativeValue *method = obj->GetProperty("onDisconnect");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onDisconnect from PrintExtension object");
return;
}
nativeEngine->CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
PRINT_HILOGD("%{public}s end.", __func__);
}
void JsPrintExtension::OnCommand(const AAFwk::Want &want, bool restart, int startId)
{
PRINT_HILOGD("jws JsPrintExtension OnCommand begin.");
Extension::OnCommand(want, restart, startId);
PRINT_HILOGD(
"%{public}s begin restart=%{public}s,startId=%{public}d.", __func__, restart ? "true" : "false", startId);
PRINT_HILOGD("%{public}s end.", __func__);
}
NativeValue *JsPrintExtension::CallObjectMethod(const char *name, NativeValue *const *argv, size_t argc)
{
PRINT_HILOGD("jws JsPrintExtension::CallObjectMethod(%{public}s), begin", name);
if (!jsObj_) {
PRINT_HILOGW("Not found PrintExtension.js");
return nullptr;
}
HandleScope handleScope(jsRuntime_);
auto &nativeEngine = jsRuntime_.GetNativeEngine();
NativeValue *value = jsObj_->Get();
NativeObject *obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return nullptr;
}
NativeValue *method = obj->GetProperty(name);
if (method == nullptr) {
PRINT_HILOGE("Failed to get '%{public}s' from PrintExtension object", name);
return nullptr;
}
PRINT_HILOGD("JsPrintExtension::CallFunction(%{public}s), success", name);
return nativeEngine.CallFunction(value, method, argv, argc);
}
void JsPrintExtension::GetSrcPath(std::string &srcPath)
{
PRINT_HILOGD("jws JsPrintExtension GetSrcPath begin.");
if (!Extension::abilityInfo_->isModuleJson) {
/* temporary compatibility api8 + config.json */
srcPath.append(Extension::abilityInfo_->package);
srcPath.append("/assets/js/");
if (!Extension::abilityInfo_->srcPath.empty()) {
srcPath.append(Extension::abilityInfo_->srcPath);
}
srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc");
return;
}
if (!Extension::abilityInfo_->srcEntrance.empty()) {
srcPath.append(Extension::abilityInfo_->moduleName + "/");
srcPath.append(Extension::abilityInfo_->srcEntrance);
srcPath.erase(srcPath.rfind('.'));
srcPath.append(".abc");
}
}
void JsPrintExtension::RegisterAllCallback()
{
PRINT_HILOGD("Register Print Extension Callback");
PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_START_DISCOVERY, []() -> bool {
PRINT_HILOGD("Start Print Discovery");
HandleScope handleScope(jsExtension_->jsRuntime_);
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onStartDiscoverPrinter");
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_STOP_DISCOVERY, []() -> bool {
PRINT_HILOGD("Stop Print Discovery");
HandleScope handleScope(jsExtension_->jsRuntime_);
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onStopDiscoverPrinter");
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_CONNECT_PRINTER, [](uint32_t printId) -> bool {
PRINT_HILOGD("Connect Printer");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jsPrintId =
OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onConnectPrinter", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(
PRINT_EXTCB_DISCONNECT_PRINTER, [](uint32_t printId) -> bool {
PRINT_HILOGD("Disconnect Printer");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jsPrintId =
OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onDisconnectPrinter", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_START_PRINT, [](const PrintJob &job) -> bool {
PRINT_HILOGD("Start Print Job");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(jobObject);
NativeValue *arg[] = { nativeJob };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onStartPrintJob", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_CANCEL_PRINT, [](const PrintJob &job) -> bool {
PRINT_HILOGD("Cancel Print Job");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(jobObject);
NativeValue *arg[] = { nativeJob };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onCancelPrintJob", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(
PRINT_EXTCB_REQUEST_CAP, [](uint32_t printId, PrinterCapability &cap) -> bool {
PRINT_HILOGD("Request Capability");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jsPrintId =
OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
NativeValue *result = callback->Exec(value, "onRequestPrinterCapability", arg, NapiPrintUtils::ARGC_ONE);
if (result != nullptr) {
PRINT_HILOGD("Request Capability Success");
cap.BuildFromJs(reinterpret_cast<napi_env>(nativeEng), reinterpret_cast<napi_value>(result));
return true;
}
PRINT_HILOGD("Request Capability Failed!!!");
return false;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(
PRINT_EXTCB_REQUEST_PREVIEW, [](const PrintJob &job) -> bool {
PRINT_HILOGD("Requet preview");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(jobObject);
NativeValue *arg[] = { nativeJob };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onRequestPreview", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -1,185 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "js_print_extension_connection.h"
#include "js_extension_context.h"
#include "js_data_struct_converter.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi_common_want.h"
#include "napi_common_util.h"
#include "napi_remote_object.h"
#include "napi_common_start_options.h"
#include "start_options.h"
#include "napi_print_utils.h"
#include "print_log.h"
using namespace OHOS::Print;
namespace OHOS {
namespace AbilityRuntime {
JSPrintExtensionConnection::JSPrintExtensionConnection(NativeEngine& engine) : engine_(engine) {}
JSPrintExtensionConnection::~JSPrintExtensionConnection() = default;
void JSPrintExtensionConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &element,
const sptr<IRemoteObject> &remoteObject, int resultCode)
{
PRINT_HILOGD("OnAbilityConnectDone begin, resultCode:%{public}d", resultCode);
if (handler_ == nullptr) {
PRINT_HILOGD("handler_ nullptr");
return;
}
wptr<JSPrintExtensionConnection> connection = this;
auto task = [connection, element, remoteObject, resultCode]() {
sptr<JSPrintExtensionConnection> connectionSptr = connection.promote();
if (!connectionSptr) {
PRINT_HILOGD("connectionSptr nullptr");
return;
}
connectionSptr->HandleOnAbilityConnectDone(element, remoteObject, resultCode);
};
handler_->PostTask(task, "OnAbilityConnectDone");
}
void JSPrintExtensionConnection::HandleOnAbilityConnectDone(const AppExecFwk::ElementName &element,
const sptr<IRemoteObject> &remoteObject, int resultCode)
{
PRINT_HILOGD("HandleOnAbilityConnectDone begin, resultCode:%{public}d", resultCode);
// wrap ElementName
napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast<napi_env>(&engine_), element);
NativeValue* nativeElementName = reinterpret_cast<NativeValue*>(napiElementName);
// wrap RemoteObject
PRINT_HILOGD("OnAbilityConnectDone begin NAPI_ohos_rpc_CreateJsRemoteObject");
napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(
reinterpret_cast<napi_env>(&engine_), remoteObject);
NativeValue* nativeRemoteObject = reinterpret_cast<NativeValue*>(napiRemoteObject);
NativeValue* argv[] = {nativeElementName, nativeRemoteObject};
if (jsConnectionObject_ == nullptr) {
PRINT_HILOGE("jsConnectionObject_ nullptr");
return;
}
NativeValue* value = jsConnectionObject_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get object");
return;
}
NativeValue* methodOnConnect = obj->GetProperty("onConnect");
if (methodOnConnect == nullptr) {
PRINT_HILOGE("Failed to get onConnect from object");
return;
}
PRINT_HILOGD("JSPrintExtensionConnection::CallFunction onConnect, success");
engine_.CallFunction(value, methodOnConnect, argv, NapiPrintUtils::ARGC_TWO);
PRINT_HILOGD("OnAbilityConnectDone end");
}
void JSPrintExtensionConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode)
{
PRINT_HILOGD("OnAbilityDisconnectDone begin, resultCode:%{public}d", resultCode);
if (handler_ == nullptr) {
PRINT_HILOGD("handler_ nullptr");
return;
}
wptr<JSPrintExtensionConnection> connection = this;
auto task = [connection, element, resultCode]() {
sptr<JSPrintExtensionConnection> connectionSptr = connection.promote();
if (!connectionSptr) {
PRINT_HILOGD("connectionSptr nullptr");
return;
}
connectionSptr->HandleOnAbilityDisconnectDone(element, resultCode);
};
handler_->PostTask(task, "OnAbilityDisconnectDone");
}
void JSPrintExtensionConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element,
int resultCode)
{
PRINT_HILOGD("HandleOnAbilityDisconnectDone begin, resultCode:%{public}d", resultCode);
napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast<napi_env>(&engine_), element);
NativeValue* nativeElementName = reinterpret_cast<NativeValue*>(napiElementName);
NativeValue* argv[] = {nativeElementName};
if (jsConnectionObject_ == nullptr) {
PRINT_HILOGE("jsConnectionObject_ nullptr");
return;
}
NativeValue* value = jsConnectionObject_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get object");
return;
}
NativeValue* method = obj->GetProperty("onDisconnect");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onDisconnect from object");
return;
}
// release connect
PRINT_HILOGD("OnAbilityDisconnectDone connects_.size:%{public}zu", connects_.size());
std::string bundleName = element.GetBundleName();
std::string abilityName = element.GetAbilityName();
auto item = std::find_if(connects_.begin(),
connects_.end(),
[bundleName, abilityName](
const std::map<ConnecttionKey, sptr<JSPrintExtensionConnection>>::value_type &obj) {
return (bundleName == obj.first.want.GetBundle()) &&
(abilityName == obj.first.want.GetElement().GetAbilityName());
});
if (item != connects_.end()) {
// match bundlename && abilityname
connects_.erase(item);
PRINT_HILOGD("OnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size());
}
PRINT_HILOGD("OnAbilityDisconnectDone CallFunction success");
engine_.CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
}
void JSPrintExtensionConnection::SetJsConnectionObject(NativeValue* jsConnectionObject)
{
jsConnectionObject_ = std::unique_ptr<NativeReference>(engine_.CreateReference(jsConnectionObject, 1));
}
void JSPrintExtensionConnection::CallJsFailed(int32_t errorCode)
{
PRINT_HILOGD("CallJsFailed begin");
if (jsConnectionObject_ == nullptr) {
PRINT_HILOGE("jsConnectionObject_ nullptr");
return;
}
NativeValue* value = jsConnectionObject_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get object");
return;
}
NativeValue* method = obj->GetProperty("onFailed");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onFailed from object");
return;
}
NativeValue* argv[] = {engine_.CreateNumber(errorCode)};
PRINT_HILOGD("CallJsFailed CallFunction success");
engine_.CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
PRINT_HILOGD("CallJsFailed end");
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -1,500 +0,0 @@
/*
* 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 "js_print_extension_context.h"
#include "js_data_struct_converter.h"
#include "js_extension_context.h"
#include "js_print_extension_connection.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi_common_start_options.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_print_utils.h"
#include "napi_remote_object.h"
#include "print_log.h"
#include "start_options.h"
using namespace OHOS::Print;
namespace OHOS {
namespace AbilityRuntime {
class JsPrintExtensionContext final {
public:
explicit JsPrintExtensionContext(const std::shared_ptr<PrintExtensionContext> &context) : context_(context) {}
~JsPrintExtensionContext() = default;
static void Finalizer(NativeEngine *engine, void *data, void *hint)
{
PRINT_HILOGD("JsAbilityContext::Finalizer is called");
std::unique_ptr<JsPrintExtensionContext>(static_cast<JsPrintExtensionContext *>(data));
}
static NativeValue *StartAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext *me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr;
}
static NativeValue *StartAbilityWithAccount(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext *me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnStartAbilityWithAccount(*engine, *info) : nullptr;
}
static NativeValue *ConnectAbilityWithAccount(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext *me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnConnectAbilityWithAccount(*engine, *info) : nullptr;
}
static NativeValue *TerminateAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext *me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnTerminateAbility(*engine, *info) : nullptr;
}
static NativeValue *ConnectAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext *me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnConnectAbility(*engine, *info) : nullptr;
}
static NativeValue *DisconnectAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext *me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnDisconnectAbility(*engine, *info) : nullptr;
}
private:
std::weak_ptr<PrintExtensionContext> context_;
NativeValue *OnStartAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnStartAbility is called");
// only support one or two or three params
if (info.argc != NapiPrintUtils::ARGC_ONE && info.argc != NapiPrintUtils::ARGC_TWO &&
info.argc != NapiPrintUtils::ARGC_THREE) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
decltype(info.argc) unwrapArgc = 0;
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ZERO]), want);
PRINT_HILOGD("%{public}s bundlename:%{public}s abilityname:%{public}s", __func__, want.GetBundle().c_str(),
want.GetElement().GetAbilityName().c_str());
unwrapArgc++;
AAFwk::StartOptions startOptions;
if (info.argc > NapiPrintUtils::ARGC_ONE && info.argv[NapiPrintUtils::INDEX_ONE]->TypeOf() == NATIVE_OBJECT) {
PRINT_HILOGD("OnStartAbility start options is used.");
AppExecFwk::UnwrapStartOptions(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ONE]), startOptions);
unwrapArgc++;
}
AsyncTask::CompleteCallback complete = [weak = context_, want, startOptions, unwrapArgc](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("startAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released"));
return;
}
ErrCode errcode = ERR_OK;
(unwrapArgc == 1) ? errcode = context->StartAbility(want)
: errcode = context->StartAbility(want, startOptions);
if (errcode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed."));
}
};
NativeValue *lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnStartAbility", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
NativeValue *OnStartAbilityWithAccount(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnStartAbilityWithAccount is called");
// only support two or three or four params
if (info.argc != NapiPrintUtils::ARGC_TWO && info.argc != NapiPrintUtils::ARGC_THREE &&
info.argc != NapiPrintUtils::ARGC_FOUR) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
decltype(info.argc) unwrapArgc = 0;
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ZERO]), want);
PRINT_HILOGD("%{public}s bundlename:%{public}s abilityname:%{public}s", __func__, want.GetBundle().c_str(),
want.GetElement().GetAbilityName().c_str());
unwrapArgc++;
int32_t accountId = 0;
if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ONE]), accountId)) {
PRINT_HILOGD("%{public}s called, the second parameter is invalid.", __func__);
return engine.CreateUndefined();
}
PRINT_HILOGD("%{public}d accountId:", accountId);
unwrapArgc++;
AAFwk::StartOptions startOptions;
if (info.argc > NapiPrintUtils::ARGC_TWO && info.argv[NapiPrintUtils::INDEX_TWO]->TypeOf() == NATIVE_OBJECT) {
PRINT_HILOGD("OnStartAbilityWithAccount start options is used.");
AppExecFwk::UnwrapStartOptions(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_TWO]), startOptions);
unwrapArgc++;
}
AsyncTask::CompleteCallback complete = [weak = context_, want, accountId, startOptions, unwrapArgc](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("startAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
ErrCode errcode = ERR_OK;
(unwrapArgc == NapiPrintUtils::ARGC_TWO)
? errcode = context->StartAbilityWithAccount(want, accountId)
: errcode = context->StartAbilityWithAccount(want, accountId, startOptions);
if (errcode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed."));
}
};
NativeValue *lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnStartAbilityWithAccount", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
NativeValue *OnTerminateAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnTerminateAbility is called");
// only support one or zero params
if (info.argc != NapiPrintUtils::ARGC_ZERO && info.argc != NapiPrintUtils::ARGC_ONE) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
AsyncTask::CompleteCallback complete = [weak = context_](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("TerminateAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
auto errcode = context->TerminateAbility();
if (errcode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errcode, "Terminate Ability failed."));
}
};
NativeValue *lastParam =
(info.argc == NapiPrintUtils::ARGC_ZERO) ? nullptr : info.argv[NapiPrintUtils::INDEX_ZERO];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnTerminateAbility", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
NativeValue *OnConnectAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnConnectAbility is called");
// only support two params
if (info.argc != NapiPrintUtils::ARGC_TWO) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
// unwrap want
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(
reinterpret_cast<napi_env>(&engine), reinterpret_cast<napi_value>(info.argv[INDEX_ZERO]), want);
PRINT_HILOGD("%{public}s bundlename:%{public}s abilityname:%{public}s", __func__, want.GetBundle().c_str(),
want.GetElement().GetAbilityName().c_str());
// unwarp connection
sptr<JSPrintExtensionContext> connection = new JSPrintExtensionContext(engine);
connection->SetJsConnectionObject(info.argv[1]);
int64_t connectId = serialNumber_;
ConnecttionKey key;
key.id = serialNumber_;
key.want = want;
connects_.emplace(key, connection);
if (serialNumber_ < INT64_MAX) {
serialNumber_++;
} else {
serialNumber_ = 0;
}
PRINT_HILOGD("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr());
AsyncTask::CompleteCallback complete = [weak = context_, want, connection, connectId](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("OnConnectAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released"));
return;
}
PRINT_HILOGD("context->ConnectAbility connection:%{public}d", (int32_t)connectId);
if (!context->ConnectAbility(want, connection)) {
connection->CallJsFailed(ERROR_CODE_ONE);
}
task.Resolve(engine, engine.CreateUndefined());
};
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnConnectAbility", engine,
CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result));
return engine.CreateNumber(connectId);
}
NativeValue *OnConnectAbilityWithAccount(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnConnectAbilityWithAccount is called");
// only support three params
if (info.argc != NapiPrintUtils::ARGC_THREE) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
// unwrap want
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ZERO]), want);
PRINT_HILOGD("%{public}s bundlename:%{public}s abilityname:%{public}s", __func__, want.GetBundle().c_str(),
want.GetElement().GetAbilityName().c_str());
int32_t accountId = 0;
if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ONE]), accountId)) {
PRINT_HILOGD("%{public}s called, the second parameter is invalid.", __func__);
return engine.CreateUndefined();
}
// unwarp connection
sptr<JSPrintExtensionConnection> connection = new JSPrintExtensionConnection(engine);
connection->SetJsConnectionObject(info.argv[1]);
int64_t connectId = serialNumber_;
ConnecttionKey key;
key.id = serialNumber_;
key.want = want;
connects_.emplace(key, connection);
if (serialNumber_ < INT64_MAX) {
serialNumber_++;
} else {
serialNumber_ = 0;
}
PRINT_HILOGD("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr());
AsyncTask::CompleteCallback complete = [weak = context_, want, accountId, connection, connectId](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("OnConnectAbilityWithAccount begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released"));
return;
}
PRINT_HILOGD("context->ConnectAbilityWithAccount connection:%{public}d", (int32_t)connectId);
if (!context->ConnectAbilityWithAccount(want, accountId, connection)) {
connection->CallJsFailed(ERROR_CODE_ONE);
}
task.Resolve(engine, engine.CreateUndefined());
};
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnConnectAbilityWithAccount", engine,
CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result));
return engine.CreateNumber(connectId);
}
NativeValue *OnDisconnectAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnDisconnectAbility is called");
// only support one or two params
if (info.argc != NapiPrintUtils::ARGC_ONE && info.argc != NapiPrintUtils::ARGC_TWO) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
// unwrap want
AAFwk::Want want;
// unwrap connectId
int64_t connectId = -1;
sptr<JSPrintExtensionConnection> connection = nullptr;
napi_get_value_int64(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ZERO]), &connectId);
PRINT_HILOGD("OnDisconnectAbility connection:%{public}d", (int32_t)connectId);
auto item = std::find_if(connects_.begin(), connects_.end(),
[&connectId](const std::map<ConnecttionKey, sptr<JSPrintExtensionConnection>>::value_type &obj) {
return connectId == obj.first.id;
});
if (item != connects_.end()) {
// match id
want = item->first.want;
connection = item->second;
PRINT_HILOGD("%{public}s find conn ability:%{public}p exist", __func__, item->second.GetRefPtr());
} else {
PRINT_HILOGD("%{public}s not find conn exist.", __func__);
}
// begin disconnect
AsyncTask::CompleteCallback complete = [weak = context_, want, connection](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("OnDisconnectAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
if (connection == nullptr) {
PRINT_HILOGW("connection nullptr");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_TWO, "not found connection"));
return;
}
PRINT_HILOGD("context->DisconnectAbility");
auto errcode = context->DisconnectAbility(want, connection);
errcode == 0 ? task.Resolve(engine, engine.CreateUndefined())
: task.Reject(engine, CreateJsError(engine, errcode, "Disconnect Ability failed."));
};
NativeValue *lastParam =
(info.argc == NapiPrintUtils::ARGC_ONE) ? nullptr : info.argv[NapiPrintUtils::INDEX_ONE];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnDisconnectAbility", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
};
NativeValue *CreateJsMetadata(NativeEngine &engine, const AppExecFwk::Metadata &Info)
{
PRINT_HILOGD("CreateJsMetadata");
NativeValue *objValue = engine.CreateObject();
NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
object->SetProperty("name", CreateJsValue(engine, Info.name));
object->SetProperty("value", CreateJsValue(engine, Info.value));
object->SetProperty("resource", CreateJsValue(engine, Info.resource));
return objValue;
}
NativeValue *CreateJsMetadataArray(NativeEngine &engine, const std::vector<AppExecFwk::Metadata> &info)
{
PRINT_HILOGD("CreateJsMetadataArray");
NativeValue *arrayValue = engine.CreateArray(info.size());
NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
uint32_t index = 0;
for (const auto &item : info) {
array->SetElement(index++, CreateJsMetadata(engine, item));
}
return arrayValue;
}
NativeValue *CreateJsExtensionAbilityInfo(NativeEngine &engine, const AppExecFwk::ExtensionAbilityInfo &info)
{
PRINT_HILOGD("CreateJsExtensionAbilityInfo");
NativeValue *objValue = engine.CreateObject();
NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
object->SetProperty("bundleName", CreateJsValue(engine, info.bundleName));
object->SetProperty("moduleName", CreateJsValue(engine, info.moduleName));
object->SetProperty("name", CreateJsValue(engine, info.name));
object->SetProperty("labelId", CreateJsValue(engine, info.labelId));
object->SetProperty("descriptionId", CreateJsValue(engine, info.descriptionId));
object->SetProperty("iconId", CreateJsValue(engine, info.iconId));
object->SetProperty("isVisible", CreateJsValue(engine, info.visible));
object->SetProperty("extensionAbilityType", CreateJsValue(engine, info.type));
NativeValue *permissionArrayValue = engine.CreateArray(info.permissions.size());
NativeArray *permissionArray = ConvertNativeValueTo<NativeArray>(permissionArrayValue);
if (permissionArray != nullptr) {
int index = 0;
for (auto permission : info.permissions) {
permissionArray->SetElement(index++, CreateJsValue(engine, permission));
}
}
object->SetProperty("permissions", permissionArrayValue);
object->SetProperty("applicationInfo", CreateJsApplicationInfo(engine, info.applicationInfo));
object->SetProperty("metadata", CreateJsMetadataArray(engine, info.metadata));
object->SetProperty("enabled", CreateJsValue(engine, info.enabled));
object->SetProperty("readPermission", CreateJsValue(engine, info.readPermission));
object->SetProperty("writePermission", CreateJsValue(engine, info.writePermission));
return objValue;
}
NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine, std::shared_ptr<PrintExtensionContext> context)
{
PRINT_HILOGD("CreateJsPrintExtensionContext begin");
NativeValue *objValue = CreateJsExtensionContext(engine, context);
NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
std::unique_ptr<JsPrintExtensionContext> jsContext = std::make_unique<JsPrintExtensionContext>(context);
object->SetNativePointer(jsContext.release(), JsPrintExtensionContext::Finalizer, nullptr);
// make handler
handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
const char *moduleName = "JsPrintExtensionContext";
BindNativeFunction(engine, *object, "startAbility", moduleName, JsPrintExtensionContext::StartAbility);
BindNativeFunction(engine, *object, "terminateSelf", moduleName, JsPrintExtensionContext::TerminateAbility);
BindNativeFunction(engine, *object, "connectAbility", moduleName, JsPrintExtensionContext::ConnectAbility);
BindNativeFunction(engine, *object, "disconnectAbility", moduleName, JsPrintExtensionContext::DisconnectAbility);
BindNativeFunction(
engine, *object, "startAbilityWithAccount", moduleName, JsPrintExtensionContext::StartAbilityWithAccount);
BindNativeFunction(
engine, *object, "connectAbilityWithAccount", moduleName, JsPrintExtensionContext::ConnectAbilityWithAccount);
if (context) {
PRINT_HILOGD("Set ExtensionAbilityInfo Property");
auto abilityInfo = context->GetAbilityInfo();
auto hapModuleInfo = context->GetHapModuleInfo();
if (abilityInfo && hapModuleInfo) {
auto isExist = [&abilityInfo](const AppExecFwk::ExtensionAbilityInfo &info) {
PRINT_HILOGD("%{public}s, %{public}s", info.bundleName.c_str(), info.name.c_str());
return info.bundleName == abilityInfo->bundleName && info.name == abilityInfo->name;
};
auto infoIter =
std::find_if(hapModuleInfo->extensionInfos.begin(), hapModuleInfo->extensionInfos.end(), isExist);
if (infoIter == hapModuleInfo->extensionInfos.end()) {
PRINT_HILOGD("Get target fail.");
return objValue;
}
object->SetProperty("extensionAbilityInfo", CreateJsExtensionAbilityInfo(engine, *infoIter));
}
}
return objValue;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -1,67 +0,0 @@
/*
* 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 "print_extension.h"
#include "ability_loader.h"
#include "connection_manager.h"
#include "js_print_extension.h"
#include "print_extension_context.h"
#include "print_log.h"
#include "runtime.h"
namespace OHOS {
namespace AbilityRuntime {
using namespace OHOS::AppExecFwk;
PrintExtension *PrintExtension::Create(const std::unique_ptr<Runtime> &runtime)
{
PRINT_HILOGD("jws PrintExtension::Create runtime");
if (!runtime) {
return new PrintExtension();
}
PRINT_HILOGD("jws PrintExtension::Create runtime");
switch (runtime->GetLanguage()) {
case Runtime::Language::JS:
return JsPrintExtension::Create(runtime);
default:
return new PrintExtension();
}
}
void PrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
PRINT_HILOGD("jws PrintExtension begin init context");
ExtensionBase<PrintExtensionContext>::Init(record, application, handler, token);
PRINT_HILOGD("PrintExtension begin init context");
}
std::shared_ptr<PrintExtensionContext> PrintExtension::CreateAndInitContext(
const std::shared_ptr<AbilityLocalRecord> &record, const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token)
{
PRINT_HILOGD("jws PrintExtension begin init context");
std::shared_ptr<PrintExtensionContext> context =
ExtensionBase<PrintExtensionContext>::CreateAndInitContext(record, application, handler, token);
if (context == nullptr) {
PRINT_HILOGE("PrintExtension::CreateAndInitContext context is nullptr");
return context;
}
return context;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -1,128 +0,0 @@
/*
* 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 "print_extension_context.h"
#include "ability_connection.h"
#include "ability_manager_client.h"
#include "print_log.h"
namespace OHOS {
namespace AbilityRuntime {
const size_t PrintExtensionContext::CONTEXT_TYPE_ID(std::hash<const char *> {}("PrintExtensionContext"));
int PrintExtensionContext::ILLEGAL_REQUEST_CODE(-1);
ErrCode PrintExtensionContext::StartAbility(const AAFwk::Want &want) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE);
PRINT_HILOGD("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbility is failed %{public}d", err);
}
return err;
}
ErrCode PrintExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err =
AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, ILLEGAL_REQUEST_CODE);
PRINT_HILOGD("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbility is failed %{public}d", err);
}
return err;
}
bool PrintExtensionContext::ConnectAbility(
const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode ret = ConnectionManager::GetInstance().ConnectAbility(token_, want, connectCallback);
PRINT_HILOGD("PrintExtensionContext::ConnectAbility ErrorCode = %{public}d", ret);
return ret == ERR_OK;
}
ErrCode PrintExtensionContext::StartAbilityWithAccount(const AAFwk::Want &want, int accountId) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
PRINT_HILOGD("%{public}d accountId:", accountId);
ErrCode err =
AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE, accountId);
PRINT_HILOGD("%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbilityWithAccount is failed %{public}d", err);
}
return err;
}
ErrCode PrintExtensionContext::StartAbilityWithAccount(
const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(
want, startOptions, token_, ILLEGAL_REQUEST_CODE, accountId);
PRINT_HILOGD("%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbilityWithAccount is failed %{public}d", err);
}
return err;
}
bool PrintExtensionContext::ConnectAbilityWithAccount(
const AAFwk::Want &want, int accountId, const sptr<AbilityConnectCallback> &connectCallback) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode ret = ConnectionManager::GetInstance().ConnectAbilityWithAccount(token_, want, accountId, connectCallback);
PRINT_HILOGD("PrintExtensionContext::ConnectAbilityWithAccount ErrorCode = %{public}d", ret);
return ret == ERR_OK;
}
ErrCode PrintExtensionContext::DisconnectAbility(
const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode ret = ConnectionManager::GetInstance().DisconnectAbility(token_, want.GetElement(), connectCallback);
if (ret != ERR_OK) {
PRINT_HILOGE("%{public}s end DisconnectAbility error, ret=%{public}d", __func__, ret);
}
PRINT_HILOGD("%{public}s end DisconnectAbility", __func__);
return ret;
}
ErrCode PrintExtensionContext::TerminateAbility()
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::TerminateAbility is failed %{public}d", err);
}
PRINT_HILOGD("%{public}s end.", __func__);
return err;
}
AppExecFwk::AbilityType PrintExtensionContext::GetAbilityInfoType() const
{
std::shared_ptr<AppExecFwk::AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
PRINT_HILOGE("PrintExtensionContext::GetAbilityInfoType info == nullptr");
return AppExecFwk::AbilityType::UNKNOWN;
}
return info->type;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -1,43 +0,0 @@
/*
* 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 "print_extension_module_loader.h"
#include "print_extension.h"
#include "print_log.h"
namespace OHOS::AbilityRuntime {
PrintExtensionModuleLoader::PrintExtensionModuleLoader() = default;
PrintExtensionModuleLoader::~PrintExtensionModuleLoader() = default;
Extension *PrintExtensionModuleLoader::Create(const std::unique_ptr<Runtime> &runtime) const
{
PRINT_HILOGD("jws PrintExtension::Create runtime");
return PrintExtension::Create(runtime);
}
std::map<std::string, std::string> PrintExtensionModuleLoader::GetParams()
{
std::map<std::string, std::string> params;
params.insert(std::pair<std::string, std::string>("type", "15"));
params.insert(std::pair<std::string, std::string>("name", "PrintExtension"));
return params;
}
extern "C" __attribute__((visibility("default"))) void *OHOS_EXTENSION_GetExtensionModule()
{
return &PrintExtensionModuleLoader::GetInstance();
}
} // namespace OHOS::AbilityRuntime

View File

@ -1,55 +0,0 @@
# 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.
#####################################################
# below is the format of defining event #
#####################################################
#domain: domain name. [Only one domain name can be defined at the top]
#
#author: the author name who defined this event.
#date: the date when this event was defined, format is YYYY-MM-DD.
#logged: source file which refer to this event.
#usage: the usage of this event.
#//Define event name and event properties.
#@EVENT_NAME: the event definition part begin.
# // __BASE is used for defining the basic info of the event.
# // "type" optional values are: FAULT, STATISTICS, SECURITY, BEHAVIOR.
# // "level" optional values are: CRITICAL, MINOR.
# // "tag" set tags with may used by subscriber of this event, multiple tags devided by space.
# // "desc" full description of this event.
# @PARAMETER: {type: parameter type, arrsize: array length(optional), desc: parameter description}.
# // follow the __BASE block, each line defines a parameter of this event.
# // "type" optional values are: INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, FLOAT, DOUBLE, STRING.
# // "arrsize" of the parameter is an array, set a non-zero value.
# // "desc" full description of this parameter.
#####################################################
# Example of some hiviewdfx events definition #
#####################################################
domain: PRINT
SERVICE_FAULT:
__BASE: {type: FAULT, level: CRITICAL, desc: The event is service fault }
FAULT_TYPE: {type: INT32, desc: fault id }
MODULE_NAME: {type: STRING, desc: module name }
ERROR_TYPE: {type: INT32, desc: error type }
RUNTIME_FAULT:
__BASE: {type: FAULT, level: CRITICAL, desc: The event is runtime fault }
FAULT_TYPE: {type: INT32, desc: fault id }
ERROR_TYPE: {type: INT32, desc: error type }
USAGETIME_STATISTIC:
__BASE: {type: STATISTIC, level: MINOR, desc: The event is usagetime statistic }
PRINT_INFO: {type: STRING, desc: print infomation }

View File

@ -1,137 +0,0 @@
/*
* 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.
*/
/**
* class of print extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @StageModelOnly
*/
declare class PrintExtensionAbility {
/**
* Called once to initialize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onCreated(want: Want): void;
/**
* Called once to start to discover the printers connected with the device.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onStartDiscoverPrinter(): void;
/**
* Called once to stop discovering the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onStopDiscoverPrinter(): void;
/**
* Called once to connect to the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onConnectPrinter(printerId: number): void;
/**
* Called once to disconnect the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onDisconnectPrinter(printerId: number): void;
/**
* Called once to start print job.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onStartPrintJob(jobInfo: PrintJob): void;
/**
* Called once to remove the print job has been started.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onCancelPrintJob(jobInfo: PrintJob): void;
/**
* Called once to request the capability of the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onRequestPrinterCapability(printerId: number): PrinterCapability;
/**
* Called once to request preview and send result to Print SA.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onRequestPreview(jobInfo: PrintJob): Uri;
/**
* Called once to finalize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onDestroy(): void;
}
export default PrintExtensionAbility;

View File

@ -1,329 +0,0 @@
/*
* 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 {AsyncCallback} from './basic';
/**
* System print
* @sysCap SystemCapability.Print.print
* @import import print from '@ohos.app.print';
* @since 9
*/
declare namespace print {
interface PrintTask {
/**
* Register event callback when the current print task is in process.
* @since 9
* @param type block Indicates the print task has been blocked.
* type success Indicates the print task succeed. .
* type fail Indicates the print task has completed with failure.
* type cancel Indicates the print task has been cancelled.
* @param callback The callback function for print task change event
* @permission {@code ohos.permission.PRINT}
* @return -
*/
on(type:'block'| 'success'| 'fail' | 'cancel', callback:() => void): void;
/**
* Unregister event callback when the current print task is in process.
* @since 9
* @param type block Indicates the print task has been blocked.
* type success Indicates the print task succeed. .
* type fail Indicates the print task has completed with failure.
* type cancel Indicates the print task has been cancelled.
* @param callback The callback function for print task change event
* @permission {@code ohos.permission.PRINT}
* @return -
*/
off(type:'block'| 'success'| 'fail' | 'cancel', callback?:() => void): void;
}
/**
* Start new print task for App.
* @since 9
* @param files Indicates the document list to be printed.
* @param callback The callback function for print task
* @permission {@code ohos.permission.PRINT}
* @return -
*/
function print(files: Array<string>, callback: AsyncCallback<PrintTask>): void;
function print(files: Array<string>): Promise<PrintTask>;
interface PrintMargin {
top: number; // top margin
bottom: number; // bottom margin
left: number; // left side margin
right: number; // right side margin
}
interface PrinterRange {
startPage: number; // start page of sequence
endPage: number; // end page of sequence
pages: Array<number>; // discrete page of sequence
}
interface PreviewAttribute {
previewRange: PrinterRange; // preview page range
result: string; // preview file
}
interface PrinterResolution {
id: number; // resolution id
horizontalDpi: number // horizontal DPI
verticalDpi: number; // vertical DPI
}
interface PrinterPageSize {
id: number; // page size id
name: string; // page size name
width: number; // unit: milimeter
height: number; // unit: milimeter
}
interface PrinterCapability {
/* Printer Capability */
minMargin: PrintMargin; // min margin of printer
pageSize: Array<PrinterPageSize>; // the page size list supported by the printer
resolution: Array<PrinterResolution>; // the resolution list supported by the printer
colorMode: number; // color mode
duplexMode: number; // duplex mode
}
interface PrinterInfo {
printerId: number; // printer id
printerName: string; // printer name
printerIcon: number; // resource id of printer icon
printerState: PrinterState; // current printer state
description: string; // printer description
capability: PrinterCapability; // printer capability
}
interface PrintJob {
files: Array<string>; // document list to be printed
/* job attributes */
printerId: number; // printer id to take charge of printing
jobState: PrintJobState; // current print job state
copyNumber: number; // copies of document list
pageRange: PrinterRange; // range size to be printed
isSequential?: boolean; // sequential print
pageSize?: PrinterPageSize; // the selected page size
isLandscape?: boolean; // vertical printing
colorMode?: number; // color mode
duplexMode?: number; // duplex mode
margin?: PrintMargin; // current margin setting
preview?: PreviewAttribute; // preview setting
}
enum PrinterState {
PRINTER_ADD = 1, // new printers arrival
PRINTER_REMOVED = 2, // printers lost
PRINTER_IDLE = 3, // printer idle
PRINTER_PRINTING = 4, // printer is working
PRINTER_BLOCK = 5, // printer has been blocked
PRINTER_BUSY = 6, // printer is busy
PRINTER_FAULT = 7 // printer failure
}
enum PrintJobState {
PRINT_JOB_INIT = 1, // initial state of print job
PRINT_JOB_START = 2, // start print job
PRINT_JOB_PRINTING = 3, // printing
PRINT_JOB_BLOCK = 4, // print job has been blocked
PRINT_JOB_COMPLETE = 5, // print completed
PRINT_JOB_CANCEL = 6 // print job has been cancelled
}
interface PrinterExtensionInfo extends ExtensionAbilityInfo{
extensionId: number; // extesion id of printer extension
vendorId: number; // vendor id of extension
vendorName: string; // vendor name
vendorIcon: number; // resource id of vendor
version: string; // version of current printer extension
}
/**
* Get all printer extensin installed.
*
* @since 9
* @param callback The callback function for handling the extension list found
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function queryExtensionAbilityInfos(callback: AsyncCallback<Array<PrinterExtensionInfo>>): void;
function queryExtensionAbilityInfos(): Promise<Array<PrinterExtensionInfo>>;
/**
* Load the specific printer extension and start to discover printer.
*
* @since 9
* @param extensionList Indicates the list of printer extension
* empty list of extensionList Indicates to find printer with all installed extension
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function startDiscoverPrinter(extensionList:Array<number>, callback: AsyncCallback<boolean>): void;
function startDiscoverPrinter(extensionList:Array<number>): Promise<boolean>;
/**
* Stop discovering the printer with specific printer extension.
*
* @since 9
* @param extensionList Indicates the list of printer extension
* empty list of extensionList Indicates to find printer with all installed extension
* @param callback The callback function for indcating the result of API execution
* @permission {@ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function stopDiscoverPrinter(callback: AsyncCallback<boolean>): void;
function stopDiscoverPrinter(): Promise<boolean>;
/**
* Start print job.
*
* @since 9
* @param jobInfo Indicates the information of print job.
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function startPrintJob(jobinfo:PrintJob, callback:AsyncCallback<boolean>):void;
function startPrintJob(jobinfo:PrintJob): Promise<boolean>;
/**
* Cancel the print job has been sent to printer.
*
* @since 9
* @param jobInfo Indicates the information of print job.
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function cancelPrintJob(jobinfo:PrintJob, callback:AsyncCallback<boolean>):void;
function cancelPrintJob(jobinfo:PrintJob): Promise<boolean>;
/**
* Request preview of the print job.
*
* @since 9
* @param jobInfo Indicates the information of print job.
* @param callback The callback function for preview result from printer
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function requestPrintPreview(jobinfo:PrintJob, callback:(result:string) => void): void;
function requestPrintPreview(jobinfo:PrintJob): Promise<string>;
/**
* Query capability for the specific printer.
*
* @since 9
* @param printerId Indicates id of the printer
* @param callback The callback function for capability from printer
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function queryPrinterCapability(printerId:number, callback:AsyncCallback<PrinterCapability>):void;
function queryPrinterCapability(printerId:number): Promise<PrinterCapability>
/**
* Register event callback for the state change of printer.
*
* @since 9
* @param printerStateChange Indicates state change of printer
* @param callback The callback function for state change of printer.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
on(type: 'printerStateChange', callback:(state: PrinterState, info: PrinterInfo) => void): void;
off(type: 'printerStateChange', callback:(boolean) => void): void;
/**
* Register event callback for the specific print job.
*
* @since 9
* @param jobStateChange Indicates state change of print job
* @param callback The callback function for state change of print job.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
on(type: 'jobStateChange', callback:(state: PrintJobState, job: PrintJob) => void): void;
off(type: 'jobStateChange', callback:(boolean) => void): void;
/**
* New printers have been found and notify Print SA.
*
* @since 9
* @param printers Indicates new arrived printer lists.
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function addPrinters(printers: Array<PrinterInfo>, callback: AsyncCallback<boolean>): void;
function addPrinters(printers: Array<PrinterInfo>): Promise<boolean>;
/**
* Printers have been lost and notify Print SA.
*
* @since 9
*
* @param printerId Indicates id of the printer
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function removePrinters(printers: Array<PrinterInfo>, callback: AsyncCallback<boolean>): void;
function removePrinters(printers: Array<PrinterInfo>): Promise<boolean>;
/**
* Notify Print SA the state of printer has been changed.
*
* @since 9
* @param state Indicates new printer state
* @param printerId Indicates id of the printer
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function updatePrinterState(state: PrinterState, printerId: number, callback: AsyncCallback<boolean>): void;
function updatePrinterState(state: PrinterState, printerId: number): Promise<boolean>;
/**
* Notify Print SA the state of print job has been changed.
*
* @since 9
* @param state Indicates new printer state
* @param jobId Indicates id of the print job
* @param callback The callback function for indcating the result of API execution
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function updatePrintJobState(state: PrintJobState, jobId: number, callback: AsyncCallback<boolean>): void;
function updatePrintJobState(state: PrintJobState, jobId: number): Promise<boolean>;
}
export default print;

View File

@ -1,137 +0,0 @@
/*
* 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.
*/
/**
* class of print extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @StageModelOnly
*/
declare class printExtension {
/**
* Called once to initialize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onCreated(want: object): void;
/**
* Called once to start to discover the printers connected with the device.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onStartDiscoverPrinter(): void;
/**
* Called once to stop discovering the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onStopDiscoverPrinter(): void;
/**
* Called once to connect to the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onConnectPrinter(printerId: number): void;
/**
* Called once to disconnect the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onDisconnectPrinter(printerId: number): void;
/**
* Called once to start print job.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onStartJob(jobInfo: PrintJob): void;
/**
* Called once to remove the print job has been started.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onCancelJob(jobInfo: PrintJob): void;
/**
* Called once to request the capability of the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onRequestCapability(printerId: number): PrinterCapability;
/**
* Called once to request preview and send result to Print SA.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onRequestPreview(jobInfo: PrintJob): Uri;
/**
* Called once to finalize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onDestroy(): void;
}
export default printExtension;

View File

@ -1,69 +0,0 @@
/*
* 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 Extension from '@ohos.PrintExtensionAbility'
import print from '@ohos.print'
let MODULE_TAG = "hwprintext"
export default class PrintExtAbility extends Extension {
Array<PrinterInfo> printerList
onCreated(want) {
console.info(MODULE_TAG + 'ability on created start');
}
onStartDiscoverPrinter() {
console.info(MODULE_TAG + "ability start to discover printer";
if (hasFoundDevice) {
print.addPrinters(printerList);
}
}
onStopDiscoverPrinter() {
console.info(MODULE_TAG + 'ability stop discovering printer');
}
onDestroy() {
console.info(MODULE_TAG + 'ability on destroy');
}
onConnectPrinter(printerId) {
console.info(MODULE_TAG + 'ability connect the speci1 printer');
}
onDisconnectPrinter(printerId) {
console.info(MODULE_TAG + 'ability disconnect the speci1 printer');
}
onStartPrintJob(jobInfo) {
console.info(MODULE_TAG + 'ability start Print Job');
}
onCancelPrintJob(jobInfo) {
console.info(MODULE_TAG + 'ability cancel Print Job');
}
onRequestPrinterCapability(printerId) {
console.info(MODULE_TAG + 'ability request printer capability');
var capability = GetDeviceCapability(printerId);
return capability;
}
onRequestPreview(jobInfo) {
console.info(MODULE_TAG + 'ability request printer preview');
FileDescriptor fd = print.OpenFile(jobInfo.preview.result);
SavePreviewToFile(fd);
return jobInfo.preview.result;
}
};

View File

@ -1,34 +0,0 @@
/*
* 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 printmanager from '@ohos.app.print';
// start print
export async function startPrint() {
Array<string> fileList = ['./data/printsample.pdf', './data/photo.jpg'];
await printmanager.print(fileList).then(async (task) => {
task.on('block', () => {
console.info('[block] event is called');
});
task.on('success', () => {
console.info('[success] event is called');
});
task.on('fail', () => {
console.info('[fail] event is called');
});
task.on('cancel', () => {
console.info('[cancel] event is called');
});
});
}

View File

@ -1,50 +0,0 @@
# 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("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_print_extension_abc") {
src_js = rebase_path("print_extension.js")
dst_file = rebase_path(target_out_dir + "/print_extension.abc")
in_puts = [ "print_extension.js" ]
out_puts = [ target_out_dir + "/print_extension.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("print_extension_js") {
input = "print_extension.js"
output = target_out_dir + "/print_extension.o"
}
gen_js_obj("print_extension_abc") {
input = get_label_info(":gen_print_extension_abc", "target_out_dir") +
"/print_extension.abc"
output = target_out_dir + "/print_extension_abc.o"
dep = ":gen_print_extension_abc"
}
ohos_shared_library("printextension_napi") {
sources = [ "print_extension_module.cpp" ]
deps = [
":print_extension_abc",
":print_extension_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -1,58 +0,0 @@
/*
* 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.
*/
class PrintExtension {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
onStartDiscoverPrinter() {
console.log('onStartDiscoverPrinter');
}
onStopDiscoverPrinter() {
console.log('onStopDiscoverPrinter');
}
onConnectPrinter(printerId) {
console.log('onConnectPrinter:' + printerId);
}
onDisconnectPrinter(printerId) {
console.log('onDisconnectPrinter');
}
onStartPrintJob(jobInfo) {
console.log('onStartPrintJob');
}
onCancelPrintJob(jobInfo) {
console.log('onCancelPrintJob');
}
onRequestPrinterCapability(printerId) {
console.log('onRequestPrinterCapability:' + printerId);
}
onRequestPreview(jobInfo) {
console.log('onRequestPreview');
}
onDestroy() {
console.log('onDestroy');
}
}
export default PrintExtension

View File

@ -1,54 +0,0 @@
/*
* 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 "native_engine/native_engine.h"
extern const char _binary_print_extension_js_start[];
extern const char _binary_print_extension_js_end[];
extern const char _binary_print_extension_abc_start[];
extern const char _binary_print_extension_abc_end[];
extern "C" __attribute__((constructor)) void NAPI_PrintExtension_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "PrintExtension",
.fileName = "libprintextension_napi.so/PrintExtension.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtension_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_print_extension_js_end - _binary_print_extension_js_start;
}
}
// print_extension JS register
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtension_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_print_extension_abc_end - _binary_print_extension_abc_start;
}
}

View File

@ -1,50 +0,0 @@
# 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("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_print_extension_context_abc") {
src_js = rebase_path("print_extension_context.js")
dst_file = rebase_path(target_out_dir + "/print_extension_context.abc")
in_puts = [ "print_extension_context.js" ]
out_puts = [ target_out_dir + "/print_extension_context.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("print_extension_context_js") {
input = "print_extension_context.js"
output = target_out_dir + "/print_extension_context.o"
}
gen_js_obj("print_extension_context_abc") {
input = get_label_info(":gen_print_extension_context_abc",
"target_out_dir") + "/print_extension_context.abc"
output = target_out_dir + "/print_extension_context_abc.o"
dep = ":gen_print_extension_context_abc"
}
ohos_shared_library("printextensioncontext_napi") {
sources = [ "print_extension_context_module.cpp" ]
deps = [
":print_extension_context_abc",
":print_extension_context_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -1,55 +0,0 @@
/*
* 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.
*/
var ExtensionContext = requireNapi("application.ExtensionContext")
class PrintExtensionContext extends ExtensionContext {
constructor(obj) {
super(obj);
this.extensionAbilityInfo = obj.extensionAbilityInfo
}
startAbility(want, options, callback) {
console.log("startAbility");
return this.__context_impl__.startAbility(want, options, callback);
}
connectAbility(want, options) {
console.log("connectAbility");
return this.__context_impl__.connectAbility(want, options);
}
startAbilityWithAccount(want, accountId, options, callback) {
console.log("startAbilityWithAccount");
return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback);
}
connectAbilityWithAccount(want, accountId, options) {
console.log("connectAbilityWithAccount");
return this.__context_impl__.connectAbilityWithAccount(want, accountId, options);
}
disconnectAbility(connection, callback) {
console.log("disconnectAbility");
return this.__context_impl__.disconnectAbility(connection, callback);
}
terminateSelf(callback) {
console.log("terminateSelf");
return this.__context_impl__.terminateSelf(callback);
}
}
export default PrintExtensionContext

View File

@ -1,56 +0,0 @@
/*
* 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 "native_engine/native_engine.h"
extern const char _binary_print_extension_context_js_start[];
extern const char _binary_print_extension_context_js_end[];
extern const char _binary_print_extension_context_abc_start[];
extern const char _binary_print_extension_context_abc_end[];
extern "C" __attribute__((constructor)) void NAPI_PrintExtensionContext_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "PrintExtensionContext",
.fileName = "libprintextensioncontext_napi.so/PrintExtensionContext.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtensionContext_GetJSCode(
const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_context_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_print_extension_context_js_end - _binary_print_extension_context_js_start;
}
}
// print_extension_context JS register
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtensionContext_GetABCCode(
const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_context_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_print_extension_context_abc_end - _binary_print_extension_context_abc_start;
}
}

View File

@ -1,76 +0,0 @@
# 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("//base/request/request/request_aafwk.gni")
import("//build/ohos.gni")
config("print_interfaces_kits_napi_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags_cc = [ "-fexceptions" ]
}
ohos_shared_library("print_napi") {
include_dirs = [
"//foundation/arkui/ace_engine/frameworks/base/utils",
"//foundation/arkui/napi",
"//foundation/arkui/napi/interfaces/kits",
"//foundation/arkui/napi/interfaces/inner_api",
"//third_party/node/src",
"//third_party/curl/include",
"${ability_runtime_services_path}/common/include",
"//utils/system/safwk/native/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/app/",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_services_path}/abilitymgr/include",
"${ability_runtime_inner_api_path}/ability_manager/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/Isamgr",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//base/print/print/utils/include",
"//base/print/print/frameworks/innerkitsimpl/include",
]
public_configs = [ ":print_interfaces_kits_napi_config" ]
sources = [
"src/print_module.cpp",
"src/napi_print_task.cpp",
"src/napi_inner_print.cpp",
"src/napi_print_ext.cpp",
"src/async_call.cpp",
"src/print_task.cpp",
"src/print_parse_type.cpp",
]
deps = [
"//foundation/arkui/napi:ace_napi",
"//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//base/print/print/frameworks/innerkitsimpl:print_client",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"ability_runtime:data_ability_helper",
"ability_runtime:napi_base_context",
"c_utils:utils",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"preferences:native_preferences",
"relational_store:native_appdatafwk",
"relational_store:native_dataability",
"relational_store:native_rdb",
]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -1,102 +0,0 @@
/*
* 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 PRINT_ASYNC_CALL_H
#define PRINT_ASYNC_CALL_H
#include <functional>
#include <memory>
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
namespace OHOS::Print {
class AsyncCall final {
public:
class Context {
public:
using InputAction = std::function<napi_status(napi_env, size_t, napi_value *, napi_value)>;
using OutputAction = std::function<napi_status(napi_env, napi_value *)>;
using ExecAction = std::function<void(Context *)>;
Context(InputAction input, OutputAction output) : input_(std::move(input)), output_(std::move(output)) {};
virtual ~Context() {};
void SetAction(InputAction input, OutputAction output = nullptr)
{
input_ = input;
output_ = output;
}
void SetAction(OutputAction output)
{
SetAction(nullptr, std::move(output));
}
virtual napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self)
{
if (input_ == nullptr) {
return napi_ok;
}
return input_(env, argc, argv, self);
}
virtual napi_status operator()(napi_env env, napi_value *result)
{
if (output_ == nullptr) {
*result = nullptr;
return napi_ok;
}
return output_(env, result);
}
virtual void Exec()
{
if (exec_ == nullptr) {
return;
}
exec_(this);
};
protected:
friend class AsyncCall;
InputAction input_ = nullptr;
OutputAction output_ = nullptr;
ExecAction exec_ = nullptr;
};
// The default AsyncCallback in the parameters is at the end position.
static constexpr size_t ASYNC_DEFAULT_POS = -1;
AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr<Context> context, size_t pos = ASYNC_DEFAULT_POS);
~AsyncCall();
napi_value Call(napi_env env, Context::ExecAction exec = nullptr);
napi_value SyncCall(napi_env env, Context::ExecAction exec = nullptr);
private:
enum { ARG_ERROR, ARG_DATA, ARG_BUTT };
static void OnExecute(napi_env env, void *data);
static void OnComplete(napi_env env, napi_status status, void *data);
struct AsyncContext {
std::shared_ptr<Context> ctx = nullptr;
napi_ref callback = nullptr;
napi_ref self = nullptr;
napi_deferred defer = nullptr;
napi_async_work work = nullptr;
};
static void DeleteContext(napi_env env, AsyncContext *context);
AsyncContext *context_ = nullptr;
napi_env env_ = nullptr;
};
} // namespace OHOS::Print
#endif // REQUEST_ASYNC_CALL_H

View File

@ -1,101 +0,0 @@
/*
* 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 PRINT_BASE_CONTEXT_H
#define PRINT_BASE_CONTEXT_H
#include <list>
#include "event_manager.h"
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "noncopyable.h"
namespace OHOS::Request::Print {
typedef void (*AsyncWorkExecutor)(napi_env env, void *data);
typedef void (*AsyncWorkCallback)(napi_env env, napi_status status, void *data);
class BaseContext {
public:
ACE_DISALLOW_COPY_AND_MOVE(BaseContext);
BaseContext() = delete;
explicit BaseContext(napi_env env, napi_callback_info info, EventManager *manager);
virtual ~BaseContext();
virtual void ParseParams(napi_value *params, size_t paramsCount);
void SetParseOK(bool parseOK);
void SetExecOK(bool execOK);
void SetErrorCode(int32_t errorCode);
napi_status SetCallback(napi_value callback);
void DeleteCallback();
void CreateAsyncWork(const std::string &name, AsyncWorkExecutor executor, AsyncWorkCallback callback);
void DeleteAsyncWork();
napi_value CreatePromise();
[[nodiscard]] bool IsParseOK() const;
[[nodiscard]] bool IsExecOK() const;
[[nodiscard]] napi_env GetEnv() const;
[[nodiscard]] napi_callback_info GetInfo() const;
[[nodiscard]] int32_t GetErrorCode() const;
[[nodiscard]] napi_value GetCallback() const;
[[nodiscard]] napi_deferred GetDeferred() const;
[[nodiscard]] const std::string &GetAsyncWorkName() const;
void Emit(const std::string &type, const std::pair<napi_value, napi_value> &argv);
protected:
EventManager *manager_;
private:
napi_env env_;
napi_callback_info info_;
bool parseOK_;
bool execOK_;
int32_t errorCode_;
napi_ref callback_;
napi_async_work asyncWork_;
napi_deferred deferred_;
std::string asyncWorkName_;
};
} // namespace OHOS::Request::Print
#endif /* PRINT_BASE_CONTEXT_H */

View File

@ -1,94 +0,0 @@
/*
* 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 NAPI_INNER_PRINT_H
#define NAPI_INNER_PRINT_H
#include <string>
#include <vector>
#include "async_call.h"
#include "iprint_callback.h"
#include "napi/native_api.h"
#include "napi_print_ext.h"
#include "noncopyable.h"
#include "print_extension_info.h"
#include "print_job.h"
#include "print_page_size.h"
#include "print_resolution.h"
#include "print_task.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
enum EventType {
NO_ARG_EVENT,
ONE_ARG_EVENT,
TWO_ARG_EVENT,
};
class NapiInnerPrint {
public:
explicit NapiInnerPrint(uint32_t taskId);
~NapiInnerPrint();
static napi_value QueryExtensionInfo(napi_env env, napi_callback_info info);
static napi_value StartDiscovery(napi_env env, napi_callback_info info);
static napi_value StopDiscovery(napi_env env, napi_callback_info info);
static napi_value ConnectPrint(napi_env env, napi_callback_info info);
static napi_value DisconnectPrint(napi_env env, napi_callback_info info);
static napi_value StartPrintJob(napi_env env, napi_callback_info info);
static napi_value CancelPrintJob(napi_env env, napi_callback_info info);
static napi_value RequestPreview(napi_env env, napi_callback_info info);
static napi_value QueryCapability(napi_env env, napi_callback_info info);
static napi_value On(napi_env env, napi_callback_info info);
static napi_value Off(napi_env env, napi_callback_info info);
static int32_t GetEventType(const std::string &type);
private:
static sptr<IPrintCallback> CreateNotify(napi_env env, const std::string &type, napi_ref callbackRef);
struct OperationContext : public AsyncCall::Context {
int32_t dummy = 0;
std::vector<PrintExtensionInfo> arrExtInfo;
std::vector<uint32_t> extensionList;
uint32_t state;
PrinterInfo info;
std::string previewResult = "";
std::string type = "";
PrintJob jobinfo;
PrintTask *task_ = nullptr;
std::string title_ = "";
std::string description_ = "";
std::string filePath_ = "";
uint32_t speedLimit_ = 0;
uint32_t priority_ = 0;
PrinterCapability printerCapability;
bool result = false;
std::string stateType_ = "";
PrintJob printStartJob;
PrintJob printCancelJob;
PrintJob printReqPreviewJob;
uint32_t printCapacityId = 0;
uint32_t printConnId = 0;
uint32_t printDisConnId = 0;
std::vector<uint32_t> extensionVector;
napi_status status = napi_generic_failure;
OperationContext() : Context(nullptr, nullptr) {};
OperationContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~OperationContext() {};
};
};
} // namespace OHOS::Print
#endif // NAPI_INNER_PRINT_H

View File

@ -1,55 +0,0 @@
/*
* 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 NAPI_PRINT_EXT_H
#define NAPI_PRINT_EXT_H
#include "async_call.h"
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_margin.h"
#include "print_page_size.h"
#include "print_resolution.h"
#include "print_task.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
class NapiPrintExt {
public:
static napi_value AddPrinters(napi_env env, napi_callback_info info);
static napi_value RemovePrinters(napi_env env, napi_callback_info info);
static napi_value UpdatePrinterState(napi_env env, napi_callback_info info);
static napi_value UpdatePrintJobState(napi_env env, napi_callback_info info);
private:
struct NapiPrintExtContext : public AsyncCall::Context {
PrintTask *task_ = nullptr;
PrinterInfo info_;
bool result = false;
uint32_t printerId = 0;
uint32_t printerJobId = 0;
uint32_t printerState = 0;
uint32_t printerJobState = 0;
napi_status status = napi_generic_failure;
std::vector<PrinterInfo> printAddInfoVector;
std::vector<PrinterInfo> printRemoveInfoVector;
NapiPrintExtContext() : Context(nullptr, nullptr) {};
NapiPrintExtContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~NapiPrintExtContext() {};
};
};
} // namespace OHOS::Print
#endif // NAPI_PRINT_EXT_H

View File

@ -1,34 +0,0 @@
/*
* 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 NAPI_PRINT_TASK_H
#define NAPI_PRINT_TASK_H
#include "async_call.h"
namespace OHOS::Print {
class NapiPrintTask {
public:
static napi_value Print(napi_env env, napi_callback_info info);
private:
static napi_value GetCtor(napi_env env);
static napi_value Initialize(napi_env env, napi_callback_info info);
private:
static __thread napi_ref globalCtor;
};
} // namespace OHOS::Print
#endif // NAPI_PRINT_TASK_H

View File

@ -1,63 +0,0 @@
/*
* 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 PARSE_TYPE_H
#define PARSE_TYPE_H
#include <string>
#include <vector>
#include "async_call.h"
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_job.h"
#include "print_page_size.h"
#include "print_resolution.h"
#include "print_task.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
class PrintParseType {
public:
static bool ParseInfo(napi_env env, napi_value InfoValue, PrinterInfo &Info);
static bool ParseCapability(napi_env env, napi_value InfoValue, PrinterCapability &capability);
static bool ParsePageSize(napi_env env, napi_value capValue, PrintPageSize &PrintPageSize);
static bool ParseResolution(napi_env env, napi_value reValue, PrintResolution &PrintResolution);
static bool ParseMargin(napi_env env, napi_value marginValue, PrintMargin &PrintMargin);
static bool ParseJob(napi_env env, napi_value jobValue, PrintJob &printJob);
static bool ParsePreviewAttribute(napi_env env, napi_value preAttValue, PreviewAttribute &preAtt);
static bool ParseRange(napi_env env, napi_value preAttValue, PrintRange &range);
static bool ParseInfoParam(napi_env env, napi_value InfoValue, PrinterInfo &info);
static bool ParseCapParam(napi_env env, napi_value InfoValue, PrinterCapability &capability);
static void CoversePriotResolutionObject(napi_env env, napi_value capValue, PrinterCapability &capability);
static bool ParseArrPrintResolution(
napi_env env, napi_value capValue, PrinterCapability &capability) static bool ParsePageSizeParam(napi_env env,
napi_value capValue, PrintPageSize &PrintPageSize);
static bool ParseResolutionParam(napi_env env, napi_value reValue, PrintResolution &PrintResolution);
static bool ParseMarginParam(napi_env env, napi_value marginValue, PrintMargin &PrintMargin);
static bool ParseJobParam(napi_env env, napi_value jobValue, PrintJob &printJob);
static bool ParseArrFiles(napi_env env, napi_value jobValue, PrintJob &printJob);
static bool ParseHasNum(napi_env env, napi_value jobValue, PrintJob &printJob);
static bool ParseHasObj(napi_env env, napi_value jobValue, PrintJob &printJob);
static bool ParsePreviewAttributeParam(napi_env env, napi_value preAttValue, PreviewAttribute &preAtt);
static bool ParseRangeParam(napi_env env, napi_value preAttValue, PrintRange &range);
private:
struct PrintParseTypeContext : public AsyncCall::Context {};
};
} // namespace OHOS::Print
#endif // PARSE_TYPE_H

View File

@ -1,68 +0,0 @@
/*
* 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 PRINT_TASK_H
#define PRINT_TASK_H
#include <map>
#include <mutex>
#include <string>
#include "napi/native_api.h"
static constexpr const char *EVENT_BLOCK = "blocked";
static constexpr const char *EVENT_SUCCESS = "success";
static constexpr const char *EVENT_FAIL = "failed";
static constexpr const char *EVENT_CANCEL = "cancelled";
static constexpr const char *PRINTER_STATE_ADD = "PRINTER_ADDED";
static constexpr const char *PRINTER_STATE_REMOVED = "PRINTER_REMOVED";
static constexpr const char *PRINTER_STATE_IDLE = "PRINTER_IDLE";
static constexpr const char *PRINTER_STATE_PRINTING = "PRINTER_PRINTING";
static constexpr const char *PRINTER_STATE_BLOCKED = "PRINTER_BLOCKED";
static constexpr const char *PRINTER_STATE_BUSY = "PRINTER_BUSY";
static constexpr const char *PRINTER_STATE_FAILED = "PRINTER_FAILED";
static constexpr const char *PRINTJOB_STATE_CREATED = "PRINT_JOB_CREATED";
static constexpr const char *PRINTJOB_STATE_QUEUED = "PRINT_JOB_QUEUED";
static constexpr const char *PRINTJOB_STATE_PRINTING = "PRINT_JOB_PRINTING";
static constexpr const char *PRINTJOB_STATE_BLOCKED = "PRINT_JOB_BLOCKED";
static constexpr const char *PRINTJOB_STATE_SUCCESS = "PRINT_JOB_SUCCESS";
static constexpr const char *PRINTJOB_STATE_FAILED = "PRINT_JOB_FAILED";
static constexpr const char *PRINTJOB_STATE_cancelled = "PRINT_JOB_cancelled";
namespace OHOS::Print {
class PrintTask {
public:
explicit PrintTask(uint32_t taskId);
~PrintTask();
uint32_t GetId() const;
static napi_value On(napi_env env, napi_callback_info info);
static napi_value Off(napi_env env, napi_callback_info info);
bool IsSupportType(const std::string &type);
bool IsSupportPrinterStateType(const std::string &type);
bool IsSupportJobStateType(const std::string &type);
private:
int taskId_;
std::mutex mutex_;
std::map<std::string, bool> supportEvents_;
std::map<std::string, bool> supportPrinterState_;
std::map<std::string, bool> supportJobState_;
};
} // namespace OHOS::Print
#endif // PRINT_TASK_H

View File

@ -1,147 +0,0 @@
/*
* 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 "async_call.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
AsyncCall::AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr<Context> context, size_t pos) : env_(env)
{
context_ = new AsyncContext();
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value self = nullptr;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
pos = ((pos == ASYNC_DEFAULT_POS) ? (argc - 1) : pos);
if (pos >= 0 && pos < argc) {
napi_valuetype valueType = napi_undefined;
napi_typeof(env, argv[pos], &valueType);
if (valueType == napi_function) {
napi_create_reference(env, argv[pos], 1, &context_->callback);
argc = pos;
}
}
NAPI_CALL_RETURN_VOID(env, (*context)(env, argc, argv, self));
context_->ctx = std::move(context);
napi_create_reference(env, self, 1, &context_->self);
}
AsyncCall::~AsyncCall()
{
if (context_ == nullptr) {
return;
}
DeleteContext(env_, context_);
}
napi_value AsyncCall::Call(napi_env env, Context::ExecAction exec)
{
if ((context_ == nullptr) || (context_->ctx == nullptr)) {
PRINT_HILOGD("context_ or context_->ctx is null");
return nullptr;
}
PRINT_HILOGD("async call exec");
context_->ctx->exec_ = std::move(exec);
napi_value promise = nullptr;
if (context_->callback == nullptr) {
napi_create_promise(env, &context_->defer, &promise);
} else {
napi_get_undefined(env, &promise);
}
napi_async_work work = context_->work;
napi_value resource = nullptr;
napi_create_string_utf8(env, "AsyncCall", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env, nullptr, resource, AsyncCall::OnExecute, AsyncCall::OnComplete, context_, &work);
context_->work = work;
context_ = nullptr;
napi_queue_async_work(env, work);
PRINT_HILOGD("async call exec");
return promise;
}
napi_value AsyncCall::SyncCall(napi_env env, AsyncCall::Context::ExecAction exec)
{
if ((context_ == nullptr) || (context_->ctx == nullptr)) {
PRINT_HILOGD("context_ or context_->ctx is null");
return nullptr;
}
context_->ctx->exec_ = std::move(exec);
napi_value promise = nullptr;
if (context_->callback == nullptr) {
napi_create_promise(env, &context_->defer, &promise);
} else {
napi_get_undefined(env, &promise);
}
AsyncCall::OnExecute(env, context_);
AsyncCall::OnComplete(env, napi_ok, context_);
return promise;
}
void AsyncCall::OnExecute(napi_env env, void *data)
{
PRINT_HILOGD("run the async runnable");
AsyncContext *context = reinterpret_cast<AsyncContext *>(data);
context->ctx->Exec();
}
void AsyncCall::OnComplete(napi_env env, napi_status status, void *data)
{
PRINT_HILOGD("run the js callback function");
AsyncContext *context = reinterpret_cast<AsyncContext *>(data);
napi_value output = nullptr;
napi_status runStatus = (*context->ctx)(env, &output);
napi_value result[ARG_BUTT] = { 0 };
if (status == napi_ok && runStatus == napi_ok) {
napi_get_undefined(env, &result[ARG_ERROR]);
if (output != nullptr) {
result[ARG_DATA] = output;
} else {
napi_get_undefined(env, &result[ARG_DATA]);
}
} else {
napi_value message = nullptr;
napi_create_string_utf8(env, "async call failed", NAPI_AUTO_LENGTH, &message);
napi_create_error(env, nullptr, message, &result[ARG_ERROR]);
napi_get_undefined(env, &result[ARG_DATA]);
}
if (context->defer != nullptr) {
// promise
if (status == napi_ok && runStatus == napi_ok) {
napi_resolve_deferred(env, context->defer, result[ARG_DATA]);
} else {
napi_reject_deferred(env, context->defer, result[ARG_ERROR]);
}
} else {
// callback
napi_value callback = nullptr;
napi_get_reference_value(env, context->callback, &callback);
napi_value returnValue;
napi_call_function(env, nullptr, callback, ARG_BUTT, result, &returnValue);
}
DeleteContext(env, context);
}
void AsyncCall::DeleteContext(napi_env env, AsyncContext *context)
{
if (env != nullptr) {
napi_delete_reference(env, context->callback);
napi_delete_reference(env, context->self);
napi_delete_async_work(env, context->work);
}
delete context;
}
} // namespace OHOS::Print

View File

@ -1,526 +0,0 @@
/*
* 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 "napi_inner_print.h"
#include "async_call.h"
#include "napi_print_utils.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "print_parse_type.h"
#include "print_task.h"
namespace OHOS::Print {
napi_value NapiInnerPrint::QueryExtensionInfo(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ZERO, " should 0 parameter!", napi_invalid_arg);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
PRINT_HILOGD("ouput enter---->");
napi_status status = napi_create_array(env, result);
uint32_t extInfoLength = context->arrExtInfo.size();
for (uint32_t i = 0; i < extInfoLength; i++) {
PRINT_HILOGD("ExtInfo, ExtensionId = %{public}d", context->arrExtInfo[i].GetExtensionId());
PRINT_HILOGD("ExtInfo, VendorId = %{public}d", context->arrExtInfo[i].GetVendorId());
PRINT_HILOGD("ExtInfo, VendorName = %{public}s", context->arrExtInfo[i].GetVendorName().c_str());
PRINT_HILOGD("ExtInfo, VendorIcon = %{public}d", context->arrExtInfo[i].GetVendorIcon());
PRINT_HILOGD("ExtInfo, Version = %{public}s", context->arrExtInfo[i].GetVersion().c_str());
napi_value PrinterInfo;
napi_create_object(env, &PrinterInfo);
NapiPrintUtils::SetUint32Property(env, PrinterInfo, "extensionId", context->arrExtInfo[i].GetExtensionId());
NapiPrintUtils::SetUint32Property(env, PrinterInfo, "vendorId", context->arrExtInfo[i].GetVendorId());
NapiPrintUtils::SetStringPropertyUtf8(
env, PrinterInfo, "vendorName", context->arrExtInfo[i].GetVendorName().c_str());
NapiPrintUtils::SetUint32Property(env, PrinterInfo, "vendorIcon", context->arrExtInfo[i].GetVendorIcon());
NapiPrintUtils::SetStringPropertyUtf8(
env, PrinterInfo, "version", context->arrExtInfo[i].GetVersion().c_str());
status = napi_set_element(env, *result, i, PrinterInfo);
}
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
PRINT_HILOGD("exec enter---->");
context->result = PrintManagerClient::GetInstance()->QueryAllExtension(context->arrExtInfo);
if (context->result == true) {
PRINT_HILOGD("exec over---->");
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::StartDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter StartDiscovery---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, " should 1 parameter!", napi_invalid_arg);
uint32_t result_size = 0;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &result_size);
napi_value array = argv[NapiPrintUtils::INDEX_ZERO];
bool isArray = false;
napi_is_array(env, array, &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_invalid_arg);
for (uint32_t i = 0; i < result_size; i++) {
napi_value value;
napi_get_element(env, array, i, &value);
uint32_t valueNumber;
napi_get_value_uint32(env, value, &valueNumber);
PRINT_HILOGD("output for :---- extensionVector value is :[%{public}d]", valueNumber);
context->extensionVector.push_back((int32_t)valueNumber);
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->StartDiscoverPrinter(context->extensionVector);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::StopDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter StopDiscovery---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 0, " should 0 parameter!", napi_invalid_arg);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->StopDiscoverPrinter();
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::ConnectPrint(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ConnectPrint---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, "should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "printerId number is not a number", napi_invalid_arg);
uint32_t printId;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ZERO], &printId);
PRINT_HILOGD("printId : %{public}d", printId);
context->printConnId = printId;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->ConnectPrinter(context->printConnId);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::DisconnectPrint(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter DisconnectPrint---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "printerId number is not a number", napi_invalid_arg);
uint32_t printId;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ZERO], &printId);
PRINT_HILOGD("printId : %{public}d", printId);
context->printDisConnId = printId;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->DisconnectPrinter(context->printDisConnId);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::StartPrintJob(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter StartPrintJob---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, " should 1 parameter!", napi_invalid_arg);
napi_value value = argv[NapiPrintUtils::INDEX_ZERO];
PrintJob printJob;
if (!PrintParseType::ParseJob(env, value, printJob)) {
PRINT_HILOGD("ParseJob type error!");
}
context->printStartJob = printJob;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
PRINT_HILOGD("exec----");
context->printStartJob.Dump();
context->result = PrintManagerClient::GetInstance()->StartPrintJob(context->printStartJob);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::CancelPrintJob(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter CancelPrintJob---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, " should 1 parameter!", napi_invalid_arg);
napi_value value = argv[NapiPrintUtils::INDEX_ZERO];
PrintJob printJob;
if (!PrintParseType::ParseJob(env, value, printJob)) {
PRINT_HILOGD("ParseJob type error!");
}
context->printCancelJob = printJob;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
PRINT_HILOGD("exec----");
context->printCancelJob.Dump();
context->result = PrintManagerClient::GetInstance()->CancelPrintJob(context->printCancelJob);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context), 0);
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::RequestPreview(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, " should 1 parameter!", napi_invalid_arg);
napi_value value = argv[NapiPrintUtils::INDEX_ZERO];
PrintJob printJob;
if (!PrintParseType::ParseJob(env, value, printJob)) {
PRINT_HILOGD("ParseJob type error!");
}
context->printReqPreviewJob = printJob;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_create_string_utf8(env, context->previewResult.c_str(), NAPI_AUTO_LENGTH, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
PRINT_HILOGD("exec----");
context->printReqPreviewJob.Dump();
context->result =
PrintManagerClient::GetInstance()->RequestPreview(context->printReqPreviewJob, context->previewResult);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::QueryCapability(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter QueryCapability---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "number is not a number", napi_invalid_arg);
uint32_t number;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ZERO], &number);
PRINT_HILOGD("printjob : %{public}d", number);
context->printCapacityId = number;
PRINT_HILOGD("input over---->");
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
context->printerCapability.ConvertToJs(env, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->QueryPrinterCapability(
context->printCapacityId, context->printerCapability); //
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::On(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
napi_value result = nullptr;
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
napi_value thisVal = nullptr;
void *data = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVal, &data));
if (argc != NapiPrintUtils::ARGC_ONE) {
PRINT_HILOGE("Wrong number of arguments, requires 1");
return result;
}
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "type is not a string");
char event[NapiPrintUtils::MAX_LEN] = { 0 };
size_t len = 0;
napi_get_value_string_utf8(env, argv[NapiPrintUtils::INDEX_ZERO], event, NapiPrintUtils::MAX_LEN, &len);
std::string type = event;
PRINT_HILOGD("type : %{public}s", type.c_str());
PrintTask *task;
PRINT_HILOGD("napi_unwrap begin.");
NAPI_CALL(env, napi_unwrap(env, thisVal, reinterpret_cast<void **>(&task)));
PRINT_HILOGD("state judge begin.");
if (task->IsSupportPrinterStateType(type)) {
PRINT_HILOGD("State type is Printer State. value is : %{public}s", type.c_str());
} else if (task->IsSupportJobStateType(type)) {
PRINT_HILOGD("State type is Print Job State. value is : %{public}s", type.c_str());
} else {
PRINT_HILOGD("state error!");
return result;
}
PRINT_HILOGD("state judge end.");
napi_ref callbackRef = nullptr;
napi_create_reference(env, argv[argc - 1], 1, &callbackRef);
return nullptr;
}
napi_value NapiInnerPrint::Off(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter Off---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<OperationContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "valuetype is not a number", napi_invalid_arg);
char buf[NapiPrintUtils::MAX_LEN] = {};
size_t len = 0;
napi_get_value_string_utf8(env, argv[NapiPrintUtils::INDEX_ZERO], buf, NapiPrintUtils::MAX_LEN, &len);
PRINT_HILOGD("printerId :");
context->type = buf;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->Off(context->type);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
int32_t NapiInnerPrint::GetEventType(const std::string &type)
{
if (type == EVENT_SUCCESS) {
return TWO_ARG_EVENT;
} else if (type == EVENT_FAIL) {
return ONE_ARG_EVENT;
}
return NO_ARG_EVENT;
}
sptr<IPrintCallback> NapiInnerPrint::CreateNotify(napi_env env, const std::string &type, napi_ref callbackRef)
{
sptr<IPrintCallback> listener = nullptr;
int32_t eventType = GetEventType(type);
switch (eventType) {
case NO_ARG_EVENT:
break;
case ONE_ARG_EVENT:
break;
case TWO_ARG_EVENT:
break;
default:
PRINT_HILOGE("not support event type");
break;
}
return listener;
}
} // namespace OHOS::Print

View File

@ -1,218 +0,0 @@
/*
* 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 "napi_print_ext.h"
#include "async_call.h"
#include "napi_print_utils.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "print_parse_type.h"
namespace OHOS::Print {
napi_value NapiPrintExt::AddPrinters(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_value array = argv[NapiPrintUtils::INDEX_ZERO];
bool isArray = false;
napi_is_array(env, array, &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_invalid_arg);
uint32_t result_size;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &result_size);
PrinterInfo info_;
for (uint32_t i = 0; i < result_size; i++) {
napi_value value;
napi_get_element(env, array, i, &value);
if (!PrintParseType::ParseInfo(env, value, info_)) {
PRINT_HILOGD("PrinterInfo is format error!");
}
context->printAddInfoVector.push_back(info_);
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->AddPrinters(context->printAddInfoVector);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::RemovePrinters(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_value array = argv[NapiPrintUtils::INDEX_ZERO];
bool isArray = false;
napi_is_array(env, array, &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_invalid_arg);
uint32_t result_size;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &result_size);
PrinterInfo info_;
for (uint32_t i = 0; i < result_size; i++) {
napi_value value;
napi_get_element(env, array, i, &value);
if (!PrintParseType::ParseInfo(env, value, info_)) {
PRINT_HILOGD("PrinterInfo is format error!");
}
context->printRemoveInfoVector.push_back(info_);
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result = PrintManagerClient::GetInstance()->RemovePrinters(context->printRemoveInfoVector);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::UpdatePrinterState(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_TWO, " should 2 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "valuetype is not a number", napi_invalid_arg);
uint32_t printerId = 0;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ZERO], &printerId);
PRINT_HILOGD("printerId : %{public}d", printerId);
context->printerId = printerId;
napi_valuetype valueSecondtype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valueSecondtype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valueSecondtype == napi_number, "valueSecondtype is not a string", napi_invalid_arg);
uint32_t printerState = 0;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ONE], &printerState);
PRINT_HILOGD("printerState : %{public}d", printerState);
context->printerState = printerState;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result =
PrintManagerClient::GetInstance()->UpdatePrinterState(context->printerId, context->printerState);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::UpdatePrintJobState(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
if (!PrintManagerClient::GetInstance()->CheckPermission()) {
PRINT_HILOGW("no permission to access print service");
return nullptr;
}
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_TWO, " should 2 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "printerJobState is not a number", napi_invalid_arg);
uint32_t printerJobId = 0;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ZERO], &printerJobId);
PRINT_HILOGD("printerJobId : %{public}d", printerJobId);
context->printerJobId = printerJobId;
napi_valuetype valueSecondtype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valueSecondtype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valueSecondtype == napi_number, "valueSecondtype is not a string", napi_invalid_arg);
uint32_t printerJobState = 0;
napi_get_value_uint32(env, argv[NapiPrintUtils::INDEX_ONE], &printerJobState);
PRINT_HILOGD("printerJobState : %{public}d", printerJobState);
context->printerJobState = printerJobState;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](AsyncCall::Context *ctx) {
context->result =
PrintManagerClient::GetInstance()->UpdatePrinterJobState(context->printerJobId, context->printerJobState);
if (context->result == true) {
context->status = napi_ok;
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
} // namespace OHOS::Print

View File

@ -1,109 +0,0 @@
/*
* 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 "napi_print_task.h"
#include <mutex>
#include "async_call.h"
#include "napi_print_utils.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "print_task.h"
static constexpr const char *FUNCTION_ON = "on";
static constexpr const char *FUNCTION_OFF = "off";
namespace OHOS::Print {
__thread napi_ref NapiPrintTask::globalCtor = nullptr;
std::mutex mutex_;
napi_value NapiPrintTask::Print(napi_env env, napi_callback_info info) // PrintTask
{
PRINT_HILOGD("Enter print JsMain.");
if (!PrintManagerClient::GetInstance()->LoadServer()) {
PRINT_HILOGE("load print server fail");
return nullptr;
}
struct ContextInfo {
napi_ref ref = nullptr;
};
auto ctxInfo = std::make_shared<ContextInfo>();
auto input = [ctxInfo](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
PRINT_HILOGD("print parser to native params %{public}d!", static_cast<int>(argc));
NAPI_ASSERT_BASE(env, (argc > 0) && (argc <= 3), " need 2 or 3 parameters!", napi_invalid_arg);
napi_value proxy = nullptr;
napi_status status = napi_new_instance(env, GetCtor(env), argc, argv, &proxy);
if ((proxy == nullptr) || (status != napi_ok)) {
PRINT_HILOGE("Failed to create print task");
return napi_generic_failure;
}
napi_create_reference(env, proxy, 1, &(ctxInfo->ref));
return napi_ok;
};
auto output = [ctxInfo](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_reference_value(env, ctxInfo->ref, result);
napi_delete_reference(env, ctxInfo->ref);
return status;
};
auto context = std::make_shared<AsyncCall::Context>(input, output);
AsyncCall asyncCall(env, info, context);
return asyncCall.Call(env);
}
napi_value NapiPrintTask::GetCtor(napi_env env)
{
std::lock_guard<std::mutex> lock(mutex_);
napi_value cons;
if (globalCtor != nullptr) {
NAPI_CALL(env, napi_get_reference_value(env, globalCtor, &cons));
return cons;
}
napi_property_descriptor clzDes[] = {
{ FUNCTION_ON, 0, PrintTask::On, 0, 0, 0, napi_default, 0 },
{ FUNCTION_OFF, 0, PrintTask::Off, 0, 0, 0, napi_default, 0 },
};
NAPI_CALL(env, napi_define_class(env, "NapiPrintTask", NAPI_AUTO_LENGTH, Initialize, nullptr,
sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons));
NAPI_CALL(env, napi_create_reference(env, cons, 1, &globalCtor));
return cons;
}
napi_value NapiPrintTask::Initialize(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("constructor print task!");
napi_value self = nullptr;
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
auto task = new PrintTask(PrintManagerClient::GetInstance()->StartPrint());
if (task == nullptr) {
PRINT_HILOGE("print task fail");
return nullptr;
}
auto finalize = [](napi_env env, void *data, void *hint) {
PRINT_HILOGD("destructed print task");
PrintTask *task = reinterpret_cast<PrintTask *>(data);
delete task;
};
if (napi_wrap(env, self, task, finalize, nullptr, nullptr) != napi_ok) {
finalize(env, task, nullptr);
return nullptr;
}
PRINT_HILOGD("Succeed to allocate print task");
return self;
}
} // namespace OHOS::Print

View File

@ -1,83 +0,0 @@
/*
* 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 "napi_inner_print.h"
#include "napi_print_ext.h"
#include "napi_print_task.h"
#include "print_constant.h"
#include "print_log.h"
using namespace OHOS::Print;
static constexpr const char *FUNCTION_PRINT = "print";
static constexpr const char *FUNCTION_QUERY_EXT = "queryExtensionAbilityInfos";
static constexpr const char *FUNCTION_START_DISCOVERY = "startDiscoverPrinter";
static constexpr const char *FUNCTION_STOP_DISCOVERY = "stopDiscoverPrinter";
static constexpr const char *FUNCTION_CONNECT_PRINT = "connectPrinter";
static constexpr const char *FUNCTION_DISCONNECT_PRINT = "disconnectPrinter";
static constexpr const char *FUNCTION_START_PRINT = "startPrintJob";
static constexpr const char *FUNCTION_CANCEL_PRINT = "cancelPrintJob";
static constexpr const char *FUNCTION_REQUEST_PREVIEW = "requestPrintPreview";
static constexpr const char *FUNCTION_QUERY_CAPABILITY = "queryPrinterCapability";
static constexpr const char *FUNCTION_REGISTER_EVENT = "on";
static constexpr const char *FUNCTION_UNREGISTER_EVENT = "off";
static constexpr const char *FUNCTION_ADD_PRINTER = "addPrinters";
static constexpr const char *FUNCTION_REMOVE_PRINTER = "removePrinters";
static constexpr const char *FUNCTION_UPDATE_PRINTER_STATE = "updatePrinterState";
static constexpr const char *FUNCTION_UPDATE_JOB_STATE = "updatePrintJobState";
#define DECLARE_NAPI_METHOD(name, func) \
{ \
name, 0, func, 0, 0, 0, napi_default, 0 \
}
static napi_value Init(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_METHOD(FUNCTION_PRINT, NapiPrintTask::Print),
DECLARE_NAPI_METHOD(FUNCTION_QUERY_EXT, NapiInnerPrint::QueryExtensionInfo),
DECLARE_NAPI_METHOD(FUNCTION_START_DISCOVERY, NapiInnerPrint::StartDiscovery),
DECLARE_NAPI_METHOD(FUNCTION_STOP_DISCOVERY, NapiInnerPrint::StopDiscovery),
DECLARE_NAPI_METHOD(FUNCTION_CONNECT_PRINT, NapiInnerPrint::ConnectPrint),
DECLARE_NAPI_METHOD(FUNCTION_DISCONNECT_PRINT, NapiInnerPrint::DisconnectPrint),
DECLARE_NAPI_METHOD(FUNCTION_START_PRINT, NapiInnerPrint::StartPrintJob),
DECLARE_NAPI_METHOD(FUNCTION_CANCEL_PRINT, NapiInnerPrint::CancelPrintJob),
DECLARE_NAPI_METHOD(FUNCTION_REQUEST_PREVIEW, NapiInnerPrint::RequestPreview),
DECLARE_NAPI_METHOD(FUNCTION_QUERY_CAPABILITY, NapiInnerPrint::QueryCapability),
DECLARE_NAPI_METHOD(FUNCTION_REGISTER_EVENT, NapiInnerPrint::On),
DECLARE_NAPI_METHOD(FUNCTION_UNREGISTER_EVENT, NapiInnerPrint::Off),
DECLARE_NAPI_METHOD(FUNCTION_ADD_PRINTER, NapiPrintExt::AddPrinters),
DECLARE_NAPI_METHOD(FUNCTION_REMOVE_PRINTER, NapiPrintExt::RemovePrinters),
DECLARE_NAPI_METHOD(FUNCTION_UPDATE_PRINTER_STATE, NapiPrintExt::UpdatePrinterState),
DECLARE_NAPI_METHOD(FUNCTION_UPDATE_JOB_STATE, NapiPrintExt::UpdatePrintJobState),
};
napi_status status = napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc);
PRINT_HILOGD("init upload %{public}d", status);
return exports;
}
static __attribute__((constructor)) void RegisterModule()
{
static napi_module module = { .nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "print",
.nm_priv = ((void *)0),
.reserved = { 0 } };
napi_module_register(&module);
PRINT_HILOGD("module register print");
}

View File

@ -1,648 +0,0 @@
/*
* 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 "print_parse_type.h"
#include "async_call.h"
#include "napi_print_ext.h"
#include "napi_print_utils.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS::Print {
static constexpr const char *PARAM_INFO_PRINTID = "printerId";
static constexpr const char *PARAM_INFO_PRINTERNAME = "printerName";
static constexpr const char *PARAM_INFO_PRINTERICON = "printerIcon";
static constexpr const char *PARAM_INFO_PRINTERSTATE = "printerState";
static constexpr const char *PARAM_INFO_DESCRIPTION = "description";
static constexpr const char *PARAM_INFO_CAPABILITY = "capability";
static constexpr const char *PARAM_CAPABILITY_MINMARGIN = "minMargin";
static constexpr const char *PARAM_CAPABILITY_PAGESIZE = "pageSize";
static constexpr const char *PARAM_CAPABILITY_RESOLUTION = "resolution";
static constexpr const char *PARAM_CAPABILITY_COLORMODE = "colorMode";
static constexpr const char *PARAM_CAPABILITY_DUPLEXMODE = "duplexMode";
static constexpr const char *PARAM_PAGESIZE_ID = "id";
static constexpr const char *PARAM_PAGESIZE_NAME = "name";
static constexpr const char *PARAM_PAGESIZE_WIDTH = "width";
static constexpr const char *PARAM_PAGESIZE_HEIGHT = "height";
static constexpr const char *PARAM_RESOLUTION_ID = "id";
static constexpr const char *PARAM_RESOLUTION_HORIZONTALDPI = "horizontalDpi";
static constexpr const char *PARAM_RESOLUTION_VERTICALDPI = "verticalDpi";
static constexpr const char *PARAM_MARGIN_TOP = "top";
static constexpr const char *PARAM_MARGIN_BOTTOM = "bottom";
static constexpr const char *PARAM_MARGIN_LEFT = "left";
static constexpr const char *PARAM_MARGIN_RIGHT = "right";
static constexpr const char *PARAM_JOB_FILES = "files";
static constexpr const char *PARAM_JOB_JOBID = "jobId";
static constexpr const char *PARAM_JOB_PRINTERID = "printerId";
static constexpr const char *PARAM_JOB_JOBSTATE = "jobState";
static constexpr const char *PARAM_JOB_COPYNUMBER = "copyNumber";
static constexpr const char *PARAM_JOB_PAGERANGE = "pageRange";
static constexpr const char *PARAM_JOB_ISSEQUENTIAL = "isSequential";
static constexpr const char *PARAM_JOB_PAGESIZE = "pageSize";
static constexpr const char *PARAM_JOB_ISLANDSCAPE = "isLandscape";
static constexpr const char *PARAM_JOB_COLORMODE = "colorMode";
static constexpr const char *PARAM_JOB_DUPLEXMODE = "duplexMode";
static constexpr const char *PARAM_JOB_MARGIN = "margin";
static constexpr const char *PARAM_JOB_PREVIEW = "preview";
static constexpr const char *PARAM_PREATTRIBUTE_RANGE = "previewRange";
static constexpr const char *PARAM_PREATTRIBUTE_RESULT = "result";
static constexpr const char *PARAM_RANGE_STARTPAGE = "startPage";
static constexpr const char *PARAM_RANGE_ENDPAGE = "endPage";
static constexpr const char *PARAM_RANGE_PAGES = "pages";
bool PrintParseType::ParseInfo(napi_env env, napi_value InfoValue, PrinterInfo &info)
{
if (!ParseInfoParam(env, InfoValue, info)) {
PRINT_HILOGD("ParseInfoParam is error!");
return false;
}
info.SetPrinterId(NapiPrintUtils::GetUint32Property(env, InfoValue, PARAM_INFO_PRINTID));
info.SetPrinterName(NapiPrintUtils::GetStringPropertyUtf8(env, InfoValue, PARAM_INFO_PRINTERNAME));
info.SetPrinterIcon(NapiPrintUtils::GetUint32Property(env, InfoValue, PARAM_INFO_PRINTERICON));
info.SetPrinterState(NapiPrintUtils::GetUint32Property(env, InfoValue, PARAM_INFO_PRINTERSTATE));
info.SetDescription(NapiPrintUtils::GetStringPropertyUtf8(env, InfoValue, PARAM_INFO_DESCRIPTION));
PRINT_HILOGD("info_value printId value is: %{public}d", info.GetPrintId());
PRINT_HILOGD("info_value printerName value is %{public}s", info.GetPrinterName().c_str());
PRINT_HILOGD("info_value printerIcon value is %{public}d", info.GetPrinterIcon());
PRINT_HILOGD("info_value printerState value is %{public}d", info.GetPrinterState());
PRINT_HILOGD("info_value description value is %{public}s", info.GetDescription().c_str());
return true;
}
bool PrintParseType::ParseCapability(napi_env env, napi_value capValue, PrinterCapability &capability)
{
if (!ParseCapParam(env, capValue, capability)) {
PRINT_HILOGD("ParseCapParam is error!");
return false;
}
capability.SetColorMode(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_CAPABILITY_COLORMODE));
capability.SetDuplexMode(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_CAPABILITY_DUPLEXMODE));
PRINT_HILOGD("capability_value colorMode value is %{public}d", capability.GetColorMode());
PRINT_HILOGD("capability_value duplexMode value is %{public}d", capability.GetDuplexMode());
return true;
}
bool PrintParseType::ParsePageSize(napi_env env, napi_value capValue, PrintPageSize &pageSize)
{
if (!ParsePageSizeParam(env, capValue, pageSize)) {
PRINT_HILOGD("ParsePageSizeParam is error!");
return false;
}
pageSize.SetId(NapiPrintUtils::GetStringPropertyUtf8(env, capValue, PARAM_PAGESIZE_ID));
pageSize.SetName(NapiPrintUtils::GetStringPropertyUtf8(env, capValue, PARAM_PAGESIZE_NAME));
pageSize.SetWidth(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_PAGESIZE_WIDTH));
pageSize.SetHeight(NapiPrintUtils::GetUint32Property(env, capValue, PARAM_PAGESIZE_HEIGHT));
PRINT_HILOGD("printerPageSize_value GetId value is %{public}s", pageSize.GetId().c_str());
PRINT_HILOGD("printerPageSize_value GetName value is %{public}s", pageSize.GetName().c_str());
PRINT_HILOGD("printerPageSize_value GetWidth value is %{public}d", pageSize.GetWidth());
PRINT_HILOGD("printerPageSize_value GetHeight value is %{public}d", pageSize.GetHeight());
return true;
}
bool PrintParseType::ParseResolution(napi_env env, napi_value reValue, PrintResolution &resolution)
{
if (!ParseResolutionParam(env, reValue, resolution)) {
PRINT_HILOGD("ParseResolutionParam is error!");
return false;
}
resolution.SetId(NapiPrintUtils::GetUint32Property(env, reValue, PARAM_RESOLUTION_ID));
resolution.SetHorizontalDpi(NapiPrintUtils::GetUint32Property(env, reValue, PARAM_RESOLUTION_HORIZONTALDPI));
resolution.SetVerticalDpi(NapiPrintUtils::GetUint32Property(env, reValue, PARAM_RESOLUTION_VERTICALDPI));
PRINT_HILOGD("printerResolution_value GetId value is %{public}d", resolution.GetId());
PRINT_HILOGD("printerResolution_value GetHorizontalDpi value is %{public}d", resolution.GetHorizontalDpi());
PRINT_HILOGD("printerResolution_value GetVerticalDpi value is %{public}d", resolution.GetVerticalDpi());
return true;
}
bool PrintParseType::ParseMargin(napi_env env, napi_value marginValue, PrintMargin &margin)
{
if (!ParseMarginParam(env, marginValue, margin)) {
PRINT_HILOGD("ParseResolutionParam is error!");
return false;
}
margin.SetTop(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_TOP));
margin.SetBottom(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_BOTTOM));
margin.SetLeft(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_LEFT));
margin.SetRight(NapiPrintUtils::GetUint32Property(env, marginValue, PARAM_MARGIN_RIGHT));
PRINT_HILOGD("printerMargin_value GetTop value is %{public}d", margin.GetTop());
PRINT_HILOGD("printerMargin_value GetBottom value is %{public}d", margin.GetBottom());
PRINT_HILOGD("printerMargin_value GetLeft value is %{public}d", margin.GetLeft());
PRINT_HILOGD("printerMargin_value GetRight value is %{public}d", margin.GetRight());
return true;
}
bool PrintParseType::ParseJob(napi_env env, napi_value jobValue, PrintJob &printJob)
{
if (!ParseJobParam(env, jobValue, printJob)) {
PRINT_HILOGD("ParseJobParam is error!");
return false;
}
printJob.SetJobId(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_JOBID));
printJob.SetPrintId(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_PRINTERID));
printJob.SetJobState(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_JOBSTATE));
printJob.SetCopyNumber(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_COPYNUMBER));
PRINT_HILOGD("printJob_value GetJobId value is %{public}d", printJob.GetJobId());
PRINT_HILOGD("printJob_value GetPrinterId value is %{public}d", printJob.GetPrinterId());
PRINT_HILOGD("printJob_value GetJobState value is %{public}d", printJob.GetJobState());
PRINT_HILOGD("printJob_value GetCopyNumber value is %{public}d", printJob.GetCopyNumber());
PRINT_HILOGD("printJob_value SetIsLandscape value is %{public}s", printJob.GetIsLandscape() ? "true" : "false");
PRINT_HILOGD("printJob_value SetIsLandscape value is %{public}s", printJob.GetIsLandscape() ? "true" : "false");
PRINT_HILOGD("printJob_value ColorMode value is %{public}d", printJob.GetIsSequential());
PRINT_HILOGD("printJob_value DuplexMode value is %{public}d", printJob.GetDuplexMode());
return true;
}
bool PrintParseType::ParsePreviewAttribute(napi_env env, napi_value preAttValue, PreviewAttribute &preAtt)
{
if (!ParsePreviewAttributeParam(env, preAttValue, preAtt)) {
PRINT_HILOGD("ParsePreviewAttributeParam is error!");
return false;
}
preAtt.SetResult(NapiPrintUtils::GetStringPropertyUtf8(env, preAttValue, PARAM_PREATTRIBUTE_RESULT));
PRINT_HILOGD("preAtt_value GetResult value is %{public}s", preAtt.GetResult().c_str());
return true;
}
bool PrintParseType::ParseRange(napi_env env, napi_value rangeValue, PrintRange &range)
{
if (!ParseRangeParam(env, rangeValue, range)) {
PRINT_HILOGD("ParseRangeParam is error!");
return false;
}
range.SetStartPage(NapiPrintUtils::GetUint32Property(env, rangeValue, PARAM_RANGE_STARTPAGE));
range.SetEndPage(NapiPrintUtils::GetUint32Property(env, rangeValue, PARAM_RANGE_ENDPAGE));
PRINT_HILOGD("printRange_value GetStartPage value is %{public}d", range.GetStartPage());
PRINT_HILOGD("printRange_value GetEndPage value is %{public}d", range.GetEndPage());
return true;
}
bool PrintParseType::ParseInfoParam(napi_env env, napi_value InfoValue, PrinterInfo &info)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, InfoValue, PARAM_INFO_PRINTID);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, InfoValue, PARAM_INFO_PRINTERNAME);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_string) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, InfoValue, PARAM_INFO_PRINTERICON);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, InfoValue, PARAM_INFO_PRINTERSTATE);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
napi_value param_five = NapiPrintUtils::GetNamedProperty(env, InfoValue, PARAM_INFO_DESCRIPTION);
if (NapiPrintUtils::GetValueType(env, param_five) != napi_string) {
PRINT_HILOGD("error param_five");
return false;
}
napi_value param_six = NapiPrintUtils::GetNamedProperty(env, InfoValue, PARAM_INFO_CAPABILITY);
if (NapiPrintUtils::GetValueType(env, param_six) != napi_object) {
PRINT_HILOGD("error param_six");
return false;
} else {
PrinterCapability capability;
if (!ParseCapability(env, param_six, capability)) {
PRINT_HILOGD("ParseCapability type error!");
return false;
}
info.SetCapability(capability);
}
return true;
}
bool PrintParseType::ParseCapParam(napi_env env, napi_value capValue, PrinterCapability &capability)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_MINMARGIN);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_object) {
PRINT_HILOGD("error param_one");
return false;
} else {
PrintMargin margin;
if (!ParseMargin(env, param_one, margin)) {
PRINT_HILOGD("ParseCapability type error!");
return false;
}
capability.SetMinMargin(margin);
}
if (!CoversePriotResolutionObject(env, capValue, capability)) {
PRINT_HILOGD("error Arr ParsePageSize");
return false;
}
if (!ParseArrPrintResolution(env, capValue, capability)) {
PRINT_HILOGD("error Arr PrintResolution");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_COLORMODE);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
napi_value param_five = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_DUPLEXMODE);
if (NapiPrintUtils::GetValueType(env, param_five) != napi_number) {
// ParseCapParam()
PRINT_HILOGD("error param_five");
return false;
}
auto names = NapiPrintUtils::GetPropertyNames(env, capValue);
return true;
}
void PrintPaeseType::CoversePriotResolutionObject(napi_env env, napi_value capValue, PrinterCapability &capability)
{
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_PAGESIZE);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_object) {
PRINT_HILOGD("error param_two");
return false;
} else {
bool isArray = false;
napi_is_array(env, param_two, &isArray);
if (!isArray) {
PRINT_HILOGD("ParsePageSize type error!");
return false;
}
std::vector<PrintPageSize> pageSizeList;
uint32_t arrayLength = 0;
napi_get_array_length(env, param_two, &arrayLength);
for (uint32_t i = 0; i < arrayLength; i++) {
napi_value pageSizeValue;
PrintPageSize pageSize;
napi_get_element(env, param_two, i, &pageSizeValue);
if (!ParsePageSize(env, pageSizeValue, pageSize)) {
PRINT_HILOGD("ParsePageSize type error!");
return false;
}
pageSizeList.push_back(pageSize);
}
capability.SetPageSize(pageSizeList);
}
}
bool PrintParseType::ParseArrPrintResolution(napi_env env, napi_value capValue, PrinterCapability &capability)
{
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_RESOLUTION);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_object) {
PRINT_HILOGD("error param_three");
return false;
} else {
bool isReArray = false;
napi_is_array(env, param_three, &isReArray);
if (!isReArray) {
PRINT_HILOGD("PrintResolution type error!");
return false;
}
std::vector<PrintResolution> resolutionList;
uint32_t arrayReLength = 0;
napi_get_array_length(env, param_three, &arrayReLength);
for (uint32_t i = 0; i < arrayReLength; i++) {
napi_value reValue;
PrintResolution resolution;
napi_get_element(env, param_three, i, &reValue);
if (!ParseResolution(env, reValue, resolution)) {
PRINT_HILOGD("PrintResolution type error!");
return false;
}
resolutionList.push_back(resolution);
}
capability.SetResolution(resolutionList);
}
return true;
}
bool PrintParseType::ParsePageSizeParam(napi_env env, napi_value capValue, PrintPageSize &pageSize)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_ID);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_string) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_NAME);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_string) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_WIDTH);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_HEIGHT);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
return true;
}
bool PrintParseType::ParseResolutionParam(napi_env env, napi_value reValue, PrintResolution &resolution)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, reValue, PARAM_RESOLUTION_ID);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, reValue, PARAM_RESOLUTION_HORIZONTALDPI);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_number) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, reValue, PARAM_RESOLUTION_VERTICALDPI);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
return true;
}
bool PrintParseType::ParseMarginParam(napi_env env, napi_value marginValue, PrintMargin &margin)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_TOP);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_BOTTOM);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_number) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_LEFT);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, marginValue, PARAM_MARGIN_RIGHT);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
auto names = NapiPrintUtils::GetPropertyNames(env, marginValue);
PRINT_HILOGD("current margin paramster name list size = %{public}zu", names.size());
return true;
}
bool PrintParseType::ParseArrFiles(napi_env env, napi_value jobValue, PrintJob &printJob)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_FILES);
bool isFileArray = false;
napi_is_array(env, param_one, &isFileArray);
if (!isFileArray) {
PRINT_HILOGD("PrinterJobFile type error!");
return false;
}
std::vector<std::string> printfiles;
uint32_t arrayReLength = 0;
napi_get_array_length(env, param_one, &arrayReLength);
for (uint32_t i = 0; i < arrayReLength; i++) {
napi_value filesValue;
napi_get_element(env, param_one, i, &filesValue);
std::string files = NapiPrintUtils::GetStringFromValueUtf8(env, filesValue);
PRINT_HILOGD("printJob_value param_one %{public}s", files.c_str());
printfiles.push_back(files);
}
printJob.SetFiles(printfiles);
return true;
}
bool PrintParseType::ParseHasNum(napi_env env, napi_value jobValue, PrintJob &printJob)
{
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_ISSEQUENTIAL)) {
PRINT_HILOGD("No isSequential present, ignore it");
} else {
napi_value param_seven = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_ISSEQUENTIAL);
if (NapiPrintUtils::GetValueType(env, param_seven) != napi_boolean) {
PRINT_HILOGD("error param_seven");
return false;
} else {
printJob.SetIsSequential(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_ISSEQUENTIAL));
}
}
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_ISLANDSCAPE)) {
PRINT_HILOGD("No isLandscape present, ignore it");
} else {
napi_value param_nine = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_ISLANDSCAPE);
if (NapiPrintUtils::GetValueType(env, param_nine) != napi_boolean) {
PRINT_HILOGD("error param_nine");
return false;
} else {
printJob.SetIsLandscape(NapiPrintUtils::GetBooleanProperty(env, jobValue, PARAM_JOB_ISLANDSCAPE));
}
}
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_COLORMODE)) {
PRINT_HILOGD("No colorMode present, ignore it");
} else {
napi_value param_ten = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_COLORMODE);
if (NapiPrintUtils::GetValueType(env, param_ten) != napi_number) {
PRINT_HILOGD("error param_ten");
return false;
} else {
printJob.SetColorMode(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_COLORMODE));
}
}
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_DUPLEXMODE)) {
PRINT_HILOGD("No duplexMode present, ignore it");
} else {
napi_value param_eleven = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_DUPLEXMODE);
if (NapiPrintUtils::GetValueType(env, param_eleven) != napi_number) {
PRINT_HILOGD("error param_eleven");
return false;
} else {
printJob.SetDuplexMode(NapiPrintUtils::GetUint32Property(env, jobValue, PARAM_JOB_DUPLEXMODE));
}
}
return true;
}
bool PrintParseType::ParseHasObj(napi_env env, napi_value jobValue, PrintJob &printJob)
{
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_PAGESIZE)) {
PRINT_HILOGD("No pageSize present, ignore it");
} else {
napi_value param_eight = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_PAGESIZE);
if (NapiPrintUtils::GetValueType(env, param_eight) != napi_object) {
PRINT_HILOGD("error param_eight");
return false;
} else {
PrintPageSize pagesize;
if (!ParsePageSize(env, param_eight, pagesize)) {
PRINT_HILOGD("ParsePageSize type error!");
return false;
}
printJob.SetPageSize(pagesize);
}
}
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_MARGIN)) {
PRINT_HILOGD("No isSequential present, ignore it");
} else {
napi_value param_twelve = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_MARGIN);
if (NapiPrintUtils::GetValueType(env, param_twelve) != napi_object) {
PRINT_HILOGD("error param_twelve");
return false;
} else {
PrintMargin margin;
if (!ParseMargin(env, param_twelve, margin)) {
PRINT_HILOGD("PrintMargin type error!");
}
printJob.SetMargin(margin);
}
}
if (!NapiPrintUtils::HasNamedProperty(env, jobValue, PARAM_JOB_PREVIEW)) {
PRINT_HILOGD("No PreviewAttribute present, ignore it");
} else {
napi_value param_thirteen = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_PREVIEW);
PreviewAttribute previewAttribute;
if (!ParsePreviewAttribute(env, param_thirteen, previewAttribute)) {
PRINT_HILOGD("ParsePreviewAttribute type error!");
return false;
}
printJob.SetPreview(previewAttribute);
}
return true;
}
bool PrintParseType::ParseJobParam(napi_env env, napi_value jobValue, PrintJob &printJob)
{
if (!ParseArrFiles(env, jobValue, printJob)) {
PRINT_HILOGD("ParseArrFiles error");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_JOBID);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_number) {
PRINT_HILOGD("error param_two");
return false;
}
napi_value param_three = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_PRINTERID);
if (NapiPrintUtils::GetValueType(env, param_three) != napi_number) {
PRINT_HILOGD("error param_three");
return false;
}
napi_value param_four = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_JOBSTATE);
if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) {
PRINT_HILOGD("error param_four");
return false;
}
napi_value param_five = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_COPYNUMBER);
if (NapiPrintUtils::GetValueType(env, param_five) != napi_number) {
PRINT_HILOGD("error param_five");
return false;
}
napi_value param_six = NapiPrintUtils::GetNamedProperty(env, jobValue, PARAM_JOB_PAGERANGE);
if (NapiPrintUtils::GetValueType(env, param_six) != napi_object) {
PRINT_HILOGD("error param_six");
return false;
} else {
PrintRange range;
if (!ParseRange(env, param_six, range)) {
PRINT_HILOGD("ParseRange type error!");
return false;
}
printJob.SetPageRange(range);
}
if (!ParseHasObj(env, jobValue, printJob) && !ParseHasNum(env, jobValue, printJob)) {
PRINT_HILOGD("default-value has error!");
return false;
}
return true;
}
bool PrintParseType::ParsePreviewAttributeParam(napi_env env, napi_value preAttValue, PreviewAttribute &preAtt)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, preAttValue, PARAM_PREATTRIBUTE_RANGE);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_object) {
PRINT_HILOGD("error param_one");
return false;
} else {
PrintRange range;
if (!ParseRange(env, param_one, range)) {
PRINT_HILOGD("ParseRange type error!");
return false;
}
preAtt.SetPreviewRange(range);
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, preAttValue, PARAM_PREATTRIBUTE_RESULT);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_string) {
PRINT_HILOGD("error param_two");
return false;
}
return true;
}
bool PrintParseType::ParseRangeParam(napi_env env, napi_value rangeValue, PrintRange &range)
{
napi_value param_one = NapiPrintUtils::GetNamedProperty(env, rangeValue, PARAM_RANGE_STARTPAGE);
if (NapiPrintUtils::GetValueType(env, param_one) != napi_number) {
PRINT_HILOGD("error param_one");
return false;
}
napi_value param_two = NapiPrintUtils::GetNamedProperty(env, rangeValue, PARAM_RANGE_ENDPAGE);
if (NapiPrintUtils::GetValueType(env, param_two) != napi_number) {
PRINT_HILOGD("error param_two");
return false;
}
PRINT_HILOGD("Set startPage, endPage value begin.");
napi_value startPage, endPage, param_three = NapiPrintUtils::GetNamedProperty(env, rangeValue, PARAM_RANGE_PAGES);
bool isArray = false;
napi_is_array(env, param_three, &isArray);
uint32_t arrayLength = 0, startPageNum, endPageNum;
napi_get_array_length(env, param_three, &arrayLength);
if (!isArray || arrayLength != NapiPrintUtils::ARGC_TWO) {
PRINT_HILOGD("ParseRangeParam pages array error!");
return false;
}
PRINT_HILOGD("Set startPageNum value begin.");
napi_get_element(env, param_three, 0, &startPage);
napi_get_element(env, param_three, 1, &endPage);
napi_get_value_uint32(env, startPage, &startPageNum);
napi_get_value_uint32(env, endPage, &endPageNum);
if (startPageNum > endPageNum) {
PRINT_HILOGD("startPage is less than endPage, Param Pages is illegal!");
return false;
}
PRINT_HILOGD("Set page value begin.");
std::vector<uint32_t> page = { startPageNum, endPageNum };
range.SetPages(page);
PRINT_HILOGD("SetPage value is : %{public}d, %{public}d.", startPageNum, endPageNum);
return true;
}
} // namespace OHOS::Print

View File

@ -1,83 +0,0 @@
/*
* 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 "print_task.h"
#include "async_call.h"
#include "print_log.h"
namespace OHOS::Print {
PrintTask::PrintTask(uint32_t taskId) : taskId_(taskId)
{
supportEvents_[EVENT_BLOCK] = true;
supportEvents_[EVENT_SUCCESS] = true;
supportEvents_[EVENT_FAIL] = true;
supportEvents_[EVENT_CANCEL] = true;
supportPrinterState_[PRINTER_STATE_ADD] = true;
supportPrinterState_[PRINTER_STATE_REMOVED] = true;
supportPrinterState_[PRINTER_STATE_IDLE] = true;
supportPrinterState_[PRINTER_STATE_PRINTING] = true;
supportPrinterState_[PRINTER_STATE_BLOCKED] = true;
supportPrinterState_[PRINTER_STATE_BUSY] = true;
supportPrinterState_[PRINTER_STATE_FAILED] = true;
supportJobState_[PRINTJOB_STATE_CREATED] = true;
supportJobState_[PRINTJOB_STATE_QUEUED] = true;
supportJobState_[PRINTJOB_STATE_PRINTING] = true;
supportJobState_[PRINTJOB_STATE_BLOCKED] = true;
supportJobState_[PRINTJOB_STATE_SUCCESS] = true;
supportJobState_[PRINTJOB_STATE_FAILED] = true;
supportJobState_[PRINTJOB_STATE_cancelled] = true;
}
PrintTask::~PrintTask()
{
supportEvents_.clear();
}
uint32_t PrintTask::GetId() const
{
return taskId_;
}
napi_value PrintTask::On(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
return nullptr;
}
napi_value PrintTask::Off(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
return nullptr;
}
bool PrintTask::IsSupportType(const std::string &type)
{
return supportEvents_.find(type) != supportEvents_.end();
}
bool PrintTask::IsSupportPrinterStateType(const std::string &type)
{
return supportPrinterState_.find(type) != supportPrinterState_.end();
}
bool PrintTask::IsSupportJobStateType(const std::string &type)
{
PRINT_HILOGD("Enter IsSupportJobStateType.");
return supportJobState_.find(type) != supportJobState_.end();
}
} // namespace OHOS::Print

View File

@ -1,23 +0,0 @@
# 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/test.gni")
#################################group#########################################
group("unittest") {
testonly = true
deps = []
deps += [ "unittest/src:unittest" ]
}
###############################################################################

Some files were not shown because too many files have changed in this diff Show More