From 05763567dc99d4a88322416e42c825b25e50791e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=87=AF?= Date: Wed, 12 Jun 2024 10:22:21 +0800 Subject: [PATCH] sync print code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张凯 --- bundle.json | 215 ++- cfi_blocklist.txt | 1 + etc/init/printservice.cfg | 4 +- figures/print-architecture.png | Bin 26211 -> 20038 bytes frameworks/helper/print_helper/BUILD.gn | 14 +- .../print_helper/include/napi_print_utils.h | 3 + .../print_helper/src/napi_print_utils.cpp | 20 + .../src/print_attributes_helper.cpp | 16 +- .../print_helper/src/print_job_helper.cpp | 21 +- .../src/print_page_size_helper.cpp | 17 +- .../src/print_preview_attribute_helper.cpp | 17 +- .../src/print_resolution_helper.cpp | 21 +- .../src/printer_capability_helper.cpp | 16 +- .../print_helper/src/printer_info_helper.cpp | 31 +- frameworks/innerkitsimpl/print_impl/BUILD.gn | 26 +- .../print_impl/include/iprint_adapter.h | 1 + .../include/iprint_ipc_interface_code.h | 12 + .../print_impl/include/iprint_service.h | 23 +- .../print_impl/include/print_callback.h | 9 +- .../print_innerkit_modal_ui_callback.h | 42 + .../print_impl/include/print_manager_client.h | 20 +- .../print_impl/include/print_service_proxy.h | 23 +- .../print_impl/src/print_callback.cpp | 41 +- .../src/print_innerkit_modal_ui_callback.cpp | 75 + .../print_impl/src/print_manager_client.cpp | 421 ++--- .../print_impl/src/print_service_proxy.cpp | 349 +++- frameworks/kits/extension/BUILD.gn | 26 +- .../kits/extension/src/js_print_extension.cpp | 8 +- frameworks/models/print_models/BUILD.gn | 17 +- .../print_models/include/print_page_size.h | 126 +- .../models/print_models/include/print_utils.h | 24 + .../print_models/include/printer_capability.h | 11 + .../print_models/include/printer_info.h | 30 + .../print_models/src/print_attributes.cpp | 4 + .../models/print_models/src/print_job.cpp | 7 +- .../print_models/src/print_page_size.cpp | 193 +- .../models/print_models/src/print_utils.cpp | 161 ++ .../print_models/src/printer_capability.cpp | 35 + .../models/print_models/src/printer_info.cpp | 117 +- frameworks/ohprint/BUILD.gn | 21 +- frameworks/ohprint/src/print_helper.cpp | 18 +- .../kits/jsnapi/print_extension/BUILD.gn | 10 + .../kits/jsnapi/print_extensionctx/BUILD.gn | 10 + .../print_extension_context.js | 22 +- interfaces/kits/napi/print_napi/BUILD.gn | 28 +- .../print_napi/include/napi_inner_print.h | 6 + .../napi/print_napi/include/napi_print_ext.h | 3 +- .../print_napi/include/print_async_call.h | 8 +- .../napi/print_napi/include/print_context.h | 77 + .../include/print_modal_ui_callback.h | 54 + .../kits/napi/print_napi/include/print_task.h | 29 +- .../napi/print_napi/src/napi_inner_print.cpp | 70 +- .../napi/print_napi/src/napi_print_ext.cpp | 96 +- .../napi/print_napi/src/napi_print_task.cpp | 16 +- .../napi/print_napi/src/print_async_call.cpp | 32 +- .../src/print_modal_ui_callback.cpp | 306 ++++ .../kits/napi/print_napi/src/print_module.cpp | 33 +- .../kits/napi/print_napi/src/print_task.cpp | 276 ++- interfaces/kits/ndk/ohprint/BUILD.gn | 34 + .../kits/ndk/ohprint/libohprint.ndk.json | 74 + print.gni | 4 +- services/print_service/BUILD.gn | 59 +- .../include/print_attribute_preference.h | 94 + .../print_service/include/print_bms_helper.h | 2 +- .../include/print_cups_attribute.h | 25 + .../print_service/include/print_cups_client.h | 61 +- .../include/print_event_subscriber.h | 33 + .../include/print_http_request_process.h | 124 ++ .../include/print_http_server_manager.h | 53 + .../include/print_ipp_over_usb_manager.h | 42 + .../include/print_security_guard_info.h | 4 +- .../include/print_service_ability.h | 100 +- .../include/print_service_converter.h | 82 + .../include/print_service_helper.h | 24 +- .../include/print_service_stub.h | 15 +- .../print_service/include/print_system_data.h | 75 + .../print_service/include/print_usb_manager.h | 83 + .../print_service/include/print_user_data.h | 69 + .../print_service/src/print_bms_helper.cpp | 2 +- .../src/print_cups_attribute.cpp | 433 +++++ .../print_service/src/print_cups_client.cpp | 495 ++++-- .../src/print_event_subscriber.cpp | 59 + .../src/print_http_request_process.cpp | 568 ++++++ .../src/print_http_server_manager.cpp | 152 ++ .../src/print_ipp_over_usb_manager.cpp | 116 ++ .../src/print_security_guard_info.cpp | 14 +- .../src/print_service_ability.cpp | 1576 ++++++++++++++--- .../src/print_service_converter.cpp | 83 + .../src/print_service_helper.cpp | 63 +- .../print_service/src/print_service_stub.cpp | 233 ++- .../print_service/src/print_system_data.cpp | 604 +++++++ .../print_service/src/print_usb_manager.cpp | 355 ++++ .../print_service/src/print_user_data.cpp | 286 +++ test/fuzztest/BUILD.gn | 8 +- test/fuzztest/printcupsclient_fuzzer/BUILD.gn | 110 ++ .../printcupsclient_fuzzer/curpus/init | 16 + .../printcupsclient_fuzzer.cpp | 238 +++ .../printcupsclient_fuzzer.h | 21 + .../printcupsclient_fuzzer/project.xml | 25 + .../printservice_fuzzer.cpp | 23 +- .../printserviceability_fuzzer/BUILD.gn | 113 ++ .../printserviceability_fuzzer/curpus/init | 16 + .../print_service_ability_mock_permission.h | 27 + .../printserviceability_fuzzer.cpp | 845 +++++++++ .../printserviceability_fuzzer.h | 21 + .../printserviceability_mock_permission.cpp | 44 + .../printserviceability_fuzzer/project.xml | 25 + test/unittest/fwk_inner_napi_test/BUILD.gn | 4 +- .../mock/mock_print_manager_client.h | 30 + .../print_attributes_test.cpp | 28 + .../print_manager_client_test.cpp | 352 +++- .../print_page_size_test.cpp | 8 +- .../fwk_inner_napi_test/print_range_test.cpp | 16 + .../print_service_proxy_test.cpp | 94 +- .../fwk_inner_napi_test/print_utils_test.cpp | 137 +- .../fwk_print_cups_client_test/BUILD.gn | 96 + .../print_cups_client_test.cpp | 1542 ++++++++++++++++ test/unittest/fwk_print_helper_test/BUILD.gn | 82 + .../print_bms_helper_test.cpp | 140 ++ .../fwk_print_service_ability_test/BUILD.gn | 85 + .../print_service_ability_test.cpp | 1071 +++++++++++ .../print_service_mock_permission.cpp | 44 + test/unittest/service_test/BUILD.gn | 37 +- .../service_test/mock/mock_bundle_mgr.h | 1 + .../service_test/mock/mock_print_service.h | 70 +- .../mock/mock_print_service_helper.h | 2 - .../print_bms_death_recipient_test.cpp | 12 - .../print_callback_proxy_test.cpp | 60 +- .../print_cups_attribute_test.cpp | 578 ++++++ .../print_http_request_process_test.cpp | 1049 +++++++++++ .../print_http_server_manager_test.cpp | 158 ++ .../print_ipp_over_usb_manager_test.cpp | 130 ++ .../print_security_guard_manager_test.cpp | 16 + .../print_service_converter_test.cpp | 178 ++ .../print_service_helper_test.cpp | 38 +- .../service_test/print_service_stub_test.cpp | 276 ++- .../service_test/print_system_data_test.cpp | 931 ++++++++++ .../service_test/print_usb_manager_test.cpp | 354 ++++ .../service_test/print_user_data_test.cpp | 258 +++ utils/include/print_constant.h | 26 +- utils/include/print_ipp_over_usb_constant.h | 203 +++ utils/include/print_ipp_over_usb_util.h | 184 ++ utils/include/print_log.h | 11 +- utils/include/print_util.h | 34 + 144 files changed, 17610 insertions(+), 1665 deletions(-) create mode 100644 cfi_blocklist.txt create mode 100644 frameworks/innerkitsimpl/print_impl/include/print_innerkit_modal_ui_callback.h create mode 100644 frameworks/innerkitsimpl/print_impl/src/print_innerkit_modal_ui_callback.cpp create mode 100644 interfaces/kits/napi/print_napi/include/print_context.h create mode 100644 interfaces/kits/napi/print_napi/include/print_modal_ui_callback.h create mode 100644 interfaces/kits/napi/print_napi/src/print_modal_ui_callback.cpp create mode 100644 interfaces/kits/ndk/ohprint/BUILD.gn create mode 100644 interfaces/kits/ndk/ohprint/libohprint.ndk.json create mode 100644 services/print_service/include/print_attribute_preference.h create mode 100644 services/print_service/include/print_cups_attribute.h create mode 100644 services/print_service/include/print_event_subscriber.h create mode 100644 services/print_service/include/print_http_request_process.h create mode 100644 services/print_service/include/print_http_server_manager.h create mode 100644 services/print_service/include/print_ipp_over_usb_manager.h create mode 100644 services/print_service/include/print_service_converter.h create mode 100644 services/print_service/include/print_system_data.h create mode 100644 services/print_service/include/print_usb_manager.h create mode 100644 services/print_service/include/print_user_data.h create mode 100644 services/print_service/src/print_cups_attribute.cpp create mode 100644 services/print_service/src/print_event_subscriber.cpp create mode 100644 services/print_service/src/print_http_request_process.cpp create mode 100644 services/print_service/src/print_http_server_manager.cpp create mode 100644 services/print_service/src/print_ipp_over_usb_manager.cpp create mode 100644 services/print_service/src/print_service_converter.cpp create mode 100644 services/print_service/src/print_system_data.cpp create mode 100644 services/print_service/src/print_usb_manager.cpp create mode 100644 services/print_service/src/print_user_data.cpp create mode 100644 test/fuzztest/printcupsclient_fuzzer/BUILD.gn create mode 100644 test/fuzztest/printcupsclient_fuzzer/curpus/init create mode 100644 test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.cpp create mode 100644 test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.h create mode 100644 test/fuzztest/printcupsclient_fuzzer/project.xml create mode 100644 test/fuzztest/printserviceability_fuzzer/BUILD.gn create mode 100644 test/fuzztest/printserviceability_fuzzer/curpus/init create mode 100644 test/fuzztest/printserviceability_fuzzer/mock/print_service_ability_mock_permission.h create mode 100644 test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.cpp create mode 100644 test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.h create mode 100644 test/fuzztest/printserviceability_fuzzer/printserviceability_mock_permission.cpp create mode 100644 test/fuzztest/printserviceability_fuzzer/project.xml create mode 100644 test/unittest/fwk_inner_napi_test/mock/mock_print_manager_client.h create mode 100644 test/unittest/fwk_print_cups_client_test/BUILD.gn create mode 100644 test/unittest/fwk_print_cups_client_test/print_cups_client_test.cpp create mode 100644 test/unittest/fwk_print_helper_test/BUILD.gn create mode 100644 test/unittest/fwk_print_helper_test/print_bms_helper_test.cpp create mode 100644 test/unittest/fwk_print_service_ability_test/BUILD.gn create mode 100644 test/unittest/fwk_print_service_ability_test/print_service_ability_test.cpp create mode 100644 test/unittest/fwk_print_service_ability_test/print_service_mock_permission.cpp create mode 100644 test/unittest/service_test/print_cups_attribute_test.cpp create mode 100644 test/unittest/service_test/print_http_request_process_test.cpp create mode 100644 test/unittest/service_test/print_http_server_manager_test.cpp create mode 100644 test/unittest/service_test/print_ipp_over_usb_manager_test.cpp create mode 100644 test/unittest/service_test/print_service_converter_test.cpp create mode 100644 test/unittest/service_test/print_system_data_test.cpp create mode 100644 test/unittest/service_test/print_usb_manager_test.cpp create mode 100644 test/unittest/service_test/print_user_data_test.cpp create mode 100644 utils/include/print_ipp_over_usb_constant.h create mode 100644 utils/include/print_ipp_over_usb_util.h diff --git a/bundle.json b/bundle.json index 59389f3..bae86f9 100644 --- a/bundle.json +++ b/bundle.json @@ -1,68 +1,65 @@ { - "name": "@ohos/print_fwk", - "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_fwk" + "name": "@ohos/print_fwk", + "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_fwk" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "print_fwk", + "subsystem": "print", + "syscap": [ + "SystemCapability.Print.PrintFramework" + ], + "features": [ + ], + "adapted_system_type": [ + "standard" + ], + "rom":"2MB", + "ram":"10MB", + "deps": { + "components": [ + "ability_base", + "ability_runtime", + "access_token", + "bundle_framework", + "c_utils", + "common_event_service", + "drivers_interface_usb", + "eventhandler", + "hisysevent", + "hilog", + "init", + "ipc", + "napi", + "netmanager_ext", + "os_account", + "safwk", + "samgr", + "security_guard", + "time_service", + "usb_manager", + "wifi", + "cJSON", + "ace_engine" + ], + "third_party": [ + "zlib", + "cups", + "cups-filters", + "backends", + "libjpeg-turbo" + ] }, - "dirs": {}, - "scripts": {}, - "component": { - "name": "print_fwk", - "subsystem": "print", - "syscap": [ - "SystemCapability.Print.PrintFramework" - ], - "features": [ - ], - "adapted_system_type": [ - "standard" - ], - "rom":"2MB", - "ram":"10MB", - "deps": { - "components": [ - "ability_base", - "ability_runtime", - "access_token", - "bundle_framework", - "c_utils", - "common_event_service", - "core_service", - "distributed_notification_service", - "drivers_interface_ril", - "eventhandler", - "hisysevent", - "hitrace", - "hilog", - "i18n", - "init", - "ipc", - "napi", - "netmanager_base", - "os_account", - "preferences", - "relational_store", - "resource_management", - "safwk", - "samgr", - "security_guard", - "time_service", - "wifi" - ], - "third_party": [ - "zlib", - "cups", - "cups-filters", - "pdfium" - ] - }, - "build": { - "group_type":{ - "base_group": [], - "fwk_group":[ + "build": { + "group_type":{ + "base_group": [], + "fwk_group":[ "//base/print/print_fwk/interfaces/kits/napi/print_napi:print_napi", "//base/print/print_fwk/interfaces/kits/jsnapi/print_extension:printextensionability_napi", "//base/print/print_fwk/interfaces/kits/jsnapi/print_extensionctx:printextensioncontext_napi", @@ -72,52 +69,54 @@ "//base/print/print_fwk/frameworks/helper/print_helper:print_helper", "//base/print/print_fwk/frameworks/models/print_models:print_models", "//base/print/print_fwk/frameworks/ohprint:ohprint" - ], - "service_group":[ - "//base/print/print_fwk/services/print_service:print_service", - "//base/print/print_fwk/etc/init:printservice.rc", - "//base/print/print_fwk/profile:print_sa_profiles", - "//base/print/print_fwk/etc/init:cups-files.conf", - "//base/print/print_fwk/etc/init:cupsd.conf", - "//base/print/print_fwk/etc/init:cups_service.cfg", - "//base/print/print_fwk/etc/param:print.para", - "//base/print/print_fwk/etc/param:print.para.dac" - ] - }, - "inner_kits": [ - { - "name": "//base/print/print_fwk/frameworks/innerkitsimpl/print_impl:print_client", - "header": { - "header_files": [ - ], - "header_base":"//base/print/print_fwk/frameworks/innerkitsimpl/print_impl/include" - } - }, - { - "name": "//base/print/print_fwk/frameworks/helper/print_helper:print_helper", - "header": { - "header_files": [ - ], - "header_base":"//base/print/print_fwk/frameworks/helper/print_helper/include" - } - }, - { - "name": "//base/print/print_fwk/frameworks/models/print_models:print_models", - "header": { - "header_files": [ - ], - "header_base":"//base/print/print_fwk/frameworks/models/print_models/include" - } - } ], - "test": [ - "//base/print/print_fwk/test/unittest/fwk_inner_napi_test:print_fwk_inner_napi_test", - "//base/print/print_fwk/test/unittest/service_test:print_service_test", - "//base/print/print_fwk/test/fuzztest:fuzztest" + "service_group":[ + "//base/print/print_fwk/services/print_service:print_service", + "//base/print/print_fwk/etc/init:printservice.rc", + "//base/print/print_fwk/profile:print_sa_profiles", + "//base/print/print_fwk/etc/init:cups-files.conf", + "//base/print/print_fwk/etc/init:cupsd.conf", + "//base/print/print_fwk/etc/init:cups_service.cfg", + "//base/print/print_fwk/etc/param:print.para", + "//base/print/print_fwk/etc/param:print.para.dac" ] + }, + "inner_kits": [ + { + "name": "//base/print/print_fwk/frameworks/innerkitsimpl/print_impl:print_client", + "header": { + "header_files": [ + ], + "header_base":"//base/print/print_fwk/frameworks/innerkitsimpl/print_impl/include" + } }, - "hisysevent_config": [ - "//base/print/print_fwk/hisysevent.yaml" - ] - } + { + "name": "//base/print/print_fwk/frameworks/helper/print_helper:print_helper", + "header": { + "header_files": [ + ], + "header_base":"//base/print/print_fwk/frameworks/helper/print_helper/include" + } + }, + { + "name": "//base/print/print_fwk/frameworks/models/print_models:print_models", + "header": { + "header_files": [ + ], + "header_base":"//base/print/print_fwk/frameworks/models/print_models/include" + } + } + ], + "test": [ + "//base/print/print_fwk/test/unittest/fwk_inner_napi_test:print_fwk_inner_napi_test", + "//base/print/print_fwk/test/unittest/fwk_print_helper_test:fwk_print_helper_test", + "//base/print/print_fwk/test/unittest/fwk_print_service_ability_test:fwk_print_service_ability_test", + "//base/print/print_fwk/test/unittest/service_test:print_service_test", + "//base/print/print_fwk/test/fuzztest:fuzztest" + ] + }, + "hisysevent_config": [ + "//base/print/print_fwk/hisysevent.yaml" + ] + } } diff --git a/cfi_blocklist.txt b/cfi_blocklist.txt new file mode 100644 index 0000000..328142b --- /dev/null +++ b/cfi_blocklist.txt @@ -0,0 +1 @@ +src:*/base/print/print_fwk/test/unittest/* \ No newline at end of file diff --git a/etc/init/printservice.cfg b/etc/init/printservice.cfg index 4cc1991..2007513 100644 --- a/etc/init/printservice.cfg +++ b/etc/init/printservice.cfg @@ -27,7 +27,9 @@ "permission" : [ "ohos.permission.securityguard.REPORT_SECURITY_INFO", "ohos.permission.MANAGE_PRINT_JOB", - "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED" + "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", + "ohos.permission.MANAGE_USB_CONFIG", + "ohos.permission.MANAGE_LOCAL_ACCOUNTS" ] } ] diff --git a/figures/print-architecture.png b/figures/print-architecture.png index 10a97a378f5720da1ba574782487a05cdee626c3..7bcd0826e45c3cd7461aa4c93f1341516dd09e21 100644 GIT binary patch literal 20038 zcmd^nc|4Ts|F=4+P#MWmwq`1n5Gwm9jS$glU$R7H-`AmJYD9zzS*B#GM8epKFxHWM z8T(*}nMuP8#+c_Go%1{Abk6U2J>TE+{r;Zs^E`j(ZtnZOuIqDs_WS+$+;_w!1MS_M z2RPZ-*mmpcz^<^dZG`}T={vUrXXdw+d{CW83qY^|uA%mSfMxb`hrwJA2LFikPYzy`b~L!BME-t`)4rO2=9=9sNXe zRo?8FG|#P5J4`)~?cN7!IS%gKt63&>tBPH0D6$A+*fl&XYVcinoQ=o3>sAK*B>l6x z>oAi7EXF1nE(64ki@D!^2aNbBCLg2L^))Ll8TG z>wDrgw*jXg>Vm_NNaW`X&{-I)-sTGOAOtdb;wTIl;*q!y0$ftk|1nJb9~rjedrS>n z4H~i*yneLu0n#4^%&1ByIonE~~mZRy>B%MPnF?R$lZqnwl#& z&-^BR1)$DIJaLgW7vPOsO3&dxciW?XOg8fS6^q0$af=0%zxLrkf%<*hZEBu+jjhkS zb5*MQVW9;h}Q)Jj0HoRFaCTOQBXvX)0Zng%5Xph;JeiMF+VgVthVBdFEU zaz8txYc$8=4&(qJ@Otcn$m#N~bV1j57RcGHwZ~iHHWrn&&SRmq)Mlb)J^zJ``EqG; z5P9VB`21=yk$wgcnl)=&wIkRTx0n8`I*Sh8w=0C{2@ou$$i?&Ot}e}blwFrxSjOE| zVTgTS4Yn0xX@%-r(4g5}zcFd#BetvdFhU>wxXaW6Z-q6|AA=PuhSA?KLdrEll1LYW zMY}_aEQ{^vI=?MOm4%5DA$b-I_|xL8XPh+nBls6qQDtTfcBmuD#8~q15M_J*JNnCf zDN@Ndo@htUJ!DZmnlKLzkRj4Ax$s7edC&CL-8^Gg0UZw>Dv^OrT3^wsFL@5w28x=> z#RIn*-F;Rq3NVC~BC-jxt%fc)X(tQoO-D7D)Q}di0Ix{Xp?gAON+NM*4MF^R5#>RKsIqMzawL8cQIwyW6-A874;0iJ&MbysxSd!o` zNp}V1x9olIHPQH7b82cy5O)QjwrN}a6OJdhQn?h-`ydk8{|89D89bsPDpt~gDPe5r zKZ%gXrf_KenMn`cIZo0k)RmP)e$d!R!xVinK$V<+PP{4nCvE~aYRanAPId;KT@4)0 zMi4h{*1*p-ZACqJq2fz>z7{-g4MZ&ywNF1UzK>p}bU}RIPmIn> zu*RA;H!vOS6=YSD0WAvC z?`aB$C<>5Kf5Q@prFR#iPJd;hLTDmAUS=;RrQ6j%#VPdmsBm)bk;yuNlHTp|mk;qi z8n&nm{X23BC38679;cgeyQXp4r!a_Ryi@^Yo1fY17pKdHQhI`3;vp3qo1 zx|YV4cc@2IyEpI60tFEM?p`1MR7cKO4u&iwi&52pkya~ACOB~=<-~F{@Rs>g{xam> z&!T!>B+W9&^FdeWLwSJ7H-&0Xj(~aJg9YMToeeFKDFGfWEXQ%c5wdCrtrJ^{E#MAl zFQ9G=Tnf<`Is^U~Q?1=4wzqr9V%u6utGZNB=w7u11qV$Jghis$F7*q5>5Ha=j+(zb zaNIzsCr$89C*T?$E4(7xoUnS2IkCYM-Q{q+yCzKO4&Y+sKOkN!bvSN3wDp-SC{6Mj zCU>7QZfQ8G@T&BTOx$X%mGR@%w=8cWnhgrL&weL$jrW{1%K>?acX_1UQZd!Rr)-FU zUcUl0*G46u?2JU*R8ZLm3G_(K%bqOs!0Jn4QCzn}zTl3fyxW|n2$VEiea7X>4ci$h2kF!=xP^H3@vIYMRmwHTnzTu;G z(t^arlg)CY^G>uTj|_da`;{LOj~_-%H!{31&eM*K8};fzOnrfrwna;!e8H+3*O#M{ zzJ296Z`HW$`eK$?M{KM@MbpF|C`)>Lt7Ldm zkG|Rzf~K$|T*H-HaoZY{gLbnzbWK%tPj^V`fG+z33-`R#&vG>+TJPgz)$@UR10>$5 zqjojlhQycTTGf;C`$>iU%tJRPk1oLV$eE$};=ZJ@b@&M*&5-Z{JrbO>(&&=UWBEEM zKYdX&IX=TNjBvaC{lfEABx?Tk8!_<(VQ?ybKQ@^| z>#@a@y=JF|fJ4m}W6JoZo$ru_wVhe3joW_FjkoT(P}bq6Tbm2&>Ob)3qT7K8Kp0| zeF`$tktQW|6~_vOIQ%|{mE==puAZ-KL_{<6o9(5o-^CyFo|z8ET95!ll}KV916@Ea>)$E|(;m7R#6N5}Rw18qO>O@fNTD zG`bKnY!#5g7bsk*dH5FQ!%}ULkU;CB58MHCL_azt%8n?i9Q`z6@6xj2{kLQr`BFMf zR#wA_m`I!%h+DM$Ow}EBn=e+wrg1blmHE3G%q2uVV@Sg6tvTXFQ&P9YZa*|)O76FgtwIg>B=@h}%S=r0j8)Ap z-R0fV04ujH-Kf<35xJ9eJ{MUPVAbU0>cKrauW*Ce;hTyO(dA(jj-yEI_KSJe>Yu#m zhx^?B+^e0b+4>?Xz8~#z^VPthVY!21YULrto-E%LN&K?)zPFeh1E{lkdyYh zWmwqaV>yCpP1@=UE{RAAAcYGuX^B_G1E)24Phohkj4bRL+1QK|T7HkVTXhO1;kS$=IGt$R;ag)~)}NWNZ;y*(wW-kDyJY zhU~BYbE@}wze4P~R@;S8&~%N@`l2Z^b3ngs+cAUQ=xfuP;{k zOYCmc|1ev*J?Y6y(Ct5`i0+O0&eAGt#r9`SH)JJg z*2`SYWY(k)+4-1L=jTeNLS55@W#NVVf{4++)+3L`$d& z9c={aeSbG1`q@IEmam3aaeE(6qT15p0nqVk;hKIO8UzowE34z_Nc91?!FyPit~ zDa2|=#;$Q(cWX*q&xVsjl516k=F$(P$(rSS#L^ENw}soP3Xp*`E9CEm=g#Xhc~WjZ zLOldGQavJ~KkRF3ycTKLMRhnEZ?G}5j{P9km5!&KQxT_CcDNVoOMdiRlu5eeJQJpQ zxV7sGju-uBkG%f^bm}bldw=Nq7anffVd$ouN7k~ zkU6`Vlp1aTv8$JPI|R_h0vrJ3<6nT*{T=r`K7_6l@r#Sy1iaxy@u8r;dCmHA03I~@ z-eK()6BBcLae2fNStAz8e6twF=%B~L-`ddU{Pd14L$Xx5SCI>F(@&{ZW&)>U`p%tIMhbWF#mIeUD0zkZr0El-P0P&90=-K=L@tj#8Ub>L0Vix;D<&rxR!!ozHvdYx+H3Hy! zXxDMmV>|`$z1YIu9nB2Q`cX_-I}6UU)kskqleYTH_r|QXwXecU8VY$kx zvL}6-Z^vAE>G79(9$-E`o7h7~Q)MqR_cV85Rt_C0cs!NZJUfD#DqkSK-NxSS-8R;{ zp$bo=(T1g98|%x}qiH?Nm5}Gd054y=?ATY|%gx!w5O4v=e zJxRDQ^o>*UO$SM-CI?9uuu7;B_vjoYpZhRUZj3zqwXTkcqFM(sR_S5L4gjz+X}(cg z(kPaYp@lgQ-YY$ni9mKAPr2acQ9`z@XZXHFXF{cXLen)r*Nl!U1&J2q?}zI|C$$}g zJ$Lezp}SF;2-ZY^MVU0a+r&TP&-XS@)~vsU^Cdd-?d^Y4iBcn8Vne!&DxddYf#cIe*5n8>)6NSzOZ-J$!l-u{L6}JuJdYi z_>p=NOg$PqPhlqLY;J~C zsV{$4Iie}U(*2n^`E)6~kLndk%I!xH+56G5l`^7)Wn-y*u)=qQlj3w$m*m>{x6*J@ zsk;YFTjo{^nF}(*!T|-0WY$0hC_owfEtj=VFJg?511vnSGItHn2f%;A#{lHp3cKp3 zu_D4go!5j28A+r0__RV6ng3A|oIuI9Q+YeT0ao;VGwQ%&^Zn{6&63 z1@+_?(FmO{*?n4#{dg#!DovJ7j8Bo~{igC0Qu*9|QV`L^LeZ$21s`@JcJ?6tBVXPG zID6vs!x2b0!Nx51bBs2r`wFpX5c8QIL3x+Vl6j zp(c`OO6KC@KEG$uo3N&IbGQj|TV%meww^FoV4CkfC~AfJbDt4Wr;h9nX<-R|Ncl_C zp}1)HhM92Xp{+i@r|6pqYVl#-$w?8uEi;zC&eJiT5>pFeS^QF4s`-{gMFpb|Dw~VP$z3Hy zJ)EeT;aXG)3vHNwg$Y%!G49yb^NRJ5QSAoatG~xZB5LjpHt-z|CD{d^M%3T1su;^| zK3Do6Wj+&h&kRr&$0XUV`9${`n26%ReGpP`5F_qJ+7I+P=!vF11fRgs8enT%HX`PC z>fT|E$Ikm8u3aW&f103v{>x6Wh6X@`9_B6uCQ1B2v;hn%LNui01SWLalSp(O$r>`O zQ2R9Diyy+h@T#dtUFqZE8Ih>693>>pKMO*$(DUUa{WI#==MjZ%0^fZE+XC=)pF^x) z&D#D(&<8&lnt3HtGsPsVxlaGmgvUfi@q;m01-TVW?mkH8VVh_!4O)Bk=ri3rkwD)4 zRUzqa;Ez4l&%49=6?}s4xE+Hntba7xHC?CnL&nsD2pyIEi4hHSj#`Mp@y^dK;_S=; zg2eMOVwp%8NEdrVUwE)z$WnU`PzmU9l;5%pXgyZmI-`HWhVVGRkA68yt}4&b=2sf& z)rh9`C;Rb_LS1b5C7$1E%uy)NA84*El1-IL1rZpPlp4>fAeO$Mnz!}fos*PWgJT!S zuVeT|c|3^w+IB)=Xq#}u@ z7wvY^HPg;Cvhe2QGXlYKh6|CHTC5B^2HTfsZ8#J8>$F63e#oWGE#&C0@P?SVIrBkg zii>NWywed7!=;rx*0i^rVO3@RR7Oxa#+zl5!xZr3yA77-AsT`|%1~JKls^??M4m;I znYg2Rcknd?g44NnR>9$71)u`4&zF%4t$%e0+BfTD`Iq`@D}3B`p)8AdhZ{?!s7MRKLfjYYldp$jrO`)3Q^?GSGICu)dpV zKtbux)u`9<`#zYsiD<6?{pV!ym+WIs~>snW4o;ma-Dh}K!^kGnoGUiCP3Lncug7B;E5 zCZtt)=&#G97J+mlcg!UW8FR(vt1+5BVOb%uiar@K{__+ z5<^HAi#c+;v*0ok#=g0=xXCOZt|Gch&U*vK{hz(`AZ0YK8*g|NSz)}Ohcvfl(1#0-0 znZBiN$zI2Xn^m@N%!Oja^6(C|hJC)4`*J4hWiRlDpQ*dbj(VXp8G0b&CmQi z!=9?081iwQHnD&evZrLYCTzvOp0;t5D=epFCs)|?2-llXT_Dhxwvn*_vK8>7Shkbx zQ^Q=r_NQj$zD37j_339Qu(RU=r&tit0kZ?*Y;3pmVots6=_)>y50c|rS?|>UP_xw8 zwuU+UAS~?Q8Y3nF`r;L65d9}%7=ZW6tS#Eg2(USL2#g->6q4r*yFFGh=CIV7e;fSK z6Z`TmP}ceQ$1xAhD|v~w?*-OZ@Pagt2=gyQ+x#W2xC~;iZ6iov+srWb1NRkh`r=xg zs5Ut6=Iul_wwKZ@8JMd6hC;Hj$ru2%Uh9kY__Gc?E4CB#rM8Tg# z`9GT`r{$}L`hA;vyE?(M`hQ*l#KYXZL7KeDln#2W!erEzyA}dQk@-fBmfCxqKjd z4ElM^0#F41fs#+~K~zg`f6bA|(eK$0M-0i0(;a&r;vOe6YvbYlheouP4P6rWVYrx8 z;YF1CC^_3EKQ&_3P;LxbGlO;AExjeuh%@T8|Z$<^{g1P{U z`vbROOLco?jV^C_DR8oQ)}PC{yh)mi_VGlLCfFpAh`w>P-U6v_{f<)4l^SBH_yoPo z2%vEa;IhL)NX2-5d**O6{K9Cn4lb7D@`;yh&|nuA-C6H|`c8U`d)_VKFUvCJkG@f_ ze*o2YbX=L@-PGhkgGX17#V<{R7?mMDzEbs%4gc#STlvf$zx1l@)-X zN6HM}9!%_zD!Iw;XU$wMV+`MNT(;!Qcd0P+Ur$#xDlge`iYs;m+ADO<-|#0gkyiF- z{yL7^1^Ok$$6)Kw^IE!H&sU*JV?(NtWXAAqLWHLMyb50h0!h?cBk5gm1%Dis;EXL~ zd9y$A_PJI_YA2#8xJ_N=SUTFf08}0H1pTbDW5l=b(JzG~MOA3SrVy|#jU(@@xT};) zP`=?lh-3CoYBZ}Q?g);e>XxXNAYG)t%*nZ$2U`>!{JOP{9=O$GG8g#|%+hJ2+ zi?f2ivtL&qtXtOa^-?ZfypHauaYl!t}~a)*3sYB%EqFrcDSN+=lqU``97_nd8B4Y zzX5$8GII*5`a7AhwZ{s0-t~L+=e?Y9TF_SN0e{Q;N$qoxYo(fN@Mps@rflcG{F#X_ z+Yzgs zF#TWJP6%KnZKPizXjY#h&Gs zV%+HJY@a#-xLB}_Mj$RO%JJ>1Hf?ACV2{2$P!hekyIST!7K3E%`#EW~Tp)^<%^7gR zCj_g;cW{~Ew%VCp6r)Ae)h^9bOX0(!C?}ECjh_6mtc|oPkQ`zVULGWR)yC7jN}27+ zFNmF=ZggqdYs!9m&rbua|Mo=HJ3loe-#+?qHvGl%vgHX{RQfM3p#VyKp9jeEOx$a@ zzGp_>pB{<(<_B9)J=%RX3z=BmC!^5-xOS(=cT%wGg$mI**S9fuf-D9GLfQz(QLU!g zAI|-C9FEXGOpTKMI>Sg0s`7O^*LEt8&t5@@5Qn9hp9tZaC^b+UbR7!4O9R+`;{?#O zD7_I_a5+-H2=suf@1whH1ET0|BjSGBuMV9(5^(5y(KNuJKjOz_kFNnn-XASxyFRZ& zikG>z4msxHNE~fkAeDH@EUru?a+rI!RXi)=az6;5@7v?~A#>@@{K-oqTdLsD(=1PZ z*2cdYBo{ehCZtL{f|;QzKyG1D6yS;&^m|piYJ;^S`~gCQW%mZd@^5669yCT7TNC{a z`V`IOF3g&d_qc1H|GnK@(dBF zgGz*jrJaA?iV78593X1$uNxXOo$0$}4;xG0mNW|spX5rPo}dnE+Skb}wG@ZJ)C>f+ zEru=dL3mv!dfryIlMg8U@Yf+F9a9V`7u8$Z`$sVAh+&KDF{5BI8e0q(#Zg=4r-@rD zH2_lGAybeYY@-5z%_?zI4+(z--Nl~)sxA* z;9sav=BtkTKy8JbZ&s4IT>1Q~uq79(T^a^-)&6VSrT07^BN&)8$=Bz0@(O~ z*7cw^1ajz`29tgU*!M#ETXojs8IK3@zrC)vvO?*{;qmxG->EC~lNvhoLy*2W;Q8|+ z_&ci}6-s9ni!QS_k5z}kd3c;yD845+oe{V$&v%GbTN;W+vMLp@VM*99<}?i>w&6>2 zjp$aT#?%aw@$fi5BmG#s6>}Q3;e_<(10G~O3PEyO4{3A=v(gZ8pGiN&YEM7O$4m9M zMCMG^xyi03O2D(HW2}v_G01FI_pbsc4=oyTR3*+&w$io%!0l8e<7-u=&L$)MZvqp_ zF-3T2*v3b1KO}0rh`@1->K2gGbMSrGNMynjV7MYztm9a7lN2mB#OB=DFn?VZ5wAfJ zp$T?O>&{&G$wIT2l0LC@+NY4lPl5ZVfu8Ffi#5J-t#`+<(1NsgScv!$h95~<7v zS%(ZiJ<#G_pfoXQVG*81zLQHL^U0A?V>Hs?lYXi*VOn}TVgA>FH45G)i`5>4oCj{T zW&K{fju^G?l$(eHCp zEkBmK%$NOEB&**72&wLJffr@i zir=sXU(7EH)7&<0yY#|>?ao!z3VWYqD=&7ypEb;$Dr4)(^7U>0db(I+xY}%=J)@GjQ^r6|*dod* zp6iUuzb!#ZF5vGzO#k3vsMr`aD8gTCE-}S-T>VDw_dhY<(K!Lg7>e~~1_n<}l2NBe zb^&<{+8CKZ@AEX(y__!l%aJ@P?1}{{_+c{Jr>AB$V3QAT*!t^k3X~0PG8cBBW%wEaWl<%M;WDM zhcL487N>ZV0wl@ZsmqD{u_;=$juznWf#QK(PM-Uly^@B~^lbe@Fqc&;)IXM+A-CbC z!~!oyckhCaD1J1Kweo84;NoF)V^4O@?yx$LqbLi@svhfIH9F8m*XPB@@|ViDF@n*v zKu=LKAX52g358;Xg!*sm(XV}dgX~Y`gOZSxY_GxWag*2m79IndFz!52Idk3fhIF+R zUw1-DaV2B&uFk#1k|d5Mv>n6m)uZb=F3Q6&2XW}pTX!JWahdE`EAsFTW_I8JD80^JFI(C;A0rtdW%;a-+u@6FUfnT&4SKLGKD)1U!AsELl?(z!=pjaLs%MNL^UBbYGy+^zPl^y_Gh3PgF8_g@kN6cY&g<5HS`%B$1olk>##T%jG8P+ z!Y$?>5u_BQ<{MU!XOvupvpwj8ZX!uEN7sJqeKU>vxFFiM{ea~iYHlArWG54`pRs<7 znl_Qv;bwTpu|(Tw8NNiw;82HlqHp7$YN?7|meKBX%2TojPa1A}aic&k@u4K+C^!wa zenRJ-Zb?IYWPtzuW*v?3xiXQn%y>A1+8uEmtOQMcvagx($aLwpR44eE8@dW8YI!QTg<(8cZKAC0o1A8H)~gOA-L^` zT&*1W+xoFE-!+Yzs+`mjQPXE>*6LZcrxhH$45~Z?b@R(6?;>OxXrIO^UVwQ#37q;N2DY*ebrY;-KS&SjB|; z%FmQ{CN7TS6x@rUL1JugucJyip>{nB^H4LRymz~W?6C>9wep8<%iuegkZS8+?6*m# znLI~`zvzkc8jR>hJzZK>Q-~!N%PrQ!o|6hcsBEtopupfERiJ_~T=jh03Z48IKjeW9 zt*vUR(&*gNb?W$P&bj>N=_;hcsaWNN`Y3n^pDHoeA-|u3i{2#RqoY|GB@l4BN+w`i zvBMs0pZk}_cW~#|a%%~Lj-Hr14K$-!`S4!CrWc$pm<@$Wy7&oAvim@srR*R$mvaSF zP$DslQ4HtLpeJ2y+$J4u?Jn}5H)Pgp#V$!Xy4j;s>9#z%1AFS|Y5J8j042mH@<&Gd z-}f*0@9fY^AQ%_mux8XYs!WI5p-p|#L*0g3JjvbwJahDQRt?^O4Gerrp_ zFA#R|5%hPqcW5`DrSydk(AldiAzvcxYW$+9l1xB-K_xc%;!Y&e1q^%_)qUW546=s` zg#g0R^W@ZGyhUb)t;C2vhw+4EL%cP)rzFV#Y`0TqSufgO*e@ntA=U=~Yl-ODv^ig2 zvKoxDS? z)$_Cyi9`9f-wSCp__BfOANe7qp*ej^D-mar+P~-l|*o#8h z&4>3G1OF*)KKE`dlRi1rlH7#GnVg^nEp9wRixp)Km!afIqtfDtw2IRuF^Y|gtG<}v zkc)wd(;ma>25qoLMnvPWYH@_?p?T;G5bpN3`ewEHXC+yGz-Z%NBT*6;F#w-OqQPy> zt%MS>O^==r?QRx~pcn}OF>%NG&0asPG#Hk>-+wz`>fc<2HE_QN!ye7`h*|rAlDi$2 z4^u*ggMb?xQpQ)`|3@Is*t`8`n}2MlK78#CFPfiuwPCA$-;dxxP;4hKs_4-v#n#Iu<=wn;&S|%u3K{ zQa#G${H#|rkp};0!sZ43KE`B>Z6@{u*RKcV90>Pg<@yB`6jjKNv*!QkoFiPnJw@4F z??_*Y>Wgy}Srq<_Oj0=8iRXPCsvRnylxKfWpV)-|n3R1g_(Nv(f9WNA3S*@bc=wfL zy;hM=Us@)54RMmU;XfJz>En2m#qDTdi^5r;&ihQBK>EUd#2TWBMrgNaHBcoD5#MyQ z_p1xy9m#TtCYEop`?g$44@j=8_YyzRp{-peCX3~}Ip8x6@zMt(lnDZkR~sr**X_!G2h<`JGB!W(E_Vp`Ly3IRMQUS$bNyN&wgxO={hILcUJ zFJ~+quz$D58@Jb9uwxEjj>5jS@qI7^==p@uF%ir~D5$wAH}2cg-9MD`(Wu^yKB57< zO-q+)4{pPrQ#W3wTE;AuUFpw2>v3mQJzovpI5lNOFcK2&tSW_vu+uaPJ%}VLcv&@) z)?i`x#o-KgC2$PG&>bpft0nLK=B1L2W1$Dn}+D7G)d81DY4U!@d z)~`rz4q~}wS8%$3HnX?z)zuGUkm37=lIirwd|ea>GV( zasf^$|DjZH(b?C^_==Fc@gY3N$xjxB?xKFyr(>?_;GYJBrWeHJog2yz2a*=tM~a0^ z?zHu(f~hy&>n+i(b5{o`VroH!t^kC;6Nl?4!#UPicX>VCyQHY@G3u2t98)zPh52k1 zKQNdQ^nH{S!I_0RQw)dLxR%^&-md#%3vDcg}u<+Kyv*3_`KXa;4T~G>P)& zE}wA5vF!e-@90^%W|N&p6pe{#fYwLRtzWNhP{@S|`QLn)WtYZCgkh1wvHVKS`d8#6 zXpCZ3Sx2gSRdT;F&=Gk`)RZ<=#j@PBgzE`A3_}$vK>?>t7Jn&KWAj+S@8}K|Q>$FF zDkXb~u2h{C_atdG7U!#fqYqGKq0>?1#;u6=&)+ z2Vn2yHZudwJ`6V0=mI8xp)>_L-R5=FgL&8jwOoCcPFF@@pA5>*DYx86lUh;?=oo2P z&a-w59_|b9B>ga}PHhEWF^w<2uS}@TK_GoqO}^ZrkC;Y=oC}OQ<}LEI*J=j$c$b0T z=xlA2z!~!ZS(lp@1XrO4DM1B(#Ko$(%l(3B64iUWtnx#fSF+&UJNpB^5^1?~-pX4gS~UHV!XPmki>->M&249%yG#yf1soHp>B3X#PZc{F>Ipmr zNeLTyu>-QQgjL3n`6n8Iv%xAfBS^i_BX!YZG9U}zOQZiTbo?2^L(UQj)5|ALu5#ZB zuBIFN=kBu=C?8CHXr@9gk_(V>S1~t1>Te@lA#`#_J4umMN^m9v6#|dmJ0*~wMU@%U zq`J!w35`u#P&Aqg&zC^TvsOZ+EUeLGIoefLOuy0O9!e3*uj08oo() z5KA07!j{mhrhmL96L^`bfmd5J2U7@T5;8@AR#FHDNO*w6lxKZo&O2giQ>_=W>bb853s=OFshv|fv4ggu}61*1jD zzP7g+D%$;;^{Jqj?57m;jb0tG=Zn^C&%IE-eg*mIXik#NM^0(*JNJEe9IkgwCunXn zINQD}{`xHrQ^e~_3h&}%YW6|gIqx_m=4$FS9TP^pFn#8|3UpOoy`=Ejp3h9vXhO0F zSff=Iu`?y?#eVU3U-o|F)PCh)bi^_Q(5-zvZ6{0-&!1dZ;yhJ&Z0@@rcx(1chX>8a zio$d2F6Sg&*G&Mv3Ze9GOIqx%YLZw?432=ug)m(!gP4K9zO`H4iqh!`41*cV?`I8m z8@Jz)olJ?X@Z4k}t%@@?pN_}daXzL<*RgWFQww?sran^}d9kd*&@eeXV7nXYnCb1&W=rKwmeEfmkb*_Gzbi}xYU{69 zn|j@`q?GO;E(cwTe6fGD_3h^e?k8vS=6O#O{F8EW&4OXY*ZHw@_^@GJHM9CVm9}>7iC25a@~UdJ;#u4T+(Y*L zvKtGt8oB=xC4|qwrEQ{C4~cmf)sCK0s7$?%2%szadHB-0I-V+bRX?uutWw4w8*MH2 zU7$U1x9IK{(QbaTL0ZivwMmpSRyKy<(XqW=H%LBK;Eyj<=?r}}YP@dSGPiK+d`X8a zrA=HlEq+ra;mI)$-X=Xa+;+Qvzj|va;N|X%l?M$5ll*NzMy-K&3>GPp#W%u*iM$1& z?S|Ar@@sfgTfuErYt)9i`8=)BQgoaP?MRbNtt#3#7~nHxJbiq2vzT7Bi+mSBm5$#nm!K+4qoJMMr;Q!GTcgRs#dR zW`??%k)h@?fWG}w`-I)po3M+Pq>!TAr=7iNA7ft=uHQ$Uh`V<>9#(FO(7q_{yVrEL zj>_eu^@SL&}BPa{9>F3KmloxId_Dx5Kt z5-Z|YVc-q6mnSZN7 z*5ezVz4&6k;rdUS_206Tujh(5(Uq+IX5gD-?1Q+x0_{KdgDW0DcddRKE}pqD?|Ikv zoGRGGi@=qvK)3|=cd+H$nYS7N<>G!bOy+>^sUasZ45H&nwWCS{Aw-M#$y5p2`v|#^ zi^4k;Cjx{T@V<@L%M);fF)`HfQRVDMBe^ppI{@i0Mu;)mE7{53o(kXye(3d)q1}`7-QiQ!{r8qWJ4?JHerdsFz4yFy zJ-K8qCd;}^qA zuB9r?oqoMTxmvsdEKXB$Gn)|Q?B^Liv|R4$q}(S`qMFxPbrL9tZzGHa8`zF&0Nk}h z-#g6U`E{fDRZEB4#lj+6&-x0ZraF61)HpEM%|G0w#|q}4hlW#r4xOi z$4=wMDTQ?zQ_Ivdvh9lkVG0h*DwmKwJwUX~IK3wAJ10@5NXTKJd)mHL*gw;RjgKo| zPmz0CODW6>}6ha}`)L1qZ6XFmcai^_?)Ul((bhzS!2 z6nFX&hBNk39NTwr&0VI80Ky>0UFVEN6i!|9Xv|IHW9)i6tepSd2$}i+N|gO)CIH0W z5V3mxx52t)Qn9(Vdd};&D|I!j{(}I05{z-Qj}X1vWNZ80Y%+ z9l+o0x1iTN*x0!5u>RjNbVJyOjm>^VOXGsEkM+zTy6Jcq>I(`v=LLn`cUR7RE#FdL zny-4=I#KA`mIqqiNhN6?Ij=tp0`)j8a0`@A zf3eCWBg<8FJab_Hwp{IY^336o%dbA)1U?k<4WVtUf3W^8dLIJ0|MSA-SG!$#xqsj2 za_d$2i_Irk*B`);p!o{&N+`WE!{+2;wUrn6i4x5wbq3}bFb`~^8e{Wkk0@T(|DGf_ zj$VT(b=VLxgKE^*KdL7P3^DKGnX!Q%*ZVrK3D}Jxn>clb$2Q<8+xyiU&7@|dR;!al zHB_CTPk#*kfgAd4G95eQ6jVdrm?29mG3!bu*zsjsBrDWSw>L`KV-1Mi%2 zjiKwY%+=*FRpx43Ij}TrYzy=6T6B;Hc-}yUt4CVn9BfuDda@RhZS0a-y!nzsMrHWQ zd-Mjl_Q8%j_O4`Bl~)?wgpGRV4e7ZoXMi=`sexTfYbgc?QAQ%80=a|>`E ztW_V@!JT7J(P!N7 z!#6zW$)yRZVXpBy)@99=U%SxT&P4J@m`B7#^hEHt!=)~d&N)6s!J&IXI-W0dmfJP4 z8cm51KiMgeN@%uReJ4Hkv|?6{sK&T|*bGrI@;;+E(XG0x@+*0Y$aY5?t_g?2wSsZx z;U6<(>o6e2J0hZy8J20`Pq;8!r~1|~ux3BCxnL*%kW0g>dc=}W#*Rmk=1-SI^!B8t z{UQ2jv~2>TXn@xM?cdM6!xDeTp;54W%}~At66H-j$RlO1e$PZpx7KToP0@d-E`dMt zVunkbyj~+v&E=Emt4qqJ++*Ls+P^VdN?tH)z={UT=i)kd^#!AAc)9TFvp6B zyJrVc*la{*JDvSfAZ}+h)LHA9BaV+-(ZBFv5^MCbF)9?!AdT%%-nmP|lQU-rUa^|@ zo9+wTk_Y|Ut>d6azi)MH+AgXH=@)w!&7XI1bgr345*vAO{CdlRy<$mP2;_qtFy6x+ zN!g=xHlsa{6gb$4K!1)+?%K{DOMw<@=ws{$ylc8uYQi)8 zBM<_8;$XpJhVL@uh!VKnWO&)0{o{#Z#sm9d3;QmnP%nkL+zT%u)H=b88U_F0 zuSyz8ZYfvXHJzI;a-kad{`U;xvNX8GMfl{dJ>U}WuJMc~tp0Ruf&K(eSD*F>S*Y@U zP3l+Plili8aK-)XQjf@^82Bfn>QA`cE)O^{oCZg%c18}jMe%ic-l-Tful^pYm?6_~ zeK|+*j88?No~q$dSA^(ExIlHtA#!}&uzzcPs-zXdWzAqHC-0TAGmSD;-9K#-J2BT@ ze1rLAM*rg5GJ#_yPe9ARI??CE1buX9-eIq*H$>7-h4Kdd5wu;QHje#S&m%WPowsQE zIk&{^GM3)Cy{~dI>ennL21nuCS|D7x96Xr+wk)um!Gis5C6__&ok@MoM+i6dh4des za-a4`38{;N^HG0VD_4t>V_%o>=+)^RIh)v+CzV&amLiEA*%kDV6H#+eZq)kcv^N`q zBF+(_cD+%>wGwu@ujDAk<|YO@T~{w%=lv)N9W~;}Hdv!&q#ImTv~< zTz63Nd)*Uh_@^p<>T}uK&KF^2kPqD%;cc%Q4WYJ1A@T2?xU4AL@OOYeU5FOFS5h5y zUa#D;ADlmdpHyA6T2m+i*6*_O{)^vhfBK)`0d5*!M&pi0R#0QH)tMlT?l49ib9baJuDWXP zf9fC!-CJH^e$y}SHqxlv(rg|Ax~C_1W9zY!ul;fJ$ry>2L~^dxRWXa*v+X7NTXSVw zz4TNTTw+`ihUNiYGyOe~+ChHYB`!SQ&;8(G4mEc5)W(a0pZ2E%YuEd?wOatUrM!^F zCu~0$RYB9TC2fy}ymWmAIP5?$$bc?FR4Br)g=%c$V1Jh^$HNb7xw>bwy1MRpgu-l2 zRrb!jb<%!X158NzS~PfkqgXk5A>|?BFB7#V<2#osOGOyi8pe}cqPA&3BeM1G=H5u z4nZ~enKO55z7~$%FK7~tbAI`49`kTR#w|jHrfOnc9e0QE96$YL5qIalY4Vq1J(2!V z9#v1K0Im6RhAe{r^gVj$Obb8%t!iqu>8i#{@q^ky8Zg{ps}qLMoCb%aaYbY4TSO&? z5u)~d`Ln{kX~Qih&igfkN~SIc=nr51Gf3i)q0#zZ3_YC8V6GdM$Ddx&X0Lpm^5Q-( zclOXz2$l0AEuQ(d>NCd#miFQX#v~_*Avzq3XuRKMr`ez=O{Y4!j=riI#q5;L=0!QFqujEildL(=cU!vQ$WC7uR}G0Wy9** zcqU@Z+21RDXG{b>OlC944?h}u`%+8E?H9=-D$_c@=0yt>LGCW9LdvM1?$DXV{fROO zMvf6U|2(S1<$}Dy@j1%K7a7CtF~?J5F7RcAn>&m3?{y(iH5`{B)D_OZvm0-SV{h_y z#u`I=au#|mpf}qohdD7(q*$@p5FElrHwqI`rC)bMUC13KU{n=LlAY8enhAwjVX?Bn zd0FS3L_!oY=D&YvRU&c2-tcE0jKgSi&8VZyL!u!B2x*83s&%NgE|^96)684nTyY;i zRr2K38B8R1>A z7?HOpB#OAqmA~?Z!M2rXh(3_w<$kk7!TSnN)?OZD!pSQd@PKMW#gi=+;rX&^wIiq# zqD9`aQ+!6s`kP0L&xsPpWf!+X+u3aKu*dKKmo*x0qThz$j`X7=ubjv@AgD*os;aJj zc8GjvR#7GO?u5H5VQ8r`4%doS9CON1Ar07MCGbc^)k-R3vqoN>CYr)e5!8%{(Kdk7 zIs#71SzB#Rgu7tx%y@%;K?N^R1bVBxEinnEa^nD-UeJY?WlQye12SqXt1>VmubsaX zbM^S&J$blysi!Y(|qVlM8SM%zx?tae3BZXS~ORuSS2gc@|4g^9@DejUW zW^C$Fm2~N^(1Se4?fdzPtc+x%sheK|0TB_Hg=?p}-%1qUnx%JYTBGRs-dkZoH6reI zYmuU_R18m)WFN29uurCp>|RTkQQi#z7&30q|H4hoPfL#W%_kD80>5_2+R*sds^LT&|ZKX6j^)G>q2Nc7khd(K)`RUuv z=!E&7HOBgU9wT<)bHXUyU;ugKnm~C|Rf;~TXWo?Inhsp$i>M%Gs?dv|^%USZs-+9SW&l001?ZCl}dJtt5{`iUmR{ zkLY8*ac6Sr`YflT)s<}%$=Xp1F+{-0rPe^{)#&{Kaq%rCvT+wf9be5&9?+lFQ6NU)s znsc8Fo$cwCk<|NTWp-n_6QR#Idik17Y1X2|V^3U1r_9}|*iza@-w-P4O%_$j>&JeH zzoMw(7qV>QFs_7*9}2Q*?I~F+EHO!Fi>1A9sTd6Uo*(DfGj6;;Bf36K46shq*~Lpx z{s4D3Zm}$dt4qo{N7;d+A*pNWHZl@O&`f2)<*u?>sx~rQXD9?!xjXc8D^T7GcJ(he z%}RJi-BMw!`@BFSf@?I2!hQvH-%dJq_sW@TGdio1w2U586k~Y49h~b(XN80JBb^{J zPRIZ_dSqiT3^8>2!SVQXb4zFCSsR!F!sez?F0R*s-VkWs8ZEPuIT^USDz1WczTBtG zX*)mnAYBbSlBGTV2JL*77Mqze+n{FJ>wa4NMowUt+~=iA1YnPjv&(J4<3;|aR}-*h zpJlBlJhDypJvaC+$&kRfWqKd%S(5zs-HJ-43Drc8p!6 zoR!(#a(Cr>*sNGkF*l{Yg_p81iqDIiG5fYBp6wvd=k$@1l0&wFKwwhG731B(MI#O0 z79y9H!eWE#2bOXamqxF7xR$!K&-&uK>Vbhy1@!ucYhQmMgAge97hDH(Fsbi*&iMp` z+t9aeOq~%cb)rhjoK&@EH;A-yAqQ6n_vf5)S>u&ujuiD8Bb0OUf+hM`C&IA*!oz>z zFKNS0vPphQD;bl|<;zDf0O5+pM=Qh>aeG~wwks6(9N86AqXc9IT>mwn-+tM7`2q+R z3T&l||1BZ^ojvXQXHL&)4t3u7|A)fC{{rmZTe=*&=%zO4ZXTfKl{OsObf^xiiqe)JS46Ti+i3y(TN69;HDVa$5x4xNi#aq(X~sAA)@! ze!_oP@+Shg4Eh?^sIkTP&z#zyh?3iKXTAj~81*ib^MJPuqR~ol|HX^HQ)xbKp!#t* z96w_IYsJ-$Fcshb245p<3T#Pf9k>%eL zhZv9cjDmcj_`^&nF4_IB!rwjno5jn@^|XhwRzLyJzBIQ;Z);+Tlv~G8=!b;1E;01W zSK;D%W0Oz&-BxEG%L1{--np3gc~!2HRvC6K;VRc(W@aLTolYp^al{(=I~nrw*CL25 z{mj%{Bmca6++_4l7R@4tqM zmvr2PY!z^B0>a0~QdVZ8+!9=`N2+*D!Nk&J@)X#eQ*6@#gi*V_CBZ*4s$rO3qGdbp z>Xk(sxXYLWAO`+fZlHUS1sA5x{mh@+1}_CJG7vtj79mc~x>MpWWmK(CSCH5Z)X18D z*T?|Ozbp+l4Lplq9(7z9%~rtck_1k%pIH60nh|b(DfOI%;v z>y5e3lnkD0a<)thqb0u7lExj|{?&FoTa1`tcSQpY?05myvJsu!POZ0_3cV8`9k3j5X%i z$-(ZN@Yhg)tr9?9t3GC#D&9NwoSa-NdPQR5)rS5Z$y6VcZkJ^LULGZwoMN`Y)|tRN zweAm-w>v>~X&wdxxfB>+zea<0AD_NC}6T2R*Wk~VfDAamUl3d3=`i0$=ZgtC(yX-{{4E6{D zKj7lNIKmWJV=lqpIx4FT|HU(=te|BMgR92nL5_Wvq8u-re*43}&JveO$cOR+S*uzf zpGSy)>G-{xkIs=*Siv*l@vlPQ9OR`}WBW6;kbOWk{LJqH8>rPiy2!VFB!YuG?niLlqdy) z9wKy0fU)!BdRNZA8jIv}HCpC0kFANRi96^Aiuec&uu|K(`C}aEI$0bnGMATHMXH=f ziNbEphGe*%W)3@qX1eoz`0Qs853nhjYddpv;8WkK2w8R3P@p0&GH%g=KggN4AJ)Nl z%DN8V5bh!N5^QAxz8sWiyXU$72?J}=R9`wS{~fY2?SYMNoUJq&JZo#k4dX^wOb2P~ zA)mONM@d5Bz8uEM2Y^QGxp=wv`%tFHXUzrz!Vcekr?k=U7x=z%y#fso65=doXWY&OEin$Pm|-_n6=!*zo3a^WA(eoR!u+lQ(irVZM|k>zzyV%vb(pr-6y ze~G{Ic+eKzo`f=6wau<3|1m$%AF5voHDF5n715pWJ8A>Cc4u_v`uIAEo_RhW;>RBlZSDxffJONol04Av|^EAPM#ode*RJdBLOR}q{Vq~aOy3|@HJm2X@{qYH( za>Z}kRQPMf^jsGH!IN<-%MG@4J`_|7xHeF)_}oKc+*p~EwjbvHRNfl$BK%1Y!0b4= zuC9!X0US)>%5FHS>YgNKHyvX}_e{qT%m-uF+e6o#GuC&r!3Ffd3gF9NQ}~K!dfKP2 z9pG{8miQ!P#m9YkApzWhFo~LAgCArZi^+TRDjfJ=JINok9r(EWUL4H&lj|~Q3-Dok zl4Fy*d;p|j19$q5Ic2aej_EnwOOuub=LODIjU}R2&N>k{zn+*P`wtHIjA~dMSakaj zq+^Qj_xp-?57AtX)zZpvpJ5WZ(SH?#&H6z+W*|~k5G_nvP?6*}G8Hnsi%G{e`=Q4k z_9+6b-=))|gxA{umetf^KNk|URq?;t}7$rve$XWE<%xrqsyL?kg@J1t=;kS^2 z4$vL^W3vGt+wtQIJ((Vk$4^#9bFe$2*Gkc)D?TFvW`mJKgfM;ZP3l1=s(#Z8+TFI z|JJ;w+ZNc@x(?lCOp;0ib9G{ut0(?{2;Vh^t8p_xN3o*?Z4RW%K`)9;9qR_ znZ7TV|MJw%vmESy(&AWz z)07Ex{e39`xu?>lQE+Ya&_bsNUlWNyFQ<2?p9OAa6NQc~oWjP^tC|+=C0N8A@!gm*a)>!x&_G5RTTEQ%T4Z2^Tk?47QB?Ya;6{+<7)N;FjNvpMt=QQ&I) zO##+qom4-?ob^jILV!Ta+V0A%2J#i{He@}|rvh_KopGTL2X+5&ib$mwtysm(poiMp2iTURGwFf^!J0{H4KJ<9h*HtW$^ z<=jnc@7t0{OfD15`KgAOADRR^a2EEia(7U}M|)KiWF~dX#6bcU&g!)pCm5 zY}wa`sPPERgILuo$8qy{%d>Gn6n3_z_bqpsALeoAvV97#&mFz82*QEnL~tTsECqs9&#shoDec=&yo*;uCXIbujh=>Tag0P+=;9oY{WRp-zzGWGrOnQP~OZ=e8GDHj`jggb4 znO*=$fBG?zKCNAr;VbRKE%L+s??l~`Stc~wH(iBlXjmJ~JlrPp@NgkuoZhe!FxOub z8{?v@%K-tvQSjasUZ*B*pnuF1tA95cgz4&}6H5}I^2O+_oDN_wIL`yHw;KQK+C+A? zA#^*0debI!{{qO7O6mb-{Oxrg0?q1DI#pJ>t zVx4ix2*G34qx{dBJz0}*Hdan5z*C+Ba~`gB#4l9X$~x}AT9}P7>GMoN0KHuK2DV)H zF<)x}L$w6f=imu3oYpb2p+D5H^y{8BjG18eS)PftN>t;k-wre#ay;~`fxjH7PA`Q$ z7Ex1%zh<+&tZD2a zYTp&;(IPr8H>c`??pwiQ-HoRix1Yt`PU+S7$Aoh0P{n27w4j!9+vAgbSAMyL3O zCM%+Z0#tEPdETAV24P09JSOrY=w4g81@u|GL$?%oCnY{b@v^RBtFs6RA1%m1wyeup z?CKH+Z^ax(edEJv1cFY;+@)(Sky7OS3YT)cxo5_^yxVfrW`b`s?pJl9zE&yVp$?6) zGC4CmJJ-~vUSe03UovbGS7heW>YPuwSE7pIrp^wn%EoHD?P`cMtkX7gy%p^Mq44AM zQzjA-HP08CL~s9cHEkQK5Qs>)c_dMr&nMB--MQ)$vYqnCdNi04g}GmxTC1Gk5~MLd z0H^y$8Y^zpJeU1PFC-O(>>ZlFyYNk!Nd0eJJPzD1CG(IrLfc_o!B%QBy2&ooL;FVw zId|?EY*v-o{x-Ni)H-+eiy9EwCVGdnw$J55O?@DFew{A=M3U|7zT}NdPOmPf5mWAPpbgT@==t2?%PCd-)9kO_}IRy&Wo{o)P??m+p*B%{1p+WH!LZyeN|d zbH9P@J-nJVG?gnpgc73m)p+0AD}Mul8EJl1Ye}B(cEjhf=T&{5464aj;gKXhiKaHa z6EqsqH(5vB;KBcWe?m{xzbbpuCHu|9kdONfk<-hjna?@6IQ8F?(#6-BK5^#V({T{^hB$gWMP~FDm3iO3yg?K^ZNlH}Suy zdlb@Mya4h*P$~dwOuPuLXBdwtkcWXYnv-5RoZjVAIA` zg;IswV2B9BTg9iPasnZnDJIN6tSRi6AnV?2eO4#d{WVuv>ZK+Gv)P?({qO zyx|}STpj=>ky<^&LRPMO-#;C?LzWs-)jVQ4BE<_F{{t&6xru-X=r7tDaj?R}fg>Wz z35|Sa6ti0^T6%X-BOT})GK`wpIH~VSh)~tlr-#kb03ebsW9K@U1A)j20?20IWq8j? zs?<4ZR04Hvo%+~qw0Kt*SYc>sLkJK`#x`%J$uV^rz(`-V;Y~_1^)|-9bu5id6HBvK z%CU(U093mDJjiey8=fDd=kh^}XA`NO*4X?CTIth0ZKG1H0g~flWqaqr3Tff*$~H5; z8&4oxt2d!))4rhX{+q})4#dH}vY7~;yvWNv7s3L+wvWWYUw{+^K*3yw(04!*0wC!_ zFT?M;{px88P>%qH@n0ImoTLo}z7sqbUKU^$5ZD6D)+Z({m!Pm5Fj?B6LtHfLc0v64UN6Ipadl$ZWH^J2CvrYYO=dN#%+^meTgEG#SL58}cL+jc3#P_fqENsz+F<4akRD<&_aW?!;#h zc-_Vdldf4f`&4?VW*ghxbL%~5rr|;#bAy>lqI&8Uhkqh?T#?)(lhBygd_>(z#t%o2 z3h_@~jLBHXBU=+xyS=mn8Zy`org#i2jNiZ>HCR2h`n zxB$YOz@*kLHa2(Ef@W(%YchTBq)42G%%~1l4@lRNz>f47F}57ooaAHMyxi@7F(F#Ab;J zv9Z-qG}V?8==d4gY|^5MUU@jQQ+-F9XlDbMFw$}NB|lDd%JkmVX&Z&iQqH^2X^xj@ zam5U$uh)euOh=1mHT`c~g$l}NcohdH_*_k-NCmGc)o>KD*yDS#|~ zU#w0Fda!aNK&%tFnl%iNnnRAV249K|wiQ8M;;(3V@^W7S+3J1i8n&bR!$5{>2PBv9 zTh{i+9|9ubLakPV=rVoz=$=&h@q(pxgA>!^F{!rZwNL!DuP=#RNFChhT*N@Rb_A`P z7JGfz!gfAsv@h4H!%Th&0%sV2%SFF@6q_p+IeyIz3Q9vaoCkr@4WT^%1DBPB+_cz?VB!qqrP60NS#W_GAWf9DC!&x>IrV@P{F|kIgGP?Wy%Jbh zOsZt3*Z@t5;!V%h^3h&>i%y8JaNO#~x3h$@umt(={UXT+C;;Y4e~ZnX!30#9ix(Z_ z?&iy{;NWA$hkVJ{s8jo=EMHWGuc+sIc$ad%KZ@Q^Q%+qL>8qB)^=-G70zWl4+zEkS zxP~ox_9A>A02eroH^V9rou0w~$s!PCU@~I%_wj5$;RNS`5c>{R9C{Mps1`x{j}bZqSa8?TT~UIkX~&lzIanVTCp)s&m@8E`Tm>k|90bPn-jeNSuGO3$4xLVs ze|#`ZmK6l=rUAxp_t^3?-x@0lKYu!M*O(~NglmmY`lNfeY_vJS?gPFq{kEzw{CD3# zLI6S?-8o1&kcTyMU_P{7vw^rg-%zn7d1Vt+tr^*`Iiph#+kME+u8z^6(K|TUca4{0 zQ{=Wh9QIYK`8}A;#P2*;9|vZ~(sGd}%0^1BFSvf94Fc)6o&hGL!GgKZ$P9%0j{lyG z)@4g8OW7;OclWRP+4=zkOAtW{K3VGh!H3%}?_i7?zPnUOXA;Tc0H58B_U7;7H z`vxu#4Ou}SUI5)&`46pZs|tsj&zko~mBG2u-P6t8dSY=jk4E+kdG=_G|Af^Xyue~@ z@o3i>R8wh`u1_K6hU2Luz2{iH6t@%L>3)xdn2Ay*V@=0IZFdjazZ6wqU3Ez(zNs{s z#}9wJ0y@1AYrX_|8JK63yf!5!diRQD>*F}icYgvR=#eMy8-gB6C!Z)e$nyFwPRw9C z)1lRY5iR;HTC2)e5JOd1n?W--xT8g0)=d^pcxE1yn=Hu<)Sku!8l@Sv6T-ih5(42{ z|EOK^fAZUR04Vx!^d3Jij{+c{B3sGw@zY)xD`jRI$joRVSXy4y_m*F~)7zE%uGw5; z7N{a&#gLa1WeK8HGizk5`kH6)k<#Gc^Y3H492)Q9apS{s* zg!GI5rPDKn;7a4YLYGU`UVPk>8_N@|7U`DIPMeCcg~)=<_I%2VGnpH!81|#Qqy^B}R#qwFM}E04au@ss zfoCAcrQHH8qYJveT)G~eoxg^0kB)kE6vii7F|8&)V zo$nfRU~8Im0-29@s;lNR6$eifv$WSJ|8%`#z&b0BChbK$ zOF!?4N}Ueql^gH0A3je#&owLo=B8EjVL*U>$n~Q}r?rA%!eWC5T`l(tbn&}e<_6~c zLZDNSCTUq}dfdXqde+iWI47Xv>7xdPie-`kYr7^rXa7CXF6JP2HJy#8h8*k&8I^eJ zPb(T*-+||>*lZ>L7J?LBgx~aAR!6zMhQKAEN8XJ^cuxzE)3DV7dygvpEig{mY(}yI z$jjCWCXEV_I76L13vNwrRJ(R=U2&o9dO)&2DmxsvCcbP#*f9mXfsi}Sqe}aHAaYke zstATY<$rifO)KTK?#bUVMJiAv;%5Av@lt`V=j!$19NTo-XBz?46t$a{3jyAPIPChq zfD==__Kl-{TaSt_$dGwt$K7+l(exKP+q}V@80NiKW1V?bmU3U!z0~}sUn)iiHrN`B z&1`6=9yCwo9Ss-_i!L>j1yA44uzZr#Q2H4yYz0CAz)JdWCJNB(ryg4Cnn%r+$l3+x z8Sor@sufV;zrhZ%@3j!7)3SGj+P_mPhfo2$YVr4JEDJX;5M9MnYO3flX~tOK?9x;- zxw%pFqE8c5bvrd4v}we@&W@)+8t*qA!rc?Eq#A6$3gD#))AWT^7d?0ta8NIQj`lu+ z(op>hl+N{U&vfTaWdA%9Mj&uA28Q%994bbk$%3MXdV#knTw+OX(tu(Yv}dYR9%CU) zqv-y5m7514~SN|yD z<6eS=7s*~g2Amlzx5JXXg{>5QXAc!RjNkVi22h11ZF;>LKQWTg1z;E;y#6X@ek}`c ztLDQQuTu>#BsQ7FPDz5bQw7iXkEh}GQaHQ1W|n(3&HhaJ05D!dDNrUjr}&J?|6@Ss zWWf1(eY)Qj#%=>C6CEP z?@lDW92nXzj08qndd&0^Xn&gW5fz7_MOQQ*#z)z3dm%)Yz5gYayYk>;y&7!RkM z+y@YmtC8mq&R(ATEXv0A*{34_8@DWoGOzNgsIz24>Hsf%ebU?y0xHL%!s_)^&eU3d zdW@?2u3c>Beg0A=w{mF0Y1$ZKd#g|Ky}R;@lgo2+C@_TT-u17r4$RUCTsGTy@}!am zq(18S@6}Tb<*}ZRvWZy#8NW$SrR`%|zg>i1gloWSDcIBU5iVZxKe)5w{}Zwx|4UF! zkXTs4HsEz4uO>wb;PY&3^Z(!%L{5OcnsK!YF@Mp@2>;T`Odx=F9zYdXR><;824w8R zc#qx0rOxzsd`B#5%vQKq9 ztR)oIS5^7XXI?V29&7e0~+7l7OYP|_(hC;f36*c#2f;lJVztbM9zEkY> zNO)+)8#N4E9gFK5@Ob-{1GDNOO=z=|MX!9LcCc6M%SY#Cu4WtbQ|^Q6Aj5wrK3F`V zZN8nWgokcC(#fL@bom6B7bg5!*yb%CcUS7u+(1Jm*?n1(J1#m0JxuC38!&yGF$zFs zHe@7zth`pkGN^{;ilWMhnTTBLE=y){twYB>^yB@UJlfULt)S+FIb+82>rd6zrl~q7Co!y- zF$JUW<5`5UGxdOWp`u+^EhIdZ66w~76gvc5yrnmma%xxCSh`iZ4YcX?lYLYH!g`Gq za0L>9&uF?(jCYLHI>_yD9DPzl`91LUUD+SE0~H}m~{hl6UkuCQpbqh~lUhhBuUwb{?kObCxu z0*U?+08xvBZvZ-;xC~WdE}_l_$6UGODKwbZ8;h+#(6Sou_{`_@k`WcC_mO?e4+|{& z%&G-z^@0MbPq1q0os=!Mg1p?P&x5u!8NoofleX~q<>L0&RdGFgq`^fqU7^6+Msqd# z^kN(U-=A>(7|MdNZdq7DqjeMT?wU+RNt|WY?22+J1mr&RdC}XZ^fc*d8xVP{>;a>gfE*BW%xd}%~9c93o z@a>~Dv2PcpvMbl4k}W-SbCvF*Bt_l4K-UcvfLGU4G1>Z&3*%Hkm$Sch6(`&w7OS^I zLzEn<3t7ORy3M)?&aHi>x#2gJWc*TBXVHX>X;PQ(fQ$^4lxJSDQuL;$gmJhynJ1*m zKdqA4QsNfyA$&PX{f1iyd46l0!Vec1%cNU4j*Uu-CKwjaWuL#UoQA=1hl2R$Jwz;lu=HQb3vJZQ!gwc-AC5Rqc2Ap;BhqJQzOQ;?Hwi@^coAcox zR^MH!SN=}%?wK+8V>Li>J6qzz9|6KPpf6YXkXi`aU8P?)P6TNzc<*Gh?f8EZVOXce zWIgNW3;ZJ#-zuD)fq?c$cvqo`mGcwoMg}K=3ttkNRPFauRN*6 z3Z9lxKcgTY2j)p7b!j$HO6|6VYCUl2F4Ankv(BG_BpZ#VTLJOVWBRjM6F`J_@~~=q zWz_UF>uXJ_#fpx?0K4qly6cEstlDChFHpH*yX(pLc9DE$R*{;o#5V&}ny<3xa6CYF z1Ep=?Ve{xFIs3fK<_nKmTAs`fvfSE`Zy|oVMK)1Yncya)xDe~a8akWaKMpW)4h*{w zz;QR}39GvRrTzKZ+4TnGUf|9<5%^b4AbS}J4{et`yyOG{;EP!;h^PHs&tobBb}gUT zU;L-S!H5&H*L5b&ta{$zr=CY=k}Y#rd4dIWy>Hw`Axv#U`KO}i&kOV31h-S_6TUD8BV^dhhn{w8v%Qh^wfQlzIu5S>Bd>7z=_+&{ETtHK2%3|YrQk7hW zmJ5k|1ZgSs+fCKRolh#(Kcp&*ESD>Pk<#33|39j-`JW1UN-qS}(8<-dte>G^{Tu~r z*%l1Y!z@&CmpuYi*)(o%ExWL00>eUv_f|8kJifTV#(KnB<1$hzY&U<5B6S1Ln!%G7 zPNl}8s+wl)Q)CwyX}N{rKGU6w9*sg_iR$$Cd%KcZlXueURBJ4~x@qlk5wHeIetD=48j4J?)QY4XGKlfX>{udZsu$+|8|# zPqwIq)pt{D=azuLW-V#(XvT|C*nq_kZP;&5`ZU`B2&aG>ffQEh{N%knmZV2hvPl0c z*{C(JaUg&+-qf|Lw0ZYzl?~&V2-|wpyx7QwJ1Tq+-34t&R3bIz;$WXZ`LX~dY$ zZB}~HU^|E6Jzrac$2UH$uNZ73;VEApj72>@a@Jtzc3%?nlNsAHXkFSf%|o%L)a;X- zMo4F=+tNj2a2-LopiFkflGjJR0V0h3J=L>1V|Cdj&2B>|>)nUhMxy2=MvUvS6+#0* z>b8@0hn21PVR1@iL@)%tb#xT{t=u4U%hsc6r>rmPJ^8dZE-D<6!HMAX7)Ck+@8uSCO-6h5Tx_NfJ7+DuYU!4AnwSa(o=!O?lT{#-wkN62Y-|V#7XsfU(FHdLahe1SLIh6ju%hPrN$+E; zF{qmz^bW8VB2S5^+qU?JCd)jNZi=760eO@hUC1`@#-2EtLj)3d#9ZJ%-ttPsVjmz; zJ4EbTvE~CtGLGCF$#=`p&5Y2cZ*6lqmvT(5CMi%s!GWy)eDBD|j49ln+S7Hz;icrD5H}Jc2LyQySXn*BL$3 z7cmY4*H47F<)AK~Az3%dlhm=Yvo(^W#jo80M$g1zfzCH6t!H*kcBV(>y6#nIx8u4$ zb6}k5#iGm6kl}YRblv`iLP>BIF~w0)Gb^g@RgH?1GXNnIH{3TG*@!#7DQJm!7Tq+x#ZOOZrBTZ{ddncLB_g-ht6L!F zT7e|ZZ|cdCf65<59@<>JQ)Z}u)T%(FZM%@fHDyJnJ2hJB0cDp1?!c#V+!+e)OriUk zZWY8cB$nZb%DoBAvw|V`xTkKNN-tBukKT6HV#zk(U<9~uhu@dC4?Z1f>t#AHyJH+J z9Oy}_GEF98RPU3kd~%mSI8T#==ehlf1sYYJCiJ+;{!;b&{89%(_SK<4KjE&WMMRtW zj)EA~c4`YW$1YX#pNbh; zZf#^*za1D-EXD!m9a}Fh^$BSluWV219&22|zAbtTO<1Q5@ppOPWQ{NUlZ)#9b?FAxOpTzbbh`<=AQ@`8?a7dkdITkM_2 zDf5Nx_6A8^A4H9KxlxhL%VK^qbnnc)%8nM)jo^T0HOgDrj&9A59-No98rnS2rZ$yg zh5S-(6)s7(#>U`M+>+LB_Qfhj9&n>=P_Rq6V^4~m)3d|*7t8JP22R03#wAq%_b?Cq z#skBQdAw1NwdvedYwsz@8>ZZNJRsD&O$}*xh=Dr9GqaW*_U3w2%Cjor`H(lbu|w~% zRlRt<5p$~>X^w(LRu9UD^V7(>fz`qGeR(h^&{sR%-HM?FG^Ei2vQr_wk7~6xb%?lB zPw9zdslRHV_r(f>;OC_|cS&8K@V$Y@ui71jVfmqruMy0ORZB?4+wp*I9y7zvo~HrD z}*Q0wHTD#s?w2wcP zJBnC3UC-}gQMzHiKbGPiuKHaecKab67sN{!bboh8sFnDda?s|guN0g4xy*QktCP;` z$ts{UOz}po5993Dr5I!Vt?-jDQAVjyV_#XGIa*hOXgIhlH>~~k?h%5cYDCqZDy&|C zn+rCB7FS@^`g>P{eNORc+d6D}?UNIErJYi6@7fWl1^3l%(oQ5IRqsKbrON19GFRU; zlTYhaLGJL1b6=oCf2MkOCsA`xdRS~|c4c+7>tvQ+yZwya;0JwE&h9{DeE}`bt5R<~ zEqn&HKzFisxS+^nSo6)SC>`N!GRxyi5w?J5FIigA^A-sdT(SUfY?u3sn(Qdc$T_u` z9CrT(wUX$%s~>R&o+m=&Tlw9bugx0=6R3FEum@wvaNjDuGnB=boy;{;3R~;py%YL@S-=X*Q9oW)EwN}dF@>H9>5m>M`09Q< zMmsDU*P9+#nLX=alyai8t|lDUd28B8NC(k;`hHmMdU0_JdPWf=C7sS)ypoSad>p=Y z3-lSuWpbduF|1S}Fe_|HaStlzo3hbifk~f9ob@a+YB6&rvCjQ2Qxj`f)Ha+Mw1uwq zglpLMZKUG`8p-pl82nfb*X5N*9dC$wJ`+7$;Cm#RD6ss-#+jyMy%&+GAnNnoaJ#{4B4moOjUhy0$!l$y}Jt3w{SyLg;R zUlr86M)$1mp5>3qRWf?%$Zn+Tj zN>tt3gy!4eMGdIuepx_>pDxCxWE;l}bS-q@LIXE;Rm)gh?f&7)F~X)HxjPiiRz2u= zVZe_UdJgW&Ov8ga%_k4@VBRA#=X){~W9kwdwi9SFMKz6(k9cja>Yesfxhp3Sd^;#E zCd@(kJZT_YhmCyWHwqa+&&4?j7_>Vq6&I9#o;N@GXS`O3zqajT`P^8}`y$Vp!(cl0 z*zxImy$KJWUx*POG_{|7Q0yYFMR|(&6m`AYRpA|vDadf6nA3$^6p*Xd{rPb*Gnmmv z)6&!Rq8626#a)iQ%0bAA5pDYUkbZjOroE;UmFBJEVcxk>ZLQ3^q~qkvM8rKh>wtQ2 z`}-oPaKchL6+5JGP1l^8rcgdyP-MlJFTSls9uX>N?K8hxV$?6@f>!QEs?gX&S&{lW zw#vTv<%`9Hvmp;kkXJMXW$YTcB)~BiM9<5ZUMKZpiW4G>=q}zb5h5`~PbU^HJ+ew1 zRiqRHbi-fmzWvc})@+;Y$g^`j1BHUjwyiStno&8o8ud-;6|7u3FqC2#Ln+enH< zCCQfBtv8(Ou3IiwP*vxWEAFv7K^NK_gE*Mqz&?+7Fi4}un!dW+?DF`C>9*@Uybn_E zsqaX_mZz#OKA|^|sxv}oJzabQ`Qc8udUL8W3r&v&%^Q#TvViON*dxC61GN>Q??wj# z7{|u!{xdvfFPqO0K11*sA(%Yadfs0x;u&dq&<7&aninB_QVc}Y=c_w7Rzm_TiF?wI z-gu6mm>em7$F`5}P{t|iV)toI0A-%6`vHhoSd+#>rOO63uJ@={)H@5QIR0O)U3)lG zYug_w9oV~~q7spiVvIt1K9UopxRN_bXb4sVKce-lIjh{Vrh=6-G?RX*OY?+Ki~C#E^?bKh$O2C>j}l&#F~kz zv-8vdQm<1RDt~`UFm}TB_1XA*rh8IXxw5X%!AS5zS~zY_{%WPU$B)1A+%=)Up8ZHX z4&Ic^An~ryvKX+kipRm~F{fTM}4zC_8R`${A>Ah*+wH5<#g!CBaT>Yiq%&;4t^h91EkoqENv}bmomg19_TfX%NBxH?T%gBp%^07!-844{A;Oba2 zu!Lrx9`WxsMm@w8ds#&dV1n+SAQw$)=3%m@XFN&@JOa&tZPzD4;H!izWy@Ekh6zpM zf7o-sBqYg-Vh4t5@<&WiN)Bs%Q0RpcOkT0;a>0_#^5_MQGRhl}^$}(XeVW(-Nm_LP zs@cwh;Lzo}vyc2EO;V4&;iN3OV~NvMq8@UDmpJ?RgKd&znUNpj^HL2xuV^$U9H*@C z)-8!ldUl%>5O2D~jOj1;v+DH*QjJBa*^djK-a@C~;~I}2MTpUs7DEki7X7aJBV7ZG z=7iYR-%wl;Ee;X(o&$1IfMfG-NL$7zC#=6Sesv*&+_ZqAsST}4c0tb(ulcRZqc1bP z6Vt!@`3%~~x9|mHtkjkZDloGavZHV8r_F{poCbGdMKI!~^ZB0y&c3_>XY1q%r<*Qi zUb=_xMCFTA8wmDYI(?JpnSDwmF=azBuue0RG-IaSph!RMS7>LTkIA~l{jdv_cUYo` zIB>s~uKsU^y+H!M)eOBX{Nsg{<^)4vx;FtdV@;siMpn4+Plh?*URFtLsQ5~S!){l4 z4ciaJqa^6B11;b7>u#h$tr`Q;uVkb5-){;m-QPiky8*;Ec@anWXsp>QNmdeMKYupN z?w8lW2%0qBKBDU8@lFeuzJf;eHC4&MJ_(q6vh1&aTI^ns^+;Q?%Lr#x8xmIVZK@JF z4U>Hu7rG8EIO zN8b$RGbTg|JjJS*{hq7RS6jDaafTiaha>gOWZmy!H}|ZmM~IKDN6ASM;(~y@uvr*I_TCce7lB+h|2x z1bJI!W>zbM!PmCt3hf_we)Tr|E_fMaAwS%hhTYz5%+$u{nIN^(*>UZCnf3P@3{J?C z>K9DgR$~S}Ayp?z`<9AUaKyYg%qlN89p2ss%wnL6q=7(dtTZgjcjxfE9}qax`EX#K3ILC=lO!7@e^fhR&$E-5mBFMl1GyH@9cGex^zS}D8ShsB?AO#OU6cTy> z+G_a1Y?Q4YDS;-O)z&4;6yA=!4|K10lZp6R+FoL{+YBQZXm#9ulVDq{Dx*WOs{lX% zOBr{Ebrf3^JY#lgPHoJo`fIaklR6L+dmiG3rmvmy zA{!04=s{j2M3^6~AFO)t7=(P9@>a+PjAzkxP-pw=-mE{h<;kJLZ4P0X8CA>{36W!h zUHgJFyG%VWgDigbNa%T+h}9AL7WajAy{ebjj}2_q z!&kIS_pE+v!t&(}(?wh=Z$#?8OuiNCKfJF|i|{6*CpuOL$)4jLu>~s(DSn8XnbG3z zikDmj9#x4;+&X)hdxE&nb9m4`7M(S|A;-W*_%Ebma@h&r>FA>vyW#lD?(cgWrME`m zq83%O0))(3p9~I+^K2Af5AYJwuQO`3e6v2RmZhS2cC;!1GyigQN4&~8VG6sdkIaTW zf2$AwjLBWZIEVIS1UY9v;YiNO#etV@4=SiYCHH2h^Iz7yN3yR67+gdQ?Rv_*v*(@l zTMxT#6}B@)$DOx!s79OtLa!ud%i|4Bti}~4hSB7E+gPz(Yo@= zGe6SGs+lt}xs=Eiv;?4PI~`>uBX3#Z7O>E{;9|=m4L^#J(Q&ACArHvXcH~GcCbE6u z0KixC3G<^j#voQYXrXtSfBfuxpHnEWYAujH*El?_1y7X1 zT}YLN5bPjwQ@m0V(sPPz%)+((8kX<*8T{uVV3$QAgrUL7kV%fe$Hu~+Ggdi5P=HZc z7iDRE)|JxNvBB{O*1_+rdI7lW-~P}ir!uieJ0W7!^(AY08O88QJHiQEkY(T<)s1`T zcqcaP=UWM0SZz?Xmol*Enh=bQX6Aam4^8Qy$L(%^%yLI2L%W{XAIm7w14R;}oZ&jgyp!dZKNEolwj&>EG*x`$BWP6k^nbQ$BW# zr+&Wz81DWBu9E>WI`05Q+1#MR7uMqF`A3ClR;%LbH-@;#@5!#+b_17el`*=<47?;n zq7d0cqkzxpfCT?CbFo`pVkmImUZa6pX%wC_wAJenH`ykgMjGr7UjZ5lbCWo+qKS=Q z=Jl)fWS9BZHI_`i8I*n3?KS~t-+nmI2F@9C!O{QZxwUx8b2j2d2-78Z8ZLRHm1xoC zZIh-K=yreoa2E9=(1nw8H|DduC1WxdMYZawkq`dqF>&2#&N$95@Ao>p6JA)3-NUYDig%R&p#pdg}9h2*HsO@X$)= zWV%C?eNzfPkl~6dP_UIunUWCUz)K~at!y_YSMU4a-N}{0o1=?P!PW(<+gY&_k7L_eO%9KjcJKDvovJx(by%&kPglsN@28~ZO!69q%xth!pe!D#186E zJuH?F`<5rf7VDZMyzv;9Y7e)2!DrA;f!JVJ-Dse0KEPV3uq0qd$5X!vuPV7+1rp^X&e4 zZ@J6oq{CQ1=lC&`{c-GHGWS*n{6e-~0EJP>NnW9HhudX_{l z=$cp?Kv^(gPN;FBUZEAg*Q#k*$-D1mI}QTzbd)>U_c9fX3BJEiS%P! zs5|9MerE&9_c@#82`x^XK3`Yl_WI~Q7q$e?T-ca!;kkzse=ORXr3DT0cIAYZXIEfy zm_4HLnP!>;yh~%H{!d&0LFpfuzc%b|L6@6Gm7nnHa~$$?88R7<{U+gu7ozCL;AfI` zvs$q}XYc~b{dvmu;?f*-Qg>qOaQ$7deueW0%S5;%Xy5FAGw&X*mmvQib91Ff{bn^} zh(|eze{!>LUl0P1BVvhVf$~eQ=j?C@qf&(Bg0&j3A4d>%W9ZvXF7cV4k(u`^f`>y35g7z&$20vk1zh!Ll%%7{yDbdt6ymCaQvpm!LJ=LcCw0H!guV zBoN%V(*kvGNXfU&S@uucu=0n!39X~fiRksuL+ggY9m3@0c1$)?fO#xd2{F2SdLd&5o-JzmH%O&s2_O|82$dPpiF`>Hn%~I|cS5!ylOB)o z--7ebmTPs$&0PPZHv>pdFhM(i0iz6$j+0Pp7lOcfNM9vV$g{@{oqIxb2DFnJFa&X)NVNA~cVkRi$?k@TBEaTH!+`;~=!j{U)2_T7h=rDo4 +#include #include "napi/native_api.h" #include "napi/native_common.h" +#include "print_constant.h" namespace OHOS::Print { class NapiPrintUtils { @@ -75,6 +77,7 @@ public: napi_env env, napi_value object, const std::initializer_list &properties); static size_t GetJsVal(napi_env env, napi_callback_info info, napi_value argv[], size_t length); + static bool VerifyProperty(std::vector &names, std::map &propertyList); }; } // namespace OHOS::Print #endif // NAPI_PRINT_UTILS_H \ No newline at end of file diff --git a/frameworks/helper/print_helper/src/napi_print_utils.cpp b/frameworks/helper/print_helper/src/napi_print_utils.cpp index 77f6dbd..e086c03 100644 --- a/frameworks/helper/print_helper/src/napi_print_utils.cpp +++ b/frameworks/helper/print_helper/src/napi_print_utils.cpp @@ -324,4 +324,24 @@ size_t NapiPrintUtils::GetJsVal(napi_env env, napi_callback_info info, napi_valu napi_get_cb_info(env, info, &argc, argv, &thisVal, &data); return argc; } + +bool NapiPrintUtils::VerifyProperty( + std::vector &names, std::map &propertyList) +{ + for (auto name : names) { + if (propertyList.find(name) == propertyList.end()) { + PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); + return false; + } + propertyList[name] = PRINT_PARAM_SET; + } + + for (auto propertypItem : propertyList) { + if (propertypItem.second == PRINT_PARAM_NOT_SET) { + PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); + return false; + } + } + return true; +} } // namespace OHOS::Print diff --git a/frameworks/helper/print_helper/src/print_attributes_helper.cpp b/frameworks/helper/print_helper/src/print_attributes_helper.cpp index d5b675f..4566c31 100644 --- a/frameworks/helper/print_helper/src/print_attributes_helper.cpp +++ b/frameworks/helper/print_helper/src/print_attributes_helper.cpp @@ -202,20 +202,6 @@ bool PrintAttributesHelper::ValidateProperty(napi_env env, napi_value object) }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } diff --git a/frameworks/helper/print_helper/src/print_job_helper.cpp b/frameworks/helper/print_helper/src/print_job_helper.cpp index 6d3f8a9..41efd25 100644 --- a/frameworks/helper/print_helper/src/print_job_helper.cpp +++ b/frameworks/helper/print_helper/src/print_job_helper.cpp @@ -149,11 +149,6 @@ std::shared_ptr PrintJobHelper::BuildFromJs(napi_env env, napi_value j std::shared_ptr PrintJobHelper::BuildJsWorkerIsLegal(napi_env env, napi_value jsValue, std::string jobId, uint32_t jobState, uint32_t subState, std::shared_ptr &nativeObj) { - if (jobId == "") { - PRINT_HILOGE("Invalid job id"); - return nullptr; - } - if (jobState >= PRINT_JOB_UNKNOWN || subState > PRINT_JOB_BLOCKED_UNKNOWN) { PRINT_HILOGE("Invalid job state[%{public}d] or sub state [%{public}d]", jobState, subState); return nullptr; @@ -276,20 +271,6 @@ bool PrintJobHelper::ValidateProperty(napi_env env, napi_value object) }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } diff --git a/frameworks/helper/print_helper/src/print_page_size_helper.cpp b/frameworks/helper/print_helper/src/print_page_size_helper.cpp index ef79e44..209c03e 100644 --- a/frameworks/helper/print_helper/src/print_page_size_helper.cpp +++ b/frameworks/helper/print_helper/src/print_page_size_helper.cpp @@ -72,21 +72,6 @@ bool PrintPageSizeHelper::ValidateProperty(napi_env env, napi_value object) }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } // namespace OHOS::Print diff --git a/frameworks/helper/print_helper/src/print_preview_attribute_helper.cpp b/frameworks/helper/print_helper/src/print_preview_attribute_helper.cpp index c2200bb..72a2205 100644 --- a/frameworks/helper/print_helper/src/print_preview_attribute_helper.cpp +++ b/frameworks/helper/print_helper/src/print_preview_attribute_helper.cpp @@ -73,21 +73,6 @@ bool PrintPreviewAttributeHelper::ValidateProperty(napi_env env, napi_value obje }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } // namespace OHOS::Print diff --git a/frameworks/helper/print_helper/src/print_resolution_helper.cpp b/frameworks/helper/print_helper/src/print_resolution_helper.cpp index ec74593..9ef1afe 100644 --- a/frameworks/helper/print_helper/src/print_resolution_helper.cpp +++ b/frameworks/helper/print_helper/src/print_resolution_helper.cpp @@ -43,6 +43,10 @@ std::shared_ptr PrintResolutionHelper::BuildFromJs(napi_env env PRINT_HILOGE("Invalid resolution id"); return nullptr; } + if (nativeObj == nullptr) { + PRINT_HILOGE("nativeObj is nullptr"); + return nullptr; + } nativeObj->SetId(id); nativeObj->SetHorizontalDpi(horizontalDpi); nativeObj->SetVerticalDpi(verticalDpi); @@ -59,21 +63,6 @@ bool PrintResolutionHelper::ValidateProperty(napi_env env, napi_value object) }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } // namespace OHOS::Print diff --git a/frameworks/helper/print_helper/src/printer_capability_helper.cpp b/frameworks/helper/print_helper/src/printer_capability_helper.cpp index af27e87..e9836c3 100644 --- a/frameworks/helper/print_helper/src/printer_capability_helper.cpp +++ b/frameworks/helper/print_helper/src/printer_capability_helper.cpp @@ -180,20 +180,6 @@ bool PrinterCapabilityHelper::ValidateProperty(napi_env env, napi_value object) }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } // namespace OHOS::Print diff --git a/frameworks/helper/print_helper/src/printer_info_helper.cpp b/frameworks/helper/print_helper/src/printer_info_helper.cpp index 5666a59..592936c 100644 --- a/frameworks/helper/print_helper/src/printer_info_helper.cpp +++ b/frameworks/helper/print_helper/src/printer_info_helper.cpp @@ -27,6 +27,9 @@ static constexpr const char *PARAM_INFO_PRINTERICON = "printerIcon"; static constexpr const char *PARAM_INFO_DESCRIPTION = "description"; static constexpr const char *PARAM_INFO_CAPABILITY = "capability"; static constexpr const char *PARAM_JOB_OPTION = "options"; +static constexpr const char *PARAM_INFO_IS_DAFAULT_PRINTER = "isDefaultPrinter"; +static constexpr const char *PARAM_INFO_IS_LAST_USED_PRINTER = "isLastUsedPrinter"; +static constexpr const char *PARAM_INFO_PRINTER_STATUS = "printerStatus"; napi_value PrinterInfoHelper::MakeJsObject(napi_env env, const PrinterInfo &info) { @@ -54,6 +57,18 @@ napi_value PrinterInfoHelper::MakeJsObject(napi_env env, const PrinterInfo &info if (info.HasOption()) { NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_JOB_OPTION, info.GetOption()); } + + if (info.HasIsDefaultPrinter()) { + NapiPrintUtils::SetBooleanProperty(env, jsObj, PARAM_INFO_IS_DAFAULT_PRINTER, info.GetIsDefaultPrinter()); + } + + if (info.HasIsLastUsedPrinter()) { + NapiPrintUtils::SetBooleanProperty(env, jsObj, PARAM_INFO_IS_LAST_USED_PRINTER, info.GetIsLastUsedPrinter()); + } + + if (info.HasPrinterStatus()) { + NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_INFO_PRINTER_STATUS, info.GetPrinterStatus()); + } return jsObj; } @@ -123,20 +138,6 @@ bool PrinterInfoHelper::ValidateProperty(napi_env env, napi_value object) }; auto names = NapiPrintUtils::GetPropertyNames(env, object); - for (auto name : names) { - if (propertyList.find(name) == propertyList.end()) { - PRINT_HILOGE("Invalid property: %{public}s", name.c_str()); - return false; - } - propertyList[name] = PRINT_PARAM_SET; - } - - for (auto propertypItem : propertyList) { - if (propertypItem.second == PRINT_PARAM_NOT_SET) { - PRINT_HILOGE("Missing Property: %{public}s", propertypItem.first.c_str()); - return false; - } - } - return true; + return NapiPrintUtils::VerifyProperty(names, propertyList); } } // namespace OHOS::Print diff --git a/frameworks/innerkitsimpl/print_impl/BUILD.gn b/frameworks/innerkitsimpl/print_impl/BUILD.gn index be6e153..2021194 100644 --- a/frameworks/innerkitsimpl/print_impl/BUILD.gn +++ b/frameworks/innerkitsimpl/print_impl/BUILD.gn @@ -31,12 +31,23 @@ ohos_shared_library("print_client") { ] public_configs = [ ":print_interfaces_kits_napi_config" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + sources = [ "src/iprint_adapter.cpp", "src/iprint_adapter_inner.cpp", "src/print_callback.cpp", "src/print_callback_stub.cpp", "src/print_extension_callback_stub.cpp", + "src/print_innerkit_modal_ui_callback.cpp", "src/print_manager_client.cpp", "src/print_sa_death_recipient.cpp", "src/print_service_proxy.cpp", @@ -47,15 +58,6 @@ ohos_shared_library("print_client") { "${print_path}/frameworks/helper/print_helper:print_helper", "${print_path}/frameworks/models/print_models:print_models", ] - if (pdfium_enable) { - include_dirs += [ - "//third_party/pdfium", - "//third_party/pdfium/public", - "//third_party/pdfium/testing/image_diff", - ] - cflags_cc += [ "-DPDFIUM_ENABLE" ] - deps += [ "//third_party/pdfium:pdfium_shared" ] - } external_deps = [ "ability_base:want", "ability_base:zuri", @@ -63,16 +65,14 @@ ohos_shared_library("print_client") { "ability_runtime:abilitykit_native", "ability_runtime:data_ability_helper", "ability_runtime:napi_base_context", + "ability_runtime:ui_extension", + "ace_engine:ace_uicontent", "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", - "preferences:native_preferences", - "relational_store:native_appdatafwk", - "relational_store:native_dataability", - "relational_store:native_rdb", "samgr:samgr_proxy", ] diff --git a/frameworks/innerkitsimpl/print_impl/include/iprint_adapter.h b/frameworks/innerkitsimpl/print_impl/include/iprint_adapter.h index 48cd608..929d533 100644 --- a/frameworks/innerkitsimpl/print_impl/include/iprint_adapter.h +++ b/frameworks/innerkitsimpl/print_impl/include/iprint_adapter.h @@ -28,6 +28,7 @@ public: std::function writeResultCallback); virtual void onJobStateChanged(const std::string &jobId, uint32_t state); + virtual ~PrintDocumentAdapter() {}; }; } #endif // PRINT_FWK_IPRINT_ADAPTER_H diff --git a/frameworks/innerkitsimpl/print_impl/include/iprint_ipc_interface_code.h b/frameworks/innerkitsimpl/print_impl/include/iprint_ipc_interface_code.h index bcb5853..b4491fe 100644 --- a/frameworks/innerkitsimpl/print_impl/include/iprint_ipc_interface_code.h +++ b/frameworks/innerkitsimpl/print_impl/include/iprint_ipc_interface_code.h @@ -48,6 +48,18 @@ namespace OHOS::Print { CMD_STARTPRINTJOB_BY_ADAPTER, CMD_START_GET_FILE, CMD_NOTIFY_PRINT_SERVICE, + CMD_START_SERVICE, + CMD_REG_PRINTER_CB, + CMD_UNREG_PRINTER_CB, + CMD_QUERYPRINTERINFOBYPRINTERID, + CMD_QUERYADDEDPRINTER, + CMD_QUERYPRINTERPROPERTIES, + CMD_STARTNATIVEPRINTJOB, + CMD_NOTIFY_PRINT_SERVICE_EVENT, + CMD_GET_PRINTER_PREFERENCE, + CMD_SET_PRINTER_PREFERENCE, + CMD_SET_DEFAULT_PRINTERID, + CMD_DELETE_PRINTER_FROM_CUPS, }; } // namespace OHOS:Print #endif // PRINT_SERVICE_INTERFACE_H diff --git a/frameworks/innerkitsimpl/print_impl/include/iprint_service.h b/frameworks/innerkitsimpl/print_impl/include/iprint_service.h index 3e45572..6887ae3 100644 --- a/frameworks/innerkitsimpl/print_impl/include/iprint_service.h +++ b/frameworks/innerkitsimpl/print_impl/include/iprint_service.h @@ -31,28 +31,30 @@ namespace OHOS::Print { class IPrintService : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print.IPrintService"); + virtual int32_t StartService() = 0; virtual int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, std::string &taskId) = 0; - virtual int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token) = 0; virtual int32_t StopPrint(const std::string &taskId) = 0; virtual int32_t ConnectPrinter(const std::string &printerId) = 0; virtual int32_t DisconnectPrinter(const std::string &printerId) = 0; virtual int32_t StartDiscoverPrinter(const std::vector &extensionList) = 0; virtual int32_t StopDiscoverPrinter() = 0; virtual int32_t QueryAllExtension(std::vector &extensionInfos) = 0; - virtual int32_t StartPrintJob(const PrintJob &jobInfo) = 0; + virtual int32_t StartPrintJob(PrintJob &jobInfo) = 0; virtual int32_t CancelPrintJob(const std::string &jobId) = 0; virtual int32_t AddPrinters(const std::vector &printerInfos) = 0; virtual int32_t RemovePrinters(const std::vector &printerIds) = 0; virtual int32_t UpdatePrinters(const std::vector &printerInfos) = 0; virtual int32_t UpdatePrinterState(const std::string &printerId, uint32_t state) = 0; - virtual int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) = 0; + virtual int32_t UpdatePrintJobStateOnlyForSystemApp( + const std::string &jobId, uint32_t state, uint32_t subState) = 0; virtual int32_t UpdateExtensionInfo(const std::string &extensionId) = 0; virtual int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult) = 0; virtual int32_t QueryPrinterCapability(const std::string &printerId) = 0; virtual int32_t On(const std::string taskId, const std::string &type, const sptr &listener) = 0; virtual int32_t Off(const std::string taskId, const std::string &type) = 0; + virtual int32_t RegisterPrinterCallback(const std::string &type, const sptr &listener) = 0; + virtual int32_t UnregisterPrinterCallback(const std::string &type) = 0; virtual int32_t RegisterExtCallback(const std::string &extensionCID, const sptr &listener) = 0; virtual int32_t UnregisterAllExtCallback(const std::string &extensionId) = 0; @@ -64,10 +66,21 @@ public: virtual int32_t QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId, PrinterCapability &printerCaps) = 0; virtual int32_t PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes, - std::string &taskId, const sptr &token) = 0; + std::string &taskId) = 0; virtual int32_t StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes, const uint32_t fd) = 0; virtual int32_t NotifyPrintService(const std::string &jobId, const std::string &type) = 0; + virtual int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) = 0; + virtual int32_t QueryAddedPrinter(std::vector &printerNameList) = 0; + virtual int32_t QueryPrinterProperties(const std::string &printerId, const std::vector &keyList, + std::vector &valueList) = 0; + virtual int32_t StartNativePrintJob(PrintJob &printJob) = 0; + virtual int32_t NotifyPrintServiceEvent(std::string &jobId, uint32_t event) = 0; + virtual int32_t GetPrinterPreference(const std::string &printerId, std::string &printerPreference) = 0; + virtual int32_t SetPrinterPreference(const std::string &printerId, const std::string &printerPreference) = 0; + virtual int32_t SetDefaultPrinter(const std::string &printerId) = 0; + virtual int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake) = 0; }; } // namespace OHOS::Print #endif // PRINT_SERVICE_INTERFACE_H \ No newline at end of file diff --git a/frameworks/innerkitsimpl/print_impl/include/print_callback.h b/frameworks/innerkitsimpl/print_impl/include/print_callback.h index 23b3edc..5e58b5a 100644 --- a/frameworks/innerkitsimpl/print_impl/include/print_callback.h +++ b/frameworks/innerkitsimpl/print_impl/include/print_callback.h @@ -51,7 +51,8 @@ class PrintCallback : public PrintCallbackStub { public: PrintCallback(napi_env env, napi_ref ref); explicit PrintCallback(PrintDocumentAdapter *adapter); // This interface is invoked by other domains. - virtual ~PrintCallback(); + PrintCallback(){}; + ~PrintCallback(); bool OnCallback() override; bool OnCallback(uint32_t state, const PrinterInfo &info) override; bool OnCallback(uint32_t state, const PrintJob &info) override; @@ -62,6 +63,11 @@ public: const uint32_t subState) override; bool OnCallbackAdapterGetFile(uint32_t state) override; + void SetNativePrinterChangeCallback(NativePrinterChangeCallback cb) + { + nativePrinterChange_cb = cb; + } + private: bool onBaseCallback(std::function paramFun, uv_after_work_cb after_work_cb); @@ -70,6 +76,7 @@ private: napi_ref ref_ = nullptr; std::mutex mutex_; PrintDocumentAdapter *adapter_ = nullptr; + NativePrinterChangeCallback nativePrinterChange_cb = nullptr; }; } // namespace OHOS::Print #endif // IPRINT_CALLBACK_H diff --git a/frameworks/innerkitsimpl/print_impl/include/print_innerkit_modal_ui_callback.h b/frameworks/innerkitsimpl/print_impl/include/print_innerkit_modal_ui_callback.h new file mode 100644 index 0000000..c28d77e --- /dev/null +++ b/frameworks/innerkitsimpl/print_impl/include/print_innerkit_modal_ui_callback.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_INNERKIT_MODAL_UI_CALLBACK_H +#define PRINT_INNERKIT_MODAL_UI_CALLBACK_H + +#include "want.h" +#include +#include "ability_context.h" +#include "ui_extension_context.h" + +namespace OHOS { +namespace Print { + +class PrintInnerkitModalUICallback { +public: + explicit PrintInnerkitModalUICallback(OHOS::Ace::UIContent *uiContent); + void OnRelease(int32_t releaseCode); + void OnResultForModal(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string& message); + void SetSessionId(int32_t sessionId); + +private: + int32_t sessionId_ = 0; + OHOS::Ace::UIContent *uiContent = nullptr; +}; +} // namespace Print +} // namespace OHOS +#endif // PRINT_INNERKIT_MODAL_UI_CALLBACK_H \ No newline at end of file diff --git a/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h b/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h index 3b5e3af..f09cab9 100644 --- a/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h +++ b/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h @@ -20,6 +20,7 @@ #include #include +#include "want.h" #include "iprint_callback.h" #include "iprint_service.h" #include "iremote_object.h" @@ -47,8 +48,6 @@ public: int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, std::string &taskId); int32_t StopPrint(const std::string &taskId); - int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token); int32_t QueryAllExtension(std::vector &extensionInfos); int32_t StartDiscoverPrinter(const std::vector &extensionList); int32_t StopDiscoverPrinter(); @@ -57,10 +56,10 @@ public: int32_t UpdatePrinters(const std::vector &printerInfos); int32_t ConnectPrinter(const std::string &printerId); int32_t DisconnectPrinter(const std::string &printerId); - int32_t StartPrintJob(const PrintJob &jobinfo); + int32_t StartPrintJob(PrintJob &jobinfo); int32_t CancelPrintJob(const std::string &jobId); int32_t UpdatePrinterState(const std::string &printerId, uint32_t state); - int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState); + int32_t UpdatePrintJobStateOnlyForSystemApp(const std::string &jobId, uint32_t state, uint32_t subState); int32_t UpdateExtensionInfo(const std::string &extensionId); int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult); int32_t QueryPrinterCapability(const std::string &printerId); @@ -70,6 +69,10 @@ public: const std::string &printerMake); int32_t QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId, PrinterCapability &printerCaps); + int32_t NotifyPrintServiceEvent(std::string &jobId, uint32_t event); + int32_t SetDefaultPrinter(const std::string &printerId); + int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake); int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info); int32_t QueryAddedPrinter(std::vector &printerNameList); int32_t QueryPrinterProperties(const std::string &printerId, const std::vector &keyList, @@ -95,14 +98,6 @@ public: int32_t StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes, const uint32_t fd); int32_t NotifyPrintService(const std::string &jobId, const std::string &type); -#ifdef PDFIUM_ENABLE - int32_t PdfRenderInit(const std::string filePath, const std::string sandBoxPath, std::string &basePngName, - int32_t &pageCount, FPDF_DOCUMENT &doc); - int32_t PdfRenderDestroy(const std::string basePngName, const int32_t pageCount, FPDF_DOCUMENT &doc); - int32_t GetPdfPageSize(const int32_t pageIndex, uint32_t &width, uint32_t &height, FPDF_DOCUMENT &doc); - int32_t RenderPdfToPng(const std::string basePngName, const int32_t pageIndex, std::string &imagePath, - FPDF_DOCUMENT &doc); -#endif // PDFIUM_ENABLE int32_t RegisterExtCallback(const std::string &extensionId, uint32_t callbackId, PrintExtCallback cb); int32_t RegisterExtCallback(const std::string &extensionId, uint32_t callbackId, PrintJobCallback cb); @@ -119,6 +114,7 @@ public: void ResetProxy(); private: + void SetWantParam(AAFwk::Want &want, std::string &taskId); bool LoadServer(); bool GetPrintServiceProxy(); int32_t runBase(const char* callerFunName, std::function)> func); diff --git a/frameworks/innerkitsimpl/print_impl/include/print_service_proxy.h b/frameworks/innerkitsimpl/print_impl/include/print_service_proxy.h index a5c7628..6495930 100644 --- a/frameworks/innerkitsimpl/print_impl/include/print_service_proxy.h +++ b/frameworks/innerkitsimpl/print_impl/include/print_service_proxy.h @@ -25,28 +25,29 @@ public: explicit PrintServiceProxy(const sptr &object); ~PrintServiceProxy() = default; DISALLOW_COPY_AND_MOVE(PrintServiceProxy); + virtual int32_t StartService() override; int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, std::string &taskId) override; int32_t StopPrint(const std::string &taskId) override; - int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token) override; int32_t ConnectPrinter(const std::string &printerId) override; int32_t DisconnectPrinter(const std::string &printerId) override; int32_t StartDiscoverPrinter(const std::vector &extensionList) override; int32_t StopDiscoverPrinter() override; int32_t QueryAllExtension(std::vector &extensionInfos) override; - int32_t StartPrintJob(const PrintJob &jobinfo) override; + int32_t StartPrintJob(PrintJob &jobinfo) override; int32_t CancelPrintJob(const std::string &jobId) override; int32_t AddPrinters(const std::vector &printerInfos) override; int32_t RemovePrinters(const std::vector &printerIds) override; int32_t UpdatePrinters(const std::vector &printerInfos) override; int32_t UpdatePrinterState(const std::string &printerId, uint32_t state) override; - int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) override; + int32_t UpdatePrintJobStateOnlyForSystemApp(const std::string &jobId, uint32_t state, uint32_t subState) override; int32_t UpdateExtensionInfo(const std::string &extensionId) override; int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult) override; int32_t QueryPrinterCapability(const std::string &printerId) override; int32_t On(const std::string taskId, const std::string &type, const sptr &listener) override; int32_t Off(const std::string taskId, const std::string &type) override; + int32_t RegisterPrinterCallback(const std::string &type, const sptr &listener) override; + int32_t UnregisterPrinterCallback(const std::string &type) override; int32_t RegisterExtCallback(const std::string &extensionCID, const sptr &listener) override; int32_t UnregisterAllExtCallback(const std::string &extensionId) override; @@ -58,11 +59,23 @@ public: int32_t QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId, PrinterCapability &printerCaps) override; int32_t PrintByAdapter(const std::string printJobName, const PrintAttributes &printAttributes, - std::string &taskId, const sptr &token) override; + std::string &taskId) override; int32_t StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes, const uint32_t fd) override; int32_t NotifyPrintService(const std::string &jobId, const std::string &type) override; + int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) override; + int32_t QueryAddedPrinter(std::vector &printerNameList) override; + int32_t QueryPrinterProperties(const std::string &printerId, const std::vector &keyList, + std::vector &valueList) override; + int32_t StartNativePrintJob(PrintJob &printJob) override; + int32_t NotifyPrintServiceEvent(std::string &jobId, uint32_t event) override; + int32_t GetPrinterPreference(const std::string &printerId, std::string &printerPreference) override; + int32_t SetPrinterPreference(const std::string &printerId, const std::string &printerPreference) override; + int32_t SetDefaultPrinter(const std::string &printerId) override; + int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake) override; + private: int32_t GetResult(int retCode, MessageParcel &reply); static inline BrokerDelegator delegator_; diff --git a/frameworks/innerkitsimpl/print_impl/src/print_callback.cpp b/frameworks/innerkitsimpl/print_impl/src/print_callback.cpp index 7d8f332..7e9a423 100644 --- a/frameworks/innerkitsimpl/print_impl/src/print_callback.cpp +++ b/frameworks/innerkitsimpl/print_impl/src/print_callback.cpp @@ -32,7 +32,10 @@ PrintCallback::PrintCallback(PrintDocumentAdapter* adapter) :adapter_(adapter) PrintCallback::~PrintCallback() { if (adapter_ != nullptr) { + delete adapter_; adapter_ = nullptr; + } else if (nativePrinterChange_cb != nullptr) { + nativePrinterChange_cb = nullptr; } else { std::lock_guard autoLock(mutex_); PRINT_HILOGD("callback has been destroyed"); @@ -51,7 +54,7 @@ PrintCallback::~PrintCallback() return; } work->data = reinterpret_cast(param); - uv_queue_work(loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int _status) { + int retVal = uv_queue_work(loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int _status) { PRINT_HILOGD("uv_queue_work PrintCallback DeleteReference"); Param *param_ = reinterpret_cast(work->data); if (param_ == nullptr) { @@ -71,6 +74,12 @@ PrintCallback::~PrintCallback() delete param_; delete work; }); + if (retVal != 0) { + PRINT_HILOGE("Failed to get uv_queue_work."); + delete param; + delete work; + return; + } } } @@ -232,7 +241,8 @@ static void PrintAdapterAfterCallFun(uv_work_t *work, int status) std::string jobId = NapiPrintUtils::GetStringFromValueUtf8(env, args[0]); uint32_t replyState = NapiPrintUtils::GetUint32FromValue(env, args[1]); - PrintManagerClient::GetInstance()->UpdatePrintJobState(jobId, PRINT_JOB_CREATE_FILE_COMPLETED, replyState); + PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp( + jobId, PRINT_JOB_CREATE_FILE_COMPLETED, replyState); PRINT_HILOGI("from js return jobId:%{public}s, replyState:%{public}d", jobId.c_str(), replyState); return nullptr; }; @@ -340,6 +350,7 @@ bool PrintCallback::onBaseCallback(std::function paramFun, CallbackParam *param = new (std::nothrow) CallbackParam; if (param == nullptr) { PRINT_HILOGE("Failed to create callback parameter"); + delete work; return false; } else { std::lock_guard lock(mutex_); @@ -352,7 +363,13 @@ bool PrintCallback::onBaseCallback(std::function paramFun, } work->data = param; - uv_queue_work(loop, work, [](uv_work_t *work) {}, after_work_cb); + int retVal = uv_queue_work(loop, work, [](uv_work_t *work) {}, after_work_cb); + if (retVal != 0) { + PRINT_HILOGE("Failed to get uv_queue_work."); + delete param; + delete work; + return false; + } return true; } @@ -365,6 +382,9 @@ bool PrintCallback::OnCallback() bool PrintCallback::OnCallback(uint32_t state, const PrinterInfo &info) { PRINT_HILOGI("Printer Notification in"); + if (nativePrinterChange_cb != nullptr) { + return nativePrinterChange_cb(state, info); + } return onBaseCallback( [state, info](CallbackParam* param) { param->state = state; @@ -392,27 +412,30 @@ bool PrintCallback::OnCallback(const std::string &extensionId, const std::string }, ExtensionAfterCallFun); } -bool PrintCallback::OnCallbackAdapterLayout(const std::string &jobId, const PrintAttributes &oldAttrs, - const PrintAttributes &newAttrs, uint32_t fd) +bool PrintCallback::OnCallbackAdapterLayout( + const std::string &jobId, const PrintAttributes &oldAttrs, const PrintAttributes &newAttrs, uint32_t fd) { PRINT_HILOGI("PrintCallback OnCallbackAdapterLayout Notification in, jobId:%{public}s newAttrs copyNum:%{public}d", - jobId.c_str(), newAttrs.GetCopyNumber()); + jobId.c_str(), + newAttrs.GetCopyNumber()); if (adapter_ != nullptr) { PRINT_HILOGI("OnCallbackAdapterLayout run c++"); adapter_->onStartLayoutWrite(jobId, oldAttrs, newAttrs, fd, [](std::string jobId, uint32_t state) { PRINT_HILOGI("onStartLayoutWrite write over, jobId:%{public}s state: %{public}d", jobId.c_str(), state); - PrintManagerClient::GetInstance()->UpdatePrintJobState(jobId, PRINT_JOB_CREATE_FILE_COMPLETED, state); + PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp( + jobId, PRINT_JOB_CREATE_FILE_COMPLETED, state); }); return true; } else { PRINT_HILOGI("OnCallbackAdapterLayout run ets"); return onBaseCallback( - [jobId, oldAttrs, newAttrs, fd](CallbackParam* param) { + [jobId, oldAttrs, newAttrs, fd](CallbackParam *param) { param->jobId = jobId; param->oldAttrs = oldAttrs; param->newAttrs = newAttrs; param->fd = fd; - }, PrintAdapterAfterCallFun); + }, + PrintAdapterAfterCallFun); } } diff --git a/frameworks/innerkitsimpl/print_impl/src/print_innerkit_modal_ui_callback.cpp b/frameworks/innerkitsimpl/print_impl/src/print_innerkit_modal_ui_callback.cpp new file mode 100644 index 0000000..4368822 --- /dev/null +++ b/frameworks/innerkitsimpl/print_impl/src/print_innerkit_modal_ui_callback.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_innerkit_modal_ui_callback.h" +#include "napi_print_utils.h" +#include "print_log.h" + +#include "ui_content.h" + +using namespace OHOS::Ace; + +namespace OHOS { +namespace Print { + +PrintInnerkitModalUICallback::PrintInnerkitModalUICallback(OHOS::Ace::UIContent *uiContent) +{ + this->uiContent = uiContent; + PRINT_HILOGD("constructor ModalUICallback"); +} + +void PrintInnerkitModalUICallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void PrintInnerkitModalUICallback::OnRelease(int32_t releaseCode) +{ + PRINT_HILOGD("OnRelease enter. release code is %{public}d", releaseCode); + if (this->uiContent == nullptr) { + PRINT_HILOGE("OnRelease uiContent is null"); + return; + } + + PRINT_HILOGI("CloseModalUIExtension"); + this->uiContent->CloseModalUIExtension(this->sessionId_); + return; +} + +void PrintInnerkitModalUICallback::OnReceive(const OHOS::AAFwk::WantParams& request) +{ + PRINT_HILOGD("OnReceive enter."); +} + +void PrintInnerkitModalUICallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + PRINT_HILOGE("OnError enter. errorCode=%{public}d, name=%{public}s, message=%{public}s", + code, name.c_str(), message.c_str()); + if (this->uiContent == nullptr) { + PRINT_HILOGE("OnError uiContent is null"); + return; + } + + PRINT_HILOGI("CloseModalUIExtension"); + this->uiContent->CloseModalUIExtension(this->sessionId_); + return; +} + +void PrintInnerkitModalUICallback::OnResultForModal(int32_t resultCode, const OHOS::AAFwk::Want& result) +{ + PRINT_HILOGD("OnResultForModal enter."); +} +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp b/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp index a4d1a09..4a2cb7d 100644 --- a/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp +++ b/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp @@ -13,26 +13,34 @@ * limitations under the License. */ -#include "print_manager_client.h" - -#ifdef PDFIUM_ENABLE -#include "fpdf_edit.h" -#include "cpp/fpdf_scopers.h" -#include "image_diff_png.h" -#include "iostream" -#include "sys/stat.h" -#include "unistd.h" -#endif // PDFIUM_ENABLE - #include "iservice_registry.h" +#include "system_ability_definition.h" +#include "napi/native_common.h" +#include "ui_content.h" +#include "ipc_skeleton.h" +#include "want.h" +#include "bundle_mgr_client.h" + +#include "print_manager_client.h" #include "print_constant.h" #include "print_extension_callback_stub.h" #include "print_log.h" #include "print_sync_load_callback.h" #include "print_utils.h" -#include "system_ability_definition.h" +#include "print_callback.h" +#include "print_innerkit_modal_ui_callback.h" namespace OHOS::Print { + +static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler"; +static const std::string SPOOLER_PREVIEW_ABILITY_NAME = "PrintServiceExtAbility"; +static const std::string LAUNCH_PARAMETER_JOB_ID = "jobId"; +static const std::string LAUNCH_PARAMETER_FILE_LIST = "fileList"; +static const std::string TOKEN_KEY = "ohos.ability.params.token"; +static const std::string UI_EXTENSION_TYPE_NAME = "ability.want.params.uiExtensionType"; +static const std::string PRINT_UI_EXTENSION_TYPE = "sysDialog/common"; +static const std::string CALLER_PKG_NAME = "caller.pkgName"; + std::mutex PrintManagerClient::instanceLock_; sptr PrintManagerClient::instance_ = nullptr; @@ -109,18 +117,6 @@ int32_t PrintManagerClient::StartPrint(const std::vector &fileList, return ret; } -int32_t PrintManagerClient::StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token) -{ - PRINT_HILOGD("PrintManagerClient StartPrint start."); - int32_t ret = E_PRINT_RPC_FAILURE; - if (LoadServer() && GetPrintServiceProxy()) { - ret = printServiceProxy_->StartPrint(fileList, fdList, taskId, token); - PRINT_HILOGD("PrintManagerClient StartPrint out ret = [%{public}d].", ret); - } - return ret; -} - int32_t PrintManagerClient::StopPrint(const std::string &taskId) { PRINT_HILOGD("PrintManagerClient StopPrint start."); @@ -187,7 +183,7 @@ int32_t PrintManagerClient::StopDiscoverPrinter() return ret; } -int32_t PrintManagerClient::StartPrintJob(const PrintJob &jobinfo) +int32_t PrintManagerClient::StartPrintJob(PrintJob &jobinfo) { PRINT_HILOGD("PrintManagerClient StartPrintJob start."); int32_t ret = E_PRINT_RPC_FAILURE; @@ -253,13 +249,14 @@ int32_t PrintManagerClient::UpdatePrinterState(const std::string &printerId, uin return ret; } -int32_t PrintManagerClient::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) +int32_t PrintManagerClient::UpdatePrintJobStateOnlyForSystemApp( + const std::string &jobId, uint32_t state, uint32_t subState) { - PRINT_HILOGD("PrintManagerClient UpdatePrintJobState start."); + PRINT_HILOGD("PrintManagerClient UpdatePrintJobStateOnlyForSystemApp start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { - ret = printServiceProxy_->UpdatePrintJobState(jobId, state, subState); - PRINT_HILOGD("PrintManagerClient UpdatePrintJobState out ret = [%{public}d].", ret); + ret = printServiceProxy_->UpdatePrintJobStateOnlyForSystemApp(jobId, state, subState); + PRINT_HILOGD("PrintManagerClient UpdatePrintJobStateOnlyForSystemApp out ret = [%{public}d].", ret); } return ret; } @@ -302,6 +299,7 @@ int32_t PrintManagerClient::QueryPrinterInfoByPrinterId(const std::string &print PRINT_HILOGD("PrintManagerClient QueryPrinterInfoByPrinterId start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->QueryPrinterInfoByPrinterId(printerId, info); PRINT_HILOGD("PrintManagerClient QueryPrinterInfoByPrinterId out ret = [%{public}d].", ret); } return ret; @@ -312,6 +310,7 @@ int32_t PrintManagerClient::QueryAddedPrinter(std::vector &printerN PRINT_HILOGD("PrintManagerClient QueryAddedPrinter start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->QueryAddedPrinter(printerNameList); PRINT_HILOGD("PrintManagerClient QueryAddedPrinter out ret = [%{public}d].", ret); } return ret; @@ -323,6 +322,7 @@ int32_t PrintManagerClient::QueryPrinterProperties(const std::string &printerId, PRINT_HILOGD("PrintManagerClient QueryPrinterProperties start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->QueryPrinterProperties(printerId, keyList, valueList); PRINT_HILOGD("PrintManagerClient QueryPrinterProperties out ret = [%{public}d].", ret); } return ret; @@ -333,6 +333,7 @@ int32_t PrintManagerClient::StartNativePrintJob(PrintJob &printJob) PRINT_HILOGD("PrintManagerClient StartNativePrintJob start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->StartNativePrintJob(printJob); PRINT_HILOGD("PrintManagerClient QueryPrinterProperties out ret = [%{public}d].", ret); } return ret; @@ -343,6 +344,7 @@ int32_t PrintManagerClient::GetPrinterPreference(const std::string &printerId, s PRINT_HILOGI("PrintManagerClient GetPrinterPreference start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->GetPrinterPreference(printerId, printerPreference); PRINT_HILOGI("PrintManagerClient GetPrinterPreference out ret = [%{public}d].", ret); } return ret; @@ -353,6 +355,7 @@ int32_t PrintManagerClient::SetPrinterPreference(const std::string &printerId, c PRINT_HILOGI("PrintManagerClient SetPrinterPreference start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->SetPrinterPreference(printerId, printerPreference); PRINT_HILOGI("PrintManagerClient SetPrinterPreference out ret = [%{public}d].", ret); } return ret; @@ -404,6 +407,40 @@ int32_t PrintManagerClient::QueryPrinterCapabilityByUri(const std::string &print return ret; } +int32_t PrintManagerClient::NotifyPrintServiceEvent(std::string &jobId, uint32_t event) +{ + PRINT_HILOGD("PrintManagerClient NotifyPrintServiceEvent start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->NotifyPrintServiceEvent(jobId, event); + PRINT_HILOGD("PrintManagerClient NotifyPrintServiceEvent out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::SetDefaultPrinter(const std::string &printerId) +{ + PRINT_HILOGD("PrintManagerClient SetDefaultPrinter start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->SetDefaultPrinter(printerId); + PRINT_HILOGD("PrintManagerClient SetDefaultPrinter out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake) +{ + PRINT_HILOGD("PrintManagerClient DeletePrinterFromCups start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->DeletePrinterFromCups(printerUri, printerName, printerMake); + PRINT_HILOGD("PrintManagerClient DeletePrinterFromCups out ret = [%{public}d].", ret); + } + return ret; +} + int32_t PrintManagerClient::On(const std::string &taskId, const std::string &type, const sptr &listener) { PRINT_HILOGD("PrintManagerClient On start."); @@ -461,16 +498,71 @@ int32_t PrintManagerClient::Print(const std::string &printJobName, const sptr &listener, - const PrintAttributes &printAttributes, std::string &taskId, void* contextToken) + const PrintAttributes &printAttributes, std::string &taskId, void* uiContent) { - auto func = [printJobName, listener, printAttributes, &taskId, contextToken](sptr serviceProxy) { + if (uiContent == nullptr) { + PRINT_HILOGE("uiContent is nullptr."); + return E_PRINT_INVALID_PARAMETER; + } + PRINT_HILOGI("PrintManagerClient Print start."); + if (taskId.empty()) { + taskId = PrintUtils::GetPrintJobId(); + std::shared_ptr adapterParam = std::make_shared(); + if (adapterParam == nullptr) { + PRINT_HILOGE("create adapterParam failed."); + return E_PRINT_SERVER_FAILURE; + } + adapterParam->documentName = printJobName; + adapterParam->isCheckFdList = false; + adapterParam->printAttributes = printAttributes; + AAFwk::Want want; + SetWantParam(want, taskId); + PrintUtils::BuildAdapterParam(adapterParam, want); + + OHOS::Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + auto printUiContent = static_cast(uiContent); + auto callback = std::make_shared(printUiContent); + OHOS::Ace::ModalUIExtensionCallbacks extensionCallbacks = { + std::bind(&PrintInnerkitModalUICallback::OnRelease, callback, std::placeholders::_1), + std::bind(&PrintInnerkitModalUICallback::OnResultForModal, + callback, std::placeholders::_1, std::placeholders::_2), + std::bind(&PrintInnerkitModalUICallback::OnReceive, callback, std::placeholders::_1), + std::bind(&PrintInnerkitModalUICallback::OnError, + callback, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), + }; + int32_t sessionId = printUiContent->CreateModalUIExtension(want, extensionCallbacks, config); + PRINT_HILOGI("StartUIExtensionAbility sessionId %{public}d", sessionId); + if (callback != nullptr) { + callback->SetSessionId(sessionId); + } + } + + auto func = [printJobName, listener, printAttributes, &taskId](sptr serviceProxy) { serviceProxy->On("", PRINT_CALLBACK_ADAPTER, listener); - sptr token = static_cast(contextToken); - return serviceProxy->PrintByAdapter(printJobName, printAttributes, taskId, token); + return serviceProxy->PrintByAdapter(printJobName, printAttributes, taskId); }; return CALL_COMMON_CLIENT(func); } +void PrintManagerClient::SetWantParam(AAFwk::Want &want, std::string &taskId) +{ + std::vector fileList; + want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_PREVIEW_ABILITY_NAME); + want.SetParam(LAUNCH_PARAMETER_JOB_ID, taskId); + want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList); + int32_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + int32_t callerUid = IPCSkeleton::GetCallingUid(); + int32_t callerPid = IPCSkeleton::GetCallingPid(); + std::string callerPkg = PrintUtils::GetBundleNameForUid(callerUid); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid); + want.SetParam(CALLER_PKG_NAME, callerPkg); + want.SetParam(UI_EXTENSION_TYPE_NAME, PRINT_UI_EXTENSION_TYPE); + want.SetParam(TOKEN_KEY, true); +} + int32_t PrintManagerClient::StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes, const uint32_t fd) { @@ -491,257 +583,6 @@ int32_t PrintManagerClient::NotifyPrintService(const std::string &jobId, const s return ret; } -#ifdef PDFIUM_ENABLE -#ifndef INT_MAX -#define INT_MAX 2147483647 -#endif -static constexpr const int FPDF_CONFIG_VERSION = 2; -static constexpr const double SCALING_RATE = 300.0 / 72.0; -static int pdfiumInitRequestCount = 0; - -static void initializeLibraryIfNeeded() -{ - if (pdfiumInitRequestCount == 0) { - // Init - FPDF_LIBRARY_CONFIG config; - config.version = FPDF_CONFIG_VERSION; - config.m_pUserFontPaths = NULL; - config.m_pIsolate = NULL; - config.m_v8EmbedderSlot = 0; - FPDF_InitLibraryWithConfig(&config); - } - pdfiumInitRequestCount++; -} - -static void destroyLibraryIfNeeded() -{ - if (pdfiumInitRequestCount == 1) { - FPDF_DestroyLibrary(); - } - pdfiumInitRequestCount--; -} - -static FPDF_DOCUMENT LoadPdfFile(const std::string filePath) -{ - initializeLibraryIfNeeded(); - // Load pdf file - FPDF_DOCUMENT doc = FPDF_LoadDocument(filePath.c_str(), nullptr); - return doc; -} - -static bool CheckDimensions(int stride, int width, int height) -{ - if (stride <= 0 || width <= 0 || height <= 0) { - return false; - } - if (height > 0 && stride > INT_MAX / height) { - return false; - } - return true; -} - -static std::vector EncodePng(pdfium::span input, int height, int width, int format, int stride) -{ - std::vector png; - switch (format) { - case FPDFBitmap_Unknown: - break; - case FPDFBitmap_Gray: - PRINT_HILOGD("EncodePng FPDFBitmap_Gray\n"); - png = image_diff_png::EncodeGrayPNG(input, width, height, stride); - break; - case FPDFBitmap_BGR: - PRINT_HILOGD("EncodePng FPDFBitmap_BGR\n"); - png = image_diff_png::EncodeBGRPNG(input, width, height, stride); - break; - case FPDFBitmap_BGRx: - PRINT_HILOGD("EncodePng FPDFBitmap_BGRx\n"); - png = image_diff_png::EncodeBGRAPNG(input, width, height, stride, true); - break; - case FPDFBitmap_BGRA: - PRINT_HILOGD("EncodePng FPDFBitmap_BGRA\n"); - png = image_diff_png::EncodeBGRAPNG(input, width, height, stride, false); - break; - } - return png; -} - -static bool WritePng(std::string imagePath, void *buffer, int width, int height, int stride) -{ - if (!CheckDimensions(stride, width, height)) { - return false; - } - auto input = pdfium::make_span(static_cast(buffer), stride * height); - std::vector png_encoding = EncodePng(input, height, width, FPDFBitmap_BGRA, stride); - if (png_encoding.empty()) { - PRINT_HILOGE("Failed to convert bitmap to PNG\n"); - return false; - } - FILE *fp = fopen(imagePath.c_str(), "wb"); - if (!fp) { - PRINT_HILOGE("Failed to open %s for output\n", imagePath.c_str()); - return false; - } - size_t bytes_written = fwrite(&png_encoding.front(), 1, png_encoding.size(), fp); - if (bytes_written != png_encoding.size()) { - PRINT_HILOGE("Failed to write to %s\n", imagePath.c_str()); - } - (void)fclose(fp); - return true; -} - -static std::string GetImagePathByIndex(std::string basePngName, int32_t pageIndex) -{ - std::string imagePath = basePngName + "-" + std::to_string(pageIndex) + ".png"; - return imagePath; -} - -static ScopedFPDFBitmap BitmapInit(FPDF_PAGE page, uint32_t width, uint32_t height) -{ - int alpha = FPDFPage_HasTransparency(page) ? 1 : 0; - ScopedFPDFBitmap bitmap(FPDFBitmap_Create(width, height, alpha)); - FPDF_DWORD fill_color = alpha ? 0x00000000 : 0xFFFFFFFF; - FPDFBitmap_FillRect(bitmap.get(), 0, 0, width, height, fill_color); - int rotation = 0; - int flags = FPDF_ANNOT; - FPDF_RenderPageBitmap(bitmap.get(), page, 0, 0, width, height, rotation, flags); - return bitmap; -} - -int32_t PrintManagerClient::PdfRenderInit(const std::string filePath, const std::string sandBoxPath, - std::string &basePngName, int32_t &pageCount, FPDF_DOCUMENT &doc) -{ - if (access(sandBoxPath.c_str(), F_OK) != 0) { - PRINT_HILOGE("PdfRenderInit SandBoxPath can't be opened."); - return E_PRINT_INVALID_PARAMETER; - } - // Create floder when the floder isn't exist; - std::string floderPath = sandBoxPath + "/preview/"; - if (access(floderPath.c_str(), F_OK) != 0) { - mkdir(floderPath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); - if (access(floderPath.c_str(), F_OK) == 0) { - PRINT_HILOGD("PdfRenderInit Create floder %{public}s success.", floderPath.c_str()); - } - } - PRINT_HILOGD("PdfRenderInit SandBoxPath:%{public}s.", sandBoxPath.c_str()); - doc = LoadPdfFile(filePath); - if (doc == NULL) { - PRINT_HILOGE("PdfRenderInit Pdfium LoadPdfFile failed."); - return E_PRINT_FILE_IO; - } - size_t filename_start = filePath.find_last_of("/"); - size_t filename_end = filePath.find_last_of("."); - if (filename_start == filePath.npos || filename_end == filePath.npos) { - PRINT_HILOGE("PdfRenderInit Find filename failed."); - return E_PRINT_INVALID_PARAMETER; - } - std::string filename = filePath.substr(filename_start + 1, filename_end - filename_start - 1); - basePngName = floderPath + filename; - PRINT_HILOGD("PdfRenderInit basePngName:%{public}s.", basePngName.c_str()); - // Get pdf file pageCount - pageCount = FPDF_GetPageCount(doc); - if (pageCount == 0) { - PRINT_HILOGE("PdfRenderInit Pdfium GetPageCount failed."); - return E_PRINT_INVALID_PARAMETER; - } - PRINT_HILOGD("PdfRenderInit filePath:%{public}s count %{public}d.", filePath.c_str(), pageCount); - return E_PRINT_NONE; -} - -int32_t PrintManagerClient::PdfRenderDestroy(const std::string basePngName, const int32_t pageCount, - FPDF_DOCUMENT &doc) -{ - for (int32_t pageIndex = 0; pageIndex < pageCount; pageIndex++) { - std::string imagePath = GetImagePathByIndex(basePngName, pageIndex); - if (imagePath.empty()) { - PRINT_HILOGE("PdfRenderDestroy This imagePath is empty."); - return E_PRINT_INVALID_PARAMETER; - } - if (access(imagePath.c_str(), F_OK) == 0) { - PRINT_HILOGD("PdfRenderDestroy Start delete floder %{public}s.", imagePath.c_str()); - unlink(imagePath.c_str()); - } - } - FPDF_CloseDocument(doc); - destroyLibraryIfNeeded(); - return E_PRINT_NONE; -} - -int32_t PrintManagerClient::GetPdfPageSize(const int32_t pageIndex, uint32_t &width, uint32_t &height, - FPDF_DOCUMENT &doc) -{ - if (doc == NULL) { - PRINT_HILOGE("GetPdfPageSize loaded doc is null."); - return E_PRINT_FILE_IO; - } - // Get page of pageIndex from pdf - FPDF_PAGE page = FPDF_LoadPage(doc, pageIndex); - if (page == NULL) { - PRINT_HILOGE("GetPdfPageSize Pdfium FPDF_LoadPage failed."); - return E_PRINT_FILE_IO; - } - // Get pdf's width and length - width = static_cast(FPDF_GetPageWidth(page) * SCALING_RATE); - height = static_cast(FPDF_GetPageHeight(page) * SCALING_RATE); - PRINT_HILOGD("GetPdfPageSize page width: %{public}d, height: %{public}d.", width, height); - FPDF_ClosePage(page); - return E_PRINT_NONE; -} - -int32_t PrintManagerClient::RenderPdfToPng(const std::string basePngName, const int32_t pageIndex, - std::string &imagePath, FPDF_DOCUMENT &doc) -{ - if (doc == NULL) { - PRINT_HILOGE("RenderPdfToPng loaded doc is null.."); - return E_PRINT_FILE_IO; - } - imagePath = GetImagePathByIndex(basePngName, pageIndex); - if (imagePath.empty()) { - PRINT_HILOGE("RenderPdfToPng This imagePath is empty."); - return E_PRINT_INVALID_PARAMETER; - } - if (access(imagePath.c_str(), F_OK) != -1) { - PRINT_HILOGD("RenderPdfToPng This page image is exist %{public}s.", imagePath.c_str()); - return E_PRINT_NONE; - } - // Get pdf file pageCount. - int pageCount = FPDF_GetPageCount(doc); - if (pageCount == 0) { - PRINT_HILOGE("RenderPdfToPng Pdfium GetPageCount failed."); - return E_PRINT_INVALID_PARAMETER; - } - PRINT_HILOGD("RenderPdfToPng %{public}s count %{public}d.", basePngName.c_str(), pageCount); - // Get page of pageIndex from pdf. - FPDF_PAGE page = FPDF_LoadPage(doc, pageIndex); - if (page == NULL) { - PRINT_HILOGE("RenderPdfToPng Pdfium FPDF_LoadPage failed."); - return E_PRINT_FILE_IO; - } - // Get pdf's width and length. - uint32_t width = static_cast(FPDF_GetPageWidth(page) * SCALING_RATE); - uint32_t height = static_cast(FPDF_GetPageHeight(page) * SCALING_RATE); - if (width <= 0 || height <= 0) { - PRINT_HILOGE("RenderPdfToPng pdfium get page's width or height error."); - return E_PRINT_GENERIC_FAILURE; - } - PRINT_HILOGD("RenderPdfToPng page width: %{public}d height: %{public}d.", width, height); - ScopedFPDFBitmap bitmap = BitmapInit(page, width, height); - FPDF_ClosePage(page); - if (bitmap) { - void *buffer = FPDFBitmap_GetBuffer(bitmap.get()); - int stride = FPDFBitmap_GetStride(bitmap.get()); - PRINT_HILOGD("RenderPdfToPng bitmap stride %{public}d.", stride); - if (!WritePng(imagePath, buffer, width, height, stride)) { - unlink(imagePath.c_str()); - } - } else { - PRINT_HILOGE("RenderPdfToPng FPDF_RenderPageBitmap error."); - return E_PRINT_GENERIC_FAILURE; - } - return E_PRINT_NONE; -} -#endif // PDFIUM_ENABLE - int32_t PrintManagerClient::runBase(const char* callerFunName, std::function)> func) { PRINT_HILOGI("PrintManagerClient %{public}s start.", callerFunName); @@ -900,6 +741,17 @@ int32_t PrintManagerClient::SetNativePrinterChangeCallback(const std::string &ty int32_t ret = E_PRINT_RPC_FAILURE; PRINT_HILOGI("PrintManagerClient SetNativePrinterChangeCallback start"); if (LoadServer() && GetPrintServiceProxy()) { + if (cb != nullptr) { + sptr callback = new (std::nothrow) PrintCallback; + if (callback != nullptr) { + callback->SetNativePrinterChangeCallback(cb); + ret = printServiceProxy_->RegisterPrinterCallback(type, callback); + } else { + ret = E_PRINT_GENERIC_FAILURE; + } + } else { + ret = printServiceProxy_->UnregisterPrinterCallback(type); + } } PRINT_HILOGD("PrintManagerClient SetNativePrinterChangeCallback out ret = [%{public}d].", ret); return ret; @@ -996,6 +848,7 @@ int32_t PrintManagerClient::Init() PRINT_HILOGI("nativePrint Init start."); int32_t ret = E_PRINT_RPC_FAILURE; if (LoadServer() && GetPrintServiceProxy()) { + ret = printServiceProxy_->StartService(); } PRINT_HILOGD("PrintManagerClient Init out ret = [%{public}d].", ret); return ret; diff --git a/frameworks/innerkitsimpl/print_impl/src/print_service_proxy.cpp b/frameworks/innerkitsimpl/print_impl/src/print_service_proxy.cpp index ec7edf9..5603009 100644 --- a/frameworks/innerkitsimpl/print_impl/src/print_service_proxy.cpp +++ b/frameworks/innerkitsimpl/print_impl/src/print_service_proxy.cpp @@ -36,42 +36,26 @@ int32_t PrintServiceProxy::GetResult(int retCode, MessageParcel &reply) return retCode; } -int32_t PrintServiceProxy::StartPrint(const std::vector &fileList, - const std::vector &fdList, std::string &taskId) +int32_t PrintServiceProxy::StartService() { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); - PRINT_HILOGD("Current file is %{public}zd", fileList.size()); - for (auto file : fileList) { - PRINT_HILOGD("file is %{private}s", file.c_str()); - } - - data.WriteBool(fileList.size() > 0); - if (!fileList.empty()) { - data.WriteStringVector(fileList); - } - - data.WriteBool(fdList.size() > 0); - if (!fdList.empty()) { - data.WriteInt32(fdList.size()); - for (auto fd : fdList) { - data.WriteFileDescriptor(fd); - } - } - - PRINT_HILOGD("PrintServiceProxy StartPrint started."); - int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_START_PRINT, data, reply, option); + const std::string ndkInfo = "nativePrint"; + data.WriteString(ndkInfo); + PRINT_HILOGI("nativePrint PrintServiceProxy StartService started."); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_START_SERVICE, data, reply, option); ret = GetResult(ret, reply); - taskId = reply.ReadString(); - PRINT_HILOGD("PrintServiceProxy StartPrint ret = [%{public}d] TaskId = %{public}s", ret, taskId.c_str()); + PRINT_HILOGD("PrintServiceProxy CMD_START_SERVICE ret = [%{public}d]", ret); return ret; } -int32_t PrintServiceProxy::StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token) +int32_t PrintServiceProxy::StartPrint(const std::vector &fileList, + const std::vector &fdList, std::string &taskId) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); PRINT_HILOGD("Current file is %{public}zd", fileList.size()); @@ -92,10 +76,8 @@ int32_t PrintServiceProxy::StartPrint(const std::vector &fileList, } } - if (token == nullptr || !data.WriteRemoteObject(token)) { - PRINT_HILOGE("StartPrint, Failed to write remote object."); - return E_PRINT_INVALID_PARAMETER; - } + data.WriteString(taskId); + PRINT_HILOGD("PrintServiceProxy StartPrint started."); int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_START_PRINT, data, reply, option); ret = GetResult(ret, reply); @@ -106,7 +88,8 @@ int32_t PrintServiceProxy::StartPrint(const std::vector &fileList, int32_t PrintServiceProxy::StopPrint(const std::string &taskId) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(taskId); @@ -119,7 +102,8 @@ int32_t PrintServiceProxy::StopPrint(const std::string &taskId) int32_t PrintServiceProxy::ConnectPrinter(const std::string &printerId) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printerId); @@ -132,7 +116,8 @@ int32_t PrintServiceProxy::ConnectPrinter(const std::string &printerId) int32_t PrintServiceProxy::DisconnectPrinter(const std::string &printerId) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printerId); @@ -145,7 +130,8 @@ int32_t PrintServiceProxy::DisconnectPrinter(const std::string &printerId) int32_t PrintServiceProxy::QueryAllExtension(std::vector &extensionInfos) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); PRINT_HILOGD("PrintServiceProxy QueryAllExtension started."); @@ -171,7 +157,8 @@ int32_t PrintServiceProxy::QueryAllExtension(std::vector &ex int32_t PrintServiceProxy::StartDiscoverPrinter(const std::vector &extensionList) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteStringVector(extensionList); @@ -185,7 +172,8 @@ int32_t PrintServiceProxy::StartDiscoverPrinter(const std::vector & int32_t PrintServiceProxy::StopDiscoverPrinter() { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); PRINT_HILOGD("PrintServiceProxy StopDiscoverPrinter started."); @@ -195,9 +183,10 @@ int32_t PrintServiceProxy::StopDiscoverPrinter() return ret; } -int32_t PrintServiceProxy::StartPrintJob(const PrintJob &jobinfo) +int32_t PrintServiceProxy::StartPrintJob(PrintJob &jobinfo) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -211,7 +200,8 @@ int32_t PrintServiceProxy::StartPrintJob(const PrintJob &jobinfo) int32_t PrintServiceProxy::CancelPrintJob(const std::string &jobId) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -225,7 +215,8 @@ int32_t PrintServiceProxy::CancelPrintJob(const std::string &jobId) int32_t PrintServiceProxy::AddPrinters(const std::vector &printerInfos) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteUint32(printerInfos.size()); @@ -242,7 +233,8 @@ int32_t PrintServiceProxy::AddPrinters(const std::vector &printerIn int32_t PrintServiceProxy::RemovePrinters(const std::vector &printerIds) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteStringVector(printerIds); @@ -256,7 +248,8 @@ int32_t PrintServiceProxy::RemovePrinters(const std::vector &printe int32_t PrintServiceProxy::UpdatePrinters(const std::vector &printerInfos) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteUint32(printerInfos.size()); @@ -273,7 +266,8 @@ int32_t PrintServiceProxy::UpdatePrinters(const std::vector &printe int32_t PrintServiceProxy::UpdatePrinterState(const std::string &printerId, uint32_t state) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printerId); @@ -285,24 +279,28 @@ int32_t PrintServiceProxy::UpdatePrinterState(const std::string &printerId, uint return ret; } -int32_t PrintServiceProxy::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) +int32_t PrintServiceProxy::UpdatePrintJobStateOnlyForSystemApp( + const std::string &jobId, uint32_t state, uint32_t subState) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(jobId); data.WriteUint32(state); data.WriteUint32(subState); - PRINT_HILOGD("PrintServiceProxy UpdatePrintJobState started."); - int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTJOBSTATE, data, reply, option); + PRINT_HILOGD("PrintServiceProxy UpdatePrintJobStateOnlyForSystemApp started."); + int32_t ret = Remote()->SendRequest( + OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTJOBSTATE, data, reply, option); ret = GetResult(ret, reply); - PRINT_HILOGD("PrintServiceProxy UpdatePrintJobState out. ret = [%{public}d]", ret); + PRINT_HILOGD("PrintServiceProxy UpdatePrintJobStateOnlyForSystemApp out. ret = [%{public}d]", ret); return ret; } int32_t PrintServiceProxy::UpdateExtensionInfo(const std::string &extInfo) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(extInfo); @@ -315,7 +313,8 @@ int32_t PrintServiceProxy::UpdateExtensionInfo(const std::string &extInfo) int32_t PrintServiceProxy::RequestPreview(const PrintJob &jobinfo, std::string &previewResult) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); jobinfo.Marshalling(data); @@ -330,7 +329,8 @@ int32_t PrintServiceProxy::RequestPreview(const PrintJob &jobinfo, std::string & int32_t PrintServiceProxy::QueryPrinterCapability(const std::string &printerId) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printerId); @@ -342,9 +342,113 @@ int32_t PrintServiceProxy::QueryPrinterCapability(const std::string &printerId) return ret; } +int32_t PrintServiceProxy::QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(printerId); + info.Marshalling(data); + PRINT_HILOGD("PrintServiceProxy QueryPrinterInfoByPrinterId started."); + int32_t ret = Remote()->SendRequest( + OHOS::Print::IPrintInterfaceCode::CMD_QUERYPRINTERINFOBYPRINTERID, data, reply, option); + ret = GetResult(ret, reply); + auto printerInfoPtr = PrinterInfo::Unmarshalling(reply); + if (printerInfoPtr == nullptr) { + PRINT_HILOGE("wrong printJob from data"); + return E_PRINT_GENERIC_FAILURE; + } + info = *printerInfoPtr; + PRINT_HILOGD("PrintServiceProxy QueryPrinterInfoByPrinterId out. ret = [%{public}d]", ret); + return ret; +} + +int32_t PrintServiceProxy::QueryAddedPrinter(std::vector &printerNameList) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + PRINT_HILOGD("PrintServiceProxy QueryAddedPrinter started."); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_QUERYADDEDPRINTER, data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy QueryAddedPrinter out. ret = [%{public}d]", ret); + reply.ReadStringVector(&printerNameList); + PRINT_HILOGD("PrintServiceProxy QueryAddedPrinter printerNameList size %{public}zu.", printerNameList.size()); + return ret; +} + +int32_t PrintServiceProxy::QueryPrinterProperties(const std::string &printerId, + const std::vector &keyList, std::vector &valueList) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(printerId); + data.WriteStringVector(keyList); + PRINT_HILOGD("PrintServiceProxy QueryPrinterProperties started."); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_QUERYPRINTERPROPERTIES, data, reply, + option); + ret = GetResult(ret, reply); + reply.ReadStringVector(&valueList); + PRINT_HILOGD("PrintServiceProxy RemovePrinters out. ret = [%{public}d]", ret); + return ret; +} + +int32_t PrintServiceProxy::StartNativePrintJob(PrintJob &printJob) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + printJob.Marshalling(data); + PRINT_HILOGD("PrintServiceProxy RequestPreview started."); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_STARTNATIVEPRINTJOB, data, reply, + option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy RemovePrinters out. ret = [%{public}d]", ret); + return ret; +} + +int32_t PrintServiceProxy::GetPrinterPreference(const std::string &printerId, std::string &printerPreference) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(printerId); + PRINT_HILOGD("PrintServiceProxy GetPrinterPreference started."); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_GET_PRINTER_PREFERENCE, + data, reply, option); + ret = GetResult(ret, reply); + printerPreference = reply.ReadString(); + PRINT_HILOGI("PrintServiceProxy GetPrinterPreference ret = [%{public}d] GetPrinterPreference = %{public}s", + ret, printerPreference.c_str()); + return ret; +} + +int32_t PrintServiceProxy::SetPrinterPreference(const std::string &printerId, const std::string &printerPreference) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(printerId); + data.WriteString(printerPreference); + PRINT_HILOGI("PrintServiceProxy SetPrinterPreference started."); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_SET_PRINTER_PREFERENCE, + data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGI("PrintServiceProxy SetPrinterPreference ret = [%{public}d]", ret); + return ret; +} + int32_t PrintServiceProxy::QueryAllPrintJob(std::vector &printJobs) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); PRINT_HILOGD("PrintServiceProxy QueryAllPrintJob started."); @@ -370,7 +474,8 @@ int32_t PrintServiceProxy::QueryAllPrintJob(std::vector &printJobs) int32_t PrintServiceProxy::QueryPrintJobById(std::string &printJobId, PrintJob &printJob) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printJobId); @@ -391,7 +496,8 @@ int32_t PrintServiceProxy::QueryPrintJobById(std::string &printJobId, PrintJob & int32_t PrintServiceProxy::AddPrinterToCups(const std::string &printerUri, const std::string &printerName, const std::string &printerMake) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printerUri); @@ -412,7 +518,8 @@ int32_t PrintServiceProxy::AddPrinterToCups(const std::string &printerUri, const int32_t PrintServiceProxy::QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId, PrinterCapability &printerCaps) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printerUri); @@ -432,6 +539,55 @@ int32_t PrintServiceProxy::QueryPrinterCapabilityByUri(const std::string &printe return ret; } +int32_t PrintServiceProxy::NotifyPrintServiceEvent(std::string &jobId, uint32_t event) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(jobId); + data.WriteUint32(event); + PRINT_HILOGD("PrintServiceProxy NotifyPrintServiceEvent started."); + int32_t ret = Remote()->SendRequest( + OHOS::Print::IPrintInterfaceCode::CMD_NOTIFY_PRINT_SERVICE_EVENT, data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy NotifyPrintServiceEvent out. ret = [%{public}d]", ret); + return ret; +} + +int32_t PrintServiceProxy::SetDefaultPrinter(const std::string &printerId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(printerId); + PRINT_HILOGD("PrintServiceProxy SetDefaultPrinter started."); + int32_t ret = + Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_SET_DEFAULT_PRINTERID, data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy SetDefaultPrinter out. ret = [%{public}d]", ret); + return ret; +} + +int32_t PrintServiceProxy::DeletePrinterFromCups( + const std::string &printerUri, const std::string &printerName, const std::string &printerMake) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(printerUri); + data.WriteString(printerName); + data.WriteString(printerMake); + PRINT_HILOGD("PrintServiceProxy DeletePrinterFromCups started."); + int32_t ret = + Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_DELETE_PRINTER_FROM_CUPS, data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy DeletePrinterFromCups out. ret = [%{public}d]", ret); + return ret; +} + int32_t PrintServiceProxy::On(const std::string taskId, const std::string &type, const sptr &listener) { if (listener == nullptr) { @@ -444,7 +600,8 @@ int32_t PrintServiceProxy::On(const std::string taskId, const std::string &type, return E_PRINT_INVALID_PARAMETER; } - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -465,7 +622,8 @@ int32_t PrintServiceProxy::Off(const std::string taskId, const std::string &type return E_PRINT_INVALID_PARAMETER; } - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -477,11 +635,62 @@ int32_t PrintServiceProxy::Off(const std::string taskId, const std::string &type return ret; } +int32_t PrintServiceProxy::RegisterPrinterCallback(const std::string &type, const sptr &listener) +{ + if (listener == nullptr) { + PRINT_HILOGE("listener is nullptr"); + return E_PRINT_INVALID_PARAMETER; + } + + if (type.empty()) { + PRINT_HILOGE("PrintServiceProxy:: type is empty."); + return E_PRINT_INVALID_PARAMETER; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(type); + data.WriteRemoteObject(listener->AsObject().GetRefPtr()); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_REG_PRINTER_CB, data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy RegisterPrinterCallback out. ret = [%{public}d]", ret); + return ret; +} + +int32_t PrintServiceProxy::UnregisterPrinterCallback(const std::string &type) +{ + PRINT_HILOGD("PrintServiceProxy::UnregisterPrinterCallback in"); + if (type.empty()) { + PRINT_HILOGE("PrintServiceProxy::type is empty."); + return E_PRINT_INVALID_PARAMETER; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(GetDescriptor()); + data.WriteString(type); + int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_UNREG_PRINTER_CB, data, reply, option); + ret = GetResult(ret, reply); + PRINT_HILOGD("PrintServiceProxy UnregisterPrinterCallback out. ret = [%{public}d]", ret); + return ret; +} + int32_t PrintServiceProxy::RegisterExtCallback(const std::string &extensionCID, const sptr &listener) { + if (listener == nullptr) { + PRINT_HILOGE("listener is nullptr"); + return E_PRINT_INVALID_PARAMETER; + } + PRINT_HILOGD("PrintServiceProxy::RegisterExtCallback in: %{public}s", extensionCID.c_str()); - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -495,16 +704,17 @@ int32_t PrintServiceProxy::RegisterExtCallback(const std::string &extensionCID, } int32_t PrintServiceProxy::PrintByAdapter(const std::string printJobName, const PrintAttributes &printAttributes, - std::string &taskId, const sptr &token) + std::string &taskId) { PRINT_HILOGI("PrintServiceProxy PrintByAdapter start."); - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(printJobName); printAttributes.Marshalling(data); - data.WriteRemoteObject(token); + data.WriteString(taskId); PRINT_HILOGD("PrintServiceProxy PrintByAdapter started."); int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_STARTPRINTJOB_BY_ADAPTER, data, reply, option); @@ -513,7 +723,6 @@ int32_t PrintServiceProxy::PrintByAdapter(const std::string printJobName, const return E_PRINT_RPC_FAILURE; } ret = GetResult(ret, reply); - taskId = reply.ReadString(); PRINT_HILOGD("PrintServiceProxy PrintByAdapter out. ret = [%{public}d]", ret); return ret; } @@ -521,7 +730,8 @@ int32_t PrintServiceProxy::PrintByAdapter(const std::string printJobName, const int32_t PrintServiceProxy::StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes, const uint32_t fd) { - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -543,7 +753,8 @@ int32_t PrintServiceProxy::StartGetPrintFile(const std::string &jobId, const Pri int32_t PrintServiceProxy::NotifyPrintService(const std::string &jobId, const std::string &type) { PRINT_HILOGD("PrintServiceProxy::NotifyPrintService in"); - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); @@ -559,7 +770,8 @@ int32_t PrintServiceProxy::NotifyPrintService(const std::string &jobId, const st int32_t PrintServiceProxy::UnregisterAllExtCallback(const std::string &extensionId) { PRINT_HILOGD("PrintServiceProxy::UnregisterAllExtCallback in"); - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(extensionId); @@ -572,7 +784,8 @@ int32_t PrintServiceProxy::UnregisterAllExtCallback(const std::string &extension int32_t PrintServiceProxy::LoadExtSuccess(const std::string &extensionId) { PRINT_HILOGD("PrintServiceProxy::LoadExtSuccess in"); - MessageParcel data, reply; + MessageParcel data; + MessageParcel reply; MessageOption option; data.WriteInterfaceToken(GetDescriptor()); data.WriteString(extensionId); diff --git a/frameworks/kits/extension/BUILD.gn b/frameworks/kits/extension/BUILD.gn index 728825f..f931914 100644 --- a/frameworks/kits/extension/BUILD.gn +++ b/frameworks/kits/extension/BUILD.gn @@ -53,6 +53,16 @@ ohos_shared_library("print_extension_framework") { "${print_path}/frameworks/kits/extension/include", ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + sources = [ "src/js_print_callback.cpp", "src/js_print_extension.cpp", @@ -87,12 +97,9 @@ ohos_shared_library("print_extension_framework") { "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hilog:libhilog", - "hitrace:hitrace_meter", - "i18n:intl_util", "ipc:ipc_napi", "ipc:rpc", "napi:ace_napi", - "resource_management:global_resmgr", ] subsystem_name = "print" @@ -105,6 +112,16 @@ ohos_shared_library("print_extension_module") { configs = [ ":ability_config" ] public_configs = [ ":ability_public_config" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + deps = [ ":print_extension_framework" ] external_deps = [ @@ -117,10 +134,7 @@ ohos_shared_library("print_extension_module") { "common_event_service:cesfwk_innerkits", "hilog:libhilog", "hisysevent:libhisysevent", - "hitrace:hitrace_meter", - "i18n:intl_util", "napi:ace_napi", - "resource_management:global_resmgr", ] relative_install_dir = "extensionability" subsystem_name = "print" diff --git a/frameworks/kits/extension/src/js_print_extension.cpp b/frameworks/kits/extension/src/js_print_extension.cpp index e60d9a6..449cfbe 100644 --- a/frameworks/kits/extension/src/js_print_extension.cpp +++ b/frameworks/kits/extension/src/js_print_extension.cpp @@ -246,8 +246,13 @@ void JsPrintExtension::OnCommand(const AAFwk::Want &want, bool restart, int star PRINT_HILOGD("%{public}s ignore.", __func__); return; } - PrintManagerClient::GetInstance()->LoadExtSuccess(extensionId_); + HandleScope handleScope(jsRuntime_); + napi_env nativeEngine = jsRuntime_.GetNapiEnv(); + napi_value nativeWant = OHOS::AppExecFwk::WrapWant(nativeEngine, want); + napi_value argv[] = { nativeWant }; + CallObjectMethod("onCreate", argv, NapiPrintUtils::ARGC_ONE); RegisterCb(); + PrintManagerClient::GetInstance()->LoadExtSuccess(extensionId_); PRINT_HILOGD("%{public}s end.", __func__); } @@ -508,6 +513,7 @@ void JsPrintExtension::RegisterExtensionCb() if (JsPrintExtension::jsExtension_ == nullptr) { return false; } + JsPrintExtension::jsExtension_->OnStop(); return JsPrintExtension::jsExtension_->Callback("onDestroy"); }); } diff --git a/frameworks/models/print_models/BUILD.gn b/frameworks/models/print_models/BUILD.gn index bfd4efb..063ae9b 100644 --- a/frameworks/models/print_models/BUILD.gn +++ b/frameworks/models/print_models/BUILD.gn @@ -17,12 +17,22 @@ config("print_models_config") { visibility = [ ":*" ] include_dirs = [ "include" ] - cflags_cc = [ "-fno-exceptions" ] + cflags_cc = [ "-fexceptions" ] } ohos_shared_library("print_models") { include_dirs = [ "${print_utils_path}/include" ] public_configs = [ ":print_models_config" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + sources = [ "src/print_attributes.cpp", "src/print_extension_info.cpp", @@ -44,16 +54,13 @@ ohos_shared_library("print_models") { "ability_runtime:abilitykit_native", "ability_runtime:data_ability_helper", "ability_runtime:napi_base_context", + "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", - "preferences:native_preferences", - "relational_store:native_appdatafwk", - "relational_store:native_dataability", - "relational_store:native_rdb", "samgr:samgr_proxy", ] diff --git a/frameworks/models/print_models/include/print_page_size.h b/frameworks/models/print_models/include/print_page_size.h index 7f1e302..0331630 100644 --- a/frameworks/models/print_models/include/print_page_size.h +++ b/frameworks/models/print_models/include/print_page_size.h @@ -17,127 +17,10 @@ #define PRINT_PAGESIZE_H #include +#include #include "parcel.h" 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; @@ -145,8 +28,8 @@ using PAGE_SIZE_ID = std::string; class PrintPageSize final : public Parcelable { public: static void BuildPageSizeMap(); - - static PrintPageSize GetPageSize(PageSizeId id); + static PAGE_SIZE_ID MatchPageSize(const std::string& pageString); + static bool FindPageSizeById(const PAGE_SIZE_ID &id, PrintPageSize& pageSize); explicit PrintPageSize(); @@ -156,6 +39,8 @@ public: PrintPageSize &operator=(const PrintPageSize &right); + bool operator==(const PrintPageSize &right); + virtual ~PrintPageSize(); void Reset(); @@ -191,6 +76,7 @@ private: uint32_t width_; uint32_t height_; static std::map> pageSize_; + static std::mutex pageSizeMapMutex; }; } // namespace OHOS::Print #endif // PRINT_PAGESIZE_H diff --git a/frameworks/models/print_models/include/print_utils.h b/frameworks/models/print_models/include/print_utils.h index db1053e..7436f47 100644 --- a/frameworks/models/print_models/include/print_utils.h +++ b/frameworks/models/print_models/include/print_utils.h @@ -17,8 +17,21 @@ #define PRINT_UTILS_H #include +#include "want.h" +#include "bundle_mgr_client.h" +#include +#include + +#include namespace OHOS::Print { +struct AdapterParam { + std::string documentName; + bool isCheckFdList; + PrintAttributes printAttributes; + std::string jobId; +}; + class PrintUtils { public: static std::string ToLower(const std::string &s); @@ -32,6 +45,17 @@ public: static bool IsPathValid(const std::string &filePath); static uint32_t GetIdFromFdPath(const std::string &fdPath); static std::string GetJobStateChar(const uint32_t state); + + static void BuildAdapterParam(const std::shared_ptr &adapterParam, AAFwk::Want &want); + static void BuildPrintAttributesParam(const std::shared_ptr &adapterParam, AAFwk::Want &want); + static void ParseAttributesObjectParamForJson(const PrintAttributes &attrParam, nlohmann::json &attrJson); + static std::string GetBundleNameForUid(const int uid); + static std::string GetPrintJobId(); + static std::string GetEventTypeWithToken(int64_t callerTokenId, const std::string &type); + static std::string GetEventType(const std::string &type); + +private: + static std::mutex instanceLock_; }; } // namespace OHOS::Print #endif // PRINT_UTILS_H diff --git a/frameworks/models/print_models/include/printer_capability.h b/frameworks/models/print_models/include/printer_capability.h index 19d6d68..c2aea53 100644 --- a/frameworks/models/print_models/include/printer_capability.h +++ b/frameworks/models/print_models/include/printer_capability.h @@ -21,6 +21,7 @@ #include "print_margin.h" #include "print_page_size.h" #include "print_resolution.h" +#include namespace OHOS::Print { class PrinterCapability final : public Parcelable { @@ -71,6 +72,14 @@ public: void Dump(); + const char* GetPrinterAttrValue(const char* name); + + void SetPrinterAttrNameAndValue(const char* name, const char* value); + + nlohmann::json GetPrinterAttrGroupJson(); + + void ClearCurPrinterAttrGroup(); + private: bool ReadFromParcel(Parcel &parcel); @@ -87,6 +96,8 @@ private: bool hasOption_; std::string option_; + + std::map printerAttr_group; }; } // namespace OHOS::Print #endif // PRINTER_CAPABILITY_H diff --git a/frameworks/models/print_models/include/printer_info.h b/frameworks/models/print_models/include/printer_info.h index b646f40..2e89799 100644 --- a/frameworks/models/print_models/include/printer_info.h +++ b/frameworks/models/print_models/include/printer_info.h @@ -44,6 +44,12 @@ public: void SetOption(const std::string &option); + void SetIsDefaultPrinter(bool isDefaultPrinter); + + void SetIsLastUsedPrinter(bool isLastUsedPrinter); + + void SetPrinterStatus(uint32_t printerStatus); + [[nodiscard]] const std::string &GetPrinterId() const; [[nodiscard]] const std::string &GetPrinterName() const; @@ -62,6 +68,18 @@ public: [[nodiscard]] std::string GetOption() const; + [[nodiscard]] bool HasIsDefaultPrinter() const; + + [[nodiscard]] bool GetIsDefaultPrinter() const; + + [[nodiscard]] bool HasIsLastUsedPrinter() const; + + [[nodiscard]] bool GetIsLastUsedPrinter() const; + + [[nodiscard]] bool HasPrinterStatus() const; + + [[nodiscard]] uint32_t GetPrinterStatus() const; + virtual bool Marshalling(Parcel &parcel) const override; static std::shared_ptr Unmarshalling(Parcel &parcel); @@ -89,6 +107,18 @@ private: bool hasOption_; std::string option_; + + bool hasIsDefaultPrinter_; + + bool isDefaultPrinter_; + + bool hasIsLastUsedPrinter_; + + bool isLastUsedPrinter_; + + bool hasPrinterStatus_; + + uint32_t printerStatus_; }; } // namespace OHOS::Print #endif // PRINTER_INFO_H diff --git a/frameworks/models/print_models/src/print_attributes.cpp b/frameworks/models/print_models/src/print_attributes.cpp index 7badf81..a99e2c7 100644 --- a/frameworks/models/print_models/src/print_attributes.cpp +++ b/frameworks/models/print_models/src/print_attributes.cpp @@ -268,6 +268,10 @@ bool PrintAttributes::HasOption() const bool PrintAttributes::ReadFromParcel(Parcel &parcel) { + if (parcel.GetReadableBytes() == 0) { + PRINT_HILOGE("no data in parcel"); + return false; + } hasCopyNumber_ = parcel.ReadBool(); if (hasCopyNumber_) { SetCopyNumber(parcel.ReadUint32()); diff --git a/frameworks/models/print_models/src/print_job.cpp b/frameworks/models/print_models/src/print_job.cpp index 59abd0d..cb268f9 100644 --- a/frameworks/models/print_models/src/print_job.cpp +++ b/frameworks/models/print_models/src/print_job.cpp @@ -110,8 +110,7 @@ void PrintJob::SetSubState(uint32_t subState) if (jobState_ == PRINT_JOB_COMPLETED && subState <= PRINT_JOB_COMPLETED_FILE_CORRUPT) { subState_ = subState; } - if (jobState_ == PRINT_JOB_BLOCKED && - (subState < PRINT_JOB_BLOCKED_UNKNOWN && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT)) { + if (jobState_ == PRINT_JOB_BLOCKED && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT) { subState_ = subState; } if (jobState_ == PRINT_JOB_RUNNING && @@ -306,6 +305,10 @@ void PrintJob::ReadParcelFD(Parcel &parcel) void PrintJob::ReadFromParcel(Parcel &parcel) { + if (parcel.GetReadableBytes() == 0) { + PRINT_HILOGE("no data in parcel"); + return; + } ReadParcelFD(parcel); SetJobId(parcel.ReadString()); SetPrinterId(parcel.ReadString()); diff --git a/frameworks/models/print_models/src/print_page_size.cpp b/frameworks/models/print_models/src/print_page_size.cpp index e96b64a..40bd4f4 100644 --- a/frameworks/models/print_models/src/print_page_size.cpp +++ b/frameworks/models/print_models/src/print_page_size.cpp @@ -16,14 +16,176 @@ #include "print_page_size.h" #include "print_log.h" -namespace OHOS::Print { -std::map> PrintPageSize::pageSize_; -void PrintPageSize::BuildPageSizeMap() -{ - PRINT_HILOGD(""); +namespace { +const uint32_t ISO_A0_WIDTH = 33110; +const uint32_t ISO_A0_HEIGHT = 46810; +const uint32_t ISO_A1_WIDTH = 23390; +const uint32_t ISO_A1_HEIGHT = 33110; +const uint32_t ISO_A2_WIDTH = 16540; +const uint32_t ISO_A2_HEIGHT = 23390; +const uint32_t ISO_A3_WIDTH = 11690; +const uint32_t ISO_A3_HEIGHT = 16540; +const uint32_t ISO_A4_WIDTH = 8268; +const uint32_t ISO_A4_HEIGHT = 11692; +const uint32_t ISO_A5_WIDTH = 5830; +const uint32_t ISO_A5_HEIGHT = 8270; +const uint32_t ISO_A6_WIDTH = 4130; +const uint32_t ISO_A6_HEIGHT = 5830; +const uint32_t ISO_B0_WIDTH = 39370; +const uint32_t ISO_B0_HEIGHT = 55670; +const uint32_t ISO_B1_WIDTH = 27830; +const uint32_t ISO_B1_HEIGHT = 39370; +const uint32_t ISO_B2_WIDTH = 19690; +const uint32_t ISO_B2_HEIGHT = 27830; +const uint32_t ISO_B3_WIDTH = 13900; +const uint32_t ISO_B3_HEIGHT = 19690; +const uint32_t ISO_B4_WIDTH = 9840; +const uint32_t ISO_B4_HEIGHT = 13900; +const uint32_t ISO_B5_WIDTH = 6930; +const uint32_t ISO_B5_HEIGHT = 9840; +const uint32_t ISO_C5_WIDTH = 6380; +const uint32_t ISO_C5_HEIGHT = 9020; +const uint32_t ISO_DL_WIDTH = 4330; +const uint32_t ISO_DL_HEIGHT = 8660; +const uint32_t LEGAL_WIDTH = 8500; +const uint32_t LEGAL_HEIGHT = 14000; +const uint32_t LETTER_WIDTH = 4000; +const uint32_t LETTER_HEIGHT = 6000; +const uint32_t ROC_16K_WIDTH = 7677; +const uint32_t ROC_16K_HEIGHT = 10629; +const uint32_t ROC_8K_WIDTH = 10629; +const uint32_t ROC_8K_HEIGHT = 15354; +const uint32_t JIS_B4_WIDTH = 10119; +const uint32_t JIS_B4_HEIGHT = 14331; +const uint32_t JIS_B5_WIDTH = 7165; +const uint32_t JIS_B5_HEIGHT = 10118; +const uint32_t PHOTO_5R_WIDTH = 5000; +const uint32_t PHOTO_5R_HEIGHT = 7000; +const uint32_t PHOTO_4R_WIDTH = 4000; +const uint32_t PHOTO_4R_HEIGHT = 6000; +const uint32_t NA_GOVT_LETTER_8IN_WIDTH = 800; +const uint32_t NA_GOVT_LETTER_8IN_HEIGHT = 10000; +const uint32_t NA_LEDGER_11IN_WIDTH = 11000; +const uint32_t NA_LEDGER_11IN_HEIGHT = 17000; +const uint32_t JPN_HAGAKI_WIDTH = 3940; +const uint32_t JPN_HAGAKI_HEIGHT = 5830; +const uint32_t OM_SDC_PHOTO_WIDTH = 3504; +const uint32_t OM_SDC_PHOTO_HEIGHT = 4685; +const uint32_t OM_CARD_WIDTH = 2126; +const uint32_t OM_CARD_HEIGHT = 3386; +const uint32_t OE_PHOTO_L_WIDTH = 3500; +const uint32_t OE_PHOTO_L_HEIGHT = 5000; +const uint32_t B_TABLOID_L_WIDTH = 11000; +const uint32_t B_TABLOID_L_HEIGHT = 17000; } -PrintPageSize::PrintPageSize() : id_(""), name_("PrintPageSize"), width_(0), height_(0) {} +namespace OHOS::Print { +std::map> PrintPageSize::pageSize_; +std::mutex PrintPageSize::pageSizeMapMutex; + +void UpdatePageSizeMapIso(std::map>& pageSizeMap) +{ + pageSizeMap["ISO_A0"] = + std::make_shared("ISO_A0", "iso_a0_841x1189mm", ISO_A0_WIDTH, ISO_A0_HEIGHT); + pageSizeMap["ISO_A1"] = + std::make_shared("ISO_A1", "iso_a1_594x841mm", ISO_A1_WIDTH, ISO_A1_HEIGHT); + pageSizeMap["ISO_A2"] = + std::make_shared("ISO_A2", "iso_a2_420x594mm", ISO_A2_WIDTH, ISO_A2_HEIGHT); + pageSizeMap["ISO_A3"] = + std::make_shared("ISO_A3", "iso_a3_297x420mm", ISO_A3_WIDTH, ISO_A3_HEIGHT); + pageSizeMap["ISO_A4"] = + std::make_shared("ISO_A4", "iso_a4_210x297mm", ISO_A4_WIDTH, ISO_A4_HEIGHT); + pageSizeMap["ISO_A5"] = + std::make_shared("ISO_A5", "iso_a5_148x210mm", ISO_A5_WIDTH, ISO_A5_HEIGHT); + pageSizeMap["ISO_A6"] = + std::make_shared("ISO_A6", "iso_a6_105x148mm", ISO_A6_WIDTH, ISO_A6_HEIGHT); + pageSizeMap["ISO_B0"] = + std::make_shared("ISO_B0", "iso_b0_1000x1414mm", ISO_B0_WIDTH, ISO_B0_HEIGHT); + pageSizeMap["ISO_B1"] = + std::make_shared("ISO_B1", "iso_b1_707x1000mm", ISO_B1_WIDTH, ISO_B1_HEIGHT); + pageSizeMap["ISO_B2"] = + std::make_shared("ISO_B2", "iso_b2_500x707mm", ISO_B2_WIDTH, ISO_B2_HEIGHT); + pageSizeMap["ISO_B3"] = + std::make_shared("ISO_B3", "iso_b3_353x500mm", ISO_B3_WIDTH, ISO_B3_HEIGHT); + pageSizeMap["ISO_B4"] = + std::make_shared("ISO_B4", "iso_b4_250x353mm", ISO_B4_WIDTH, ISO_B4_HEIGHT); + pageSizeMap["ISO_B5"] = + std::make_shared("ISO_B5", "iso_b5_176x250mm", ISO_B5_WIDTH, ISO_B5_HEIGHT); + pageSizeMap["ISO_C5"] = + std::make_shared("ISO_C5", "iso_c5_162x229mm", ISO_C5_WIDTH, ISO_C5_HEIGHT); + pageSizeMap["ISO_DL"] = + std::make_shared("ISO_DL", "iso_dl_110x220mm", ISO_DL_WIDTH, ISO_DL_HEIGHT); +} +void PrintPageSize::BuildPageSizeMap() +{ + UpdatePageSizeMapIso(pageSize_); + pageSize_["NA_LEGAL"] = + std::make_shared("NA_LEGAL", "na_legal_8.5x14in", LEGAL_WIDTH, LEGAL_HEIGHT); + pageSize_["NA_LETTER"] = + std::make_shared("NA_LETTER", "na_letter_8.5x11in", LETTER_WIDTH, LETTER_HEIGHT); + pageSize_["JIS_B5"] = + std::make_shared("JIS_B5", "jis_b5_182x257mm", JIS_B5_WIDTH, JIS_B5_HEIGHT); + pageSize_["JIS_B4"] = + std::make_shared("JIS_B4", "jis_b4_257x364mm", JIS_B4_WIDTH, JIS_B4_HEIGHT); + pageSize_["NA_INDEX_5X7"] = + std::make_shared("NA_INDEX_5X7", "na_5x7_5x7in", PHOTO_5R_WIDTH, PHOTO_5R_HEIGHT); + pageSize_["NA_INDEX_4X6"] = + std::make_shared("NA_INDEX_4X6", "na_index-4x6_4x6in", PHOTO_4R_WIDTH, PHOTO_4R_HEIGHT); + pageSize_["NA_GOVT_LETTER"] = std::make_shared( + "NA_GOVT_LETTER", "na_govt-letter_8x10in", NA_GOVT_LETTER_8IN_WIDTH, NA_GOVT_LETTER_8IN_HEIGHT); + pageSize_["NA_LEDGER"] = std::make_shared( + "NA_LEDGER", "na_ledger_11x17in", NA_LEDGER_11IN_WIDTH, NA_LEDGER_11IN_HEIGHT); + pageSize_["JPN_HAGAKI"] = std::make_shared( + "JPN_HAGAKI", "jpn_hagaki_100x148mm", JPN_HAGAKI_WIDTH, JPN_HAGAKI_HEIGHT); + pageSize_["OM_DSC_PHOTO"] = std::make_shared( + "OM_DSC_PHOTO", "om_dsc-photo_89x119mm", OM_SDC_PHOTO_WIDTH, OM_SDC_PHOTO_HEIGHT); + pageSize_["OM_CARD"] = std::make_shared( + "OM_CARD", "om_card_54x86mm", OM_CARD_WIDTH, OM_CARD_HEIGHT); + pageSize_["OE_PHOTO_L"] = std::make_shared( + "OE_PHOTO_L", "oe_photo-l_3.5x5in", OE_PHOTO_L_WIDTH, OE_PHOTO_L_HEIGHT); + pageSize_["NA_TABLOID"] = std::make_shared( + "NA_TABLOID", "B_TABLOID", B_TABLOID_L_WIDTH, B_TABLOID_L_HEIGHT); + pageSize_["ROC_16K"] = std::make_shared( + "ROC_16K", "roc_16k_7.75x10.75in", ROC_16K_WIDTH, ROC_16K_HEIGHT); + pageSize_["ROC_8K"] = std::make_shared( + "ROC_8K", "roc_8k_10.75x15.5in", ROC_8K_WIDTH, ROC_8K_HEIGHT); + PRINT_HILOGD("BuildPageSizeMap count = %{public}zu", pageSize_.size()); +} + +PAGE_SIZE_ID PrintPageSize::MatchPageSize(const std::string& pageString) +{ + std::lock_guard lock(pageSizeMapMutex); + if (pageSize_.size() == 0) { + BuildPageSizeMap(); + } + for (auto& item : pageSize_) { + auto pageSizeItem = item.second; + if (pageSizeItem == nullptr) { + continue; + } + if (strcasestr(pageSizeItem->GetName().c_str(), pageString.c_str()) != nullptr) { + return item.first; + } + } + return ""; +} + +bool PrintPageSize::FindPageSizeById(const PAGE_SIZE_ID &id, PrintPageSize& pageSize) +{ + std::lock_guard lock(pageSizeMapMutex); + if (pageSize_.size() == 0) { + BuildPageSizeMap(); + } + auto iter = pageSize_.find(id); + if (iter == pageSize_.end() || iter->second == nullptr) { + return false; + } + pageSize = *(iter->second); + return true; +} + +PrintPageSize::PrintPageSize() : id_(""), name_("PrintPageSize"), width_(0), height_(0) +{} PrintPageSize::PrintPageSize(PAGE_SIZE_ID id, DiscretePageName name, uint32_t width, uint32_t height) { @@ -33,19 +195,6 @@ PrintPageSize::PrintPageSize(PAGE_SIZE_ID id, DiscretePageName name, uint32_t wi height_ = height; } -PrintPageSize PrintPageSize::GetPageSize(PageSizeId id) -{ - uint32_t pageSizeId = (uint32_t)id; - if (pageSizeId < (uint32_t)sizeof(PAGE_SIZE_TABLE)) { - auto 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_; @@ -65,10 +214,14 @@ PrintPageSize &PrintPageSize::operator=(const PrintPageSize &right) return *this; } -PrintPageSize::~PrintPageSize() +bool PrintPageSize::operator==(const PrintPageSize &right) { + return id_ == right.id_; } +PrintPageSize::~PrintPageSize() +{} + void PrintPageSize::Reset() { SetId(""); diff --git a/frameworks/models/print_models/src/print_utils.cpp b/frameworks/models/print_models/src/print_utils.cpp index 54cb397..68891a9 100644 --- a/frameworks/models/print_models/src/print_utils.cpp +++ b/frameworks/models/print_models/src/print_utils.cpp @@ -20,12 +20,29 @@ #include "print_constant.h" #include "print_log.h" #include "securec.h" +#include +#include +#include +#include +#include +#include namespace OHOS::Print { + +using json = nlohmann::json; + +std::mutex PrintUtils::instanceLock_; + +static const std::string LAUNCH_PARAMETER_DOCUMENT_NAME = "documentName"; +static const std::string LAUNCH_PARAMETER_PRINT_ATTRIBUTE = "printAttributes"; + static std::map jobStateMap_; const std::string GLOBAL_ID_DELIMITER = ":"; const std::string EXTENSION_CID_DELIMITER = ":"; const std::string TASK_EVENT_DELIMITER = "-"; +const int32_t DEFAULT_FD = 99; +const int32_t MINIMUN_RANDOM_NUMBER_100 = 100; +const int32_t MAXIMUN_RANDOM_NUMBER_999 = 999; std::string PrintUtils::ToLower(const std::string &s) { @@ -82,8 +99,29 @@ std::string PrintUtils::GetTaskEventId(const std::string &taskId, const std::str return type + TASK_EVENT_DELIMITER + taskId; } +std::string PrintUtils::GetEventTypeWithToken(int64_t callerTokenId, const std::string &type) +{ + std::string eventType = std::to_string(callerTokenId) + TASK_EVENT_DELIMITER + type; + PRINT_HILOGD("eventType: %{public}s", eventType.c_str()); + return eventType; +} + +std::string PrintUtils::GetEventType(const std::string &type) +{ + auto pos = type.find(TASK_EVENT_DELIMITER); + if (pos == std::string::npos || pos + 1 >= type.length()) { + return ""; + } + std::string eventType = type.substr(pos + 1); + PRINT_HILOGD("eventType: %{public}s", eventType.c_str()); + return eventType; +} + int32_t PrintUtils::OpenFile(const std::string &filePath) { + if (filePath.find("content://") == 0) { + return DEFAULT_FD; + } if (!IsPathValid(filePath)) { return PRINT_INVALID_ID; } @@ -137,4 +175,127 @@ std::string PrintUtils::GetJobStateChar(const uint32_t state) } return "PRINT_JOB_UNKNOWN"; } + +void PrintUtils::BuildAdapterParam(const std::shared_ptr &adapterParam, AAFwk::Want &want) +{ + want.SetParam(LAUNCH_PARAMETER_DOCUMENT_NAME, adapterParam->documentName); + if (adapterParam->isCheckFdList) { + std::string defaultAttribute = ""; + want.SetParam(LAUNCH_PARAMETER_PRINT_ATTRIBUTE, defaultAttribute); + return; + } + BuildPrintAttributesParam(adapterParam, want); +} + +void PrintUtils::BuildPrintAttributesParam(const std::shared_ptr &adapterParam, AAFwk::Want &want) +{ + json attrJson; + PrintAttributes attrParam = adapterParam->printAttributes; + if (attrParam.HasCopyNumber()) { + attrJson["copyNumber"] = attrParam.GetCopyNumber(); + } + if (attrParam.HasSequential()) { + attrJson["isSequential"] = attrParam.GetIsSequential(); + } + if (attrParam.HasLandscape()) { + attrJson["isLandscape"] = attrParam.GetIsLandscape(); + } + if (attrParam.HasDirectionMode()) { + attrJson["directionMode"] = attrParam.GetDirectionMode(); + } + if (attrParam.HasColorMode()) { + attrJson["colorMode"] = attrParam.GetColorMode(); + } + if (attrParam.HasDuplexMode()) { + attrJson["duplexMode"] = attrParam.GetDuplexMode(); + } + ParseAttributesObjectParamForJson(attrParam, attrJson); + if (attrParam.HasOption()) { + attrJson["options"] = attrParam.GetOption(); + } + want.SetParam(LAUNCH_PARAMETER_PRINT_ATTRIBUTE, attrJson.dump()); + PRINT_HILOGD("CallSpooler set printAttributes: %{public}s", attrJson.dump().c_str()); +} + +void PrintUtils::ParseAttributesObjectParamForJson(const PrintAttributes &attrParam, nlohmann::json &attrJson) +{ + if (attrParam.HasPageRange()) { + json pageRangeJson; + PrintRange printRangeAttr; + attrParam.GetPageRange(printRangeAttr); + if (printRangeAttr.HasStartPage()) { + pageRangeJson["startPage"] = printRangeAttr.GetStartPage(); + } + if (printRangeAttr.HasEndPage()) { + pageRangeJson["endPage"] = printRangeAttr.GetEndPage(); + } + if (printRangeAttr.HasPages()) { + std::vector pages; + printRangeAttr.GetPages(pages); + pageRangeJson["pages"] = pages; + } + attrJson["pageRange"] = pageRangeJson; + } + if (attrParam.HasPageSize()) { + json pageSizeJson; + PrintPageSize pageSizeAttr; + attrParam.GetPageSize(pageSizeAttr); + pageSizeJson["id"] = pageSizeAttr.GetId(); + pageSizeJson["name"] = pageSizeAttr.GetName(); + pageSizeJson["width"] = pageSizeAttr.GetWidth(); + pageSizeJson["height"] = pageSizeAttr.GetHeight(); + attrJson["pageSize"] = pageSizeJson; + } + if (attrParam.HasMargin()) { + json marginJson; + PrintMargin marginAttr; + attrParam.GetMargin(marginAttr); + if (marginAttr.HasTop()) { + marginJson["top"] = marginAttr.GetTop(); + } + if (marginAttr.HasBottom()) { + marginJson["bottom"] = marginAttr.GetBottom(); + } + if (marginAttr.HasLeft()) { + marginJson["left"] = marginAttr.GetLeft(); + } + if (marginAttr.HasRight()) { + marginJson["right"] = marginAttr.GetRight(); + } + attrJson["margin"] = marginJson; + } +} + +std::string PrintUtils::GetBundleNameForUid(const int uid) +{ + OHOS::AppExecFwk::BundleMgrClient bmsClient; + std::string bundleName = ""; + auto ret = bmsClient.GetNameForUid(uid, bundleName); + if (ret != OHOS::ERR_OK || bundleName.empty()) { + PRINT_HILOGE("get bundleName failed."); + } + PRINT_HILOGI("bundleName: %{public}s", bundleName.c_str()); + return bundleName; +} + +std::string PrintUtils::GetPrintJobId() +{ + std::lock_guard autoLock(instanceLock_); + auto nowTime = std::chrono::system_clock::now(); + auto timestamp = std::chrono::duration_cast(nowTime.time_since_epoch()).count(); + std::stringstream ss; + ss << timestamp; + + std::random_device rd; + std::time_t current_time = time(NULL); + if (current_time == -1) { + return ""; + } + std::mt19937 gen((unsigned int)current_time); + std::uniform_int_distribution<> dis(MINIMUN_RANDOM_NUMBER_100, MAXIMUN_RANDOM_NUMBER_999); + int32_t randomNumber = dis(gen); + std::string jobId = ss.str() + "_" + std::to_string(randomNumber); + PRINT_HILOGI("jobId: %{public}s", jobId.c_str()); + return jobId; +} } // namespace OHOS::Print diff --git a/frameworks/models/print_models/src/printer_capability.cpp b/frameworks/models/print_models/src/printer_capability.cpp index 458cad3..ba16c07 100644 --- a/frameworks/models/print_models/src/printer_capability.cpp +++ b/frameworks/models/print_models/src/printer_capability.cpp @@ -17,6 +17,7 @@ #include "print_constant.h" #include "print_log.h" +using json = nlohmann::json; namespace OHOS::Print { PrinterCapability::PrinterCapability() : colorMode_(0), duplexMode_(0), hasResolution_(false), hasMargin_(false), hasOption_(false), option_("") @@ -253,4 +254,38 @@ void PrinterCapability::Dump() PRINT_HILOGD("option: %{private}s", option_.c_str()); } } + +const char* PrinterCapability::GetPrinterAttrValue(const char* name) +{ + auto iter = printerAttr_group.find(name); + if (iter != printerAttr_group.end()) { + return iter->second.c_str(); + } else { + return ""; + } +} + +void PrinterCapability::SetPrinterAttrNameAndValue(const char* name, const char* value) +{ + printerAttr_group[name] = value; +} + +nlohmann::json PrinterCapability::GetPrinterAttrGroupJson() +{ + if (printerAttr_group.size() < 1) { + PRINT_HILOGI("no printerAttr_group"); + return ""; + } + nlohmann::json printerAttrGroupJson; + for (auto iter = printerAttr_group.begin(); iter != printerAttr_group.end(); iter++) { + printerAttrGroupJson[iter->first] = iter->second; + } + return printerAttrGroupJson; +} + +void PrinterCapability::ClearCurPrinterAttrGroup() +{ + PRINT_HILOGI("printerAttr_group reset"); + printerAttr_group.clear(); +} } // namespace OHOS::Print diff --git a/frameworks/models/print_models/src/printer_info.cpp b/frameworks/models/print_models/src/printer_info.cpp index ef50ba6..77c3244 100644 --- a/frameworks/models/print_models/src/printer_info.cpp +++ b/frameworks/models/print_models/src/printer_info.cpp @@ -18,8 +18,12 @@ #include "print_log.h" namespace OHOS::Print { -PrinterInfo::PrinterInfo() : printerId_(""), printerName_(""), printerState_(PRINTER_UNKNOWN), - printerIcon_(PRINT_INVALID_ID), description_(""), hasCapability_(false), hasOption_(false), option_("") { +PrinterInfo::PrinterInfo() + : printerId_(""), printerName_(""), printerState_(PRINTER_UNKNOWN), printerIcon_(PRINT_INVALID_ID), + description_(""), hasCapability_(false), hasOption_(false), option_(""), hasIsDefaultPrinter_(false), + isDefaultPrinter_(false), hasIsLastUsedPrinter_(false), isLastUsedPrinter_(false), hasPrinterStatus_(false), + printerStatus_(PRINTER_STATUS_UNAVAILABLE) +{ capability_.Reset(); } @@ -34,6 +38,12 @@ PrinterInfo::PrinterInfo(const PrinterInfo &right) capability_ = right.capability_; hasOption_ = right.hasOption_; option_= right.option_; + hasIsDefaultPrinter_ = right.hasIsDefaultPrinter_; + isDefaultPrinter_ = right.isDefaultPrinter_; + hasIsLastUsedPrinter_ = right.hasIsLastUsedPrinter_; + isLastUsedPrinter_ = right.isLastUsedPrinter_; + hasPrinterStatus_ = right.hasPrinterStatus_; + printerStatus_ = right.printerStatus_; } PrinterInfo &PrinterInfo::operator=(const PrinterInfo &right) @@ -48,6 +58,12 @@ PrinterInfo &PrinterInfo::operator=(const PrinterInfo &right) capability_ = right.capability_; hasOption_ = right.hasOption_; option_ = right.option_; + hasIsDefaultPrinter_ = right.hasIsDefaultPrinter_; + isDefaultPrinter_ = right.isDefaultPrinter_; + hasIsLastUsedPrinter_ = right.hasIsLastUsedPrinter_; + isLastUsedPrinter_ = right.isLastUsedPrinter_; + hasPrinterStatus_ = right.hasPrinterStatus_; + printerStatus_ = right.printerStatus_; } return *this; } @@ -93,6 +109,24 @@ void PrinterInfo::SetOption(const std::string &option) option_ = option; } +void PrinterInfo::SetIsDefaultPrinter(bool isDefaultPrinter) +{ + hasIsDefaultPrinter_ = true; + isDefaultPrinter_ = true; +} + +void PrinterInfo::SetIsLastUsedPrinter(bool isLastUsedPrinter) +{ + hasIsLastUsedPrinter_ = true; + isLastUsedPrinter_ = true; +} + +void PrinterInfo::SetPrinterStatus(uint32_t printerStatus) +{ + hasPrinterStatus_ = true; + printerStatus_ = printerStatus; +} + const std::string &PrinterInfo::GetPrinterId() const { return printerId_; @@ -138,8 +172,42 @@ std::string PrinterInfo::GetOption() const return option_; } +bool PrinterInfo::HasIsDefaultPrinter() const +{ + return hasIsDefaultPrinter_; +} + +bool PrinterInfo::GetIsDefaultPrinter() const +{ + return isDefaultPrinter_; +} + +bool PrinterInfo::HasIsLastUsedPrinter() const +{ + return hasIsLastUsedPrinter_; +} + +bool PrinterInfo::GetIsLastUsedPrinter() const +{ + return isLastUsedPrinter_; +} + +bool PrinterInfo::HasPrinterStatus() const +{ + return hasPrinterStatus_; +} + +uint32_t PrinterInfo::GetPrinterStatus() const +{ + return printerStatus_; +} + bool PrinterInfo::ReadFromParcel(Parcel &parcel) { + if (parcel.GetReadableBytes() == 0) { + PRINT_HILOGE("no data in parcel"); + return false; + } SetPrinterId(parcel.ReadString()); SetPrinterName(parcel.ReadString()); SetPrinterState(parcel.ReadUint32()); @@ -171,6 +239,23 @@ bool PrinterInfo::ReadFromParcel(Parcel &parcel) SetOption(parcel.ReadString()); } + hasIsDefaultPrinter_ = parcel.ReadBool(); + if (hasIsDefaultPrinter_) { + isDefaultPrinter_ = parcel.ReadBool(); + } + + hasIsLastUsedPrinter_ = parcel.ReadBool(); + if (hasIsLastUsedPrinter_) { + isLastUsedPrinter_ = parcel.ReadBool(); + } + + hasPrinterStatus_ = parcel.ReadBool(); + PRINT_HILOGD("hasPrinterStatus_: %{public}d", hasPrinterStatus_); + if (hasPrinterStatus_) { + SetPrinterStatus(parcel.ReadUint32()); + PRINT_HILOGD("GetPrinterStatus(): %{public}d", GetPrinterStatus()); + } + return true; } @@ -203,6 +288,23 @@ bool PrinterInfo::Marshalling(Parcel &parcel) const if (hasOption_) { parcel.WriteString(GetOption()); } + + parcel.WriteBool(hasIsDefaultPrinter_); + if (hasIsDefaultPrinter_) { + parcel.WriteBool(isDefaultPrinter_); + } + + parcel.WriteBool(hasIsLastUsedPrinter_); + if (hasIsLastUsedPrinter_) { + parcel.WriteBool(isLastUsedPrinter_); + } + + parcel.WriteBool(hasPrinterStatus_); + PRINT_HILOGD("hasPrinterStatus_: %{public}d", hasPrinterStatus_); + if (hasPrinterStatus_) { + PRINT_HILOGD("GetPrinterStatus(): %{public}d", GetPrinterStatus()); + parcel.WriteUint32(GetPrinterStatus()); + } return true; } @@ -229,5 +331,14 @@ void PrinterInfo::Dump() if (hasOption_) { PRINT_HILOGD("option: %{private}s", option_.c_str()); } + if (hasIsDefaultPrinter_) { + PRINT_HILOGD("isDefaultPrinter: %{public}d", isDefaultPrinter_); + } + if (hasIsLastUsedPrinter_) { + PRINT_HILOGD("isLastUsedPrinter: %{public}d", isLastUsedPrinter_); + } + if (hasPrinterStatus_) { + PRINT_HILOGD("printerStatus: %{public}d", printerStatus_); + } } -} // namespace OHOS::Print \ No newline at end of file +} // namespace OHOS::Print \ No newline at end of file diff --git a/frameworks/ohprint/BUILD.gn b/frameworks/ohprint/BUILD.gn index d1cc6d4..f6fca2e 100755 --- a/frameworks/ohprint/BUILD.gn +++ b/frameworks/ohprint/BUILD.gn @@ -29,6 +29,16 @@ ohos_shared_library("ohprint") { ] public_configs = [ ":print_ndk_config" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + sources = [ "src/print_capi.cpp", "src/print_converter.cpp", @@ -50,16 +60,19 @@ ohos_shared_library("ohprint") { "ability_runtime:abilitykit_native", "ability_runtime:data_ability_helper", "ability_runtime:napi_base_context", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", "ipc:ipc_core", "napi:ace_napi", - "preferences:native_preferences", - "relational_store:native_appdatafwk", - "relational_store:native_dataability", - "relational_store:native_rdb", + "os_account:os_account_innerkits", + "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/frameworks/ohprint/src/print_helper.cpp b/frameworks/ohprint/src/print_helper.cpp index c552830..97d7591 100755 --- a/frameworks/ohprint/src/print_helper.cpp +++ b/frameworks/ohprint/src/print_helper.cpp @@ -26,22 +26,6 @@ using json = nlohmann::json; namespace OHOS::Print { -static std::vector Str2Vec(std::string str) -{ - if (str.size() <= 1) { - return {}; - } - str.pop_back(); - str.erase(str.begin()); - std::vector vec; - std::istringstream is(str); - std::string temp; - while (getline(is, temp, ',')) { - vec.push_back(stoi(temp)); - } - return vec; -} - char *CopyString(const std::string &source) { auto len = source.length(); @@ -349,7 +333,7 @@ void ParsePrinterOpt(const nlohmann::json &cupsOpt, Print_PrinterInfo &nativePri if (cupsOpt.contains(keyword)) { std::string orientationArray = cupsOpt[keyword].get(); PRINT_HILOGD("supported orientations: %{public}s", orientationArray.c_str()); - std::vector orientationVector = Str2Vec(orientationArray); + std::vector orientationVector = PrintUtil::Str2Vec(orientationArray); nativePrinterInfo.capability.supportedOrientations = CopyArray( orientationVector, nativePrinterInfo.capability.supportedOrientationsCount, ConvertOrientationMode); } diff --git a/interfaces/kits/jsnapi/print_extension/BUILD.gn b/interfaces/kits/jsnapi/print_extension/BUILD.gn index ac47c4b..e574c75 100644 --- a/interfaces/kits/jsnapi/print_extension/BUILD.gn +++ b/interfaces/kits/jsnapi/print_extension/BUILD.gn @@ -37,6 +37,16 @@ gen_js_obj("print_extension_abc") { ohos_shared_library("printextensionability_napi") { sources = [ "print_extension_module.cpp" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + deps = [ ":print_extension_abc", ":print_extension_js", diff --git a/interfaces/kits/jsnapi/print_extensionctx/BUILD.gn b/interfaces/kits/jsnapi/print_extensionctx/BUILD.gn index 9f47bb3..1d2aae5 100644 --- a/interfaces/kits/jsnapi/print_extensionctx/BUILD.gn +++ b/interfaces/kits/jsnapi/print_extensionctx/BUILD.gn @@ -37,6 +37,16 @@ gen_js_obj("print_extension_context_abc") { ohos_shared_library("printextensioncontext_napi") { sources = [ "print_extension_context_module.cpp" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + deps = [ ":print_extension_context_abc", ":print_extension_context_js", diff --git a/interfaces/kits/jsnapi/print_extensionctx/print_extension_context.js b/interfaces/kits/jsnapi/print_extensionctx/print_extension_context.js index c1baf9f..1c501ca 100644 --- a/interfaces/kits/jsnapi/print_extensionctx/print_extension_context.js +++ b/interfaces/kits/jsnapi/print_extensionctx/print_extension_context.js @@ -21,19 +21,14 @@ class PrintExtensionContext extends ExtensionContext { 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); + startAbility(want, options, callback) { + console.log('startAbility'); + return this.__context_impl__.startAbility(want, options, callback); } connectAbilityWithAccount(want, accountId, options) { @@ -41,15 +36,20 @@ class PrintExtensionContext extends ExtensionContext { return this.__context_impl__.connectAbilityWithAccount(want, accountId, options); } - disconnectAbility(connection, callback) { - console.log('disconnectAbility'); - return this.__context_impl__.disconnectAbility(connection, callback); + startAbilityWithAccount(want, accountId, options, callback) { + console.log('startAbilityWithAccount'); + return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback); } terminateSelf(callback) { console.log('terminateSelf'); return this.__context_impl__.terminateSelf(callback); } + + disconnectAbility(connection, callback) { + console.log('disconnectAbility'); + return this.__context_impl__.disconnectAbility(connection, callback); + } } export default PrintExtensionContext; \ No newline at end of file diff --git a/interfaces/kits/napi/print_napi/BUILD.gn b/interfaces/kits/napi/print_napi/BUILD.gn index 5cbed41..828a41e 100644 --- a/interfaces/kits/napi/print_napi/BUILD.gn +++ b/interfaces/kits/napi/print_napi/BUILD.gn @@ -32,11 +32,22 @@ ohos_shared_library("print_napi") { ] public_configs = [ ":print_interfaces_kits_napi_config" ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + sources = [ "src/napi_inner_print.cpp", "src/napi_print_ext.cpp", "src/napi_print_task.cpp", "src/print_async_call.cpp", + "src/print_modal_ui_callback.cpp", "src/print_module.cpp", "src/print_task.cpp", ] @@ -45,15 +56,8 @@ ohos_shared_library("print_napi") { "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", "${print_path}/frameworks/models/print_models:print_models", ] - if (pdfium_enable) { - include_dirs += [ "//third_party/pdfium/public" ] - sources += [ - "src/napi_print_pdf_render.cpp", - "src/print_pdf_render.cpp", - ] - cflags_cc += [ "-DPDFIUM_ENABLE" ] - } external_deps = [ + "ability_base:base", "ability_base:want", "ability_base:zuri", "ability_runtime:ability_context_native", @@ -61,15 +65,15 @@ ohos_shared_library("print_napi") { "ability_runtime:abilitykit_native", "ability_runtime:data_ability_helper", "ability_runtime:napi_base_context", + "ability_runtime:ui_extension", + "access_token:libaccesstoken_sdk", + "ace_engine:ace_uicontent", + "bundle_framework:appexecfwk_core", "c_utils:utils", "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", - "preferences:native_preferences", - "relational_store:native_appdatafwk", - "relational_store:native_dataability", - "relational_store:native_rdb", "samgr:samgr_proxy", ] relative_install_dir = "module" diff --git a/interfaces/kits/napi/print_napi/include/napi_inner_print.h b/interfaces/kits/napi/print_napi/include/napi_inner_print.h index b354ca6..ae99335 100644 --- a/interfaces/kits/napi/print_napi/include/napi_inner_print.h +++ b/interfaces/kits/napi/print_napi/include/napi_inner_print.h @@ -27,6 +27,7 @@ #include "print_task.h" #include "printer_info.h" #include "print_utils.h" +#include "print_constant.h" namespace OHOS::Print { class NapiInnerPrint { @@ -49,11 +50,13 @@ public: private: static bool IsSupportType(const std::string& type); + static bool IsValidApplicationEvent(uint32_t event); private: struct InnerPrintContext : public PrintAsyncCall::Context { std::vector allExtensionInfos; std::vector allPrintJobs; + std::vector allPrinters; std::string previewResult = ""; std::string type = ""; sptr callback = nullptr; @@ -65,9 +68,12 @@ private: bool result = false; std::string stateType_ = ""; PrintJob printJob; + PrinterInfo printerInfo; std::string jobId = ""; std::string printerId = ""; std::vector extensionList; + uint32_t applicationEvent = -1; + std::string printerPreference; InnerPrintContext() : Context(nullptr, nullptr) {}; InnerPrintContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {}; diff --git a/interfaces/kits/napi/print_napi/include/napi_print_ext.h b/interfaces/kits/napi/print_napi/include/napi_print_ext.h index 871c9c9..797f35b 100644 --- a/interfaces/kits/napi/print_napi/include/napi_print_ext.h +++ b/interfaces/kits/napi/print_napi/include/napi_print_ext.h @@ -33,10 +33,11 @@ public: static napi_value RemovePrinters(napi_env env, napi_callback_info info); static napi_value UpdatePrinters(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); + static napi_value UpdatePrintJobStateOnlyForSystemApp(napi_env env, napi_callback_info info); static napi_value UpdateExtensionInfo(napi_env env, napi_callback_info info); static napi_value AddPrinterToCups(napi_env env, napi_callback_info info); static napi_value QueryPrinterCapabilityByUri(napi_env env, napi_callback_info info); + static napi_value DeletePrinterFromCups(napi_env env, napi_callback_info info); private: static bool IsValidPrinterState(uint32_t state); diff --git a/interfaces/kits/napi/print_napi/include/print_async_call.h b/interfaces/kits/napi/print_napi/include/print_async_call.h index 1b2a23d..9815277 100644 --- a/interfaces/kits/napi/print_napi/include/print_async_call.h +++ b/interfaces/kits/napi/print_napi/include/print_async_call.h @@ -28,7 +28,7 @@ class PrintAsyncCall final { public: class Context { public: - using InputAction = std::function; + using InputAction = std::function; using OutputAction = std::function; using ExecAction = std::function; Context(InputAction input, OutputAction output) : input_(std::move(input)), output_(std::move(output)) {}; @@ -45,12 +45,13 @@ public: SetAction(nullptr, std::move(output)); } - virtual napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) + virtual napi_status operator()( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) { if (input_ == nullptr) { return napi_ok; } - return input_(env, argc, argv, self); + return input_(env, argc, argv, self, info); } virtual napi_status operator()(napi_env env, napi_value *result) @@ -110,6 +111,7 @@ private: napi_status paramStatus = napi_ok; }; static void DeleteContext(napi_env env, AsyncContext *context); + static uint32_t GetErrorIndex(AsyncContext *context); AsyncContext *context_ = nullptr; napi_env env_ = nullptr; diff --git a/interfaces/kits/napi/print_napi/include/print_context.h b/interfaces/kits/napi/print_napi/include/print_context.h new file mode 100644 index 0000000..bcf097a --- /dev/null +++ b/interfaces/kits/napi/print_napi/include/print_context.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_CONTEXT_H +#define PRINT_CONTEXT_H + +#include "ability_context.h" +#include "ui_extension_context.h" +#include "napi/native_api.h" +#include +#include + +#include "print_log.h" + +namespace OHOS { +namespace Print { + +enum PrintRequestType { + REQUEST_TYPE_START, + REQUEST_TYPE_INVALID, +}; + +struct PrintInfo { + std::string jobId; + std::string fileList; +}; + +struct ErrorMessage { + int32_t code; + std::string message; +}; + +struct BaseContext { + napi_env env = nullptr; + napi_deferred deferred = nullptr; + napi_ref callback = nullptr; + + std::shared_ptr context = nullptr; + std::shared_ptr uiExtensionContext = nullptr; + PrintRequestType requestType = PrintRequestType::REQUEST_TYPE_INVALID; + ErrorMessage errorMessage; + + ~BaseContext() + { + PRINT_HILOGI("release enter"); + if (this->callback != nullptr) { + napi_delete_reference(this->env, this->callback); + this->callback = nullptr; + PRINT_HILOGI("release callback"); + } + + if (this->deferred != nullptr) { + this->deferred = nullptr; + PRINT_HILOGI("release deferred"); + } + PRINT_HILOGI("release exit"); + } +}; + +struct PrintContext : BaseContext { + PrintInfo printInfo; +}; +} // namespace OHOS +} // namespace Print +#endif diff --git a/interfaces/kits/napi/print_napi/include/print_modal_ui_callback.h b/interfaces/kits/napi/print_napi/include/print_modal_ui_callback.h new file mode 100644 index 0000000..d514bd4 --- /dev/null +++ b/interfaces/kits/napi/print_napi/include/print_modal_ui_callback.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_MODAL_UI_CALLBACK_H +#define PRINT_MODAL_UI_CALLBACK_H + +#include "want.h" +#include +#include +#include +#include "napi/native_api.h" +#include "ability_context.h" +#include "ui_extension_context.h" + +#include "print_task.h" +#include "print_context.h" + +namespace OHOS { +namespace Print { + +class PrintModalUICallback { +public: + explicit PrintModalUICallback(std::shared_ptr baseContext); + void OnRelease(int32_t releaseCode); + void OnResultForModal(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string& message); + void SetSessionId(int32_t sessionId); + +private: + static napi_status CreateResultMessage(BaseContext* context, napi_value* result, uint32_t length); + static napi_status CreatePrintResult(PrintContext* context, napi_value& result); + static napi_value CreateBusinessError(const napi_env& env, int32_t errCode, const std::string& errMsg); + void SendMessageBack(); + static void SendMessageBackWork(uv_work_t* work, int statusIn); + int32_t sessionId_ = 0; + std::shared_ptr baseContext = nullptr; + bool isResultForModal = false; +}; +} // namespace Print +} // namespace OHOS +#endif // PRINT_MODAL_UI_CALLBACK_H \ No newline at end of file diff --git a/interfaces/kits/napi/print_napi/include/print_task.h b/interfaces/kits/napi/print_napi/include/print_task.h index 0b69aa1..cae7cca 100644 --- a/interfaces/kits/napi/print_napi/include/print_task.h +++ b/interfaces/kits/napi/print_napi/include/print_task.h @@ -21,11 +21,21 @@ #include #include +#include "ui_content.h" +#include "modal_ui_extension_config.h" +#include "want.h" +#include "napi_base_context.h" +#include "ipc_skeleton.h" +#include "bundle_mgr_client.h" #include "iremote_object.h" -#include "iprint_callback.h" #include "napi/native_api.h" #include "napi/native_common.h" + +#include "iprint_callback.h" #include "print_async_call.h" +#include "print_modal_ui_callback.h" +#include "print_context.h" +#include "print_utils.h" namespace OHOS::Print { class PrintTask { @@ -35,8 +45,8 @@ public: const std::shared_ptr &printAttributes_, const sptr &callerToken_); ~PrintTask(); - uint32_t Start(); - uint32_t StartPrintAdapter(); + uint32_t Start(napi_env env, napi_callback_info info); + uint32_t StartPrintAdapter(napi_env env, napi_callback_info info); void Stop(); const std::string &GetId() const; static napi_value On(napi_env env, napi_callback_info info); @@ -44,6 +54,19 @@ public: bool IsSupportType(const std::string &type) const; +private: + uint32_t CallSpooler(napi_env env, napi_callback_info info, const std::shared_ptr &adapterParam, + bool isPrintByAdapter); + bool ParseAbilityContextReq(napi_env env, const napi_value &obj, + std::shared_ptr &abilityContext, + std::shared_ptr &uiExtensionContext); + void StartUIExtensionAbility( + std::shared_ptr asyncContext, const std::shared_ptr &adapterParam); + uint32_t StartUIExtensionAbility(OHOS::AAFwk::Want &want, std::shared_ptr asyncContext); + OHOS::Ace::UIContent* GetUIContent(const BaseContext *asyncContext); + void CreateDefaultAdapterParam(const std::shared_ptr &adapterParam); + bool CheckPermission(const std::string &name); + private: struct TaskEventContext : public PrintAsyncCall::Context { std::string type = ""; diff --git a/interfaces/kits/napi/print_napi/src/napi_inner_print.cpp b/interfaces/kits/napi/print_napi/src/napi_inner_print.cpp index 9b912c2..0921994 100644 --- a/interfaces/kits/napi/print_napi/src/napi_inner_print.cpp +++ b/interfaces/kits/napi/print_napi/src/napi_inner_print.cpp @@ -24,6 +24,7 @@ #include "print_manager_client.h" #include "print_task.h" #include "iprint_adapter_inner.h" +#include "printer_info_helper.h" namespace OHOS::Print { const std::string PRINTER_EVENT_TYPE = "printerStateChange"; @@ -34,7 +35,9 @@ napi_value NapiInnerPrint::QueryExtensionInfo(napi_env env, napi_callback_info i { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ZERO, " should 0 parameter!", napi_invalid_arg); return napi_ok; }; @@ -69,7 +72,9 @@ napi_value NapiInnerPrint::StartDiscovery(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter StartDiscovery---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); bool isArray = false; napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray); @@ -111,7 +116,9 @@ napi_value NapiInnerPrint::StopDiscovery(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter StopDiscovery---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ZERO, " should 0 parameter!", napi_invalid_arg); return napi_ok; }; @@ -137,7 +144,9 @@ napi_value NapiInnerPrint::ConnectPrinter(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ConnectPrinter---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -169,7 +178,9 @@ napi_value NapiInnerPrint::DisconnectPrinter(napi_env env, napi_callback_info in { PRINT_HILOGD("Enter DisconnectPrinter---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -201,7 +212,9 @@ napi_value NapiInnerPrint::StartPrintJob(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter StartPrintJob---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); auto printJobPtr = PrintJobHelper::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]); if (printJobPtr == nullptr) { @@ -235,7 +248,9 @@ napi_value NapiInnerPrint::CancelPrintJob(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter CancelPrintJob---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -272,7 +287,9 @@ napi_value NapiInnerPrint::RequestPreview(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); auto printJobPtr = PrintJobHelper::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]); if (printJobPtr == nullptr) { @@ -307,7 +324,9 @@ napi_value NapiInnerPrint::QueryCapability(napi_env env, napi_callback_info info { PRINT_HILOGD("Enter QueryCapability---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -339,7 +358,9 @@ napi_value NapiInnerPrint::QueryAllPrintJob(napi_env env, napi_callback_info inf { PRINT_HILOGD("Enter QueryAllPrintJob---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ZERO, " should 0 parameter!", napi_invalid_arg); return napi_ok; }; @@ -371,7 +392,9 @@ napi_value NapiInnerPrint::QueryPrintJobById(napi_env env, napi_callback_info in { PRINT_HILOGD("Enter QueryPrintJobById---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -442,7 +465,9 @@ napi_value NapiInnerPrint::Off(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -517,7 +542,9 @@ napi_value NapiInnerPrint::NotifyPrintService(napi_env env, napi_callback_info i { PRINT_HILOGI("Enter NotifyPrintService---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_TWO, " should 2 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[0], &valuetype), napi_invalid_arg); @@ -526,8 +553,8 @@ napi_value NapiInnerPrint::NotifyPrintService(napi_env env, napi_callback_info i PRINT_ASSERT_BASE(env, valuetype == napi_string, "info type is not a string", napi_string_expected); std::string jobId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[0]); std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[1]); - if (jobId == "" || type == "") { - PRINT_HILOGE("Parse JobId error!"); + if (type == "") { + PRINT_HILOGE("Parse type error!"); context->SetErrorIndex(E_PRINT_INVALID_PARAMETER); return napi_invalid_arg; } @@ -553,9 +580,18 @@ napi_value NapiInnerPrint::NotifyPrintService(napi_env env, napi_callback_info i return asyncCall.Call(env, exec); } -bool NapiInnerPrint::IsSupportType(const std::string& type) +bool NapiInnerPrint::IsSupportType(const std::string &type) { - if (type == PRINTER_EVENT_TYPE || type == PRINTJOB_EVENT_TYPE || type == EXTINFO_EVENT_TYPE) { + if (type == PRINTER_EVENT_TYPE || type == PRINTJOB_EVENT_TYPE || type == EXTINFO_EVENT_TYPE || + type == PRINTER_CHANGE_EVENT_TYPE) { + return true; + } + return false; +} + +bool NapiInnerPrint::IsValidApplicationEvent(uint32_t event) +{ + if (event >= APPLICATION_CREATED && event <= APPLICATION_CLOSED_FOR_CANCELED) { return true; } return false; diff --git a/interfaces/kits/napi/print_napi/src/napi_print_ext.cpp b/interfaces/kits/napi/print_napi/src/napi_print_ext.cpp index 3259afb..413636a 100644 --- a/interfaces/kits/napi/print_napi/src/napi_print_ext.cpp +++ b/interfaces/kits/napi/print_napi/src/napi_print_ext.cpp @@ -26,7 +26,9 @@ napi_value NapiPrintExt::AddPrinters(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); bool isArray = false; napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray); @@ -77,7 +79,9 @@ napi_value NapiPrintExt::RemovePrinters(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); bool isArray = false; @@ -124,7 +128,9 @@ napi_value NapiPrintExt::UpdatePrinters(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); bool isArray = false; napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray); @@ -173,7 +179,9 @@ napi_value NapiPrintExt::UpdatePrinterState(napi_env env, napi_callback_info inf { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_TWO, " should 2 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -217,11 +225,13 @@ napi_value NapiPrintExt::UpdatePrinterState(napi_env env, napi_callback_info inf return asyncCall.Call(env, exec); } -napi_value NapiPrintExt::UpdatePrintJobState(napi_env env, napi_callback_info info) +napi_value NapiPrintExt::UpdatePrintJobStateOnlyForSystemApp(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_THREE, " should 3 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -259,7 +269,7 @@ napi_value NapiPrintExt::UpdatePrintJobState(napi_env env, napi_callback_info in return status; }; auto exec = [context](PrintAsyncCall::Context *ctx) { - int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobState(context->printJobId, + int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp(context->printJobId, context->printJobState, context->jobSubState); context->result = ret == E_PRINT_NONE; if (ret != E_PRINT_NONE) { @@ -276,7 +286,9 @@ napi_value NapiPrintExt::UpdateExtensionInfo(napi_env env, napi_callback_info in { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -315,7 +327,9 @@ napi_value NapiPrintExt::AddPrinterToCups(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter AddPrinterToCups---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_THREE, " should 3 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -363,9 +377,13 @@ napi_value NapiPrintExt::QueryPrinterCapabilityByUri(napi_env env, napi_callback { PRINT_HILOGD("Enter QueryPrinterCapabilityByUri---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE || argc == NapiPrintUtils::ARGC_TWO, - " should 1 or 2 parameter!", napi_invalid_arg); + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { + PRINT_ASSERT_BASE(env, + argc == NapiPrintUtils::ARGC_ONE || argc == NapiPrintUtils::ARGC_TWO, + " should 1 or 2 parameter!", + napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -407,6 +425,58 @@ napi_value NapiPrintExt::QueryPrinterCapabilityByUri(napi_env env, napi_callback return asyncCall.Call(env, exec); } +napi_value NapiPrintExt::DeletePrinterFromCups(napi_env env, napi_callback_info info) +{ + PRINT_HILOGD("Enter DeletePrinterFromCups---->"); + auto context = std::make_shared(); + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { + PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_THREE, " should 3 parameter!", napi_invalid_arg); + napi_valuetype valuetype; + PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); + PRINT_ASSERT_BASE(env, valuetype == napi_string, "printerUri is not a string", napi_string_expected); + + PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype), napi_invalid_arg); + PRINT_ASSERT_BASE(env, valuetype == napi_string, "printerName is not a string", napi_string_expected); + + PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_TWO], &valuetype), napi_invalid_arg); + PRINT_ASSERT_BASE(env, valuetype == napi_string, "printerMake is not a string", napi_string_expected); + + std::string printerUri = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]); + PRINT_HILOGD("printerUri : %{private}s", printerUri.c_str()); + context->printerUri = printerUri; + + std::string printerName = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ONE]); + PRINT_HILOGD("printerName : %{private}s", printerName.c_str()); + context->printerName = printerName; + + std::string printerMake = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_TWO]); + PRINT_HILOGD("printerMake : %{private}s", printerMake.c_str()); + context->printerMake = printerMake; + 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](PrintAsyncCall::Context *ctx) { + int32_t ret = + PrintManagerClient::GetInstance()->DeletePrinterFromCups( + context->printerUri, context->printerName, context->printerMake); + PRINT_HILOGD("ret: %d", ret); + context->result = (ret == E_PRINT_NONE); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("Failed to delete cups printer"); + context->SetErrorIndex(ret); + } + }; + context->SetAction(std::move(input), std::move(output)); + PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + return asyncCall.Call(env, exec); +} + bool NapiPrintExt::IsValidPrinterState(uint32_t state) { if (state >= PRINTER_ADDED && state < PRINTER_UNKNOWN) { @@ -430,4 +500,4 @@ bool NapiPrintExt::IsValidPrintJobSubState(uint32_t subState) } return false; } -} // namespace OHOS::Print +} // namespace OHOS::Print diff --git a/interfaces/kits/napi/print_napi/src/napi_print_task.cpp b/interfaces/kits/napi/print_napi/src/napi_print_task.cpp index b2d7f7b..033cf16 100644 --- a/interfaces/kits/napi/print_napi/src/napi_print_task.cpp +++ b/interfaces/kits/napi/print_napi/src/napi_print_task.cpp @@ -44,7 +44,8 @@ napi_value NapiPrintTask::Print(napi_env env, napi_callback_info info) } auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE || argc == NapiPrintUtils::ARGC_TWO, "need 1 or 2 parameter!", napi_invalid_arg); napi_status checkStatus = VerifyParameters(env, argc, argv, context); @@ -57,19 +58,17 @@ napi_value NapiPrintTask::Print(napi_env env, napi_callback_info info) if ((proxy == nullptr) || (status != napi_ok)) { PRINT_HILOGE("Failed to create print task"); context->SetErrorIndex(E_PRINT_GENERIC_FAILURE); - return napi_generic_failure; } PrintTask *task; PRINT_CALL_BASE(env, napi_unwrap(env, proxy, reinterpret_cast(&task)), napi_invalid_arg); uint32_t ret = E_PRINT_GENERIC_FAILURE; if (task != nullptr) { - ret = task->Start(); + ret = task->Start(env, info); } if (ret != E_PRINT_NONE) { PRINT_HILOGE("Failed to start print task"); context->SetErrorIndex(ret); - return napi_generic_failure; } napi_create_reference(env, proxy, 1, &(context->ref)); return napi_ok; @@ -92,7 +91,9 @@ napi_value NapiPrintTask::PrintByAdapter(napi_env env, napi_callback_info info) { PRINT_HILOGI("PrintByAdapter start ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_FOUR, "need 4 parameter!", napi_invalid_arg); napi_status checkStatus = VerifyParameters(env, argc, argv, context); if (checkStatus != napi_ok) { @@ -111,7 +112,7 @@ napi_value NapiPrintTask::PrintByAdapter(napi_env env, napi_callback_info info) PRINT_CALL_BASE(env, napi_unwrap(env, proxy, reinterpret_cast(&task)), napi_invalid_arg); uint32_t ret = E_PRINT_GENERIC_FAILURE; if (task != nullptr) { - ret = task->StartPrintAdapter(); + ret = task->StartPrintAdapter(env, info); } if (ret != E_PRINT_NONE) { PRINT_HILOGE("Failed to start print task"); @@ -289,7 +290,8 @@ bool NapiPrintTask::IsValidFile(const std::string &fileName) fclose(file); return true; } - if (fileName.find("file://") == 0 || fileName.find("fd://") == 0) { + PRINT_HILOGD("fileName: %{public}s", fileName.c_str()); + if (fileName.find("file://") == 0 || fileName.find("fd://") == 0 || fileName.find("content://") == 0) { return true; } PRINT_HILOGE("invalid file name"); diff --git a/interfaces/kits/napi/print_napi/src/print_async_call.cpp b/interfaces/kits/napi/print_napi/src/print_async_call.cpp index 62664e9..82a166b 100644 --- a/interfaces/kits/napi/print_napi/src/print_async_call.cpp +++ b/interfaces/kits/napi/print_napi/src/print_async_call.cpp @@ -27,7 +27,9 @@ PrintAsyncCall::PrintAsyncCall(napi_env env, napi_callback_info info, napi_value self = nullptr; napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr }; PRINT_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - pos = ((pos == ASYNC_DEFAULT_POS) ? (argc - 1) : pos); + if (argc > 0) { + pos = ((pos == ASYNC_DEFAULT_POS) ? (argc - 1) : pos); + } if (pos >= 0 && pos < argc) { napi_valuetype valueType = napi_undefined; napi_typeof(env, argv[pos], &valueType); @@ -36,7 +38,7 @@ PrintAsyncCall::PrintAsyncCall(napi_env env, napi_callback_info info, argc = pos; } } - context_->paramStatus = (*context)(env, argc, argv, self); + context_->paramStatus = (*context)(env, argc, argv, self, info); context_->ctx = std::move(context); napi_create_reference(env, self, 1, &context_->self); } @@ -104,6 +106,21 @@ void PrintAsyncCall::OnExecute(napi_env env, void *data) } } +uint32_t PrintAsyncCall::GetErrorIndex(AsyncContext *context) +{ + uint32_t errorIndex = E_PRINT_NONE; + if (context->paramStatus != napi_ok) { + errorIndex = E_PRINT_INVALID_PARAMETER; + } else { + if (context->ctx == nullptr) { + errorIndex = E_PRINT_GENERIC_FAILURE; + } else { + errorIndex = context->ctx->GetErrorIndex(); + } + } + return errorIndex; +} + void PrintAsyncCall::OnComplete(napi_env env, napi_status status, void *data) { AsyncContext *context = reinterpret_cast(data); @@ -127,16 +144,7 @@ void PrintAsyncCall::OnComplete(napi_env env, napi_status status, void *data) } } else { napi_value message = nullptr; - uint32_t errorIndex = E_PRINT_NONE; - if (context->paramStatus != napi_ok) { - errorIndex = E_PRINT_INVALID_PARAMETER; - } else { - if (context->ctx == nullptr) { - errorIndex = E_PRINT_GENERIC_FAILURE; - } else { - errorIndex = context->ctx->GetErrorIndex(); - } - } + uint32_t errorIndex = GetErrorIndex(context); PRINT_HILOGE("ErrorMessage: [%{public}s], ErrorIndex:[%{public}d]", GetErrorText(errorIndex).c_str(), errorIndex); napi_create_uint32(env, errorIndex, &message); diff --git a/interfaces/kits/napi/print_napi/src/print_modal_ui_callback.cpp b/interfaces/kits/napi/print_napi/src/print_modal_ui_callback.cpp new file mode 100644 index 0000000..2928da2 --- /dev/null +++ b/interfaces/kits/napi/print_napi/src/print_modal_ui_callback.cpp @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_modal_ui_callback.h" +#include "napi_print_utils.h" + +#include +#include +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi_base_context.h" +#include "ui_content.h" + +using namespace OHOS::Ace; + +#define PRINT_ERROR_CODE "code" +#define PRINT_ERROR_MSG "message" + +namespace OHOS { +namespace Print { + +const uint32_t RESULT_LENGTH_TWO = 2; + +PrintModalUICallback::PrintModalUICallback(std::shared_ptr baseContext) +{ + this->baseContext = baseContext; + PRINT_HILOGI("constructor ModalUICallback"); +} + +void PrintModalUICallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void PrintModalUICallback::OnRelease(int32_t releaseCode) +{ + PRINT_HILOGE("OnRelease enter. release code is %{public}d", releaseCode); + if (this->baseContext == nullptr) { + PRINT_HILOGE("OnRelease baseContext is null"); + return; + } + + if (this->isResultForModal) { + PRINT_HILOGE("SendMessageBack isResultForModal true."); + return; + } + + this->isResultForModal = true; + + this->baseContext->errorMessage.code = E_PRINT_SERVER_FAILURE; + SendMessageBack(); + return; +} + +void PrintModalUICallback::OnReceive(const OHOS::AAFwk::WantParams& request) +{ + PRINT_HILOGI("OnReceive enter."); +} + +void PrintModalUICallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + PRINT_HILOGE("OnError enter. errorCode=%{public}d, name=%{public}s, message=%{public}s", + code, name.c_str(), message.c_str()); + if (this->baseContext == nullptr) { + PRINT_HILOGE("OnError baseContext is null"); + return; + } + + if (this->isResultForModal) { + PRINT_HILOGE("SendMessageBack isResultForModal true."); + return; + } + + this->isResultForModal = true; + + this->baseContext->errorMessage.code = E_PRINT_SERVER_FAILURE; + SendMessageBack(); + return; +} + +void PrintModalUICallback::OnResultForModal(int32_t resultCode, const OHOS::AAFwk::Want& result) +{ + PRINT_HILOGI("OnResultForModal enter. resultCode is %d", resultCode); + if (this->baseContext == nullptr) { + PRINT_HILOGE("OnResultForModal baseContext is null"); + return; + } + + if (this->isResultForModal) { + PRINT_HILOGI("SendMessageBack isResultForModal true."); + return; + } + + this->isResultForModal = true; + + this->baseContext->errorMessage.code = resultCode; + if (this->baseContext->errorMessage.code != E_PRINT_NONE) { + this->baseContext->errorMessage.message = result.GetStringParam("message"); + PRINT_HILOGI("OnResultForModal errorMessage is %s", this->baseContext->errorMessage.message.c_str()); + } + + SendMessageBack(); + return; +} + +void PrintModalUICallback::SendMessageBack() +{ + PRINT_HILOGI("SendMessageBack enter."); + if (this->baseContext == nullptr) { + PRINT_HILOGE("baseContext is null"); + return; + } + + auto abilityContext = this->baseContext->context; + auto uiExtContext = this->baseContext->uiExtensionContext; + OHOS::Ace::UIContent* uiContent = nullptr; + if (abilityContext != nullptr) { + uiContent = abilityContext->GetUIContent(); + } else if (uiExtContext != nullptr) { + uiContent = uiExtContext->GetUIContent(); + } + + if (uiContent != nullptr) { + PRINT_HILOGE("CloseModalUIExtension"); + uiContent->CloseModalUIExtension(this->sessionId_); + } + + uv_loop_s* loop = nullptr; + napi_get_uv_event_loop(this->baseContext->env, &loop); + if (loop == nullptr) { + PRINT_HILOGE("loop is nullptr"); + return; + } + uv_work_t* work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + PRINT_HILOGE("work is nullptr"); + return; + } + BaseContext *printBaseContext = new (std::nothrow) BaseContext(*this->baseContext); + if (printBaseContext == nullptr) { + PRINT_HILOGE("printBaseContext is nullptr."); + delete work; + work = nullptr; + return; + } + work->data = reinterpret_cast(printBaseContext); + + int ret = uv_queue_work( + loop, work, [](uv_work_t* work) { (void)work; }, SendMessageBackWork); + if (ret != 0) { + PRINT_HILOGE("Failed to get uv_queue_work."); + delete printBaseContext; + delete work; + } +} + +void PrintModalUICallback::SendMessageBackWork(uv_work_t* work, int statusIn) +{ + (void)statusIn; + napi_handle_scope scope = nullptr; + if (work == nullptr) { + PRINT_HILOGE("work is nullptr"); + return; + } + BaseContext* context = reinterpret_cast(work->data); + if (context == nullptr) { + PRINT_HILOGE("context is null"); + return; + } + + napi_status status; + size_t resultLength = RESULT_LENGTH_TWO; + size_t errorIndex = NapiPrintUtils::INDEX_ZERO; + size_t resultIndex = NapiPrintUtils::INDEX_ONE; + + napi_open_handle_scope(context->env, &scope); + if (scope == nullptr) { + PRINT_HILOGE("open handle scope failed"); + } + + napi_value result[2] = { nullptr }; + CreateResultMessage(context, result, resultLength); + if (context->deferred) { + if (context->errorMessage.code == E_PRINT_NONE) { + status = napi_resolve_deferred(context->env, context->deferred, result[resultIndex]); + PRINT_HILOGD("promise SUCCEED status %{public}d", (status == napi_ok)); + } else { + status = napi_reject_deferred(context->env, context->deferred, result[errorIndex]); + PRINT_HILOGE("promise FAILD status %{public}d", (status == napi_ok)); + } + } else { + napi_value callback = nullptr; + status = napi_get_reference_value(context->env, context->callback, &callback); + status = napi_call_function(context->env, nullptr, callback, sizeof(result) / sizeof(result[0]), result, + nullptr); + PRINT_HILOGD("callBack status %{public}d", (status == napi_ok)); + } + + PRINT_HILOGD("uv_queue_work callback success"); + napi_close_handle_scope(context->env, scope); + + delete context; + context = nullptr; + + delete work; + work = nullptr; +} + +napi_status PrintModalUICallback::CreateResultMessage(BaseContext* context, napi_value* result, uint32_t length) +{ + PRINT_HILOGD("CreateResultMessage resultLength %{public}d", length); + size_t errorIndex = NapiPrintUtils::INDEX_ZERO; + if (length < RESULT_LENGTH_TWO) { + PRINT_HILOGE("Result length is less than 2."); + return napi_invalid_arg; + } + size_t resultIndex = NapiPrintUtils::INDEX_ONE; + napi_status status; + + if (context == nullptr) { + PRINT_HILOGE("context is nullptr"); + return napi_invalid_arg; + } + PRINT_HILOGD("errorcode: %{public}d", context->errorMessage.code); + if (context->errorMessage.code == E_PRINT_NONE) { + if (context->requestType == PrintRequestType::REQUEST_TYPE_START) { + PrintContext* printContext = static_cast(context); + CreatePrintResult(printContext, result[resultIndex]); + status = napi_get_undefined(context->env, &result[errorIndex]); + return status; + } + status = napi_get_undefined(context->env, &result[resultIndex]); + status = napi_get_undefined(context->env, &result[errorIndex]); + return status; + } else { + result[errorIndex] = + CreateBusinessError(context->env, context->errorMessage.code, context->errorMessage.message); + status = napi_get_undefined(context->env, &result[resultIndex]); + return status; + } +} + +napi_status PrintModalUICallback::CreatePrintResult(PrintContext* printContext, napi_value& result) +{ + if (printContext == nullptr) { + PRINT_HILOGE("printContext is nullptr"); + return napi_invalid_arg; + } + napi_status status = napi_create_object(printContext->env, &result); + if (status != napi_ok) { + PRINT_HILOGE("create js object failed"); + } + return status; +} + +napi_value PrintModalUICallback::CreateBusinessError(const napi_env& env, int32_t errCode, const std::string& errMsg) +{ + PRINT_HILOGD("CreateBusinessError errCode: %{public}d errMsg: %{public}s", errCode, errMsg.c_str()); + + napi_value message = nullptr; + napi_status status = napi_create_string_utf8(env, errMsg.c_str(), NAPI_AUTO_LENGTH, &message); + if (status != napi_ok) { + PRINT_HILOGE("napi create errorMessage failed"); + } + + napi_value code = nullptr; + status = napi_create_int32(env, errCode, &code); + if (status != napi_ok) { + PRINT_HILOGE("napi create errorCode failed"); + } + + napi_value businessError = nullptr; + status = napi_create_object(env, &businessError); + if (status != napi_ok) { + PRINT_HILOGE("napi create businessError failed"); + return businessError; + } + + status = napi_set_named_property(env, businessError, PRINT_ERROR_CODE, code); + if (status != napi_ok) { + PRINT_HILOGE("napi set errorCode failed"); + } + + status = napi_set_named_property(env, businessError, PRINT_ERROR_MSG, message); + if (status != napi_ok) { + PRINT_HILOGE("napi set errorMessage failed"); + } + + PRINT_HILOGI("CreateBusinessError exit"); + return businessError; +} + +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/print_napi/src/print_module.cpp b/interfaces/kits/napi/print_napi/src/print_module.cpp index 6b13d74..ffeea1f 100644 --- a/interfaces/kits/napi/print_napi/src/print_module.cpp +++ b/interfaces/kits/napi/print_napi/src/print_module.cpp @@ -25,9 +25,6 @@ using namespace OHOS::Print; static constexpr const char *FUNCTION_PRINT = "print"; -#ifdef PDFIUM_ENABLE -static constexpr const char *FUNCTION_CREATE_PDF_RENDER = "createPdfRender"; -#endif // PDFIUM_ENABLE static constexpr const char *FUNCTION_QUERY_EXT = "queryAllPrinterExtensionInfos"; static constexpr const char *FUNCTION_START_DISCOVERY = "startDiscoverPrinter"; static constexpr const char *FUNCTION_STOP_DISCOVERY = "stopDiscoverPrinter"; @@ -52,6 +49,7 @@ static constexpr const char *FUNCTION_NATIVE_ADD_PRINTER_TO_CUPS = "addPrinterTo static constexpr const char *FUNCTION_QUERY_CAPABILITY_BY_URI = "queryPrinterCapabilityByUri"; static constexpr const char *FUNCTION_START_GET_PRINT_FILE = "startGettingPrintFile"; static constexpr const char *FUNCTION_NOTIFY_PRINT_SERVICE = "notifyPrintService"; +static constexpr const char *FUNCTION_DELETE_PRINTER_FROM_CUPS = "deletePrinterFromCups"; #define PRINT_NAPI_METHOD(name, func) \ { \ @@ -232,6 +230,27 @@ static napi_value NapiCreatePrintErrorCodeEnum(napi_env env) return object; } +static napi_value NapiCreatePrintStatusEnum(napi_env env) +{ + napi_value object = nullptr; + napi_create_object(env, &object); + SetEnumProperty(env, object, "PRINTER_STATUS_IDLE", static_cast(PRINTER_STATUS_IDLE)); + SetEnumProperty(env, object, "PRINTER_STATUS_BUSY", static_cast(PRINTER_STATUS_BUSY)); + SetEnumProperty(env, object, "PRINTER_STATUS_UNAVAILABLE", static_cast(PRINTER_STATUS_UNAVAILABLE)); + return object; +} + +static napi_value NapiCreatePrintEventEnum(napi_env env) +{ + napi_value object = nullptr; + napi_create_object(env, &object); + SetEnumProperty(env, object, "PRINTER_EVENT_ADDED", static_cast(PRINTER_STATUS_IDLE)); + SetEnumProperty(env, object, "PRINTER_EVENT_DELETED", static_cast(PRINTER_STATUS_BUSY)); + SetEnumProperty(env, object, "PRINTER_EVENT_STATE_CHANGED", static_cast(PRINTER_STATUS_UNAVAILABLE)); + SetEnumProperty(env, object, "PRINTER_EVENT_INFO_CHANGED", static_cast(PRINTER_STATUS_UNAVAILABLE)); + return object; +} + static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { @@ -245,11 +264,10 @@ static napi_value Init(napi_env env, napi_value exports) PRINT_NAPI_PROPERTY("PrintJobState", NapiCreatePrintJobStateEnum(env)), PRINT_NAPI_PROPERTY("PrintJobSubState", NapiCreatePrintJobSubStateEnum(env)), PRINT_NAPI_PROPERTY("PrintErrorCode", NapiCreatePrintErrorCodeEnum(env)), + PRINT_NAPI_PROPERTY("PrinterStatus", NapiCreatePrintStatusEnum(env)), + PRINT_NAPI_PROPERTY("PrinterEvent", NapiCreatePrintEventEnum(env)), PRINT_NAPI_METHOD(FUNCTION_PRINT, NapiPrintTask::Print), -#ifdef PDFIUM_ENABLE - PRINT_NAPI_METHOD(FUNCTION_CREATE_PDF_RENDER, NapiPrintPdfRender::CreatePdfRender), -#endif // PDFIUM_ENABLE PRINT_NAPI_METHOD(FUNCTION_QUERY_EXT, NapiInnerPrint::QueryExtensionInfo), PRINT_NAPI_METHOD(FUNCTION_START_DISCOVERY, NapiInnerPrint::StartDiscovery), PRINT_NAPI_METHOD(FUNCTION_STOP_DISCOVERY, NapiInnerPrint::StopDiscovery), @@ -268,12 +286,13 @@ static napi_value Init(napi_env env, napi_value exports) PRINT_NAPI_METHOD(FUNCTION_REMOVE_PRINTER, NapiPrintExt::RemovePrinters), PRINT_NAPI_METHOD(FUNCTION_UPDATE_PRINTER, NapiPrintExt::UpdatePrinters), PRINT_NAPI_METHOD(FUNCTION_UPDATE_PRINTER_STATE, NapiPrintExt::UpdatePrinterState), - PRINT_NAPI_METHOD(FUNCTION_UPDATE_JOB_STATE, NapiPrintExt::UpdatePrintJobState), + PRINT_NAPI_METHOD(FUNCTION_UPDATE_JOB_STATE, NapiPrintExt::UpdatePrintJobStateOnlyForSystemApp), PRINT_NAPI_METHOD(FUNCTION_UPDATE_EXTENSION_INFO, NapiPrintExt::UpdateExtensionInfo), PRINT_NAPI_METHOD(FUNCTION_NATIVE_ADD_PRINTER_TO_CUPS, NapiPrintExt::AddPrinterToCups), PRINT_NAPI_METHOD(FUNCTION_QUERY_CAPABILITY_BY_URI, NapiPrintExt::QueryPrinterCapabilityByUri), PRINT_NAPI_METHOD(FUNCTION_START_GET_PRINT_FILE, NapiInnerPrint::StartGetPrintFile), PRINT_NAPI_METHOD(FUNCTION_NOTIFY_PRINT_SERVICE, NapiInnerPrint::NotifyPrintService), + PRINT_NAPI_METHOD(FUNCTION_DELETE_PRINTER_FROM_CUPS, NapiPrintExt::DeletePrinterFromCups), }; napi_status status = napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc); diff --git a/interfaces/kits/napi/print_napi/src/print_task.cpp b/interfaces/kits/napi/print_napi/src/print_task.cpp index b395106..9ff7daf 100644 --- a/interfaces/kits/napi/print_napi/src/print_task.cpp +++ b/interfaces/kits/napi/print_napi/src/print_task.cpp @@ -13,20 +13,35 @@ * limitations under the License. */ -#include "print_task.h" #include "napi/native_common.h" +#include "accesstoken_kit.h" + +#include "print_task.h" #include "napi_print_utils.h" #include "print_callback.h" #include "print_log.h" #include "print_manager_client.h" -#include "print_utils.h" +#include "print_constant.h" namespace OHOS::Print { + +using namespace std; +using namespace Security::AccessToken; + const std::string EVENT_BLOCK = "block"; const std::string EVENT_SUCCESS = "succeed"; const std::string EVENT_FAIL = "fail"; const std::string EVENT_CANCEL = "cancel"; +static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler"; +static const std::string SPOOLER_PREVIEW_ABILITY_NAME = "PrintServiceExtAbility"; +static const std::string LAUNCH_PARAMETER_JOB_ID = "jobId"; +static const std::string LAUNCH_PARAMETER_FILE_LIST = "fileList"; +static const std::string TOKEN_KEY = "ohos.ability.params.token"; +static const std::string UI_EXTENSION_TYPE_NAME = "ability.want.params.uiExtensionType"; +static const std::string PRINT_UI_EXTENSION_TYPE = "sysDialog/common"; +static const std::string CALLER_PKG_NAME = "caller.pkgName"; + PrintTask::PrintTask(const std::vector &innerList, const sptr &innerCallerToken_) : taskId_("") { @@ -75,7 +90,7 @@ PrintTask::~PrintTask() Stop(); } -uint32_t PrintTask::Start() +uint32_t PrintTask::Start(napi_env env, napi_callback_info info) { if (fileList_.empty() && fdList_.empty()) { PRINT_HILOGE("fileList and fdList are both empty"); @@ -91,25 +106,243 @@ uint32_t PrintTask::Start() fdList_.emplace_back(fd); } } + if (callerToken_ != nullptr && NEW_PRINT_INTERFACE_SWITCH) { PRINT_HILOGI("call client's new StartPrint interface."); - return PrintManagerClient::GetInstance()->StartPrint(fileList_, fdList_, taskId_, callerToken_); - } else { - PRINT_HILOGI("call client's old StartPrint interface."); - return PrintManagerClient::GetInstance()->StartPrint(fileList_, fdList_, taskId_); + std::shared_ptr adapterParam = std::make_shared(); + CreateDefaultAdapterParam(adapterParam); + std::string jobId = PrintUtils::GetPrintJobId(); + adapterParam->jobId = jobId; + taskId_ = jobId; + uint32_t ret = CallSpooler(env, info, adapterParam, false); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("CallSpooler failed."); + return ret; + } } + return PrintManagerClient::GetInstance()->StartPrint(fileList_, fdList_, taskId_); } -uint32_t PrintTask::StartPrintAdapter() +uint32_t PrintTask::StartPrintAdapter(napi_env env, napi_callback_info info) { if (printAdapterCallback_ != nullptr && printAttributes_ != nullptr) { PRINT_HILOGI("call client's StartPrintAdapter interface."); - return PrintManagerClient::GetInstance()->Print( - printJobName_, printAdapterCallback_, *printAttributes_, taskId_, static_cast(callerToken_)); + if (callerToken_ != nullptr) { + std::shared_ptr adapterParam = std::make_shared(); + if (adapterParam == nullptr) { + PRINT_HILOGE("create adapterParam failed."); + return E_PRINT_SERVER_FAILURE; + } + adapterParam->documentName = printJobName_; + adapterParam->isCheckFdList = false; + adapterParam->printAttributes = *printAttributes_; + std::string jobId = PrintUtils::GetPrintJobId(); + adapterParam->jobId = jobId; + taskId_ = jobId; + uint32_t ret = CallSpooler(env, info, adapterParam, true); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("CallSpooler failed."); + } + return PrintManagerClient::GetInstance()->Print( + printJobName_, printAdapterCallback_, *printAttributes_, taskId_, callerToken_); + } } return E_PRINT_INVALID_PARAMETER; } +uint32_t PrintTask::CallSpooler( + napi_env env, napi_callback_info info, const std::shared_ptr &adapterParam, bool isPrintByAdapter) +{ + PRINT_HILOGI("enter CallSpooler."); + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION); + return E_PRINT_NO_PERMISSION; + } + size_t argc = isPrintByAdapter ? NapiPrintUtils::ARGC_FOUR : NapiPrintUtils::ARGC_TWO; + size_t contextIndex = isPrintByAdapter ? NapiPrintUtils::INDEX_THREE : NapiPrintUtils::INDEX_ONE; + size_t callBackIndex = isPrintByAdapter ? NapiPrintUtils::INDEX_FOUR : NapiPrintUtils::INDEX_TWO; + size_t argMaxNum = isPrintByAdapter ? NapiPrintUtils::ARGC_FIVE : NapiPrintUtils::ARGC_THREE; + napi_value argv[NapiPrintUtils::ARGC_FOUR] = {0}; + napi_value thisArg = nullptr; + void *data = nullptr; + napi_value result = nullptr; + + PRINT_CALL_BASE(env, napi_get_undefined(env, &result), E_PRINT_INVALID_PARAMETER); + PRINT_CALL_BASE(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data), E_PRINT_INVALID_PARAMETER); + PRINT_HILOGI("CallSpooler params size: %{public}zu", argc); + if (argc < argMaxNum - 1) { + PRINT_HILOGE("invalid parameters."); + return E_PRINT_INVALID_PARAMETER; + } + + auto asyncContext = std::make_shared(); + if (asyncContext == nullptr) { + PRINT_HILOGE("create asyncContext failed."); + return E_PRINT_SERVER_FAILURE; + } + asyncContext->env = env; + asyncContext->requestType = PrintRequestType::REQUEST_TYPE_START; + if (!ParseAbilityContextReq(env, argv[contextIndex], asyncContext->context, asyncContext->uiExtensionContext)) { + PRINT_HILOGE("invalid parameters."); + return E_PRINT_INVALID_PARAMETER; + } + + if (argc == argMaxNum) { + napi_valuetype valueType = napi_undefined; + PRINT_CALL_BASE(env, napi_typeof(env, argv[callBackIndex], &valueType), napi_undefined); + if (valueType == napi_function) { + PRINT_CALL_BASE(env, napi_create_reference(env, argv[callBackIndex], 1, &asyncContext->callback), + E_PRINT_INVALID_PARAMETER); + PRINT_HILOGD("is a callback api"); + } + } else { + PRINT_CALL_BASE(env, napi_create_promise(env, &asyncContext->deferred, &result), E_PRINT_INVALID_PARAMETER); + PRINT_HILOGD("is a promise api"); + } + StartUIExtensionAbility(asyncContext, adapterParam); + PRINT_HILOGI("end CallSpooler"); + return E_PRINT_NONE; +} + +bool PrintTask::ParseAbilityContextReq(napi_env env, const napi_value &obj, + std::shared_ptr &abilityContext, + std::shared_ptr &uiExtensionContext) +{ + PRINT_HILOGD("begin ParseAbilityContextReq"); + bool stageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, obj, stageMode); + if (status != napi_ok || !stageMode) { + PRINT_HILOGE("it is not a stage mode"); + return false; + } + + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, obj); + if (context == nullptr) { + PRINT_HILOGE("get context failed"); + return false; + } + + abilityContext = OHOS::AbilityRuntime::Context::ConvertTo(context); + if (abilityContext == nullptr) { + PRINT_HILOGE("get abilityContext failed"); + uiExtensionContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (uiExtensionContext == nullptr) { + PRINT_HILOGE("get uiExtensionContext failed"); + return false; + } + } + + PRINT_HILOGD("end ParseAbilityContextReq"); + return true; +} + +void PrintTask::StartUIExtensionAbility( + std::shared_ptr asyncContext, const std::shared_ptr &adapterParam) +{ + PRINT_HILOGD("begin StartUIExtensionAbility"); + + if (adapterParam == nullptr) { + PRINT_HILOGE("adapterParam is nullptr."); + return; + } + if ((adapterParam->isCheckFdList && fileList_.empty() && fdList_.empty())) { + PRINT_HILOGE("to be printed filelist and fdlist are empty."); + return; + } + AAFwk::Want want; + want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_PREVIEW_ABILITY_NAME); + want.SetParam(LAUNCH_PARAMETER_JOB_ID, adapterParam->jobId); + want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList_); + PrintUtils::BuildAdapterParam(adapterParam, want); + int32_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + int32_t callerUid = IPCSkeleton::GetCallingUid(); + int32_t callerPid = IPCSkeleton::GetCallingPid(); + std::string callerPkg = PrintUtils::GetBundleNameForUid(callerUid); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid); + want.SetParam(CALLER_PKG_NAME, callerPkg); + want.SetParam(UI_EXTENSION_TYPE_NAME, PRINT_UI_EXTENSION_TYPE); + want.SetParam(TOKEN_KEY, callerToken_); + + StartUIExtensionAbility(want, asyncContext); + PRINT_HILOGD("end StartUIExtensionAbility"); + return; +} + +uint32_t PrintTask::StartUIExtensionAbility(OHOS::AAFwk::Want &want, std::shared_ptr asyncContext) +{ + PRINT_HILOGI("begin StartUIExtensionAbility"); + if (asyncContext == nullptr) { + PRINT_HILOGE("asyncContext is nullptr"); + return E_PRINT_INVALID_PARAMETER; + } + + if (asyncContext->context == nullptr && asyncContext->uiExtensionContext == nullptr) { + PRINT_HILOGE("asyncContext is nullptr"); + return E_PRINT_INVALID_PARAMETER; + } + + auto uiContent = GetUIContent(asyncContext.get()); + if (uiContent == nullptr) { + PRINT_HILOGE("UIContent is nullptr"); + return E_PRINT_INVALID_PARAMETER; + } + + std::string info = uiContent->GetContentInfo(); + auto callback = std::make_shared(asyncContext); + if (callback == nullptr) { + PRINT_HILOGE("create callback failed."); + return E_PRINT_SERVER_FAILURE; + } + OHOS::Ace::ModalUIExtensionCallbacks extensionCallbacks = { + std::bind(&PrintModalUICallback::OnRelease, callback, std::placeholders::_1), + std::bind(&PrintModalUICallback::OnResultForModal, callback, std::placeholders::_1, std::placeholders::_2), + std::bind(&PrintModalUICallback::OnReceive, callback, std::placeholders::_1), + std::bind(&PrintModalUICallback::OnError, + callback, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + }; + + OHOS::Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + int32_t sessionId = uiContent->CreateModalUIExtension(want, extensionCallbacks, config); + PRINT_HILOGI("StartUIExtensionAbility sessionId %{public}d", sessionId); + callback->SetSessionId(sessionId); + + PRINT_HILOGI("end StartUIExtensionAbility"); + return E_PRINT_NONE; +} + +OHOS::Ace::UIContent *PrintTask::GetUIContent(const BaseContext *asyncContext) +{ + if (asyncContext == nullptr) { + PRINT_HILOGE("asyncContext is nullptr."); + return nullptr; + } + OHOS::Ace::UIContent *uiContent = nullptr; + if (asyncContext->context != nullptr) { + PRINT_HILOGI("get uiContext by ability context"); + uiContent = asyncContext->context->GetUIContent(); + } else if (asyncContext->uiExtensionContext != nullptr) { + PRINT_HILOGI("get uiContext by ui extension ability context"); + uiContent = asyncContext->uiExtensionContext->GetUIContent(); + } else { + PRINT_HILOGE("get uiContext failed."); + } + + return uiContent; +} + +void PrintTask::CreateDefaultAdapterParam(const std::shared_ptr &adapterParam) +{ + adapterParam->documentName = ""; + adapterParam->isCheckFdList = true; +} + void PrintTask::Stop() { PrintManagerClient::GetInstance()->StopPrint(taskId_); @@ -166,7 +399,13 @@ napi_value PrintTask::Off(napi_env env, napi_callback_info info) { PRINT_HILOGD("Enter ---->"); auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + if (context == nullptr) { + PRINT_HILOGE("create context failed."); + return nullptr; + } + auto input = + [context]( + napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, "need 1 parameter!", napi_invalid_arg); napi_valuetype valuetype; PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); @@ -207,4 +446,19 @@ bool PrintTask::IsSupportType(const std::string &type) const { return supportEvents_.find(type) != supportEvents_.end(); } + +bool PrintTask::CheckPermission(const std::string &name) +{ + AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); + TypeATokenTypeEnum tokenType = AccessTokenKit::GetTokenTypeFlag(tokenId); + if (tokenType == TOKEN_INVALID) { + PRINT_HILOGE("invalid token id %{public}d", tokenId); + return false; + } + int result = AccessTokenKit::VerifyAccessToken(tokenId, name); + if (result != PERMISSION_GRANTED) { + PRINT_HILOGE("Current tokenId permission is %{public}d", result); + } + return result == PERMISSION_GRANTED; +} } // namespace OHOS::Print diff --git a/interfaces/kits/ndk/ohprint/BUILD.gn b/interfaces/kits/ndk/ohprint/BUILD.gn new file mode 100644 index 0000000..80b5881 --- /dev/null +++ b/interfaces/kits/ndk/ohprint/BUILD.gn @@ -0,0 +1,34 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/ohos/ndk/ndk.gni") + +ohos_ndk_headers("ohprint_header") { + dest_dir = "$ndk_headers_out_dir/ohprint" + sources = [ + "${print_path}/frameworks/ohprint/include/print_base.h", + "${print_path}/frameworks/ohprint/include/print_capi.h", + ] +} + +ohos_ndk_library("libohprint_ndk") { + output_name = "ohprint" + output_extension = "so" + ndk_description_file = "./libohprint.ndk.json" + system_capability = "SystemCapability.Print.PrintFramework" + system_capability_headers = [ + "ohprint/print_base.h", + "ohprint/print_capi.h", + ] +} diff --git a/interfaces/kits/ndk/ohprint/libohprint.ndk.json b/interfaces/kits/ndk/ohprint/libohprint.ndk.json new file mode 100644 index 0000000..28feec0 --- /dev/null +++ b/interfaces/kits/ndk/ohprint/libohprint.ndk.json @@ -0,0 +1,74 @@ +[ + { + "first_introduced": "12", + "name": "OH_Print_Init" + }, + { + "first_introduced": "12", + "name": "OH_Print_Release" + }, + { + "first_introduced": "12", + "name": "OH_Print_StartPrinterDiscovery" + }, + { + "first_introduced": "12", + "name": "OH_Print_StopPrinterDiscovery" + }, + { + "first_introduced": "12", + "name": "OH_Print_ConnectPrinter" + }, + { + "first_introduced": "12", + "name": "OH_Print_StartPrintJob" + }, + { + "first_introduced": "12", + "name": "OH_Print_RegisterPrinterChangeListener" + }, + { + "first_introduced": "12", + "name": "OH_Print_UnregisterPrinterChangeListener" + }, + { + "first_introduced": "12", + "name": "OH_Print_QueryPrinterList" + }, + { + "first_introduced": "12", + "name": "OH_Print_ReleasePrinterList" + }, + { + "first_introduced": "12", + "name": "OH_Print_QueryPrinterInfo" + }, + { + "first_introduced": "12", + "name": "OH_Print_ReleasePrinterInfo" + }, + { + "first_introduced": "12", + "name": "OH_Print_LaunchPrinterManager" + }, + { + "first_introduced": "12", + "name": "OH_Print_QueryPrinterProperties" + }, + { + "first_introduced": "12", + "name": "OH_Print_ReleasePrinterProperties" + }, + { + "first_introduced": "12", + "name": "OH_Print_UpdatePrinterProperties" + }, + { + "first_introduced": "12", + "name": "OH_Print_RestorePrinterProperties" + }, + { + "first_introduced": "12", + "name": "OH_Print_LaunchPrinterPreference" + } +] diff --git a/print.gni b/print.gni index 8b85285..b025d17 100644 --- a/print.gni +++ b/print.gni @@ -25,4 +25,6 @@ if (!defined(global_parts_info) || security_guard_enabled = false } cups_enable = true -pdfium_enable = false +jpeg_enable = true +debug_enable = false +ipp_over_usb_enable = false diff --git a/services/print_service/BUILD.gn b/services/print_service/BUILD.gn index 81912c9..95a747f 100644 --- a/services/print_service/BUILD.gn +++ b/services/print_service/BUILD.gn @@ -23,7 +23,7 @@ config("print_service_config") { "${print_path}/frameworks/models/print_models/include", ] - cflags_cc += [ "-fno-exceptions" ] + cflags_cc += [ "-fexceptions" ] } ohos_shared_library("print_service") { @@ -32,14 +32,28 @@ ohos_shared_library("print_service") { "src/print_bms_death_recipient.cpp", "src/print_bms_helper.cpp", "src/print_callback_proxy.cpp", + "src/print_event_subscriber.cpp", "src/print_extension_callback_proxy.cpp", "src/print_security_guard_info.cpp", "src/print_security_guard_manager.cpp", "src/print_service_ability.cpp", + "src/print_service_converter.cpp", "src/print_service_helper.cpp", "src/print_service_stub.cpp", + "src/print_system_data.cpp", + "src/print_user_data.cpp", ] + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + boundary_sanitize = true + debug = false + integer_overflow = true + ubsan = true + } + public_configs = [ "${c_utils_path}/base:utils_config", ":print_service_config", @@ -48,17 +62,8 @@ ohos_shared_library("print_service") { "${print_path}/frameworks/innerkitsimpl/print_impl/include", "${print_utils_path}/include", ] - deps = [ "${print_path}/frameworks/models/print_models:print_models" ] - if (cups_enable) { - include_dirs += [ "//third_party/cups/cups-2.4.0" ] - sources += [ "src/print_cups_client.cpp" ] - cflags_cc += [ "-DCUPS_ENABLE" ] - deps += [ - "//third_party/cups:third_party_cups", - "//third_party/cups-filters:third_party_cupsfilters", - ] - } + deps = [ "${print_path}/frameworks/models/print_models:print_models" ] external_deps = [ "ability_base:base", @@ -71,23 +76,45 @@ ohos_shared_library("print_service") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "core_service:tel_core_service_api", - "distributed_notification_service:ans_innerkits", + "drivers_interface_usb:libusb_proxy_1.0", "eventhandler:libeventhandler", "hilog:libhilog", "hisysevent:libhisysevent", - "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "napi:ace_napi", - "netmanager_base:net_conn_manager_if", "os_account:os_account_innerkits", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "usb_manager:usbsrv_client", "wifi:wifi_sdk", ] + if (cups_enable) { + include_dirs += [ "//third_party/cups/cups-2.4.0" ] + sources += [ "src/print_cups_attribute.cpp" ] + sources += [ "src/print_cups_client.cpp" ] + cflags_cc += [ "-DCUPS_ENABLE" ] + deps += [ + "//third_party/cups:third_party_cups", + "//third_party/cups-filters:third_party_cupsfilters", + ] + external_deps += [ "cJSON:cjson" ] + } + + if (ipp_over_usb_enable) { + include_dirs += [ "//third_party/cpp-httplib" ] + sources += [ + "src/print_http_request_process.cpp", + "src/print_http_server_manager.cpp", + "src/print_ipp_over_usb_manager.cpp", + "src/print_usb_manager.cpp", + ] + cflags_cc += [ "-DCPPHTTPLIB_NO_EXCEPTIONS" ] + cflags_cc += [ "-DCPPHTTPLIB_RECV_BUFSIZ=4096ul" ] + cflags_cc += [ "-DIPPOVERUSB_ENABLE" ] + } + if (security_guard_enabled) { external_deps += [ "security_guard:libsg_collect_sdk", diff --git a/services/print_service/include/print_attribute_preference.h b/services/print_service/include/print_attribute_preference.h new file mode 100644 index 0000000..ac04cd4 --- /dev/null +++ b/services/print_service/include/print_attribute_preference.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_ATTRIBUTR_PREFERENCE_H +#define PRINT_ATTRIBUTR_PREFERENCE_H + +#include +#include +#include + +using json = nlohmann::json; +namespace OHOS::Print { +class PreferenceSetting { +public: + std::string pagesizeId; + std::string orientation; + std::string duplex; + std::string quality; + PreferenceSetting() {}; + PreferenceSetting(std::string pagesizeId, std::string orientation, std::string duplex, std::string quality) + : pagesizeId(pagesizeId), orientation(orientation), duplex(duplex), quality(quality) {} + + static PreferenceSetting BuildPreferenceSettingFromJson(const json& printerAttr) + { + return { + printerAttr.at("pagesizeId").get(), + printerAttr.at("orientation").get(), + printerAttr.at("duplex").get(), + printerAttr.at("quality").get() + }; + } + + json BuildPreferenceSettingJson() const + { + return json{{"pagesizeId", pagesizeId}, {"orientation", orientation}, + {"duplex", duplex}, {"quality", quality}}; + } + ~PreferenceSetting() {}; +}; + +class PrinterPreference { +public: + std::vector pagesizeId; + std::vector orientation; + std::vector duplex; + std::vector quality; + PreferenceSetting defaultSetting; + PreferenceSetting setting; + PrinterPreference() {}; + PrinterPreference(std::vector pagesizeId, std::vector orientation, + std::vector duplex, std::vector quality, + PreferenceSetting defaultSetting, PreferenceSetting setting) + : pagesizeId(pagesizeId), orientation(orientation), duplex(duplex), quality(quality), + defaultSetting(defaultSetting), setting(setting) {} + + static PrinterPreference BuildPrinterPreferenceFromJson(const json& printerAttrs) + { + return { + printerAttrs.at("pagesizeId").get>(), + printerAttrs.at("orientation").get>(), + printerAttrs.at("duplex").get>(), + printerAttrs.at("quality").get>(), + PreferenceSetting::BuildPreferenceSettingFromJson(printerAttrs.at("defaultSetting")), + PreferenceSetting::BuildPreferenceSettingFromJson(printerAttrs.at("setting")) + }; + } + + json BuildPrinterPreferenceJson() const + { + return json{ + {"pagesizeId", pagesizeId}, + {"orientation", orientation}, + {"duplex", duplex}, + {"quality", quality}, + {"defaultSetting", defaultSetting.BuildPreferenceSettingJson()}, + {"setting", setting.BuildPreferenceSettingJson()} + }; + } + ~PrinterPreference() {}; +}; +} +#endif \ No newline at end of file diff --git a/services/print_service/include/print_bms_helper.h b/services/print_service/include/print_bms_helper.h index 80c1a54..52a0686 100644 --- a/services/print_service/include/print_bms_helper.h +++ b/services/print_service/include/print_bms_helper.h @@ -32,7 +32,7 @@ public: virtual ~PrintBMSHelper(); - void SetHelper(const std::shared_ptr &helper); + void SetHelper(std::shared_ptr &helper); bool QueryExtensionInfos(std::vector &extensionInfo); diff --git a/services/print_service/include/print_cups_attribute.h b/services/print_service/include/print_cups_attribute.h new file mode 100644 index 0000000..fbc5a8d --- /dev/null +++ b/services/print_service/include/print_cups_attribute.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_CUPS_ATTRIBUTE_H +#define PRINT_CUPS_ATTRIBUTE_H + +#include +#include "printer_capability.h" + +namespace OHOS::Print { +void ParsePrinterAttributes(ipp_t *response, PrinterCapability &printerCaps); +} // namespace OHOS::Print +#endif // PRINT_CUPS_ATTRIBUTE_H \ No newline at end of file diff --git a/services/print_service/include/print_cups_client.h b/services/print_service/include/print_cups_client.h index aa0d89d..a431bc3 100644 --- a/services/print_service/include/print_cups_client.h +++ b/services/print_service/include/print_cups_client.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include "singleton.h" @@ -30,45 +31,6 @@ namespace OHOS::Print { using json = nlohmann::json; typedef std::function CallbackFunc; -enum MediaTypeCode { - MEDIA_PLAIN = 0, - MEDIA_SPECIAL = 1, - MEDIA_PHOTO = 2, - MEDIA_TRANSPARENCY = 3, - MEDIA_IRON_ON = 4, - MEDIA_IRON_ON_MIRROR = 5, - MEDIA_ADVANCED_PHOTO = 6, - MEDIA_FAST_TRANSPARENCY = 7, - MEDIA_BROCHURE_GLOSSY = 8, - MEDIA_BROCHURE_MATTE = 9, - MEDIA_PHOTO_GLOSSY = 10, - MEDIA_PHOTO_MATTE = 11, - MEDIA_PREMIUM_PHOTO = 12, - MEDIA_OTHER_PHOTO = 13, - MEDIA_PRINTABLE_CD = 14, - MEDIA_PREMIUM_PRESENTATION = 15, - MEDIA_AUTO = 98, - MEDIA_UNKNOWN = 99 -}; - -enum DuplexModeCode { - DUPLEX_MODE_ONE_SIDED = 0, - DUPLEX_MODE_TWO_SIDED_LONG_EDGE = 1, - DUPLEX_MODE_TWO_SIDED_SHORT_EDGE = 2, -}; - -enum ColorModeCode { - COLOR_MODE_MONOCHROME = 0, - COLOR_MODE_COLOR = 1, - COLOR_MODE_AUTO = 2 -}; - -enum PrintQualityCode { - PRINT_QUALITY_DRAFT = 3, - PRINT_QUALITY_NORMAL = 4, - PRINT_QUALITY_HIGH = 5 -}; - struct JobParameters { uint32_t cupsJobId; uint32_t borderless; @@ -87,7 +49,9 @@ struct JobParameters { std::string serviceJobId; std::vector fdList; PrintServiceAbility *serviceAbility; + std::string printerAttrsOption_cupsOption; }; + struct JobStatus { char printer_state_reasons[1024]; ipp_jstate_t job_state; @@ -123,6 +87,16 @@ public: void AddCupsPrintJob(const PrintJob &jobInfo); void CancelCupsJob(std::string serviceJobId); + int32_t QueryAddedPrinterList(std::vector &printerName); + ppd_file_t* GetPPDFile(const std::string &printerName); + int32_t SetDefaultPrinter(const std::string &printerName); + + int32_t QueryPrinterAttrList(const std::string &printerName, const std::vector &keyList, + std::vector &valueList); + int32_t QueryPrinterInfoByPrinterId(const std::string& printerId, PrinterInfo &info); + int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake); + private: static void StartCupsJob(JobParameters *jobParams, CallbackFunc callback); static void MonitorJobState(JobMonitorParam *param, CallbackFunc callback); @@ -139,8 +113,12 @@ private: static int FillBorderlessOptions(JobParameters *jobParams, int num_options, cups_option_t **options); static int FillJobOptions(JobParameters *jobParams, int num_options, cups_option_t **options); static float ConvertInchTo100MM(float num); + static void UpdateJobStatus(JobStatus *prevousJobStatus, JobStatus *jobStatus); + static void UpdatePrintJobStateInJobParams(JobParameters *jobParams, uint32_t state, uint32_t subState); static std::string GetIpAddress(unsigned int number); static bool IsIpConflict(const std::string &printerId, std::string &nic); + static void QueryJobStateAgain(http_t *http, JobMonitorParam *param, JobStatus *jobStatus); + static uint32_t GetBlockedSubstate(JobStatus *jobStatus); int32_t StartCupsdService(); void StartNextJob(); @@ -153,11 +131,6 @@ private: bool IsCupsServerAlive(); bool IsPrinterExist(const char *printerUri, const char *printerName, const char *ppdName); - void ParsePrinterAttributes(ipp_t *response, PrinterCapability &printerCaps); - void SetOptionAttribute(ipp_t *response, PrinterCapability &printerCaps); - void GetSupportedDuplexType(ipp_t *response, PrinterCapability &printerCaps); - nlohmann::json ParseSupportQualities(ipp_t *response); - nlohmann::json ParseSupportMediaTypes(ipp_t *response); void ParsePPDInfo(ipp_t *response, const char *ppd_make_model, const char *ppd_name, std::vector &ppds); diff --git a/services/print_service/include/print_event_subscriber.h b/services/print_service/include/print_event_subscriber.h new file mode 100644 index 0000000..482050d --- /dev/null +++ b/services/print_service/include/print_event_subscriber.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_EVENT_SUBSCRIBER_H +#define PRINT_EVENT_SUBSCRIBER_H + +#include "common_event_data.h" +#include "common_event_subscriber.h" + +namespace OHOS { +namespace Print { +class PrintEventSubscriber final : public EventFwk::CommonEventSubscriber { +public: + explicit PrintEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); + virtual ~PrintEventSubscriber(); + void OnReceiveEvent(const EventFwk::CommonEventData &data) override; +}; + +} // namespace Print +} // namespace OHOS +#endif // PRINT_EVENT_SUBSCRIBER_H diff --git a/services/print_service/include/print_http_request_process.h b/services/print_service/include/print_http_request_process.h new file mode 100644 index 0000000..963a8df --- /dev/null +++ b/services/print_service/include/print_http_request_process.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef PRINT_HTTP_REQUEST_PROCESS_H_ +#define PRINT_HTTP_REQUEST_PROCESS_H_ +#ifdef IPPOVERUSB_ENABLE + +#include +#include +#include +#include "singleton.h" +#include "httplib.h" +#include "print_usb_manager.h" + +namespace OHOS::Print { +template +class DoubleBufQue { +public: + void push(T& val) + { + std::lock_guard mtx_locker(mutexSwap); + writeQueue.emplace(val); + } + + bool pop(T& val) + { + if (readQueue.empty()) { + std::lock_guard mtx_locker(mutexSwap); + if (writeQueue.empty()) { + return false; + } + readQueue.swap(writeQueue); + } + val = readQueue.front(); + readQueue.pop(); + return true; + } + +private: + std::queue writeQueue; + std::queue readQueue; + std::mutex mutexSwap; +}; + +class PrintHttpRequestProcess { +public: + PrintHttpRequestProcess(); + virtual ~PrintHttpRequestProcess(); + + uint32_t ProcessRequest(const httplib::Request &requestData, httplib::Response &responseData, + const httplib::ContentReader &content_reader); + + void SetDeviceName(std::string name); + std::string GetDeviceName(); + + void Stop(); + +private: + std::string PrintOperation(Operation operation); + size_t NeedOffset(const std::vector &readTempBuffer); + void RecordBufByOperation(Operation operation, size_t requestId, const std::vector &tmVector); + void GetContentLength(const std::vector &readTempBuffer, size_t index, bool &findContentLength, + size_t &contentLength); + void DumpRespIdCode(const std::vector &readTempBuffer, Operation operation, size_t begin, size_t maxSize); + bool ProcessDataFromDevice(Operation operation); + void StartWriteDataToPrinterLooper(); + void StartReadSendDocDataFromPrinterLooper(); + void ProcessHttpResponse(httplib::Response &responseData, size_t requestId); + void ProcessHttpResponseGetAttr(httplib::Response &responseData, size_t requestId); + void ProcessHttpResponseSendDoc(httplib::Response &responseData, size_t requestId); + bool DealRequestHeader(const httplib::Request &requestData, std::string &sHeadersAndBody); + void CalcReqIdOperaId(const char *data, size_t dataLength, size_t &requestId); + void ProcessOtherRequest(const char *data, size_t data_length, std::string &sHeadersAndBody, size_t requestId); + void DumpReqIdOperaId(const char *data, size_t data_length); + std::string CreateChunk(const char *data, size_t data_length); + void CreatWriteDataTask(); + void CreatReadSendDocTask(); + bool CheckLineEnd(std::vector &readTempBuffer, size_t index); + size_t CalculateRequestId(std::vector &readTempBuffer, size_t index, Operation operation); + size_t CalculateFileDataBeginIndex(size_t index, Operation operation); + int32_t WriteDataSync(const std::string &dataStr); + int32_t BulkTransferWriteData(const std::string &dataStr); + void ProcessHttpResp(size_t requestId, httplib::Response &responseData, const std::string &sHeadersAndBody); + void GetAttrAgain(Operation operation, std::vector &tmVector); + +private: + bool needWriteData = false; + bool needReadSendDoc = false; + bool needWriteSendDoc = false; + bool deviceOpen = true; + + std::map reqIdOperaIdMap; // requestId + operationId + std::map> readBufMap; // requestId + buffer + std::map> readSendDocBufMap; // requestId + buffer + std::map> readGetAttrBufMap; // requestId + buffer + + std::string devName; + + std::mutex mutexCommon; + std::mutex mutexGetAttr; + std::mutex mutexSendDoc; + + DoubleBufQue sendDocDataQue; + DoubleBufQue ippDataQue; + size_t sendDocTotalLen = 0; +}; + +} + +#endif // PRINT_HTTP_REQUEST_PROCESS_H_ +#endif // IPPOVERUSB_ENABLE \ No newline at end of file diff --git a/services/print_service/include/print_http_server_manager.h b/services/print_service/include/print_http_server_manager.h new file mode 100644 index 0000000..958a25d --- /dev/null +++ b/services/print_service/include/print_http_server_manager.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef PRINT_HTTP_SERVER_MANAGER_H_ +#define PRINT_HTTP_SERVER_MANAGER_H_ +#ifdef IPPOVERUSB_ENABLE + +#include +#include +#include "singleton.h" +#include "httplib.h" +#include "print_ipp_over_usb_constant.h" +#include "print_http_request_process.h" + +namespace OHOS::Print { + +class PrintHttpServerManager final : public DelayedSingleton { +public: + PrintHttpServerManager(); + ~PrintHttpServerManager(); + + bool CreateServer(std::string printerName, int32_t &port); + static void StartServer(std::shared_ptr svr, + std::shared_ptr process); + void StopServer(std::string printerName); + void DealUsbDevDetach(const std::string &devStr); + +private: + bool AllocatePort(std::shared_ptr svr, int32_t &port); + +private: + std::map> printHttpServerMap; + std::map printHttpPortMap; + std::map> printHttpProcessMap; +}; + +} + +#endif // IPPOVERUSB_ENABLE +#endif // PRINT_HTTP_SERVER_MANAGER_H_ \ No newline at end of file diff --git a/services/print_service/include/print_ipp_over_usb_manager.h b/services/print_service/include/print_ipp_over_usb_manager.h new file mode 100644 index 0000000..d3235de --- /dev/null +++ b/services/print_service/include/print_ipp_over_usb_manager.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_IPP_OVER_USB_MANAGER_H_ +#define PRINT_IPP_OVER_USB_MANAGER_H_ +#ifdef IPPOVERUSB_ENABLE + +#include "singleton.h" +#include +#include "print_event_subscriber.h" + +namespace OHOS::Print { +class PrintIppOverUsbManager final : public DelayedSingleton { +public: + PrintIppOverUsbManager(); + ~PrintIppOverUsbManager(); + + void Init(); + bool ConnectPrinter(const std::string printerId, int32_t &port); + void DisConnectPrinter(const std::string printerId); + +private: + std::shared_ptr usbDevStatusListener; + bool isInit = false; +}; + +} + +#endif // IPPOVERUSB_ENABLE +#endif // PRINT_IPP_OVER_USB_MANAGER_H_ \ No newline at end of file diff --git a/services/print_service/include/print_security_guard_info.h b/services/print_service/include/print_security_guard_info.h index 1106d2f..edd47ab 100644 --- a/services/print_service/include/print_security_guard_info.h +++ b/services/print_service/include/print_security_guard_info.h @@ -35,8 +35,10 @@ namespace OHOS::Print { class PrintSecurityGuardInfo { struct PrintTypeInfo { - std::string ip; int32_t port = 631; + int32_t copyNumber = 1; + int32_t printPages = 1; + std::string ip; std::string mac; std::string domain; std::string name; diff --git a/services/print_service/include/print_service_ability.h b/services/print_service/include/print_service_ability.h index ab34098..cdf9b1a 100644 --- a/services/print_service/include/print_service_ability.h +++ b/services/print_service/include/print_service_ability.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include "ability_manager_client.h" @@ -31,18 +32,14 @@ #include "system_ability.h" #include "print_security_guard_manager.h" #include "print_service_helper.h" +#include "print_user_data.h" +#include "print_system_data.h" +#include "print_attribute_preference.h" namespace OHOS::Print { enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; -static int32_t curRequestCode_ = 0; class IKeyguardStateCallback; -struct AdapterParam { - std::string documentName; - bool isCheckFdList; - PrintAttributes printAttributes; -}; - class PrintServiceAbility : public SystemAbility, public PrintServiceStub { DECLARE_SYSTEM_ABILITY(PrintServiceAbility); @@ -52,28 +49,29 @@ public: PrintServiceAbility(); ~PrintServiceAbility(); static sptr GetInstance(); + int32_t StartService() override; int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, std::string &taskId) override; - int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token) override; int32_t StopPrint(const std::string &taskId) override; int32_t ConnectPrinter(const std::string &printerId) override; int32_t DisconnectPrinter(const std::string &printerId) override; int32_t StartDiscoverPrinter(const std::vector &extensionList) override; int32_t StopDiscoverPrinter() override; int32_t QueryAllExtension(std::vector &extensionInfos) override; - int32_t StartPrintJob(const PrintJob &jobinfo) override; + int32_t StartPrintJob(PrintJob &jobinfo) override; int32_t CancelPrintJob(const std::string &jobId) override; int32_t AddPrinters(const std::vector &printerInfos) override; int32_t RemovePrinters(const std::vector &printerIds) override; int32_t UpdatePrinters(const std::vector &printerInfos) override; int32_t UpdatePrinterState(const std::string &printerId, uint32_t state) override; - int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) override; + int32_t UpdatePrintJobStateOnlyForSystemApp(const std::string &jobId, uint32_t state, uint32_t subState) override; int32_t UpdateExtensionInfo(const std::string &extInfo) override; int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult) override; int32_t QueryPrinterCapability(const std::string &printerId) override; int32_t On(const std::string taskId, const std::string &type, const sptr &listener) override; int32_t Off(const std::string taskId, const std::string &type) override; + int32_t RegisterPrinterCallback(const std::string &type, const sptr &listener) override; + int32_t UnregisterPrinterCallback(const std::string &type) override; int32_t RegisterExtCallback(const std::string &extensionCID, const sptr &listener) override; int32_t UnregisterAllExtCallback(const std::string &extensionId) override; @@ -86,11 +84,28 @@ public: PrinterCapability &printerCaps) override; void SetHelper(const std::shared_ptr &helper); int32_t PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes, - std::string &taskId, const sptr &token) override; + std::string &taskId) override; int32_t StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes, const uint32_t fd) override; int32_t NotifyPrintService(const std::string &jobId, const std::string &type) override; + int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) override; + + int32_t QueryAddedPrinter(std::vector &printerNameList) override; + + int32_t QueryPrinterProperties(const std::string &printerId, const std::vector &keyList, + std::vector &valueList) override; + int32_t StartNativePrintJob(PrintJob &printJob) override; + int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState); + void CancelUserPrintJobs(const int32_t userId); + void SwitchUser(const int32_t userId); + int32_t NotifyPrintServiceEvent(std::string &jobId, uint32_t event) override; + int32_t GetPrinterPreference(const std::string &printerId, std::string &printerPreference) override; + int32_t SetPrinterPreference(const std::string &printerId, const std::string &printerPreference) override; + int32_t SetDefaultPrinter(const std::string &printerId) override; + int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake) override; + protected: void OnStart() override; void OnStop() override; @@ -99,41 +114,65 @@ private: int32_t Init(); void InitServiceHandler(); void ManualStart(); - std::string GetPrintJobId(); + std::string GetPrintJobOrderId(); bool StartAbility(const AAFwk::Want &want); - bool KillAbility(const std::string bundleName); - void KillAllAbility(); - bool StartPrintServiceExtension(const AAFwk::Want &want, int32_t curRequestCode_); PrintExtensionInfo ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo &extInfo); bool DelayStartDiscovery(const std::string &extensionId); + void SendPrinterDiscoverEvent(int event, const PrinterInfo &info); + void SendPrinterChangeEvent(int event, const PrinterInfo &info); void SendPrinterEvent(const PrinterInfo &info); + void SendPrinterEventChangeEvent(PrinterEvent printerEvent, const PrinterInfo &info); void SendPrintJobEvent(const PrintJob &jobInfo); void SendExtensionEvent(const std::string &extensionId, const std::string &extInfo); bool CheckPermission(const std::string &permissionName); void SendQueuePrintJob(const std::string &printerId); void BuildFDParam(const std::vector &fdList, AAFwk::Want &want); - void DestroyExtension(const std::string &printerId); void NotifyAppJobQueueChanged(const std::string &applyResult); std::shared_ptr getPrinterInfo(const std::string printerId); bool isEprint(const std::string &printerId); void ReportHisysEvent(const std::shared_ptr &jobInfo, const std::string &printerId, uint32_t subState); void ReportCompletedPrint(const std::string &printerId); void CheckJobQueueBlocked(const PrintJob &jobInfo); - int32_t CallSpooler(const std::vector &fileList, - const std::vector &fdList, std::string &taskId, const std::shared_ptr &adapterParam); int32_t CallSpooler(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token, const std::shared_ptr &adapterParam); + std::string &taskId); void notifyAdapterJobChanged(const std::string jobId, const uint32_t state, const uint32_t subState); bool checkJobState(uint32_t state, uint32_t subState); int32_t CheckAndSendQueuePrintJob(const std::string &jobId, uint32_t state, uint32_t subState); void UpdateQueuedJobList(const std::string &jobId, const std::shared_ptr &printJob); void StartPrintJobCB(const std::string &jobId, const std::shared_ptr &printJob); - void CreateDefaultAdapterParam(const std::shared_ptr &adapterParam); - void BuildAdapterParam( - const std::shared_ptr &adapterParam, AAFwk::Want &want, const std::string &jobId); - void BuildPrintAttributesParam(const std::shared_ptr &adapterParam, AAFwk::Want &want); - void ParseAttributesObjectParamForJson(const PrintAttributes &attrParam, nlohmann::json &attrJson); + void RegisterAdapterListener(const std::string &jobId); int32_t AdapterGetFileCallBack(const std::string &jobId, uint32_t state, uint32_t subState); + bool UpdatePrintJobOptionByPrinterId(PrintJob &printJob); + std::shared_ptr AddNativePrintJob(const std::string &jobId, PrintJob &printJob); + int32_t CallStatusBar(); + bool StartPluginPrintIconExtAbility(const AAFwk::Want &want); + bool IsPrinterJobMapEmpty(); + int32_t GetCurrentUserId(); + void UpdatePrintUserMap(); + void AddToPrintJobList(std::string jobId, const std::shared_ptr &printjob); + std::shared_ptr GetCurrentUserData(); + int32_t GetUserIdByJobId(const std::string jobId); + std::shared_ptr GetUserDataByJobId(const std::string jobId); + bool IsQueuedJobListEmpty(const std::string &jobId); + void SetPrintJobCanceled(PrintJob &jobinfo); + void UnloadSystemAbility(); + void ReduceAppCount(); + void InitPreferenceMap(); + bool WritePreferenceToFile(); + bool ReadPreferenceFromFile(const std::string &printerId, std::string& printPreference); + int32_t BuildPrinterPreference(PrinterCapability &cap, PrinterPreference &printPreference); + void BuildPrinterPreferenceByDefault(nlohmann::json& capOpt, PreferenceSetting &printerDefaultAttr); + void BuildPrinterPreferenceByOption(std::string& key, std::string& supportedOpts, + std::vector& optAttrs); + void BuildPrinterAttrComponentByJson(std::string& key, nlohmann::json& jsonArrObject, + std::vector &printerAttrs); + std::string StandardizePrinterId(const std::string &printerId); + bool CheckIsDefaultPrinter(const std::string &printerId); + bool CheckIsLastUsedPrinter(const std::string &printerId); + void DeletePrinterFromSystemData(const std::string &printerName); + void SetLastUsedPrinter(const std::string &printerId); + int32_t DestroyExtension(); + void DeletePrinterFromUserData(const std::string &printerId); private: PrintSecurityGuardManager securityGuardManager_; @@ -153,6 +192,7 @@ private: std::map extensionStateList_; std::map> printJobList_; std::map> queuedJobList_; + std::map jobOrderList_; std::map printAttributesList_; std::map> printerInfoList_; @@ -162,10 +202,18 @@ private: std::string spoolerAbilityName_; std::mutex lock_; - uint64_t currentJobId_; + uint64_t currentJobOrderId_; std::shared_ptr helper_; bool isJobQueueBlocked_; + std::map> printUserDataMap_; + PrintSystemData printSystemData_; + std::map> printUserMap_; + std::map userJobMap_; + int32_t currentUserId_; + + uint32_t printAppCount_; + std::map printerIdAndPreferenceMap_; }; } // namespace OHOS::Print #endif // PRINT_SYSTEM_ABILITY_H diff --git a/services/print_service/include/print_service_converter.h b/services/print_service/include/print_service_converter.h new file mode 100644 index 0000000..730b4f3 --- /dev/null +++ b/services/print_service/include/print_service_converter.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_SERVICE_CONVERTER_H +#define PRINT_SERVICE_CONVERTER_H + +#include +#include +#include +#include "print_page_size.h" + +namespace OHOS { +namespace Print { +enum DuplexModeCode { + DUPLEX_MODE_ONE_SIDED = 0, + DUPLEX_MODE_TWO_SIDED_LONG_EDGE = 1, + DUPLEX_MODE_TWO_SIDED_SHORT_EDGE = 2, +}; + +enum ColorModeCode { + COLOR_MODE_MONOCHROME = 0, + COLOR_MODE_COLOR = 1, + COLOR_MODE_AUTO = 2 +}; + +enum PrintQualityCode { + PRINT_QUALITY_DRAFT = 3, + PRINT_QUALITY_NORMAL = 4, + PRINT_QUALITY_HIGH = 5 +}; + +inline int DpcToDpi(int dpc) +{ + return dpc * 300 / 120; // 300 DPI = 120 DPC +} + +template +void AddToUniqueList(std::vector &list, T value) +{ + for (auto &item : list) { + if (item == value) { + return; + } + } + list.push_back(value); +} + +template +std::string ConvertListToJson(const std::vector &list, bool (*ConvertToJson)(const T &, nlohmann::json &)) +{ + nlohmann::json array = nlohmann::json::array(); + for (auto &item : list) { + nlohmann::json object; + if (ConvertToJson(item, object)) { + array.push_back(object); + } + } + return array.dump(); +} + +bool ConvertColorModeCode(const char *src, ColorModeCode &dst); +bool ConvertColorModeToJson(const ColorModeCode &code, nlohmann::json &jsonObject); +bool ConvertDuplexModeToJson(const DuplexModeCode &code, nlohmann::json &jsonObject); +bool ConvertPageSizeId(const char *src, std::string &id); +bool ConvertPrintPageSize(const char *src, PrintPageSize &dst); +bool ConvertPageSizeToJson(const PrintPageSize &code, nlohmann::json &jsonObject); +std::string GetQulityString(int code); +} // namespace Print +} // namespace OHOS +#endif // PRINT_SERVICE_CONVERTER_H diff --git a/services/print_service/include/print_service_helper.h b/services/print_service/include/print_service_helper.h index 7fafc05..1995e33 100644 --- a/services/print_service/include/print_service_helper.h +++ b/services/print_service/include/print_service_helper.h @@ -20,7 +20,10 @@ #include "ability_manager_client.h" #include "bundle_mgr_proxy.h" #include "bundle_mgr_client.h" +#include "ability_connect_callback_stub.h" #include "system_ability.h" +#include "print_log.h" +#include "print_event_subscriber.h" namespace OHOS::Print { class PrintServiceHelper { @@ -28,14 +31,31 @@ public: virtual ~PrintServiceHelper(); virtual bool CheckPermission(const std::string &name); virtual bool StartAbility(const AAFwk::Want &want); - virtual bool KillAbility(const std::string &bundleName); - virtual bool StartPrintServiceExtension(const AAFwk::Want &want, int32_t requestCode_); virtual sptr GetBundleMgr(); virtual bool QueryAccounts(std::vector &accountList); virtual bool QueryExtension(sptr mgr, int userId, std::vector &extensionInfos); virtual bool QueryNameForUid(sptr mgr, int32_t userId, std::string& name); virtual bool IsSyncMode(); + virtual bool StartPluginPrintIconExtAbility(const AAFwk::Want &want); + virtual void PrintSubscribeCommonEvent(); + +private: + class PrintAbilityConnection : public AAFwk::AbilityConnectionStub { + void OnAbilityConnectDone(const AppExecFwk::ElementName &element, const sptr &remoteObject, + int32_t resultCode) override + { + PRINT_HILOGI("connect done"); + } + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int32_t resultCode) override + { + PRINT_HILOGI("disconnect done"); + } + }; + +private: + std::shared_ptr userStatusListener; + bool isSubscribeCommonEvent = false; }; } // namespace OHOS #endif // PRINT_SERVICE_HELPER_H diff --git a/services/print_service/include/print_service_stub.h b/services/print_service/include/print_service_stub.h index 7907b0f..e7323c0 100644 --- a/services/print_service/include/print_service_stub.h +++ b/services/print_service/include/print_service_stub.h @@ -26,6 +26,7 @@ public: int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; private: + bool OnStartService(MessageParcel &data, MessageParcel &reply); bool OnStartPrint(MessageParcel &data, MessageParcel &reply); bool OnStopPrint(MessageParcel &data, MessageParcel &reply); bool OnEventOn(MessageParcel &data, MessageParcel &reply); @@ -45,10 +46,12 @@ private: bool OnStartPrintJob(MessageParcel &data, MessageParcel &reply); bool OnCancelPrintJob(MessageParcel &data, MessageParcel &reply); bool OnUpdatePrinterState(MessageParcel &data, MessageParcel &reply); - bool OnUpdatePrintJobState(MessageParcel &data, MessageParcel &reply); + bool OnUpdatePrintJobStateOnlyForSystemApp(MessageParcel &data, MessageParcel &reply); bool OnUpdateExtensionInfo(MessageParcel &data, MessageParcel &reply); bool OnRequestPreview(MessageParcel &data, MessageParcel &reply); bool OnQueryPrinterCapability(MessageParcel &data, MessageParcel &reply); + bool OnRegisterPrinterCallback(MessageParcel &data, MessageParcel &reply); + bool OnUnregisterPrinterCallback(MessageParcel &data, MessageParcel &reply); bool OnRegisterExtCallback(MessageParcel &data, MessageParcel &reply); bool OnUnregisterAllExtCallback(MessageParcel &data, MessageParcel &reply); bool OnLoadExtSuccess(MessageParcel &data, MessageParcel &reply); @@ -60,6 +63,16 @@ private: bool OnStartGetPrintFile(MessageParcel &data, MessageParcel &reply); bool OnNotifyPrintService(MessageParcel &data, MessageParcel &reply); + bool OnQueryPrinterInfoByPrinterId(MessageParcel &data, MessageParcel &reply); + bool OnQueryAddedPrinter(MessageParcel &data, MessageParcel &reply); + bool OnQueryPrinterProperties(MessageParcel &data, MessageParcel &reply); + bool OnStartNativePrintJob(MessageParcel &data, MessageParcel &reply); + bool OnNotifyPrintServiceEvent(MessageParcel &data, MessageParcel &reply); + bool OnGetPrinterPreference(MessageParcel &data, MessageParcel &reply); + bool OnSetPrinterPreference(MessageParcel &data, MessageParcel &reply); + bool OnSetDefaultPrinter(MessageParcel &data, MessageParcel &reply); + bool OnDeletePrinterFromCups(MessageParcel &data, MessageParcel &reply); + private: using PrintCmdHandler = bool (PrintServiceStub::*)(MessageParcel &, MessageParcel &); std::map cmdMap_; diff --git a/services/print_service/include/print_system_data.h b/services/print_service/include/print_system_data.h new file mode 100644 index 0000000..e51dbb8 --- /dev/null +++ b/services/print_service/include/print_system_data.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_SYSTEM_DATA_H +#define PRINT_SYSTEM_DATA_H + +#include +#include +#include +#include "printer_info.h" +#include "printer_capability.h" +#include "print_constant.h" + +namespace OHOS { +namespace Print { + +struct CupsPrinterInfo { + std::string name; + std::string uri; + std::string maker; + PrinterCapability printerCapability; + PrinterStatus printerStatus = PRINTER_STATUS_UNAVAILABLE; +}; + +class PrintSystemData { +public: + bool Init(); + void InsertCupsPrinter(const std::string &printerId, const CupsPrinterInfo &printerInfo, bool needUpdateCaps); + bool SaveCupsPrinterMap(); + std::string QueryPrinterIdByStandardizeName(const std::string &printerName); + bool QueryCupsPrinterInfoByPrinterId(const std::string &printerId, CupsPrinterInfo &cupsPrinter); + void InsertPrinterInfo(const std::string &printerId, const PrinterInfo &printerInfo); + std::shared_ptr QueryPrinterInfoByPrinterId(const std::string &printerId); + bool IsPrinterAdded(const std::string &printerId); + bool GetPrinterCapabilityFromSystemData( + CupsPrinterInfo &cupsPrinter, std::string printerId, PrinterCapability &printerCapability); + void DeleteCupsPrinter(const std::string &printerId); + void GetAddedPrinterListFromSystemData(std::vector &printerNameList); + void UpdatePrinterStatus(const std::string &printerId, PrinterStatus printerStatus); + void QueryPrinterInfoById(const std::string &printerId, PrinterInfo &printerInfo); + +private: + bool ParsePrinterListJsonV1(nlohmann::json& jsonObject); + bool GetJsonObjectFromFile(nlohmann::json &jsonObject); + void ConvertPrinterCapabilityToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson); + void ConvertPrintMarginToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson); + void ConvertPageSizeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson); + void ConvertPrintResolutionToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson); + bool ConvertJsonToPrinterCapability(nlohmann::json &capsJson, PrinterCapability &printerCapability); + void ConvertJsonToPrintMargin(nlohmann::json &capsJson, PrinterCapability &printerCapability); + bool ConvertJsonToPageSize(nlohmann::json &capsJson, PrinterCapability &printerCapability); + bool ConvertJsonToPrintResolution(nlohmann::json &capsJson, PrinterCapability &printerCapability); + bool GetPrinterCapabilityFromFile(std::string printerId, PrinterCapability &printerCapability); + bool CheckPrinterInfoJson(nlohmann::json &object, std::string &printerId); + +private: + std::map> addedPrinterMap_; + std::map> addedPrinterInfoList_; +}; + +} // namespace Print +} // namespace OHOS +#endif // PRINT_SYSTEM_DATA_H diff --git a/services/print_service/include/print_usb_manager.h b/services/print_service/include/print_usb_manager.h new file mode 100644 index 0000000..1c40514 --- /dev/null +++ b/services/print_service/include/print_usb_manager.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef PRINT_USB_MANAGER_H_ +#define PRINT_USB_MANAGER_H_ +#ifdef IPPOVERUSB_ENABLE + +#include +#include +#include +#include "singleton.h" +#include "usb_srv_client.h" +#include "httplib.h" +#include "print_ipp_over_usb_constant.h" + +namespace OHOS::Print { + +struct PrinterTranIndex { + int32_t sendDocConfigIndex = INVAILD_VALUE; + int32_t sendDocInterfaceIndex = INVAILD_VALUE; + int32_t commonConfigIndex = INVAILD_VALUE; + int32_t commonInterfaceIndex = INVAILD_VALUE; +}; + +enum class Operation { + Get_Printer_Attributes, + Send_Document, + Common +}; + +class PrintUsbManager final : public DelayedSingleton { +public: + PrintUsbManager(); + ~PrintUsbManager(); + + void Init(); + bool isExistIppOverUsbPrinter(std::string printerName); + bool ConnectUsbPinter(const std::string &printerName); + void DisConnectUsbPinter(const std::string &printerName); + int32_t BulkTransferWrite(std::string printerName, const Operation operation, + std::vector &vectorRequestBuffer); + int32_t BulkTransferRead(std::string printerName, const Operation operation, + std::vector &vectorRequestBuffer); + + void DealUsbDevStatusChange(const std::string &devStr, bool isAttach); + std::string GetPrinterName(const std::string &name); + +private: + void RefreshUsbPrinterDevice(); + bool isPrintDevice(USB::UsbDevice &usbdevice, std::string &printerName); + std::string GetProductName(USB::UsbDevice &usbDevice); + std::string QueryPrinterInfoFromStringDescriptor( + USB::USBDevicePipe &usbDevicePipe, uint16_t indexInStringDescriptor); + void DisConnectLastUsbPinter(const std::string &printerName); + bool AllocateInterface(const std::string &printerName, USB::UsbDevice &usbdevice, + USB::USBDevicePipe &usbDevicePipe); + +private: + bool isInit = false; + std::map printDeviceMap; + std::map>> printerIndexMap; + std::map printPipeMap; + std::map printTranIndexMap; + std::string currentPrinterName; +}; + +} + +#endif // IPPOVERUSB_ENABLE +#endif // PRINT_USB_MANAGER_H_ \ No newline at end of file diff --git a/services/print_service/include/print_user_data.h b/services/print_service/include/print_user_data.h new file mode 100644 index 0000000..925f88a --- /dev/null +++ b/services/print_service/include/print_user_data.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_USER_DATA_H +#define PRINT_USER_DATA_H + +#include +#include + +#include "printer_info.h" +#include "iprint_callback.h" + +namespace OHOS { +namespace Print { +struct JobIdCmp { + bool operator()(const std::string a, const std::string b) const + { + return atoi(a.c_str()) > atoi(b.c_str()); + } +}; + +class PrintUserData { +public: + void RegisterPrinterCallback(const std::string &type, const sptr &listener); + void UnregisterPrinterCallback(const std::string &type); + void SendPrinterEvent(const std::string &type, int event, const PrinterInfo &info); + void AddToPrintJobList(const std::string jobId, const std::shared_ptr &printjob); + void UpdateQueuedJobList( + const std::string &jobId, const std::shared_ptr &printJob, std::string jobOrderId); + int32_t QueryPrintJobById(std::string &printJobId, PrintJob &printJob); + int32_t QueryAllPrintJob(std::vector &printJobs); + int32_t SetDefaultPrinter(const std::string &printerId); + int32_t SetLastUsedPrinter(const std::string &printerId); + void ParseUserData(); + void SetUserId(int32_t userId); + std::string GetLastUsedPrinter(); + std::string GetDefaultPrinter(); + +private: + bool SetUserDataToFile(); + bool GetFileData(std::string &fileData); + +public: + std::map> registeredListeners_; + std::map> printJobList_; + std::map> queuedJobList_; + std::map jobOrderList_; + +private: + std::string defaultPrinterId_ = ""; + std::string lastUsedPrinterId_ = ""; + int32_t userId_ = 0; +}; + +} // namespace Print +} // namespace OHOS +#endif // PRINT_USER_DATA_H diff --git a/services/print_service/src/print_bms_helper.cpp b/services/print_service/src/print_bms_helper.cpp index a994caf..94c6700 100644 --- a/services/print_service/src/print_bms_helper.cpp +++ b/services/print_service/src/print_bms_helper.cpp @@ -27,7 +27,7 @@ PrintBMSHelper::PrintBMSHelper() : sptrBundleMgr_(nullptr), printBMSDeath_(nullp PrintBMSHelper::~PrintBMSHelper() {} -void PrintBMSHelper::SetHelper(const std::shared_ptr &helper) +void PrintBMSHelper::SetHelper(std::shared_ptr &helper) { helper_ = helper; sptrBundleMgr_ = nullptr; diff --git a/services/print_service/src/print_cups_attribute.cpp b/services/print_service/src/print_cups_attribute.cpp new file mode 100644 index 0000000..8a26d43 --- /dev/null +++ b/services/print_service/src/print_cups_attribute.cpp @@ -0,0 +1,433 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "print_cups_attribute.h" +#include "print_service_converter.h" +#include "print_log.h" + +namespace OHOS::Print { +template +bool ParseAttributeToValue(ipp_t *response, const std::string &keyword, T &value, + bool (*convertAttr)(const char *src, T &dst)) +{ + if (convertAttr == nullptr) { + PRINT_HILOGW("convertAttr is null"); + return false; + } + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_KEYWORD); + if (attrPtr == nullptr) { + PRINT_HILOGW("attrPtr is null"); + return false; + } + const char *attrString = ippGetString(attrPtr, 0, NULL); + if (attrString == nullptr) { + PRINT_HILOGW("attrString is null"); + return false; + } + PRINT_HILOGD("attrString: %{public}s", attrString); + if (!convertAttr(attrString, value)) { + PRINT_HILOGW("ConvertFunction fail"); + return false; + } + return true; +} + +template +bool ParseAttributesToList(ipp_t *response, const std::string &keyword, std::vector &list, + bool (*convertAttr)(const char *src, T &dst)) +{ + if (convertAttr == nullptr) { + PRINT_HILOGW("convertAttr is null"); + return false; + } + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_KEYWORD); + if (attrPtr == nullptr) { + PRINT_HILOGW("attrPtr is null"); + return false; + } + int num = ippGetCount(attrPtr); + PRINT_HILOGD("number of values %{public}d", num); + for (int i = 0; i < num; i++) { + const char *attrString = ippGetString(attrPtr, i, NULL); + if (attrString == nullptr) { + PRINT_HILOGW("attrString is null"); + continue; + } + PRINT_HILOGD("attrString: %{public}s", attrString); + T attrValue; + if (!convertAttr(attrString, attrValue)) { + PRINT_HILOGW("ConvertFunction fail"); + continue; + } + AddToUniqueList(list, attrValue); + } + return true; +} + +bool ConvertDuplexModeCode(const char *src, DuplexModeCode &dst) +{ + if (src == nullptr) { + return false; + } + if (strcasestr(src, CUPS_SIDES_ONE_SIDED)) { + dst = DUPLEX_MODE_ONE_SIDED; + } else if (strcasestr(src, CUPS_SIDES_TWO_SIDED_PORTRAIT)) { + dst = DUPLEX_MODE_TWO_SIDED_LONG_EDGE; + } else if (strcasestr(src, CUPS_SIDES_TWO_SIDED_LANDSCAPE)) { + dst = DUPLEX_MODE_TWO_SIDED_SHORT_EDGE; + } else { + return false; + } + return true; +} + +std::string ConvertIppAttributesToJsonString(ipp_t *response, const std::string &keyword) +{ + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_KEYWORD); + if (attrPtr == nullptr) { + return ""; + } + nlohmann::json jsonArray = nlohmann::json::array(); + for (int i = 0; i < ippGetCount(attrPtr); i++) { + const char *attrString = ippGetString(attrPtr, i, NULL); + if (attrString == nullptr) { + continue; + } + jsonArray.push_back(attrString); + } + return jsonArray.dump(); +} + +void SetCapabilityGroupAttribute(ipp_t *response, PrinterCapability &printerCaps) +{ + ipp_attribute_t *attrPtr; + if ((attrPtr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("printer-state", + ippEnumString("printer-state", ippGetInteger(attrPtr, 0))); + } + if ((attrPtr = ippFindAttribute(response, "printer-info", IPP_TAG_TEXTLANG)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("printer-info", ippGetString(attrPtr, 0, NULL)); + } + if ((attrPtr = ippFindAttribute(response, "printer-location", IPP_TAG_TEXT)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("printer-location", ippGetString(attrPtr, 0, NULL)); + } +} + +void ParseDuplexModeAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "sides-supported"; + std::vector list; + ParseAttributesToList(response, keyword, list, ConvertDuplexModeCode); + std::string duplexModeJson = ConvertListToJson(list, ConvertDuplexModeToJson); + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), duplexModeJson.c_str()); + size_t num = list.size(); + if (static_cast(num) <= 1) { + printerCaps.SetDuplexMode((uint32_t)DUPLEX_MODE_ONE_SIDED); + } else { + printerCaps.SetDuplexMode((uint32_t)DUPLEX_MODE_TWO_SIDED_LONG_EDGE); + } + + keyword = "sides-default"; + DuplexModeCode code; + if (ParseAttributeToValue(response, keyword, code, ConvertDuplexModeCode)) { + uint32_t value = static_cast(code); + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), std::to_string(value).c_str()); + } +} + +void ParseColorModeAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "print-color-mode-supported"; + std::vector supportedColorModes; + ParseAttributesToList(response, keyword, supportedColorModes, ConvertColorModeCode); + std::string colorModeJson = ConvertListToJson(supportedColorModes, ConvertColorModeToJson); + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), colorModeJson.c_str()); + + keyword = "print-color-mode-default"; + ColorModeCode code; + if (ParseAttributeToValue(response, keyword, code, ConvertColorModeCode)) { + uint32_t mode = static_cast(code); + printerCaps.SetColorMode(mode); + printerCaps.SetPrinterAttrNameAndValue("defaultColorMode", std::to_string(mode).c_str()); + } +} + +void ParsePageSizeAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "media-supported"; + std::vector supportedPageSizes; + ParseAttributesToList(response, keyword, supportedPageSizes, ConvertPrintPageSize); + std::string pageSizeJson = ConvertListToJson(supportedPageSizes, ConvertPageSizeToJson); + printerCaps.SetPageSize(supportedPageSizes); + printerCaps.SetPrinterAttrNameAndValue("supportedPageSizeArray", pageSizeJson.c_str()); + + std::string defaultPageSizeId; + keyword = "media-default"; + if (ParseAttributeToValue(response, keyword, defaultPageSizeId, ConvertPageSizeId)) { + printerCaps.SetPrinterAttrNameAndValue("defaultPageSizeId", defaultPageSizeId.c_str()); + } +} + +void ParseQualityAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "print-quality-supported"; + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_ENUM); + if (attrPtr == nullptr) { + PRINT_HILOGW("%{public}s missing", keyword.c_str()); + return; + } + nlohmann::json supportedQualities = nlohmann::json::array(); + for (int i = 0; i < ippGetCount(attrPtr); i++) { + nlohmann::json jsonObject; + jsonObject["quality"] = ippGetInteger(attrPtr, i); + supportedQualities.push_back(jsonObject); + } + std::string attrString = supportedQualities.dump(); + PRINT_HILOGD("%{public}s: %{public}s", keyword.c_str(), attrString.c_str()); + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), attrString.c_str()); +} + +void ParseCopiesAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + ipp_attribute_t *attrPtr = ippFindAttribute(response, "copies-supported", IPP_TAG_RANGE); + if (attrPtr != nullptr) { + int upper = 0; + for (int i = 0; i < ippGetCount(attrPtr); i++) { + ippGetRange(attrPtr, i, &upper); + } + printerCaps.SetPrinterAttrNameAndValue("copies-supported", std::to_string(upper).c_str()); + } + attrPtr = ippFindAttribute(response, "copies-default", IPP_TAG_INTEGER); + if (attrPtr != nullptr) { + printerCaps.SetPrinterAttrNameAndValue("copies-default", std::to_string(ippGetInteger(attrPtr, 0)).c_str()); + } +} + +void ParseSupportedResolutionAttribute(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "printer-resolution-supported"; + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_RESOLUTION); + if (attrPtr == nullptr) { + PRINT_HILOGW("attrPtr is null"); + return; + } + int num = ippGetCount(attrPtr); + PRINT_HILOGD("number of values %{public}d", num); + nlohmann::json resolutionArray = nlohmann::json::array(); + for (int i = 0; i < num; i++) { + ipp_res_t units = IPP_RES_PER_INCH; + int xres = 0; + int yres = 0; + xres = ippGetResolution(attrPtr, i, &yres, &units); + if (xres == 0 || yres == 0) { + continue; + } + if (units == IPP_RES_PER_CM) { + xres = DpcToDpi(xres); + yres = DpcToDpi(yres); + } else if (units != IPP_RES_PER_INCH) { + PRINT_HILOGW("unknown dpi unit: %{public}d", static_cast(units)); + continue; + } + nlohmann::json object; + object["horizontalDpi"] = xres; + object["verticalDpi"] = yres; + resolutionArray.push_back(object); + } + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), resolutionArray.dump().c_str()); +} + +void ParseDefaultResolutionAttribute(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "printer-resolution-default"; + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_RESOLUTION); + if (attrPtr == nullptr) { + PRINT_HILOGW("attrPtr is null"); + return; + } + int num = ippGetCount(attrPtr); + PRINT_HILOGD("number of values %{public}d", num); + for (int i = 0; i < num; i++) { + ipp_res_t units = IPP_RES_PER_INCH; + int xres = 0; + int yres = 0; + xres = ippGetResolution(attrPtr, i, &yres, &units); + if (xres == 0 || yres == 0) { + continue; + } + if (units == IPP_RES_PER_CM) { + xres = DpcToDpi(xres); + yres = DpcToDpi(yres); + } else if (units != IPP_RES_PER_INCH) { + PRINT_HILOGW("unknown dpi unit: %{public}d", static_cast(units)); + continue; + } + nlohmann::json object; + object["horizontalDpi"] = xres; + object["verticalDpi"] = yres; + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), object.dump().c_str()); + break; + } +} + +void ParseMediaColDefaultAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + ipp_attribute_t *defaultMediaPtr = ippFindAttribute(response, "media-col-default", IPP_TAG_BEGIN_COLLECTION); + if (defaultMediaPtr == nullptr) { + PRINT_HILOGW("media-col-default missing"); + return; + } + ipp_t *defaultMediaCol = defaultMediaPtr->values[0].collection; + std::vector keywordList; + keywordList.push_back("media-top-margin"); + keywordList.push_back("media-bottom-margin"); + keywordList.push_back("media-left-margin"); + keywordList.push_back("media-right-margin"); + for (auto &keyword : keywordList) { + ipp_attribute_t *attrPtr = ippFindAttribute(defaultMediaCol, keyword.c_str(), IPP_TAG_INTEGER); + if (attrPtr != nullptr) { + int value = ippGetInteger(attrPtr, 0); + PRINT_HILOGD("%{public}s found: %{public}d", keyword.c_str(), value); + std::string defaultKeyword = keyword + "-default"; + printerCaps.SetPrinterAttrNameAndValue(defaultKeyword.c_str(), std::to_string(value).c_str()); + } + } + ipp_attribute_t *attrPtr = ippFindAttribute(defaultMediaCol, "duplex-supported", IPP_TAG_BOOLEAN); + if (attrPtr != nullptr) { + PRINT_HILOGD("duplex-supported found: %{public}d", ippGetBoolean(attrPtr, 0)); + } + attrPtr = ippFindAttribute(defaultMediaCol, "media-source", IPP_TAG_KEYWORD); + if (attrPtr != nullptr) { + PRINT_HILOGD("media-source-default found: %{public}s", ippGetString(attrPtr, 0, NULL)); + printerCaps.SetPrinterAttrNameAndValue("media-source-default", ippGetString(attrPtr, 0, NULL)); + } + attrPtr = ippFindAttribute(defaultMediaCol, "media-type", IPP_TAG_KEYWORD); + if (attrPtr != nullptr) { + PRINT_HILOGD("media-type-default found: %{public}s", ippGetString(attrPtr, 0, NULL)); + printerCaps.SetPrinterAttrNameAndValue("media-type-default", ippGetString(attrPtr, 0, NULL)); + } +} + +void ParseMediaMarginAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + ipp_attribute_t *attrPtr; + if ((attrPtr = ippFindAttribute(response, "media-bottom-margin-supported", IPP_TAG_INTEGER)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("media-bottom-margin-supported", + std::to_string(ippGetInteger(attrPtr, 0)).c_str()); + } + if ((attrPtr = ippFindAttribute(response, "media-top-margin-supported", IPP_TAG_INTEGER)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("media-top-margin-supported", + std::to_string(ippGetInteger(attrPtr, 0)).c_str()); + } + if ((attrPtr = ippFindAttribute(response, "media-left-margin-supported", IPP_TAG_INTEGER)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("media-left-margin-supported", + std::to_string(ippGetInteger(attrPtr, 0)).c_str()); + } + if ((attrPtr = ippFindAttribute(response, "media-right-margin-supported", IPP_TAG_INTEGER)) != NULL) { + printerCaps.SetPrinterAttrNameAndValue("media-right-margin-supported", + std::to_string(ippGetInteger(attrPtr, 0)).c_str()); + } +} + +void ParseOrientationAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "orientation-requested-default"; + ipp_attribute_t *attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_ENUM); + if (attrPtr != NULL) { + int orientationEnum = ippGetInteger(attrPtr, 0); + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), std::to_string(orientationEnum).c_str()); + PRINT_HILOGD("orientation-default found: %{public}d", orientationEnum); + } + keyword = "orientation-requested-supported"; + attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_ENUM); + if (attrPtr != NULL) { + int num = ippGetCount(attrPtr); + if (num > 0) { + nlohmann::json supportedOrientationArray = nlohmann::json::array(); + for (int i = 0; i < ippGetCount(attrPtr); i++) { + int orientationEnum = ippGetInteger(attrPtr, i); + supportedOrientationArray.push_back(orientationEnum); + PRINT_HILOGD("orientation-supported found: %{public}d", orientationEnum); + } + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), supportedOrientationArray.dump().c_str()); + } + } +} + +void ParseOtherAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + std::string keyword = "media-source-supported"; + std::string attrString = ConvertIppAttributesToJsonString(response, keyword); + PRINT_HILOGD("%{public}s: %{public}s", keyword.c_str(), attrString.c_str()); + if (!attrString.empty()) { + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), attrString.c_str()); + } + + keyword = "multiple-document-handling-supported"; + attrString = ConvertIppAttributesToJsonString(response, keyword); + PRINT_HILOGD("%{public}s: %{public}s", keyword.c_str(), attrString.c_str()); + if (!attrString.empty()) { + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), attrString.c_str()); + } +} + +void SetOptionAttribute(ipp_t *response, PrinterCapability &printerCaps) +{ + ipp_attribute_t *attrPtr; + nlohmann::json options; + if ((attrPtr = ippFindAttribute(response, "printer-make-and-model", IPP_TAG_TEXT)) != NULL) { + options["make"] = ippGetString(attrPtr, 0, NULL); + } + if ((attrPtr = ippFindAttribute(response, "printer-uuid", IPP_TAG_URI)) != NULL) { + options["uuid"] = ippGetString(attrPtr, 0, NULL); + } + if ((attrPtr = ippFindAttribute(response, "printer-name", IPP_TAG_TEXT)) != NULL) { + options["printerName"] = ippGetString(attrPtr, 0, NULL); + } + std::string keyword = "media-type-supported"; + std::string supportTypes = ConvertIppAttributesToJsonString(response, keyword); + PRINT_HILOGD("%{public}s: %{public}s", keyword.c_str(), supportTypes.c_str()); + if (!supportTypes.empty()) { + printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), supportTypes.c_str()); + } + + nlohmann::json cupsOptionsJson = printerCaps.GetPrinterAttrGroupJson(); + options["cupsOptions"] = cupsOptionsJson; + + std::string optionStr = options.dump(); + PRINT_HILOGD("SetOption: %{public}s", optionStr.c_str()); + printerCaps.SetOption(optionStr); +} + +void ParsePrinterAttributes(ipp_t *response, PrinterCapability &printerCaps) +{ + SetCapabilityGroupAttribute(response, printerCaps); + ParseColorModeAttributes(response, printerCaps); + ParseDuplexModeAttributes(response, printerCaps); + ParsePageSizeAttributes(response, printerCaps); + ParseQualityAttributes(response, printerCaps); + ParseSupportedResolutionAttribute(response, printerCaps); + ParseDefaultResolutionAttribute(response, printerCaps); + ParseMediaColDefaultAttributes(response, printerCaps); + ParseMediaMarginAttributes(response, printerCaps); + ParseOrientationAttributes(response, printerCaps); + ParseCopiesAttributes(response, printerCaps); + ParseOtherAttributes(response, printerCaps); + SetOptionAttribute(response, printerCaps); +} +} // namespace OHOS::Print \ No newline at end of file diff --git a/services/print_service/src/print_cups_client.cpp b/services/print_service/src/print_cups_client.cpp index c4a6d6c..f320769 100644 --- a/services/print_service/src/print_cups_client.cpp +++ b/services/print_service/src/print_cups_client.cpp @@ -35,6 +35,8 @@ #include "print_log.h" #include "print_constant.h" #include "print_utils.h" +#include "print_service_converter.h" +#include "print_cups_attribute.h" namespace OHOS::Print { using namespace std; @@ -46,8 +48,9 @@ const uint32_t TIME_OUT = 2000; const uint32_t CONVERSION_UNIT = 2540; const uint32_t LONG_TIME_OUT = 3000; const uint32_t LONG_LONG_TIME_OUT = 30000; +const uint32_t INTERVAL_FOR_FIRST_QUERY = 1; const uint32_t INTERVAL_FOR_QUERY = 2; -const uint32_t OFFLINE_RETRY_TIMES = 5; +const uint32_t OFFLINE_RETRY_TIMES = 1; const uint32_t RESOURCE_COUNT = 2; const uint32_t DIR_COUNT = 3; const uint32_t INDEX_ZERO = 0; @@ -60,6 +63,9 @@ const uint32_t IP_RIGHT_SHIFT_0 = 0; const uint32_t IP_RIGHT_SHIFT_8 = 8; const uint32_t IP_RIGHT_SHIFT_16 = 16; const uint32_t IP_RIGHT_SHIFT_24 = 24; +const uint32_t NUMBER_FOR_SPLICING_SUBSTATE = 100; + +static bool g_isFirstQueryState = false; static const std::string CUPS_ROOT_DIR = "/data/service/el1/public/print_service/cups"; static const std::string CUPS_RUN_DIR = "/data/service/el1/public/print_service/cups/run"; @@ -68,6 +74,18 @@ static const std::string DEFAULT_MAKE_MODEL = "IPP Everywhere"; static const std::string DEFAULT_USER = "default"; static const std::string PRINTER_STATE_WAITING_COMPLETE = "cups-waiting-for-job-completed"; static const std::string PRINTER_STATE_WIFI_NOT_CONFIGURED = "wifi-not-configured-report"; +static const std::string PRINTER_STATE_IGNORE_HP = "wifi-not-configured-report,cups-waiting-for-job-completed"; +static const std::string PRINTER_STATE_IGNORE_BUSY = + "cups-ipp-conformance-failure-report,cups-ipp-missing-job-history,cups-waiting-for-job-completed"; +static const std::string PRINTER_STATE_IGNORE_BUSY_COMPLETED = + "cups-ipp-conformance-failure-report,cups-ipp-missing-job-history"; +static const std::string PRINTER_STATE_IGNORE_BUSY_MISSING_JOB_STATE = + "cups-ipp-conformance-failure-report,cups-ipp-missing-job-state"; +static const std::string PRINTER_STATE_IGNORE_BUSY_MISSING_JOB_STATE_COMPLETED = + "cups-ipp-conformance-failure-report,cups-ipp-missing-job-state,cups-waiting-for-job-completed"; +static const std::string PRINTER_STATE_IGNORE_BUSY_WAITING_COMPLETE_OTHER_REPORT = + "cups-waiting-for-job-completed,other-report"; +static const std::string PRINTER_STATE_IGNORE_BUSY_OTHER_REPORT = "other-report"; static const std::string PRINTER_STATE_NONE = "none"; static const std::string PRINTER_STATE_EMPTY = ""; static const std::string PRINTER_STATE_MEDIA_EMPTY = "media-empty"; @@ -85,9 +103,17 @@ static const std::string PRINTER_STATE_OFFLINE = "offline"; static const std::string DEFAULT_JOB_NAME = "test"; static const std::string CUPSD_CONTROL_PARAM = "print.cupsd.ready"; static const std::string P2P_PRINTER = "p2p"; -static const std::vector IGNORE_STATE_LIST = { - PRINTER_STATE_WAITING_COMPLETE, PRINTER_STATE_NONE, PRINTER_STATE_EMPTY, PRINTER_STATE_WIFI_NOT_CONFIGURED -}; +static const std::vector IGNORE_STATE_LIST = {PRINTER_STATE_WAITING_COMPLETE, + PRINTER_STATE_NONE, + PRINTER_STATE_EMPTY, + PRINTER_STATE_WIFI_NOT_CONFIGURED, + PRINTER_STATE_IGNORE_HP, + PRINTER_STATE_IGNORE_BUSY, + PRINTER_STATE_IGNORE_BUSY_COMPLETED, + PRINTER_STATE_IGNORE_BUSY_MISSING_JOB_STATE, + PRINTER_STATE_IGNORE_BUSY_MISSING_JOB_STATE_COMPLETED, + PRINTER_STATE_IGNORE_BUSY_WAITING_COMPLETE_OTHER_REPORT, + PRINTER_STATE_IGNORE_BUSY_OTHER_REPORT}; PrintCupsClient::PrintCupsClient() {} @@ -129,8 +155,7 @@ int32_t PrintCupsClient::StartCupsdService() } lseek(fd, 0, SEEK_SET); char buf[BUFFER_LEN] = {0}; - ssize_t bytes; - if ((bytes = read(fd, buf, sb.st_size)) < 0) { + if ((read(fd, buf, sb.st_size)) < 0) { PRINT_HILOGE("Read pidFile error!"); close(fd); return E_PRINT_SERVER_FAILURE; @@ -175,13 +200,13 @@ void PrintCupsClient::SymlinkDirectory(const char *srcDir, const char *destDir) PRINT_HILOGE("Failed to open Dir: %{private}s", srcDir); return; } - if (access(destDir, F_OK) != 0) { + if (access(destDir, F_OK)) { mkdir(destDir, DIR_MODE); } struct dirent *file; struct stat filestat; while ((file = readdir(dir)) != nullptr) { - if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) { + if (!strcmp(file->d_name, ".") || !strcmp(file->d_name, "..")) { continue; } std::string srcFilePath = std::string(srcDir) + "/" + std::string(file->d_name); @@ -193,7 +218,7 @@ void PrintCupsClient::SymlinkDirectory(const char *srcDir, const char *destDir) } else { int ret = symlink(srcFilePath.c_str(), destFilePath.c_str()); PRINT_HILOGI("symlink ret = %{public}d, errno = %{public}d", ret, errno); - if (ret == 0) { + if (!ret) { PRINT_HILOGE("symlink success"); } else { PRINT_HILOGE("symlink failed"); @@ -265,7 +290,7 @@ int32_t PrintCupsClient::InitCupsResources() PRINT_HILOGD("The resource has been copied."); continue; } - if (i == 0) { + if (!i) { SymlinkDirectory(array[i][INDEX_ZERO].c_str(), array[i][INDEX_ONE].c_str()); } else { CopyDirectory(array[i][INDEX_ZERO].c_str(), array[i][INDEX_ONE].c_str()); @@ -396,6 +421,49 @@ int32_t PrintCupsClient::AddPrinterToCups(const std::string &printerUri, const s return E_PRINT_NONE; } +int32_t PrintCupsClient::DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake) +{ + PRINT_HILOGD("PrintCupsClient DeletePrinterFromCups start, printerMake: %{public}s", printerMake.c_str()); + ipp_t *request; + http_t *http = NULL; + char uri[HTTP_MAX_URI]; + std::vector ppds; + std::string ppd = DEFAULT_PPD_NAME; + std::string standardName = PrintUtil::StandardizePrinterName(printerName); + + ippSetPort(CUPS_SEVER_PORT); + QueryPPDInformation(printerMake.c_str(), ppds); + if (!ppds.empty()) { + ppd = ppds[0]; + std::string serverBin = CUPS_ROOT_DIR + "/serverbin"; + mode_t permissions = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH; + ChangeFilterPermission(serverBin, permissions); + } + PRINT_HILOGI("ppd driver: %{public}s", ppd.c_str()); + if (!IsPrinterExist(printerUri.c_str(), standardName.c_str(), ppd.c_str())) { + PRINT_HILOGI("printer has not added"); + return E_PRINT_NONE; + } + request = ippNewRequest(IPP_OP_CUPS_DELETE_PRINTER); + httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL, "localhost", 0, "/printers/%s", + standardName.c_str()); + ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); + ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser()); + ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, standardName.c_str()); + ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL, printerUri.c_str()); + ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_NAME, "ppd-name", NULL, ppd.c_str()); + PRINT_HILOGD("IPP_OP_CUPS_DELETE_PRINTER cupsDoRequest"); + ippDelete(cupsDoRequest(http, request, "/admin/")); + if (cupsLastError() > IPP_STATUS_OK_CONFLICTING) { + PRINT_HILOGE("delete error: %s", cupsLastErrorString()); + return E_PRINT_SERVER_FAILURE; + } + httpClose(http); + PRINT_HILOGI("delete success"); + return E_PRINT_NONE; +} + int32_t PrintCupsClient::DeleteCupsPrinter(const char *printerName) { ipp_t *request; @@ -588,6 +656,150 @@ int PrintCupsClient::FillJobOptions(JobParameters *jobParams, int num_options, c return num_options; } +int32_t PrintCupsClient::QueryAddedPrinterList(std::vector &printerNameList) +{ + if (!IsCupsServerAlive()) { + PRINT_HILOGI("The cupsd process is not started, start it now."); + int32_t ret = StartCupsdService(); + if (ret != 0) { + return E_PRINT_SERVER_FAILURE; + } + } + printerNameList.clear(); + cups_dest_t *dests = NULL; + int num = cupsGetDests(&dests); + PRINT_HILOGI("QueryAddedPrinterList, num: %{public}d.", num); + for (int i = 0; i < num; i++) { + PRINT_HILOGD("QueryAddedPrinterList, printerIsDefault: %{public}d.", dests[i].is_default); + printerNameList.emplace_back(dests[i].name); + } + cupsFreeDests(num, dests); + return E_PRINT_NONE; +} + +int32_t PrintCupsClient::SetDefaultPrinter(const std::string &printerName) +{ + http_t *http; + ippSetPort(CUPS_SEVER_PORT); + http = httpConnect2(cupsServer(), ippPort(), NULL, AF_UNSPEC, HTTP_ENCRYPTION_IF_REQUESTED, 1, LONG_TIME_OUT, NULL); + if (http == nullptr) { + PRINT_HILOGE("cups server is not alive"); + return E_PRINT_SERVER_FAILURE; + } + ipp_t *request; /* IPP Request */ + char uri[HTTP_MAX_URI]; /* URI for printer/class */ + httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL, + "localhost", 0, "/printers/%s", printerName.c_str()); + request = ippNewRequest(IPP_OP_CUPS_SET_DEFAULT); + ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, + "printer-uri", NULL, uri); + ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", + NULL, cupsUser()); + ippDelete(cupsDoRequest(http, request, "/admin/")); + + const char* default_printer = cupsGetDefault(); + PRINT_HILOGI("default_printer=%{public}s", default_printer); + if (cupsLastError() > IPP_STATUS_OK_CONFLICTING) { + PRINT_HILOGI("[ERROR] occur a error when do cups-request{setDefault}. error is:> "); + return E_PRINT_SERVER_FAILURE; + } + return E_PRINT_NONE; +} + +ppd_file_t* PrintCupsClient::GetPPDFile(const std::string &printerName) +{ + if (!IsCupsServerAlive()) { + PRINT_HILOGI("The cupsd process is not started, start it now."); + int32_t ret = StartCupsdService(); + if (ret != 0) { + return nullptr; + } + } + ppd_file_t *ppd = 0; + std::string fileDir = "/data/service/el1/public/print_service/cups/ppd/"; + std::string pName = printerName; + std::string filePath = fileDir + pName + ".ppd"; + PRINT_HILOGI("GetPPDFile started filePath %{public}s", filePath.c_str()); + char realPath[PATH_MAX] = {}; + if (realpath(filePath.c_str(), realPath) == nullptr) { + PRINT_HILOGE("The realPidFile is null."); + return nullptr; + } + int fd; + if ((fd = open(realPath, O_RDWR)) < 0) { + PRINT_HILOGE("Open ppdFile error!"); + return nullptr; + } + PRINT_HILOGI("GetPPDFile %{public}d", fd); + ppd = ppdOpenFd(fd); + close(fd); + PRINT_HILOGI("GetPPDFile groups:%{public}d,pagesize_num:%{public}d", ppd->num_groups, ppd->num_sizes); + return ppd; +} + +int32_t PrintCupsClient::QueryPrinterAttrList(const std::string &printerName, const std::vector &keyList, + std::vector &valueList) +{ + cups_dest_t *dest = nullptr; + dest = cupsGetNamedDest(CUPS_HTTP_DEFAULT, printerName.c_str(), NULL); + if (dest == nullptr) { + PRINT_HILOGW("the printer is not found"); + return E_PRINT_SERVER_FAILURE; + } + for (auto &key : keyList) { + const char *ret = cupsGetOption(key.c_str(), dest->num_options, dest ->options); + if (ret != NULL) { + std::string valueStr = ret; + std::string value = key + "&" + valueStr; + valueList.emplace_back(value); + } + } + PRINT_HILOGI("QueryPrinterAttr end"); + return E_PRINT_NONE; +} + +int32_t PrintCupsClient::QueryPrinterInfoByPrinterId(const std::string& printerId, PrinterInfo &info) +{ + PRINT_HILOGD("the printerInfo printerName %{public}s", info.GetPrinterName().c_str()); + cups_dest_t *dest = nullptr; + dest = cupsGetNamedDest(CUPS_HTTP_DEFAULT, info.GetPrinterName().c_str(), NULL); + if (dest == nullptr) { + PRINT_HILOGW("the printer is not found"); + return E_PRINT_SERVER_FAILURE; + } + if (info.HasOption()) { + PRINT_HILOGI("the printerInfo option"); + PrinterCapability printerCaps; + std::string infoOpt = info.GetOption(); + PRINT_HILOGD("the printerInfo option %{public}s", infoOpt.c_str()); + if (!json::accept(infoOpt)) { + PRINT_HILOGE("infoOpt can not parse to json object"); + return E_PRINT_INVALID_PARAMETER; + } + nlohmann::json infoJson = nlohmann::json::parse(infoOpt); + if (!infoJson.contains("printerUri") || !infoJson["printerUri"].is_string()) { + PRINT_HILOGE("The infoJson does not have a necessary printerUri attribute."); + return E_PRINT_INVALID_PARAMETER; + } + std::string printerUri = infoJson["printerUri"].get(); + PRINT_HILOGD("QueryPrinterInfoByPrinterId in %{public}s", printerUri.c_str()); + if (infoJson.contains("printerName") && infoJson["printerName"].is_string()) { + info.SetPrinterName(infoJson["printerName"].get()); + } + int32_t ret = QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps); + PRINT_HILOGI("QueryPrinterInfoByPrinterId out"); + if (ret != 0) { + PRINT_HILOGE("QueryPrinterInfoByPrinterId QueryPrinterCapabilityByUri fail"); + return E_PRINT_SERVER_FAILURE; + } + nlohmann::json cupsOptionsJson = printerCaps.GetPrinterAttrGroupJson(); + infoJson["cupsOptions"] = cupsOptionsJson; + info.SetOption(infoJson.dump()); + info.Dump(); + } + return E_PRINT_NONE; +} + bool PrintCupsClient::CheckPrinterMakeModel(JobParameters *jobParams) { cups_dest_t *dest = nullptr; @@ -677,8 +889,7 @@ void PrintCupsClient::StartCupsJob(JobParameters *jobParams, CallbackFunc callba if ((fp = cupsFileOpenFd(jobParams->fdList[i], "rb")) == NULL) { PRINT_HILOGE("Unable to open print file, cancel the job"); cupsCancelJob2(http, jobParams->printerName.c_str(), jobId, 0); - jobParams->serviceAbility->UpdatePrintJobState(jobParams->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_COMPLETED_FILE_CORRUPT); + UpdatePrintJobStateInJobParams(jobParams, PRINT_JOB_BLOCKED, PRINT_JOB_COMPLETED_FILE_CORRUPT); callback(); return; } @@ -695,8 +906,7 @@ void PrintCupsClient::StartCupsJob(JobParameters *jobParams, CallbackFunc callba != IPP_STATUS_OK) { PRINT_HILOGE("Unable to queue, error is %s, cancel the job and return...", cupsLastErrorString()); cupsCancelJob2(http, jobParams->printerUri.c_str(), jobId, 0); - jobParams->serviceAbility->UpdatePrintJobState(jobParams->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_UNKNOWN); + UpdatePrintJobStateInJobParams(jobParams, PRINT_JOB_BLOCKED, PRINT_JOB_BLOCKED_UNKNOWN); callback(); return; } @@ -707,9 +917,15 @@ void PrintCupsClient::StartCupsJob(JobParameters *jobParams, CallbackFunc callba jobParams->serviceJobId, jobId, jobParams->printerUri, jobParams->printerName, jobParams->printerId }; if (param == nullptr) return; + g_isFirstQueryState = true; MonitorJobState(param, callback); } +void PrintCupsClient::UpdatePrintJobStateInJobParams(JobParameters *jobParams, uint32_t state, uint32_t subState) +{ + jobParams->serviceAbility->UpdatePrintJobState(jobParams->serviceJobId, state, subState); +} + void PrintCupsClient::MonitorJobState(JobMonitorParam *param, CallbackFunc callback) { http_t *http = NULL; @@ -727,6 +943,9 @@ void PrintCupsClient::MonitorJobState(JobMonitorParam *param, CallbackFunc callb if (httpGetFd(http) > 0 && CheckPrinterOnline(param->printerUri.c_str(), param->printerId)) { fail_connect_times = 0; QueryJobState(http, param, jobStatus); + if (g_isFirstQueryState) { + QueryJobStateAgain(http, param, jobStatus); + } } else if (fail_connect_times < OFFLINE_RETRY_TIMES) { PRINT_HILOGE("unable connect to printer, retry: %{public}d", fail_connect_times); fail_connect_times++; @@ -748,11 +967,7 @@ void PrintCupsClient::MonitorJobState(JobMonitorParam *param, CallbackFunc callb PRINT_HILOGD("the prevous jobState is the same as current, ignore"); continue; } - if (prevousJobStatus != nullptr) { - prevousJobStatus->job_state = jobStatus->job_state; - strlcpy(prevousJobStatus->printer_state_reasons, jobStatus->printer_state_reasons, - sizeof(jobStatus->printer_state_reasons)); - } + UpdateJobStatus(prevousJobStatus, jobStatus); JobStatusCallback(param, jobStatus, false); } httpClose(http); @@ -763,6 +978,23 @@ void PrintCupsClient::MonitorJobState(JobMonitorParam *param, CallbackFunc callb callback(); } +void PrintCupsClient::QueryJobStateAgain(http_t *http, JobMonitorParam *param, JobStatus *jobStatus) +{ + sleep(INTERVAL_FOR_FIRST_QUERY); + QueryJobState(http, param, jobStatus); + g_isFirstQueryState = false; +} + +void PrintCupsClient::UpdateJobStatus(JobStatus *prevousJobStatus, JobStatus *jobStatus) +{ + if (prevousJobStatus != nullptr && jobStatus != nullptr) { + prevousJobStatus->job_state = jobStatus->job_state; + strlcpy(prevousJobStatus->printer_state_reasons, + jobStatus->printer_state_reasons, + sizeof(jobStatus->printer_state_reasons)); + } +} + void PrintCupsClient::JobStatusCallback(JobMonitorParam *param, JobStatus *jobStatus, bool isOffline) { PRINT_HILOGD("JobStatusCallback enter, job_state: %{public}d", jobStatus->job_state); @@ -803,48 +1035,56 @@ void PrintCupsClient::ReportBlockedReason(JobMonitorParam *param, JobStatus *job PRINT_HILOGE("ReportBlockedReason parameter is nullptr"); return; } - if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MEDIA_EMPTY.c_str()) != NULL) { + if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_OFFLINE.c_str()) != NULL) { + param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, PRINT_JOB_BLOCKED_OFFLINE); + return; + } + if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_PAUSED.c_str()) != NULL) { + param->serviceAbility->UpdatePrintJobState( + param->serviceJobId, PRINT_JOB_BLOCKED, PRINT_JOB_BLOCKED_SERVICE_REQUEST); + return; + } + + uint32_t substate = GetBlockedSubstate(jobStatus); + if (substate > PRINT_JOB_COMPLETED_SUCCESS) { param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_OUT_OF_PAPER); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MEDIA_JAM.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_JAMMED); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_PAUSED.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_SERVICE_REQUEST); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_TONER_LOW.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_LOW_ON_TONER); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_TONER_EMPTY.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_OUT_OF_TONER); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_DOOR_EMPTY.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_DOOR_OPEN); + substate); } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MEDIA_NEEDED.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_OUT_OF_PAPER); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MARKER_LOW.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_LOW_ON_INK); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MARKER_EMPTY.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_OUT_OF_INK); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_INK_EMPTY.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_OUT_OF_INK); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_COVER_OPEN.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_DOOR_OPEN); - } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_OFFLINE.c_str()) != NULL) { - param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, - PRINT_JOB_BLOCKED_OFFLINE); + param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_RUNNING, + PRINT_JOB_BLOCKED_BUSY); } else { param->serviceAbility->UpdatePrintJobState(param->serviceJobId, PRINT_JOB_BLOCKED, PRINT_JOB_BLOCKED_UNKNOWN); } } +uint32_t PrintCupsClient::GetBlockedSubstate(JobStatus *jobStatus) +{ + uint32_t substate = PRINT_JOB_COMPLETED_SUCCESS; + if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MEDIA_EMPTY.c_str()) != NULL) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_OUT_OF_PAPER; + } + if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MEDIA_JAM.c_str()) != NULL) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_JAMMED; + } + if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_TONER_EMPTY.c_str()) != NULL) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_OUT_OF_TONER; + } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_TONER_LOW.c_str()) != NULL) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_LOW_ON_TONER; + } + if ((strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MARKER_EMPTY.c_str()) != NULL) || + (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_INK_EMPTY.c_str()) != NULL)) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_OUT_OF_INK; + } else if (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_MARKER_LOW.c_str()) != NULL) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_LOW_ON_INK; + } + if ((strstr(jobStatus->printer_state_reasons, PRINTER_STATE_DOOR_EMPTY.c_str()) != NULL) || + (strstr(jobStatus->printer_state_reasons, PRINTER_STATE_COVER_OPEN.c_str()) != NULL)) { + substate = substate * NUMBER_FOR_SPLICING_SUBSTATE + PRINT_JOB_BLOCKED_DOOR_OPEN; + } + return substate; +} + void PrintCupsClient::QueryJobState(http_t *http, JobMonitorParam *param, JobStatus *jobStatus) { ipp_t *request; /* IPP request */ @@ -942,6 +1182,25 @@ void PrintCupsClient::CancelCupsJob(std::string serviceJobId) } } +static void UpdateBorderlessJobParameter(json& optionJson, JobParameters *params) +{ + if (params == nullptr) { + return; + } + if (optionJson.contains("documentCategory") && optionJson["documentCategory"].is_number()) { + params->borderless = optionJson["documentCategory"]; + } else if (optionJson.contains("borderless") && optionJson["borderless"].is_string()) { + std::string isBorderless = optionJson["borderless"].get(); + if (isBorderless == "true") { + params->borderless = 1; // 1: borderless + } else { + params->borderless = 0; + } + } else { + params->borderless = 0; + } +} + JobParameters* PrintCupsClient::BuildJobParameters(const PrintJob &jobInfo) { JobParameters *params = nullptr; @@ -973,23 +1232,24 @@ JobParameters* PrintCupsClient::BuildJobParameters(const PrintJob &jobInfo) params->printerName = PrintUtil::StandardizePrinterName(optionJson["printerName"]); params->printerUri = optionJson["printerUri"]; params->documentFormat = optionJson["documentFormat"]; - if (optionJson.contains("documentCategory")) { - params->borderless = optionJson["documentCategory"]; - } else { - params->borderless = 0; + if (optionJson.contains("cupsOptions")) { + params->printerAttrsOption_cupsOption = optionJson["cupsOptions"]; } - if (optionJson.contains("printQuality")) - params->printQuality = optionJson["printQuality"]; - else + UpdateBorderlessJobParameter(optionJson, params); + if (optionJson.contains("printQuality") && optionJson["printQuality"].is_number()) { + params->printQuality = GetQulityString(optionJson["printQuality"]); + } else { params->printQuality = CUPS_PRINT_QUALITY_NORMAL; + } if (optionJson.contains("jobName")) params->jobName = optionJson["jobName"]; else params->jobName = DEFAULT_JOB_NAME; - if (optionJson.contains("mediaType")) + if (optionJson.contains("mediaType")) { params->mediaType = optionJson["mediaType"]; - else + } else { params->mediaType = CUPS_MEDIA_TYPE_PLAIN; + } params->serviceAbility = PrintServiceAbility::GetInstance(); return params; } @@ -1010,6 +1270,8 @@ void PrintCupsClient::DumpJobParameters(JobParameters* jobParams) PRINT_HILOGD("jobParams->mediaSize: %{public}s", jobParams->mediaSize.c_str()); PRINT_HILOGD("jobParams->mediaType: %{public}s", jobParams->mediaType.c_str()); PRINT_HILOGD("jobParams->color: %{public}s", jobParams->color.c_str()); + PRINT_HILOGD("jobParams->printerAttrsOption_cupsOption: %{public}s", + jobParams->printerAttrsOption_cupsOption.c_str()); } @@ -1101,119 +1363,12 @@ bool PrintCupsClient::IsPrinterExist(const char *printerUri, const char *printer return printerExist; } -void PrintCupsClient::ParsePrinterAttributes(ipp_t *response, PrinterCapability &printerCaps) -{ - int i; - ipp_attribute_t *attrptr; - SetOptionAttribute(response, printerCaps); - GetSupportedDuplexType(response, printerCaps); - - if ((attrptr = ippFindAttribute(response, "color-supported", IPP_TAG_BOOLEAN)) != NULL) { - if (ippGetBoolean(attrptr, 0)) { - printerCaps.SetColorMode(1); - } - } - if ((attrptr = ippFindAttribute(response, "media-supported", IPP_TAG_KEYWORD)) != NULL) { - PRINT_HILOGD("media-supported found; number of values %{public}d", ippGetCount(attrptr)); - std::vector supportedMediaSizes; - for (i = 0; i < ippGetCount(attrptr); i++) { - const char* meidaSize = ippGetString(attrptr, i, NULL); - PRINT_HILOGD("media-supported found; mediaSizes: %s", meidaSize); - auto nativeObj = std::make_shared(); - nativeObj->SetName(meidaSize); - supportedMediaSizes.emplace_back(*nativeObj); - } - printerCaps.SetPageSize(supportedMediaSizes); - } -} - -void PrintCupsClient::SetOptionAttribute(ipp_t *response, PrinterCapability &printerCaps) -{ - ipp_attribute_t *attrptr; - nlohmann::json options; - if ((attrptr = ippFindAttribute(response, "printer-make-and-model", IPP_TAG_TEXT)) != NULL) { - options["make"] = ippGetString(attrptr, 0, NULL); - } - if ((attrptr = ippFindAttribute(response, "printer-uuid", IPP_TAG_URI)) != NULL) { - options["uuid"] = ippGetString(attrptr, 0, NULL); - } - if ((attrptr = ippFindAttribute(response, "printer-name", IPP_TAG_TEXT)) != NULL) { - options["printerName"] = ippGetString(attrptr, 0, NULL); - } - nlohmann::json supportTypes = ParseSupportMediaTypes(response); - options["supportedMediaTypes"] = supportTypes; - nlohmann::json supportQualities = ParseSupportQualities(response); - options["supportQualities"] = supportQualities; - std::string optionStr = options.dump(); - printerCaps.SetOption(optionStr); -} - -void PrintCupsClient::GetSupportedDuplexType(ipp_t *response, PrinterCapability &printerCaps) -{ - ipp_attribute_t *attrptr; - if ((attrptr = ippFindAttribute(response, "sides-supported", IPP_TAG_KEYWORD)) != NULL) { - if (ippContainsString(attrptr, CUPS_SIDES_TWO_SIDED_LANDSCAPE)) { - printerCaps.SetDuplexMode((uint32_t)DUPLEX_MODE_TWO_SIDED_SHORT_EDGE); - } else if (ippContainsString(attrptr, CUPS_SIDES_TWO_SIDED_PORTRAIT)) { - printerCaps.SetDuplexMode((uint32_t)DUPLEX_MODE_TWO_SIDED_LONG_EDGE); - } else { - printerCaps.SetDuplexMode((uint32_t)DUPLEX_MODE_ONE_SIDED); - } - } -} - -nlohmann::json PrintCupsClient::ParseSupportQualities(ipp_t *response) -{ - ipp_attribute_t *attrptr; - nlohmann::json supportedQualities = nlohmann::json::array(); - if ((attrptr = ippFindAttribute(response, "print-quality-supported", IPP_TAG_ENUM)) != NULL) { - for (int i = 0; i < ippGetCount(attrptr); i++) { - int mediaQuality = ippGetInteger(attrptr, i); - PRINT_HILOGD("print-quality-supported: %{public}d", mediaQuality); - supportedQualities.push_back(mediaQuality); - } - } - return supportedQualities; -} - -nlohmann::json PrintCupsClient::ParseSupportMediaTypes(ipp_t *response) -{ - ipp_attribute_t *attrptr; - nlohmann::json _supportedMediaTypes = nlohmann::json::array(); - attrptr = ippFindAttribute(response, "media-type-supported", IPP_TAG_KEYWORD); - if (attrptr == NULL) { - attrptr = ippFindAttribute(response, "media-type-supported", IPP_TAG_NAME); - } - if (attrptr != NULL) { - PRINT_HILOGD("media-type-supported found; number of values %d", ippGetCount(attrptr)); - for (int i = 0; i < ippGetCount(attrptr); i++) { - const char* mediaType = ippGetString(attrptr, i, NULL); - PRINT_HILOGD("media-type-supported found; mediaType: %s", mediaType); - if (strcasestr(mediaType, "photographic-glossy")) { - _supportedMediaTypes.push_back((uint32_t)MEDIA_PHOTO_GLOSSY); - } else if (strcasestr(mediaType, "photo")) { - _supportedMediaTypes.push_back((uint32_t)MEDIA_PHOTO); - } else if (strcasestr(mediaType, "stationery")) { - _supportedMediaTypes.push_back((uint32_t)MEDIA_PLAIN); - } else if (strcasestr(mediaType, "auto")) { - _supportedMediaTypes.push_back((uint32_t)MEDIA_AUTO); - } - } - if (_supportedMediaTypes.empty()) { - _supportedMediaTypes.push_back((uint32_t)MEDIA_PLAIN); - _supportedMediaTypes.push_back((uint32_t)MEDIA_PHOTO); - _supportedMediaTypes.push_back((uint32_t)MEDIA_PHOTO_GLOSSY); - } - } - return _supportedMediaTypes; -} - float PrintCupsClient::ConvertInchTo100MM(float num) { return ((num / THOUSAND_INCH) * CONVERSION_UNIT); } -bool PrintCupsClient::IsIpConflict(const std::string &printerId, std::string &nic) +bool PrintCupsClient::IsIpConflict(const std::string &printerId, std::string &nic) __attribute__((no_sanitize("cfi"))) { if (printerId.find(P2P_PRINTER) == std::string::npos) { PRINT_HILOGD("The printer is not p2p: %{private}s", printerId.c_str()); diff --git a/services/print_service/src/print_event_subscriber.cpp b/services/print_service/src/print_event_subscriber.cpp new file mode 100644 index 0000000..9db373f --- /dev/null +++ b/services/print_service/src/print_event_subscriber.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_event_subscriber.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "print_usb_manager.h" +#include "print_http_server_manager.h" +#include "print_log.h" +#include "print_service_ability.h" + +namespace OHOS { +namespace Print { +PrintEventSubscriber::PrintEventSubscriber( + const EventFwk::CommonEventSubscribeInfo &subscribeInfo) : EventFwk::CommonEventSubscriber(subscribeInfo) +{} + +PrintEventSubscriber::~PrintEventSubscriber() +{} + +void PrintEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + std::string action = data.GetWant().GetAction(); +#ifdef IPPOVERUSB_ENABLE + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED) { + std::string devStr = data.GetData(); + DelayedSingleton::GetInstance()->DealUsbDevStatusChange(devStr, true); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED) { + std::string devStr = data.GetData(); + DelayedSingleton::GetInstance()->DealUsbDevDetach(devStr); + DelayedSingleton::GetInstance()->DealUsbDevStatusChange(devStr, false); + } +#endif // IPPOVERUSB_ENABLE + + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + int32_t userId = data.GetCode(); + PRINT_HILOGI("user switched, current userId: %{public}d", userId); + PrintServiceAbility::GetInstance()->SwitchUser(userId); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + int32_t userId = data.GetCode(); + PRINT_HILOGI("user removed, removed userId: %{public}d", userId); + PrintServiceAbility::GetInstance()->CancelUserPrintJobs(userId); + } +} + +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/services/print_service/src/print_http_request_process.cpp b/services/print_service/src/print_http_request_process.cpp new file mode 100644 index 0000000..30d1f21 --- /dev/null +++ b/services/print_service/src/print_http_request_process.cpp @@ -0,0 +1,568 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_http_request_process.h" +#include +#include "print_log.h" +#include "print_ipp_over_usb_util.h" +#include "usb_errors.h" + +namespace OHOS::Print { +using namespace std; +using namespace OHOS; +using namespace OHOS::USB; +using namespace httplib; + +PrintHttpRequestProcess::PrintHttpRequestProcess() +{} + +PrintHttpRequestProcess::~PrintHttpRequestProcess() +{} + +std::string PrintHttpRequestProcess::PrintOperation(Operation operation) +{ + if (operation == Operation::Get_Printer_Attributes) { + return HTTP_OPERATION_GET_ATTR; + } else if (operation == Operation::Send_Document) { + return HTTP_OPERATION_SEND_DOC; + } else { + return HTTP_OPERATION_COMMON; + } +} + +size_t PrintHttpRequestProcess::NeedOffset(const std::vector &readTempBuffer) +{ + size_t readSize = readTempBuffer.size(); + size_t reqindex = 0; + bool checkNeedOffset = (readSize > HTTP_COMMON_CONST_VALUE_25 && readTempBuffer[INDEX_0] == HTTP_RESPONSE_H && + readTempBuffer[INDEX_1] == HTTP_RESPONSE_T && readTempBuffer[INDEX_2] == HTTP_RESPONSE_T && + readTempBuffer[INDEX_3] == HTTP_RESPONSE_P && + readTempBuffer[INDEX_4] == HTTP_RESPONSE_VERSION_SPLIT_GANG && + readTempBuffer[INDEX_5] == HTTP_MSG_CHAR_1 && + readTempBuffer[INDEX_6] == HTTP_MSG_CHAR_2E && + readTempBuffer[INDEX_7] == HTTP_MSG_CHAR_1 && + readTempBuffer[INDEX_8] == HTTP_MSG_CHAR_20 && + readTempBuffer[INDEX_9] == HTTP_MSG_CHAR_1 && + readTempBuffer[INDEX_10] == HTTP_MSG_CHAR_0 && + readTempBuffer[INDEX_11] == HTTP_MSG_CHAR_0); + if (checkNeedOffset) { + PRINT_HILOGD("include HTTP/1.1 100"); + reqindex = HTTP_COMMON_CONST_VALUE_25; + } + return reqindex; +} + +void PrintHttpRequestProcess::RecordBufByOperation(Operation operation, size_t requestId, + const std::vector &tmVector) +{ + if (operation == Operation::Send_Document) { + std::lock_guard mtx_locker(mutexSendDoc); + if (readSendDocBufMap.find(requestId) == readSendDocBufMap.end()) { + readSendDocBufMap[requestId] = tmVector; + } + } else { + if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_GET_ATTR) { + std::lock_guard mtx_locker(mutexGetAttr); + if (readGetAttrBufMap.find(requestId) == readGetAttrBufMap.end()) { + readGetAttrBufMap[requestId] = tmVector; + } + } else { + std::lock_guard mtx_locker(mutexCommon); + if (readBufMap.find(requestId) == readBufMap.end()) { + readBufMap[requestId] = tmVector; + } + } + } +} + +void PrintHttpRequestProcess::GetContentLength(const std::vector &readTempBuffer, size_t index, + bool &findContentLength, size_t &contentLength) +{ + size_t readSize = readTempBuffer.size(); + if ((index + HTTP_COMMON_CONST_VALUE_14) < readSize) { + std::string tmpStr = ""; + for (size_t offset = 0; offset < HTTP_COMMON_CONST_VALUE_14; offset++) { + tmpStr += readTempBuffer[index + offset]; + } + if (tmpStr == HTTP_CONTENT_LENGTH) { + findContentLength = true; + std::string lenStr = ""; + size_t lenIndex = index + HTTP_COMMON_CONST_VALUE_14 + HTTP_COMMON_CONST_VALUE_2; + while (lenIndex < readSize - 1 && (!(readTempBuffer[lenIndex] == HTTP_SPLIT_R_CODE && + readTempBuffer[lenIndex + INDEX_1] == HTTP_SPLIT_N_CODE))) { + lenStr += readTempBuffer[lenIndex]; + lenIndex++; + } + contentLength = static_cast(std::stoi(lenStr)); + PRINT_HILOGD("contentLength = %{public}s, %{public}lu", lenStr.c_str(), contentLength); + } + } +} + +void PrintHttpRequestProcess::DumpRespIdCode(const std::vector &readTempBuffer, + Operation operation, size_t begin, size_t maxSize) +{ + for (size_t i = begin; i < (begin + HTTP_COMMON_CONST_VALUE_8) && i < maxSize; i++) { + PRINT_HILOGD("operation:%{public}s, readTempBuffer: %{public}x", + PrintOperation(operation).c_str(), readTempBuffer[i]); + } +} + +bool PrintHttpRequestProcess::CheckLineEnd(std::vector &readTempBuffer, size_t index) +{ + size_t readSize = readTempBuffer.size(); + if ((index + HTTP_COMMON_CONST_VALUE_15) < readSize && readTempBuffer[index] == HTTP_SPLIT_R_CODE && + readTempBuffer[index + INDEX_1] == HTTP_SPLIT_N_CODE && readTempBuffer[index + INDEX_2] == HTTP_SPLIT_R_CODE && + readTempBuffer[index + INDEX_3] == HTTP_SPLIT_N_CODE) { + return true; + } + return false; +} + +size_t PrintHttpRequestProcess::CalculateRequestId( + std::vector &readTempBuffer, size_t index, Operation operation) +{ + size_t readSize = readTempBuffer.size(); + DumpRespIdCode(readTempBuffer, operation, index + HTTP_COMMON_CONST_VALUE_4, readSize); + return readTempBuffer[index + HTTP_COMMON_CONST_VALUE_8] * + pow(HTTP_COMMON_CONST_VALUE_10, HTTP_COMMON_CONST_VALUE_3) + + readTempBuffer[index + HTTP_COMMON_CONST_VALUE_9] * + pow(HTTP_COMMON_CONST_VALUE_10, HTTP_COMMON_CONST_VALUE_2) + + readTempBuffer[index + HTTP_COMMON_CONST_VALUE_10] * HTTP_COMMON_CONST_VALUE_10 + + readTempBuffer[index + HTTP_COMMON_CONST_VALUE_11]; +} + +size_t PrintHttpRequestProcess::CalculateFileDataBeginIndex(size_t index, Operation operation) +{ + size_t fileDataBeginIndex = index + INDEX_4; + PRINT_HILOGD("operation:%{public}s, fileDataBeginIndex = %{public}lu", + PrintOperation(operation).c_str(), fileDataBeginIndex); + return fileDataBeginIndex; +} + +bool PrintHttpRequestProcess::ProcessDataFromDevice(Operation operation) +{ + std::vector readTempBuffer; + int32_t readFromUsbRes = + DelayedSingleton::GetInstance()->BulkTransferRead(devName, operation, readTempBuffer); + if (readFromUsbRes == EORROR_HDF_DEV_ERR_NO_DEVICE) { + PRINT_HILOGE("HDF_DEV_ERR_NO_DEVICE, The device module has no device"); + deviceOpen = false; + return true; + } + size_t readSize = readTempBuffer.size(); + if (readSize > 0 && readFromUsbRes == UEC_OK) { + PRINT_HILOGD("operation:%{public}s, readSize = %{public}lu", PrintOperation(operation).c_str(), readSize); + size_t reqindex = NeedOffset(readTempBuffer); + size_t requestId = 0; + std::vector tmVector; + bool findRequestId = false; + bool findContentLength = false; + size_t contentLength = 0; + size_t fileDataBeginIndex = 0; + // 解析出报文中的RequestId 和 Content-Length + for (size_t index = reqindex; index < readSize; index++) { + bool findLineEnd = (!findRequestId && CheckLineEnd(readTempBuffer, index)); + if (findLineEnd) { + requestId = CalculateRequestId(readTempBuffer, index, operation); + fileDataBeginIndex = CalculateFileDataBeginIndex(index, operation); + findRequestId = true; + } + if (!findContentLength) { + GetContentLength(readTempBuffer, index, findContentLength, contentLength); + } + tmVector.push_back(readTempBuffer[index]); + } + // 一次读取的报文长度小于 Content-Length字段的值则需再读取一次 + if ((readSize - fileDataBeginIndex) < contentLength) { + GetAttrAgain(operation, tmVector); + } + PRINT_HILOGD("operation:%{public}s requestId: %{public}lu ", PrintOperation(operation).c_str(), requestId); + RecordBufByOperation(operation, requestId, tmVector); + return true; + } + return false; +} + +void PrintHttpRequestProcess::GetAttrAgain(Operation operation, std::vector &tmVector) +{ + PRINT_HILOGD("GetAttr again"); + std::vector readBuffer; + int32_t readFromUsbRes = + DelayedSingleton::GetInstance()->BulkTransferRead(devName, operation, readBuffer); + size_t readSize = readBuffer.size(); + if (readSize > 0 && readFromUsbRes == UEC_OK) { + PRINT_HILOGD("GetAttr again readSize = %{public}lu", readSize); + for (size_t index = 0; index < readSize; index++) { + tmVector.push_back(readBuffer[index]); + } + } +} + +void PrintHttpRequestProcess::StartReadSendDocDataFromPrinterLooper() +{ + PRINT_HILOGD("StartReadSendDocDataFromPrinterLooper"); + while (deviceOpen && needReadSendDoc) { + if (ProcessDataFromDevice(Operation::Send_Document)) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(USB_READ_INTERVAL)); + } + PRINT_HILOGD("EndReadSendDocDataFromPrinterLooper"); +} + +void PrintHttpRequestProcess::ProcessHttpResponse(httplib::Response &responseData, size_t requestId) +{ + PRINT_HILOGD("processHttpResponse enter"); + int retryCount = 0; + // cups timeout is 30 seconds + while (retryCount < RESPONSE_RETRY_MAX_TIMES && deviceOpen) { + std::this_thread::sleep_for(std::chrono::milliseconds(RESPONSE_RETRY_INTERVAL)); + retryCount++; + std::lock_guard mtx_locker(mutexCommon); + if (readBufMap.find(requestId) != readBufMap.end()) { + size_t totalSize = readBufMap[requestId].size(); + PRINT_HILOGD("Response totalSize:%{public}lu, retryCout = %{public}d", totalSize, retryCount); + PrintIppOverUsbUtil::ConstructHttpResponse(&readBufMap[requestId][0], totalSize, responseData); + readBufMap.erase(requestId); + break; + } else { + continue; + } + } + // 超时错误 + if (retryCount >= RESPONSE_RETRY_MAX_TIMES) { + PRINT_HILOGE("process_http_response time out retryCout: %{public}d", retryCount); + } + PRINT_HILOGD("process_http_response out"); +} + +void PrintHttpRequestProcess::ProcessHttpResponseGetAttr(httplib::Response &responseData, size_t requestId) +{ + PRINT_HILOGD("processHttpResponseGetAttr enter"); + int retryCount = 0; + while (retryCount < RESPONSE_RETRY_MAX_TIMES && deviceOpen) { + std::this_thread::sleep_for(std::chrono::milliseconds(RESPONSE_RETRY_INTERVAL)); + retryCount++; + std::lock_guard mtx_locker(mutexGetAttr); + if (readGetAttrBufMap.find(requestId) != readGetAttrBufMap.end()) { + size_t totalSize = readGetAttrBufMap[requestId].size(); + PRINT_HILOGD("Response GetAttr totalSize:%{public}lu, retryCout = %{public}d", totalSize, retryCount); + PrintIppOverUsbUtil::ConstructHttpResponse(&readGetAttrBufMap[requestId][0], totalSize, responseData); + readGetAttrBufMap.erase(requestId); + break; + } else { + continue; + } + } + // 超时错误 + if (retryCount >= RESPONSE_RETRY_MAX_TIMES) { + PRINT_HILOGE("process_http_response_get_attr time out retryCout: %{public}d", retryCount); + } + PRINT_HILOGD("process_http_response_get_attr out"); +} + +void PrintHttpRequestProcess::ProcessHttpResponseSendDoc(httplib::Response &responseData, size_t requestId) +{ + PRINT_HILOGD("ProcessHttpResponseSendDoc enter"); + int retryCount = 0; + while (retryCount < RESPONSE_RETRY_MAX_TIMES && deviceOpen) { + std::this_thread::sleep_for(std::chrono::milliseconds(RESPONSE_RETRY_INTERVAL)); + retryCount++; + std::lock_guard mtx_locker(mutexSendDoc); + if (readSendDocBufMap.find(requestId) != readSendDocBufMap.end()) { + size_t totalSize = readSendDocBufMap[requestId].size(); + PRINT_HILOGD("Response SendDoc totalSize:%{public}lu, retryCout = %{public}d", totalSize, retryCount); + PrintIppOverUsbUtil::ConstructHttpResponse(&readSendDocBufMap[requestId][0], totalSize, responseData); + readSendDocBufMap.erase(requestId); + break; + } else { + continue; + } + } + // 超时错误 + if (retryCount >= RESPONSE_RETRY_MAX_TIMES) { + PRINT_HILOGE("ProcessHttpResponseSendDoc time out retryCout: %{public}d", retryCount); + needReadSendDoc = false; + } + PRINT_HILOGD("ProcessHttpResponseSendDoc out"); +} + +bool PrintHttpRequestProcess::DealRequestHeader(const httplib::Request &requestData, std::string &sHeadersAndBody) +{ + bool ischunked = false; + for (const auto &x : requestData.headers) { + PRINT_HILOGD("requestData.headers first: %{public}s, second : %{public}s", x.first.c_str(), x.second.c_str()); + if (x.first == HTTP_TRANSFER_ENCODING && x.second == HTTP_CHUNKED) { + ischunked = true; + } + if (x.first == HTTP_EXPECT) { + continue; + } + sHeadersAndBody += x.first; + sHeadersAndBody += SPLIT_VALUE_COLON; + sHeadersAndBody += x.second; + sHeadersAndBody += HTTP_MSG_STRING_R_AND_N; + } + sHeadersAndBody += HTTP_MSG_STRING_R_AND_N; + return ischunked; +} + +void PrintHttpRequestProcess::CalcReqIdOperaId(const char *data, size_t dataLength, size_t &requestId) +{ + if (dataLength < HTTP_COMMON_CONST_VALUE_8) { + return; + } + DumpReqIdOperaId(data, dataLength); + size_t operationId = (uint8_t)(*(data + INDEX_2)) * HTTP_COMMON_CONST_VALUE_10 + (uint8_t)(*(data + INDEX_3)); + requestId = (uint8_t)(*(data + INDEX_4)) * HTTP_COMMON_CONST_VALUE_1000 + + (uint8_t)(*(data + INDEX_5)) * HTTP_COMMON_CONST_VALUE_100 + + (uint8_t)(*(data + INDEX_6)) * HTTP_COMMON_CONST_VALUE_10 + (uint8_t)(*(data + INDEX_7)); + reqIdOperaIdMap[requestId] = operationId; +} + +void PrintHttpRequestProcess::StartWriteDataToPrinterLooper() +{ + PRINT_HILOGD("StartWriteDataToPrinterLooper"); + std::vector vectorRequestBuffer; + while (deviceOpen && needWriteData) { + std::string str = ""; + if (!ippDataQue.pop(str)) { + continue; + } + + vectorRequestBuffer.assign(str.begin(), str.end()); + int32_t ret = 0; + int32_t writeDataRetryCount = 0; + do { + ret = DelayedSingleton::GetInstance()->BulkTransferWrite( + devName, Operation::Common, vectorRequestBuffer); + PRINT_HILOGD("writeBody ret: %{public}d", ret); + if (ret == EORROR_HDF_DEV_ERR_TIME_OUT) { + std::this_thread::sleep_for(std::chrono::milliseconds(USB_WRITE_INTERVAL)); + writeDataRetryCount++; + PRINT_HILOGE( + "StartWriteDataToPrinterLooper, retrwriteDataRetryCounty = %{public}d", writeDataRetryCount); + } + } while (ret == EORROR_HDF_DEV_ERR_TIME_OUT && writeDataRetryCount < WRITE_RETRY_MAX_TIMES); + + if (ret == EORROR_HDF_DEV_ERR_NO_DEVICE) { + PRINT_HILOGE("WriteData HDF_DEV_ERR_NO_DEVICE, The device module has no device"); + needWriteData = false; + break; + } + vectorRequestBuffer.clear(); + int retryCount = 0; + while (retryCount < READ_RETRY_MAX_TIMES) { + retryCount++; + if (ProcessDataFromDevice(Operation::Common)) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(USB_READ_INTERVAL)); + } + // 读超时错误 + if (retryCount >= READ_RETRY_MAX_TIMES) { + PRINT_HILOGE("read data time out retryCout: %{public}d", retryCount); + } + } + PRINT_HILOGD("endtWriteDataToPrinterLooper"); +} + +void PrintHttpRequestProcess::CreatWriteDataTask() +{ + PRINT_HILOGD("CreatWriteDataTask needWriteData: %{public}d", needWriteData); + if (!needWriteData) { + needWriteData = true; + std::thread writeDataTask(&PrintHttpRequestProcess::StartWriteDataToPrinterLooper, this); + writeDataTask.detach(); + } +} + +void PrintHttpRequestProcess::ProcessOtherRequest(const char *data, size_t data_length, + std::string &sHeadersAndBody, size_t requestId) +{ + CreatWriteDataTask(); + + sHeadersAndBody.append(data, data_length); + ippDataQue.push(sHeadersAndBody); +} + +void PrintHttpRequestProcess::DumpReqIdOperaId(const char *data, size_t data_length) +{ + if (data_length < REQID_OPERAID_LEN) { + return; + } + for (size_t i = 0; i < REQID_OPERAID_LEN; i++) { + PRINT_HILOGD("ipp: %{public}x", *(data + i)); + } +} + +void PrintHttpRequestProcess::CreatReadSendDocTask() +{ + PRINT_HILOGD("CreatReadSendDocTask needReadSendDoc: %{public}d", needReadSendDoc); + if (!needReadSendDoc) { + needReadSendDoc = true; + std::thread readSendDocTask(&PrintHttpRequestProcess::StartReadSendDocDataFromPrinterLooper, this); + readSendDocTask.detach(); + } +} + +std::string PrintHttpRequestProcess::CreateChunk(const char *data, size_t data_length) +{ + std::string chunkStr = PrintIppOverUsbUtil::IntToHexString(static_cast(data_length)); + chunkStr += HTTP_MSG_STRING_R_AND_N; + chunkStr.append(data, data_length); + chunkStr += HTTP_MSG_STRING_R_AND_N; + return chunkStr; +} + +int32_t PrintHttpRequestProcess::WriteDataSync(const std::string &dataStr) +{ + std::string sHeadersAndBody = dataStr; + int32_t ret = 0; + while (sHeadersAndBody.length() > USB_ENDPOINT_MAX_LENGTH) { + std::string send = sHeadersAndBody.substr(0, USB_ENDPOINT_MAX_LENGTH); + ret = BulkTransferWriteData(send); + if (ret != 0) { + return ret; + } + sHeadersAndBody = sHeadersAndBody.substr(USB_ENDPOINT_MAX_LENGTH); + } + if (!sHeadersAndBody.empty()) { + ret = BulkTransferWriteData(sHeadersAndBody); + } + return ret; +} + +int32_t PrintHttpRequestProcess::BulkTransferWriteData(const std::string &dataStr) +{ + std::vector vectorRequestBuffer; + size_t len = dataStr.length(); + sendDocTotalLen += len; + vectorRequestBuffer.assign(dataStr.begin(), dataStr.end()); + uint32_t retryNum = 0; + int32_t ret = 0; + do { + ret = DelayedSingleton::GetInstance()->BulkTransferWrite(devName, + Operation::Send_Document, vectorRequestBuffer); + PRINT_HILOGD("writeBody chunk, ret: %{public}d, len: %{public}lu, sendDocTotalLen: %{public}lu", + ret, len, sendDocTotalLen); + if (ret == EORROR_HDF_DEV_ERR_NO_DEVICE) { + sendDocTotalLen = 0; + deviceOpen = false; + return ret; + } + if (ret == EORROR_HDF_DEV_ERR_TIME_OUT) { + std::this_thread::sleep_for(std::chrono::milliseconds(USB_BULKTRANSFER_WRITE_SLEEP)); + retryNum++; + } + } while (ret == EORROR_HDF_DEV_ERR_TIME_OUT && retryNum < WRITE_RETRY_MAX_TIMES); + if (ret != 0) { + sendDocTotalLen = 0; + PRINT_HILOGD("Write data fail"); + return ret; + } + vectorRequestBuffer.clear(); + return ret; +} + +void PrintHttpRequestProcess::ProcessHttpResp(size_t requestId, httplib::Response &responseData, + const std::string &sHeadersAndBody) +{ + if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_GET_ATTR) { + ProcessHttpResponseGetAttr(responseData, requestId); + } else if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_SEND_DOC) { + if (!deviceOpen) { + PRINT_HILOGE("Device disconnect, return"); + return; + } + PRINT_HILOGD("writeBody chunk end sHeadersAndBody len: %{public}lu", sHeadersAndBody.length()); + std::string dataStr = sHeadersAndBody + HTTP_MSG_STRING_CHUNK_END; + auto ret = WriteDataSync(dataStr); + sendDocTotalLen = 0; + if (ret != 0) { + PRINT_HILOGE("writeBody chunk end fail"); + return; + } + PRINT_HILOGD("writeBody chunk end"); + ProcessHttpResponseSendDoc(responseData, requestId); + } else { + ProcessHttpResponse(responseData, requestId); + } +} + +uint32_t PrintHttpRequestProcess::ProcessRequest(const httplib::Request &requestData, httplib::Response &responseData, + const httplib::ContentReader &content_reader) +{ + PRINT_HILOGI("ProcessRequest devName: %{public}s", devName.c_str()); + std::string sHeadersAndBody = HTTP_POST; + bool isChunked = DealRequestHeader(requestData, sHeadersAndBody); + size_t requestId = 0; + bool isFirstRead = true; + content_reader([&](const char *data, size_t data_length) { + if (isChunked) { + if (isFirstRead) { + isFirstRead = false; + CalcReqIdOperaId(data, data_length, requestId); + CreatReadSendDocTask(); + sHeadersAndBody += CreateChunk(data, data_length); + return CPP_HTTP_OK; + } + } else { + CalcReqIdOperaId(data, data_length, requestId); + } + + if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_SEND_DOC) { + std::string dataChunk = CreateChunk(data, data_length); + if ((sHeadersAndBody.length() + dataChunk.length()) < USB_DATA_MAX_LENGTH) { + sHeadersAndBody += dataChunk; + return CPP_HTTP_OK; + } + auto ret = WriteDataSync(sHeadersAndBody); + if (ret != 0) { + return CPP_HTTP_FAIL; + } + sHeadersAndBody = dataChunk; + return CPP_HTTP_OK; + } + + ProcessOtherRequest(data, data_length, sHeadersAndBody, requestId); + return CPP_HTTP_OK; + }); + ProcessHttpResp(requestId, responseData, sHeadersAndBody); + PRINT_HILOGD("processRequest path: %{public}s end", requestData.path.c_str()); + return 0; +} + +void PrintHttpRequestProcess::SetDeviceName(std::string name) +{ + devName = name; +} + +std::string PrintHttpRequestProcess::GetDeviceName() +{ + return devName; +} + +void PrintHttpRequestProcess::Stop() +{ + PRINT_HILOGD("stop read data looper"); + needReadSendDoc = false; + needWriteSendDoc = false; + needWriteData = false; +} + +} + diff --git a/services/print_service/src/print_http_server_manager.cpp b/services/print_service/src/print_http_server_manager.cpp new file mode 100644 index 0000000..e0be569 --- /dev/null +++ b/services/print_service/src/print_http_server_manager.cpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_http_server_manager.h" +#include "print_http_request_process.h" +#include "print_usb_manager.h" +#include "print_log.h" +#include "nlohmann/json.hpp" +#include "cJSON.h" + +namespace OHOS::Print { +using namespace std; +using namespace OHOS; +using namespace httplib; + +using json = nlohmann::json; + +PrintHttpServerManager::PrintHttpServerManager() +{} + +PrintHttpServerManager::~PrintHttpServerManager() +{ +} + +bool PrintHttpServerManager::AllocatePort(std::shared_ptr svr, int32_t &port) +{ + for (int allocPort = HTTP_MIN_PORT; allocPort <= HTTP_MAX_PORT; allocPort++) { + bool isPortUse = false; + for (const auto& pair : printHttpPortMap) { + if (pair.second == allocPort) { + isPortUse = true; + break; + } + } + if (isPortUse) { + PRINT_HILOGD("port : %{public}d is using", allocPort); + continue; + } + if (svr->bind_to_port(LOCAL_HOST, allocPort)) { + PRINT_HILOGD("bind to port : %{public}d success", allocPort); + port = allocPort; + return true; + } + } + return false; +} + +void PrintHttpServerManager::StartServer(std::shared_ptr svr, + std::shared_ptr process) +{ + PRINT_HILOGD("startServer"); + svr->set_payload_max_length(HTTP_SERVER_MAX_LENGTH); + PRINT_HILOGD("post /"); + svr->Post("^/.*", [process](const httplib::Request &req, httplib::Response &res, + const httplib::ContentReader &content_reader) { + PRINT_HILOGD("listen path: %{public}s", req.path.c_str()); + if (process != nullptr) { + process->ProcessRequest(req, res, content_reader); + } + }); + + PRINT_HILOGD("after post"); + svr->listen_after_bind(); + PRINT_HILOGD("after listen"); +} + +bool PrintHttpServerManager::CreateServer(std::string printerName, int32_t &port) +{ + PRINT_HILOGD("PrintHttpServerManager init printerName: %{public}s, port: %{public}d", printerName.c_str(), port); + if (printHttpServerMap.find(printerName) != printHttpServerMap.end()) { + PRINT_HILOGI("printerName: %{public}s has server", printerName.c_str()); + if (printHttpPortMap.find(printerName) != printHttpPortMap.end()) { + port = printHttpPortMap[printerName]; + return true; + } + PRINT_HILOGE("printerName: %{public}s has server, but do not has port", printerName.c_str()); + return false; + } + + std::shared_ptr newServer = std::make_shared(); + int32_t allocPort = HTTP_MIN_PORT; + if (!AllocatePort(newServer, allocPort)) { + PRINT_HILOGE("AllocatePort fail, return!"); + return false; + } + port = allocPort; + printHttpServerMap[printerName] = newServer; + printHttpPortMap[printerName] = port; + std::shared_ptr newProcess = std::make_shared(); + printHttpProcessMap[printerName] = newProcess; + newProcess->SetDeviceName(printerName); + + std::thread tServer = std::thread(StartServer, printHttpServerMap[printerName], + printHttpProcessMap[printerName]); + tServer.detach(); + return true; +} + +void PrintHttpServerManager::StopServer(std::string printerName) +{ + PRINT_HILOGD("stopServer printerName: %{public}s", printerName.c_str()); + if (printHttpServerMap.find(printerName) != printHttpServerMap.end()) { + if (printHttpServerMap[printerName]->is_running()) { + printHttpServerMap[printerName]->stop(); + printHttpServerMap.erase(printerName); + } + } + if (printHttpPortMap.find(printerName) != printHttpPortMap.end()) { + printHttpPortMap.erase(printerName); + } + if (printHttpProcessMap.find(printerName) != printHttpProcessMap.end()) { + printHttpProcessMap[printerName]->Stop(); + printHttpProcessMap.erase(printerName); + } +} + +void PrintHttpServerManager::DealUsbDevDetach(const std::string &devStr) +{ + PRINT_HILOGD("devStr: %{public}s", devStr.c_str()); + cJSON *devJson = cJSON_Parse(devStr.c_str()); + if (!devJson) { + PRINT_HILOGE("Create devJson error"); + } + cJSON *jsonTemp = cJSON_GetObjectItem(devJson, "name"); + if (jsonTemp == nullptr || jsonTemp->valuestring == NULL) { + PRINT_HILOGE("The devJson does not have a necessary attribute."); + cJSON_Delete(devJson); + return; + } + string name = jsonTemp->valuestring; + string printerName = DelayedSingleton::GetInstance()->GetPrinterName(name); + PRINT_HILOGD("DealUsbDevDetach name: %{public}s, printerName: %{public}s", name.c_str(), printerName.c_str()); + if (printerName.empty()) { + cJSON_Delete(devJson); + return; + } + StopServer(printerName); + cJSON_Delete(devJson); +} +} diff --git a/services/print_service/src/print_ipp_over_usb_manager.cpp b/services/print_service/src/print_ipp_over_usb_manager.cpp new file mode 100644 index 0000000..9cede88 --- /dev/null +++ b/services/print_service/src/print_ipp_over_usb_manager.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_ipp_over_usb_manager.h" +#include "print_log.h" +#include "print_usb_manager.h" +#include "print_http_server_manager.h" +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_support.h" + +namespace OHOS::Print { +using namespace std; +using namespace OHOS; +using namespace OHOS::USB; +using namespace httplib; + +static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler"; + +PrintIppOverUsbManager::PrintIppOverUsbManager() +{} + +PrintIppOverUsbManager::~PrintIppOverUsbManager() +{} + +void PrintIppOverUsbManager::Init() +{ + if (isInit) { + return; + } + isInit = true; + PRINT_HILOGD("listen usb device attach detach"); + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); + + usbDevStatusListener = std::make_shared(subscribeInfo); + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(usbDevStatusListener)) { + PRINT_HILOGE("subscribe common event failed"); + } + DelayedSingleton::GetInstance()->Init(); +} + +bool PrintIppOverUsbManager::ConnectPrinter(const std::string printerId, int32_t &port) +{ + PRINT_HILOGD("ConnectPrinter printerId = %{public}s", printerId.c_str()); + // printerId: com.ohos.spooler:USB-XXXXX + auto posColon = printerId.find_first_of(SPLIT_VALUE_COLON); + if (posColon == std::string::npos) { + PRINT_HILOGE("can not find : , return!"); + return false; + } + std::string extensionId = printerId.substr(0, posColon); + PRINT_HILOGD("ConnectPrinter extensionId = %{public}s", extensionId.c_str()); + if (extensionId != SPOOLER_BUNDLE_NAME) { + PRINT_HILOGE("not system spooler, return!"); + return false; + } + std::string tmp = printerId.substr(posColon + INDEX_1); + PRINT_HILOGD("ConnectPrinter tmp = %{public}s", tmp.c_str()); + if (tmp.length() > INDEX_4 && (tmp.substr(0, INDEX_4) == PRINTER_ID_PREFIX)) { + std::string printerName = tmp.substr(INDEX_4); + PRINT_HILOGI("ConnectPrinter printerName = %{public}s", printerName.c_str()); + if (DelayedSingleton::GetInstance()->isExistIppOverUsbPrinter(printerName)) { + if (DelayedSingleton::GetInstance()->ConnectUsbPinter(printerName)) { + auto ret = DelayedSingleton::GetInstance()->CreateServer(printerName, port); + PRINT_HILOGI("printerName = %{public}s CreateServer ret: %{public}d ", printerName.c_str(), ret); + return ret; + } + PRINT_HILOGE("usb connect printerName = %{public}s fail", printerName.c_str()); + } + PRINT_HILOGE("printerName = %{public}s not Exist", printerName.c_str()); + } + return false; +} + +void PrintIppOverUsbManager::DisConnectPrinter(const std::string printerId) +{ + PRINT_HILOGD("DisConnectPrinter printerId = %{public}s", printerId.c_str()); + auto posColon = printerId.find_first_of(SPLIT_VALUE_COLON); + if (posColon == std::string::npos) { + PRINT_HILOGE("can not find : , return!"); + return; + } + std::string extensionId = printerId.substr(0, posColon); + PRINT_HILOGD("DisConnectPrinter extensionId = %{public}s", extensionId.c_str()); + if (extensionId != SPOOLER_BUNDLE_NAME) { + PRINT_HILOGE("not system spooler, return!"); + return; + } + std::string tmp = printerId.substr(posColon + INDEX_1); + PRINT_HILOGD("DisConnectPrinter tmp = %{public}s", tmp.c_str()); + if (tmp.length() > INDEX_4 && (tmp.substr(0, INDEX_4) == PRINTER_ID_PREFIX)) { + std::string printerName = tmp.substr(INDEX_4); + PRINT_HILOGD("DisConnectPrinter printerName = %{public}s", printerName.c_str()); + if (DelayedSingleton::GetInstance()->isExistIppOverUsbPrinter(printerName)) { + DelayedSingleton::GetInstance()->StopServer(printerName); + DelayedSingleton::GetInstance()->DisConnectUsbPinter(printerName); + } + } +} +} diff --git a/services/print_service/src/print_security_guard_info.cpp b/services/print_service/src/print_security_guard_info.cpp index 1af1197..3ec53f6 100644 --- a/services/print_service/src/print_security_guard_info.cpp +++ b/services/print_service/src/print_security_guard_info.cpp @@ -51,7 +51,17 @@ void PrintSecurityGuardInfo::setPrintTypeInfo(const PrinterInfo &printerInfo, co } } } - + printTypeInfo_.copyNumber = (int32_t)printJob.GetCopyNumber(); + if (json::accept(printJob.GetOption())) { + json jobOptionJson = json::parse(printJob.GetOption()); + if (jobOptionJson.contains("printPages") && jobOptionJson["printPages"].is_number()) { + printTypeInfo_.printPages = jobOptionJson["printPages"]; + } else { + std::vector fdList; + printJob.GetFdList(fdList); + printTypeInfo_.printPages = (int32_t)fdList.size(); + } + } uint32_t subState = printJob.GetSubState(); switch (subState) { case PRINT_JOB_COMPLETED_SUCCESS: @@ -76,6 +86,8 @@ nlohmann::json PrintSecurityGuardInfo::ToJson() printTypeInfoJson["mac"] = printTypeInfo_.mac; printTypeInfoJson["domain"] = printTypeInfo_.domain; printTypeInfoJson["name"] = printTypeInfo_.name; + printTypeInfoJson["copyNumber"] = printTypeInfo_.copyNumber; + printTypeInfoJson["printPages"] = printTypeInfo_.printPages; targetInfo_ = printTypeInfoJson.dump(); nlohmann::json securityGuardInfoJson; diff --git a/services/print_service/src/print_service_ability.cpp b/services/print_service/src/print_service_ability.cpp index b696799..d5f660e 100644 --- a/services/print_service/src/print_service_ability.cpp +++ b/services/print_service/src/print_service_ability.cpp @@ -26,7 +26,6 @@ #endif // CUPS_ENABLE #include "accesstoken_kit.h" #include "array_wrapper.h" -#include "core_service_client.h" #include "int_wrapper.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -44,25 +43,36 @@ #include "print_security_guard_manager.h" #include "hisys_event_util.h" #include "nlohmann/json.hpp" +#ifdef IPPOVERUSB_ENABLE +#include "print_ipp_over_usb_manager.h" +#endif // IPPOVERUSB_ENABLE +#include +#include namespace OHOS::Print { using namespace std; using namespace OHOS::HiviewDFX; using namespace Security::AccessToken; using json = nlohmann::json; +const std::string PRINTER_PREFERENCE_FILE = "/data/service/el1/public/print_service/printer_preference.json"; +const uint32_t MAX_JOBQUEUE_NUM = 512; const uint32_t ASYNC_CMD_DELAY = 10; const int64_t INIT_INTERVAL = 5000L; +const int32_t UID_TRANSFORM_DIVISOR = 200000; +const std::int32_t START_USER_ID = 100; +const std::int32_t MAX_USER_ID = 1099; +const uint32_t UNLOAD_SA_INTERVAL_10000 = 10000; static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler"; +static const std::string PCSETTINGS_BUNDLE_NAME = "com.hw.hmos.pcsettings"; +static const std::string SPOOLER_PACKAGE_NAME = "com.ohos.spooler"; static const std::string SPOOLER_ABILITY_NAME = "MainAbility"; static const std::string LAUNCH_PARAMETER_DOCUMENT_NAME = "documentName"; static const std::string LAUNCH_PARAMETER_JOB_ID = "jobId"; static const std::string LAUNCH_PARAMETER_FILE_LIST = "fileList"; static const std::string LAUNCH_PARAMETER_FD_LIST = "fdList"; static const std::string LAUNCH_PARAMETER_PRINT_ATTRIBUTE = "printAttributes"; -static const std::string PERMISSION_NAME_PRINT = "ohos.permission.PRINT"; -static const std::string PERMISSION_NAME_PRINT_JOB = "ohos.permission.MANAGE_PRINT_JOB"; static const std::string PRINTER_EVENT_TYPE = "printerStateChange"; static const std::string PRINTJOB_EVENT_TYPE = "jobStateChange"; static const std::string EXTINFO_EVENT_TYPE = "extInfoChange"; @@ -84,11 +94,14 @@ static const std::string QUEUE_JOB_LIST_COMPLETED = "completed"; static const std::string QUEUE_JOB_LIST_BLOCKED = "blocked"; static const std::string QUEUE_JOB_LIST_CLEAR_BLOCKED = "clear_blocked"; static const std::string SPOOLER_PREVIEW_ABILITY_NAME = "PrintServiceExtAbility"; +static const std::string SPOOLER_STATUS_BAR_ABILITY_NAME = "PluginPrintIconExtAbility"; static const std::string TOKEN_KEY = "ohos.ability.params.token"; static const std::string NOTIFY_INFO_SPOOLER_CLOSED_FOR_CANCELLED = "spooler_closed_for_cancelled"; static const std::string NOTIFY_INFO_SPOOLER_CLOSED_FOR_STARTED = "spooler_closed_for_started"; +static const std::string PRINTER_ID_DELIMITER = ":"; + static bool g_publishState = false; REGISTER_SYSTEM_ABILITY_BY_ID(PrintServiceAbility, PRINT_SERVICE_ID, true); @@ -101,8 +114,8 @@ std::string PrintServiceAbility::ingressPackage; PrintServiceAbility::PrintServiceAbility(int32_t systemAbilityId, bool runOnCreate) : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START), - spoolerBundleName_(SPOOLER_BUNDLE_NAME), spoolerAbilityName_(SPOOLER_ABILITY_NAME), currentJobId_(0), - helper_(nullptr), isJobQueueBlocked_(false) + spoolerBundleName_(SPOOLER_BUNDLE_NAME), spoolerAbilityName_(SPOOLER_ABILITY_NAME), currentJobOrderId_(0), + helper_(nullptr), isJobQueueBlocked_(false), currentUserId_(-1), printAppCount_(0) {} PrintServiceAbility::~PrintServiceAbility() @@ -135,10 +148,14 @@ int32_t PrintServiceAbility::Init() } g_publishState = true; } - KillAllAbility(); + printSystemData_.Init(); state_ = ServiceRunningState::STATE_RUNNING; PRINT_HILOGI("state_ is %{public}d.", static_cast(state_)); PRINT_HILOGI("Init PrintServiceAbility success."); + helper_->PrintSubscribeCommonEvent(); +#ifdef CUPS_ENABLE + return DelayedSingleton::GetInstance()->InitCupsResources(); +#endif // CUPS_ENABLE return ERR_OK; } @@ -150,6 +167,9 @@ void PrintServiceAbility::OnStart() } if (state_ == ServiceRunningState::STATE_RUNNING) { PRINT_HILOGI("PrintServiceAbility is already running."); +#ifdef CUPS_ENABLE + DelayedSingleton::GetInstance()->InitCupsResources(); +#endif // CUPS_ENABLE return; } InitServiceHandler(); @@ -181,13 +201,17 @@ void PrintServiceAbility::ManualStart() if (state_ != ServiceRunningState::STATE_RUNNING) { PRINT_HILOGI("PrintServiceAbility restart."); OnStart(); + } else { +#ifdef CUPS_ENABLE + DelayedSingleton::GetInstance()->InitCupsResources(); +#endif // CUPS_ENABLE } } -std::string PrintServiceAbility::GetPrintJobId() +std::string PrintServiceAbility::GetPrintJobOrderId() { std::lock_guard autoLock(instanceLock_); - return std::to_string(currentJobId_++); + return std::to_string(currentJobOrderId_++); } void PrintServiceAbility::OnStop() @@ -224,73 +248,38 @@ void PrintServiceAbility::BuildFDParam(const std::vector &fdList, AAFw want.SetParams(wantParams); } -int32_t PrintServiceAbility::StartPrint(const std::vector &fileList, - const std::vector &fdList, std::string &taskId) -{ - std::shared_ptr adapterParam = std::make_shared(); - CreateDefaultAdapterParam(adapterParam); - return CallSpooler(fileList, fdList, taskId, adapterParam); -} - -int32_t PrintServiceAbility::CallSpooler(const std::vector &fileList, - const std::vector &fdList, std::string &taskId, const std::shared_ptr &adapterParam) +int32_t PrintServiceAbility::StartService() { ManualStart(); if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION); return E_PRINT_NO_PERMISSION; } - PRINT_HILOGD("PrintServiceAbility StartPrint started."); - std::lock_guard lock(apiMutex_); - if (adapterParam->isCheckFdList && fileList.empty() && fdList.empty()) { - PRINT_HILOGE("to be printed filelist and fdlist are empty"); - return E_PRINT_INVALID_PARAMETER; + int64_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + auto iter = printUserDataMap_.find(callerTokenId); + if (iter == printUserDataMap_.end()) { + auto userData = std::make_shared(); + if (userData != nullptr) { + printUserDataMap_.insert(std::make_pair(callerTokenId, userData)); + } } - std::string jobId = GetPrintJobId(); - auto printJob = std::make_shared(); - printJob->SetFdList(fdList); - printJob->SetJobId(jobId); - printJob->SetJobState(PRINT_JOB_PREPARED); - AAFwk::Want want; - want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_ABILITY_NAME); - want.SetParam(LAUNCH_PARAMETER_JOB_ID, jobId); - want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList); - BuildAdapterParam(adapterParam, want, jobId); - BuildFDParam(fdList, want); - int32_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); - std::string callerPkg = DelayedSingleton::GetInstance()->QueryCallerBundleName(); - ingressPackage = callerPkg; - int32_t callerUid = IPCSkeleton::GetCallingUid(); - int32_t callerPid = IPCSkeleton::GetCallingPid(); - want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId); - want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid); - want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid); - want.SetParam(CALLER_PKG_NAME, callerPkg); - if (!StartAbility(want)) { - PRINT_HILOGE("Failed to start spooler ability"); - return E_PRINT_SERVER_FAILURE; - } - printJobList_.insert(std::make_pair(jobId, printJob)); - taskId = jobId; - SendPrintJobEvent(*printJob); - // save securityGuard base info - securityGuardManager_.receiveBaseInfo(jobId, callerPkg, fileList); + PRINT_HILOGI("nativePrint PrintServiceAbility StartService started."); + printAppCount_++; + PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_); #ifdef CUPS_ENABLE return DelayedSingleton::GetInstance()->InitCupsResources(); #endif // CUPS_ENABLE return E_PRINT_NONE; } -int32_t PrintServiceAbility::StartPrint(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token) +int32_t PrintServiceAbility::StartPrint(const std::vector &fileList, + const std::vector &fdList, std::string &taskId) { - std::shared_ptr adapterParam = std::make_shared(); - CreateDefaultAdapterParam(adapterParam); - return CallSpooler(fileList, fdList, taskId, token, adapterParam); + return CallSpooler(fileList, fdList, taskId); } int32_t PrintServiceAbility::CallSpooler(const std::vector &fileList, const std::vector &fdList, - std::string &taskId, const sptr &token, const std::shared_ptr &adapterParam) + std::string &taskId) { ManualStart(); if (!CheckPermission(PERMISSION_NAME_PRINT)) { @@ -299,42 +288,29 @@ int32_t PrintServiceAbility::CallSpooler(const std::vector &fileLis } PRINT_HILOGD("PrintServiceAbility StartPrint started."); std::lock_guard lock(apiMutex_); - if ((adapterParam->isCheckFdList && fileList.empty() && fdList.empty()) || token == nullptr) { - PRINT_HILOGE("to be printed filelist and fdlist are empty, or token is null."); + if (taskId.empty()) { + PRINT_HILOGE("jobId is empty"); return E_PRINT_INVALID_PARAMETER; } - std::string jobId = GetPrintJobId(); + PRINT_HILOGI("CallSpooler jobId: %{public}s", taskId.c_str()); auto printJob = std::make_shared(); printJob->SetFdList(fdList); - printJob->SetJobId(jobId); + printJob->SetJobId(taskId); printJob->SetJobState(PRINT_JOB_PREPARED); - AAFwk::Want want; - want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_PREVIEW_ABILITY_NAME); - want.SetParam(LAUNCH_PARAMETER_JOB_ID, jobId); - want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList); - BuildAdapterParam(adapterParam, want, jobId); - BuildFDParam(fdList, want); - int32_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + RegisterAdapterListener(taskId); std::string callerPkg = DelayedSingleton::GetInstance()->QueryCallerBundleName(); ingressPackage = callerPkg; - int32_t callerUid = IPCSkeleton::GetCallingUid(); - int32_t callerPid = IPCSkeleton::GetCallingPid(); - want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId); - want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid); - want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid); - want.SetParam(CALLER_PKG_NAME, callerPkg); - want.SetParam(TOKEN_KEY, token); - curRequestCode_ = (curRequestCode_ == INT_MAX) ? 0 : (curRequestCode_ + 1); - if (!StartPrintServiceExtension(want, curRequestCode_)) { - PRINT_HILOGE("Failed to start spooler ability"); - return E_PRINT_SERVER_FAILURE; - } - printJobList_.insert(std::make_pair(jobId, printJob)); - taskId = jobId; + AddToPrintJobList(taskId, printJob); SendPrintJobEvent(*printJob); + securityGuardManager_.receiveBaseInfo(taskId, callerPkg, fileList); - // save securityGuard base info - securityGuardManager_.receiveBaseInfo(jobId, callerPkg, fileList); +#ifdef IPPOVERUSB_ENABLE + PRINT_HILOGD("before PrintIppOverUsbManager Init"); + DelayedSingleton::GetInstance()->Init(); + PRINT_HILOGD("end PrintIppOverUsbManager Init"); +#endif // IPPOVERUSB_ENABLE + printAppCount_++; + PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_); return E_PRINT_NONE; } @@ -353,7 +329,7 @@ int32_t PrintServiceAbility::StopPrint(const std::string &taskId) int32_t PrintServiceAbility::ConnectPrinter(const std::string &printerId) { ManualStart(); - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; } @@ -373,10 +349,19 @@ int32_t PrintServiceAbility::ConnectPrinter(const std::string &printerId) return E_PRINT_SERVER_FAILURE; } + std::string newPrinterId = printerId; +#ifdef IPPOVERUSB_ENABLE + int32_t port = 0; + auto ret = DelayedSingleton::GetInstance()->ConnectPrinter(printerId, port); + if (ret && port > 0) { + newPrinterId = PrintUtils::GetGlobalId(printerId, std::to_string(port)); + } +#endif // IPPOVERUSB_ENABLE + auto cbFunc = extCallbackMap_[cid]; auto callback = [=]() { if (cbFunc != nullptr) { - cbFunc->OnCallback(printerId); + cbFunc->OnCallback(newPrinterId); } }; if (helper_->IsSyncMode()) { @@ -427,7 +412,7 @@ int32_t PrintServiceAbility::DisconnectPrinter(const std::string &printerId) int32_t PrintServiceAbility::StartDiscoverPrinter(const std::vector &extensionIds) { ManualStart(); - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; } @@ -501,7 +486,7 @@ bool PrintServiceAbility::DelayStartDiscovery(const std::string &extensionId) int32_t PrintServiceAbility::StopDiscoverPrinter() { ManualStart(); - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; } @@ -528,17 +513,54 @@ int32_t PrintServiceAbility::StopDiscoverPrinter() if (helper_->IsSyncMode()) { callback(); } else { - serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY); + serviceHandler_->PostTask(callback, 0); } } PRINT_HILOGW("StopDiscoverPrinter out."); return E_PRINT_NONE; } +int32_t PrintServiceAbility::DestroyExtension() +{ + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + PRINT_HILOGD("DestroyExtension started."); + std::lock_guard lock(apiMutex_); + + for (auto extension : extensionStateList_) { + if (extension.second < PRINT_EXTENSION_LOADING) { + continue; + } + extension.second = PRINT_EXTENSION_UNLOAD; + std::string cid = PrintUtils::EncodeExtensionCid(extension.first, PRINT_EXTCB_DESTROY_EXTENSION); + if (extCallbackMap_.find(cid) == extCallbackMap_.end()) { + PRINT_HILOGE("Destroy extension Not Register, BUT State is LOADED"); + continue; + } + + auto cbFunc = extCallbackMap_[cid]; + auto callback = [=]() { + if (cbFunc != nullptr) { + cbFunc->OnCallback(); + } + }; + if (helper_->IsSyncMode()) { + callback(); + } else { + serviceHandler_->PostTask(callback, 0); + } + } + PRINT_HILOGW("DestroyExtension out."); + return E_PRINT_NONE; +} + int32_t PrintServiceAbility::QueryAllExtension(std::vector &extensionInfos) { ManualStart(); - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; } @@ -575,11 +597,146 @@ int32_t PrintServiceAbility::QueryAllPrintJob(std::vector &printJobs) } PRINT_HILOGD("QueryAllPrintJob started."); std::lock_guard lock(apiMutex_); - printJobs.clear(); - for (auto printJob : queuedJobList_) { - printJobs.emplace_back(*printJob.second); + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; + } + int32_t ret = userData->QueryAllPrintJob(printJobs); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("QueryAllPrintJob failed."); + return ret; + } + return E_PRINT_NONE; +} + +int32_t PrintServiceAbility::QueryAddedPrinter(std::vector &printerList) +{ + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + PRINT_HILOGD("QueryAddedPrinter started."); + std::vector printerNameList; +#ifdef CUPS_ENABLE + int32_t ret = DelayedSingleton::GetInstance()->QueryAddedPrinterList(printerNameList); + PRINT_HILOGI("QueryAddedPrinter ret = %{public}d.", ret); + PRINT_HILOGI("QueryAddedPrinter printerNameList size = %{public}zd.", printerNameList.size()); + if (ret != 0) { + PRINT_HILOGE("cups QueryAddedPrinterList fail"); + return E_PRINT_INVALID_PRINTER; + } +#endif // CUPS_ENABLE + if (printerNameList.size() <= 0) { + printSystemData_.GetAddedPrinterListFromSystemData(printerNameList); + if (printerNameList.size() <= 0) { + PRINT_HILOGI("no added printerId"); + return E_PRINT_NONE; + } + } + for (uint32_t i = 0; i < printerNameList.size(); i++) { + PRINT_HILOGD("QueryAddedPrinter in printerName %{public}s", printerNameList[i].c_str()); + std::string printerId = printSystemData_.QueryPrinterIdByStandardizeName(printerNameList[i]); + PRINT_HILOGD("QueryAddedPrinter in printerId %{public}s", printerId.c_str()); + if (printerId.empty()) { + continue; + } + printerList.push_back(printerId); + } + return E_PRINT_NONE; +} + +int32_t PrintServiceAbility::QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) +{ + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + PRINT_HILOGD("QueryPrinterInfoByPrinterId started %{public}s", printerId.c_str()); + std::lock_guard lock(apiMutex_); + info.SetPrinterId(printerId); + bool findCapsInSystemData = false; + OHOS::Print::CupsPrinterInfo cupsPrinter; + if (printSystemData_.QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinter)) { + info.SetPrinterName(cupsPrinter.name); + nlohmann::json option; + option["printerName"] = cupsPrinter.name; + option["printerUri"] = cupsPrinter.uri; + option["make"] = cupsPrinter.maker; + info.SetOption(option.dump()); + PrinterCapability printerCapability; + if (printSystemData_.GetPrinterCapabilityFromSystemData(cupsPrinter, printerId, printerCapability)) { + findCapsInSystemData = true; + info.SetCapability(printerCapability); + } + info.SetPrinterStatus(cupsPrinter.printerStatus); + PRINT_HILOGI("QueryPrinterInfoByPrinterId printerStatus: %{public}d", info.GetPrinterStatus()); + } + PRINT_HILOGD("QueryPrinterInfoByPrinterId printerName = %{public}s", info.GetPrinterName().c_str()); + if (!findCapsInSystemData) { +#ifdef CUPS_ENABLE + int32_t ret = DelayedSingleton::GetInstance()->QueryPrinterInfoByPrinterId(printerId, info); + if (ret != 0) { + PRINT_HILOGE("cups QueryPrinterInfoByPrinterId fail, ret = %{public}d", ret); + return E_PRINT_INVALID_PRINTER; + } +#endif // CUPS_ENABLE + } + if (info.HasCapability()) { + printSystemData_.InsertPrinterInfo(printerId, info); + } + if (CheckIsDefaultPrinter(printerId)) { + PRINT_HILOGI("is default printer"); + info.SetIsDefaultPrinter(true); + } + if (CheckIsLastUsedPrinter(printerId)) { + PRINT_HILOGI("is last used printer"); + info.SetIsLastUsedPrinter(true); + } + return E_PRINT_NONE; +} + +int32_t PrintServiceAbility::QueryPrinterProperties(const std::string &printerId, + const std::vector &keyList, std::vector &valueList) +{ + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + std::lock_guard lock(apiMutex_); + std::shared_ptr printerInfo = printSystemData_.QueryPrinterInfoByPrinterId(printerId); + if (printerInfo == nullptr) { + PRINT_HILOGW("no printerInfo"); + return E_PRINT_INVALID_PRINTER; + } + + PrinterPreference printerPreference; + auto iter = printerIdAndPreferenceMap_.find(printerId); + if (iter != printerIdAndPreferenceMap_.end()) { + std::string savePrinterPreference = printerIdAndPreferenceMap_[printerId]; + if (!json::accept(savePrinterPreference)) { + PRINT_HILOGW("no printerPreference"); + return E_PRINT_INVALID_PRINTER; + } + nlohmann::json AttrsJson = json::parse(savePrinterPreference); + printerPreference = PrinterPreference::BuildPrinterPreferenceFromJson(AttrsJson); + } + + PRINT_HILOGD("printerInfo %{public}s", printerInfo->GetPrinterName().c_str()); + for (auto &key : keyList) { + if (key == "pagesizeId") { + valueList.emplace_back(key + "&" + printerPreference.setting.pagesizeId); + } else if (key == "orientation") { + valueList.emplace_back(key + "&" + printerPreference.setting.orientation); + } else if (key == "duplex") { + valueList.emplace_back(key + "&" + printerPreference.setting.duplex); + } else if (key == "quality") { + valueList.emplace_back(key + "&" + printerPreference.setting.quality); + } } - PRINT_HILOGE("QueryAllPrintJob End."); return E_PRINT_NONE; } @@ -593,19 +750,16 @@ int32_t PrintServiceAbility::QueryPrintJobById(std::string &printJobId, PrintJob PRINT_HILOGD("QueryPrintJobById started."); std::lock_guard lock(apiMutex_); - if (printJobList_.empty()) { - PRINT_HILOGD("printJobList is empty!"); - return E_PRINT_INVALID_PRINTJOB; + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; } - - auto jobIt = printJobList_.find(printJobId); - if (jobIt == printJobList_.end()) { - PRINT_HILOGD("no print job exists"); - return E_PRINT_INVALID_PRINTJOB; - } else { - printJob = *jobIt->second; + int32_t ret = userData->QueryPrintJobById(printJobId, printJob); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("QueryPrintJobById failed."); + return ret; } - PRINT_HILOGI("QueryPrintJobById End."); return E_PRINT_NONE; } @@ -613,14 +767,42 @@ int32_t PrintServiceAbility::AddPrinterToCups(const std::string &printerUri, con const std::string &printerMake) { ManualStart(); - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; } PRINT_HILOGD("AddPrinterToCups started."); #ifdef CUPS_ENABLE - DelayedSingleton::GetInstance()->AddPrinterToCups(printerUri, printerName, printerMake); + auto ret = DelayedSingleton::GetInstance()->AddPrinterToCups(printerUri, printerName, printerMake); + if (ret != E_PRINT_NONE) { + PRINT_HILOGW("AddPrinterToCups error = %{public}d.", ret); + return ret; + } #endif // CUPS_ENABLE + PRINT_HILOGD("AddPrinterToCups printerName %{public}s.", printerName.c_str()); + for (auto iter = printerInfoList_.begin(); iter != printerInfoList_.end(); ++iter) { + auto printerInfoPtr = iter->second; + if (printerInfoPtr == nullptr) { + continue; + } + std::string stdName = PrintUtil::StandardizePrinterName(printerInfoPtr->GetPrinterName()); + PRINT_HILOGD("AddPrinterToCups stdName %{public}s.", stdName.c_str()); + if (stdName != printerName) { + continue; + } + std::string id = iter->first; + CupsPrinterInfo info; + info.name = printerName; + info.uri = printerUri; + info.maker = printerMake; + printSystemData_.InsertCupsPrinter(id, info, false); + printSystemData_.SaveCupsPrinterMap(); + SendPrinterChangeEvent(0, *printerInfoPtr); + PrinterInfo printerInfo; + printSystemData_.QueryPrinterInfoById(id, printerInfo); + SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, printerInfo); + break; + } PRINT_HILOGD("AddPrinterToCups End."); return E_PRINT_NONE; } @@ -629,7 +811,7 @@ int32_t PrintServiceAbility::QueryPrinterCapabilityByUri(const std::string &prin PrinterCapability &printerCaps) { ManualStart(); - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + if (!CheckPermission(PERMISSION_NAME_PRINT)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; } @@ -638,10 +820,363 @@ int32_t PrintServiceAbility::QueryPrinterCapabilityByUri(const std::string &prin DelayedSingleton::GetInstance()->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps); #endif // CUPS_ENABLE PRINT_HILOGD("QueryPrinterCapabilityByUri End."); + if (printerCaps.HasOption()) { + std::string extensionId = DelayedSingleton::GetInstance()->QueryCallerBundleName(); + std::string printerExtId = PrintUtils::GetGlobalId(extensionId, printerId); + if (printerIdAndPreferenceMap_.count(printerExtId)) { + return E_PRINT_NONE; + } + PrinterPreference printPreference; + int32_t ret = BuildPrinterPreference(printerCaps, printPreference); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("printerCaps can not success to printPreference"); + return E_PRINT_NONE; + } + nlohmann::json jsonObject = nlohmann::json::object(); + jsonObject = printPreference.BuildPrinterPreferenceJson(); + std::string savePrinterPreference = jsonObject.dump(); + printerIdAndPreferenceMap_.insert(std::make_pair(printerExtId, savePrinterPreference)); + WritePreferenceToFile(); + } + std::string standardPrinterId = StandardizePrinterId(printerId); + for (auto iter = printerInfoList_.begin(); iter != printerInfoList_.end(); ++iter) { + auto printerInfoPtr = iter->second; + if (printerInfoPtr == nullptr) { + continue; + } + std::string id = iter->first; + if (standardPrinterId != id) { + continue; + } + std::string stdName = PrintUtil::StandardizePrinterName(printerInfoPtr->GetPrinterName()); + PRINT_HILOGD("QueryPrinterCapabilityByUri stdName %{public}s.", stdName.c_str()); + CupsPrinterInfo info; + info.name = stdName; + info.printerCapability = printerCaps; + printSystemData_.InsertCupsPrinter(id, info, true); + break; + } return E_PRINT_NONE; } -int32_t PrintServiceAbility::StartPrintJob(const PrintJob &jobInfo) +std::string PrintServiceAbility::StandardizePrinterId(const std::string &printerId) +{ + PRINT_HILOGI("printerId: %{public}s", printerId.c_str()); + std::string standardPrinterId = printerId; + auto pos = printerId.find(PRINTER_ID_DELIMITER); + if (pos == std::string::npos) { + return ""; + } + if (printerId.substr(0, pos) != SPOOLER_BUNDLE_NAME) { + standardPrinterId.assign(SPOOLER_BUNDLE_NAME + PRINTER_ID_DELIMITER + printerId); + } + return standardPrinterId; +} + +void PrintServiceAbility::BuildPrinterPreferenceByDefault(nlohmann::json& capOpt, PreferenceSetting &printerDefaultAttr) +{ + if (capOpt.contains("defaultPageSizeId") && capOpt["defaultPageSizeId"].is_string()) { + printerDefaultAttr.pagesizeId = capOpt["defaultPageSizeId"].get(); + } + if (capOpt.contains("orientation-requested-default") && capOpt["orientation-requested-default"].is_string()) { + printerDefaultAttr.orientation = capOpt["orientation-requested-default"].get(); + } + if (capOpt.contains("sides-default") && capOpt["sides-default"].is_string()) { + printerDefaultAttr.duplex = capOpt["sides-default"].get(); + } + if (capOpt.contains("print-quality-default") && capOpt["print-quality-default"].is_string()) { + printerDefaultAttr.quality = capOpt["print-quality-default"].get(); + } +} + +void PrintServiceAbility::BuildPrinterPreferenceByOption(std::string& key, std::string& supportedOpts, + std::vector& optAttrs) +{ + if (supportedOpts.length() <= 0) { + return; + } + PRINT_HILOGI("BuildPrinterPreferenceByOption %{public}s", supportedOpts.c_str()); + if (json::accept(supportedOpts) && supportedOpts.find("{") != std::string::npos) { + nlohmann::json ArrJson = json::parse(supportedOpts); + BuildPrinterAttrComponentByJson(key, ArrJson, optAttrs); + } else { + PrintUtil::Str2VecStr(supportedOpts, optAttrs); + } +} + +int32_t PrintServiceAbility::BuildPrinterPreference(PrinterCapability &cap, PrinterPreference &printPreference) +{ + std::string capOption = cap.GetOption(); + PRINT_HILOGI("printer capOption %{public}s", capOption.c_str()); + if (!json::accept(capOption)) { + PRINT_HILOGW("capOption can not parse to json object"); + return E_PRINT_INVALID_PARAMETER; + } + nlohmann::json capJson = json::parse(capOption); + if (!capJson.contains("cupsOptions")) { + PRINT_HILOGW("The capJson does not have a cupsOptions attribute."); + return E_PRINT_INVALID_PARAMETER; + } + nlohmann::json capOpt = capJson["cupsOptions"]; + + std::string key = "id"; + if (capOpt.contains("supportedPageSizeArray") && capOpt["supportedPageSizeArray"].is_string()) { + std::string supportedPageSizeOpts = capOpt["supportedPageSizeArray"].get(); + BuildPrinterPreferenceByOption(key, supportedPageSizeOpts, printPreference.pagesizeId); + } + + key = "orientation"; + if (capOpt.contains("orientation-requested-supported") && capOpt["orientation-requested-supported"].is_string()) { + std::string supportedOriOpts = capOpt["orientation-requested-supported"].get(); + BuildPrinterPreferenceByOption(key, supportedOriOpts, printPreference.orientation); + } + + key = "duplex"; + if (capOpt.contains("sides-supported") && capOpt["sides-supported"].is_string()) { + std::string supportedDeplexOpts = capOpt["sides-supported"].get(); + BuildPrinterPreferenceByOption(key, supportedDeplexOpts, printPreference.duplex); + } + + key = "quality"; + if (capOpt.contains("print-quality-supported") && capOpt["print-quality-supported"].is_string()) { + std::string supportedQualityOpts = capOpt["print-quality-supported"].get(); + BuildPrinterPreferenceByOption(key, supportedQualityOpts, printPreference.quality); + } + + BuildPrinterPreferenceByDefault(capOpt, printPreference.defaultSetting); + return E_PRINT_NONE; +} + +void PrintServiceAbility::BuildPrinterAttrComponentByJson(std::string& key, nlohmann::json& jsonArrObject, + std::vector &printerAttrs) +{ + if (!jsonArrObject.is_array()) { + PRINT_HILOGW("can not PrinterAttrsComponent by jsonArrObject"); + return; + } + for (auto &element : jsonArrObject.items()) { + nlohmann::json object = element.value(); + if (object.contains(key)) { + if (object[key].is_string()) { + printerAttrs.push_back(object[key].get()); + } else if (object[key].is_number()) { + int value = object[key]; + printerAttrs.push_back(std::to_string(value)); + } + } + } +} + +int32_t PrintServiceAbility::GetPrinterPreference(const std::string &printerId, std::string &printerPreference) +{ + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + int printerPreferenceNum = static_cast(printerIdAndPreferenceMap_.size()); + if (printerPreferenceNum <= 0) { + InitPreferenceMap(); + } + if (printerIdAndPreferenceMap_.size() > 0 && ReadPreferenceFromFile(printerId, printerPreference)) { + PRINT_HILOGI("ReadPreferenceFromFile %{public}s", printerPreference.c_str()); + return E_PRINT_NONE; + } + return E_PRINT_INVALID_PRINTER; +} + +int32_t PrintServiceAbility::SetPrinterPreference(const std::string &printerId, const std::string &printerSetting) +{ + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + int printerPreferenceNum = static_cast(printerIdAndPreferenceMap_.size()); + if (printerPreferenceNum <= 0) { + InitPreferenceMap(); + } + std::string printPreference; + if (printerIdAndPreferenceMap_.size() > 0 && ReadPreferenceFromFile(printerId, printPreference)) { + if (!nlohmann::json::accept(printPreference) && !nlohmann::json::accept(printerSetting)) { + PRINT_HILOGW("json accept fail"); + return E_PRINT_INVALID_PRINTER; + } + nlohmann::json objectJson = nlohmann::json::parse(printPreference); + PrinterPreference oldPrintPreference = PrinterPreference::BuildPrinterPreferenceFromJson(objectJson); + + PRINT_HILOGD("printerSetting %{public}s", printerSetting.c_str()); + nlohmann::json settingJson = nlohmann::json::parse(printerSetting); + PreferenceSetting newSetting = PreferenceSetting::BuildPreferenceSettingFromJson(settingJson); + oldPrintPreference.setting = newSetting; + + nlohmann::json savePrinterPreference = oldPrintPreference.BuildPrinterPreferenceJson(); + std::string newPrintPreference = savePrinterPreference.dump(); + PRINT_HILOGI("WriteNewPreferenceToFile %{public}s", newPrintPreference.c_str()); + printerIdAndPreferenceMap_[printerId] = newPrintPreference; + WritePreferenceToFile(); + return E_PRINT_NONE; + } + return E_PRINT_INVALID_PRINTER; +} + +bool PrintServiceAbility::ReadPreferenceFromFile(const std::string &printerId, std::string& printPreference) +{ + auto iter = printerIdAndPreferenceMap_.find(printerId); + if (iter != printerIdAndPreferenceMap_.end()) { + printPreference = printerIdAndPreferenceMap_[printerId]; + PRINT_HILOGE("open printer preference find %{public}s", printPreference.c_str()); + return true; + } + return false; +} + +void PrintServiceAbility::InitPreferenceMap() +{ + std::lock_guard lock(apiMutex_); + std::ifstream ifs(PRINTER_PREFERENCE_FILE.c_str(), std::ios::in | std::ios::binary); + if (!ifs.is_open()) { + PRINT_HILOGW("open printer preference file fail"); + return; + } + std::string fileData((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); + ifs.close(); + if (!nlohmann::json::accept(fileData)) { + PRINT_HILOGW("json accept fail"); + return; + } + nlohmann::json jsonObject = nlohmann::json::parse(fileData); + if (!jsonObject.contains("printer_list") || !jsonObject["printer_list"].is_array()) { + PRINT_HILOGW("can not find printer_list"); + return; + } + for (auto &element : jsonObject["printer_list"].items()) { + nlohmann::json object = element.value(); + for (auto it = object.begin(); it != object.end(); it++) { + std::string printerId = it.key(); + nlohmann::json printPreferenceJson = object[printerId]; + printerIdAndPreferenceMap_[printerId] = printPreferenceJson.dump(); + } + } +} + +bool PrintServiceAbility::WritePreferenceToFile() +{ + std::lock_guard lock(apiMutex_); + int32_t fd = open(PRINTER_PREFERENCE_FILE.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0740); + PRINT_HILOGD("SavePrinterPreferenceMap fd: %{public}d", fd); + if (fd < 0) { + PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str()); + close(fd); + return false; + } + nlohmann::json printerMapJson = nlohmann::json::array(); + + for (auto& printPreference : printerIdAndPreferenceMap_) { + if (json::accept(printPreference.second)) { + nlohmann::json printPreferenceJson = nlohmann::json::parse(printPreference.second); + nlohmann::json objectJson; + objectJson[printPreference.first] = printPreferenceJson; + printerMapJson.push_back(objectJson); + } + } + + nlohmann::json jsonObject; + jsonObject["printer_list"] = printerMapJson; + std::string jsonString = jsonObject.dump(); + size_t jsonLength = jsonString.length(); + auto writeLength = write(fd, jsonString.c_str(), jsonLength); + close(fd); + return (size_t)writeLength == jsonLength; +} + +bool PrintServiceAbility::UpdatePrintJobOptionByPrinterId(PrintJob &printJob) +{ + CupsPrinterInfo printerInfo; + if (!printSystemData_.QueryCupsPrinterInfoByPrinterId(printJob.GetPrinterId(), printerInfo)) { + PRINT_HILOGW("cannot find printer info by printerId"); + return false; + } + std::string oldOption = printJob.GetOption(); + PRINT_HILOGD("Print job option: %{public}s", oldOption.c_str()); + if (!json::accept(oldOption)) { + PRINT_HILOGW("old option not accepted"); + return false; + } + nlohmann::json infoJson = json::parse(oldOption); + infoJson["printerName"] = printerInfo.name; + infoJson["printerUri"] = printerInfo.uri; + std::string updatedOption = infoJson.dump(); + PRINT_HILOGD("Updated print job option: %{public}s", updatedOption.c_str()); + printJob.SetOption(updatedOption); + return true; +} + +std::shared_ptr PrintServiceAbility::AddNativePrintJob(const std::string &jobId, PrintJob &printJob) +{ + PRINT_HILOGD("jobId %{public}s", jobId.c_str()); + printJob.SetJobId(jobId); + printJob.SetJobState(PRINT_JOB_PREPARED); + auto nativePrintJob = std::make_shared(); + if (nativePrintJob == nullptr) { + PRINT_HILOGW("nativePrintJob is null"); + return nullptr; + } + nativePrintJob->UpdateParams(printJob); + nativePrintJob->Dump(); + AddToPrintJobList(jobId, nativePrintJob); + return nativePrintJob; +} + +int32_t PrintServiceAbility::StartNativePrintJob(PrintJob &printJob) +{ + startPrintTime_ = std::chrono::high_resolution_clock::now(); + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + std::lock_guard lock(apiMutex_); + if (!UpdatePrintJobOptionByPrinterId(printJob)) { + PRINT_HILOGW("cannot update printer name/uri"); + return E_PRINT_INVALID_PRINTER; + } + std::string jobId = PrintUtils::GetPrintJobId(); + auto nativePrintJob = AddNativePrintJob(jobId, printJob); + if (nativePrintJob == nullptr) { + return E_PRINT_SERVER_FAILURE; + } + auto printerId = nativePrintJob->GetPrinterId(); + auto extensionId = PrintUtils::GetExtensionId(printerId); + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT); + if (extCallbackMap_.find(cid) == extCallbackMap_.end()) { + return E_PRINT_SERVER_FAILURE; + } + UpdateQueuedJobList(jobId, nativePrintJob); + printerJobMap_[printerId].insert(std::make_pair(jobId, true)); +#ifdef CUPS_ENABLE + if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) { + NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING); + DelayedSingleton::GetInstance()->AddCupsPrintJob(printJob); + CallStatusBar(); + return E_PRINT_NONE; + } +#endif // CUPS_ENABLE + auto cbFunc = extCallbackMap_[cid]; + auto callback = [=]() { + if (cbFunc != nullptr) { + StartPrintJobCB(jobId, nativePrintJob); + cbFunc->OnCallback(*nativePrintJob); + CallStatusBar(); + } + }; + if (helper_->IsSyncMode()) { + callback(); + } else { + serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY); + } + return E_PRINT_NONE; +} + +int32_t PrintServiceAbility::StartPrintJob(PrintJob &jobInfo) { startPrintTime_ = std::chrono::high_resolution_clock::now(); ManualStart(); @@ -669,15 +1204,18 @@ int32_t PrintServiceAbility::StartPrintJob(const PrintJob &jobInfo) printerJobMap_[printerId].insert(std::make_pair(jobId, true)); #ifdef CUPS_ENABLE if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) { + NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING); DelayedSingleton::GetInstance()->AddCupsPrintJob(jobInfo); + CallStatusBar(); return E_PRINT_NONE; } -#endif // CUPS_ENABLE +#endif // CUPS_ENABLE auto cbFunc = extCallbackMap_[cid]; auto callback = [=]() { if (cbFunc != nullptr) { StartPrintJobCB(jobId, printJob); cbFunc->OnCallback(*printJob); + CallStatusBar(); } }; if (helper_->IsSyncMode()) { @@ -690,10 +1228,61 @@ int32_t PrintServiceAbility::StartPrintJob(const PrintJob &jobInfo) void PrintServiceAbility::UpdateQueuedJobList(const std::string &jobId, const std::shared_ptr &printJob) { + PRINT_HILOGI("enter UpdateQueuedJobList, jobId: %{public}s.", jobId.c_str()); + std::string jobOrderId = GetPrintJobOrderId(); + if (jobOrderId == "0") { + jobOrderList_.clear(); + } + PRINT_HILOGI("UpdateQueuedJobList jobOrderId: %{public}s.", jobOrderId.c_str()); if (queuedJobList_.find(jobId) != queuedJobList_.end()) { queuedJobList_[jobId] = printJob; - } else { + jobOrderList_[jobOrderId] = jobId; + } else if (static_cast(queuedJobList_.size()) < MAX_JOBQUEUE_NUM) { queuedJobList_.insert(std::make_pair(jobId, printJob)); + jobOrderList_.insert(std::make_pair(jobOrderId, jobId)); + } else { + PRINT_HILOGE("UpdateQueuedJobList out of MAX_JOBQUEUE_NUM"); + } + + int32_t userId = GetCurrentUserId(); + if (userId == E_PRINT_INVALID_USERID) { + PRINT_HILOGE("Invalid user id."); + return; + } + auto iter = printUserMap_.find(userId); + if (iter == printUserMap_.end() || iter->second == nullptr) { + PRINT_HILOGE("Invalid user id"); + return; + } + iter->second->UpdateQueuedJobList(jobId, printJob, jobOrderId); + + std::string printerId = printJob->GetPrinterId(); + auto iterator = printerInfoList_.find(printerId); + if (iterator != printerInfoList_.end()) { + iterator->second->SetPrinterStatus(PRINTER_STATUS_BUSY); + printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_BUSY); + SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *iterator->second); + } + SetLastUsedPrinter(printerId); +} + +void PrintServiceAbility::SetLastUsedPrinter(const std::string &printerId) +{ + PRINT_HILOGD("SetLastUsedPrinter started."); + if (!printSystemData_.IsPrinterAdded(printerId)) { + PRINT_HILOGE("Printer is not added to cups."); + return; + } + + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return; + } + int32_t ret = userData->SetLastUsedPrinter(printerId); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("SetLastUsedPrinter failed."); + return; } } @@ -714,9 +1303,14 @@ int32_t PrintServiceAbility::CancelPrintJob(const std::string &jobId) } std::lock_guard lock(apiMutex_); - auto jobIt = queuedJobList_.find(jobId); - if (jobIt == queuedJobList_.end()) { - PRINT_HILOGD("invalid job id"); + auto userData = GetUserDataByJobId(jobId); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; + } + auto jobIt = userData->queuedJobList_.find(jobId); + if (jobIt == userData->queuedJobList_.end()) { + PRINT_HILOGE("invalid job id"); return E_PRINT_INVALID_PRINTJOB; } @@ -736,7 +1330,7 @@ int32_t PrintServiceAbility::CancelPrintJob(const std::string &jobId) #endif // CUPS_ENABLE auto cbFunc = extCallbackMap_[cid]; - auto tmpPrintJob = queuedJobList_[jobId]; + auto tmpPrintJob = userData->queuedJobList_[jobId]; auto callback = [=]() { if (cbFunc != nullptr && cbFunc->OnCallback(*tmpPrintJob) == false) { UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED); @@ -748,25 +1342,73 @@ int32_t PrintServiceAbility::CancelPrintJob(const std::string &jobId) serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY); } } else { - auto printJob = std::make_shared(*jobIt->second); - printJob->SetJobState(PRINT_JOB_COMPLETED); - printJob->SetSubState(PRINT_JOB_COMPLETED_CANCELLED); - printJobList_.insert(std::make_pair(jobId, printJob)); - - UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED); + SetPrintJobCanceled(*jobIt->second); } return E_PRINT_NONE; } +void PrintServiceAbility::SetPrintJobCanceled(PrintJob &jobinfo) +{ + auto printJob = std::make_shared(jobinfo); + if (printJob == nullptr) { + PRINT_HILOGE("create printJob failed."); + return; + } + std::string jobId = printJob->GetJobId(); + auto userData = GetUserDataByJobId(jobId); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return; + } + printJob->SetJobState(PRINT_JOB_COMPLETED); + printJob->SetSubState(PRINT_JOB_COMPLETED_CANCELLED); + userData->printJobList_.insert(std::make_pair(jobId, printJob)); + printJobList_.insert(std::make_pair(jobId, printJob)); + UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED); +} + +void PrintServiceAbility::CancelUserPrintJobs(const int32_t userId) +{ + auto removedUser = printUserMap_.find(userId); + if (removedUser == printUserMap_.end()) { + PRINT_HILOGE("User dose not exist."); + return; + } + std::lock_guard lock(apiMutex_); + if (removedUser->second == nullptr) { + PRINT_HILOGE("PrintUserData is nullptr."); + return; + } + for (auto jobIt: removedUser->second->queuedJobList_) { + PRINT_HILOGI("CancelUserPrintJobs user jobId: %{public}s", jobIt.first.c_str()); + int32_t ret = CancelPrintJob(jobIt.first); + PRINT_HILOGI("CancelUserPrintJobs CancelPrintJob ret: %{public}d", ret); + userJobMap_.erase(jobIt.first); + } + printUserMap_.erase(userId); + PRINT_HILOGI("remove user-%{publis}d success.", userId); +} + +void PrintServiceAbility::SwitchUser(const int32_t userId) +{ + currentUserId_ = userId; + PRINT_HILOGI("currentUserId_: %{public}d.", currentUserId_); +} + void PrintServiceAbility::SendQueuePrintJob(const std::string &printerId) { if (printerJobMap_[printerId].empty()) { return; } + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return; + } auto jobId = printerJobMap_[printerId].begin()->first; - auto jobIt = queuedJobList_.find(jobId); - if (jobIt == queuedJobList_.end()) { + auto jobIt = userData->queuedJobList_.find(jobId); + if (jobIt == userData->queuedJobList_.end()) { PRINT_HILOGE("invalid print job, jobId:%{public}s", jobId.c_str()); return; } @@ -825,8 +1467,14 @@ int32_t PrintServiceAbility::AddPrinters(const std::vector &printer printerInfo->SetPrinterId(PrintUtils::GetGlobalId(extensionId, printerInfo->GetPrinterId())); printerInfo->SetPrinterState(PRINTER_ADDED); printerInfoList_.insert(std::make_pair(printerInfo->GetPrinterId(), printerInfo)); + SendPrinterDiscoverEvent(PRINTER_ADDED, *printerInfo); SendPrinterEvent(*printerInfo); SendQueuePrintJob(printerInfo->GetPrinterId()); + if (printSystemData_.IsPrinterAdded(printerInfo->GetPrinterId())) { + printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE); + printSystemData_.UpdatePrinterStatus(printerInfo->GetPrinterId(), PRINTER_STATUS_IDLE); + SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo); + } } PRINT_HILOGD("AddPrinters end. Total size is %{public}zd", printerInfoList_.size()); return E_PRINT_NONE; @@ -856,8 +1504,14 @@ int32_t PrintServiceAbility::RemovePrinters(const std::vector &prin } PrinterInfo info = *printerIt->second; info.SetPrinterState(PRINTER_REMOVED); + SendPrinterDiscoverEvent(PRINTER_REMOVED, info); SendPrinterEvent(info); printerInfoList_.erase(printerIt); + if (printSystemData_.IsPrinterAdded(info.GetPrinterId())) { + info.SetPrinterStatus(PRINTER_STATUS_UNAVAILABLE); + printSystemData_.UpdatePrinterStatus(info.GetPrinterId(), PRINTER_STATUS_UNAVAILABLE); + SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, info); + } } if (count == printerInfoList_.size()) { PRINT_HILOGE("Invalid printer ids"); @@ -891,6 +1545,7 @@ int32_t PrintServiceAbility::UpdatePrinters(const std::vector &prin *printerIt->second = info; printerIt->second->SetPrinterState(PRINTER_UPDATE_CAP); printerIt->second->SetPrinterId(printExtId); + SendPrinterDiscoverEvent(PRINTER_UPDATE_CAP, *printerIt->second); SendPrinterEvent(*printerIt->second); isChanged = true; } @@ -925,6 +1580,7 @@ int32_t PrintServiceAbility::UpdatePrinterState(const std::string &printerId, ui } printerInfoList_[printerExtId]->SetPrinterState(state); + SendPrinterDiscoverEvent(PRINTER_CONNECTED, *printerInfoList_[printerExtId]); SendPrinterEvent(*printerInfoList_[printerExtId]); PRINT_HILOGD("UpdatePrinterState end."); return E_PRINT_NONE; @@ -935,7 +1591,7 @@ bool PrintServiceAbility::checkJobState(uint32_t state, uint32_t subState) if (state > PRINT_JOB_UNKNOWN) { return false; } - if (state == PRINT_JOB_BLOCKED && (subState < PRINT_JOB_BLOCKED_OFFLINE || subState > PRINT_JOB_BLOCKED_UNKNOWN)) { + if (state == PRINT_JOB_BLOCKED && subState < PRINT_JOB_BLOCKED_OFFLINE) { return false; } if (state == PRINT_JOB_COMPLETED && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT) { @@ -945,16 +1601,23 @@ bool PrintServiceAbility::checkJobState(uint32_t state, uint32_t subState) return true; } +int32_t PrintServiceAbility::UpdatePrintJobStateOnlyForSystemApp( + const std::string &jobId, uint32_t state, uint32_t subState) +{ + ManualStart(); + if (state != PRINT_JOB_CREATE_FILE_COMPLETED && !CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + return UpdatePrintJobState(jobId, state, subState); +} + int32_t PrintServiceAbility::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) { ManualStart(); if (state == PRINT_JOB_CREATE_FILE_COMPLETED) { return AdapterGetFileCallBack(jobId, state, subState); } - if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { - PRINT_HILOGE("no permission to access print service"); - return E_PRINT_NO_PERMISSION; - } if (!checkJobState(state, subState)) { return E_PRINT_INVALID_PARAMETER; @@ -993,12 +1656,17 @@ int32_t PrintServiceAbility::AdapterGetFileCallBack(const std::string &jobId, ui int32_t PrintServiceAbility::CheckAndSendQueuePrintJob(const std::string &jobId, uint32_t state, uint32_t subState) { - auto jobIt = queuedJobList_.find(jobId); + auto userData = GetUserDataByJobId(jobId); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; + } + auto jobIt = userData->queuedJobList_.find(jobId); bool jobInQueue = true; - if (jobIt == queuedJobList_.end()) { + if (jobIt == userData->queuedJobList_.end()) { jobInQueue = false; - jobIt = printJobList_.find(jobId); - if (jobIt == printJobList_.end()) { + jobIt = userData->printJobList_.find(jobId); + if (jobIt == userData->printJobList_.end()) { PRINT_HILOGD("Invalid print job id"); return E_PRINT_INVALID_PRINTJOB; } @@ -1017,9 +1685,18 @@ int32_t PrintServiceAbility::CheckAndSendQueuePrintJob(const std::string &jobId, if (state == PRINT_JOB_COMPLETED) { if (jobInQueue) { printerJobMap_[printerId].erase(jobId); - queuedJobList_.erase(jobIt); + userData->queuedJobList_.erase(jobId); + queuedJobList_.erase(jobId); } if (printerJobMap_[printerId].empty()) { + auto iter = printerInfoList_.find(printerId); + if (iter != printerInfoList_.end()) { + iter->second->SetPrinterStatus(PRINTER_STATUS_IDLE); + printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_IDLE); + SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *iter->second); + } + } + if (IsQueuedJobListEmpty(jobId)) { ReportCompletedPrint(printerId); } SendQueuePrintJob(printerId); @@ -1029,11 +1706,32 @@ int32_t PrintServiceAbility::CheckAndSendQueuePrintJob(const std::string &jobId, return E_PRINT_NONE; } +bool PrintServiceAbility::IsQueuedJobListEmpty(const std::string &jobId) +{ + auto userData = GetUserDataByJobId(jobId); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; + } + if (!userData->queuedJobList_.empty()) { + PRINT_HILOGD("This user still has print jobs in progress."); + return false; + } + if (GetUserIdByJobId(jobId) != currentUserId_) { + PRINT_HILOGE("The user corresponding to this task is different from the current user."); + return false; + } + return true; +} + void PrintServiceAbility::ReportCompletedPrint(const std::string &printerId) { NotifyAppJobQueueChanged(QUEUE_JOB_LIST_COMPLETED); PRINT_HILOGD("no print job exists, destroy extension"); - DestroyExtension(printerId); + PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_); + if (queuedJobList_.size() == 0 && printAppCount_ == 0) { + UnloadSystemAbility(); + } json msg; auto endPrintTime = std::chrono::high_resolution_clock::now(); auto printTime = std::chrono::duration_cast(endPrintTime - startPrintTime_); @@ -1043,8 +1741,8 @@ void PrintServiceAbility::ReportCompletedPrint(const std::string &printerId) HisysEventUtil::reportPrintSuccess(msg.dump()); } -void PrintServiceAbility::ReportHisysEvent(const std::shared_ptr &jobInfo, - const std::string &printerId, uint32_t subState) +void PrintServiceAbility::ReportHisysEvent( + const std::shared_ptr &jobInfo, const std::string &printerId, uint32_t subState) { json msg; auto endPrintTime = std::chrono::high_resolution_clock::now(); @@ -1109,34 +1807,6 @@ bool PrintServiceAbility::isEprint(const std::string &printerId) return std::equal(ePrintID.rbegin(), ePrintID.rend(), printerId.rbegin()); } -void PrintServiceAbility::DestroyExtension(const std::string &printerId) -{ - std::lock_guard lock(apiMutex_); - if (printerInfoList_.find(printerId) == printerInfoList_.end()) { - PRINT_HILOGE("Invalid printer id"); - return; - } - - std::string extensionId = PrintUtils::GetExtensionId(printerId); - std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_DESTROY_EXTENSION); - if (extCallbackMap_.find(cid) == extCallbackMap_.end()) { - PRINT_HILOGW("DestroyExtension Not Register Yet!!!"); - return; - } - - auto cbFunc = extCallbackMap_[cid]; - auto callback = [=]() { - if (cbFunc != nullptr) { - cbFunc->OnCallback(); - } - }; - if (helper_->IsSyncMode()) { - callback(); - } else { - serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY); - } -} - int32_t PrintServiceAbility::UpdateExtensionInfo(const std::string &extInfo) { ManualStart(); @@ -1170,18 +1840,27 @@ int32_t PrintServiceAbility::RequestPreview(const PrintJob &jobInfo, std::string PRINT_HILOGD("RequestPreview started."); std::lock_guard lock(apiMutex_); + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; + } auto jobId = jobInfo.GetJobId(); auto printerId = jobInfo.GetPrinterId(); auto extensionId = PrintUtils::GetExtensionId(printerId); - auto jobIt = printJobList_.find(jobId); - if (jobIt == printJobList_.end()) { + auto jobIt = userData->printJobList_.find(jobId); + if (jobIt == userData->printJobList_.end()) { PRINT_HILOGD("invalid job id"); return E_PRINT_INVALID_PRINTJOB; } - if (printJobList_[jobId]->GetJobState() < PRINT_JOB_QUEUED) { - PRINT_HILOGD("invalid job state [%{public}d]", printJobList_[jobId]->GetJobState()); + if (userData->printJobList_[jobId] == nullptr) { + PRINT_HILOGE("printJob is nullptr."); + return E_PRINT_INVALID_PRINTJOB; + } + if (userData->printJobList_[jobId]->GetJobState() < PRINT_JOB_QUEUED) { + PRINT_HILOGD("invalid job state [%{public}d]", userData->printJobList_[jobId]->GetJobState()); return E_PRINT_INVALID_PRINTJOB; } @@ -1196,9 +1875,13 @@ int32_t PrintServiceAbility::RequestPreview(const PrintJob &jobInfo, std::string return E_PRINT_SERVER_FAILURE; } - printJobList_[jobId]->UpdateParams(jobInfo); + userData->printJobList_[jobId]->UpdateParams(jobInfo); auto cbFunc = extCallbackMap_[cid]; - auto callback = [=]() { cbFunc->OnCallback(*printJobList_[jobId]); }; + if (cbFunc == nullptr) { + PRINT_HILOGE("cbFunc is nullptr."); + return E_PRINT_SERVER_FAILURE; + } + auto callback = [=]() { cbFunc->OnCallback(*userData->printJobList_[jobId]); }; return E_PRINT_NONE; } @@ -1237,6 +1920,77 @@ int32_t PrintServiceAbility::QueryPrinterCapability(const std::string &printerId return E_PRINT_NONE; } +int32_t PrintServiceAbility::NotifyPrintServiceEvent(std::string &jobId, uint32_t event) +{ + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + + if (event < APPLICATION_CREATED || event > APPLICATION_CLOSED_FOR_CANCELED) { + PRINT_HILOGE("Invalid parameter"); + return E_PRINT_INVALID_PARAMETER; + } + + switch (event) { + case APPLICATION_CREATED: + if (printJobList_.find(jobId) == printJobList_.end()) { + PRINT_HILOGI("add printJob from phone, jobId: %{public}s", jobId.c_str()); + auto printJob = std::make_shared(); + printJob->SetJobId(jobId); + printJob->SetJobState(PRINT_JOB_PREPARED); + RegisterAdapterListener(jobId); + AddToPrintJobList(jobId, printJob); + SendPrintJobEvent(*printJob); + } + printAppCount_++; + PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_); + break; + case APPLICATION_CLOSED_FOR_STARTED: + ReduceAppCount(); + break; + case APPLICATION_CLOSED_FOR_CANCELED: + ReduceAppCount(); + break; + default: + break; + } + return E_PRINT_NONE; +} + +void PrintServiceAbility::UnloadSystemAbility() +{ + PRINT_HILOGI("delay unload task begin"); + auto unloadTask = [this]() { + PRINT_HILOGI("do unload tsak"); + if (printAppCount_ != 0) { + PRINT_HILOGE("There are still print jobs being executed."); + return; + } +#ifdef CUPS_ENABLE + DelayedSingleton::GetInstance()->StopCupsdService(); +#endif // CUPS_ENABLE + int32_t ret = DestroyExtension(); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("DestroyExtension failed."); + return; + } + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + PRINT_HILOGE("get samgr failed"); + return; + } + ret = samgrProxy->UnloadSystemAbility(PRINT_SERVICE_ID); + if (ret != ERR_OK) { + PRINT_HILOGE("unload print system ability failed"); + return; + } + PRINT_HILOGI("unload print system ability successfully"); + }; + serviceHandler_->PostTask(unloadTask, UNLOAD_SA_INTERVAL_10000); +} + bool PrintServiceAbility::CheckPermission(const std::string &permissionName) { if (helper_ == nullptr) { @@ -1245,6 +1999,49 @@ bool PrintServiceAbility::CheckPermission(const std::string &permissionName) return helper_->CheckPermission(permissionName); } +int32_t PrintServiceAbility::RegisterPrinterCallback(const std::string &type, const sptr &listener) +{ + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + if (listener == nullptr) { + PRINT_HILOGE("Invalid listener"); + return E_PRINT_INVALID_PARAMETER; + } + int64_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + std::lock_guard lock(apiMutex_); + auto iter = printUserDataMap_.find(callerTokenId); + if (iter == printUserDataMap_.end() || iter->second == nullptr) { + PRINT_HILOGE("Invalid token"); + return E_PRINT_INVALID_TOKEN; + } + iter->second->RegisterPrinterCallback(type, listener); + PRINT_HILOGD("PrintServiceAbility::RegisterPrinterCallback end."); + return E_PRINT_NONE; +} + +int32_t PrintServiceAbility::UnregisterPrinterCallback(const std::string &type) +{ + if (!CheckPermission(PERMISSION_NAME_PRINT)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + int64_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + std::lock_guard lock(apiMutex_); + auto iter = printUserDataMap_.find(callerTokenId); + if (iter == printUserDataMap_.end() || iter->second == nullptr) { + PRINT_HILOGE("Invalid token"); + return E_PRINT_INVALID_TOKEN; + } + iter->second->UnregisterPrinterCallback(type); + PRINT_HILOGD("PrintServiceAbility::UnregisterPrinterCallback end."); + if (type == PRINTER_CHANGE_EVENT_TYPE) { + ReduceAppCount(); + } + return E_PRINT_NONE; +} + int32_t PrintServiceAbility::RegisterExtCallback(const std::string &extensionCID, const sptr &listener) { @@ -1348,6 +2145,7 @@ int32_t PrintServiceAbility::LoadExtSuccess(const std::string &extensionId) int32_t PrintServiceAbility::On(const std::string taskId, const std::string &type, const sptr &listener) { + ManualStart(); std::string permission = PERMISSION_NAME_PRINT_JOB; std::string eventType = type; if (taskId != "") { @@ -1360,6 +2158,11 @@ int32_t PrintServiceAbility::On(const std::string taskId, const std::string &typ eventType = type; } + if (type == PRINTER_CHANGE_EVENT_TYPE) { + int64_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + eventType = PrintUtils::GetEventTypeWithToken(callerTokenId, type); + } + if (!CheckPermission(permission)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; @@ -1383,6 +2186,15 @@ int32_t PrintServiceAbility::On(const std::string taskId, const std::string &typ PRINT_HILOGD("PrintServiceAbility::On Replace listener."); registeredListeners_[eventType] = listener; } + std::string callerPkg = DelayedSingleton::GetInstance()->QueryCallerBundleName(); + PRINT_HILOGD("PrintServiceAbility::On started. callerPkg=%{public}s", callerPkg.c_str()); + if (PrintUtils::GetEventType(eventType) == PRINTER_CHANGE_EVENT_TYPE && callerPkg == PCSETTINGS_BUNDLE_NAME) { + PRINT_HILOGD("enter PCSettings, StartDiscoverPrinter"); + std::vector extensionInfos; + QueryAllExtension(extensionInfos); + std::vector extensionIds; + StartDiscoverPrinter(extensionIds); + } PRINT_HILOGD("PrintServiceAbility::On end."); return E_PRINT_NONE; } @@ -1395,6 +2207,10 @@ int32_t PrintServiceAbility::Off(const std::string taskId, const std::string &ty permission = PERMISSION_NAME_PRINT; eventType = PrintUtils::GetTaskEventId(taskId, type); } + if (type == PRINTER_CHANGE_EVENT_TYPE) { + int64_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + eventType = PrintUtils::GetEventTypeWithToken(callerTokenId, type); + } if (!CheckPermission(permission)) { PRINT_HILOGE("no permission to access print service"); return E_PRINT_NO_PERMISSION; @@ -1424,35 +2240,6 @@ bool PrintServiceAbility::StartAbility(const AAFwk::Want &want) return helper_->StartAbility(want); } -bool PrintServiceAbility::KillAbility(const std::string bundleName) -{ - if (helper_ == nullptr) { - return false; - } - return helper_->KillAbility(bundleName); -} - -void PrintServiceAbility::KillAllAbility() -{ - std::vector extensionInfo; - if (!DelayedSingleton::GetInstance()->QueryExtensionInfos(extensionInfo)) { - PRINT_HILOGE("Failed to query extension"); - } - - for (auto extInfo : extensionInfo) { - KillAbility(extInfo.bundleName.c_str()); - } -} - -bool PrintServiceAbility::StartPrintServiceExtension(const AAFwk::Want &want, int32_t curRequestCode_) -{ - if (helper_ == nullptr) { - return false; - } - PRINT_HILOGI("StartPrintServiceExtension curRequestCode_ [%{public}d]", curRequestCode_); - return helper_->StartPrintServiceExtension(want, curRequestCode_); -} - PrintExtensionInfo PrintServiceAbility::ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo &extInfo) { PrintExtensionInfo printExtInfo; @@ -1464,6 +2251,27 @@ PrintExtensionInfo PrintServiceAbility::ConvertToPrintExtensionInfo(const AppExe return printExtInfo; } +void PrintServiceAbility::SendPrinterDiscoverEvent(int event, const PrinterInfo &info) +{ + PRINT_HILOGD("PrintServiceAbility::SendPrinterDiscoverEvent type %{private}s, %{public}d", + info.GetPrinterId().c_str(), event); + for (auto &item : printUserDataMap_) { + if (item.second != nullptr) { + item.second->SendPrinterEvent(PRINTER_DISCOVER_EVENT_TYPE, event, info); + } + } +} + +void PrintServiceAbility::SendPrinterChangeEvent(int event, const PrinterInfo &info) +{ + PRINT_HILOGD("PrintServiceAbility::SendPrinterChangeEvent type %{private}s, %{public}d", + info.GetPrinterId().c_str(), event); + for (auto &item : printUserDataMap_) { + if (item.second != nullptr) { + item.second->SendPrinterEvent(PRINTER_CHANGE_EVENT_TYPE, event, info); + } + } +} void PrintServiceAbility::SendPrinterEvent(const PrinterInfo &info) { PRINT_HILOGD("PrintServiceAbility::SendPrinterEvent type %{private}s, %{public}d", @@ -1474,6 +2282,18 @@ void PrintServiceAbility::SendPrinterEvent(const PrinterInfo &info) } } +void PrintServiceAbility::SendPrinterEventChangeEvent(PrinterEvent printerEvent, const PrinterInfo &info) +{ + PRINT_HILOGD("PrintServiceAbility::SendPrinterEventChangeEvent printerId: %{public}s, printerEvent: %{public}d", + info.GetPrinterId().c_str(), printerEvent); + for (auto eventIt: registeredListeners_) { + if (PrintUtils::GetEventType(eventIt.first) == PRINTER_CHANGE_EVENT_TYPE && eventIt.second != nullptr) { + PRINT_HILOGD("PrintServiceAbility::SendPrinterEventChangeEvent find PRINTER_CHANGE_EVENT_TYPE"); + eventIt.second->OnCallback(printerEvent, info); + } + } +} + void PrintServiceAbility::SendPrintJobEvent(const PrintJob &jobInfo) { PRINT_HILOGD("PrintServiceAbility::SendPrintJobEvent jobId: %{public}s, state: %{public}d, subState: %{public}d", @@ -1553,13 +2373,20 @@ void PrintServiceAbility::CheckJobQueueBlocked(const PrintJob &jobInfo) if (!isJobQueueBlocked_ && jobInfo.GetJobState() == PRINT_JOB_BLOCKED) { // going blocked isJobQueueBlocked_ = true; - NotifyAppJobQueueChanged(QUEUE_JOB_LIST_BLOCKED); + if (GetUserIdByJobId(jobInfo.GetJobId()) == currentUserId_) { + NotifyAppJobQueueChanged(QUEUE_JOB_LIST_BLOCKED); + } } if (isJobQueueBlocked_ && jobInfo.GetJobState() != PRINT_JOB_BLOCKED) { bool hasJobBlocked = false; - for (auto printJob : queuedJobList_) { - if (printJob.second -> GetJobState() == PRINT_JOB_BLOCKED) { + auto userData = GetUserDataByJobId(jobInfo.GetJobId()); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return; + } + for (auto printJob : userData->queuedJobList_) { + if (printJob.second->GetJobState() == PRINT_JOB_BLOCKED) { hasJobBlocked = true; break; } @@ -1567,14 +2394,16 @@ void PrintServiceAbility::CheckJobQueueBlocked(const PrintJob &jobInfo) if (!hasJobBlocked) { // clear blocked isJobQueueBlocked_ = false; - NotifyAppJobQueueChanged(QUEUE_JOB_LIST_CLEAR_BLOCKED); + if (GetUserIdByJobId(jobInfo.GetJobId()) == currentUserId_) { + NotifyAppJobQueueChanged(QUEUE_JOB_LIST_CLEAR_BLOCKED); + } } } PRINT_HILOGD("CheckJobQueueBlocked end,isJobQueueBlocked_=%{public}s", isJobQueueBlocked_ ? "true" : "false"); } int32_t PrintServiceAbility::PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes, - std::string &taskId, const sptr &token) + std::string &taskId) { ManualStart(); if (!CheckPermission(PERMISSION_NAME_PRINT)) { @@ -1582,18 +2411,12 @@ int32_t PrintServiceAbility::PrintByAdapter(const std::string jobName, const Pri return E_PRINT_NO_PERMISSION; } PRINT_HILOGI("PrintServiceAbility::PrintByAdapter start"); - // 拉起打印预览页面 + std::vector fileList; std::vector fdList; - std::shared_ptr adapterParam = std::make_shared(); - adapterParam->documentName = jobName; - adapterParam->isCheckFdList = false; - adapterParam->printAttributes = printAttributes; - int32_t ret = E_PRINT_NONE; - if (token == nullptr) { - ret = CallSpooler(fileList, fdList, taskId, adapterParam); - } else { - ret = CallSpooler(fileList, fdList, taskId, token, adapterParam); + int32_t ret = CallSpooler(fileList, fdList, taskId); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("PrintServiceAbility::PrintByAdapter CallSpooler failed, ret: %{public}d", ret); } PRINT_HILOGI("PrintServiceAbility::PrintByAdapter end"); return ret; @@ -1639,17 +2462,28 @@ int32_t PrintServiceAbility::NotifyPrintService(const std::string &jobId, const if (type == "0" || type == NOTIFY_INFO_SPOOLER_CLOSED_FOR_STARTED) { PRINT_HILOGI("Notify Spooler Closed for started jobId : %{public}s", jobId.c_str()); notifyAdapterJobChanged(jobId, PRINT_JOB_SPOOLER_CLOSED, PRINT_JOB_SPOOLER_CLOSED_FOR_STARTED); + ReduceAppCount(); return E_PRINT_NONE; } if (type == NOTIFY_INFO_SPOOLER_CLOSED_FOR_CANCELLED) { PRINT_HILOGI("Notify Spooler Closed for canceled jobId : %{public}s", jobId.c_str()); notifyAdapterJobChanged(jobId, PRINT_JOB_SPOOLER_CLOSED, PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED); + ReduceAppCount(); return E_PRINT_NONE; } return E_PRINT_INVALID_PARAMETER; } +void PrintServiceAbility::ReduceAppCount() +{ + printAppCount_ = printAppCount_ >= 1 ? printAppCount_ - 1 : 0; + PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_); + if (printAppCount_ == 0 && queuedJobList_.size() == 0) { + UnloadSystemAbility(); + } +} + void PrintServiceAbility::notifyAdapterJobChanged(const std::string jobId, const uint32_t state, const uint32_t subState) { @@ -1699,110 +2533,266 @@ void PrintServiceAbility::notifyAdapterJobChanged(const std::string jobId, const } } -void PrintServiceAbility::CreateDefaultAdapterParam(const std::shared_ptr &adapterParam) +int32_t PrintServiceAbility::CallStatusBar() { - adapterParam->documentName = ""; - adapterParam->isCheckFdList = true; + PRINT_HILOGI("PrintServiceAbility CallStatusBar enter."); + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT) && !CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION); + return E_PRINT_NO_PERMISSION; + } + std::lock_guard lock(apiMutex_); + AAFwk::Want want; + want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_STATUS_BAR_ABILITY_NAME); + int32_t callerTokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + std::string callerPkg = SPOOLER_PACKAGE_NAME; + ingressPackage = callerPkg; + int32_t callerUid = IPCSkeleton::GetCallingUid(); + int32_t callerPid = IPCSkeleton::GetCallingPid(); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid); + want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid); + want.SetParam(CALLER_PKG_NAME, callerPkg); + if (!StartPluginPrintIconExtAbility(want)) { + PRINT_HILOGE("Failed to start PluginPrintIconExtAbility"); + return E_PRINT_SERVER_FAILURE; + } + return E_PRINT_NONE; } -void PrintServiceAbility::BuildAdapterParam(const std::shared_ptr &adapterParam, - AAFwk::Want &want, const std::string &jobId) +bool PrintServiceAbility::StartPluginPrintIconExtAbility(const AAFwk::Want &want) { - want.SetParam(LAUNCH_PARAMETER_DOCUMENT_NAME, adapterParam->documentName); - if (adapterParam->isCheckFdList) { - std::string defaultAttribute = ""; - want.SetParam(LAUNCH_PARAMETER_PRINT_ATTRIBUTE, defaultAttribute); + if (helper_ == nullptr) { + PRINT_HILOGE("Invalid print service helper."); + return false; + } + PRINT_HILOGI("enter PrintServiceAbility::StartPluginPrintIconExtAbility"); + return helper_->StartPluginPrintIconExtAbility(want); +} + +std::shared_ptr PrintServiceAbility::GetCurrentUserData() +{ + int32_t userId = GetCurrentUserId(); + if (userId == E_PRINT_INVALID_USERID) { + PRINT_HILOGE("Invalid user id."); + return nullptr; + } + auto iter = printUserMap_.find(userId); + if (iter == printUserMap_.end()) { + PRINT_HILOGE("Current user is not added, add it."); + UpdatePrintUserMap(); + iter = printUserMap_.find(userId); + if (iter == printUserMap_.end()) { + PRINT_HILOGE("add user failed."); + return nullptr; + } + } + return iter->second; +} + +int32_t PrintServiceAbility::GetCurrentUserId() +{ + int32_t userId = IPCSkeleton::GetCallingUid() / UID_TRANSFORM_DIVISOR; + PRINT_HILOGI("Current userId = %{public}d", userId); + if (userId < START_USER_ID) { + PRINT_HILOGE("id %{public}d is system reserved", userId); + return E_PRINT_INVALID_USERID; + } + if (userId > MAX_USER_ID) { + PRINT_HILOGE("id %{public}d is out of range", userId); + return E_PRINT_INVALID_USERID; + } + return userId; +} + +std::shared_ptr PrintServiceAbility::GetUserDataByJobId(const std::string jobId) +{ + int32_t userId = GetUserIdByJobId(jobId); + PRINT_HILOGI("the job is belong to user-%{public}d.", userId); + if (userId == E_PRINT_INVALID_PRINTJOB) { + PRINT_HILOGE("Invalid job id."); + return nullptr; + } + auto iter = printUserMap_.find(userId); + if (iter == printUserMap_.end()) { + PRINT_HILOGE("Current user is not added."); + UpdatePrintUserMap(); + iter = printUserMap_.find(userId); + if (iter == printUserMap_.end()) { + PRINT_HILOGE("add user failed."); + return nullptr; + } + } + return iter->second; +} + +int32_t PrintServiceAbility::GetUserIdByJobId(const std::string jobId) +{ + for (std::map::iterator it = userJobMap_.begin(); it != userJobMap_.end(); + ++it) { + PRINT_HILOGI("jobId: %{public}s, userId: %{public}d.", it->first.c_str(), it->second); + } + auto iter = userJobMap_.find(jobId); + if (iter == userJobMap_.end()) { + PRINT_HILOGE("Invalid job id."); + return E_PRINT_INVALID_PRINTJOB; + } + return iter->second; +} + +void PrintServiceAbility::UpdatePrintUserMap() +{ + int32_t userId = GetCurrentUserId(); + if (userId == E_PRINT_INVALID_USERID) { + PRINT_HILOGE("Invalid user id."); return; } + PRINT_HILOGI("new user id: %{public}d.", userId); + currentUserId_ = userId; + auto iter = printUserMap_.find(userId); + if (iter == printUserMap_.end()) { + auto userData = std::make_shared(); + if (userData != nullptr) { + printUserMap_.insert(std::make_pair(userId, userData)); + userData->SetUserId(userId); + userData->ParseUserData(); + PRINT_HILOGI("add user success"); + } + } +} - PRINT_HILOGI("BuildAdapterParam for jobId %{public}s", jobId.c_str()); +void PrintServiceAbility::AddToPrintJobList(const std::string jobId, const std::shared_ptr &printjob) +{ + PRINT_HILOGD("begin AddToPrintJobList."); + UpdatePrintUserMap(); + printJobList_.insert(std::make_pair(jobId, printjob)); + for (auto printjob : printJobList_) { + PRINT_HILOGI("printjob in printJobList_, jobId: %{public}s.", printjob.first.c_str()); + } + int32_t userId = GetCurrentUserId(); + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return; + } + userJobMap_.insert(std::make_pair(jobId, userId)); + userData->AddToPrintJobList(jobId, printjob); +} + +void PrintServiceAbility::RegisterAdapterListener(const std::string &jobId) +{ + PRINT_HILOGD("RegisterAdapterListener for jobId %{public}s", jobId.c_str()); auto eventIt = registeredListeners_.find(PRINT_ADAPTER_EVENT_TYPE); if (eventIt != registeredListeners_.end()) { PRINT_HILOGI("adapterListenersByJobId_ set adapterListenersByJobId_ %{public}s", jobId.c_str()); adapterListenersByJobId_.insert(std::make_pair(jobId, eventIt->second)); } - want.SetParam(LAUNCH_PARAMETER_DOCUMENT_NAME, adapterParam->documentName); - BuildPrintAttributesParam(adapterParam, want); } -void PrintServiceAbility::BuildPrintAttributesParam(const std::shared_ptr &adapterParam, - AAFwk::Want &want) +int32_t PrintServiceAbility::SetDefaultPrinter(const std::string &printerId) { - json attrJson; - PrintAttributes attrParam = adapterParam->printAttributes; - if (attrParam.HasCopyNumber()) { - attrJson["copyNumber"] = attrParam.GetCopyNumber(); + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; } - if (attrParam.HasSequential()) { - attrJson["isSequential"] = attrParam.GetIsSequential(); + PRINT_HILOGD("SetDefaultPrinter started."); + std::lock_guard lock(apiMutex_); + + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return E_PRINT_INVALID_USERID; } - if (attrParam.HasLandscape()) { - attrJson["isLandscape"] = attrParam.GetIsLandscape(); + int32_t ret = userData->SetDefaultPrinter(printerId); + if (ret != E_PRINT_NONE) { + PRINT_HILOGE("SetDefaultPrinter failed."); + return ret; } - if (attrParam.HasDirectionMode()) { - attrJson["directionMode"] = attrParam.GetDirectionMode(); - } - if (attrParam.HasColorMode()) { - attrJson["colorMode"] = attrParam.GetColorMode(); - } - if (attrParam.HasDuplexMode()) { - attrJson["duplexMode"] = attrParam.GetDuplexMode(); - } - ParseAttributesObjectParamForJson(attrParam, attrJson); - if (attrParam.HasOption()) { - attrJson["options"] = attrParam.GetOption(); - } - want.SetParam(LAUNCH_PARAMETER_PRINT_ATTRIBUTE, attrJson.dump()); - PRINT_HILOGD("CallSpooler set printAttributes: %{public}s", attrJson.dump().c_str()); + return E_PRINT_NONE; } -void PrintServiceAbility::ParseAttributesObjectParamForJson( - const PrintAttributes &attrParam, nlohmann::json &attrJson) +bool PrintServiceAbility::CheckIsDefaultPrinter(const std::string &printerId) { - if (attrParam.HasPageRange()) { - json pageRangeJson; - PrintRange printRangeAttr; - attrParam.GetPageRange(printRangeAttr); - if (printRangeAttr.HasStartPage()) { - pageRangeJson["startPage"] = printRangeAttr.GetStartPage(); - } - if (printRangeAttr.HasEndPage()) { - pageRangeJson["endPage"] = printRangeAttr.GetEndPage(); - } - if (printRangeAttr.HasPages()) { - std::vector pages; - printRangeAttr.GetPages(pages); - pageRangeJson["pages"] = pages; - } - attrJson["pageRange"] = pageRangeJson; + std::lock_guard lock(apiMutex_); + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return false; } - if (attrParam.HasPageSize()) { - json pageSizeJson; - PrintPageSize pageSizeAttr; - attrParam.GetPageSize(pageSizeAttr); - pageSizeJson["id"] = pageSizeAttr.GetId(); - pageSizeJson["name"] = pageSizeAttr.GetName(); - pageSizeJson["width"] = pageSizeAttr.GetWidth(); - pageSizeJson["height"] = pageSizeAttr.GetHeight(); - attrJson["pageSize"] = pageSizeJson; + if (printerId != userData->GetDefaultPrinter()) { + return false; } - if (attrParam.HasMargin()) { - json marginJson; - PrintMargin marginAttr; - attrParam.GetMargin(marginAttr); - if (marginAttr.HasTop()) { - marginJson["top"] = marginAttr.GetTop(); + return true; +} + +bool PrintServiceAbility::CheckIsLastUsedPrinter(const std::string &printerId) +{ + std::lock_guard lock(apiMutex_); + auto userData = GetCurrentUserData(); + if (userData == nullptr) { + PRINT_HILOGE("Get user data failed."); + return false; + } + if (printerId != userData->GetLastUsedPrinter()) { + return false; + } + return true; +} + +int32_t PrintServiceAbility::DeletePrinterFromCups( + const std::string &printerUri, const std::string &printerName, const std::string &printerMake) +{ + ManualStart(); + if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) { + PRINT_HILOGE("no permission to access print service"); + return E_PRINT_NO_PERMISSION; + } + PRINT_HILOGD("DeletePrinterFromCups started."); + std::lock_guard lock(apiMutex_); +#ifdef CUPS_ENABLE + auto ret = + DelayedSingleton::GetInstance()->DeletePrinterFromCups(printerUri, printerName, printerMake); + if (ret != E_PRINT_NONE) { + PRINT_HILOGW("DeletePrinterFromCups error = %{public}d.", ret); + return ret; + } +#endif // CUPS_ENABLE + DeletePrinterFromSystemData(printerName); + return E_PRINT_NONE; +} + +void PrintServiceAbility::DeletePrinterFromSystemData(const std::string &printerName) +{ + PRINT_HILOGD("DeletePrinterFromSystemData printerName %{public}s.", printerName.c_str()); + for (auto iter = printerInfoList_.begin(); iter != printerInfoList_.end(); ++iter) { + auto printerInfoPtr = iter->second; + if (printerInfoPtr == nullptr) { + continue; } - if (marginAttr.HasBottom()) { - marginJson["bottom"] = marginAttr.GetBottom(); + std::string stdName = PrintUtil::StandardizePrinterName(printerInfoPtr->GetPrinterName()); + PRINT_HILOGD("DeletePrinterFromSystemData stdName %{public}s.", stdName.c_str()); + if (stdName != printerName) { + continue; } - if (marginAttr.HasLeft()) { - marginJson["left"] = marginAttr.GetLeft(); + std::string id = iter->first; + printSystemData_.DeleteCupsPrinter(id); + printerInfoList_.erase(id); + SendPrinterEventChangeEvent(PRINTER_EVENT_DELETED, *printerInfoPtr); + DeletePrinterFromUserData(id); + return; + } +} + +void PrintServiceAbility::DeletePrinterFromUserData(const std::string &printerId) +{ + for (auto user: printUserMap_) { + std::string temp = user.second->GetDefaultPrinter(); + PRINT_HILOGI("DeletePrinterFromSystemData temp %{public}s.", temp.c_str()); + if (printerId == temp) { + PRINT_HILOGI("DeletePrinterFromSystemData userId %{public}d.", user.first); + user.second->SetDefaultPrinter(""); } - if (marginAttr.HasRight()) { - marginJson["right"] = marginAttr.GetRight(); - } - attrJson["margin"] = marginJson; } } } // namespace OHOS::Print diff --git a/services/print_service/src/print_service_converter.cpp b/services/print_service/src/print_service_converter.cpp new file mode 100644 index 0000000..5617acb --- /dev/null +++ b/services/print_service/src/print_service_converter.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_service_converter.h" +#include "print_log.h" + +namespace OHOS { +namespace Print { +std::string GetQulityString(int code) +{ + return std::to_string(code); +} + +bool ConvertColorModeCode(const char *src, ColorModeCode &dst) +{ + if (src == nullptr) { + return false; + } + if (strcasestr(src, "color")) { + dst = COLOR_MODE_COLOR; + } else if (strcasestr(src, "monochrome")) { + dst = COLOR_MODE_MONOCHROME; + } else if (strcasestr(src, "auto")) { + dst = COLOR_MODE_AUTO; + } else { + return false; + } + return true; +} + +bool ConvertColorModeToJson(const ColorModeCode &code, nlohmann::json &jsonObject) +{ + jsonObject["color"] = std::to_string(static_cast(code)); + return true; +} + +bool ConvertDuplexModeToJson(const DuplexModeCode &code, nlohmann::json &jsonObject) +{ + jsonObject["duplex"] = std::to_string(static_cast(code)); + return true; +} + +bool ConvertPageSizeId(const char *src, std::string &id) +{ + if (src == nullptr) { + return false; + } + std::string pageString(src); + id = PrintPageSize::MatchPageSize(pageString); + return !id.empty(); +} + +bool ConvertPrintPageSize(const char *src, PrintPageSize &dst) +{ + std::string id; + if (ConvertPageSizeId(src, id)) { + return PrintPageSize::FindPageSizeById(id, dst); + } + return false; +} + +bool ConvertPageSizeToJson(const PrintPageSize &pageSize, nlohmann::json &jsonObject) +{ + jsonObject["id"] = pageSize.GetId(); + jsonObject["name"] = pageSize.GetName(); + jsonObject["width"] = pageSize.GetWidth(); + jsonObject["height"] = pageSize.GetHeight(); + return true; +} +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/services/print_service/src/print_service_helper.cpp b/services/print_service/src/print_service_helper.cpp index 68d39de..912b3f8 100644 --- a/services/print_service/src/print_service_helper.cpp +++ b/services/print_service/src/print_service_helper.cpp @@ -22,6 +22,9 @@ #include "print_constant.h" #include "print_log.h" #include "system_ability_definition.h" +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_support.h" namespace OHOS::Print { const uint32_t MAX_RETRY_TIMES = 3; @@ -42,6 +45,9 @@ bool PrintServiceHelper::CheckPermission(const std::string &name) } int result = AccessTokenKit::VerifyAccessToken(tokenId, name); if (result != PERMISSION_GRANTED) { + if (name == PERMISSION_NAME_PRINT) { + result = AccessTokenKit::VerifyAccessToken(tokenId, PERMISSION_NAME_PRINT_JOB); + } PRINT_HILOGE("Current tokenId permission is %{public}d", result); } return result == PERMISSION_GRANTED; @@ -68,35 +74,31 @@ bool PrintServiceHelper::StartAbility(const AAFwk::Want &want) return true; } -bool PrintServiceHelper::KillAbility(const std::string &bundleName) -{ - for (uint32_t retry = 0; retry < MAX_RETRY_TIMES; ++retry) { - if (AAFwk::AbilityManagerClient::GetInstance()->KillProcess(bundleName) == ERR_OK) { - return true; - } - PRINT_HILOGD("PrintServiceHelper::KillAbility %{public}d %{public}s", - retry, bundleName.c_str()); - } - PRINT_HILOGE("PrintServiceHelper::KillAbility %{public}s failed", bundleName.c_str()); - return false; -} - -bool PrintServiceHelper::StartPrintServiceExtension(const AAFwk::Want &want, int32_t requestCode_) +bool PrintServiceHelper::StartPluginPrintIconExtAbility(const AAFwk::Want &want) { + PRINT_HILOGD("enter PrintServiceHelper::StartPluginPrintIconExtAbility"); + PRINT_HILOGD("want: %{public}s", want.ToUri().c_str()); AppExecFwk::ElementName element = want.GetElement(); AAFwk::AbilityManagerClient::GetInstance()->Connect(); uint32_t retry = 0; + sptr printAbilityConnection = new (std::nothrow) PrintAbilityConnection(); + if (printAbilityConnection == nullptr) { + PRINT_HILOGE("fail to create printAbilityConnection"); + return false; + } + PRINT_HILOGD("PrintServiceHelper::StartPluginPrintIconExtAbility %{public}s %{public}s", + element.GetBundleName().c_str(), + element.GetAbilityName().c_str()); while (retry++ < MAX_RETRY_TIMES) { - PRINT_HILOGD("PrintServiceHelper::StartPrintServiceExtension %{public}s %{public}s", - element.GetBundleName().c_str(), element.GetAbilityName().c_str()); - if (AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, requestCode_) == 0) { + if (AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, printAbilityConnection, -1) == 0) { + PRINT_HILOGI("PrintServiceHelper::StartPluginPrintIconExtAbility ConnectAbility success"); break; } std::this_thread::sleep_for(std::chrono::seconds(START_ABILITY_INTERVAL)); - PRINT_HILOGD("PrintServiceHelper::StartPrintServiceExtension %{public}d", retry); + PRINT_HILOGE("PrintServiceHelper::StartPluginPrintIconExtAbility %{public}d", retry); } if (retry > MAX_RETRY_TIMES) { - PRINT_HILOGE("PrintServiceHelper::StartPrintServiceExtension --> failed "); + PRINT_HILOGE("PrintServiceHelper::StartPluginPrintIconExtAbility --> failed "); return false; } return true; @@ -151,4 +153,27 @@ bool PrintServiceHelper::IsSyncMode() { return false; } + +void PrintServiceHelper::PrintSubscribeCommonEvent() +{ + if (isSubscribeCommonEvent) { + return; + } + isSubscribeCommonEvent = true; + PRINT_HILOGI("listen user status."); + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); + + userStatusListener = std::make_shared(subscribeInfo); + if (userStatusListener == nullptr) { + PRINT_HILOGE("create userStatusListener failed."); + return; + } + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(userStatusListener)) { + PRINT_HILOGE("subscribe common event failed"); + } +} } // namespace OHOS diff --git a/services/print_service/src/print_service_stub.cpp b/services/print_service/src/print_service_stub.cpp index e38a6f1..081cba1 100644 --- a/services/print_service/src/print_service_stub.cpp +++ b/services/print_service/src/print_service_stub.cpp @@ -40,10 +40,12 @@ PrintServiceStub::PrintServiceStub() cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_REMOVEPRINTERS] = &PrintServiceStub::OnRemovePrinters; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTERS] = &PrintServiceStub::OnUpdatePrinters; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTERSTATE] = &PrintServiceStub::OnUpdatePrinterState; - cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTJOBSTATE] = &PrintServiceStub::OnUpdatePrintJobState; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTJOBSTATE] = + &PrintServiceStub::OnUpdatePrintJobStateOnlyForSystemApp; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UPDATEEXTENSIONINFO] = &PrintServiceStub::OnUpdateExtensionInfo; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_REQUESTPREVIEW] = &PrintServiceStub::OnRequestPreview; - cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_QUERYPRINTERCAPABILITY] = &PrintServiceStub::OnQueryPrinterCapability; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_QUERYPRINTERCAPABILITY] = + &PrintServiceStub::OnQueryPrinterCapability; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_ON] = &PrintServiceStub::OnEventOn; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_OFF] = &PrintServiceStub::OnEventOff; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_REG_EXT_CB] = &PrintServiceStub::OnRegisterExtCallback; @@ -57,6 +59,24 @@ PrintServiceStub::PrintServiceStub() cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_STARTPRINTJOB_BY_ADAPTER] = &PrintServiceStub::OnPrintByAdapter; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_START_GET_FILE] = &PrintServiceStub::OnStartGetPrintFile; cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_NOTIFY_PRINT_SERVICE] = &PrintServiceStub::OnNotifyPrintService; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_START_SERVICE] = &PrintServiceStub::OnStartService; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_REG_PRINTER_CB] = &PrintServiceStub::OnRegisterPrinterCallback; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UNREG_PRINTER_CB] = &PrintServiceStub::OnUnregisterPrinterCallback; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_QUERYPRINTERINFOBYPRINTERID] = + &PrintServiceStub::OnQueryPrinterInfoByPrinterId; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_QUERYADDEDPRINTER] = &PrintServiceStub::OnQueryAddedPrinter; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_QUERYPRINTERPROPERTIES] = + &PrintServiceStub::OnQueryPrinterProperties; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_STARTNATIVEPRINTJOB] = &PrintServiceStub::OnStartNativePrintJob; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_NOTIFY_PRINT_SERVICE_EVENT] = + &PrintServiceStub::OnNotifyPrintServiceEvent; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_GET_PRINTER_PREFERENCE] = + &PrintServiceStub::OnGetPrinterPreference; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_SET_PRINTER_PREFERENCE] = + &PrintServiceStub::OnSetPrinterPreference; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_SET_DEFAULT_PRINTERID] = &PrintServiceStub::OnSetDefaultPrinter; + cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_DELETE_PRINTER_FROM_CUPS] = + &PrintServiceStub::OnDeletePrinterFromCups; } int32_t PrintServiceStub::OnRemoteRequest( @@ -80,6 +100,19 @@ int32_t PrintServiceStub::OnRemoteRequest( return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } +bool PrintServiceStub::OnStartService(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGD("nativePrint PrintServiceStub::OnStartService in"); + int32_t ret = E_PRINT_NONE; + if (data.ReadString() == "nativePrint") { + std::string result = ""; + ret = StartService(); + reply.WriteInt32(ret); + PRINT_HILOGI("nativePrint PrintServiceStub::OnStartService out:%{public}d", ret); + } + return ret == E_PRINT_NONE; +} + bool PrintServiceStub::OnStartPrint(MessageParcel &data, MessageParcel &reply) { PRINT_HILOGD("PrintServiceStub::OnStartPrint in"); @@ -105,17 +138,9 @@ bool PrintServiceStub::OnStartPrint(MessageParcel &data, MessageParcel &reply) fdList.emplace_back(fd); } } - - sptr token = data.ReadRemoteObject(); - PRINT_HILOGI("OnStartPrint read token %{public}s", token != nullptr ? "success" : "failed"); - int32_t ret = E_PRINT_NONE; - if (token == nullptr) { - ret = StartPrint(fileList, fdList, result); - } else { - ret = StartPrint(fileList, fdList, result, token); - } + std::string taskId = data.ReadString(); + int32_t ret = StartPrint(fileList, fdList, taskId); reply.WriteInt32(ret); - reply.WriteString(result); PRINT_HILOGD("PrintServiceStub::OnStartPrint out"); return ret == E_PRINT_NONE; } @@ -212,7 +237,11 @@ bool PrintServiceStub::OnAddPrinters(MessageParcel &data, MessageParcel &reply) { PRINT_HILOGD("PrintServiceStub::OnAddPrinters in"); std::vector printerInfos; - uint32_t len = data.ReadUint32(); + uint32_t len = 0; + if (!data.ReadUint32(len)) { + PRINT_HILOGE("read data len failed."); + return false; + } PRINT_HILOGD("OnStartDiscoverPrinter len = %{public}d", len); CHECK_IS_EXCEED_PRINT_RANGE_BOOL(len); @@ -234,6 +263,81 @@ bool PrintServiceStub::OnAddPrinters(MessageParcel &data, MessageParcel &reply) return ret == E_PRINT_NONE; } +bool PrintServiceStub::OnQueryPrinterInfoByPrinterId(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGD("PrintServiceStub::OnQueryPrinterInfoByPrinterId in"); + std::string printerId = data.ReadString(); + PrinterInfo info; + int32_t ret = QueryPrinterInfoByPrinterId(printerId, info); + reply.WriteInt32(ret); + PRINT_HILOGI("PrintServiceStub::OnQueryPrinterInfoByPrinterId out %{public}s", info.GetPrinterName().c_str()); + info.Marshalling(reply); + PRINT_HILOGI("PrintServiceStub::OnQueryPrinterInfoByPrinterId out"); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnGetPrinterPreference(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGD("PrintServiceStub::OnGetPrinterPreference in"); + std::string printerId = data.ReadString(); + std::string printPreference; + int32_t ret = GetPrinterPreference(printerId, printPreference); + reply.WriteInt32(ret); + reply.WriteString(printPreference); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnSetPrinterPreference(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGI("PrintServiceStub::OnSetPrinterPreference in"); + std::string printerId = data.ReadString(); + std::string printPreference = data.ReadString(); + int32_t ret = SetPrinterPreference(printerId, printPreference); + reply.WriteInt32(ret); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnQueryAddedPrinter(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGI("PrintServiceStub::OnQueryAddedPrinter in"); + std::vector printerNameList; + + int32_t ret = QueryAddedPrinter(printerNameList); + reply.WriteInt32(ret); + reply.WriteStringVector(printerNameList); + + PRINT_HILOGI("PrintServiceStub::OnQueryAddedPrinter out"); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnQueryPrinterProperties(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGI("PrintServiceStub::OnQueryAddedPrinter in"); + std::string printerId = data.ReadString(); + std::vector keyList; + data.ReadStringVector(&keyList); + std::vector valueList; + int32_t ret = QueryPrinterProperties(printerId, keyList, valueList); + reply.WriteInt32(ret); + reply.WriteStringVector(valueList); + PRINT_HILOGI("PrintServiceStub::OnQueryAddedPrinter out"); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnStartNativePrintJob(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGI("PrintServiceStub::OnStartNativePrintJob in"); + int32_t ret = E_PRINT_RPC_FAILURE; + auto printJobPtr = PrintJob::Unmarshalling(data); + if (printJobPtr != nullptr) { + printJobPtr->Dump(); + ret = StartNativePrintJob(*printJobPtr); + } + reply.WriteInt32(ret); + PRINT_HILOGD("PrintServiceStub::OnStartPrintJob out"); + return ret == E_PRINT_NONE; +} + bool PrintServiceStub::OnRemovePrinters(MessageParcel &data, MessageParcel &reply) { PRINT_HILOGD("PrintServiceStub::OnRemovePrinters in"); @@ -253,8 +357,12 @@ bool PrintServiceStub::OnUpdatePrinters(MessageParcel &data, MessageParcel &repl { PRINT_HILOGD("PrintServiceStub::OnUpdatePrinters in"); std::vector printerInfos; - uint32_t len = data.ReadUint32(); - PRINT_HILOGD("OnStartDiscoverPrinter len = %{public}d", len); + uint32_t len = 0; + if (!data.ReadUint32(len)) { + PRINT_HILOGE("read data len failed."); + return false; + } + PRINT_HILOGD("OnUpdatePrinters len = %{public}d", len); CHECK_IS_EXCEED_PRINT_RANGE_BOOL(len); for (uint32_t i = 0; i < len; i++) { @@ -286,19 +394,19 @@ bool PrintServiceStub::OnUpdatePrinterState(MessageParcel &data, MessageParcel & return ret == E_PRINT_NONE; } -bool PrintServiceStub::OnUpdatePrintJobState(MessageParcel &data, MessageParcel &reply) +bool PrintServiceStub::OnUpdatePrintJobStateOnlyForSystemApp(MessageParcel &data, MessageParcel &reply) { - PRINT_HILOGD("PrintServiceStub::OnUpdatePrintJobState in"); + PRINT_HILOGD("PrintServiceStub::OnUpdatePrintJobStateOnlyForSystemApp in"); std::string jobId = data.ReadString(); uint32_t state = data.ReadUint32(); uint32_t subState = data.ReadUint32(); - PRINT_HILOGD("OnUpdatePrintJobState jobId = %{public}s", jobId.c_str()); - PRINT_HILOGD("OnUpdatePrintJobState state = %{public}d", state); - PRINT_HILOGD("OnUpdatePrintJobState subState = %{public}d", subState); + PRINT_HILOGD("OnUpdatePrintJobStateOnlyForSystemApp jobId = %{public}s", jobId.c_str()); + PRINT_HILOGD("OnUpdatePrintJobStateOnlyForSystemApp state = %{public}d", state); + PRINT_HILOGD("OnUpdatePrintJobStateOnlyForSystemApp subState = %{public}d", subState); - int32_t ret = UpdatePrintJobState(jobId, state, subState); + int32_t ret = UpdatePrintJobStateOnlyForSystemApp(jobId, state, subState); reply.WriteInt32(ret); - PRINT_HILOGD("PrintServiceStub::OnUpdatePrintJobState out"); + PRINT_HILOGD("PrintServiceStub::OnUpdatePrintJobStateOnlyForSystemApp out"); return ret == E_PRINT_NONE; } @@ -396,6 +504,40 @@ bool PrintServiceStub::OnQueryPrinterCapabilityByUri(MessageParcel &data, Messag return ret == E_PRINT_NONE; } +bool PrintServiceStub::OnNotifyPrintServiceEvent(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGD("PrintServiceStub::OnNotifyPrintServiceEvent in"); + std::string jobId = data.ReadString(); + uint32_t event = data.ReadUint32(); + PRINT_HILOGD("OnNotifyPrintServiceEvent jobId = %{public}s, event = %{public}d", jobId.c_str(), event); + int32_t ret = NotifyPrintServiceEvent(jobId, event); + reply.WriteInt32(ret); + PRINT_HILOGD("PrintServiceStub::OnNotifyPrintServiceEvent out"); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnSetDefaultPrinter(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGD("PrintServiceStub::OnSetDefaultPrinter in"); + std::string printerId = data.ReadString(); + int32_t ret = SetDefaultPrinter(printerId); + reply.WriteInt32(ret); + PRINT_HILOGD("PrintServiceStub::OnSetDefaultPrinter out"); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnDeletePrinterFromCups(MessageParcel &data, MessageParcel &reply) +{ + PRINT_HILOGD("PrintServiceStub::OnDeletePrinterFromCups in"); + std::string printerUri = data.ReadString(); + std::string printerName = data.ReadString(); + std::string printerMake = data.ReadString(); + int32_t ret = DeletePrinterFromCups(printerUri, printerName, printerMake); + reply.WriteInt32(ret); + PRINT_HILOGD("PrintServiceStub::OnDeletePrinterFromCups out"); + return ret == E_PRINT_NONE; +} + bool PrintServiceStub::OnEventOn(MessageParcel &data, MessageParcel &reply) { std::string taskId = data.ReadString(); @@ -436,6 +578,47 @@ bool PrintServiceStub::OnEventOff(MessageParcel &data, MessageParcel &reply) return ret == E_PRINT_NONE; } +bool PrintServiceStub::OnRegisterPrinterCallback(MessageParcel &data, MessageParcel &reply) +{ + std::string type = data.ReadString(); + if (type.empty()) { + PRINT_HILOGE("PrintServiceStub::OnEventOn type is null."); + reply.WriteInt32(E_PRINT_RPC_FAILURE); + return false; + } + PRINT_HILOGD("PrintServiceStub::OnRegisterPrinterCallback type=%{public}s ", type.c_str()); + sptr remote = data.ReadRemoteObject(); + if (remote == nullptr) { + PRINT_HILOGE("PrintServiceStub::OnEventOn remote is nullptr"); + reply.WriteInt32(E_PRINT_RPC_FAILURE); + return false; + } + sptr listener = iface_cast(remote); + if (listener.GetRefPtr() == nullptr) { + PRINT_HILOGE("PrintServiceStub::OnEventOn listener is null"); + reply.WriteInt32(E_PRINT_RPC_FAILURE); + return false; + } + int32_t ret = RegisterPrinterCallback(type, listener); + reply.WriteInt32(ret); + PRINT_HILOGD("PrintServiceStub::OnRegisterPrinterCallback out"); + return ret == E_PRINT_NONE; +} + +bool PrintServiceStub::OnUnregisterPrinterCallback(MessageParcel &data, MessageParcel &reply) +{ + std::string type = data.ReadString(); + if (type.empty()) { + reply.WriteInt32(E_PRINT_RPC_FAILURE); + return false; + } + PRINT_HILOGD("PrintServiceStub::OnUnregisterPrinterCallback type=%{public}s ", type.c_str()); + int32_t ret = UnregisterPrinterCallback(type); + reply.WriteInt32(ret); + PRINT_HILOGD("PrintServiceStub::OnUnregisterPrinterCallback out"); + return ret == E_PRINT_NONE; +} + bool PrintServiceStub::OnRegisterExtCallback(MessageParcel &data, MessageParcel &reply) { PRINT_HILOGD("PrintServiceStub::OnRegisterExtCallback in"); @@ -482,17 +665,15 @@ bool PrintServiceStub::OnLoadExtSuccess(MessageParcel &data, MessageParcel &repl bool PrintServiceStub::OnPrintByAdapter(MessageParcel &data, MessageParcel &reply) { PRINT_HILOGI("PrintServiceStub::OnPrintByAdapter in"); - std::string resultTaskId = ""; int32_t ret = E_PRINT_RPC_FAILURE; std::string jobName = data.ReadString(); auto attrs = PrintAttributes::Unmarshalling(data); - sptr token = data.ReadRemoteObject(); + std::string taskId = data.ReadString(); if (attrs != nullptr) { attrs->Dump(); - ret = PrintByAdapter(jobName, *attrs, resultTaskId, token); + ret = PrintByAdapter(jobName, *attrs, taskId); } reply.WriteInt32(ret); - reply.WriteString(resultTaskId); PRINT_HILOGI("PrintServiceStub::OnPrintByAdapter out"); return ret == E_PRINT_NONE; } diff --git a/services/print_service/src/print_system_data.cpp b/services/print_service/src/print_system_data.cpp new file mode 100644 index 0000000..6846704 --- /dev/null +++ b/services/print_service/src/print_system_data.cpp @@ -0,0 +1,604 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "print_system_data.h" +#include "print_log.h" +#include "print_util.h" +#include "print_constant.h" + +namespace { +const std::string PRINTER_LIST_FILE = "/data/service/el1/public/print_service/printer_list.json"; +const std::string PRINTER_LIST_VERSION = "v1"; +} // namespace + +namespace OHOS { +namespace Print { + +bool PrintSystemData::ParsePrinterListJsonV1(nlohmann::json &jsonObject) +{ + if (!jsonObject.contains("printer_list") || !jsonObject["printer_list"].is_array()) { + PRINT_HILOGW("can not find printer_list"); + return false; + } + for (auto &element : jsonObject["printer_list"].items()) { + nlohmann::json object = element.value(); + if (!object.contains("id") || !object["id"].is_string()) { + PRINT_HILOGW("can not find id"); + continue; + } + std::string id = object["id"]; + if (!object.contains("name") || !object["name"].is_string()) { + PRINT_HILOGW("can not find name"); + continue; + } + std::string name = object["name"]; + if (!object.contains("uri") || !object["uri"].is_string()) { + PRINT_HILOGW("can not find uri"); + continue; + } + std::string uri = object["uri"]; + if (!object.contains("maker") || !object["maker"].is_string()) { + PRINT_HILOGW("can not find maker"); + continue; + } + std::string maker = object["maker"]; + if (!object.contains("capability") || !object["capability"].is_object()) { + PRINT_HILOGW("can not find capability"); + continue; + } + nlohmann::json capsJson = object["capability"]; + PrinterCapability printerCapability; + if (!ConvertJsonToPrinterCapability(capsJson, printerCapability)) { + PRINT_HILOGW("convert json to printer capability failed"); + continue; + } + printerCapability.Dump(); + CupsPrinterInfo info; + info.name = name; + info.uri = uri; + info.maker = maker; + info.printerCapability = printerCapability; + InsertCupsPrinter(id, info, true); + } + return true; +} + +bool PrintSystemData::Init() +{ + addedPrinterMap_.clear(); + nlohmann::json jsonObject; + if (!GetJsonObjectFromFile(jsonObject)) { + PRINT_HILOGW("get json from file fail"); + return false; + } + if (!jsonObject.contains("version") || !jsonObject["version"].is_string()) { + PRINT_HILOGW("can not find version"); + return false; + } + std::string version = jsonObject["version"].get(); + PRINT_HILOGI("json version: %{public}s", version.c_str()); + if (version == PRINTER_LIST_VERSION) { + return ParsePrinterListJsonV1(jsonObject); + } + return false; +} + +bool PrintSystemData::GetJsonObjectFromFile(nlohmann::json &jsonObject) +{ + std::ifstream ifs(PRINTER_LIST_FILE.c_str(), std::ios::in | std::ios::binary); + if (!ifs.is_open()) { + PRINT_HILOGW("open printer list file fail"); + return false; + } + std::string fileData((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); + ifs.close(); + if (!nlohmann::json::accept(fileData)) { + PRINT_HILOGW("json accept fail"); + return false; + } + jsonObject = nlohmann::json::parse(fileData); + if (!jsonObject.contains("version") || !jsonObject["version"].is_string()) { + PRINT_HILOGW("can not find version"); + return false; + } + return true; +} + +void PrintSystemData::InsertCupsPrinter( + const std::string &printerId, const CupsPrinterInfo &printerInfo, bool needUpdateCaps) +{ + PRINT_HILOGI("InsertCupsPrinter printerId: %{public}s", printerId.c_str()); + auto iter = addedPrinterMap_.find(printerId); + if (iter == addedPrinterMap_.end() || iter->second == nullptr) { + PRINT_HILOGI("insert new printer"); + addedPrinterMap_[printerId] = std::make_shared(printerInfo); + } else { + PRINT_HILOGI("update exist printer"); + iter->second->name = printerInfo.name; + iter->second->uri = printerInfo.uri; + iter->second->maker = printerInfo.maker; + if (needUpdateCaps) { + iter->second->printerCapability = printerInfo.printerCapability; + } + } +} + +void PrintSystemData::DeleteCupsPrinter(const std::string &printerId) +{ + PRINT_HILOGI("DeleteCupsPrinter printerId: %{public}s", printerId.c_str()); + addedPrinterMap_.erase(printerId); + SaveCupsPrinterMap(); +} + +bool PrintSystemData::SaveCupsPrinterMap() +{ + int32_t fd = open(PRINTER_LIST_FILE.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0740); + PRINT_HILOGD("SaveCupsPrinterMap fd: %{public}d", fd); + if (fd < 0) { + PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str()); + close(fd); + return false; + } + nlohmann::json printerMapJson = nlohmann::json::array(); + for (auto iter = addedPrinterMap_.begin(); iter != addedPrinterMap_.end(); ++iter) { + auto info = iter->second; + if (info == nullptr) { + continue; + } + nlohmann::json printerJson = nlohmann::json::object(); + printerJson["id"] = iter->first; + printerJson["name"] = info->name; + printerJson["uri"] = info->uri; + printerJson["maker"] = info->maker; + nlohmann::json capsJson; + ConvertPrinterCapabilityToJson(info->printerCapability, capsJson); + printerJson["capability"] = capsJson; + printerMapJson.push_back(printerJson); + } + nlohmann::json jsonObject; + jsonObject["version"] = PRINTER_LIST_VERSION; + jsonObject["printer_list"] = printerMapJson; + std::string jsonString = jsonObject.dump(); + size_t jsonLength = jsonString.length(); + auto writeLength = write(fd, jsonString.c_str(), jsonLength); + close(fd); + PRINT_HILOGI("SaveCupsPrinterMap finished"); + if (writeLength < 0) { + return false; + } + return (size_t)writeLength == jsonLength; +} + +std::string PrintSystemData::QueryPrinterIdByStandardizeName(const std::string &printerName) +{ + for (auto iter = addedPrinterMap_.begin(); iter != addedPrinterMap_.end(); ++iter) { + auto info = iter->second; + if (info == nullptr) { + continue; + } + std::string name = PrintUtil::StandardizePrinterName(info->name); + if (name == printerName) { + return iter->first; + } + } + return ""; +} + +bool PrintSystemData::QueryCupsPrinterInfoByPrinterId(const std::string &printerId, CupsPrinterInfo &cupsPrinter) +{ + for (auto iter = addedPrinterMap_.begin(); iter != addedPrinterMap_.end(); ++iter) { + auto info = iter->second; + if (info == nullptr) { + continue; + } + if (printerId == iter->first) { + cupsPrinter.name = info->name; + cupsPrinter.uri = info->uri; + cupsPrinter.maker = info->maker; + cupsPrinter.printerCapability = info->printerCapability; + cupsPrinter.printerStatus = info->printerStatus; + return true; + } + } + return false; +} + +void PrintSystemData::QueryPrinterInfoById(const std::string &printerId, PrinterInfo &printerInfo) +{ + CupsPrinterInfo cupsPrinter; + if (QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinter)) { + printerInfo.SetPrinterId(printerId); + printerInfo.SetPrinterName(cupsPrinter.name); + printerInfo.SetCapability(cupsPrinter.printerCapability); + nlohmann::json option; + option["printerName"] = cupsPrinter.name; + option["printerUri"] = cupsPrinter.uri; + option["make"] = cupsPrinter.maker; + printerInfo.SetOption(option.dump()); + printerInfo.Dump(); + } else { + PRINT_HILOGE("query printer info failed."); + } +} + +void PrintSystemData::UpdatePrinterStatus(const std::string &printerId, PrinterStatus printerStatus) +{ + for (auto iter = addedPrinterMap_.begin(); iter != addedPrinterMap_.end(); ++iter) { + auto info = iter->second; + if (info == nullptr) { + continue; + } + if (printerId == iter->first) { + info->printerStatus = printerStatus; + PRINT_HILOGI("UpdatePrinterStatus success, status: %{public}d", info->printerStatus); + return; + } + } +} + +void PrintSystemData::InsertPrinterInfo(const std::string &printerId, const PrinterInfo &printerInfo) +{ + auto iter = addedPrinterInfoList_.find(printerId); + if (iter == addedPrinterInfoList_.end() || iter->second == nullptr) { + PRINT_HILOGI("insert new printerInfo"); + addedPrinterInfoList_[printerId] = std::make_shared(printerInfo); + } +} + +std::shared_ptr PrintSystemData::QueryPrinterInfoByPrinterId(const std::string &printerId) +{ + for (auto iter = addedPrinterInfoList_.begin(); iter != addedPrinterInfoList_.end(); ++iter) { + if (printerId == iter->first) { + return iter->second; + } + } + return nullptr; +} + +void PrintSystemData::GetAddedPrinterListFromSystemData(std::vector &printerNameList) +{ + for (auto iter = addedPrinterMap_.begin(); iter != addedPrinterMap_.end(); ++iter) { + auto info = iter->second; + if (info == nullptr) { + continue; + } + PRINT_HILOGI("GetAddedPrinterListFromSystemData info->name: %{public}s", info->name.c_str()); + printerNameList.emplace_back(info->name); + } +} + +bool PrintSystemData::IsPrinterAdded(const std::string &printerId) +{ + auto iter = addedPrinterMap_.find(printerId); + if (iter == addedPrinterMap_.end() || iter->second == nullptr) { + return false; + } + return true; +} + +void PrintSystemData::ConvertPrinterCapabilityToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson) +{ + capsJson["colorMode"] = printerCapability.GetColorMode(); + capsJson["duplexMode"] = printerCapability.GetDuplexMode(); + if (printerCapability.HasMargin()) { + ConvertPrintMarginToJson(printerCapability, capsJson); + } + ConvertPageSizeToJson(printerCapability, capsJson); + if (printerCapability.HasResolution()) { + ConvertPrintResolutionToJson(printerCapability, capsJson); + } + if (printerCapability.HasOption()) { + std::string options = printerCapability.GetOption(); + if (!nlohmann::json::accept(options)) { + PRINT_HILOGE("json accept capability options fail"); + return; + } + capsJson["options"] = nlohmann::json::parse(options); + } +} + +void PrintSystemData::ConvertPrintResolutionToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson) +{ + nlohmann::json resolutionListJson = nlohmann::json::array(); + std::vector resolutionList; + printerCapability.GetResolution(resolutionList); + for (auto iter : resolutionList) { + nlohmann::json resolutionJson = nlohmann::json::object(); + resolutionJson["id"] = iter.GetId(); + resolutionJson["horizontalDpi"] = iter.GetHorizontalDpi(); + resolutionJson["verticalDpi"] = iter.GetVerticalDpi(); + resolutionListJson.push_back(resolutionJson); + } + capsJson["resolution"] = resolutionListJson; +} + +void PrintSystemData::ConvertPageSizeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson) +{ + nlohmann::json pageSizeListJson = nlohmann::json::array(); + std::vector pageSizeList; + printerCapability.GetPageSize(pageSizeList); + for (auto iter : pageSizeList) { + nlohmann::json pageSizeJson = nlohmann::json::object(); + pageSizeJson["id"] = iter.GetId(); + pageSizeJson["name"] = iter.GetName(); + pageSizeJson["width"] = iter.GetWidth(); + pageSizeJson["height"] = iter.GetHeight(); + pageSizeListJson.push_back(pageSizeJson); + } + capsJson["pageSize"] = pageSizeListJson; +} + +void PrintSystemData::ConvertPrintMarginToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson) +{ + nlohmann::json marginJson; + PrintMargin minMargin; + printerCapability.GetMinMargin(minMargin); + if (minMargin.HasTop()) { + marginJson["top"] = minMargin.GetTop(); + } + if (minMargin.HasBottom()) { + marginJson["bottom"] = minMargin.GetBottom(); + } + if (minMargin.HasLeft()) { + marginJson["left"] = minMargin.GetLeft(); + } + if (minMargin.HasRight()) { + marginJson["right"] = minMargin.GetRight(); + } + capsJson["minMargin"] = marginJson; +} + +bool PrintSystemData::ConvertJsonToPrinterCapability(nlohmann::json &capsJson, PrinterCapability &printerCapability) +{ + if (!capsJson.contains("colorMode") || !capsJson["colorMode"].is_number()) { + PRINT_HILOGW("can not find colorMode"); + return false; + } + printerCapability.SetColorMode(capsJson["colorMode"].get()); + + if (!capsJson.contains("duplexMode") || !capsJson["duplexMode"].is_number()) { + PRINT_HILOGW("can not find duplexMode"); + return false; + } + printerCapability.SetDuplexMode(capsJson["duplexMode"].get()); + + if (capsJson.contains("minMargin") && capsJson["minMargin"].is_object()) { + PRINT_HILOGD("find minMargin"); + ConvertJsonToPrintMargin(capsJson, printerCapability); + } + + if (!capsJson.contains("pageSize") || !capsJson["pageSize"].is_array()) { + PRINT_HILOGW("can not find pageSize"); + return false; + } + if (!ConvertJsonToPageSize(capsJson, printerCapability)) { + PRINT_HILOGW("convert json to pageSize failed"); + return false; + } + + if (capsJson.contains("resolution") && capsJson["resolution"].is_array()) { + PRINT_HILOGD("find resolution"); + if (!ConvertJsonToPrintResolution(capsJson, printerCapability)) { + PRINT_HILOGW("convert json to print resolution failed"); + return false; + } + } + + if (capsJson.contains("options") && capsJson["options"].is_object()) { + PRINT_HILOGD("find options"); + printerCapability.SetOption(capsJson["options"].dump()); + } + + return true; +} + +bool PrintSystemData::ConvertJsonToPrintResolution(nlohmann::json &capsJson, PrinterCapability &printerCapability) +{ + nlohmann::json resolutionListJson = capsJson["resolution"]; + std::vector resolutionList; + for (auto &item : resolutionListJson.items()) { + if (!item.value().is_object()) { + PRINT_HILOGW("resolutionList item is not object"); + return false; + } + nlohmann::json resolutionJson = item.value(); + PrintResolution printResolution; + if (!resolutionJson.contains("id") || !resolutionJson["id"].is_string()) { + PRINT_HILOGW("can not find id"); + return false; + } + printResolution.SetId(resolutionJson["id"]); + if (!resolutionJson.contains("horizontalDpi") || !resolutionJson["horizontalDpi"].is_number()) { + PRINT_HILOGW("can not find horizontalDpi"); + return false; + } + printResolution.SetHorizontalDpi(resolutionJson["horizontalDpi"].get()); + if (!resolutionJson.contains("verticalDpi") || !resolutionJson["verticalDpi"].is_number()) { + PRINT_HILOGW("can not find verticalDpi"); + return false; + } + printResolution.SetVerticalDpi(resolutionJson["verticalDpi"].get()); + resolutionList.emplace_back(printResolution); + } + if (resolutionList.size()) { + printerCapability.SetResolution(resolutionList); + } + + return true; +} + +bool PrintSystemData::ConvertJsonToPageSize(nlohmann::json &capsJson, PrinterCapability &printerCapability) +{ + nlohmann::json pageSizeListJson = capsJson["pageSize"]; + std::vector pageSizeList; + for (auto &item : pageSizeListJson.items()) { + if (!item.value().is_object()) { + PRINT_HILOGW("pageSizeListJson item is not object"); + return false; + } + nlohmann::json pageSizeJson = item.value(); + PrintPageSize pageSize; + if (!pageSizeJson.contains("id") || !pageSizeJson["id"].is_string()) { + PRINT_HILOGW("can not find id"); + return false; + } + pageSize.SetId(pageSizeJson["id"]); + if (!pageSizeJson.contains("name") || !pageSizeJson["name"].is_string()) { + PRINT_HILOGW("can not find name"); + return false; + } + pageSize.SetName(pageSizeJson["name"]); + if (!pageSizeJson.contains("width") || !pageSizeJson["width"].is_number()) { + PRINT_HILOGW("can not find width"); + return false; + } + pageSize.SetWidth(pageSizeJson["width"].get()); + if (!pageSizeJson.contains("height") || !pageSizeJson["height"].is_number()) { + PRINT_HILOGW("can not find height"); + return false; + } + pageSize.SetHeight(pageSizeJson["height"].get()); + pageSizeList.emplace_back(pageSize); + } + if (pageSizeList.size()) { + printerCapability.SetPageSize(pageSizeList); + } + + return true; +} + +void PrintSystemData::ConvertJsonToPrintMargin(nlohmann::json &capsJson, PrinterCapability &printerCapability) +{ + nlohmann::json marginJson = capsJson["minMargin"]; + PrintMargin minMargin; + uint32_t marginCount = 0; + + if (marginJson.contains("top") && marginJson["top"].is_number()) { + minMargin.SetTop(marginJson["top"].get()); + marginCount++; + } + if (marginJson.contains("bottom") && marginJson["bottom"].is_number()) { + minMargin.SetTop(marginJson["bottom"].get()); + marginCount++; + } + if (marginJson.contains("left") && marginJson["left"].is_number()) { + minMargin.SetLeft(marginJson["left"].get()); + marginCount++; + } + if (marginJson.contains("right") && marginJson["right"].is_number()) { + minMargin.SetRight(marginJson["right"].get()); + marginCount++; + } + if (marginCount) { + printerCapability.SetMinMargin(minMargin); + } +} + +bool PrintSystemData::GetPrinterCapabilityFromSystemData( + CupsPrinterInfo &cupsPrinter, std::string printerId, PrinterCapability &printerCapability) +{ + PrinterCapability cupsPrinterCaps = cupsPrinter.printerCapability; + std::vector pageSizeList; + cupsPrinterCaps.GetPageSize(pageSizeList); + if (pageSizeList.size() != 0 && cupsPrinterCaps.HasOption()) { + PRINT_HILOGI("find printer capability in ststem data"); + printerCapability = cupsPrinterCaps; + return true; + } else if (GetPrinterCapabilityFromFile(printerId, printerCapability)) { + return true; + } + return false; +} + +bool PrintSystemData::GetPrinterCapabilityFromFile(std::string printerId, PrinterCapability &printerCapability) +{ + PRINT_HILOGI("GetPrinterCapabilityFromFile printerId: %{public}s", printerId.c_str()); + nlohmann::json jsonObject; + if (!GetJsonObjectFromFile(jsonObject)) { + PRINT_HILOGW("get json from file fail"); + return false; + } + if (!jsonObject.contains("printer_list") || !jsonObject["printer_list"].is_array()) { + PRINT_HILOGW("can not find printer_list"); + return false; + } + nlohmann::json printerMapJson = jsonObject["printer_list"]; + if (printerMapJson.empty()) { + PRINT_HILOGW("printer map is empty"); + return false; + } + + for (auto &element : jsonObject["printer_list"].items()) { + nlohmann::json object = element.value(); + if (!CheckPrinterInfoJson(object, printerId)) { + continue; + } + if (!object.contains("capability")) { + PRINT_HILOGE("json does not contain the key as capability"); + continue; + } + nlohmann::json capsJson = object["capability"]; + PrinterCapability caps; + if (!ConvertJsonToPrinterCapability(capsJson, caps)) { + PRINT_HILOGW("convert json to printer capability failed"); + continue; + } + std::vector pageSizeList; + caps.GetPageSize(pageSizeList); + if (pageSizeList.size() != 0 && caps.HasOption()) { + PRINT_HILOGI("find printer capability in file"); + caps.Dump(); + printerCapability = caps; + return true; + } + } + return false; +} + +bool PrintSystemData::CheckPrinterInfoJson(nlohmann::json &object, std::string &printerId) +{ + if (!object.contains("id") || !object["id"].is_string()) { + PRINT_HILOGW("can not find id"); + return false; + } + std::string id = object["id"]; + if (id != printerId) { + return false; + } + if (!object.contains("name") || !object["name"].is_string()) { + PRINT_HILOGW("can not find name"); + return false; + } + if (!object.contains("uri") || !object["uri"].is_string()) { + PRINT_HILOGW("can not find uri"); + return false; + } + if (!object.contains("maker") || !object["maker"].is_string()) { + PRINT_HILOGW("can not find maker"); + return false; + } + if (!object.contains("capability") || !object["capability"].is_object()) { + PRINT_HILOGW("can not find capability"); + return false; + } + return true; +} +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/services/print_service/src/print_usb_manager.cpp b/services/print_service/src/print_usb_manager.cpp new file mode 100644 index 0000000..89389ed --- /dev/null +++ b/services/print_service/src/print_usb_manager.cpp @@ -0,0 +1,355 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_usb_manager.h" +#include "print_log.h" +#include "usb_errors.h" +#include "print_ipp_over_usb_util.h" +#include "cJSON.h" + +namespace OHOS::Print { +using namespace std; +using namespace OHOS; +using namespace OHOS::USB; + +PrintUsbManager::PrintUsbManager() +{} + +PrintUsbManager::~PrintUsbManager() +{} + +void PrintUsbManager::Init() +{ + if (isInit) { + PRINT_HILOGD("has init"); + } + isInit = true; + RefreshUsbPrinterDevice(); +} + +bool PrintUsbManager::isExistIppOverUsbPrinter(std::string printerName) +{ + PRINT_HILOGD("isExistIppOverUsbPrinter printerName = %{public}s", printerName.c_str()); + if (!printerName.empty() && printDeviceMap.find(printerName) != printDeviceMap.end()) { + return true; + } + return false; +} + + +bool PrintUsbManager::isPrintDevice(USB::UsbDevice &usbdevice, std::string &printerName) +{ + int32_t configCount = usbdevice.GetConfigCount(); + std::vector> indexVec; + int32_t ippusbInterfaceCount = 0; + PRINT_HILOGD("name = %{public}s.", usbdevice.GetName().c_str()); + for (int32_t configIndex = 0; configIndex < configCount; configIndex++) { + int32_t interfaceCount = static_cast(usbdevice.GetConfigs()[configIndex].GetInterfaceCount()); + PRINT_HILOGD("configIndex = %{public}d.", configIndex); + for (int32_t interfaceIndex = 0; interfaceIndex < interfaceCount; interfaceIndex++) { + PRINT_HILOGD("interfaceIndex = %{public}d.", interfaceIndex); + UsbInterface usbInterface = usbdevice.GetConfigs()[configIndex].GetInterfaces()[interfaceIndex]; + PRINT_HILOGD("isPrintDevice class = %{public}d, subclass = %{public}d, protocol = %{public}d", + usbInterface.GetClass(), usbInterface.GetSubClass(), usbInterface.GetProtocol()); + bool isSupportIpp = (usbInterface.GetClass() == USB_DEVICE_CLASS_PRINT && + usbInterface.GetSubClass() == USB_DEVICE_SUBCLASS_PRINT && + usbInterface.GetProtocol() == USB_DEVICE_PROTOCOL_PRINT); + if (isSupportIpp) { + auto indexPair = std::make_pair(configIndex, interfaceIndex); + indexVec.push_back(indexPair); + ippusbInterfaceCount++; + } + } + } + // Two or more interfaces are required + if (ippusbInterfaceCount >= USB_INTERFACE_MIN_COUNT) { + printerName = GetProductName(usbdevice); + PRINT_HILOGI("support IppPrint printerName = %{public}s.", printerName.c_str()); + if (printerName.empty()) { + return false; + } + printerIndexMap[printerName] = indexVec; + return true; + } + return false; +} + +void PrintUsbManager::RefreshUsbPrinterDevice() +{ + vector devlist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devlist); + if (ERR_OK != ret) { + PRINT_HILOGE("RefreshDeviceList GetDevices failed with ret = %{public}d.", ret); + return; + } else if (devlist.empty()) { + PRINT_HILOGE("RefreshDeviceList GetDevices empty with ret = %{public}d.", ret); + return; + } + for (auto dev : devlist) { + std::string printerName; + if (isPrintDevice(dev, printerName)) { + printDeviceMap[printerName] = dev; + } + } +} + +std::string PrintUsbManager::GetProductName(UsbDevice &usbDevice) +{ + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + PRINT_HILOGI("getProductName dev.GetName() = %{public}s.", usbDevice.GetName().c_str()); + USBDevicePipe usbDevicePipe; + int32_t openDeviceRet = UsbSrvClient.OpenDevice(usbDevice, usbDevicePipe); + PRINT_HILOGI("openDevice ret = %{public}d", openDeviceRet); + if (openDeviceRet != UEC_OK) { + PRINT_HILOGE("openDevice fail with ret = %{public}d", openDeviceRet); + return ""; + } + std::string productName = + QueryPrinterInfoFromStringDescriptor(usbDevicePipe, USB_VALUE_DESCRIPTOR_INDEX_PRODUCT_NAME); + std::string serialNumber = + QueryPrinterInfoFromStringDescriptor(usbDevicePipe, USB_VALUE_DESCRIPTOR_INDEX_SERIAL_NUMBER); + std::string printerName = + productName + "-" + serialNumber.substr(serialNumber.length() - HTTP_COMMON_CONST_VALUE_4); + PRINT_HILOGI("getProductName printerName = %{public}s.", printerName.c_str()); + return printerName; +} + +std::string PrintUsbManager::QueryPrinterInfoFromStringDescriptor( + USBDevicePipe &usbDevicePipe, uint16_t indexInStringDescriptor) +{ + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + PRINT_HILOGI("enter QueryPrinterInfoFromStringDescriptor"); + uint8_t requestType = USB_REQUESTTYPE_DEVICE_TO_HOST; + uint8_t request = USB_REQUEST_GET_DESCRIPTOR; + uint16_t value = (USB_VALUE_DESCRIPTOR_TYPE_STRING << HTTP_COMMON_CONST_VALUE_8) | indexInStringDescriptor; + uint16_t index = USB_INDEX_LANGUAGE_ID_ENGLISH; + int32_t timeOut = HTTP_COMMON_CONST_VALUE_500; + const HDI::Usb::V1_0::UsbCtrlTransfer tctrl = {requestType, request, value, index, timeOut}; + std::vector bufferData(HTTP_COMMON_CONST_VALUE_100, 0); + int32_t ret = UsbSrvClient.ControlTransfer(usbDevicePipe, tctrl, bufferData); + if (ret != 0 || bufferData[INDEX_0] == 0) { + PRINT_HILOGE("ControlTransfer failed ret = %{public}d, buffer length = %{public}d", ret, bufferData[0]); + return ""; + } + + std::vector arr((bufferData[INDEX_0] - HTTP_COMMON_CONST_VALUE_2) / HTTP_COMMON_CONST_VALUE_2); + int arrIndex = 0; + for (int i = INDEX_2; i < bufferData[INDEX_0];) { + arr[arrIndex++] = bufferData[i]; + i += HTTP_COMMON_CONST_VALUE_2; + } + std::string printerInfo(arr.begin(), arr.end()); + PRINT_HILOGI("bufferData printerInfo: %{public}s\n", printerInfo.c_str()); + return printerInfo; +} + +bool PrintUsbManager::AllocateInterface(const std::string &printerName, UsbDevice &usbdevice, + USBDevicePipe &usbDevicePipe) +{ + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + PrinterTranIndex tranIndex; + for (auto index : printerIndexMap[printerName]) { + int32_t configIndex = index.first; + int32_t interfaceIndex = index.second; + UsbInterface ippInterface = + usbdevice.GetConfigs()[configIndex].GetInterfaces()[interfaceIndex]; + int32_t ret = UsbSrvClient.ClaimInterface(usbDevicePipe, ippInterface, true); + if (ret != UEC_OK) { + PRINT_HILOGE("ClaimInterface fail, ret = %{public}d", ret); + continue; + } + if (tranIndex.commonConfigIndex == INVAILD_VALUE) { + tranIndex.commonConfigIndex = configIndex; + tranIndex.commonInterfaceIndex = interfaceIndex; + } else if (tranIndex.sendDocConfigIndex == INVAILD_VALUE) { + tranIndex.sendDocConfigIndex = configIndex; + tranIndex.sendDocInterfaceIndex = interfaceIndex; + break; + } + } + if (tranIndex.commonConfigIndex == INVAILD_VALUE || tranIndex.sendDocConfigIndex == INVAILD_VALUE) { + PRINT_HILOGE("connect usb printerName = %{public}s fail!", printerName.c_str()); + if (tranIndex.commonConfigIndex != INVAILD_VALUE) { + int32_t configIndex = tranIndex.commonConfigIndex; + UsbInterface commonInterface = + usbdevice.GetConfigs()[configIndex].GetInterfaces()[tranIndex.commonInterfaceIndex]; + UsbSrvClient.ReleaseInterface(usbDevicePipe, commonInterface); + } + UsbSrvClient.Close(usbDevicePipe); + return false; + } + + printPipeMap[printerName] = usbDevicePipe; + printTranIndexMap[printerName] = tranIndex; + return true; +} + +bool PrintUsbManager::ConnectUsbPinter(const std::string &printerName) +{ + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + PRINT_HILOGD("connect usb printerName = %{public}s", printerName.c_str()); + if (!printerName.empty() && printPipeMap.find(printerName) != printPipeMap.end()) { + PRINT_HILOGD("printerName = %{public}s is opened", printerName.c_str()); + return true; + } + if (!printerName.empty() && printDeviceMap.find(printerName) != printDeviceMap.end()) { + UsbDevice usbdevice = printDeviceMap[printerName]; + USBDevicePipe usbDevicePipe; + int32_t openDeviceRet = UsbSrvClient.OpenDevice(usbdevice, usbDevicePipe); + PRINT_HILOGD("openDevice ret = %{public}d", openDeviceRet); + if (openDeviceRet == UEC_OK) { + return AllocateInterface(printerName, usbdevice, usbDevicePipe); + } else { + PRINT_HILOGE("ipp usb openDevice fail with ret = %{public}d", openDeviceRet); + return false; + } + } + return false; +} + +void PrintUsbManager::DisConnectUsbPinter(const std::string &printerName) +{ + if (!printerName.empty() && printDeviceMap.find(printerName) != printDeviceMap.end() && + printPipeMap.find(printerName) != printPipeMap.end()) { + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + + UsbDevice usbdevice = printDeviceMap[printerName]; + USBDevicePipe usbDevicePipe = printPipeMap[printerName]; + + PrinterTranIndex tranIndex = printTranIndexMap[printerName]; + UsbInterface commonInterface = + usbdevice.GetConfigs()[tranIndex.commonConfigIndex].GetInterfaces()[tranIndex.commonInterfaceIndex]; + UsbSrvClient.ReleaseInterface(usbDevicePipe, commonInterface); + + UsbInterface sendDocIterface = + usbdevice.GetConfigs()[tranIndex.sendDocConfigIndex].GetInterfaces()[tranIndex.sendDocInterfaceIndex]; + UsbSrvClient.ReleaseInterface(usbDevicePipe, sendDocIterface); + + UsbSrvClient.Close(usbDevicePipe); + + printPipeMap.erase(printerName); + printTranIndexMap.erase(printerName); + } +} + +int32_t PrintUsbManager::BulkTransferWrite(std::string printerName, const Operation operation, + std::vector &vectorRequestBuffer) +{ + if (printDeviceMap.find(printerName) == printDeviceMap.end()) { + return INVAILD_VALUE; + } + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + UsbDevice usbdevice = printDeviceMap[printerName]; + int32_t currentConfigIndex = INVAILD_VALUE; + int32_t currentInterfaceIndex = INVAILD_VALUE; + PrinterTranIndex tranIndex = printTranIndexMap[printerName]; + if (operation == Operation::Send_Document) { + currentConfigIndex = tranIndex.sendDocConfigIndex; + currentInterfaceIndex = tranIndex.sendDocInterfaceIndex; + } else { + currentConfigIndex = tranIndex.commonConfigIndex; + currentInterfaceIndex = tranIndex.commonInterfaceIndex; + } + UsbInterface useInterface = usbdevice.GetConfigs()[currentConfigIndex].GetInterfaces()[currentInterfaceIndex]; + USBEndpoint point1 = useInterface.GetEndpoints().at(INDEX_0); + USBEndpoint point2 = useInterface.GetEndpoints().at(INDEX_1); + USBEndpoint pointWrite; + if (point1.GetDirection() == 0) { + pointWrite = point1; + } else { + pointWrite = point2; + } + USBDevicePipe usbDevicePipe = printPipeMap[printerName]; + int32_t writeRet = UsbSrvClient.BulkTransfer(usbDevicePipe, pointWrite, vectorRequestBuffer, + USB_BULKTRANSFER_WRITE_TIMEOUT); + return writeRet; +} + +int32_t PrintUsbManager::BulkTransferRead(std::string printerName, const Operation operation, + std::vector &readTempBUffer) +{ + if (printDeviceMap.find(printerName) == printDeviceMap.end()) { + return INVAILD_VALUE; + } + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + UsbDevice usbdevice = printDeviceMap[printerName]; + int32_t currentConfigIndex = INVAILD_VALUE; + int32_t currentInterfaceIndex = INVAILD_VALUE; + PrinterTranIndex tranIndex = printTranIndexMap[printerName]; + if (operation == Operation::Send_Document) { + currentConfigIndex = tranIndex.sendDocConfigIndex; + currentInterfaceIndex = tranIndex.sendDocInterfaceIndex; + } else { + currentConfigIndex = tranIndex.commonConfigIndex; + currentInterfaceIndex = tranIndex.commonInterfaceIndex; + } + UsbInterface useInterface = usbdevice.GetConfigs()[currentConfigIndex].GetInterfaces()[currentInterfaceIndex]; + USBEndpoint point1 = useInterface.GetEndpoints().at(INDEX_0); + USBEndpoint point2 = useInterface.GetEndpoints().at(INDEX_1); + USBEndpoint pointRead; + if (point1.GetDirection() == 0) { + pointRead = point2; + } else { + pointRead = point1; + } + USBDevicePipe usbDevicePipe = printPipeMap[printerName]; + int32_t readFromUsbRes = UsbSrvClient.BulkTransfer(usbDevicePipe, pointRead, readTempBUffer, + USB_BULKTRANSFER_READ_TIMEOUT); + return readFromUsbRes; +} + +void PrintUsbManager::DealUsbDevStatusChange(const std::string &devStr, bool isAttach) +{ + PRINT_HILOGD("DealUsbDevStatusChange isAttach = %{public}d, devStr = %{public}s.", + isAttach, devStr.c_str()); + cJSON *devJson = cJSON_Parse(devStr.c_str()); + if (!devJson) { + PRINT_HILOGE("Create devJson error"); + } + UsbDevice *dev = new UsbDevice(devJson); + if (!isAttach) { + std::string printerName = GetPrinterName(dev->GetName()); + PRINT_HILOGI("DealUsbDevStatusChange detached dev->GetName() = %{public}s, printerName = %{public}s.", + dev->GetName().c_str(), printerName.c_str()); + if (!printerName.empty()) { + DisConnectUsbPinter(printerName); + printDeviceMap.erase(printerName); + printerIndexMap.erase(printerName); + } + } else { + std::string printerName; + if (isPrintDevice(*dev, printerName)) { + printDeviceMap[printerName] = *dev; + PRINT_HILOGI("DealUsbDevStatusChange attached dev->GetName() = %{public}s , printerName = %{public}s.", + dev->GetName().c_str(), printerName.c_str()); + } + } + cJSON_Delete(devJson); + delete dev; + dev = nullptr; +} + +std::string PrintUsbManager::GetPrinterName(const std::string &name) +{ + for (const auto& pair : printDeviceMap) { + if (pair.second.GetName() == name) { + return pair.first; + } + } + return ""; +} +} + diff --git a/services/print_service/src/print_user_data.cpp b/services/print_service/src/print_user_data.cpp new file mode 100644 index 0000000..3c0c687 --- /dev/null +++ b/services/print_service/src/print_user_data.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "nlohmann/json.hpp" + +#include "print_user_data.h" +#include "print_log.h" +#include "print_constant.h" + +namespace OHOS { +namespace Print { + +const std::string PRINT_USER_DATA_FILE = "/data/service/el1/public/print_service/print_user_data.json"; +const std::string PRINT_USER_DATA_VERSION = "v1"; + +void PrintUserData::RegisterPrinterCallback(const std::string &type, const sptr &listener) +{ + registeredListeners_[type] = listener; +} + +void PrintUserData::UnregisterPrinterCallback(const std::string &type) +{ + auto iter = registeredListeners_.find(type); + if (iter != registeredListeners_.end()) { + registeredListeners_.erase(iter); + } +} + +void PrintUserData::SendPrinterEvent(const std::string &type, int event, const PrinterInfo &info) +{ + auto iter = registeredListeners_.find(type); + if (iter != registeredListeners_.end() && iter->second != nullptr) { + iter->second->OnCallback(event, info); + } +} + +void PrintUserData::AddToPrintJobList(const std::string jobId, const std::shared_ptr &printjob) +{ + printJobList_.insert(std::make_pair(jobId, printjob)); +} + +void PrintUserData::UpdateQueuedJobList( + const std::string &jobId, const std::shared_ptr &printJob, std::string jobOrderId) +{ + if (jobOrderId == "0") { + jobOrderList_.clear(); + } + auto jobIt = printJobList_.find(jobId); + if (jobIt == printJobList_.end()) { + PRINT_HILOGE("invalid job id"); + return; + } + printJobList_.erase(jobIt); + + if (queuedJobList_.find(jobId) != queuedJobList_.end()) { + queuedJobList_[jobId] = printJob; + jobOrderList_[jobOrderId] = jobId; + } else { + queuedJobList_.insert(std::make_pair(jobId, printJob)); + jobOrderList_.insert(std::make_pair(jobOrderId, jobId)); + } +} + +int32_t PrintUserData::QueryPrintJobById(std::string &printJobId, PrintJob &printJob) +{ + if (printJobList_.empty()) { + PRINT_HILOGE("printJobList is empty!"); + return E_PRINT_INVALID_PRINTJOB; + } + auto jobIt = printJobList_.find(printJobId); + if (jobIt == printJobList_.end()) { + PRINT_HILOGW("no print job exists"); + return E_PRINT_INVALID_PRINTJOB; + } else { + printJob = *jobIt->second; + } + PRINT_HILOGI("QueryPrintJobById End."); + return E_PRINT_NONE; +} + +int32_t PrintUserData::QueryAllPrintJob(std::vector &printJobs) +{ + printJobs.clear(); + for (auto iter : jobOrderList_) { + PRINT_HILOGI("QueryAllPrintJob queuedJobList_ jobOrderId: %{public}s, jobId: %{public}s", + iter.first.c_str(), + iter.second.c_str()); + auto jobIt = queuedJobList_.find(iter.second); + if (jobIt == queuedJobList_.end()) { + PRINT_HILOGW("This job dose not exist."); + continue; + } else { + printJobs.emplace_back(*jobIt->second); + } + } + PRINT_HILOGI("QueryAllPrintJob End."); + return E_PRINT_NONE; +} + +void PrintUserData::SetUserId(int32_t userId) +{ + userId_ = userId; +} + +int32_t PrintUserData::SetLastUsedPrinter(const std::string &printerId) +{ + PRINT_HILOGI("begin SetLastUsedPrinter"); + if (printerId.empty()) { + PRINT_HILOGE("printerId is empty"); + return E_PRINT_INVALID_PARAMETER; + } + lastUsedPrinterId_ = printerId; + if (!SetUserDataToFile()) { + PRINT_HILOGE("SetUserDataToFile failed."); + return E_PRINT_SERVER_FAILURE; + } + + return E_PRINT_NONE; +} + +std::string PrintUserData::GetLastUsedPrinter() +{ + return lastUsedPrinterId_; +} + +int32_t PrintUserData::SetDefaultPrinter(const std::string &printerId) +{ + PRINT_HILOGI("begin SetDefaultPrinter"); + defaultPrinterId_ = printerId; + if (!SetUserDataToFile()) { + PRINT_HILOGE("SetUserDataToFile failed."); + return E_PRINT_SERVER_FAILURE; + } + + return E_PRINT_NONE; +} + +std::string PrintUserData::GetDefaultPrinter() +{ + return defaultPrinterId_; +} + +void PrintUserData::ParseUserData() +{ + std::string fileData = ""; + if (!GetFileData(fileData)) { + PRINT_HILOGW("get file data failed"); + return; + } + if (!nlohmann::json::accept(fileData)) { + PRINT_HILOGW("json accept fail"); + return; + } + nlohmann::json jsonObject = nlohmann::json::parse(fileData); + if (!jsonObject.contains("version") || !jsonObject["version"].is_string()) { + PRINT_HILOGW("can not find version"); + return; + } + if (jsonObject["version"].get() == PRINT_USER_DATA_VERSION) { + if (!jsonObject.contains("print_user_data")) { + PRINT_HILOGW("can not find print_user_data"); + return; + } + PRINT_HILOGI("userId_: %{public}d", userId_); + nlohmann::json userDataList = jsonObject["print_user_data"]; + if (!userDataList.contains(std::to_string(userId_)) || !userDataList[std::to_string(userId_)].is_object()) { + PRINT_HILOGW("can not find current userId"); + return; + } + nlohmann::json userData = userDataList[std::to_string(userId_)]; + if (!userData.contains("defaultPrinter") || !userData["defaultPrinter"].is_string()) { + PRINT_HILOGW("can not find defaultPrinter"); + return; + } + defaultPrinterId_ = userData["defaultPrinter"]; + if (!userData.contains("lastUsedPrinter") || !userData["lastUsedPrinter"].is_string()) { + PRINT_HILOGW("can not find lastUsedPrinter"); + return; + } + lastUsedPrinterId_ = userData["lastUsedPrinter"]; + PRINT_HILOGI("defaultPrinterId_: %{public}s, lastUsedPrinterId_: %{public}s", + defaultPrinterId_.c_str(), + lastUsedPrinterId_.c_str()); + } +} + +bool PrintUserData::GetFileData(std::string &fileData) +{ + PRINT_HILOGI("begin GetFileData"); + std::ifstream ifs(PRINT_USER_DATA_FILE.c_str(), std::ios::in | std::ios::binary); + if (!ifs.is_open()) { + PRINT_HILOGW("open printer list file fail"); + int32_t fd = open(PRINT_USER_DATA_FILE.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0740); + PRINT_HILOGI("create file fd: %{public}d", fd); + if (fd < 0) { + PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str()); + close(fd); + return false; + } + nlohmann::json userDataJson = nlohmann::json::object(); + nlohmann::json jsonObject; + jsonObject["version"] = PRINT_USER_DATA_VERSION; + jsonObject["print_user_data"] = userDataJson; + fileData = jsonObject.dump(); + size_t jsonLength = fileData.length(); + auto writeLength = write(fd, fileData.c_str(), jsonLength); + close(fd); + if (writeLength < 0 && (size_t)writeLength != jsonLength) { + return false; + } + } else { + fileData.assign((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); + ifs.close(); + } + return true; +} + +bool PrintUserData::SetUserDataToFile() +{ + PRINT_HILOGI("begin SetUserDataToFile"); + std::string fileData = ""; + if (!GetFileData(fileData)) { + PRINT_HILOGW("get file data failed"); + return false; + } + if (!nlohmann::json::accept(fileData)) { + PRINT_HILOGW("json accept fail"); + return false; + } + nlohmann::json jsonObject = nlohmann::json::parse(fileData); + if (!jsonObject.contains("version") || !jsonObject["version"].is_string()) { + PRINT_HILOGW("can not find version"); + return false; + } + std::string version = jsonObject["version"].get(); + PRINT_HILOGI("json version: %{public}s", version.c_str()); + if (version == PRINT_USER_DATA_VERSION) { + if (!jsonObject.contains("print_user_data")) { + PRINT_HILOGW("can not find print_user_data"); + return false; + } + PRINT_HILOGI("userId_: %{public}d", userId_); + nlohmann::json userData = nlohmann::json::object(); + userData["defaultPrinter"] = defaultPrinterId_; + userData["lastUsedPrinter"] = lastUsedPrinterId_; + jsonObject["print_user_data"][std::to_string(userId_)] = userData; + std::string temp = jsonObject.dump(); + PRINT_HILOGI("json temp: %{public}s", temp.c_str()); + int32_t fd = open(PRINT_USER_DATA_FILE.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0740); + PRINT_HILOGI("SetUserDataToFile fd: %{public}d", fd); + if (fd < 0) { + PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str()); + close(fd); + return false; + } + std::string jsonString = jsonObject.dump(); + size_t jsonLength = jsonString.length(); + auto writeLength = write(fd, jsonString.c_str(), jsonLength); + close(fd); + PRINT_HILOGI("SetUserDataToFile finished"); + if (writeLength < 0) { + return false; + } + return (size_t)writeLength == jsonLength; + } + return true; +} +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/test/fuzztest/BUILD.gn b/test/fuzztest/BUILD.gn index 5228ba3..be13522 100644 --- a/test/fuzztest/BUILD.gn +++ b/test/fuzztest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2023-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -15,5 +15,9 @@ import("//base/print/print_fwk/print.gni") group("fuzztest") { testonly = true - deps = [ "printservice_fuzzer:fuzztest" ] + deps = [ + "printcupsclient_fuzzer:fuzztest", + "printservice_fuzzer:fuzztest", + "printserviceability_fuzzer:fuzztest", + ] } diff --git a/test/fuzztest/printcupsclient_fuzzer/BUILD.gn b/test/fuzztest/printcupsclient_fuzzer/BUILD.gn new file mode 100644 index 0000000..49fc7f3 --- /dev/null +++ b/test/fuzztest/printcupsclient_fuzzer/BUILD.gn @@ -0,0 +1,110 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/print/print_fwk/print.gni") +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PrintCupsClientFuzzTest") { + module_out_path = fuzz_test_output_path + + fuzz_config_file = "${print_path}/test/fuzztest/printcupsclient_fuzzer" + + include_dirs = [ + "${print_path}/frameworks/innerkitsimpl/print_impl/include", + "${print_utils_path}/include", + "//third_party/cpp-httplib", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + cflags_cc = [] + + deps = [ + "${print_path}/etc/init:printservice.rc", + "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", + "${print_path}/frameworks/kits/extension:print_extension_framework", + "${print_path}/frameworks/kits/extension:print_extension_module", + "${print_path}/frameworks/models/print_models:print_models", + "${print_path}/interfaces/kits/jsnapi/print_extension:printextensionability_napi", + "${print_path}/interfaces/kits/jsnapi/print_extensionctx:printextensioncontext_napi", + "${print_path}/interfaces/kits/napi/print_napi:print_napi", + "${print_path}/profile:print_sa_profiles", + "${print_path}/services/print_service:print_service", + ] + + sources = [ "printcupsclient_fuzzer.cpp" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "drivers_interface_usb:libusb_proxy_1.0", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "os_account:os_account_innerkits", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "usb_manager:usbsrv_client", + "wifi:wifi_sdk", + ] + + if (cups_enable) { + include_dirs += [ "//third_party/cups/cups-2.4.0" ] + cflags_cc += [ "-DCUPS_ENABLE" ] + external_deps += [ + "cJSON:cjson", + "cups:cups", + "cups-filters:cupsfilters", + ] + } + + if (security_guard_enabled) { + external_deps += [ + "security_guard:libsg_collect_sdk", + "time_service:time_client", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PrintCupsClientFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/printcupsclient_fuzzer/curpus/init b/test/fuzztest/printcupsclient_fuzzer/curpus/init new file mode 100644 index 0000000..6198079 --- /dev/null +++ b/test/fuzztest/printcupsclient_fuzzer/curpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.cpp b/test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.cpp new file mode 100644 index 0000000..b590c52 --- /dev/null +++ b/test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define private public +#define protected public +#include "printcupsclient_fuzzer.h" +#include "fuzzer/FuzzedDataProvider.h" +#include "print_constant.h" +#include "printer_capability.h" +#include "print_log.h" +#include "print_cups_client.h" + +namespace OHOS { +namespace Print { +constexpr uint8_t MAX_STRING_LENGTH = 255; +constexpr float MAX_FLOAT_VALUE = 1000.0; +constexpr int MAX_SET_NUMBER = 100; + +void TestInitCupsResources(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); +} + +void TestStopCupsdService(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + PrintCupsClient::GetInstance()->StopCupsdService(); +} + +void TestQueryPPDInformation(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string makeModelStr = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string ppd = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector ppds; + ppds.push_back(ppd); + PrintCupsClient::GetInstance()->QueryPPDInformation(makeModelStr.c_str(), ppds); +} + +void TestAddPrinterToCups(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerUri = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerMake = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::GetInstance()->AddPrinterToCups(printerUri, printerName, printerMake); +} + +void TestQueryPrinterCapabilityByUri(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerUri = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrinterCapability printerCaps; + PrintCupsClient::GetInstance()->QueryPrinterCapabilityByUri(printerUri, printerName, printerCaps); +} + +void TestDeleteCupsPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerNameStr = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::GetInstance()->DeleteCupsPrinter(printerNameStr.c_str()); +} + +void TestAddCupsPrintJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + PrintJob jobInfo; + PrintCupsClient::GetInstance()->AddCupsPrintJob(jobInfo); +} + +void TestCancelCupsJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string serviceJobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::GetInstance()->CancelCupsJob(serviceJobId); +} + +void TestQueryAddedPrinterList(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerNameStr = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector printerName; + printerName.push_back(printerNameStr); + PrintCupsClient::GetInstance()->QueryAddedPrinterList(printerName); +} + +void TestGetPPDFile(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::GetInstance()->GetPPDFile(printerName); +} + +void TestSetDefaultPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::GetInstance()->SetDefaultPrinter(printerName); +} + +void TestQueryPrinterAttrList(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string key = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector keyList; + keyList.push_back(key); + std::string value = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector valueList; + valueList.push_back(value); + PrintCupsClient::GetInstance()->QueryPrinterAttrList(printerName, keyList, valueList); +} + +void TestQueryPrinterInfoByPrinterId(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrinterInfo info; + PrintCupsClient::GetInstance()->QueryPrinterInfoByPrinterId(printerId, info); +} + +void TestDeletePrinterFromCups(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerUri = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerMake = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::GetInstance()->DeletePrinterFromCups(printerUri, printerName, printerMake); +} + +// below are private +void TestJobCompleteCallback(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + PrintCupsClient::GetInstance()->JobCompleteCallback(); +} + +void TestCheckPrinterMakeModel(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + JobParameters jobParams; + PrintCupsClient::CheckPrinterMakeModel(&jobParams); +} + +void TestCheckPrinterOnline(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + std::string printerUriStr = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintCupsClient::CheckPrinterOnline(printerUriStr.c_str(), printerId); +} + +void TestDumpJobParameters(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + JobParameters* jobParams = new (std::nothrow) JobParameters; + if (jobParams != nullptr) { + PrintCupsClient::GetInstance()->DumpJobParameters(jobParams); + } +} + +void TestGetMedieSize(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + PrintJob jobInfo; + PrintCupsClient::GetInstance()->GetMedieSize(jobInfo); +} + +void TestGetColorString(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + uint32_t colorCode = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintCupsClient::GetInstance()->GetColorString(colorCode); +} + +void TestConvertInchTo100MM(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + float num = dataProvider->ConsumeFloatingPointInRange(0, MAX_FLOAT_VALUE); + PrintCupsClient::ConvertInchTo100MM(num); +} + +void TestGetIpAddress(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintCupsClient::GetInstance()->InitCupsResources(); + unsigned int number = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintCupsClient::GetIpAddress(number); +} + +} // namespace Print +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + FuzzedDataProvider dataProvider(data, size); + OHOS::Print::TestInitCupsResources(data, size, &dataProvider); + OHOS::Print::TestStopCupsdService(data, size, &dataProvider); + OHOS::Print::TestQueryPPDInformation(data, size, &dataProvider); + OHOS::Print::TestAddPrinterToCups(data, size, &dataProvider); + OHOS::Print::TestQueryPrinterCapabilityByUri(data, size, &dataProvider); + OHOS::Print::TestDeleteCupsPrinter(data, size, &dataProvider); + OHOS::Print::TestAddCupsPrintJob(data, size, &dataProvider); + OHOS::Print::TestCancelCupsJob(data, size, &dataProvider); + OHOS::Print::TestQueryAddedPrinterList(data, size, &dataProvider); + OHOS::Print::TestGetPPDFile(data, size, &dataProvider); + OHOS::Print::TestSetDefaultPrinter(data, size, &dataProvider); + OHOS::Print::TestQueryPrinterAttrList(data, size, &dataProvider); + OHOS::Print::TestQueryPrinterInfoByPrinterId(data, size, &dataProvider); + OHOS::Print::TestDeletePrinterFromCups(data, size, &dataProvider); + OHOS::Print::TestJobCompleteCallback(data, size, &dataProvider); + OHOS::Print::TestCheckPrinterMakeModel(data, size, &dataProvider); + OHOS::Print::TestCheckPrinterOnline(data, size, &dataProvider); + OHOS::Print::TestDumpJobParameters(data, size, &dataProvider); + OHOS::Print::TestGetMedieSize(data, size, &dataProvider); + OHOS::Print::TestGetColorString(data, size, &dataProvider); + OHOS::Print::TestConvertInchTo100MM(data, size, &dataProvider); + OHOS::Print::TestGetIpAddress(data, size, &dataProvider); + + return 0; +} diff --git a/test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.h b/test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.h new file mode 100644 index 0000000..3ab774d --- /dev/null +++ b/test/fuzztest/printcupsclient_fuzzer/printcupsclient_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_PRINT_CUPS_CLIENT_FUZZER_H +#define OHOS_PRINT_CUPS_CLIENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "printcupsclient_fuzzer" + +#endif // OHOS_PRINT_CUPS_CLIENT_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/printcupsclient_fuzzer/project.xml b/test/fuzztest/printcupsclient_fuzzer/project.xml new file mode 100644 index 0000000..58f8171 --- /dev/null +++ b/test/fuzztest/printcupsclient_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/printservice_fuzzer/printservice_fuzzer.cpp b/test/fuzztest/printservice_fuzzer/printservice_fuzzer.cpp index 748eef1..e300b86 100644 --- a/test/fuzztest/printservice_fuzzer/printservice_fuzzer.cpp +++ b/test/fuzztest/printservice_fuzzer/printservice_fuzzer.cpp @@ -25,22 +25,17 @@ namespace Print { constexpr size_t U32_AT_SIZE = 4; const std::u16string PRINT_SERVICE_INTERFACE_TOKEN = u"OHOS.Print.IPrintService"; - uint32_t GetU32Data(const char* ptr) - { - // 将第0个数字左移24位,将第1个数字左移16位,将第2个数字左移8位,第3个数字不左移 - return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]); - } - bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) { - uint32_t code = GetU32Data(data); - MessageParcel datas; - datas.WriteInterfaceToken(PRINT_SERVICE_INTERFACE_TOKEN); - datas.WriteBuffer(data, size); - datas.RewindRead(0); - MessageParcel reply; - MessageOption option; - PrintServiceAbility::GetInstance()->OnRemoteRequest(code, datas, reply, option); + for (uint32_t code = CMD_START_PRINT; code <= CMD_NOTIFY_PRINT_SERVICE; ++code) { + MessageParcel datas; + datas.WriteInterfaceToken(PRINT_SERVICE_INTERFACE_TOKEN); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + PrintServiceAbility::GetInstance()->OnRemoteRequest(code, datas, reply, option); + } return true; } } diff --git a/test/fuzztest/printserviceability_fuzzer/BUILD.gn b/test/fuzztest/printserviceability_fuzzer/BUILD.gn new file mode 100644 index 0000000..05163be --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/BUILD.gn @@ -0,0 +1,113 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/print/print_fwk/print.gni") +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PrintServiceAbilityFuzzTest") { + module_out_path = fuzz_test_output_path + + fuzz_config_file = "${print_path}/test/fuzztest/printserviceability_fuzzer" + + include_dirs = [ + "mock", + "${print_path}/frameworks/innerkitsimpl/print_impl/include", + "${print_utils_path}/include", + "//third_party/cpp-httplib", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + cflags_cc = [] + + deps = [ + "${print_path}/etc/init:printservice.rc", + "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", + "${print_path}/frameworks/kits/extension:print_extension_framework", + "${print_path}/frameworks/kits/extension:print_extension_module", + "${print_path}/frameworks/models/print_models:print_models", + "${print_path}/interfaces/kits/jsnapi/print_extension:printextensionability_napi", + "${print_path}/interfaces/kits/jsnapi/print_extensionctx:printextensioncontext_napi", + "${print_path}/interfaces/kits/napi/print_napi:print_napi", + "${print_path}/profile:print_sa_profiles", + "${print_path}/services/print_service:print_service", + ] + + sources = [ + "printserviceability_fuzzer.cpp", + "printserviceability_mock_permission.cpp", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "drivers_interface_usb:libusb_proxy_1.0", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "os_account:os_account_innerkits", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "usb_manager:usbsrv_client", + "wifi:wifi_sdk", + ] + + if (cups_enable) { + cflags_cc += [ "-DCUPS_ENABLE" ] + external_deps += [ + "cJSON:cjson", + "cups:cups", + "cups-filters:cupsfilters", + ] + } + + if (security_guard_enabled) { + external_deps += [ + "security_guard:libsg_collect_sdk", + "time_service:time_client", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PrintServiceAbilityFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/printserviceability_fuzzer/curpus/init b/test/fuzztest/printserviceability_fuzzer/curpus/init new file mode 100644 index 0000000..6198079 --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/curpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/printserviceability_fuzzer/mock/print_service_ability_mock_permission.h b/test/fuzztest/printserviceability_fuzzer/mock/print_service_ability_mock_permission.h new file mode 100644 index 0000000..365f940 --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/mock/print_service_ability_mock_permission.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_SERVICE_ABILITY_MOCK_PERMISSION_H +#define PRINT_SERVICE_ABILITY_MOCK_PERMISSION_H + +namespace OHOS { +namespace Print { +class PrintServiceAbilityMockPermission { +public: + static void MockPermission(); +}; +} // namespace Print +} // namespace OHOS +#endif // PRINT_SERVICE_ABILITY_MOCK_PERMISSION_H \ No newline at end of file diff --git a/test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.cpp b/test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.cpp new file mode 100644 index 0000000..09b1b5a --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.cpp @@ -0,0 +1,845 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define private public +#define protected public +#include "printserviceability_fuzzer.h" +#include "fuzzer/FuzzedDataProvider.h" +#include "print_constant.h" +#include "printer_capability.h" +#include "print_log.h" +#include "print_service_ability.h" +#include "print_service_ability_mock_permission.h" + +namespace OHOS { +namespace Print { +constexpr uint8_t MAX_STRING_LENGTH = 255; +constexpr int MAX_SET_NUMBER = 100; +constexpr size_t U32_AT_SIZE = 4; +static constexpr const char *JOB_OPTIONS = + "{\"jobName\":\"xx\",\"jobNum\":1,\"mediaType\":\"stationery\",\"documentCategory\":0,\"printQuality\":\"4\"," + "\"printerName\":\"printer1\",\"printerUri\":\"ipp://192.168.0.1:111/ipp/print\"," + "\"documentFormat\":\"application/pdf\",\"files\":[\"/data/1.pdf\"]}"; + +void TestStartService(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->StartService(); +} + +void TestStartPrint(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string fileUri = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector fileList; + fileList.push_back(fileUri); + uint32_t fd = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + std::vector fdList; + fdList.push_back(fd); + std::string taskId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->StartPrint(fileList, fdList, taskId); +} + +void TestStopPrint(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string taskId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->StopPrint(taskId); +} + +void TestConnectPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->ConnectPrinter(printerId); +} + +void TestDisconnectPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->DisconnectPrinter(printerId); +} + +void TestStartDiscoverPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string extensionId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector extensionIds; + extensionIds.push_back(extensionId); + PrintServiceAbility::GetInstance()->StartDiscoverPrinter(extensionIds); +} + +void TestStopDiscoverPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->StopDiscoverPrinter(); +} + +void TestQueryAllExtension(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintExtensionInfo printExtensionInfo; + printExtensionInfo.SetExtensionId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector printExtensionInfos; + printExtensionInfos.push_back(printExtensionInfo); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->QueryAllExtension(printExtensionInfos); +} + +void TestStartPrintJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintJob testJob; + testJob.SetJobId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + testJob.SetOption(JOB_OPTIONS); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->StartPrintJob(testJob); +} + +void TestCancelPrintJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->CancelPrintJob(jobId); +} + +void TestAddPrinters(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrinterInfo printerInfo; + printerInfo.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printerInfo.SetPrinterName(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printerInfo.SetOption(JOB_OPTIONS); + std::vector printerInfos; + printerInfos.push_back(printerInfo); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->AddPrinters(printerInfos); +} + +void TestRemovePrinters(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector printerIds; + printerIds.push_back(printerId); + PrintServiceAbility::GetInstance()->RemovePrinters(printerIds); +} + +void TestUpdatePrinters(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrinterInfo printerInfo; + printerInfo.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printerInfo.SetPrinterName(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printerInfo.SetOption(JOB_OPTIONS); + std::vector printerInfos; + printerInfos.push_back(printerInfo); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->UpdatePrinters(printerInfos); + return; +} + +void TestUpdatePrinterState(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + uint32_t state = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->UpdatePrinterState(printerId, state); +} + +void TestUpdatePrintJobStateOnlyForSystemApp(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + uint32_t state = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + uint32_t subState = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->UpdatePrintJobStateOnlyForSystemApp(jobId, state, subState); +} + +void TestUpdateExtensionInfo(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string extInfo = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->UpdateExtensionInfo(extInfo); +} + +void TestRequestPreview(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintJob printJob; + printJob.SetJobId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector files = {1}; + printJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printJob.SetPageSize(pageSize); + printJob.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printJob.SetOption(JOB_OPTIONS); + std::string previewResult = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->RequestPreview(printJob, previewResult); + return; +} + +void TestQueryPrinterCapability(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->QueryPrinterCapability(printerId); +} + +void TestOn(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string taskId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string type = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->On(taskId, type, nullptr); +} + +void TestOff(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string taskId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string type = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->Off(taskId, type); +} + +void TestRegisterPrinterCallback(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string type = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->RegisterPrinterCallback(type, nullptr); +} + +void TestUnregisterPrinterCallback(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string type = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->UnregisterPrinterCallback(type); +} + +void TestRegisterExtCallback(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string extensionCID = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->RegisterExtCallback(extensionCID, nullptr); +} + +void TestUnregisterAllExtCallback(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string extensionCID = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->UnregisterAllExtCallback(extensionCID); +} + +void TestLoadExtSuccess(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string extensionId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->LoadExtSuccess(extensionId); +} + +void TestQueryAllPrintJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintJob printJob; + printJob.SetJobId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector files = {0}; + printJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printJob.SetPageSize(pageSize); + printJob.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector printJobs; + printJobs.push_back(printJob); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->QueryAllPrintJob(printJobs); +} + +void TestQueryPrintJobById(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintJob printJob; + printJob.SetJobId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector files = {0}; + printJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printJob.SetPageSize(pageSize); + printJob.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::string printJobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->QueryPrintJobById(printJobId, printJob); +} + +void TestAddPrinterToCups(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerUri = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerMake = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->AddPrinterToCups(printerUri, printerName, printerMake); +} + +void TestQueryPrinterCapabilityByUri(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerUri = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrinterCapability printerCaps; + PrintServiceAbility::GetInstance()->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps); +} + +void TestSetHelper(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->SetHelper(nullptr); +} + +void TestPrintByAdapter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + std::string jobName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintAttributes printAttributes; + std::string taskId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->PrintByAdapter(jobName, printAttributes, taskId); +} + +void TestStartGetPrintFile(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintAttributes printAttributes; + uint32_t fd = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->StartGetPrintFile(jobId, printAttributes, fd); +} + +void TestQueryPrinterInfoByPrinterId(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrinterInfo printerInfo; + printerInfo.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printerInfo.SetPrinterName(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printerInfo.SetOption(JOB_OPTIONS); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->QueryPrinterInfoByPrinterId(printerId, printerInfo); +} + +void TestNotifyPrintService(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string type = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->NotifyPrintService(jobId, type); +} + +void TestQueryAddedPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector printerNameList; + printerNameList.push_back(printerName); + PrintServiceAbility::GetInstance()->QueryAddedPrinter(printerNameList); +} + +void TestQueryPrinterProperties(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string key = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector keyList; + keyList.push_back(key); + std::string value = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector valueList; + valueList.push_back(value); + PrintServiceAbility::GetInstance()->QueryPrinterProperties(printerId, keyList, valueList); +} + +void TestUpdatePrintJobState(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + uint32_t state = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + uint32_t subState = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->UpdatePrintJobState(jobId, state, subState); +} + +void TestGetPrinterPreference(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerPreference = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->GetPrinterPreference(printerId, printerPreference); +} + +void TestSetPrinterPreference(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerPreference = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->SetPrinterPreference(printerId, printerPreference); +} + +void TestSetDefaultPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->SetDefaultPrinter(printerId); +} + +void TestDeletePrinterFromCups(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printerMake = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->DeletePrinterFromCups(printerId, printerName, printerMake); +} + +void TestDestroyExtension(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->DestroyExtension(); +} + +void TestStartNativePrintJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintJob printJob; + PrintServiceAbility::GetInstance()->StartNativePrintJob(printJob); +} + +void TestNotifyPrintServiceEvent(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + uint32_t event = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->NotifyPrintServiceEvent(jobId, event); +} + +void TestSomePublicFunction(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + TestQueryAllPrintJob(data, size, dataProvider); + TestQueryPrintJobById(data, size, dataProvider); + TestAddPrinterToCups(data, size, dataProvider); + TestQueryPrinterCapabilityByUri(data, size, dataProvider); + TestSetHelper(data, size, dataProvider); + TestPrintByAdapter(data, size, dataProvider); + TestStartGetPrintFile(data, size, dataProvider); + TestNotifyPrintService(data, size, dataProvider); + TestQueryPrinterInfoByPrinterId(data, size, dataProvider); + TestQueryAddedPrinter(data, size, dataProvider); + TestQueryPrinterProperties(data, size, dataProvider); + TestUpdatePrintJobState(data, size, dataProvider); + TestGetPrinterPreference(data, size, dataProvider); + TestSetPrinterPreference(data, size, dataProvider); + TestSetDefaultPrinter(data, size, dataProvider); + TestDeletePrinterFromCups(data, size, dataProvider); + TestDestroyExtension(data, size, dataProvider); + TestStartNativePrintJob(data, size, dataProvider); + TestNotifyPrintServiceEvent(data, size, dataProvider); +} + +// below are private test +void TestUpdateQueuedJobList(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printJobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + auto printJob = std::make_shared(); + printJob->SetJobId(printJobId); + printJob->SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->UpdateQueuedJobList(printJobId, printJob); +} + +void TestUpdatePrintJobOptionByPrinterId(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbilityMockPermission::MockPermission(); + PrintJob printJob; + printJob.SetJobId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + std::vector files = {0}; + printJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + printJob.SetPageSize(pageSize); + printJob.SetPrinterId(dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH)); + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->UpdatePrintJobOptionByPrinterId(printJob); +} + +void TestDelayStartDiscovery(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string extensionId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->DelayStartDiscovery(extensionId); +} + +void TestBuildFDParam(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + uint32_t fd = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + std::vector fdList; + fdList.push_back(fd); + AAFwk::Want want; + PrintServiceAbility::GetInstance()->BuildFDParam(fdList, want); +} + +void TestAdapterGetFileCallBack(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + uint32_t state = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + uint32_t subState = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->AdapterGetFileCallBack(jobId, state, subState); +} + +void TestAddNativePrintJob(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintJob printJob; + PrintServiceAbility::GetInstance()->AddNativePrintJob(jobId, printJob); +} + +void TestIsQueuedJobListEmpty(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->IsQueuedJobListEmpty(jobId); +} + +void TestSetPrintJobCanceled(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintJob printJob; + PrintServiceAbility::GetInstance()->SetPrintJobCanceled(printJob); +} + +void TestCancelUserPrintJobs(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + int32_t userId = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->CancelUserPrintJobs(userId); +} + +void TestSendExtensionEvent(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string extensionId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string extInfo = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->SendExtensionEvent(extensionId, extInfo); +} + +void TestgetPrinterInfo(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->getPrinterInfo(printerId); +} + +void TestCallStatusBar(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->CallStatusBar(); +} + +void TestUpdatePrintUserMap(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->UpdatePrintUserMap(); +} + +void TestnotifyAdapterJobChanged(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + uint32_t state = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + uint32_t subState = dataProvider->ConsumeIntegralInRange(0, MAX_SET_NUMBER); + PrintServiceAbility::GetInstance()->notifyAdapterJobChanged(jobId, state, subState); +} + +void TestRegisterAdapterListener(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string jobId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->RegisterAdapterListener(jobId); +} + +void TestisEprint(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->isEprint(printerId); +} + +void TestManualStart(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->ManualStart(); +} + +void TestGetPrintJobOrderId(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->GetPrintJobOrderId(); +} + +void TestOnStop(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->OnStop(); +} + +void TestWritePreferenceToFile(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintServiceAbility::GetInstance()->WritePreferenceToFile(); +} + +void TestBuildPrinterPreference(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string option = "{\ + \"cupsOptions\" : {\ + \"supportedPageSizeArray\" : \"String\",\ + \"orientation-requested-supported\" : \"String\",\ + \"print-quality-supported\" : \"String\"\ + }\ + }"; + PrinterCapability cap; + cap.SetOption(option); + PrinterPreference printPreference; + PrintServiceAbility::GetInstance()->BuildPrinterPreference(cap, printPreference); +} + +void TestBuildPrinterPreferenceByDefault(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string optJson = "{\ + \"defaultPageSizeId\" : \"String\",\ + \"orientation-requested-default\" : \"String\",\ + \"sides-default\" : \"String\",\ + \"print-quality-default\" : \"String\"\ + }"; + nlohmann::json capOpt = nlohmann::json::parse(optJson); + PreferenceSetting printerDefaultAttr; + PrintServiceAbility::GetInstance()->BuildPrinterPreferenceByDefault(capOpt, printerDefaultAttr); +} + +void TestBuildPrinterPreferenceByOption(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string key = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string supportedOpts = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string optAttr = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector optAttrs; + optAttrs.push_back(optAttr); + PrintServiceAbility::GetInstance()->BuildPrinterPreferenceByOption(key, supportedOpts, optAttrs); +} + +void TestBuildPrinterAttrComponentByJson(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string key = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string arrObject = "{\ + \"cupsOptions\" : [\ + \"supportedPageSizeArray\", \ + \"orientation-requested-supported\", \ + \"print-quality-supported\"\ + ]\ + }"; + nlohmann::json jsonArrObject = nlohmann::json::parse(arrObject); + std::string printerAttr = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::vector printerAttrs; + printerAttrs.push_back(printerAttr); + PrintServiceAbility::GetInstance()->BuildPrinterAttrComponentByJson(key, jsonArrObject, printerAttrs); +} + +void TestCheckIsDefaultPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->CheckIsDefaultPrinter(printerId); +} + +void TestCheckIsLastUsedPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->CheckIsLastUsedPrinter(printerName); +} + +void TestSetLastUsedPrinter(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->SetLastUsedPrinter(printerId); +} + +void TestSendPrintJobEvent(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + PrintJob jobInfo; + uint32_t jobStateArr[] = {PRINT_JOB_COMPLETED, PRINT_JOB_BLOCKED, PRINT_JOB_COMPLETED}; + for (auto jobState : jobStateArr) { + jobInfo.SetJobState(jobState); + PrintServiceAbility::GetInstance()->SendPrintJobEvent(jobInfo); + } +} + +void TestReadPreferenceFromFile(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + std::string printPreference = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->ReadPreferenceFromFile(printerId, printPreference); +} + +void TestReportCompletedPrint(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string printerId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->ReportCompletedPrint(printerId); +} + +void TestNotifyAppJobQueueChanged(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + std::string applyResult = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); + PrintServiceAbility::GetInstance()->NotifyAppJobQueueChanged(applyResult); +} + +void TestConvertToPrintExtensionInfo(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + PrintServiceAbility::GetInstance()->Init(); + AppExecFwk::ExtensionAbilityInfo extInfo; + PrintServiceAbility::GetInstance()->ConvertToPrintExtensionInfo(extInfo); +} + +void TestNotPublicFunction(const uint8_t *data, size_t size, FuzzedDataProvider *dataProvider) +{ + TestUpdateQueuedJobList(data, size, dataProvider); + TestUpdatePrintJobOptionByPrinterId(data, size, dataProvider); + TestDelayStartDiscovery(data, size, dataProvider); + TestBuildFDParam(data, size, dataProvider); + TestAdapterGetFileCallBack(data, size, dataProvider); + TestAddNativePrintJob(data, size, dataProvider); + TestIsQueuedJobListEmpty(data, size, dataProvider); + TestSetPrintJobCanceled(data, size, dataProvider); + TestCancelUserPrintJobs(data, size, dataProvider); + TestSendExtensionEvent(data, size, dataProvider); + TestgetPrinterInfo(data, size, dataProvider); + TestCallStatusBar(data, size, dataProvider); + TestUpdatePrintUserMap(data, size, dataProvider); + TestnotifyAdapterJobChanged(data, size, dataProvider); + TestRegisterAdapterListener(data, size, dataProvider); + TestisEprint(data, size, dataProvider); + TestWritePreferenceToFile(data, size, dataProvider); + TestBuildPrinterPreferenceByOption(data, size, dataProvider); + TestBuildPrinterPreference(data, size, dataProvider); + TestBuildPrinterPreferenceByDefault(data, size, dataProvider); + TestBuildPrinterPreferenceByOption(data, size, dataProvider); + TestBuildPrinterAttrComponentByJson(data, size, dataProvider); + TestCheckIsDefaultPrinter(data, size, dataProvider); + TestCheckIsLastUsedPrinter(data, size, dataProvider); + TestSetLastUsedPrinter(data, size, dataProvider); + TestSendPrintJobEvent(data, size, dataProvider); + TestReadPreferenceFromFile(data, size, dataProvider); + TestReportCompletedPrint(data, size, dataProvider); + TestNotifyAppJobQueueChanged(data, size, dataProvider); + TestConvertToPrintExtensionInfo(data, size, dataProvider); +} + +} // namespace Print +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + if (size < OHOS::Print::U32_AT_SIZE) { + } + + FuzzedDataProvider dataProvider(data, size); + OHOS::Print::TestStartService(data, size, &dataProvider); + OHOS::Print::TestStartPrint(data, size, &dataProvider); + OHOS::Print::TestStopPrint(data, size, &dataProvider); + OHOS::Print::TestConnectPrinter(data, size, &dataProvider); + OHOS::Print::TestDisconnectPrinter(data, size, &dataProvider); + OHOS::Print::TestStartDiscoverPrinter(data, size, &dataProvider); + OHOS::Print::TestStopDiscoverPrinter(data, size, &dataProvider); + // OHOS::Print::TestQueryAllExtension(data, size, &dataProvider); + OHOS::Print::TestStartPrintJob(data, size, &dataProvider); + OHOS::Print::TestCancelPrintJob(data, size, &dataProvider); + OHOS::Print::TestAddPrinters(data, size, &dataProvider); + OHOS::Print::TestRemovePrinters(data, size, &dataProvider); + OHOS::Print::TestUpdatePrinters(data, size, &dataProvider); + OHOS::Print::TestUpdatePrinterState(data, size, &dataProvider); + OHOS::Print::TestUpdatePrintJobStateOnlyForSystemApp(data, size, &dataProvider); + OHOS::Print::TestUpdateExtensionInfo(data, size, &dataProvider); + OHOS::Print::TestRequestPreview(data, size, &dataProvider); + OHOS::Print::TestQueryPrinterCapability(data, size, &dataProvider); + OHOS::Print::TestOn(data, size, &dataProvider); + OHOS::Print::TestOff(data, size, &dataProvider); + OHOS::Print::TestRegisterPrinterCallback(data, size, &dataProvider); + OHOS::Print::TestUnregisterPrinterCallback(data, size, &dataProvider); + OHOS::Print::TestRegisterExtCallback(data, size, &dataProvider); + OHOS::Print::TestUnregisterAllExtCallback(data, size, &dataProvider); + OHOS::Print::TestLoadExtSuccess(data, size, &dataProvider); + OHOS::Print::TestSomePublicFunction(data, size, &dataProvider); + OHOS::Print::TestNotPublicFunction(data, size, &dataProvider); + return 0; +} diff --git a/test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.h b/test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.h new file mode 100644 index 0000000..54c8dae --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/printserviceability_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_PRINT_SERVICE_ABILITY_FUZZER_H +#define OHOS_PRINT_SERVICE_ABILITY_FUZZER_H + +#define FUZZ_PROJECT_NAME "printserviceability_fuzzer" + +#endif // OHOS_PRINT_SERVICE_ABILITY_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/printserviceability_fuzzer/printserviceability_mock_permission.cpp b/test/fuzztest/printserviceability_fuzzer/printserviceability_mock_permission.cpp new file mode 100644 index 0000000..4f53c06 --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/printserviceability_mock_permission.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_service_ability_mock_permission.h" + +#include "nativetoken_kit.h" +#include "token_setproc.h" + +namespace OHOS { +namespace Print { +void PrintServiceAbilityMockPermission::MockPermission() +{ + static const char *PERMS[] = { + "ohos.permission.PRINT", + "ohos.permission.MANAGE_PRINT_JOB" + }; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = PERMS, + .acls = nullptr, + .processName = "print_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); +} +} +} \ No newline at end of file diff --git a/test/fuzztest/printserviceability_fuzzer/project.xml b/test/fuzztest/printserviceability_fuzzer/project.xml new file mode 100644 index 0000000..58f8171 --- /dev/null +++ b/test/fuzztest/printserviceability_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/unittest/fwk_inner_napi_test/BUILD.gn b/test/unittest/fwk_inner_napi_test/BUILD.gn index e264514..b86da8c 100644 --- a/test/unittest/fwk_inner_napi_test/BUILD.gn +++ b/test/unittest/fwk_inner_napi_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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 @@ -14,7 +14,7 @@ import("//base/print/print_fwk/print.gni") import("//build/test.gni") -module_output_path = "print/print_fwk" +module_output_path = "print_fwk/fwk_inner_napi_test" ohos_unittest("print_fwk_inner_napi_test") { module_out_path = module_output_path diff --git a/test/unittest/fwk_inner_napi_test/mock/mock_print_manager_client.h b/test/unittest/fwk_inner_napi_test/mock/mock_print_manager_client.h new file mode 100644 index 0000000..9769ac7 --- /dev/null +++ b/test/unittest/fwk_inner_napi_test/mock/mock_print_manager_client.h @@ -0,0 +1,30 @@ +/* + * 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 MOCK_PRINT_MANAGER_CLIENT_H +#define MOCK_PRINT_MANAGER_CLIENT_H + +#include +#include "print_manager_client.h" + +namespace OHOS { +namespace Print { +class MockPrintManagerClient final : public PrintManagerClient { +public: + MOCK_METHOD0(LoadServer, bool()); + MOCK_METHOD0(GetPrintServiceProxy, bool()); +}; +} // namespace Print +} // namespace OHOS +#endif // MOCK_PRINT_MANAGER_CLIENT_H diff --git a/test/unittest/fwk_inner_napi_test/print_attributes_test.cpp b/test/unittest/fwk_inner_napi_test/print_attributes_test.cpp index 40ad37a..79fb4d4 100644 --- a/test/unittest/fwk_inner_napi_test/print_attributes_test.cpp +++ b/test/unittest/fwk_inner_napi_test/print_attributes_test.cpp @@ -62,6 +62,19 @@ OHOS::Print::PrintAttributes PrintAttributesTest::GetDefaultPrintAttributes() return printAttributes; } +/** + * @tc.name: PrintAttributesTest_001 + * @tc.desc: Verify the Dump function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintAttributesTest, PrintAttributesTest_001, TestSize.Level1) +{ + OHOS::Print::PrintAttributes printAttributes(GetDefaultPrintAttributes()); + printAttributes.Dump(); + printAttributes.~PrintAttributes(); +} + /** * @tc.name: PrintAttributesTest_002 * @tc.desc: Verify the UpdateParams function. @@ -255,5 +268,20 @@ HWTEST_F(PrintAttributesTest, PrintAttributesTest_0014, TestSize.Level1) auto result = OHOS::Print::PrintAttributes::Unmarshalling(parcel); EXPECT_NE(nullptr, result); } + +/** + * @tc.name: PrintAttributesTest_0015 + * @tc.desc: Verify the marshalling function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintAttributesTest, PrintAttributesTest_0015, TestSize.Level1) +{ + OHOS::Print::PrintAttributes printAttributes; + printAttributes.Dump(); + Parcel parcel; + EXPECT_FALSE(printAttributes.ReadFromParcel(parcel)); +} + } // namespace Print } // namespace OHOS diff --git a/test/unittest/fwk_inner_napi_test/print_manager_client_test.cpp b/test/unittest/fwk_inner_napi_test/print_manager_client_test.cpp index 1bceeaa..c6b3de8 100644 --- a/test/unittest/fwk_inner_napi_test/print_manager_client_test.cpp +++ b/test/unittest/fwk_inner_napi_test/print_manager_client_test.cpp @@ -15,7 +15,9 @@ #include #include +#define private public #include "print_manager_client.h" +#undef private #include "iservice_registry.h" #include "print_constant.h" @@ -26,6 +28,7 @@ #include "mock_print_service.h" #include "mock_remote_object.h" #include "mock_print_callback_stub.h" +#include "mock_print_manager_client.h" using namespace testing; using namespace testing::ext; @@ -1069,7 +1072,7 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0052, TestSize.Level1) /** * @tc.name: PrintManagerClientTest_0053 - * @tc.desc: UpdatePrintJobState + * @tc.desc: UpdatePrintJobStateOnlyForSystemApp * @tc.type: FUNC * @tc.require: */ @@ -1079,13 +1082,13 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0053, TestSize.Level1) uint32_t state = 6; uint32_t subState = 6; PrintManagerClient::GetInstance()->LoadServerFail(); - int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobState(printerId, state, subState); + int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp(printerId, state, subState); EXPECT_EQ(ret, E_PRINT_NO_PERMISSION); } /** * @tc.name: PrintManagerClientTest_0054 -* @tc.desc: UpdatePrintJobState +* @tc.desc: UpdatePrintJobStateOnlyForSystemApp * @tc.type: FUNC * @tc.require: */ @@ -1096,7 +1099,7 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0054, TestSize.Level1) uint32_t subState = 6; PrintManagerClient::GetInstance()->LoadServerSuccess(); PrintManagerClient::GetInstance()->ResetProxy(); - int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobState(printerId, state, subState); + int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp(printerId, state, subState); EXPECT_EQ(ret, E_PRINT_NO_PERMISSION); } @@ -1113,13 +1116,13 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0055, TestSize.Level1) uint32_t subState = 6; PrintManagerClient::GetInstance()->LoadServerFail(); PrintManagerClient::GetInstance()->ResetProxy(); - int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobState(printerId, state, subState); + int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp(printerId, state, subState); EXPECT_EQ(ret, E_PRINT_NO_PERMISSION); } /** * @tc.name: PrintManagerClientTest_0056 -* @tc.desc: UpdatePrintJobState +* @tc.desc: UpdatePrintJobStateOnlyForSystemApp * @tc.type: FUNC * @tc.require: */ @@ -1130,8 +1133,8 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0056, TestSize.Level1) uint32_t testSubState = 6; auto service = std::make_shared(); EXPECT_NE(service, nullptr); - EXPECT_CALL(*service, UpdatePrintJobState(_, _, _)).Times(1); - ON_CALL(*service, UpdatePrintJobState).WillByDefault( + EXPECT_CALL(*service, UpdatePrintJobStateOnlyForSystemApp(_, _, _)).Times(1); + ON_CALL(*service, UpdatePrintJobStateOnlyForSystemApp).WillByDefault( [&testPrinterId, &testState, &testSubState](const std::string &printerId, const uint32_t &state, const uint32_t &subState) { EXPECT_EQ(testPrinterId, printerId); @@ -1143,7 +1146,8 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0056, TestSize.Level1) sptr dr = nullptr; CallRemoteObject(service, obj, dr); PrintManagerClient::GetInstance()->LoadServerSuccess(); - int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobState(testPrinterId, testState, testSubState); + int32_t ret = + PrintManagerClient::GetInstance()->UpdatePrintJobStateOnlyForSystemApp(testPrinterId, testState, testSubState); EXPECT_EQ(ret, E_PRINT_NONE); EXPECT_NE(dr, nullptr); dr->OnRemoteDied(obj); @@ -2150,50 +2154,6 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0108, TestSize.Level1) dr->OnRemoteDied(obj); } -/** -* @tc.name: PrintManagerClientTest_0109 -* @tc.desc: LoadServerFail -* @tc.type: FUNC -* @tc.require: -*/ -HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0109, TestSize.Level1) -{ - std::vector testFileList = {"file://data/print/a.png", - "file://data/print/b.png", "file://data/print/c.png"}; - std::vector testFdList = {1, 2}; - std::string testTaskId = "2"; - sptr testToken; - - PrintManagerClient::GetInstance()->LoadServerFail(); - PrintManagerClient::GetInstance()->StartPrint(testFileList, testFdList, testTaskId, testToken); -} - -HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0110, TestSize.Level1) -{ - std::vector testFileList = {"file://data/print/a.png", - "file://data/print/b.png", "file://data/print/c.png"}; - std::vector testFdList = {1, 2}; - std::string testTaskId = "2"; - sptr testToken; - - PrintManagerClient::GetInstance()->LoadServerSuccess(); - PrintManagerClient::GetInstance()->ResetProxy(); - PrintManagerClient::GetInstance()->StartPrint(testFileList, testFdList, testTaskId, testToken); -} - -HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0111, TestSize.Level1) -{ - std::vector testFileList = {"file://data/print/a.png", - "file://data/print/b.png", "file://data/print/c.png"}; - std::vector testFdList = {1, 2}; - std::string testTaskId = "2"; - sptr testToken; - - PrintManagerClient::GetInstance()->LoadServerFail(); - PrintManagerClient::GetInstance()->ResetProxy(); - PrintManagerClient::GetInstance()->StartPrint(testFileList, testFdList, testTaskId, testToken); -} - HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0112, TestSize.Level1) { std::string printerUri; @@ -2269,5 +2229,291 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0119, TestSize.Level1) PrintManagerClient::GetInstance()->LoadServerSuccess(); PrintManagerClient::GetInstance()->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps); } + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0121, TestSize.Level1) +{ + OHOS::Print::PrinterInfo printerInfo; + std::string printerId = "printId-123"; + printerInfo.SetPrinterId(printerId); + printerInfo.SetPrinterName("1"); + printerInfo.SetPrinterIcon(1); + printerInfo.SetPrinterState(1); + printerInfo.SetDescription("111"); + const PrinterCapability capability; + printerInfo.SetCapability(capability); + const std::string option = "1"; + printerInfo.SetOption(option); + + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->QueryPrinterInfoByPrinterId(printerId, printerInfo); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0122, TestSize.Level1) +{ + std::vector printerNameList; + printerNameList.push_back("1"); + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->QueryAddedPrinter(printerNameList); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0123, TestSize.Level1) +{ + std::string printerId = "printId-123"; + std::vector keyList; + std::vector valueList; + keyList.push_back("1"); + valueList.push_back("1"); + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->QueryPrinterProperties(printerId, keyList, valueList); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0124, TestSize.Level1) +{ + std::string testPrintJobId = "jobId-123"; + PrintJob testPrintJob; + testPrintJob.SetJobId("jobId-123"); + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->StartNativePrintJob(testPrintJob); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0125, TestSize.Level1) +{ + std::string printJobName = "jobName-123"; + sptr testListener; + PrintAttributes testPrintAttributes; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->Print(printJobName, testListener, testPrintAttributes); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0126, TestSize.Level1) +{ + std::string printJobName = "jobName-123"; + sptr testListener; + PrintAttributes testPrintAttributes; + void* contextToken = nullptr; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->Print(printJobName, testListener, testPrintAttributes, contextToken); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0127, TestSize.Level1) +{ + std::string printJobName = "jobName-123"; + sptr testListener; + PrintAttributes testPrintAttributes; + std::string taskId = "1"; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->Print(printJobName, testListener, testPrintAttributes, taskId); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0128, TestSize.Level1) +{ + std::string printJobName = "jobName-123"; + sptr testListener; + PrintAttributes testPrintAttributes; + std::string taskId = "1"; + void* contextToken = nullptr; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->Print(printJobName, testListener, testPrintAttributes, taskId, contextToken); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0129, TestSize.Level1) +{ + std::string jobId = "1"; + PrintAttributes testPrintAttributes; + uint32_t fd = 0; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->StartGetPrintFile(jobId, testPrintAttributes, fd); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0130, TestSize.Level1) +{ + std::string jobId = "1"; + std::string type = ""; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->NotifyPrintService(jobId, type); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0131, TestSize.Level1) +{ + char callerFunN[] = "testName"; + char* callerFunName = callerFunN; + std::function)> func = [](sptr) -> int32_t { + return 0; + }; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->runBase(callerFunName, func); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0132, TestSize.Level1) +{ + std::string type = "test"; + NativePrinterChangeCallback cb = nullptr; + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->SetNativePrinterChangeCallback(type, cb); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0133, TestSize.Level1) +{ + PrintManagerClient::GetInstance()->LoadServerSuccess(); + PrintManagerClient::GetInstance()->Init(); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0134, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + mockPrintManagerClient.Init(); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0135, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::vector testFileList = {"file://data/print/a.png", + "file://data/print/b.png", "file://data/print/c.png"}; + std::vector testFdList = {1, 2}; + std::string testTaskId = "2"; + mockPrintManagerClient.StartPrint(testFileList, testFdList, testTaskId); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0137, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::string testTaskId = "2"; + mockPrintManagerClient.StopPrint(testTaskId); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0138, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::string printerId = "2"; + mockPrintManagerClient.ConnectPrinter(printerId); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0139, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::string printerId = "2"; + mockPrintManagerClient.DisconnectPrinter(printerId); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0140, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::vector extensionInfos; + mockPrintManagerClient.QueryAllExtension(extensionInfos); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0141, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::vector testExtensionList = {"extensionId-1", "extensionId-2"}; + mockPrintManagerClient.StartDiscoverPrinter(testExtensionList); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0142, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + mockPrintManagerClient.StopDiscoverPrinter(); + PrintJob jobinfo; + mockPrintManagerClient.StartPrintJob(jobinfo); + std::string testJobId = "jobId-1"; + mockPrintManagerClient.CancelPrintJob(testJobId); + std::vector printerInfos; + mockPrintManagerClient.AddPrinters(printerInfos); + std::vector testPrinterIds = {"printerId-1", "printerId-2"}; + mockPrintManagerClient.RemovePrinters(testPrinterIds); + mockPrintManagerClient.UpdatePrinters(printerInfos); + std::string printerId = "2"; + uint32_t testState = 6; + mockPrintManagerClient.UpdatePrinterState(printerId, testState); + std::string jobId = "jobId-1"; + uint32_t testSubState = 6; + mockPrintManagerClient.UpdatePrintJobStateOnlyForSystemApp(jobId, testState, testSubState); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0143, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + std::string extensionId = "extensionId-1"; + mockPrintManagerClient.UpdateExtensionInfo(extensionId); + PrintJob jobinfo; + std::string previewFilePath = "/data/temp/preview.png"; + mockPrintManagerClient.RequestPreview(jobinfo, previewFilePath); + std::string printerId = "2"; + mockPrintManagerClient.QueryPrinterCapability(printerId); + PrinterInfo printerInfo; + mockPrintManagerClient.QueryPrinterInfoByPrinterId(printerId, printerInfo); + std::vector printerNameList; + printerNameList.push_back("1"); + mockPrintManagerClient.QueryAddedPrinter(printerNameList); + std::vector keyList; + std::vector valueList; + keyList.push_back("1"); + valueList.push_back("1"); + mockPrintManagerClient.QueryPrinterProperties(printerId, keyList, valueList); + mockPrintManagerClient.StartNativePrintJob(jobinfo); + std::vector printJobs; + mockPrintManagerClient.QueryAllPrintJob(printJobs); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0144, TestSize.Level1) +{ + PrintManagerClient::GetInstance()->LoadServerSuccess(); + uint32_t event = 0; + std::string jobId = "jobId"; + PrintManagerClient::GetInstance()->NotifyPrintServiceEvent(jobId, event); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0145, TestSize.Level1) +{ + PrintManagerClient::GetInstance()->LoadServerFail(); + uint32_t event = 0; + std::string jobId = "jobId"; + PrintManagerClient::GetInstance()->NotifyPrintServiceEvent(jobId, event); +} + +HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0146, TestSize.Level1) +{ + MockPrintManagerClient mockPrintManagerClient; + uint32_t event = 0; + std::string jobId = "jobId"; + mockPrintManagerClient.NotifyPrintServiceEvent(jobId, event); + std::string testPrintJobId = "jobId-123"; + PrintJob testPrintJob; + mockPrintManagerClient.QueryPrintJobById(testPrintJobId, testPrintJob); + std::string printerUri; + std::string printerName; + std::string printerMake; + mockPrintManagerClient.AddPrinterToCups(printerUri, printerName, printerMake); + std::string printerId; + PrinterCapability printerCaps; + mockPrintManagerClient.QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps); + std::string testTaskId = "taskId-123"; + std::string testType = "type"; + sptr testListener; + mockPrintManagerClient.On(testTaskId, testType, testListener); + mockPrintManagerClient.Off(testTaskId, testType); + std::string type = ""; + mockPrintManagerClient.NotifyPrintService(jobId, type); + char callerFunN[] = "testName"; + char* callerFunName = callerFunN; + std::function)> func = [](sptr) -> int32_t { + return 0; + }; + mockPrintManagerClient.runBase(callerFunName, func); + std::string testExtensionId = "com.example.ext"; + uint32_t testCallbackId = PRINT_EXTCB_START_DISCOVERY; + PrinterCapabilityCallback testCb = nullptr; + mockPrintManagerClient.RegisterExtCallback(testExtensionId, testCallbackId, testCb); + PrintJobCallback jobCb = nullptr; + mockPrintManagerClient.RegisterExtCallback(testExtensionId, testCallbackId, jobCb); + PrinterCapabilityCallback capCb = nullptr; + mockPrintManagerClient.RegisterExtCallback(testExtensionId, testCallbackId, capCb); + PrinterCallback printerCb = nullptr; + mockPrintManagerClient.RegisterExtCallback(testExtensionId, testCallbackId, printerCb); + mockPrintManagerClient.UnregisterAllExtCallback(testExtensionId); + NativePrinterChangeCallback cb = nullptr; + mockPrintManagerClient.SetNativePrinterChangeCallback(type, cb); + mockPrintManagerClient.LoadExtSuccess(testExtensionId); +} } // namespace Print } // namespace OHOS diff --git a/test/unittest/fwk_inner_napi_test/print_page_size_test.cpp b/test/unittest/fwk_inner_napi_test/print_page_size_test.cpp index 0f35da0..a2474d2 100644 --- a/test/unittest/fwk_inner_napi_test/print_page_size_test.cpp +++ b/test/unittest/fwk_inner_napi_test/print_page_size_test.cpp @@ -53,14 +53,16 @@ HWTEST_F(PrintPageSizeTest, PrintPageSizeTest_0001, TestSize.Level1) /** * @tc.name: PrintPageSizeTest_0002 - * @tc.desc: Verify the getPageSize function. + * @tc.desc: Verify the FindPageSizeById function. * @tc.type: FUNC * @tc.require: */ HWTEST_F(PrintPageSizeTest, PrintPageSizeTest_0002, TestSize.Level1) { - auto pageSize = OHOS::Print::PrintPageSize::GetPageSize(ISO_A3); - EXPECT_EQ((uint32_t)0, pageSize.GetWidth()); + constexpr uint32_t expectWidth = 11690; + OHOS::Print::PrintPageSize printpageSize; + OHOS::Print::PrintPageSize::FindPageSizeById("ISO_A3", printpageSize); + EXPECT_EQ(expectWidth, printpageSize.GetWidth()); } /** diff --git a/test/unittest/fwk_inner_napi_test/print_range_test.cpp b/test/unittest/fwk_inner_napi_test/print_range_test.cpp index 5e04305..459147e 100644 --- a/test/unittest/fwk_inner_napi_test/print_range_test.cpp +++ b/test/unittest/fwk_inner_napi_test/print_range_test.cpp @@ -259,5 +259,21 @@ HWTEST_F(PrintRangeTest, PrintRangeTest_0015, TestSize.Level1) OHOS::Print::PrintRange copyRange = range; EXPECT_EQ(copyRange.GetEndPage(), range.GetEndPage()); } + +/** + * @tc.name: PrintRangeTest_0016 + * @tc.desc: Verify the constructor function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintRangeTest, PrintRangeTest_0016, TestSize.Level1) +{ + OHOS::Print::PrintRange range; + range.SetStartPage(0); + range.SetEndPage(5); + range.SetPages({0, 1, 2, 3, 4, 5}); + range.Dump(); +} + } // namespace Print } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/fwk_inner_napi_test/print_service_proxy_test.cpp b/test/unittest/fwk_inner_napi_test/print_service_proxy_test.cpp index 7799a41..f3495f5 100644 --- a/test/unittest/fwk_inner_napi_test/print_service_proxy_test.cpp +++ b/test/unittest/fwk_inner_napi_test/print_service_proxy_test.cpp @@ -76,7 +76,7 @@ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0001, TestSize.Level1) for (size_t index = 0; index < testFdList.size(); index++) { EXPECT_NE(testFdList[index], fdList[index]); } - EXPECT_NE(testTaskId, taskId); + EXPECT_EQ(testTaskId, taskId); return E_PRINT_NONE; }); EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); @@ -116,7 +116,7 @@ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0002, TestSize.Level1) for (size_t index = 0; index < testFdList.size(); index++) { EXPECT_EQ(testFdList[index], fdList[index]); } - EXPECT_NE(testTaskId, taskId); + EXPECT_EQ(testTaskId, taskId); return E_PRINT_NONE; }); EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); @@ -514,7 +514,7 @@ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0015, TestSize.Level1) EXPECT_NE(proxy, nullptr); auto service = std::make_shared(); EXPECT_NE(service, nullptr); - EXPECT_CALL(*service, UpdatePrintJobState(_, _, _)).Times(Exactly(1)).WillOnce( + EXPECT_CALL(*service, UpdatePrintJobStateOnlyForSystemApp(_, _, _)).Times(Exactly(1)).WillOnce( [&testJobId, &testState, &testSubState](const std::string &jobId, uint32_t state, uint32_t subState) { EXPECT_EQ(testJobId, jobId); @@ -528,7 +528,7 @@ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0015, TestSize.Level1) service->OnRemoteRequest(code, data, reply, option); return E_PRINT_NONE; }); - proxy->UpdatePrintJobState(testJobId, testState, testSubState); + proxy->UpdatePrintJobStateOnlyForSystemApp(testJobId, testState, testSubState); } /** @@ -769,31 +769,91 @@ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0023, TestSize.Level1) proxy->LoadExtSuccess(testExtId); } + +/** + * @tc.name: PrintServiceProxyTest_0024 + * @tc.desc: Verify the capability function. + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0024, TestSize.Level1) { - std::vector testFileList = {"file://data/print/a.png", - "file://data/print/b.png", "file://data/print/c.png"}; - std::vector testFdList = {1, 2}; - std::string testTaskId = "2"; - sptr testToken; + std::string testExtId = "extId-123"; sptr obj = new MockRemoteObject(); EXPECT_NE(obj, nullptr); auto proxy = std::make_shared(obj); - EXPECT_NE(proxy, nullptr); - proxy->StartPrint(testFileList, testFdList, testTaskId, testToken); + EXPECT_EQ(E_PRINT_INVALID_PARAMETER, proxy->RegisterExtCallback(testExtId, nullptr)); } - + +/** + * @tc.name: PrintServiceProxyTest_0025 + * @tc.desc: Verify the capability function. + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0025, TestSize.Level1) { - std::vector testFileList = {}; - std::vector testFdList = {}; - std::string testTaskId = "2"; - sptr testToken; + sptr obj = new MockRemoteObject(); + EXPECT_NE(obj, nullptr); + auto proxy = std::make_shared(obj); + EXPECT_EQ(E_PRINT_INVALID_PARAMETER, proxy->UnregisterPrinterCallback("")); +} + +/** + * @tc.name: PrintServiceProxyTest_0026 + * @tc.desc: Verify the capability function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0026, TestSize.Level1) +{ sptr obj = new MockRemoteObject(); EXPECT_NE(obj, nullptr); auto proxy = std::make_shared(obj); EXPECT_NE(proxy, nullptr); - proxy->StartPrint(testFileList, testFdList, testTaskId, testToken); + auto service = std::make_shared(); + EXPECT_NE(service, nullptr); + const int testRetCode = -259; + EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); + ON_CALL(*obj, SendRequest) + .WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + service->OnRemoteRequest(code, data, reply, option); + return testRetCode; + }); + std::string testJobId = "jobId-123"; + EXPECT_EQ(E_PRINT_RPC_FAILURE, proxy->NotifyPrintServiceEvent(testJobId, 0)); } + +/** + * @tc.name: PrintServiceProxyTest_0027 + * @tc.desc: Verify the capability function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0027, TestSize.Level1) +{ + std::string testTaskId = "taskId-123"; + std::string testType = ""; + sptr obj = new MockRemoteObject(); + EXPECT_NE(obj, nullptr); + auto proxy = std::make_shared(obj); + EXPECT_NE(proxy, nullptr); + auto service = std::make_shared(); + EXPECT_NE(service, nullptr); + EXPECT_CALL(*service, Off(_, _)).Times(Exactly(1)).WillOnce( + [&testTaskId, &testType](const std::string taskId, const std::string &type) { + EXPECT_EQ(testTaskId, taskId); + EXPECT_EQ(testType, type); + return E_PRINT_NONE; + }); + EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); + ON_CALL(*obj, SendRequest) + .WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + service->OnRemoteRequest(code, data, reply, option); + return E_PRINT_NONE; + }); + proxy->Off(testTaskId, testType); +} + } // namespace Print } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/fwk_inner_napi_test/print_utils_test.cpp b/test/unittest/fwk_inner_napi_test/print_utils_test.cpp index 33e3de4..03d1c2d 100644 --- a/test/unittest/fwk_inner_napi_test/print_utils_test.cpp +++ b/test/unittest/fwk_inner_napi_test/print_utils_test.cpp @@ -134,7 +134,7 @@ HWTEST_F(PrintUtilsTest, PrintUtilsTest_0006, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0007, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0007, TestSize.Level1) { std::string gid = "com.sample.ext:1234"; std::string id = "com.sample.ext4"; @@ -149,7 +149,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0007, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0008, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0008, TestSize.Level1) { std::string gid = "com.sample.ext"; uint32_t cid = 1; @@ -164,7 +164,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0008, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0009, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0009, TestSize.Level1) { std::string gid = "com.sample.ext"; std::string extensionId = "com.sample.ext"; @@ -178,7 +178,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0009, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0010, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0010, TestSize.Level1) { std::string gid = "com.sample.ext:1"; std::string extensionId = "com.sample.ext"; @@ -194,7 +194,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0010, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0011, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0011, TestSize.Level1) { std::string taskId = "1234"; std::string type = "block"; @@ -209,7 +209,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0011, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0012, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0012, TestSize.Level1) { int32_t result = PrintUtils::OpenFile("/error"); EXPECT_EQ(PRINT_INVALID_ID, result); @@ -221,7 +221,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0012, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0013, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0013, TestSize.Level1) { int32_t result = PrintUtils::OpenFile("/data/e11"); EXPECT_EQ(PRINT_INVALID_ID, result); @@ -247,7 +247,7 @@ HWTEST_F(PrintUtilsTest, PrintUtilsTest_0014, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0015, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0015, TestSize.Level1) { int32_t result = PrintUtils::IsPathValid("/data/service/e11//data/service/e11"); EXPECT_EQ(E_PRINT_NONE, result); @@ -259,7 +259,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0015, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0016, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0016, TestSize.Level1) { int32_t result = PrintUtils::IsPathValid("/data/service/e11"); EXPECT_NE(PRINT_INVALID_ID, result); @@ -271,7 +271,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0016, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0017, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0017, TestSize.Level1) { int32_t result = PrintUtils::GetIdFromFdPath("/data/service"); EXPECT_EQ(E_PRINT_NONE, result); @@ -283,7 +283,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0017, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0018, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0018, TestSize.Level1) { int32_t result = PrintUtils::GetIdFromFdPath("/data/service/e11"); EXPECT_NE(PRINT_INVALID_ID, result); @@ -295,7 +295,7 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0018, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0019, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0019, TestSize.Level1) { std::string testResult = "PRINT_JOB_PREPARED"; std::string result = PrintUtils::GetJobStateChar(PRINT_JOB_PREPARED); @@ -308,11 +308,122 @@ HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0019, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(PrintUtilsTest, PrintUtsilsTest_0020, TestSize.Level1) +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0020, TestSize.Level1) { std::string testResult = "PRINT_JOB_UNKNOWN"; std::string result = PrintUtils::GetJobStateChar(PRINT_JOB_PREPARED + 100); EXPECT_EQ(testResult, result); } + +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0021, TestSize.Level1) +{ + PrintUtils printUtils; + std::shared_ptr adapterParam = std::make_shared(); + AAFwk::Want want; + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetCopyNumber(1); + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetIsSequential(true); + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetIsLandscape(false); + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetDirectionMode(0); + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetColorMode(0); + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetDuplexMode(0); + printUtils.BuildPrintAttributesParam(adapterParam, want); + adapterParam->printAttributes.SetOption("123"); + printUtils.BuildPrintAttributesParam(adapterParam, want); +} + +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0022, TestSize.Level1) +{ + PrintUtils printUtils; + PrintAttributes attrParam; + nlohmann::json attrJson; + printUtils.ParseAttributesObjectParamForJson(attrParam, attrJson); + PrintRange range; + range.SetStartPage(1); + range.SetEndPage(1); + std::vector pages; + pages.push_back(1); + range.SetPages(pages); + attrParam.SetPageRange(range); + printUtils.ParseAttributesObjectParamForJson(attrParam, attrJson); + PrintPageSize pageSize("11", "123", 400, 600); + attrParam.SetPageSize(pageSize); + printUtils.ParseAttributesObjectParamForJson(attrParam, attrJson); + PrintMargin margin; + margin.SetTop(100); + margin.SetBottom(100); + margin.SetLeft(100); + margin.SetRight(100); + attrParam.SetMargin(margin); + printUtils.ParseAttributesObjectParamForJson(attrParam, attrJson); +} + +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0023, TestSize.Level1) +{ + PrintUtils printUtils; + std::shared_ptr adapterParam = std::make_shared(); + AAFwk::Want want; + printUtils.BuildAdapterParam(adapterParam, want); + adapterParam->isCheckFdList = false; + printUtils.BuildAdapterParam(adapterParam, want); +} + +/** + * @tc.name: PrintUtilsTest_0024 + * @tc.desc: Verify the getLocalId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0024, TestSize.Level1) +{ + std::string gid = "com.sample.ext:1234"; + std::string id = "com.sample.ext"; + std::string testResult = "1234"; + std::string result = PrintUtils::GetLocalId(gid, id); + EXPECT_EQ(testResult, result); +} + +/** + * @tc.name: PrintUtilsTest_0025 + * @tc.desc: Verify the getLocalId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0025, TestSize.Level1) +{ + int32_t result = PrintUtils::OpenFile("content://test/test1"); + EXPECT_EQ(99, result); +} + +/** + * @tc.name: PrintUtilsTest_0026 + * @tc.desc: Verify the isPathValid function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0026, TestSize.Level1) +{ + string testString(2048, '1'); + int32_t result = PrintUtils::IsPathValid("testString"); + EXPECT_EQ(E_PRINT_NONE, result); +} + +/** + * @tc.name: PrintUtilsTest_0027 + * @tc.desc: Verify the isPathValid function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUtilsTest, PrintUtilsTest_0027, TestSize.Level1) +{ + std::string result = PrintUtils::GetBundleNameForUid(123); + EXPECT_EQ("", result); +} + } // namespace Print } // namespace OHOS diff --git a/test/unittest/fwk_print_cups_client_test/BUILD.gn b/test/unittest/fwk_print_cups_client_test/BUILD.gn new file mode 100644 index 0000000..4101740 --- /dev/null +++ b/test/unittest/fwk_print_cups_client_test/BUILD.gn @@ -0,0 +1,96 @@ +# 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_fwk/print.gni") +import("//build/test.gni") + +module_output_path = "print_fwk/fwk_print_cups_client_test" + +ohos_unittest("fwk_print_cups_client_test") { + module_out_path = module_output_path + include_dirs = [ + "${print_path}/frameworks/innerkitsimpl/print_impl/include", + "${print_path}/frameworks/models/print_models/include", + "${print_path}/interfaces/kits/napi/print_napi/include", + "${print_path}/services/print_service/include", + "//third_party/cpp-httplib", + "${print_utils_path}/include", + "//third_party/node/src", + ] + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${print_path}/cfi_blocklist.txt" + } + + sources = [] + cflags_cc = [] + + deps = [ + "${print_path}/etc/init:printservice.rc", + "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", + "${print_path}/frameworks/kits/extension:print_extension_framework", + "${print_path}/frameworks/kits/extension:print_extension_module", + "${print_path}/frameworks/models/print_models:print_models", + "${print_path}/interfaces/kits/jsnapi/print_extension:printextensionability_napi", + "${print_path}/interfaces/kits/jsnapi/print_extensionctx:printextensioncontext_napi", + "${print_path}/interfaces/kits/napi/print_napi:print_napi", + "${print_path}/profile:print_sa_profiles", + "${print_path}/services/print_service:print_service", + "//third_party/googletest:gmock_main", + "//third_party/zlib:libz", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "drivers_interface_usb:libusb_proxy_1.0", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "usb_manager:usbsrv_client", + ] + + if (cups_enable) { + include_dirs += [ "//third_party/cups/cups-2.4.0" ] + cflags_cc += [ "-DCUPS_ENABLE" ] + external_deps += [ + "cJSON:cjson", + "cups:cups", + "cups-filters:cupsfilters", + ] + } + + cflags_cc += [ "-DCPPHTTPLIB_NO_EXCEPTIONS" ] +} + +group("unittest") { + testonly = true + + deps = [] + + deps += [ ":fwk_print_cups_client_test" ] +} diff --git a/test/unittest/fwk_print_cups_client_test/print_cups_client_test.cpp b/test/unittest/fwk_print_cups_client_test/print_cups_client_test.cpp new file mode 100644 index 0000000..41d9f40 --- /dev/null +++ b/test/unittest/fwk_print_cups_client_test/print_cups_client_test.cpp @@ -0,0 +1,1542 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#include "print_cups_client.h" +#undef private +#include "print_constant.h" +#include "print_log.h" + +using namespace testing::ext; +using json = nlohmann::json; + +namespace OHOS { +namespace Print { +static constexpr const char *JOB_OPTIONS = + "{\"jobName\":\"xx\",\"jobNum\":1,\"mediaType\":\"stationery\",\"documentCategory\":0,\"printQuality\":\"4\"," + "\"printerName\":\"printer1\",\"printerUri\":\"ipp://192.168.0.1:111/ipp/print\",\"borderless\":true," + "\"documentFormat\":\"application/pdf\",\"files\":[\"/data/1.pdf\"]}"; + +static const std::string PRINTER_STATE_NONE = "none"; +static const std::string PRINTER_STATE_MEDIA_EMPTY = "media-empty"; +static const std::string PRINTER_STATE_MEDIA_JAM = "media-jam"; +static const std::string PRINTER_STATE_PAUSED = "paused"; +static const std::string PRINTER_STATE_TONER_LOW = "toner-low"; +static const std::string PRINTER_STATE_TONER_EMPTY = "toner-empty"; +static const std::string PRINTER_STATE_DOOR_EMPTY = "door-open"; +static const std::string PRINTER_STATE_MEDIA_NEEDED = "media-needed"; +static const std::string PRINTER_STATE_MARKER_LOW = "marker-supply-low"; +static const std::string PRINTER_STATE_MARKER_EMPTY = "marker-supply-empty"; +static const std::string PRINTER_STATE_INK_EMPTY = "marker-ink-almost-empty"; +static const std::string PRINTER_STATE_COVER_OPEN = "cover-open"; +static const std::string PRINTER_STATE_OFFLINE = "offline"; + +class PrintCupsClientTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::string GetDefaultJobId(); +}; + +void PrintCupsClientTest::SetUpTestCase(void) +{} + +void PrintCupsClientTest::TearDownTestCase(void) +{} + +void PrintCupsClientTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintCupsClientTest_%{public}d", ++testNo); +} + +void PrintCupsClientTest::TearDown(void) +{} + +std::string PrintCupsClientTest::GetDefaultJobId() +{ + return std::to_string(0); +} + +/** + * @tc.name: PrintCupsClientTest_0001 + * @tc.desc: StartCupsdService + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0001, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + int32_t ret = printCupsClient.StartCupsdService(); + EXPECT_EQ(ret, E_PRINT_NONE); +} + +/** + * @tc.name: PrintCupsClientTest_0002 + * @tc.desc: ChangeFilterPermission + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0002, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string path = ""; + mode_t mode = 16; + printCupsClient.ChangeFilterPermission(path, mode); +} + +/** + * @tc.name: PrintCupsClientTest_0003 + * @tc.desc: SymlinkDirectory + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0003, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + const char *srcDir = ""; + const char *destDir = ""; + printCupsClient.SymlinkDirectory(srcDir, destDir); +} + +/** + * @tc.name: PrintCupsClientTest_0004 + * @tc.desc: CopyDirectory + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0004, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + const char *srcDir = ""; + const char *destDir = ""; + printCupsClient.CopyDirectory(srcDir, destDir); +} + +/** + * @tc.name: PrintCupsClientTest_0005 + * @tc.desc: InitCupsResources + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0005, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + int32_t ret = printCupsClient.InitCupsResources(); + EXPECT_EQ(ret, E_PRINT_NONE); +} + +/** + * @tc.name: PrintCupsClientTest_0006 + * @tc.desc: StopCupsdService + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0006, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + int32_t ret = printCupsClient.StartCupsdService(); + EXPECT_EQ(ret, E_PRINT_NONE); + printCupsClient.StopCupsdService(); +} + +/** + * @tc.name: PrintCupsClientTest_0007 + * @tc.desc: StopCupsdService + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0007, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + printCupsClient.StopCupsdService(); +} + +/** + * @tc.name: PrintCupsClientTest_0008 + * @tc.desc: SetDefaultPrinter + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0008, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerName = "DIRECT-PixLab_V1-0105"; + printCupsClient.SetDefaultPrinter(printerName); + printCupsClient.StartCupsdService(); + printCupsClient.SetDefaultPrinter(printerName); +} + +/** + * @tc.name: PrintCupsClientTest_0009 + * @tc.desc: QueryPrinterInfoByPrinterId + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0009, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerName = "DIRECT-PixLab_V1-0105"; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-0105"; + PrinterInfo info; + info.SetPrinterName(printerName); + printCupsClient.QueryPrinterInfoByPrinterId(printerId, info); +} + +/** + * @tc.name: PrintCupsClientTest_0012 + * @tc.desc: QueryPrinterCapabilityByUri + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0012, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerUri = "ipp://192.168.186.1:631/ipp/print"; + std::string printerId = "1"; + PrinterCapability printerCaps; + int32_t ret = printCupsClient.QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps); + EXPECT_EQ(ret, E_PRINT_SERVER_FAILURE); +} + +/** + * @tc.name: PrintCupsClientTest_0013 + * @tc.desc: AddCupsPrintJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0013, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + printCupsClient.AddCupsPrintJob(testJob); +} + +/** + * @tc.name: PrintCupsClientTest_0014 + * @tc.desc: AddCupsPrintJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0014, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + testJob.SetColorMode(1); + testJob.SetCopyNumber(1); + testJob.SetDuplexMode(0); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + printCupsClient.AddCupsPrintJob(testJob); +} + +/** + * @tc.name: PrintCupsClientTest_0015 + * @tc.desc: StartNextJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0015, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + printCupsClient.StartNextJob(); +} + +/** + * @tc.name: PrintCupsClientTest_0016 + * @tc.desc: StartNextJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0016, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + printCupsClient.jobQueue_.push_back(jobParams); + printCupsClient.StartNextJob(); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0018 + * @tc.desc: StartNextJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0018, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + JobParameters *jobParams = nullptr; + printCupsClient.jobQueue_.push_back(jobParams); + printCupsClient.StartNextJob(); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0019 + * @tc.desc: JobCompleteCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0019, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + printCupsClient.JobCompleteCallback(); +} + +/** + * @tc.name: PrintCupsClientTest_0020 + * @tc.desc: JobCompleteCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0020, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + printCupsClient.currentJob_ = jobParams; + printCupsClient.JobCompleteCallback(); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0021 + * @tc.desc: FillBorderlessOptions + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0021, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + jobParams->borderless = 1; + jobParams->mediaSize = ""; + jobParams->mediaType = ""; + int numOptions = 0; + cups_option_t *options = nullptr; + printCupsClient.FillBorderlessOptions(jobParams, numOptions, &options); + EXPECT_EQ(numOptions, 0); + delete jobParams; + delete options; +} + +/** + * @tc.name: PrintCupsClientTest_0022 + * @tc.desc: FillBorderlessOptions + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0022, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + jobParams->mediaSize = "testMediaSize"; + jobParams->mediaType = "testMediaType"; + int numOptions = 0; + cups_option_t *options = nullptr; + printCupsClient.FillBorderlessOptions(jobParams, numOptions, &options); + EXPECT_EQ(numOptions, 0); + delete jobParams; + delete options; +} + +/** + * @tc.name: PrintCupsClientTest_0023 + * @tc.desc: FillBorderlessOptions + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0023, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + jobParams->borderless = 1; + jobParams->mediaType = CUPS_MEDIA_TYPE_PHOTO_GLOSSY; + int numOptions = 0; + cups_option_t *options = nullptr; + printCupsClient.FillBorderlessOptions(jobParams, numOptions, &options); + EXPECT_EQ(numOptions, 0); + delete jobParams; + delete options; +} + +/** + * @tc.name: PrintCupsClientTest_0024 + * @tc.desc: FillBorderlessOptions + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0024, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + jobParams->borderless = 1; + jobParams->mediaType = CUPS_MEDIA_TYPE_PHOTO_GLOSSY; + jobParams->mediaSize = CUPS_MEDIA_4X6; + int numOptions = 0; + cups_option_t *options = nullptr; + printCupsClient.FillBorderlessOptions(jobParams, numOptions, &options); + EXPECT_EQ(numOptions, 0); + delete jobParams; + delete options; +} + +/** + * @tc.name: PrintCupsClientTest_0025 + * @tc.desc: FillJobOptions + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0025, TestSize.Level1) +{ + int num = 0; + cups_option_t *options = nullptr; + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob jobInfo; + jobInfo.SetCopyNumber(2); + jobInfo.SetDuplexMode(1); + jobInfo.SetColorMode(0); + jobInfo.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(jobInfo); + jobParams->printerId = "1"; + jobParams->numCopies = 2; + jobParams->duplex = ""; + jobParams->printQuality = ""; + jobParams->color = ""; + int ret = printCupsClient.FillJobOptions(jobParams, num, &options); + EXPECT_EQ(ret, 6); + delete jobParams; + delete options; +} + +/** + * @tc.name: PrintCupsClientTest_0026 + * @tc.desc: FillJobOptions + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0026, TestSize.Level1) +{ + int num = 0; + cups_option_t *options = nullptr; + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob jobInfo; + jobInfo.SetCopyNumber(2); + jobInfo.SetDuplexMode(1); + jobInfo.SetColorMode(0); + jobInfo.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(jobInfo); + jobParams->printerId = "1"; + jobParams->numCopies = 0; + jobParams->duplex = "test_duplex"; + jobParams->printQuality = "test_printQuality"; + jobParams->color = "test_color"; + int ret = printCupsClient.FillJobOptions(jobParams, num, &options); + EXPECT_EQ(ret, 6); + delete jobParams; + delete options; +} + +/** + * @tc.name: PrintCupsClientTest_0027 + * @tc.desc: QueryAddedPrinterList + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0027, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::vector printerNameList; + printerNameList.push_back("testPrinterName"); + printCupsClient.StopCupsdService(); + printCupsClient.QueryAddedPrinterList(printerNameList); +} + +/** + * @tc.name: PrintCupsClientTest_0028 + * @tc.desc: QueryAddedPrinterList + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0028, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::vector printerNameList; + printerNameList.push_back("testPrinterName"); + printCupsClient.StartCupsdService(); + printCupsClient.QueryAddedPrinterList(printerNameList); +} + +/** + * @tc.name: PrintCupsClientTest_0030 + * @tc.desc: GetPPDFile + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0030, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerName = "testPrinterName"; + printCupsClient.StopCupsdService(); + printCupsClient.GetPPDFile(printerName); +} + +/** + * @tc.name: PrintCupsClientTest_0031 + * @tc.desc: GetPPDFile + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0031, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerName = "testPrinterName"; + printCupsClient.StartCupsdService(); + printCupsClient.GetPPDFile(printerName); +} + +/** + * @tc.name: PrintCupsClientTest_0032 + * @tc.desc: QueryPrinterAttrList + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0032, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerName = "testPrinterName"; + std::vector keyList; + std::vector valueList; + printCupsClient.QueryPrinterAttrList(printerName, keyList, valueList); +} + +/** + * @tc.name: PrintCupsClientTest_0033 + * @tc.desc: QueryPrinterInfoByPrinterId + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0033, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerId = "testPrinterId"; + PrinterInfo info; + info.SetPrinterName("testPrinterName"); + printCupsClient.QueryPrinterInfoByPrinterId(printerId, info); +} + +/** + * @tc.name: PrintCupsClientTest_0034 + * @tc.desc: CheckPrinterMakeModel + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0034, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + JobParameters *jobParams = nullptr; + bool ret = printCupsClient.CheckPrinterMakeModel(jobParams); + EXPECT_EQ(ret, false); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0036 + * @tc.desc: VerifyPrintJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0036, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + JobParameters *jobParams = nullptr; + int num = 0; + uint32_t jobId = 1; + cups_option_t *options = nullptr; + http_t *http = nullptr; + bool ret = printCupsClient.VerifyPrintJob(jobParams, num, jobId, options, http); + EXPECT_EQ(ret, false); + delete jobParams; + delete options; + delete http; +} + +/** + * @tc.name: PrintCupsClientTest_0039 + * @tc.desc: UpdatePrintJobStateInJobParams + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0039, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + uint32_t state = PRINT_JOB_BLOCKED; + uint32_t subState = PRINT_JOB_BLOCKED_UNKNOWN; + printCupsClient.UpdatePrintJobStateInJobParams(jobParams, state, subState); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0042 + * @tc.desc: UpdateJobStatus + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0042, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + JobStatus *prevousJobStatus = nullptr; + JobStatus *jobStatus = nullptr; + printCupsClient.UpdateJobStatus(prevousJobStatus, jobStatus); + JobStatus *prevousJobStatus2 = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + printCupsClient.UpdateJobStatus(prevousJobStatus2, jobStatus); + delete prevousJobStatus; + delete jobStatus; + delete prevousJobStatus2; +} + +/** + * @tc.name: PrintCupsClientTest_0043 + * @tc.desc: UpdateJobStatus + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0043, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + JobStatus *prevousJobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + printCupsClient.UpdateJobStatus(prevousJobStatus, jobStatus); + delete prevousJobStatus; + delete jobStatus; +} + +/** + * @tc.name: PrintCupsClientTest_0044 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0044, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = true; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0045 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0045, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_COMPLETED; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0046 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0046, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_PROCESSING; + int ret = memcpy_s(jobStatus->printer_state_reasons, + sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_NONE.c_str(), + strlen(PRINTER_STATE_NONE.c_str())); + if (ret != 0) { + delete jobParams; + delete jobStatus; + delete param; + return; + } + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0047 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0047, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_PROCESSING; + int ret = memcpy_s(jobStatus->printer_state_reasons, + sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_MEDIA_EMPTY.c_str(), + strlen(PRINTER_STATE_MEDIA_EMPTY.c_str())); + if (ret != 0) { + delete jobParams; + delete jobStatus; + delete param; + return; + } + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0048 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0048, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_CANCELED; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0049 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0049, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_ABORTED; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0050 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0050, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_PENDING; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0051 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0051, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_HELD; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0052 + * @tc.desc: JobStatusCallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0052, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + bool isOffline = false; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + jobStatus->job_state = IPP_JOB_STOPPED; + printCupsClient.JobStatusCallback(param, jobStatus, isOffline); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0053 + * @tc.desc: ReportBlockedReason + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0053, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + JobStatus *jobStatus = nullptr; + JobMonitorParam *param = nullptr; + printCupsClient.ReportBlockedReason(param, jobStatus); + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0054 + * @tc.desc: ReportBlockedReason + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0054, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility = nullptr, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + printCupsClient.ReportBlockedReason(param, jobStatus); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0055 + * @tc.desc: ReportBlockedReason + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0055, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_MEDIA_EMPTY.c_str(), strlen(PRINTER_STATE_MEDIA_EMPTY.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_MEDIA_JAM.c_str(), strlen(PRINTER_STATE_MEDIA_JAM.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_PAUSED.c_str(), strlen(PRINTER_STATE_PAUSED.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_TONER_LOW.c_str(), strlen(PRINTER_STATE_TONER_LOW.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_TONER_EMPTY.c_str(), strlen(PRINTER_STATE_TONER_EMPTY.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_DOOR_EMPTY.c_str(), strlen(PRINTER_STATE_DOOR_EMPTY.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + delete jobParams; + delete jobStatus; + delete param; +} + +/** + * @tc.name: PrintCupsClientTest_0056 + * @tc.desc: QueryJobState + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0056, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + http_t *http = nullptr; + printCupsClient.QueryJobState(http, param, jobStatus); + delete jobParams; + delete jobStatus; + delete param; + delete http; +} + +/** + * @tc.name: PrintCupsClientTest_0057 + * @tc.desc: QueryJobState + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0057, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 0, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + http_t *http = nullptr; + printCupsClient.QueryJobState(http, param, jobStatus); + delete jobParams; + delete jobStatus; + delete param; + delete http; +} + +/** + * @tc.name: PrintCupsClientTest_0058 + * @tc.desc: CheckPrinterOnline + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0058, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + const char *printerUri = "ipp://192.168.186.1:631/ipp/print"; + std::string printerId = "1"; + bool ret = printCupsClient.CheckPrinterOnline(printerUri, printerId); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: PrintCupsClientTest_0059 + * @tc.desc: CancelCupsJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0059, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + printCupsClient.CancelCupsJob(GetDefaultJobId()); +} + +/** + * @tc.name: PrintCupsClientTest_0060 + * @tc.desc: CancelCupsJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0060, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string serviceJobId = "0"; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + printCupsClient.jobQueue_.push_back(jobParams); + PRINT_HILOGI("CancelCupsJob(): printCupsClient.jobQueue_.size(): %{public}u", printCupsClient.jobQueue_.size()); + printCupsClient.CancelCupsJob(serviceJobId); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0061 + * @tc.desc: CancelCupsJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0061, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string serviceJobId = "1"; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + printCupsClient.jobQueue_.push_back(jobParams); + printCupsClient.currentJob_ = jobParams; + printCupsClient.CancelCupsJob(serviceJobId); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0062 + * @tc.desc: CancelCupsJob + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0062, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string serviceJobId = "1"; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + PrintJob testJob2; + testJob2.SetJobId(serviceJobId); + testJob2.SetFdList(files); + testJob2.SetPageSize(pageSize); + testJob2.SetPrinterId("printid-1234"); + testJob2.SetOption(JOB_OPTIONS); + JobParameters *jobParams2 = printCupsClient.BuildJobParameters(testJob2); + printCupsClient.currentJob_ = jobParams2; + printCupsClient.CancelCupsJob(serviceJobId); + delete jobParams; + delete jobParams2; +} + +/** + * @tc.name: PrintCupsClientTest_0066 + * @tc.desc: BuildJobParameters + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0066, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + testJob.SetOption("test"); + printCupsClient.BuildJobParameters(testJob); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0067 + * @tc.desc: BuildJobParameters + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0067, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(R"({"key": "value"})"); + printCupsClient.BuildJobParameters(testJob); + json optionJson = json::parse(testJob.GetOption()); + optionJson["printerUri"] = "ipp://192.168.0.1:111/ipp/print"; + optionJson["printerName"] = "printer1"; + optionJson["documentFormat"] = "application/pdf"; + testJob.SetOption(optionJson.dump()); + printCupsClient.BuildJobParameters(testJob); + optionJson["cupsOptions"] = "testCupsOptions"; + optionJson["printQuality"] = "printQuality"; + optionJson["jobName"] = "jobName"; + optionJson["mediaType"] = "mediaType"; + testJob.SetOption(optionJson.dump()); + printCupsClient.BuildJobParameters(testJob); + optionJson["printQuality"] = 1; + testJob.SetOption(optionJson.dump()); + printCupsClient.BuildJobParameters(testJob); +} + +/** + * @tc.name: PrintCupsClientTest_0068 + * @tc.desc: DumpJobParameters + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0068, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + testJob.SetColorMode(1); + testJob.SetCopyNumber(1); + testJob.SetDuplexMode(0); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + printCupsClient.DumpJobParameters(jobParams); + delete jobParams; +} + +/** + * @tc.name: PrintCupsClientTest_0069 + * @tc.desc: GetMedieSize + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0069, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + testJob.SetColorMode(1); + testJob.SetCopyNumber(1); + testJob.SetDuplexMode(0); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + printCupsClient.GetMedieSize(testJob); +} + +/** + * @tc.name: PrintCupsClientTest_0070 + * @tc.desc: GetDulpexString + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0070, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + uint32_t duplexCode = 0; + printCupsClient.GetDulpexString(duplexCode); + duplexCode = 1; + printCupsClient.GetDulpexString(duplexCode); + duplexCode = 2; + printCupsClient.GetDulpexString(duplexCode); + duplexCode = 3; + printCupsClient.GetDulpexString(duplexCode); +} + +/** + * @tc.name: PrintCupsClientTest_0071 + * @tc.desc: GetColorString + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0071, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + uint32_t colorCode = 0; + printCupsClient.GetColorString(colorCode); + colorCode = 1; + printCupsClient.GetColorString(colorCode); + colorCode = 2; + printCupsClient.GetColorString(colorCode); +} + +/** + * @tc.name: PrintCupsClientTest_0072 + * @tc.desc: IsCupsServerAlive + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0072, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + printCupsClient.IsCupsServerAlive(); +} + +/** + * @tc.name: PrintCupsClientTest_0073 + * @tc.desc: IsPrinterExist + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0073, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + const char *printerUri = "ipp://192.168.186.1:631/ipp/print"; + const char *printerName = "DIRECT-PixLab_V1-0105"; + const char *ppdName = "DIRECT-PixLab_V1-0105.ppd"; + printCupsClient.IsPrinterExist(printerUri, printerName, ppdName); +} + +/** + * @tc.name: PrintCupsClientTest_0074 + * @tc.desc: ConvertInchTo100MM + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0074, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + float num = 1000; + float ret = printCupsClient.ConvertInchTo100MM(num); + EXPECT_EQ(ret, 2540); +} + +/** + * @tc.name: PrintCupsClientTest_0075 + * @tc.desc: IsIpConflict + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0075, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + std::string printerId = "com.ohos.spooler:usb://DIRECT-HW_PixLab_V1-1620"; + std::string nic = ""; + printCupsClient.IsIpConflict(printerId, nic); + printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + printCupsClient.IsIpConflict(printerId, nic); +} + +/** + * @tc.name: PrintCupsClientTest_0076 + * @tc.desc: ReportBlockedReason + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCupsClientTest, PrintCupsClientTest_0076, TestSize.Level1) +{ + OHOS::Print::PrintCupsClient printCupsClient; + PrintJob testJob; + testJob.SetJobId(GetDefaultJobId()); + std::vector files = {1}; + testJob.SetFdList(files); + OHOS::Print::PrintPageSize pageSize; + pageSize.SetId("pgid-1234"); + testJob.SetPageSize(pageSize); + testJob.SetPrinterId("printid-1234"); + testJob.SetOption(JOB_OPTIONS); + JobParameters *jobParams = printCupsClient.BuildJobParameters(testJob); + JobStatus *jobStatus = new (std::nothrow) JobStatus{{'\0'}, (ipp_jstate_t)0, {'\0'}}; + JobMonitorParam *param = new (std::nothrow) JobMonitorParam{jobParams->serviceAbility, + jobParams->serviceJobId, + 1, + "ipp://192.168.186.1:631/ipp/print", + "DIRECT-PixLab_V1-0105"}; + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_MEDIA_NEEDED.c_str(), strlen(PRINTER_STATE_MEDIA_NEEDED.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_MARKER_LOW.c_str(), strlen(PRINTER_STATE_MARKER_LOW.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_MARKER_EMPTY.c_str(), strlen(PRINTER_STATE_MARKER_EMPTY.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_INK_EMPTY.c_str(), strlen(PRINTER_STATE_INK_EMPTY.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_COVER_OPEN.c_str(), strlen(PRINTER_STATE_COVER_OPEN.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_OFFLINE.c_str(), strlen(PRINTER_STATE_OFFLINE.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + memcpy_s(jobStatus->printer_state_reasons, sizeof(jobStatus->printer_state_reasons), + PRINTER_STATE_NONE.c_str(), strlen(PRINTER_STATE_NONE.c_str())); + printCupsClient.ReportBlockedReason(param, jobStatus); + delete jobParams; + delete jobStatus; + delete param; +} + +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/fwk_print_helper_test/BUILD.gn b/test/unittest/fwk_print_helper_test/BUILD.gn new file mode 100644 index 0000000..20d8e68 --- /dev/null +++ b/test/unittest/fwk_print_helper_test/BUILD.gn @@ -0,0 +1,82 @@ +# 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_fwk/print.gni") +import("//build/test.gni") + +module_output_path = "print_fwk/fwk_print_helper_test" + +ohos_unittest("fwk_print_helper_test") { + module_out_path = module_output_path + include_dirs = [ + "../fwk_inner_napi_test/mock", + "../service_test/mock", + "${print_path}/frameworks/models/print_models/include", + "${print_path}/services/print_service/include", + "${print_utils_path}/include", + ] + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${print_path}/cfi_blocklist.txt" + } + + sources = [ "print_bms_helper_test.cpp" ] + + deps = [ + "${print_path}/etc/init:printservice.rc", + "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", + "${print_path}/frameworks/kits/extension:print_extension_framework", + "${print_path}/frameworks/kits/extension:print_extension_module", + "${print_path}/frameworks/models/print_models:print_models", + "${print_path}/interfaces/kits/jsnapi/print_extension:printextensionability_napi", + "${print_path}/interfaces/kits/jsnapi/print_extensionctx:printextensioncontext_napi", + "${print_path}/interfaces/kits/napi/print_napi:print_napi", + "${print_path}/profile:print_sa_profiles", + "${print_path}/services/print_service:print_service", + "//third_party/googletest:gmock_main", + "//third_party/zlib:libz", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "cJSON:cjson", + "c_utils:utils", + "drivers_interface_usb:libusb_proxy_1.0", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "usb_manager:usbsrv_client", + ] +} + +group("unittest") { + testonly = true + + deps = [] + + deps += [ ":fwk_print_helper_test" ] +} diff --git a/test/unittest/fwk_print_helper_test/print_bms_helper_test.cpp b/test/unittest/fwk_print_helper_test/print_bms_helper_test.cpp new file mode 100644 index 0000000..3858e29 --- /dev/null +++ b/test/unittest/fwk_print_helper_test/print_bms_helper_test.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "print_bms_helper.h" +#include "print_constant.h" +#include "mock_bundle_mgr.h" +#include "mock_print_service_helper.h" +#include "mock_remote_object.h" +#include "print_log.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace Print { +class PrintBMSHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + void CallRemoteObject(const sptr &obj, sptr &dr); +}; + +void PrintBMSHelperTest::SetUpTestCase(void) {} + +void PrintBMSHelperTest::TearDownTestCase(void) {} + +void PrintBMSHelperTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintBMSHelperTest_%{public}d", ++testNo); +} + +void PrintBMSHelperTest::TearDown(void) {} + +void PrintBMSHelperTest::CallRemoteObject(const sptr &obj, + sptr &dr) +{ + EXPECT_CALL(*obj, IsProxyObject()).WillRepeatedly(Return(true)); + EXPECT_CALL(*obj, RemoveDeathRecipient(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*obj, AddDeathRecipient(_)).WillRepeatedly( + [&dr](const sptr &recipient) { + dr = recipient; + return true; + }); +} + +/** +* @tc.name: PrintBMSHelperTest_0001 +* @tc.desc: PrintBMSHelper +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintBMSHelperTest, PrintBMSHelperTest_0001, TestSize.Level1) +{ + PrintBMSHelper printBMSHelper; + printBMSHelper.~PrintBMSHelper(); +} + +/** +* @tc.name: PrintBMSHelperTest_0002 +* @tc.desc: PrintBMSHelper +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintBMSHelperTest, PrintBMSHelperTest_0002, TestSize.Level1) +{ + PrintBMSHelper printBMSHelper; + auto helper = std::make_shared(); + std::shared_ptr temp = std::shared_ptr(helper); + printBMSHelper.SetHelper(temp); +} + +/** +* @tc.name: PrintBMSHelperTest_0003 +* @tc.desc: QueryExtensionInfos +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintBMSHelperTest, PrintBMSHelperTest_0003, TestSize.Level1) +{ + std::vector resultInfo; + std::shared_ptr temp = nullptr; + DelayedSingleton::GetInstance()->SetHelper(temp); + EXPECT_FALSE(DelayedSingleton::GetInstance()->QueryExtensionInfos(resultInfo)); +} + +/** +* @tc.name: PrintBMSHelperTest_0008 +* @tc.desc: QueryCallerBundleName fail +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintBMSHelperTest, PrintBMSHelperTest_0008, TestSize.Level1) +{ + std::string testName = ""; + std::shared_ptr temp = nullptr; + DelayedSingleton::GetInstance()->SetHelper(temp); + EXPECT_EQ(DelayedSingleton::GetInstance()->QueryCallerBundleName(), testName); +} + +/** +* @tc.name: PrintBMSHelperTest_0010 +* @tc.desc: QueryCallerBundleName fail +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintBMSHelperTest, PrintBMSHelperTest_0010, TestSize.Level1) +{ + const wptr testObj = nullptr; + DelayedSingleton::GetInstance()->ResetProxy(testObj); +} + +/** +* @tc.name: PrintBMSHelperTest_0011 +* @tc.desc: QueryCallerBundleName fail +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintBMSHelperTest, PrintBMSHelperTest_0011, TestSize.Level1) +{ + wptr testObj = new (std::nothrow) MockBundleMgr(); + DelayedSingleton::GetInstance()->ResetProxy(testObj); +} +} // namespace Print +} // namespace OHOS diff --git a/test/unittest/fwk_print_service_ability_test/BUILD.gn b/test/unittest/fwk_print_service_ability_test/BUILD.gn new file mode 100644 index 0000000..b71154a --- /dev/null +++ b/test/unittest/fwk_print_service_ability_test/BUILD.gn @@ -0,0 +1,85 @@ +# 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_fwk/print.gni") +import("//build/test.gni") + +module_output_path = "print_fwk/fwk_print_service_ability_test" + +ohos_unittest("fwk_print_service_ability_test") { + module_out_path = module_output_path + include_dirs = [ + "../fwk_inner_napi_test/mock", + "../service_test/mock", + "${print_path}/frameworks/models/print_models/include", + "${print_path}/services/print_service/include", + "${print_utils_path}/include", + ] + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${print_path}/cfi_blocklist.txt" + } + + sources = [ + "print_service_ability_test.cpp", + "print_service_mock_permission.cpp", + ] + + deps = [ + "${print_path}/etc/init:printservice.rc", + "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", + "${print_path}/frameworks/kits/extension:print_extension_framework", + "${print_path}/frameworks/kits/extension:print_extension_module", + "${print_path}/frameworks/models/print_models:print_models", + "${print_path}/interfaces/kits/jsnapi/print_extension:printextensionability_napi", + "${print_path}/interfaces/kits/jsnapi/print_extensionctx:printextensioncontext_napi", + "${print_path}/interfaces/kits/napi/print_napi:print_napi", + "${print_path}/profile:print_sa_profiles", + "${print_path}/services/print_service:print_service", + "//third_party/googletest:gmock_main", + "//third_party/zlib:libz", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "cJSON:cjson", + "c_utils:utils", + "drivers_interface_usb:libusb_proxy_1.0", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "usb_manager:usbsrv_client", + ] +} + +group("unittest") { + testonly = true + + deps = [] + + deps += [ ":fwk_print_service_ability_test" ] +} diff --git a/test/unittest/fwk_print_service_ability_test/print_service_ability_test.cpp b/test/unittest/fwk_print_service_ability_test/print_service_ability_test.cpp new file mode 100644 index 0000000..4e796e9 --- /dev/null +++ b/test/unittest/fwk_print_service_ability_test/print_service_ability_test.cpp @@ -0,0 +1,1071 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "print_service_mock_permission.h" +#include "mock_remote_object.h" +#define private public +#define protected public +#include "print_service_ability.h" +#undef protected +#undef private +#ifdef CUPS_ENABLE +#include "print_cups_client.h" +#endif // CUPS_ENABLE +#include "accesstoken_kit.h" +#include "array_wrapper.h" +#include "int_wrapper.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "print_bms_helper.h" +#include "print_constant.h" +#include "print_log.h" +#include "printer_info.h" +#include "print_utils.h" +#include "string_wrapper.h" +#include "system_ability_definition.h" +#include "want_params_wrapper.h" +#include "print_security_guard_manager.h" +#include "hisys_event_util.h" +#include "nlohmann/json.hpp" +#include "print_ipp_over_usb_manager.h" +#include "mock_print_callback_proxy.h" +#include "mock_print_extension_callback_proxy.h" + + +using namespace testing; +using namespace testing::ext; + +namespace OHOS::Print { +using namespace std; +using namespace OHOS::HiviewDFX; +using namespace Security::AccessToken; +using json = nlohmann::json; +static constexpr const char *DEFAULT_EXTENSION_ID = "com.example.ext"; +static constexpr const char *UNLOAD_EXTENSION_ID = "com.example.ext.unload"; +static constexpr const char *NONEXIST_EXTENSION_ID = "com.example.ext.nonexist"; +static constexpr const char *DEFAULT_EXT_PRINTER_ID = "https://10.10.10.10/FE8083DCD35F"; +static constexpr const char *DEFAULT_EXT_PRINTER_ID2 = "https://10.10.10.10/0FDA6E208473"; +static constexpr const char *DEFAULT_PRINT_FILE_A = "file://data/print/a.png"; +static constexpr const char *DEFAULT_PRINT_FILE_B = "file://data/print/b.png"; +static constexpr const char *DEFAULT_PRINT_FILE_C = "file://data/print/c.png"; +const uint32_t MAX_JOBQUEUE_NUM = 512; + +enum EXTENSION_ID_TYPE { + TYPE_DEFAULT, + TYPE_UNLOAD, + TYPE_NON_EXIST, +}; +REGISTER_SYSTEM_ABILITY_BY_ID(PrintServiceAbility, PRINT_SERVICE_ID, true); +class PrintServiceAbilityTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::string GetExtensionId(EXTENSION_ID_TYPE type); + std::string GetDefaultTaskId(); + std::string GetDefaultJobId(); + std::string GetDefaultPrinterId(); + std::string GetInvalidPrinterId(); + void InitExtPrinterList(std::vector &printerList, size_t count); + void InitPrinterList(std::vector &printerList, size_t count); + void InitExtPrinterIdList(std::vector &idList, size_t count); + void InitFileList(std::vector &fileList); + void InitExtensionList(std::vector& extList); +}; + +void PrintServiceAbilityTest::SetUpTestCase(void) {} + +void PrintServiceAbilityTest::TearDownTestCase(void) {} + +void PrintServiceAbilityTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGE("PrintServiceAbilityTest_%{public}d", ++testNo); +} + +void PrintServiceAbilityTest::TearDown(void) {} + +std::string PrintServiceAbilityTest::GetExtensionId(EXTENSION_ID_TYPE type) +{ + switch (type) { + case TYPE_DEFAULT: + return DEFAULT_EXTENSION_ID; + + case TYPE_UNLOAD: + return UNLOAD_EXTENSION_ID; + + case TYPE_NON_EXIST: + return NONEXIST_EXTENSION_ID; + + default: + break; + } + return DEFAULT_EXTENSION_ID; +} + +std::string PrintServiceAbilityTest::GetDefaultTaskId() +{ + return std::to_string(0); +} + +std::string PrintServiceAbilityTest::GetDefaultJobId() +{ + return std::to_string(0); +} + +std::string PrintServiceAbilityTest::GetDefaultPrinterId() +{ + return PrintUtils::GetGlobalId(DEFAULT_EXTENSION_ID, DEFAULT_EXT_PRINTER_ID); +} + +std::string PrintServiceAbilityTest::GetInvalidPrinterId() +{ + return PrintUtils::GetGlobalId(DEFAULT_EXTENSION_ID, "wrong printer id"); +} + +void PrintServiceAbilityTest::InitExtPrinterList(std::vector &printerList, size_t count) +{ + printerList.clear(); + PrinterInfo info; + info.SetPrinterId(DEFAULT_EXT_PRINTER_ID); + printerList.emplace_back(info); + if (printerList.size() < count) { + info.SetPrinterId(DEFAULT_EXT_PRINTER_ID2); + printerList.emplace_back(info); + } +} + +void PrintServiceAbilityTest::InitPrinterList(std::vector &printerList, size_t count) +{ + printerList.clear(); + PrinterInfo info; + info.SetPrinterId(PrintUtils::GetGlobalId(DEFAULT_EXTENSION_ID, DEFAULT_EXT_PRINTER_ID)); + printerList.emplace_back(info); + if (printerList.size() < count) { + info.SetPrinterId(PrintUtils::GetGlobalId(DEFAULT_EXTENSION_ID, DEFAULT_EXT_PRINTER_ID2)); + printerList.emplace_back(info); + } +} + +void PrintServiceAbilityTest::InitExtPrinterIdList(std::vector &idList, size_t count) +{ + idList.clear(); + idList.emplace_back(DEFAULT_EXT_PRINTER_ID); + if (idList.size() < count) { + idList.emplace_back(DEFAULT_EXT_PRINTER_ID2); + } +} + +void PrintServiceAbilityTest::InitFileList(std::vector &fileList) +{ + fileList.emplace_back(DEFAULT_PRINT_FILE_A); + fileList.emplace_back(DEFAULT_PRINT_FILE_B); + fileList.emplace_back(DEFAULT_PRINT_FILE_C); +} + +void PrintServiceAbilityTest::InitExtensionList(std::vector& extList) +{ + std::vector nameList = {DEFAULT_EXTENSION_ID, UNLOAD_EXTENSION_ID}; + AppExecFwk::ExtensionAbilityInfo loadInfo; + for (size_t index = 0; index < nameList.size(); index++) { + loadInfo.bundleName = nameList[index]; + loadInfo.moduleName = nameList[index]; + loadInfo.name = nameList[index]; + extList.emplace_back(loadInfo); + } +} +/** +* @tc.name: PrintServiceAbilityTest_0001 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC ~PrintServiceAbility() +* @tc.require: +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0001, TestSize.Level1) +{ + PrintServiceAbility* print_service = new PrintServiceAbility(PRINT_SERVICE_ID, true); + if (print_service != nullptr) { + delete print_service; + print_service = nullptr; + } + PrintServiceAbility* new_print_service = new PrintServiceAbility(PRINT_SERVICE_ID, false); + if (new_print_service != nullptr) { + delete new_print_service; + new_print_service = nullptr; + } + sptr service = PrintServiceAbility::GetInstance(); + EXPECT_NE(service->instance_, nullptr); + EXPECT_EQ(PrintServiceAbility::GetInstance()->Init(), E_PRINT_SERVER_FAILURE); +} +/** +* @tc.name: PrintServiceAbilityTest_0002 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC ManualStart() +* @tc.require: +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0002, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + int state = static_cast(service->state_); + service->ManualStart(); + EXPECT_EQ(state, 0); +} +/** +* @tc.name: PrintServiceAbilityTest_0003 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC GetPrintJobOrderId() +* @tc.require: +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0003, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + service->GetPrintJobOrderId(); + EXPECT_NE(service->currentJobOrderId_, 0); +} +/** +* @tc.name: PrintServiceAbilityTest_0004 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC +* @tc.require: return E_PRINT_NO_PERMISSION +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0004, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + EXPECT_EQ(service->StartService(), E_PRINT_NO_PERMISSION); + std::vector fileList = {}; + std::vector fdList = {}; + std::string taskId = ""; + std::shared_ptr adapterParam = std::make_shared(); + EXPECT_EQ(service->StartPrint(fileList, fdList, taskId), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->CallSpooler(fileList, fdList, taskId), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->StopPrint(taskId), E_PRINT_NO_PERMISSION); + std::string printerId = "1234"; + EXPECT_EQ(service->ConnectPrinter(printerId), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->DisconnectPrinter(printerId), E_PRINT_NO_PERMISSION); + std::vector extensionIds; + EXPECT_EQ(service->StartDiscoverPrinter(extensionIds), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->StopDiscoverPrinter(), E_PRINT_NO_PERMISSION); + std::vector extensionInfos; + EXPECT_EQ(service->QueryAllExtension(extensionInfos), E_PRINT_NO_PERMISSION); + std::vector printJobs; + EXPECT_EQ(service->QueryAllPrintJob(printJobs), E_PRINT_NO_PERMISSION); + std::vector printerList; + EXPECT_EQ(service->QueryAddedPrinter(printerList), E_PRINT_NO_PERMISSION); + PrinterInfo info; + EXPECT_EQ(service->QueryPrinterInfoByPrinterId(printerId, info), E_PRINT_NO_PERMISSION); + std::vector keyList; + std::vector valueList; + EXPECT_EQ(service->QueryPrinterProperties(printerId, keyList, valueList), E_PRINT_NO_PERMISSION); + std::string printJobId = "1"; + PrintJob printJob; + EXPECT_EQ(service->QueryPrintJobById(printJobId, printJob), E_PRINT_NO_PERMISSION); + std::string printerUri = "111.222.333"; + std::string printerName = "pixlab_0759"; + std::string printerMake = "pixlab b5"; + EXPECT_EQ(service->AddPrinterToCups(printerUri, printerName, printerMake), E_PRINT_NO_PERMISSION); + PrinterCapability printerCaps; + EXPECT_EQ(service->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->StartNativePrintJob(printJob), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->StartPrintJob(printJob), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->CancelPrintJob(printJobId), E_PRINT_NO_PERMISSION); + std::vector printerInfos; + EXPECT_EQ(service->AddPrinters(printerInfos), E_PRINT_NO_PERMISSION); + std::vector printerIds; + EXPECT_EQ(service->RemovePrinters(printerIds), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->UpdatePrinters(printerInfos), E_PRINT_NO_PERMISSION); + uint32_t state = PrinterState::PRINTER_ADDED; + EXPECT_EQ(service->UpdatePrinterState(printerId, state), E_PRINT_NO_PERMISSION); + uint32_t subState = 0; + EXPECT_EQ(service->UpdatePrintJobStateOnlyForSystemApp(printJobId, state, subState), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->AdapterGetFileCallBack(printJobId, state, subState), E_PRINT_NONE); + state = PrintJobState::PRINT_JOB_CREATE_FILE_COMPLETED; + EXPECT_EQ(service->AdapterGetFileCallBack(printJobId, state, subState), E_PRINT_NO_PERMISSION); + std::string extInfo = ""; + EXPECT_EQ(service->UpdateExtensionInfo(extInfo), E_PRINT_NO_PERMISSION); + std::string previewResult = ""; + EXPECT_EQ(service->RequestPreview(printJob, previewResult), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->QueryPrinterCapability(printerId), E_PRINT_NO_PERMISSION); + std::string type = ""; + sptr listener = nullptr; + EXPECT_EQ(service->RegisterPrinterCallback(type, listener), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->UnregisterPrinterCallback(type), E_PRINT_NO_PERMISSION); + std::string extensionCID = ""; + sptr listenerCB = nullptr; + EXPECT_EQ(service->RegisterExtCallback(extensionCID, listenerCB), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->UnregisterAllExtCallback(extensionCID), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->LoadExtSuccess(extensionCID), E_PRINT_NO_PERMISSION); + std::string jobName = "a.jpeg"; + PrintAttributes printAttributes; + EXPECT_EQ(service->PrintByAdapter(jobName, printAttributes, taskId), E_PRINT_NO_PERMISSION); + uint32_t fd = 46; + EXPECT_EQ(service->StartGetPrintFile(printJobId, printAttributes, fd), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->NotifyPrintService(printJobId, type), E_PRINT_NO_PERMISSION); + EXPECT_EQ(service->CallStatusBar(), E_PRINT_NO_PERMISSION); + uint32_t event = 0; + std::string jobId = GetDefaultJobId(); + EXPECT_EQ(service->NotifyPrintServiceEvent(jobId, event), E_PRINT_NO_PERMISSION); + + PrintServiceMockPermission::MockPermission(); + EXPECT_EQ(service->StartService(), E_PRINT_NONE); + EXPECT_EQ(service->StartPrint(fileList, fdList, taskId), E_PRINT_INVALID_PARAMETER); + + EXPECT_EQ(service->StopDiscoverPrinter(), E_PRINT_NONE); + EXPECT_EQ(service->StopPrint(taskId), E_PRINT_NONE); +} +/** +* @tc.name: PrintServiceAbilityTest_0006 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC CallSpooler +* @tc.require: has token +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0006, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::vector fileList = {}; + std::vector fdList = {}; + std::string jobId = ""; + EXPECT_EQ(service->CallSpooler(fileList, fdList, jobId), E_PRINT_INVALID_PARAMETER); + jobId = "jobId"; + EXPECT_EQ(service->CallSpooler(fileList, fdList, jobId), E_PRINT_NONE); +} + +/** +* @tc.name: PrintServiceAbilityTest_0007 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC SetHelper +* @tc.require: has token +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0007, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = nullptr; + service->SetHelper(helper); + helper = make_shared(); + if (helper != nullptr) { + service->SetHelper(helper); + } +} + +/** +* @tc.name: PrintServiceAbilityTest_0008 +* @tc.desc: PrintServiceAbility ctor/dtor +* @tc.type: FUNC ConnectPrinter +* @tc.require: +*/ +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0008, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string printerId ="1234"; + EXPECT_EQ(service->ConnectPrinter(printerId), E_PRINT_INVALID_PRINTER); + std::shared_ptr info = std::make_shared(); + service->printerInfoList_[printerId] = info; + service->ConnectPrinter(printerId); + std::string extensionId = PrintUtils::GetExtensionId(printerId); + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_CONNECT_PRINTER); + sptr extCb = nullptr; + service->extCallbackMap_[cid] = extCb; + EXPECT_EQ(service->ConnectPrinter(printerId), E_PRINT_NONE); + extCb = new MockPrintExtensionCallbackProxy(); + EXPECT_NE(extCb, nullptr); + if (extCb != nullptr) { + service->extCallbackMap_.clear(); + service->extCallbackMap_[cid] = extCb; + } + service->ConnectPrinter(printerId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0009, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string printerId ="1234"; + EXPECT_EQ(service->DisconnectPrinter(printerId), E_PRINT_INVALID_PRINTER); + std::shared_ptr info = std::make_shared(); + service->printerInfoList_[printerId] = info; + service->DisconnectPrinter(printerId); + std::string extensionId = PrintUtils::GetExtensionId(printerId); + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_CONNECT_PRINTER); + sptr extCb = nullptr; + service->extCallbackMap_[cid] = extCb; + EXPECT_EQ(service->DisconnectPrinter(printerId), E_PRINT_SERVER_FAILURE); + extCb = new MockPrintExtensionCallbackProxy(); + EXPECT_NE(extCb, nullptr); + if (extCb != nullptr) { + service->extCallbackMap_.clear(); + service->extCallbackMap_[cid] = extCb; + } + service->DisconnectPrinter(printerId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0010, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::vector extensionIds; + EXPECT_EQ(service->StartDiscoverPrinter(extensionIds), E_PRINT_INVALID_EXTENSION); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0011, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string extensionCid = ""; + sptr listener = nullptr; + EXPECT_EQ(service->RegisterExtCallback(extensionCid, listener), E_PRINT_INVALID_PARAMETER); + extensionCid = PrintUtils::EncodeExtensionCid(GetExtensionId(TYPE_NON_EXIST), PRINT_EXTCB_START_DISCOVERY); + EXPECT_EQ(service->RegisterExtCallback(extensionCid, listener), E_PRINT_INVALID_EXTENSION); + extensionCid = PrintUtils::EncodeExtensionCid(GetExtensionId(TYPE_UNLOAD), PRINT_EXTCB_START_DISCOVERY); + EXPECT_EQ(service->RegisterExtCallback(extensionCid, listener), E_PRINT_INVALID_EXTENSION); + extensionCid = PrintUtils::EncodeExtensionCid(GetExtensionId(TYPE_DEFAULT), PRINT_EXTCB_MAX); + EXPECT_EQ(service->RegisterExtCallback(extensionCid, listener), E_PRINT_INVALID_EXTENSION); + EXPECT_EQ(service->LoadExtSuccess(GetExtensionId(TYPE_NON_EXIST)), E_PRINT_INVALID_EXTENSION); + EXPECT_EQ(service->LoadExtSuccess(GetExtensionId(TYPE_UNLOAD)), E_PRINT_INVALID_EXTENSION); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0012, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string taskId = ""; + std::string type = ""; + sptr listener = nullptr; + EXPECT_EQ(service->On(taskId, type, listener), E_PRINT_INVALID_PARAMETER); + EXPECT_EQ(service->Off(taskId, type), E_PRINT_INVALID_PARAMETER); + taskId = "1"; + type = "printCallback_adapter"; + service->On(taskId, type, listener); + EXPECT_EQ(service->On(taskId, type, listener), E_PRINT_INVALID_PARAMETER); + EXPECT_EQ(service->Off(taskId, type), E_PRINT_INVALID_PARAMETER); + listener = new MockPrintCallbackProxy(); + if (listener != nullptr) { + service->On(taskId, type, listener); + } + service->registeredListeners_[type] = listener; + taskId = ""; + EXPECT_EQ(service->On(taskId, type, listener), E_PRINT_NONE); + EXPECT_EQ(service->Off(taskId, type), E_PRINT_NONE); + delete listener; +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0013, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::vector printerInfos; + InitExtPrinterList(printerInfos, 1); + EXPECT_EQ(service->AddPrinters(printerInfos), E_PRINT_NONE); + EXPECT_EQ(service->UpdatePrinters(printerInfos), E_PRINT_NONE); + std::vector printerIds; + InitExtPrinterIdList(printerIds, 1); + std::shared_ptr info = std::make_shared(); + info->SetPrinterId(printerIds[0]); + std::string printerId = printerIds[0]; + service->printerInfoList_[printerId] = info; + EXPECT_EQ(service->RemovePrinters(printerIds), E_PRINT_NONE); + std::vector newPrinterIds; + newPrinterIds.push_back("1234"); + service->RemovePrinters(newPrinterIds); + printerInfos.clear(); + EXPECT_EQ(service->UpdatePrinters(printerInfos), E_PRINT_INVALID_PARAMETER); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0014, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + PrintJob testJob; + std::string jobId = GetDefaultJobId(); + testJob.SetJobId(jobId); + testJob.SetPrinterId(GetDefaultPrinterId()); + EXPECT_EQ(service->StartPrintJob(testJob), E_PRINT_INVALID_PRINTJOB); + std::shared_ptr job = std::make_shared(); + service->printJobList_["1"] = job; + EXPECT_EQ(service->StartPrintJob(testJob), E_PRINT_INVALID_PRINTJOB); + service->printJobList_["0"] = job; + EXPECT_EQ(service->StartPrintJob(testJob), E_PRINT_SERVER_FAILURE); + std::string extensionId = PrintUtils::GetExtensionId(GetDefaultPrinterId()); + sptr listener = nullptr; + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT); + service->extCallbackMap_[cid] = listener; + service->StartPrintJob(testJob); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0017, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + service->CallStatusBar(); + service->helper_= nullptr; + service->CallStatusBar(); + service->SetHelper(nullptr); + service->CallStatusBar(); + std::shared_ptr helper = std::make_shared(); + service->SetHelper(helper); + service->CallStatusBar(); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0018, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string jobId ="1"; + uint32_t state = PRINT_JOB_PREPARED; + uint32_t subState = PRINT_JOB_COMPLETED_SUCCESS; + service->notifyAdapterJobChanged(jobId, state, subState); + PrintAttributes attr; + service->printAttributesList_[jobId] = attr; + service->notifyAdapterJobChanged(jobId, state, subState); + sptr listener = nullptr; + service->adapterListenersByJobId_[jobId] = listener; + service->notifyAdapterJobChanged(jobId, state, subState); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0019, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string jobId ="1"; + uint32_t state = PRINT_JOB_PREPARED; + uint32_t subState = PRINT_JOB_COMPLETED_SUCCESS; + + state = PRINT_JOB_BLOCKED; + service->notifyAdapterJobChanged(jobId, state, subState); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0020, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string jobName = "a.jpeg"; + PrintAttributes printAttributes; + std::string taskId ="1"; + service->PrintByAdapter(jobName, printAttributes, taskId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0021, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string jobId = "1"; + PrintAttributes printAttributes; + uint32_t fd = 46; + sptr listener = nullptr; + service->adapterListenersByJobId_[jobId] = listener; + service->StartGetPrintFile(jobId, printAttributes, fd); + service->adapterListenersByJobId_.clear(); + + service->StartGetPrintFile(jobId, printAttributes, fd); + service->printAttributesList_[jobId] = printAttributes; + service->StartGetPrintFile(jobId, printAttributes, fd); + std::string newJobId = "2"; + service->StartGetPrintFile(newJobId, printAttributes, fd); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0022, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string printerId = "1234"; + EXPECT_EQ(service->getPrinterInfo(printerId), nullptr); + std::shared_ptr info =std::make_shared(); + service->printerInfoList_[printerId] = info; + service->getPrinterInfo(printerId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0024, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + PrintJob jobInfo; + service->CheckJobQueueBlocked(jobInfo); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0025, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string extensionId = "com.ohos.spooler:0"; + EXPECT_EQ(service->DelayStartDiscovery(extensionId), false); + service->extensionStateList_[extensionId] = PRINT_EXTENSION_UNLOAD; + EXPECT_EQ(service->DelayStartDiscovery(extensionId), false); + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_STOP_DISCOVERY); + sptr listener = nullptr; + service->extCallbackMap_[cid] = listener; + EXPECT_EQ(service->DelayStartDiscovery(extensionId), false); + cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_DISCOVERY); + service->extCallbackMap_.clear(); + service->extCallbackMap_[cid] = listener; + EXPECT_EQ(service->DelayStartDiscovery(extensionId), false); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0026, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + service->state_ = ServiceRunningState::STATE_NOT_START; + service->OnStop(); + service->state_ = ServiceRunningState::STATE_RUNNING; + service->OnStop(); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0028, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string extensionId = "com.ohos.spooler:0"; + service->extensionStateList_[extensionId] = PRINT_EXTENSION_UNLOAD; + EXPECT_EQ(service->StopDiscoverPrinter(), E_PRINT_NONE); + service->extensionStateList_[extensionId] = PRINT_EXTENSION_LOADED; + EXPECT_EQ(service->StopDiscoverPrinter(), E_PRINT_NONE); + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_STOP_DISCOVERY); + sptr listener = nullptr; + service->extCallbackMap_[cid] = listener; + EXPECT_EQ(service->StopDiscoverPrinter(), E_PRINT_NONE); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0029, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::vector printJobs; + int32_t userId = 100; + std::shared_ptr userData = std::make_shared(); + service->printUserMap_.insert(std::make_pair(userId, userData)); + service->QueryAllPrintJob(printJobs); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0030, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::vector printJobs; + service->QueryAllPrintJob(printJobs); + int32_t userId = 100; + service->printUserMap_.insert(std::make_pair(userId, nullptr)); + service->QueryAllPrintJob(printJobs); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0031, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::vector printerList; + EXPECT_EQ(service->QueryAddedPrinter(printerList), E_PRINT_INVALID_PRINTER); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0032, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + std::vector keyList; + std::vector valueList; + EXPECT_EQ(service->QueryPrinterProperties(printerId, keyList, valueList), E_PRINT_INVALID_PRINTER); + auto printerInfo = std::make_shared(); + service->printSystemData_.addedPrinterInfoList_[printerId] = printerInfo; + keyList.push_back("printerId"); + keyList.push_back("printerName"); + EXPECT_EQ(service->QueryPrinterProperties(printerId, keyList, valueList), E_PRINT_NONE); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0033, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + PrinterInfo info; + EXPECT_EQ(service->QueryPrinterInfoByPrinterId(printerId, info), E_PRINT_INVALID_PRINTER); + auto printerInfo = std::make_shared(); + printerInfo->name = "testName"; + printerInfo->uri = "testUri"; + printerInfo->maker = "testMaker"; + service->printSystemData_.addedPrinterMap_[printerId] = printerInfo; + EXPECT_EQ(service->QueryPrinterInfoByPrinterId(printerId, info), E_PRINT_INVALID_PRINTER); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0034, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string printJobId = "1"; + PrintJob printJob; + service->QueryPrintJobById(printJobId, printJob); + int32_t userId = 100; + service->printUserMap_.insert(std::make_pair(userId, nullptr)); + service->QueryPrintJobById(printJobId, printJob); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0035, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string printerUri = "testPrinterUri"; + std::string printerName = "testPrinterName"; + std::string printerMake = "testPrinterMake"; + EXPECT_EQ(service->AddPrinterToCups(printerUri, printerName, printerMake), E_PRINT_SERVER_FAILURE); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0036, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + PrintJob printJob1; + printJob1.SetOption("test"); + EXPECT_EQ(service->UpdatePrintJobOptionByPrinterId(printJob1), false); + + PrintJob printJob2; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + printJob2.SetPrinterId(printerId); + auto printerInfo = std::make_shared(); + printerInfo->name = "testName"; + printerInfo->uri = "testUri"; + printerInfo->maker = "testMaker"; + service->printSystemData_.addedPrinterMap_[printerId] = printerInfo; + EXPECT_EQ(service->UpdatePrintJobOptionByPrinterId(printJob2), false); + + nlohmann::json infoJson; + infoJson["printerName"] = "testPrinterName"; + printJob2.SetOption(infoJson.dump()); + EXPECT_EQ(service->UpdatePrintJobOptionByPrinterId(printJob2), true); + service->StartNativePrintJob(printJob2); + std::string extensionId = PrintUtils::GetExtensionId(printerId); + std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT); + sptr extCb = nullptr; + service->extCallbackMap_[cid] = extCb; + service->StartNativePrintJob(printJob2); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0037, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + PrintJob printJob; + std::string jobId = GetDefaultJobId(); + service->AddNativePrintJob(jobId, printJob); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0038, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + PrintJob printJob; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + printJob.SetPrinterId(printerId); + auto printerInfo = std::make_shared(); + printerInfo->name = "testName"; + printerInfo->uri = "testUri"; + printerInfo->maker = "testMaker"; + service->printSystemData_.addedPrinterMap_.insert(std::make_pair(printerId, printerInfo)); + printJob.SetOption("test"); + EXPECT_EQ(service->StartNativePrintJob(printJob), E_PRINT_INVALID_PRINTER); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0040, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::shared_ptr printJob = std::make_shared(); + std::string jobId = GetDefaultJobId(); + service->UpdateQueuedJobList(jobId, printJob); + service->UpdateQueuedJobList("0", printJob); + for (int i = 0; i < MAX_JOBQUEUE_NUM + 1; i++) { + service->queuedJobList_.insert(std::make_pair(std::to_string(i), printJob)); + } + service->UpdateQueuedJobList("515", printJob); + int32_t userId = 100; + service->printUserMap_.insert(std::make_pair(userId, nullptr)); + service->UpdateQueuedJobList("515", printJob); + service->printAppCount_ = 3; + std::string type ="0"; + EXPECT_EQ(service->NotifyPrintService(jobId, type), E_PRINT_NONE); + type = "spooler_closed_for_started"; + EXPECT_EQ(service->NotifyPrintService(jobId, type), E_PRINT_NONE); + type = "spooler_closed_for_cancelled"; + EXPECT_EQ(service->NotifyPrintService(jobId, type), E_PRINT_NONE); + type = ""; + EXPECT_EQ(service->NotifyPrintService(jobId, type), E_PRINT_INVALID_PARAMETER); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0041, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string jobId = GetDefaultJobId(); + service->CancelPrintJob(jobId); + int32_t userId = 100; + service->printUserMap_.insert(std::make_pair(userId, nullptr)); + service->CancelPrintJob(jobId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0042, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + PrintJob printJob; + printJob.SetJobId(GetDefaultJobId()); + service->SetPrintJobCanceled(printJob); + int32_t userId = 100; + service->printUserMap_.insert(std::make_pair(userId, nullptr)); + service->SetPrintJobCanceled(printJob); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0043, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + int32_t userId = 100; + service->CancelUserPrintJobs(userId); + + service->printUserMap_.insert(std::make_pair(userId, nullptr)); + service->CancelUserPrintJobs(userId); + + std::shared_ptr userData = std::make_shared(); + service->printUserMap_[userId] = userData; + service->CancelUserPrintJobs(userId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0044, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + PrintJob printJob; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + service->SendQueuePrintJob(printerId); + + std::string jobId = GetDefaultJobId(); + service->printerJobMap_[printerId].insert(std::make_pair(jobId, true)); + service->SendQueuePrintJob(printerId); + int32_t userId = 100; + std::shared_ptr userData = std::make_shared(); + service->printUserMap_[userId] = userData; + service->SendQueuePrintJob(printerId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0045, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string printerUri = "111.222.333"; + std::string printerId = "pixlab_0759"; + PrinterCapability printerCaps; + EXPECT_EQ(service->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps), E_PRINT_NONE); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0046, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string jobId = "1"; + std::shared_ptr printJob = std::make_shared(); + service->StartPrintJobCB(jobId, printJob); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0047, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + int32_t userId = 100; + service->SwitchUser(userId); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0048, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + uint32_t state = PRINTER_UNKNOWN + 1; + std::string printerId ="1234"; + service->UpdatePrinterState(printerId, state); + state = PrinterState::PRINTER_ADDED; + service->UpdatePrinterState(printerId, state); + std::shared_ptr info = std::make_shared(); + service->printerInfoList_[printerId] = info; + service->UpdatePrinterState(printerId, state); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0049, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string jobId = "1"; + uint32_t state = PRINTER_UNKNOWN + 1; + uint32_t subState = 0; + EXPECT_EQ(service->checkJobState(state, subState), true); + service->UpdatePrintJobState(jobId, state, subState); + state = PRINT_JOB_BLOCKED; + subState = PRINT_JOB_BLOCKED_OFFLINE - 1; + EXPECT_EQ(service->checkJobState(state, subState), false); + EXPECT_EQ(service->UpdatePrintJobState(jobId, state, subState), E_PRINT_INVALID_PARAMETER); + subState = PRINT_JOB_BLOCKED_UNKNOWN + 1; + EXPECT_EQ(service->checkJobState(state, subState), false); + EXPECT_EQ(service->UpdatePrintJobState(jobId, state, subState), E_PRINT_INVALID_PARAMETER); + state = PRINT_JOB_COMPLETED; + subState = PRINT_JOB_COMPLETED_FILE_CORRUPT + 1; + EXPECT_EQ(service->checkJobState(state, subState), false); + EXPECT_EQ(service->UpdatePrintJobState(jobId, state, subState), E_PRINT_INVALID_PARAMETER); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0050, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string jobId = "1"; + uint32_t state = PRINT_JOB_CREATE_FILE_COMPLETED; + uint32_t subState = 0; + EXPECT_EQ(service->UpdatePrintJobState(jobId, state, subState), false); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0051, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string jobId = "1"; + uint32_t state = PRINTER_UNKNOWN; + uint32_t subState = 0; + EXPECT_EQ(service->AdapterGetFileCallBack(jobId, state, subState), E_PRINT_NONE); + std::string type = "PRINT_GET_FILE_EVENT_TYPE"; + sptr listener = new MockPrintCallbackProxy(); + service->registeredListeners_[type] = listener; + service->AdapterGetFileCallBack(jobId, state, subState); + subState = PRINT_JOB_CREATE_FILE_COMPLETED_SUCCESS; + service->AdapterGetFileCallBack(jobId, state, subState); + subState = PRINT_JOB_CREATE_FILE_COMPLETED_FAILED; + service->AdapterGetFileCallBack(jobId, state, subState); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0052, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string jobId = "1"; + int32_t userId = 100; + std::shared_ptr userData = std::make_shared(); + service->printUserMap_[userId] = userData; + uint32_t state = PRINTER_UNKNOWN; + uint32_t subState = 0; + service->CheckAndSendQueuePrintJob(jobId, state, subState); + std::shared_ptr printJob = std::make_shared(); + userData->printJobList_[jobId] = printJob; + service->CheckAndSendQueuePrintJob(jobId, state, subState); + state = PRINT_JOB_BLOCKED; + service->CheckAndSendQueuePrintJob(jobId, state, subState); + state = PRINT_JOB_COMPLETED; + service->CheckAndSendQueuePrintJob(jobId, state, subState); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0053, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::string jobId = "1"; + EXPECT_EQ(service->IsQueuedJobListEmpty(jobId), true); + int32_t userId = 100; + std::shared_ptr userData = std::make_shared(); + std::shared_ptr printJob = std::make_shared(); + userData->printJobList_[jobId] = printJob; + service->printUserMap_[userId] = userData; + EXPECT_EQ(service->IsQueuedJobListEmpty(jobId), true); + userData->printJobList_.clear(); + service->currentUserId_ = 0; + EXPECT_EQ(service->IsQueuedJobListEmpty(jobId), true); + service->currentUserId_ = 100; + EXPECT_EQ(service->IsQueuedJobListEmpty(jobId), true); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0055, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + uint32_t event = -1; + std::string jobId = GetDefaultJobId(); + EXPECT_EQ(service->NotifyPrintServiceEvent(jobId, event), E_PRINT_INVALID_PARAMETER); + event = 3; + EXPECT_EQ(service->NotifyPrintServiceEvent(jobId, event), E_PRINT_INVALID_PARAMETER); + event = 0; + service->NotifyPrintServiceEvent(jobId, event); + event = 1; + service->NotifyPrintServiceEvent(jobId, event); + event = 2; + service->NotifyPrintServiceEvent(jobId, event); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0056, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr helper = std::make_shared(); + service->helper_ = helper; + std::string type = ""; + sptr listener = nullptr; + EXPECT_EQ(service->RegisterPrinterCallback(type, listener), E_PRINT_INVALID_PARAMETER); + EXPECT_EQ(service->UnregisterPrinterCallback(type), E_PRINT_INVALID_TOKEN); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0057, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + int event = 0; + PrinterInfo info; + service->SendPrinterChangeEvent(event, info); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0058, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + std::shared_ptr jobInfo = std::make_shared(); + std::string printerId = "1234"; + uint32_t subState = 0; + service->ReportHisysEvent(jobInfo, printerId, subState); + printerId = "ePrintID"; + service->ReportHisysEvent(jobInfo, printerId, subState); + std::shared_ptr printInfo = std::make_shared(); + printInfo->SetPrinterName("Direct0759"); + service->printerInfoList_[printerId] = printInfo; + service->ReportHisysEvent(jobInfo, printerId, subState); + nlohmann::json infoJson; + infoJson["printerUri"] = "ipp123"; + jobInfo->SetOption(infoJson.dump()); + service->ReportHisysEvent(jobInfo, printerId, subState); + infoJson["jobDescription"] = "testPrinter"; + jobInfo->SetOption(infoJson.dump()); + service->ReportHisysEvent(jobInfo, printerId, subState); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0059, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + PrintJob jobInfo; + std::string previewResult = ""; + service->RequestPreview(jobInfo, previewResult); + + std::string extensionId = "DEFAULT_EXTENSION_ID"; + std::string extInfo = "spooler"; + service->SendExtensionEvent(extensionId, extInfo); + EXPECT_EQ(service->UnregisterAllExtCallback(extensionId), E_PRINT_NONE); +} + +HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0060, TestSize.Level1) +{ + auto service = std::make_shared(PRINT_SERVICE_ID, true); + AppExecFwk::ExtensionAbilityInfo extInfo; + extInfo.bundleName = "spooler"; + + PrintExtensionInfo newExtInfo; + newExtInfo = service->ConvertToPrintExtensionInfo(extInfo); +} + // namespace Print +} // namespace OHOS diff --git a/test/unittest/fwk_print_service_ability_test/print_service_mock_permission.cpp b/test/unittest/fwk_print_service_ability_test/print_service_mock_permission.cpp new file mode 100644 index 0000000..35818c6 --- /dev/null +++ b/test/unittest/fwk_print_service_ability_test/print_service_mock_permission.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_service_mock_permission.h" + +#include "nativetoken_kit.h" +#include "token_setproc.h" + +namespace OHOS { +namespace Print { +void PrintServiceMockPermission::MockPermission() +{ + static const char *PERMS[] = { + "ohos.permission.PRINT", + "ohos.permission.MANAGE_PRINT_JOB" + }; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = PERMS, + .acls = nullptr, + .processName = "print_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); +} +} +} \ No newline at end of file diff --git a/test/unittest/service_test/BUILD.gn b/test/unittest/service_test/BUILD.gn index aa657d1..a874ed8 100644 --- a/test/unittest/service_test/BUILD.gn +++ b/test/unittest/service_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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 @@ -14,7 +14,7 @@ import("//base/print/print_fwk/print.gni") import("//build/test.gni") -module_output_path = "print/print_fwk" +module_output_path = "print_fwk/service_test" ohos_unittest("print_service_test") { module_out_path = module_output_path @@ -29,17 +29,22 @@ ohos_unittest("print_service_test") { "//third_party/node/src", ] + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${print_path}/cfi_blocklist.txt" + } + sources = [ "print_bms_death_recipient_test.cpp", - "print_bms_helper_test.cpp", - "print_callback_proxy_test.cpp", - "print_extension_callback_proxy_test.cpp", + "print_cups_attribute_test.cpp", "print_security_guard_info_test.cpp", "print_security_guard_manager_test.cpp", - "print_service_ability_test.cpp", + "print_service_converter_test.cpp", "print_service_helper_test.cpp", - "print_service_mock_permission.cpp", - "print_service_stub_test.cpp", + "print_system_data_test.cpp", + "print_user_data_test.cpp", ] deps = [ @@ -54,12 +59,12 @@ ohos_unittest("print_service_test") { "${print_path}/profile:print_sa_profiles", "${print_path}/services/print_service:print_service", "//third_party/googletest:gmock_main", + "//third_party/jsoncpp:jsoncpp", "//third_party/zlib:libz", ] if (cups_enable) { include_dirs += [ "//third_party/cups/cups-2.4.0" ] - sources += [ "print_cups_client_test.cpp" ] cflags_cc = [ "-DCUPS_ENABLE" ] deps += [ "//third_party/cups:third_party_cups", @@ -67,6 +72,18 @@ ohos_unittest("print_service_test") { ] } + if (ipp_over_usb_enable) { + include_dirs += [ "//third_party/cpp-httplib" ] + sources += [ + "print_http_request_process_test.cpp", + "print_http_server_manager_test.cpp", + "print_ipp_over_usb_manager_test.cpp", + "print_usb_manager_test.cpp", + ] + cflags_cc += [ "-DCPPHTTPLIB_NO_EXCEPTIONS" ] + cflags_cc += [ "-DIPPOVERUSB_ENABLE" ] + } + external_deps = [ "ability_base:base", "ability_base:want", @@ -79,11 +96,13 @@ ohos_unittest("print_service_test") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", + "drivers_interface_usb:libusb_proxy_1.0", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "usb_manager:usbsrv_client", ] } diff --git a/test/unittest/service_test/mock/mock_bundle_mgr.h b/test/unittest/service_test/mock/mock_bundle_mgr.h index 8fc5057..d7bcf9f 100644 --- a/test/unittest/service_test/mock/mock_bundle_mgr.h +++ b/test/unittest/service_test/mock/mock_bundle_mgr.h @@ -18,6 +18,7 @@ #include #include "iremote_object.h" +#include "iremote_broker.h" #include "bundle_mgr_proxy.h" namespace OHOS { diff --git a/test/unittest/service_test/mock/mock_print_service.h b/test/unittest/service_test/mock/mock_print_service.h index eca389e..91aa5e7 100644 --- a/test/unittest/service_test/mock/mock_print_service.h +++ b/test/unittest/service_test/mock/mock_print_service.h @@ -28,11 +28,6 @@ public: { return E_PRINT_NONE; } - int32_t StartPrint(const std::vector &fileList, - const std::vector &fdList, std::string &taskId, const sptr &token) override - { - return E_PRINT_NONE; - } int32_t StopPrint(const std::string &taskId) override { return E_PRINT_NONE; @@ -57,7 +52,7 @@ public: { return E_PRINT_NONE; } - int32_t StartPrintJob(const PrintJob &jobInfo) override + int32_t StartPrintJob(PrintJob &jobInfo) override { return E_PRINT_NONE; } @@ -81,7 +76,7 @@ public: { return E_PRINT_NONE; } - int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) override + int32_t UpdatePrintJobStateOnlyForSystemApp(const std::string &jobId, uint32_t state, uint32_t subState) override { return E_PRINT_NONE; } @@ -137,7 +132,7 @@ public: return E_PRINT_NONE; } int32_t PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes, - std::string &taskId, const sptr &token) override + std::string &taskId) override { return E_PRINT_NONE; } @@ -150,26 +145,74 @@ public: { return E_PRINT_NONE; } + int32_t StartService() override + { + return E_PRINT_NONE; + } + int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) override + { + return E_PRINT_NONE; + } + int32_t QueryAddedPrinter(std::vector &printerNameList) override + { + return E_PRINT_NONE; + } + int32_t QueryPrinterProperties(const std::string &printerId, const std::vector &keyList, + std::vector &valueList) override + { + return E_PRINT_NONE; + } + int32_t RegisterPrinterCallback(const std::string &type, const sptr &listener) override + { + return E_PRINT_NONE; + } + int32_t UnregisterPrinterCallback(const std::string &type) override + { + return E_PRINT_NONE; + } + int32_t StartNativePrintJob(PrintJob &printJob) override + { + return E_PRINT_NONE; + } + int32_t NotifyPrintServiceEvent(std::string &jobId, uint32_t event) override + { + return E_PRINT_NONE; + } + int32_t GetPrinterPreference(const std::string &printerId, std::string &printerPreference) override + { + return E_PRINT_NONE; + } + int32_t SetPrinterPreference(const std::string &printerId, const std::string &printerPreference) override + { + return E_PRINT_NONE; + } + int32_t SetDefaultPrinter(const std::string &printerId) override + { + return E_PRINT_NONE; + } + int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName, + const std::string &printerMake) override + { + return E_PRINT_NONE; + } }; class MockPrintService final : public DummyPrintServiceStub { public: MOCK_METHOD3(StartPrint, int32_t(const std::vector&, const std::vector&, std::string &)); - MOCK_METHOD4(StartPrint, int32_t(const std::vector&, const std::vector&, - std::string &, const sptr &)); MOCK_METHOD1(StopPrint, int32_t(const std::string&)); MOCK_METHOD1(ConnectPrinter, int32_t(const std::string&)); MOCK_METHOD1(DisconnectPrinter, int32_t(const std::string&)); MOCK_METHOD1(StartDiscoverPrinter, int32_t(const std::vector&)); MOCK_METHOD0(StopDiscoverPrinter, int32_t()); MOCK_METHOD1(QueryAllExtension, int32_t(std::vector&)); - MOCK_METHOD1(StartPrintJob, int32_t(const PrintJob &)); + MOCK_METHOD1(StartPrintJob, int32_t(PrintJob &)); MOCK_METHOD1(CancelPrintJob, int32_t(const std::string&)); MOCK_METHOD1(AddPrinters, int32_t(const std::vector&)); MOCK_METHOD1(RemovePrinters, int32_t(const std::vector&)); MOCK_METHOD1(UpdatePrinters, int32_t(const std::vector&)); MOCK_METHOD2(UpdatePrinterState, int32_t(const std::string&, uint32_t)); - MOCK_METHOD3(UpdatePrintJobState, int32_t(const std::string&, uint32_t, uint32_t)); + MOCK_METHOD3(UpdatePrintJobStateOnlyForSystemApp, int32_t(const std::string&, uint32_t, uint32_t)); MOCK_METHOD1(UpdateExtensionInfo, int32_t(const std::string&)); MOCK_METHOD2(RequestPreview, int32_t(const PrintJob&, std::string&)); MOCK_METHOD1(QueryPrinterCapability, int32_t(const std::string&)); @@ -182,6 +225,9 @@ public: MOCK_METHOD2(QueryPrintJobById, int32_t(std::string&, PrintJob&)); MOCK_METHOD3(AddPrinterToCups, int32_t(const std::string&, const std::string&, const std::string&)); MOCK_METHOD3(QueryPrinterCapabilityByUri, int32_t(const std::string&, const std::string&, PrinterCapability&)); + MOCK_METHOD2(NotifyPrintServiceEvent, int32_t(std::string&, uint32_t)); + MOCK_METHOD1(SetDefaultPrinter, int32_t(const std::string&)); + MOCK_METHOD3(DeletePrinterFromCups, int32_t(const std::string&, const std::string&, const std::string&)); }; } // namespace Print } // namespace OHOS diff --git a/test/unittest/service_test/mock/mock_print_service_helper.h b/test/unittest/service_test/mock/mock_print_service_helper.h index 62fd4a2..3dcb59f 100644 --- a/test/unittest/service_test/mock/mock_print_service_helper.h +++ b/test/unittest/service_test/mock/mock_print_service_helper.h @@ -25,8 +25,6 @@ class MockPrintServiceHelper final : public PrintServiceHelper { public: MOCK_METHOD1(CheckPermission, bool(const std::string&)); MOCK_METHOD1(StartAbility, bool(const AAFwk::Want&)); - MOCK_METHOD1(KillAbility, bool(const std::string&)); - MOCK_METHOD2(StartPrintServiceExtension, bool(const AAFwk::Want&, int32_t)); MOCK_METHOD0(GetBundleMgr, sptr()); MOCK_METHOD1(QueryAccounts, bool(std::vector&)); MOCK_METHOD3(QueryExtension, bool(sptr, int, diff --git a/test/unittest/service_test/print_bms_death_recipient_test.cpp b/test/unittest/service_test/print_bms_death_recipient_test.cpp index 914e027..e273f5c 100644 --- a/test/unittest/service_test/print_bms_death_recipient_test.cpp +++ b/test/unittest/service_test/print_bms_death_recipient_test.cpp @@ -38,18 +38,6 @@ void PrintBMSDeathRecipientTest::SetUp(void) {} void PrintBMSDeathRecipientTest::TearDown(void) {} -/** -* @tc.name: PrintBMSDeathRecipientTest_0001 -* @tc.desc: OnRemoteRequest -* @tc.type: FUNC -* @tc.require: -*/ -HWTEST_F(PrintBMSDeathRecipientTest, PrintBMSDeathRecipientTest_0001, TestSize.Level1) -{ - PrintBMSDeathRecipient dr; - wptr testRemote = nullptr; - dr.OnRemoteDied(testRemote); -} } // namespace Print } // namespace OHOS diff --git a/test/unittest/service_test/print_callback_proxy_test.cpp b/test/unittest/service_test/print_callback_proxy_test.cpp index bd99ddf..b7401c7 100644 --- a/test/unittest/service_test/print_callback_proxy_test.cpp +++ b/test/unittest/service_test/print_callback_proxy_test.cpp @@ -22,6 +22,7 @@ #include "system_ability_definition.h" #include "mock_remote_object.h" #include "mock_print_callback_stub.h" +#include "print_log.h" using namespace testing; using namespace testing::ext; @@ -40,7 +41,11 @@ void PrintCallbackProxyTest::SetUpTestCase(void) {} void PrintCallbackProxyTest::TearDownTestCase(void) {} -void PrintCallbackProxyTest::SetUp(void) {} +void PrintCallbackProxyTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintCallbackProxyTest_%{public}d", ++testNo); +} void PrintCallbackProxyTest::TearDown(void) {} @@ -228,6 +233,7 @@ HWTEST_F(PrintCallbackProxyTest, PrintCallbackProxyTest_0006, TestSize.Level1) EXPECT_FALSE(proxy->OnCallback(testState, testJob)); } + /** * @tc.name: PrintCallbackProxyTest_0007 * @tc.desc: printCallbackProxy @@ -242,22 +248,18 @@ HWTEST_F(PrintCallbackProxyTest, PrintCallbackProxyTest_0007, TestSize.Level1) EXPECT_NE(proxy, nullptr); auto service = std::make_shared(); EXPECT_NE(service, nullptr); - - std::string extensionId = "com.sample.ext"; - std::string extInfo = "custom extension info"; - - EXPECT_CALL(*service, OnCallback(extensionId, extInfo)).Times(1).WillOnce(Return(true)); EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); ON_CALL(*obj, SendRequest) .WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { service->OnRemoteRequest(code, data, reply, option); - return E_PRINT_NONE; + return E_PRINT_RPC_FAILURE; }); - EXPECT_TRUE(proxy->OnCallback(extensionId, extInfo)); + uint32_t testState = 0; + EXPECT_FALSE(proxy->OnCallbackAdapterGetFile(testState)); } - + /** - * @tc.name: PrintCallbackProxyTest_0007 + * @tc.name: PrintCallbackProxyTest_0008 * @tc.desc: printCallbackProxy * @tc.type: FUNC * @tc.require: @@ -270,18 +272,44 @@ HWTEST_F(PrintCallbackProxyTest, PrintCallbackProxyTest_0008, TestSize.Level1) EXPECT_NE(proxy, nullptr); auto service = std::make_shared(); EXPECT_NE(service, nullptr); - - std::string extensionId = "com.sample.ext"; - std::string extInfo = "custom extension info"; - - EXPECT_CALL(*service, OnCallback(extensionId, extInfo)).Times(1).WillOnce(Return(true)); EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); ON_CALL(*obj, SendRequest) .WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { service->OnRemoteRequest(code, data, reply, option); return E_PRINT_RPC_FAILURE; }); - EXPECT_FALSE(proxy->OnCallback(extensionId, extInfo)); + uint32_t testState = 0; + uint32_t testSubState = 0; + std::string jobId = "job:1234"; + EXPECT_FALSE(proxy->onCallbackAdapterJobStateChanged(jobId, testState, testSubState)); } + +/** + * @tc.name: PrintCallbackProxyTest_0009 + * @tc.desc: printCallbackProxy + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintCallbackProxyTest, PrintCallbackProxyTest_0009, TestSize.Level1) +{ + sptr obj = new (std::nothrow) MockRemoteObject(); + EXPECT_NE(obj, nullptr); + auto proxy = std::make_shared(obj); + EXPECT_NE(proxy, nullptr); + auto service = std::make_shared(); + EXPECT_NE(service, nullptr); + EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1); + ON_CALL(*obj, SendRequest) + .WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + service->OnRemoteRequest(code, data, reply, option); + return E_PRINT_RPC_FAILURE; + }); + uint32_t testState = 0; + uint32_t testSubState = 0; + std::string jobId = "job:1234"; + EXPECT_FALSE(proxy->onCallbackAdapterJobStateChanged(jobId, testState, testSubState)); +} + + } // namespace Print } // namespace OHOS diff --git a/test/unittest/service_test/print_cups_attribute_test.cpp b/test/unittest/service_test/print_cups_attribute_test.cpp new file mode 100644 index 0000000..ed720bf --- /dev/null +++ b/test/unittest/service_test/print_cups_attribute_test.cpp @@ -0,0 +1,578 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "print_cups_attribute.h" + +using namespace testing; +using namespace testing::ext; +using json = nlohmann::json; + +namespace { +const char *const ATTR_TEST_ALL[] = {"all"}; +const size_t ATTR_TEST_SIDES_COUNT = 3; +const char *const ATTR_TEST_SIDES_ARRAY[ATTR_TEST_SIDES_COUNT] = { + "one-sided", "two-sided-long-edge", "two-sided-short-edge"}; + +const size_t ATTR_TEST_COLOR_MODE_COUNT = 2; +const char *const ATTR_TEST_COLOR_MODE_ARRAY[ATTR_TEST_COLOR_MODE_COUNT] = {"monochrome", "color"}; + +const size_t ATTR_TEST_PAGE_SIZE_COUNT = 4; +const char *const ATTR_TEST_PAGE_SIZE_ARRAY[ATTR_TEST_PAGE_SIZE_COUNT] = { + "iso_b3_353x500mm", "iso_a4_210x297mm", "na_letter_8.5x11in", "om_card_54x86mm"}; + +const size_t ATTR_TEST_QUALITY_COUNT = 3; +const int ATTR_TEST_QUALITY_ARRAY[ATTR_TEST_QUALITY_COUNT] = {IPP_QUALITY_DRAFT, IPP_QUALITY_NORMAL, IPP_QUALITY_HIGH}; +const int ATTR_TEST_MAX_COPIES = 99; +const int ATTR_TEST_RESOLUTION_SMALL = 250; // need change +const int ATTR_TEST_RESOLUTION_DEFAULT = 600; +const int ATTR_TEST_RESULUTION_SMALL_DPCM = 100; + +const int ATTR_TEST_PAPER_LEFT = 100; +const int ATTR_TEST_PAPER_RIGHT = 200; +const int ATTR_TEST_PAPER_TOP = 300; +const int ATTR_TEST_PAPER_BOTTOM = 400; + +const int ATTR_TEST_ORIENTATION_COUNT = 3; +const int ATTR_TEST_ORIENTATION_ARRAY[ATTR_TEST_ORIENTATION_COUNT] = { + IPP_ORIENT_PORTRAIT, IPP_ORIENT_LANDSCAPE, IPP_ORIENT_REVERSE_PORTRAIT}; + +const int ATTR_TEST_SOURCE_COUNT = 2; +const char *const ATTR_TEST_SOURCE_ARRAY[ATTR_TEST_SOURCE_COUNT] = {"main source", "front slot"}; + +const int ATTR_TEST_DOCUMENT_HANDLING_COUNT = 2; +const char *const ATTR_TEST_DOCUMENT_HANDLING_ARRAY[] = {"separate-uncollated", "multi-collated"}; + +const int ATTR_TEST_MEDIA_TYPE_COUNT = 3; +const char *const ATTR_TEST_MEDIA_TYPE_ARRAY[ATTR_TEST_MEDIA_TYPE_COUNT] = {"envelope", "stationery", "transparency"}; + +void TestAttrCount(const std::string &jsonString, int count) +{ + EXPECT_TRUE(json::accept(jsonString)); + auto jsonObject = json::parse(jsonString); + EXPECT_TRUE(jsonObject.is_array()); + EXPECT_EQ(jsonObject.size(), count); +} +} // namespace + +namespace OHOS::Print { +using PreAttrTestFunc = std::function; +using PostAttrTestFunc = std::function; +class PrintCupsAttributeTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + void DoTest(PreAttrTestFunc preFunc, PostAttrTestFunc postFunc); +}; + +void PrintCupsAttributeTest::SetUpTestCase(void) +{} + +void PrintCupsAttributeTest::TearDownTestCase(void) +{} + +void PrintCupsAttributeTest::SetUp(void) +{} + +void PrintCupsAttributeTest::TearDown(void) +{} + +void PrintCupsAttributeTest::DoTest(PreAttrTestFunc preFunc, PostAttrTestFunc postFunc) +{ + if (preFunc == nullptr || postFunc == nullptr) { + return; + } + ipp_t *request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES); + if (request == nullptr) { + return; + } + ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", nullptr, "printer-uri"); + ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", nullptr, "user"); + ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", 1, nullptr, ATTR_TEST_ALL); + ipp_t *response = ippNewResponse(request); + ippDelete(request); + request = nullptr; + if (response == nullptr) { + return; + } + preFunc(response); + PrinterCapability printerCaps; + ParsePrinterAttributes(response, printerCaps); + ippDelete(response); + response = nullptr; + postFunc(printerCaps); +} + +/** + * @tc.name: PrintCupsAttributeTest_0001 + * @tc.desc: printer idle state test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0001, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", IPP_PRINTER_IDLE); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", nullptr, "Printer info test"); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", nullptr, "Printer location test"); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-state"), "idle"); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-location"), "Printer location test"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0002 + * @tc.desc: printer processing state test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0002, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", IPP_PRINTER_PROCESSING); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", nullptr, ""); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", nullptr, ""); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-state"), "processing"); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-info"), ""); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-location"), ""); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0003 + * @tc.desc: printer stopped state test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0003, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", IPP_PRINTER_STOPPED); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-state"), "stopped"); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-info"), ""); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-location"), ""); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0004 + * @tc.desc: printer empty state test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0004, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) {}; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-state"), ""); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-info"), ""); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("printer-location"), ""); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0005 + * @tc.desc: printer sides test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0005, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddStrings(response, + IPP_TAG_PRINTER, + IPP_TAG_KEYWORD, + "sides-supported", + ATTR_TEST_SIDES_COUNT, + nullptr, + ATTR_TEST_SIDES_ARRAY); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "sides-default", nullptr, ATTR_TEST_SIDES_ARRAY[0]); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string sideString = printerCaps.GetPrinterAttrValue("sides-supported"); + TestAttrCount(sideString, ATTR_TEST_SIDES_COUNT); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("sides-default"), "0"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0006 + * @tc.desc: printer sides test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0006, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "sides-default", nullptr, ATTR_TEST_SIDES_ARRAY[1]); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string sideString = printerCaps.GetPrinterAttrValue("sides-supported"); + TestAttrCount(sideString, 0); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("sides-default"), "1"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0007 + * @tc.desc: printer color mode test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0007, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddStrings(response, + IPP_TAG_PRINTER, + IPP_TAG_KEYWORD, + "print-color-mode-supported", + ATTR_TEST_COLOR_MODE_COUNT, + nullptr, + ATTR_TEST_COLOR_MODE_ARRAY); + ippAddString(response, + IPP_TAG_PRINTER, + IPP_TAG_KEYWORD, + "print-color-mode-default", + nullptr, + ATTR_TEST_COLOR_MODE_ARRAY[0]); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string colorModeString = printerCaps.GetPrinterAttrValue("print-color-mode-supported"); + TestAttrCount(colorModeString, ATTR_TEST_COLOR_MODE_COUNT); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("defaultColorMode"), "0"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0008 + * @tc.desc: printer color mode test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0008, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddString(response, + IPP_TAG_PRINTER, + IPP_TAG_KEYWORD, + "print-color-mode-default", + nullptr, + ATTR_TEST_COLOR_MODE_ARRAY[1]); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string colorModeString = printerCaps.GetPrinterAttrValue("print-color-mode-supported"); + TestAttrCount(colorModeString, 0); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("defaultColorMode"), "1"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0009 + * @tc.desc: printer page size test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0009, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddStrings(response, + IPP_TAG_PRINTER, + IPP_TAG_KEYWORD, + "media-supported", + ATTR_TEST_PAGE_SIZE_COUNT, + nullptr, + ATTR_TEST_PAGE_SIZE_ARRAY); + ippAddString( + response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-default", nullptr, ATTR_TEST_PAGE_SIZE_ARRAY[0]); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string pageSizeString = printerCaps.GetPrinterAttrValue("supportedPageSizeArray"); + TestAttrCount(pageSizeString, ATTR_TEST_PAGE_SIZE_COUNT); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("defaultPageSizeId"), "ISO_B3"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0010 + * @tc.desc: printer page size test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0010, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddString(response, + IPP_TAG_PRINTER, + IPP_TAG_KEYWORD, + "print-color-mode-default", + nullptr, + ATTR_TEST_COLOR_MODE_ARRAY[1]); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string pageSizeString = printerCaps.GetPrinterAttrValue("print-color-mode-supported"); + TestAttrCount(pageSizeString, 0); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("defaultPageSizeId"), ""); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0011 + * @tc.desc: printer quality / copies test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0011, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddIntegers(response, + IPP_TAG_PRINTER, + IPP_TAG_ENUM, + "print-quality-supported", + ATTR_TEST_QUALITY_COUNT, + ATTR_TEST_QUALITY_ARRAY); + ippAddRange(response, IPP_TAG_PRINTER, "copies-supported", 1, ATTR_TEST_MAX_COPIES); + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "copies-default", 1); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string qualityString = printerCaps.GetPrinterAttrValue("print-quality-supported"); + TestAttrCount(qualityString, ATTR_TEST_QUALITY_COUNT); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("copies-supported"), std::to_string(ATTR_TEST_MAX_COPIES).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("copies-default"), "1"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0012 + * @tc.desc: printer quality / copies test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0012, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) {}; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string pageSizeString = printerCaps.GetPrinterAttrValue("print-quality-supported"); + EXPECT_TRUE(pageSizeString.empty()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("copies-supported"), ""); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("copies-default"), ""); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0013 + * @tc.desc: printer resolution test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0013, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddResolution(response, + IPP_TAG_PRINTER, + "printer-resolution-supported", + IPP_RES_PER_INCH, + ATTR_TEST_RESOLUTION_DEFAULT, + ATTR_TEST_RESOLUTION_DEFAULT); + ippAddResolution(response, + IPP_TAG_PRINTER, + "printer-resolution-default", + IPP_RES_PER_INCH, + ATTR_TEST_RESOLUTION_DEFAULT, + ATTR_TEST_RESOLUTION_DEFAULT); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string supportedResolutionString = printerCaps.GetPrinterAttrValue("printer-resolution-supported"); + TestAttrCount(supportedResolutionString, 1); + std::string defaultResolutionString = printerCaps.GetPrinterAttrValue("printer-resolution-default"); + EXPECT_TRUE(json::accept(defaultResolutionString)); + auto defaultResolutionJson = json::parse(defaultResolutionString); + EXPECT_TRUE(defaultResolutionJson.contains("horizontalDpi")); + EXPECT_TRUE(defaultResolutionJson.contains("verticalDpi")); + EXPECT_TRUE(defaultResolutionJson["horizontalDpi"].is_number()); + EXPECT_TRUE(defaultResolutionJson["verticalDpi"].is_number()); + EXPECT_EQ(defaultResolutionJson["horizontalDpi"], ATTR_TEST_RESOLUTION_DEFAULT); + EXPECT_EQ(defaultResolutionJson["verticalDpi"], ATTR_TEST_RESOLUTION_DEFAULT); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0014 + * @tc.desc: printer resolution test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0014, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddResolution(response, + IPP_TAG_PRINTER, + "printer-resolution-default", + IPP_RES_PER_CM, + ATTR_TEST_RESULUTION_SMALL_DPCM, + ATTR_TEST_RESULUTION_SMALL_DPCM); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string supportedResolutionString = printerCaps.GetPrinterAttrValue("printer-resolution-supported"); + EXPECT_TRUE(supportedResolutionString.empty()); + std::string defaultResolutionString = printerCaps.GetPrinterAttrValue("printer-resolution-default"); + EXPECT_TRUE(json::accept(defaultResolutionString)); + auto defaultResolutionJson = json::parse(defaultResolutionString); + EXPECT_TRUE(defaultResolutionJson.contains("horizontalDpi")); + EXPECT_TRUE(defaultResolutionJson.contains("verticalDpi")); + EXPECT_TRUE(defaultResolutionJson["horizontalDpi"].is_number()); + EXPECT_TRUE(defaultResolutionJson["verticalDpi"].is_number()); + EXPECT_EQ(defaultResolutionJson["horizontalDpi"], ATTR_TEST_RESOLUTION_SMALL); + EXPECT_EQ(defaultResolutionJson["verticalDpi"], ATTR_TEST_RESOLUTION_SMALL); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0015 + * @tc.desc: printer media test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0015, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + auto mediaCol = ippNew(); + if (mediaCol == nullptr) { + return; + } + ippAddInteger(mediaCol, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-bottom-margin", ATTR_TEST_PAPER_BOTTOM); + ippAddInteger(mediaCol, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-left-margin", ATTR_TEST_PAPER_LEFT); + ippAddInteger(mediaCol, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-right-margin", ATTR_TEST_PAPER_RIGHT); + ippAddInteger(mediaCol, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-top-margin", ATTR_TEST_PAPER_TOP); + ippAddBoolean(mediaCol, IPP_TAG_PRINTER, "duplex-supported", 1); + ippAddString(mediaCol, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-source", nullptr, "Front Input Slot"); + ippAddString(mediaCol, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-type", nullptr, "stationery"); + ippAddCollection(response, IPP_TAG_PRINTER, "media-col-default", mediaCol); + ippDelete(mediaCol); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ( + printerCaps.GetPrinterAttrValue("media-top-margin-default"), std::to_string(ATTR_TEST_PAPER_TOP).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-bottom-margin-default"), + std::to_string(ATTR_TEST_PAPER_BOTTOM).c_str()); + EXPECT_STREQ( + printerCaps.GetPrinterAttrValue("media-left-margin-default"), std::to_string(ATTR_TEST_PAPER_LEFT).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-right-margin-default"), + std::to_string(ATTR_TEST_PAPER_RIGHT).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-source-default"), "Front Input Slot"); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-type-default"), "stationery"); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0016 + * @tc.desc: printer margin test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0016, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddInteger( + response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-bottom-margin-supported", ATTR_TEST_PAPER_BOTTOM); + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-left-margin-supported", ATTR_TEST_PAPER_LEFT); + ippAddInteger( + response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-right-margin-supported", ATTR_TEST_PAPER_RIGHT); + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-top-margin-supported", ATTR_TEST_PAPER_TOP); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ( + printerCaps.GetPrinterAttrValue("media-top-margin-supported"), std::to_string(ATTR_TEST_PAPER_TOP).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-bottom-margin-supported"), + std::to_string(ATTR_TEST_PAPER_BOTTOM).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-left-margin-supported"), + std::to_string(ATTR_TEST_PAPER_LEFT).c_str()); + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("media-right-margin-supported"), + std::to_string(ATTR_TEST_PAPER_RIGHT).c_str()); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0017 + * @tc.desc: printer orientation test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0017, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "orientation-requested-default", IPP_ORIENT_PORTRAIT); + ippAddIntegers(response, + IPP_TAG_PRINTER, + IPP_TAG_ENUM, + "orientation-requested-supported", + ATTR_TEST_ORIENTATION_COUNT, + ATTR_TEST_ORIENTATION_ARRAY); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + EXPECT_STREQ(printerCaps.GetPrinterAttrValue("orientation-requested-default"), "3"); + std::string orientationString = printerCaps.GetPrinterAttrValue("orientation-requested-supported"); + TestAttrCount(orientationString, ATTR_TEST_ORIENTATION_COUNT); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0018 + * @tc.desc: printer other attributes test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0018, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddStrings(response, + IPP_TAG_PRINTER, + IPP_CONST_TAG(IPP_TAG_KEYWORD), + "media-source-supported", + ATTR_TEST_SOURCE_COUNT, + nullptr, + ATTR_TEST_SOURCE_ARRAY); + ippAddStrings(response, + IPP_TAG_PRINTER, + IPP_CONST_TAG(IPP_TAG_KEYWORD), + "multiple-document-handling-supported", + ATTR_TEST_DOCUMENT_HANDLING_COUNT, + nullptr, + ATTR_TEST_DOCUMENT_HANDLING_ARRAY); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string sourceString = printerCaps.GetPrinterAttrValue("media-source-supported"); + TestAttrCount(sourceString, ATTR_TEST_SOURCE_COUNT); + std::string documentHandlingString = printerCaps.GetPrinterAttrValue("multiple-document-handling-supported"); + TestAttrCount(documentHandlingString, ATTR_TEST_DOCUMENT_HANDLING_COUNT); + }; + DoTest(preFunc, postFunc); +} + +/** + * @tc.name: PrintCupsAttributeTest_0019 + * @tc.desc: printer option test + */ +HWTEST_F(PrintCupsAttributeTest, PrintCupsAttributeTest_0019, TestSize.Level1) +{ + PreAttrTestFunc preFunc = [this](ipp_t *response) { + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-make-and-model", nullptr, "Test make and model"); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_URI, "printer-uuid", nullptr, "Test printer uuid"); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-name", nullptr, "Test printer name"); + ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", nullptr, "Printer location test"); + ippAddStrings(response, + IPP_TAG_PRINTER, + IPP_CONST_TAG(IPP_TAG_KEYWORD), + "media-type-supported", + ATTR_TEST_MEDIA_TYPE_COUNT, + nullptr, + ATTR_TEST_MEDIA_TYPE_ARRAY); + }; + PostAttrTestFunc postFunc = [this](PrinterCapability &printerCaps) { + std::string mediaTypeString = printerCaps.GetPrinterAttrValue("media-type-supported"); + TestAttrCount(mediaTypeString, ATTR_TEST_MEDIA_TYPE_COUNT); + }; + DoTest(preFunc, postFunc); +} +} // namespace OHOS::Print \ No newline at end of file diff --git a/test/unittest/service_test/print_http_request_process_test.cpp b/test/unittest/service_test/print_http_request_process_test.cpp new file mode 100644 index 0000000..d3b1563 --- /dev/null +++ b/test/unittest/service_test/print_http_request_process_test.cpp @@ -0,0 +1,1049 @@ +/* + * 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 +#define private public +#include "print_http_request_process.h" +#undef private +#include "print_ipp_over_usb_constant.h" +#include "print_log.h" + +using namespace testing::ext; + +static const std::string HTTP_RESP_CONTINUE = "HTTP/1.1 100 CONTINUE\r\n\r\nContent-Length: 122\r\n"; +static const std::string HTTP_RESP_OK = "HTTP/1.1 200 OK\r\n"; +static const std::string HTTP_RESP_CONNECTION = "Connection:close\r\n"; +static const std::string HTTP_RESP_DATE = "Date:Tue 20 Feb 2024 02:57:06 GMT"; +static const std::string HTTP_RESP_CACHE_CONTROL = "Cache-Control: no-cache\r\n"; +static const std::string HTTP_RESP_SERVER = "Server: bsa/1.2\r\n"; +static const std::string HTTP_RESP_CONTENT_TYPE = "Content-Type: application/ipp\r\n"; +static const std::string HTTP_RESP_CONTENT_LENGTH = "Content-Length: 11616\r\n"; +static const std::string HTTP_RESP_IPP = "\x02\x00\x00\x00\x00\x00\x00\x01"; +static const std::string HTTP_RESP_DATA = + R"(\x01G\x00\x12attributes-charset\x00\x05utf-8H\x00\x1b\x61\x74\x74\x72\x69\x62)"\ + R"(\x75\x74\x65\x73\x2d\x6e\x61\x74\x75\x72\x61\x6c\x2d\x6c\x61\x6e\x67\x75\x61\x67)"\ + R"(\x65\x00\x05\x65\x6e\x2d\x75\x73)"; +static const std::string HTTP_REQ_DATA = + R"(\x02\x00\x00\x0b\x00\x00\x00\x01\x01G\x00\x12attributes-charset\x00\x05utf-8H\x00\x1)"\ + R"(battributes-natural-language\x00\x05en-usE\x00\x0bprinter-uri\x00!ipp://192.168.186.1:631/ipp/printD\x00\x14)"\ + R"(requested-attributes\x00\x15compression-supportedD\x00\x00\x00\x10copies-supportedD\x00\x00\x00\x0ccups-versi)"\ + R"(onD\x00\x00\x00\x19document-format-supportedD\x00\x00\x00!job-password-encryption-supportedD\x00\x00\x00\x0d)"\ + R"(marker-colorsD\x00\x00\x00\x12marker-high-levelsD\x00\x00\x00\x0dmarker-levelsD\x00\x00\x00\x11marker-low-le)"\ + R"(velsD\x00\x00\x00\x0emarker-messageD\x00\x00\x00\x0cmarker-namesD\x00\x00\x00\x0cmarker-typesD\x00\x00\x00)"\ + R"(\x13media-col-supportedD\x00\x00\x00$multiple-document-handling-supportedD\x00\x00\x00\x14operations-support)"\ + R"(edD\x00\x00\x00\x1aprint-color-mode-supportedD\x00\x00\x00\x0dprinter-alertD\x00\x00\x00\x19printer-alert-d)"\ + R"(escriptionD\x00\x00\x00\x19printer-is-accepting-jobsD\x00\x00\x00 printer-mandatory-job-attributesD\x00\x00)"\ + R"(\x00\x0dprinter-stateD\x00\x00\x00\x15printer-state-messageD\x00\x00\x00\x15printer-state-reasons\x03")"; + +namespace OHOS { +namespace Print { +class PrintHttpRequestProcessTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintHttpRequestProcessTest::SetUpTestCase(void) +{} + +void PrintHttpRequestProcessTest::TearDownTestCase(void) +{} + +void PrintHttpRequestProcessTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintHttpRequestProcessTest_%{public}d", ++testNo); +} + +void PrintHttpRequestProcessTest::TearDown(void) +{} + +/** + * @tc.name: PrintHttpRequestProcessTest_001 + * @tc.desc: Verify the PrintOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_001, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string str = printHttpRequestProcess.PrintOperation(Operation::Common); + EXPECT_EQ(str, HTTP_OPERATION_COMMON); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_002 + * @tc.desc: Verify the PrintOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_002, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string str = printHttpRequestProcess.PrintOperation(Operation::Get_Printer_Attributes); + EXPECT_EQ(str, HTTP_OPERATION_GET_ATTR); +} +/** + * @tc.name: PrintHttpRequestProcessTest_003 + * @tc.desc: Verify the PrintOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_003, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string str = printHttpRequestProcess.PrintOperation(Operation::Send_Document); + EXPECT_EQ(str, HTTP_OPERATION_SEND_DOC); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_004 + * @tc.desc: Verify the NeedOffset function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_004, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::vector readTempBuffer; + readTempBuffer.assign(HTTP_RESP_CONTINUE.begin(), HTTP_RESP_CONTINUE.end()); + size_t reqindex = printHttpRequestProcess.NeedOffset(readTempBuffer); + size_t expect = HTTP_COMMON_CONST_VALUE_25; + EXPECT_EQ(reqindex, expect); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_005 + * @tc.desc: Verify the NeedOffset function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_005, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::vector readTempBuffer; + size_t reqindex = printHttpRequestProcess.NeedOffset(readTempBuffer); + size_t expect = 0; + EXPECT_EQ(reqindex, expect); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_006 + * @tc.desc: Verify the RecordBufByOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_006, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector tmVector; + tmVector.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.reqIdOperaIdMap[requestId] = HTTP_REQUEST_GET_ATTR; + printHttpRequestProcess.RecordBufByOperation(Operation::Get_Printer_Attributes, requestId, tmVector); + size_t expect = 1; + EXPECT_EQ(expect, printHttpRequestProcess.readGetAttrBufMap.size()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_007 + * @tc.desc: Verify the RecordBufByOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_007, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector tmVector; + tmVector.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.reqIdOperaIdMap[requestId] = HTTP_REQUEST_GET_ATTR; + printHttpRequestProcess.readGetAttrBufMap[requestId] = tmVector; + printHttpRequestProcess.RecordBufByOperation(Operation::Get_Printer_Attributes, requestId, tmVector); + size_t expect = 1; + EXPECT_EQ(expect, printHttpRequestProcess.readGetAttrBufMap.size()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_008 + * @tc.desc: Verify the RecordBufByOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_008, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector tmVector; + tmVector.assign(tempStr.begin(), tempStr.end()); + size_t expect = 1; + printHttpRequestProcess.RecordBufByOperation(Operation::Send_Document, requestId, tmVector); + EXPECT_EQ(expect, printHttpRequestProcess.readSendDocBufMap.size()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_009 + * @tc.desc: Verify the RecordBufByOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_009, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector tmVector; + tmVector.assign(tempStr.begin(), tempStr.end()); + size_t expect = 1; + printHttpRequestProcess.readSendDocBufMap[requestId] = tmVector; + printHttpRequestProcess.RecordBufByOperation(Operation::Send_Document, requestId, tmVector); + EXPECT_EQ(expect, printHttpRequestProcess.readSendDocBufMap.size()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_010 + * @tc.desc: Verify the RecordBufByOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_010, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector tmVector; + tmVector.assign(tempStr.begin(), tempStr.end()); + size_t expect = 1; + printHttpRequestProcess.RecordBufByOperation(Operation::Common, requestId, tmVector); + EXPECT_EQ(expect, printHttpRequestProcess.readBufMap.size()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_011 + * @tc.desc: Verify the RecordBufByOperation function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_011, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector tmVector; + tmVector.assign(tempStr.begin(), tempStr.end()); + size_t expect = 1; + printHttpRequestProcess.readBufMap[requestId] = tmVector; + printHttpRequestProcess.RecordBufByOperation(Operation::Common, requestId, tmVector); + EXPECT_EQ(expect, printHttpRequestProcess.readBufMap.size()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_012 + * @tc.desc: Verify the GetContentLength function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_012, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + size_t index = 0; + bool findContentLength = false; + size_t contentLength = 0; + std::vector readTempBuffer; + printHttpRequestProcess.GetContentLength(readTempBuffer, index, findContentLength, contentLength); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_013 + * @tc.desc: Verify the GetContentLength function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_013, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + size_t index = 0; + bool findContentLength = false; + size_t contentLength = 0; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.GetContentLength(readTempBuffer, index, findContentLength, contentLength); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_014 + * @tc.desc: Verify the GetContentLength function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_014, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + size_t index = 0; + bool findContentLength = false; + size_t contentLength = 0; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.GetContentLength(readTempBuffer, index, findContentLength, contentLength); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_015 + * @tc.desc: Verify the DumpRespIdCode function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_015, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::vector readTempBuffer; + readTempBuffer.assign(HTTP_RESP_IPP.begin(), HTTP_RESP_IPP.end()); + size_t begin = 0; + size_t maxSize = 30; + printHttpRequestProcess.DumpRespIdCode(readTempBuffer, Operation::Get_Printer_Attributes, begin, maxSize); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_016 + * @tc.desc: Verify the CheckLineEnd function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_016, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = "\r\n\r\n"; + tempStr += HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + bool ret = printHttpRequestProcess.CheckLineEnd(readTempBuffer, index); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_017 + * @tc.desc: Verify the CheckLineEnd function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_017, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = "\r\n\r"; + tempStr += HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + bool ret = printHttpRequestProcess.CheckLineEnd(readTempBuffer, index); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_018 + * @tc.desc: Verify the CheckLineEnd function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_018, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = "\r\n"; + tempStr += HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + bool ret = printHttpRequestProcess.CheckLineEnd(readTempBuffer, index); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_019 + * @tc.desc: Verify the CheckLineEnd function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_019, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = "\r"; + tempStr += HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + bool ret = printHttpRequestProcess.CheckLineEnd(readTempBuffer, index); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_020 + * @tc.desc: Verify the CheckLineEnd function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_020, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + bool ret = printHttpRequestProcess.CheckLineEnd(readTempBuffer, index); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_021 + * @tc.desc: Verify the CheckLineEnd function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_021, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = "HTTP/1.1"; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + bool ret = printHttpRequestProcess.CheckLineEnd(readTempBuffer, index); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_022 + * @tc.desc: Verify the CalculateRequestId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_022, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string tempStr = HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + size_t index = 0; + printHttpRequestProcess.CalculateRequestId(readTempBuffer, index, Operation::Get_Printer_Attributes); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_023 + * @tc.desc: Verify the CalculateFileDataBeginIndex function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_023, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t index = 0; + printHttpRequestProcess.CalculateFileDataBeginIndex(index, Operation::Get_Printer_Attributes); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_025 + * @tc.desc: Verify the ProcessDataFromDevice function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_025, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + printHttpRequestProcess.ProcessDataFromDevice(Operation::Get_Printer_Attributes); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_026 + * @tc.desc: Verify the GetAttrAgain function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_026, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::vector readTempBuffer; + printHttpRequestProcess.GetAttrAgain(Operation::Get_Printer_Attributes, readTempBuffer); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_028 + * @tc.desc: Verify the ProcessHttpResponse function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_028, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 1; + printHttpRequestProcess.ProcessHttpResponse(responseData, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_029 + * @tc.desc: Verify the ProcessHttpResponse function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_029, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.readBufMap[requestId] = readTempBuffer; + printHttpRequestProcess.ProcessHttpResponse(responseData, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_030 + * @tc.desc: Verify the ProcessHttpResponseGetAttr function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_030, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 1; + printHttpRequestProcess.ProcessHttpResponseGetAttr(responseData, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_031 + * @tc.desc: Verify the ProcessHttpResponseGetAttr function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_031, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.readGetAttrBufMap[requestId] = readTempBuffer; + printHttpRequestProcess.ProcessHttpResponseGetAttr(responseData, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_032 + * @tc.desc: Verify the ProcessHttpResponseSendDoc function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_032, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 1; + printHttpRequestProcess.ProcessHttpResponseSendDoc(responseData, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_033 + * @tc.desc: Verify the ProcessHttpResponseSendDoc function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_033, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 1; + std::string tempStr = HTTP_RESP_OK; + tempStr += HTTP_RESP_CONNECTION; + tempStr += HTTP_RESP_DATE; + tempStr += HTTP_RESP_CACHE_CONTROL; + tempStr += HTTP_RESP_SERVER; + tempStr += HTTP_RESP_CONTENT_TYPE; + tempStr += HTTP_RESP_CONTENT_LENGTH; + tempStr += HTTP_MSG_STRING_R_AND_N; + tempStr += HTTP_RESP_IPP; + tempStr += HTTP_RESP_DATA; + std::vector readTempBuffer; + readTempBuffer.assign(tempStr.begin(), tempStr.end()); + printHttpRequestProcess.readSendDocBufMap[requestId] = readTempBuffer; + printHttpRequestProcess.ProcessHttpResponseSendDoc(responseData, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_034 + * @tc.desc: Verify the DealRequestHeader function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_034, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Request requestData; + requestData.set_header("Content-Length", "745"); + requestData.set_header("Content-Type", "application/ipp"); + requestData.set_header("Expect", "100-continue"); + requestData.set_header("Host", "localhost:60000"); + requestData.set_header("LOCAL_ADDR", "127.0.0.1"); + requestData.set_header("LOCAL_PORT", "60000"); + requestData.set_header("REMOTE_ADDR", "127.0.0.1"); + requestData.set_header("REMOTE_PORT", "39470"); + requestData.set_header("User-Agent", "CUPS/2.4.0 (Linux 5.10.97+; aarch64) IPP/2.0"); + std::string str = ""; + printHttpRequestProcess.DealRequestHeader(requestData, str); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_035 + * @tc.desc: Verify the DealRequestHeader function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_035, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Request requestData; + requestData.set_header("Content-Length", "745"); + requestData.set_header("Content-Type", "application/ipp"); + requestData.set_header("Transfer-Encoding", "chunked"); + requestData.set_header("Host", "localhost:60000"); + requestData.set_header("LOCAL_ADDR", "127.0.0.1"); + requestData.set_header("LOCAL_PORT", "60000"); + requestData.set_header("REMOTE_ADDR", "127.0.0.1"); + requestData.set_header("REMOTE_PORT", "39470"); + requestData.set_header("User-Agent", "CUPS/2.4.0 (Linux 5.10.97+; aarch64) IPP/2.0"); + std::string str = ""; + printHttpRequestProcess.DealRequestHeader(requestData, str); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_036 + * @tc.desc: Verify the CalcReqIdOperaId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_036, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 0; + std::string reqData = HTTP_REQ_DATA; + size_t data_length = 716; + printHttpRequestProcess.CalcReqIdOperaId(reqData.c_str(), data_length, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_037 + * @tc.desc: Verify the CalcReqIdOperaId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_037, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + httplib::Response responseData; + size_t requestId = 0; + std::string reqData = HTTP_REQ_DATA; + size_t data_length = 1; + printHttpRequestProcess.CalcReqIdOperaId(reqData.c_str(), data_length, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_038 + * @tc.desc: Verify the CreatWriteDataTask function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_038, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + printHttpRequestProcess.needWriteData = true; + printHttpRequestProcess.CreatWriteDataTask(); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_040 + * @tc.desc: Verify the ProcessOtherRequest function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_040, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + const char *data = "test"; + size_t data_length = 4; + std::string sHeadersAndBody = ""; + size_t requestId = 0; + printHttpRequestProcess.needWriteData = true; + printHttpRequestProcess.ProcessOtherRequest(data, data_length, sHeadersAndBody, requestId); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_041 + * @tc.desc: Verify the DumpReqIdOperaId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_041, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string reqData = "t"; + size_t data_length = 1; + printHttpRequestProcess.DumpReqIdOperaId(reqData.c_str(), data_length); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_042 + * @tc.desc: Verify the DumpReqIdOperaId function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_042, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string reqData = "test request data"; + size_t data_length = 15; + printHttpRequestProcess.DumpReqIdOperaId(reqData.c_str(), data_length); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_044 + * @tc.desc: Verify the CreatReadSendDocTask function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_044, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + printHttpRequestProcess.needReadSendDoc = true; + printHttpRequestProcess.CreatReadSendDocTask(); + EXPECT_EQ(true, printHttpRequestProcess.needReadSendDoc); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_045 + * @tc.desc: Verify the CreateChunk function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_045, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string reqData = HTTP_REQ_DATA; + size_t data_length = 721; + printHttpRequestProcess.CreateChunk(reqData.c_str(), data_length); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_046 + * @tc.desc: Verify the WriteDataSync function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_046, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string sHeadersAndBody = "test"; + auto ret = printHttpRequestProcess.WriteDataSync(sHeadersAndBody); + EXPECT_EQ(INVAILD_VALUE, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_047 + * @tc.desc: Verify the WriteDataSync function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_047, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string sHeadersAndBody = ""; + auto ret = printHttpRequestProcess.WriteDataSync(sHeadersAndBody); + EXPECT_EQ(0, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_048 + * @tc.desc: Verify the BulkTransferWriteData function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_048, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string name = "usb"; + printHttpRequestProcess.SetDeviceName(name); + std::string reqData = HTTP_REQ_DATA; + size_t data_length = 716; + httplib::Request requestData; + requestData.set_header("Content-Length", "745"); + requestData.set_header("Content-Type", "application/ipp"); + requestData.set_header("Expect", "100-continue"); + requestData.set_header("Host", "localhost:60000"); + requestData.set_header("LOCAL_ADDR", "127.0.0.1"); + requestData.set_header("LOCAL_PORT", "60000"); + requestData.set_header("REMOTE_ADDR", "127.0.0.1"); + requestData.set_header("REMOTE_PORT", "39470"); + requestData.set_header("User-Agent", "CUPS/2.4.0 (Linux 5.10.97+; aarch64) IPP/2.0"); + std::string sHeadersAndBody = ""; + printHttpRequestProcess.DealRequestHeader(requestData, sHeadersAndBody); + sHeadersAndBody += printHttpRequestProcess.CreateChunk(reqData.c_str(), data_length); + auto ret = printHttpRequestProcess.BulkTransferWriteData(sHeadersAndBody); + EXPECT_EQ(INVAILD_VALUE, ret); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_049 + * @tc.desc: Verify the ProcessHttpResp function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_049, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + httplib::Response responseData; + printHttpRequestProcess.reqIdOperaIdMap[requestId] = HTTP_REQUEST_GET_ATTR; + std::string sHeadersAndBody = ""; + printHttpRequestProcess.ProcessHttpResp(requestId, responseData, sHeadersAndBody); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_050 + * @tc.desc: Verify the ProcessHttpResp function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_050, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + httplib::Response responseData; + printHttpRequestProcess.reqIdOperaIdMap[requestId] = HTTP_REQUEST_SEND_DOC; + printHttpRequestProcess.deviceOpen = false; + std::string sHeadersAndBody = ""; + printHttpRequestProcess.ProcessHttpResp(requestId, responseData, sHeadersAndBody); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_051 + * @tc.desc: Verify the ProcessHttpResp function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_051, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + httplib::Response responseData; + printHttpRequestProcess.reqIdOperaIdMap[requestId] = HTTP_REQUEST_SEND_DOC; + printHttpRequestProcess.deviceOpen = true; + std::string sHeadersAndBody = ""; + printHttpRequestProcess.ProcessHttpResp(requestId, responseData, sHeadersAndBody); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_052 + * @tc.desc: Verify the ProcessHttpResp function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_052, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + size_t requestId = 1; + httplib::Response responseData; + int testOperationId = 10; + printHttpRequestProcess.reqIdOperaIdMap[requestId] = testOperationId; + std::string sHeadersAndBody = ""; + printHttpRequestProcess.ProcessHttpResp(requestId, responseData, sHeadersAndBody); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_053 + * @tc.desc: Verify the SetDeviceName function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_053, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + std::string name = "usb"; + printHttpRequestProcess.SetDeviceName(name); + EXPECT_EQ("usb", printHttpRequestProcess.GetDeviceName()); +} + +/** + * @tc.name: PrintHttpRequestProcessTest_054 + * @tc.desc: Verify the Stop function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpRequestProcessTest, PrintHttpRequestProcessTest_054, TestSize.Level1) +{ + OHOS::Print::PrintHttpRequestProcess printHttpRequestProcess; + printHttpRequestProcess.Stop(); + EXPECT_EQ(false, printHttpRequestProcess.needWriteData); + EXPECT_EQ(false, printHttpRequestProcess.needReadSendDoc); + EXPECT_EQ(false, printHttpRequestProcess.needWriteSendDoc); +} + +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/service_test/print_http_server_manager_test.cpp b/test/unittest/service_test/print_http_server_manager_test.cpp new file mode 100644 index 0000000..ead5fd1 --- /dev/null +++ b/test/unittest/service_test/print_http_server_manager_test.cpp @@ -0,0 +1,158 @@ +/* + * 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 +#define private public +#include "print_http_server_manager.h" +#undef private +#include "print_log.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Print { +using namespace httplib; + +static const std::string IPP_PRINTER = + R"({"busNum":2,"clazz":0,"configs":[{"attributes":192,"id":1,"interfaces":[{"alternateSetting":0,"clazz":7,)"\ + R"("endpoints":[{"address":1,"attributes":2,"direction":0,"interfaceId":0,"interval":0,"maxPacketSize":512,)"\ + R"("number":1,"type":2},{"address":129,"attributes":2,"direction":128,"interfaceId":0,"interval":0,)"\ + R"("maxPacketSize":512,"number":1,"type":2}],"id":0,"name":"","protocol":2,"subClass":1},{"alternateSetting":0,)"\ + R"("clazz":255,"endpoints":[{"address":2,"attributes":2,"direction":0,"interfaceId":1,"interval":0,)"\ + R"("maxPacketSize":512,"number":2,"type":2},{"address":130,"attributes":2,"direction":128,"interfaceId":1,)"\ + R"("interval":0,"maxPacketSize":512,"number":2,"type":2}],"id":1,"name":"","protocol":255,"subClass":255},)"\ + R"({"alternateSetting":0,"clazz":7,"endpoints":[{"address":3,"attributes":2,"direction":0,"interfaceId":2,)"\ + R"("interval":0,"maxPacketSize":512,"number":3,"type":2},{"address":131,"attributes":2,"direction":128,)"\ + R"("interfaceId":2,"interval":0,"maxPacketSize":512,"number":3,"type":2}],"id":2,"name":"","protocol":4,)"\ + R"("subClass":1},{"alternateSetting":0,"clazz":7,"endpoints":[{"address":4,"attributes":2,"direction":0,)"\ + R"("interfaceId":3,"interval":0,"maxPacketSize":512,"number":4,"type":2},{"address":132,"attributes":2,)"\ + R"("direction":128,"interfaceId":3,"interval":0,"maxPacketSize":512,"number":4,"type":2}],"id":3,"name":"",)"\ + R"("protocol":4,"subClass":1},{"alternateSetting":0,"clazz":7,"endpoints":[{"address":5,"attributes":2,)"\ + R"("direction":0,"interfaceId":4,"interval":0,"maxPacketSize":512,"number":5,"type":2},{"address":133,)"\ + R"("attributes":2,"direction":128,"interfaceId":4,"interval":0,"maxPacketSize":512,"number":5,"type":2}],)"\ + R"("id":4,"name":"","protocol":4,"subClass":1},{"alternateSetting":0,"clazz":7,"endpoints":[{"address":6,)"\ + R"("attributes":2,"direction":0,"interfaceId":5,"interval":0,"maxPacketSize":512,"number":6,"type":2},)"\ + R"({"address":134,"attributes":2,"direction":128,"interfaceId":5,"interval":0,"maxPacketSize":512,)"\ + R"("number":6,"type":2}],"id":5,"name":" ","protocol":4,"subClass":1}],"isRemoteWakeup":false,)"\ + R"("isSelfPowered":true,"maxPower":1,"name":" "}],"devAddress":5,"manufacturerName":" ","name":"2-5",)"\ + R"("productId":4293,"productName":" ","protocol":0,"serial":"","subClass":0,"vendorId":4817,"version":"0404"})"; + +class PrintHttpServerManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintHttpServerManagerTest::SetUpTestCase(void) +{} + +void PrintHttpServerManagerTest::TearDownTestCase(void) +{} + +void PrintHttpServerManagerTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintHttpServerManagerTest_%{public}d", ++testNo); +} + +void PrintHttpServerManagerTest::TearDown(void) +{} + +/** + * @tc.name: PrintHttpServerManagerTest_001 + * @tc.desc: Verify the CreateServer function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpServerManagerTest, PrintHttpServerManagerTest_001, TestSize.Level1) +{ + auto service = std::make_shared(); + std::string printerName = "HW PixLab V1-0105"; + int32_t port; + EXPECT_TRUE(service->CreateServer(printerName, port)); +} + +/** + * @tc.name: PrintHttpServerManagerTest_002 + * @tc.desc: Verify the CreateServer function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpServerManagerTest, PrintHttpServerManagerTest_002, TestSize.Level1) +{ + auto service = std::make_shared(); + std::string printerName = "HW PixLab V1-0105"; + int32_t port; + std::shared_ptr newServer = std::make_shared(); + EXPECT_NE(newServer, nullptr); + service->printHttpServerMap[printerName] = newServer; + service->CreateServer(printerName, port); +} + +/** + * @tc.name: PrintHttpServerManagerTest_003 + * @tc.desc: Verify the CreateServer function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpServerManagerTest, PrintHttpServerManagerTest_003, TestSize.Level1) +{ + auto service = std::make_shared(); + std::string printerName = "HW PixLab V1-0105"; + int32_t port; + std::shared_ptr newServer = std::make_shared(); + EXPECT_NE(newServer, nullptr); + service->printHttpServerMap[printerName] = newServer; + service->printHttpPortMap[printerName] = 60000; + service->CreateServer(printerName, port); +} + + +/** + * @tc.name: PrintHttpServerManagerTest_004 + * @tc.desc: Verify the StopServer function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpServerManagerTest, PrintHttpServerManagerTest_004, TestSize.Level1) +{ + OHOS::Print::PrintHttpServerManager printHttpServerManager; + std::string printerName = "HW PixLab V1-0105"; + std::shared_ptr newServer = std::make_shared(); + EXPECT_NE(newServer, nullptr); + std::shared_ptr newProcess = std::make_shared(); + EXPECT_NE(newProcess, nullptr); + printHttpServerManager.printHttpServerMap[printerName] = newServer; + printHttpServerManager.printHttpPortMap[printerName] = 60000; + printHttpServerManager.printHttpProcessMap[printerName] = newProcess; + printHttpServerManager.StopServer(printerName); +} + +/** + * @tc.name: PrintHttpServerManagerTest_005 + * @tc.desc: Verify the DealUsbDevDetach function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintHttpServerManagerTest, PrintHttpServerManagerTest_005, TestSize.Level1) +{ + OHOS::Print::PrintHttpServerManager printHttpServerManager; + printHttpServerManager.DealUsbDevDetach(IPP_PRINTER); +} + +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/service_test/print_ipp_over_usb_manager_test.cpp b/test/unittest/service_test/print_ipp_over_usb_manager_test.cpp new file mode 100644 index 0000000..db479b8 --- /dev/null +++ b/test/unittest/service_test/print_ipp_over_usb_manager_test.cpp @@ -0,0 +1,130 @@ +/* + * 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 +#define private public +#include "print_ipp_over_usb_manager.h" +#undef private + +using namespace testing::ext; + +namespace OHOS { +namespace Print { +class PrintIppOverUsbManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintIppOverUsbManagerTest::SetUpTestCase(void) +{} + +void PrintIppOverUsbManagerTest::TearDownTestCase(void) +{} + +void PrintIppOverUsbManagerTest::SetUp(void) +{} + +void PrintIppOverUsbManagerTest::TearDown(void) +{} + +/** + * @tc.name: PrintIppOverUsbManagerTest_001 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintIppOverUsbManagerTest, PrintIppOverUsbManagerTest_001, TestSize.Level1) +{ + OHOS::Print::PrintIppOverUsbManager printIppOverUsbManager; + printIppOverUsbManager.isInit = true; + printIppOverUsbManager.Init(); + printIppOverUsbManager.isInit = false; + printIppOverUsbManager.Init(); +} + +/** + * @tc.name: PrintIppOverUsbManagerTest_002 + * @tc.desc: Verify the ConnectPrinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintIppOverUsbManagerTest, PrintIppOverUsbManagerTest_002, TestSize.Level1) +{ + OHOS::Print::PrintIppOverUsbManager printIppOverUsbManager; + std::string printerId = "com.ohos.spooler:USB-HW PixLab V1-0159"; + int32_t port = 60000; + printIppOverUsbManager.ConnectPrinter(printerId, port); +} + +/** + * @tc.name: PrintIppOverUsbManagerTest_003 + * @tc.desc: Verify the ConnectPrinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintIppOverUsbManagerTest, PrintIppOverUsbManagerTest_003, TestSize.Level1) +{ + OHOS::Print::PrintIppOverUsbManager printIppOverUsbManager; + std::string printerId = "com.ohos.spoolerUSB-HW PixLab V1-0159"; + int32_t port = 60000; + printIppOverUsbManager.ConnectPrinter(printerId, port); +} + +/** + * @tc.name: PrintIppOverUsbManagerTest_004 + * @tc.desc: Verify the ConnectPrinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintIppOverUsbManagerTest, PrintIppOverUsbManagerTest_004, TestSize.Level1) +{ + OHOS::Print::PrintIppOverUsbManager printIppOverUsbManager; + std::string printerId = "com.ohos.test:USB-HW PixLab V1-0159"; + int32_t port = 60000; + printIppOverUsbManager.ConnectPrinter(printerId, port); +} + +/** + * @tc.name: PrintIppOverUsbManagerTest_005 + * @tc.desc: Verify the ConnectPrinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintIppOverUsbManagerTest, PrintIppOverUsbManagerTest_005, TestSize.Level1) +{ + OHOS::Print::PrintIppOverUsbManager printIppOverUsbManager; + std::string printerId = "com.ohos.spooler:HW PixLab V1-0159"; + int32_t port = 60000; + printIppOverUsbManager.ConnectPrinter(printerId, port); +} + +/** + * @tc.name: PrintIppOverUsbManagerTest_006 + * @tc.desc: Verify the DisConnectPrinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintIppOverUsbManagerTest, PrintIppOverUsbManagerTest_006, TestSize.Level1) +{ + OHOS::Print::PrintIppOverUsbManager printIppOverUsbManager; + std::string printerId = "com.ohos.spooler:USB-HW PixLab V1-0159"; + printIppOverUsbManager.DisConnectPrinter(printerId); +} + +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/service_test/print_security_guard_manager_test.cpp b/test/unittest/service_test/print_security_guard_manager_test.cpp index 37e5f60..02e3ea9 100644 --- a/test/unittest/service_test/print_security_guard_manager_test.cpp +++ b/test/unittest/service_test/print_security_guard_manager_test.cpp @@ -53,5 +53,21 @@ HWTEST_F(PrintSecurityGuardManagerTest, PrintSecurityGuardManagerTest_0001, Test printSerPrintSecurityGuardManager.receiveBaseInfo("jobId-1", "callerPkg-1", fileList); printSerPrintSecurityGuardManager.receiveJobStateUpdate("jobId-2", printerInfo, printJob); } + +/** +* @tc.name: PrintSecurityGuardManagerTest_0002 +* @tc.desc: receiveBaseInfo +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintSecurityGuardManagerTest, PrintSecurityGuardManagerTest_0002, TestSize.Level1) +{ + PrintSecurityGuardManager printSerPrintSecurityGuardManager; + std::vector fileList; + PrinterInfo printerInfo; + PrintJob printJob; + printSerPrintSecurityGuardManager.receiveBaseInfo("jobId-1", "callerPkg-1", fileList); + printSerPrintSecurityGuardManager.receiveJobStateUpdate("jobId-1", printerInfo, printJob); +} } // namespace Print } // namespace OHOS diff --git a/test/unittest/service_test/print_service_converter_test.cpp b/test/unittest/service_test/print_service_converter_test.cpp new file mode 100644 index 0000000..1e3ff01 --- /dev/null +++ b/test/unittest/service_test/print_service_converter_test.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "print_service_converter.h" +#include "print_page_size.h" +#include "print_log.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Print { + +class PrintServiceConverterTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintServiceConverterTest::SetUpTestCase(void) {} + +void PrintServiceConverterTest::TearDownTestCase(void) {} + +void PrintServiceConverterTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintServiceConverterTest_%{public}d", ++testNo); +} + +void PrintServiceConverterTest::TearDown(void) {} + +/** +* @tc.name: PrintServiceConverterTest_0001 +* @tc.desc: reportPrintSuccess +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0001, TestSize.Level1) +{ + int dpc = 120; + EXPECT_EQ(DpcToDpi(dpc), 300); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0002, TestSize.Level1) +{ + std::vector list; + list.push_back("1111"); + list.push_back("2222"); + std::string value = "1111"; + AddToUniqueList(list, value); + EXPECT_EQ(list.size(), 2); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0003, TestSize.Level1) +{ + std::vector list; + list.push_back("1111"); + list.push_back("2222"); + std::string value = "3333"; + AddToUniqueList(list, value); + EXPECT_EQ(list.size(), 3); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0004, TestSize.Level1) +{ + int code = 3; + EXPECT_EQ(GetQulityString(code), "3"); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0005, TestSize.Level1) +{ + const char* src = nullptr; + ColorModeCode dst; + EXPECT_EQ(ConvertColorModeCode(src, dst), false); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_006, TestSize.Level1) +{ + PrintPageSize pageSize; + nlohmann::json jsonObject; + EXPECT_EQ(ConvertPageSizeToJson(pageSize, jsonObject), true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0007, TestSize.Level1) +{ + const char* src = "color"; + ColorModeCode dst; + bool re = ConvertColorModeCode(src, dst); + EXPECT_EQ(dst, 1); + EXPECT_EQ(re, true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0008, TestSize.Level1) +{ + const char* src = "monochrome"; + ColorModeCode dst; + bool re = ConvertColorModeCode(src, dst); + EXPECT_EQ(dst, 0); + EXPECT_EQ(re, true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0009, TestSize.Level1) +{ + const char* src = "auto"; + ColorModeCode dst; + bool re = ConvertColorModeCode(src, dst); + EXPECT_EQ(dst, 2); + EXPECT_EQ(re, true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0010, TestSize.Level1) +{ + const char* src = "sss"; + ColorModeCode dst; + EXPECT_EQ(ConvertColorModeCode(src, dst), false); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0011, TestSize.Level1) +{ + ColorModeCode code = ColorModeCode::COLOR_MODE_COLOR; + nlohmann::json jsonObject; + EXPECT_EQ(ConvertColorModeToJson(code, jsonObject), true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0012, TestSize.Level1) +{ + DuplexModeCode code = DuplexModeCode::DUPLEX_MODE_ONE_SIDED; + nlohmann::json jsonObject; + EXPECT_EQ(ConvertDuplexModeToJson(code, jsonObject), true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0013, TestSize.Level1) +{ + const char* src = nullptr; + std::string id = ""; + EXPECT_EQ(ConvertPageSizeId(src, id), false); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0014, TestSize.Level1) +{ + const char* src = "iso_a4_210x297mm"; + std::string id = ""; + EXPECT_EQ(ConvertPageSizeId(src, id), true); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0015, TestSize.Level1) +{ + const char* src = nullptr; + PrintPageSize dst; + EXPECT_EQ(ConvertPrintPageSize(src, dst), false); +} + +HWTEST_F(PrintServiceConverterTest, PrintServiceConverterTest_0016, TestSize.Level1) +{ + const char* src = "iso_a4_210x297mm"; + PrintPageSize dst; + EXPECT_EQ(ConvertPrintPageSize(src, dst), true); +} + +} +} diff --git a/test/unittest/service_test/print_service_helper_test.cpp b/test/unittest/service_test/print_service_helper_test.cpp index 722a4cd..e237e93 100644 --- a/test/unittest/service_test/print_service_helper_test.cpp +++ b/test/unittest/service_test/print_service_helper_test.cpp @@ -16,11 +16,18 @@ #include #include "print_service_helper.h" #include "print_constant.h" +#include "ipc_skeleton.h" using namespace testing::ext; namespace OHOS { namespace Print { + +static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler"; +static const std::string SPOOLER_PACKAGE_NAME = "com.ohos.spooler"; +static const std::string SPOOLER_STATUS_BAR_ABILITY_NAME = "PluginPrintIconExtAbility"; +static const std::string CALLER_PKG_NAME = "caller.pkgName"; + class PrintServiceHelperTest : public testing::Test { public: static void SetUpTestCase(void); @@ -33,7 +40,11 @@ void PrintServiceHelperTest::SetUpTestCase(void) {} void PrintServiceHelperTest::TearDownTestCase(void) {} -void PrintServiceHelperTest::SetUp(void) {} +void PrintServiceHelperTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintServiceHelperTest_%{public}d", ++testNo); +} void PrintServiceHelperTest::TearDown(void) {} @@ -140,5 +151,30 @@ HWTEST_F(PrintServiceHelperTest, PrintServiceHelperTest_0008, TestSize.Level1) PrintServiceHelper helper; helper.IsSyncMode(); } + +/** +* @tc.name: PrintServiceHelperTest_0013 +* @tc.desc: faultPrint +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintServiceHelperTest, PrintServiceHelperTest_009, TestSize.Level1) { + PrintServiceHelper helper; + AAFwk::Want want; + EXPECT_FALSE(helper.StartAbility(want)); +} + +/** +* @tc.name: PrintServiceHelperTest_0014 +* @tc.desc: faultPrint +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(PrintServiceHelperTest, PrintServiceHelperTest_0010, TestSize.Level1) +{ + PrintServiceHelper helper; + helper.PrintSubscribeCommonEvent(); +} + } // namespace Print } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/service_test/print_service_stub_test.cpp b/test/unittest/service_test/print_service_stub_test.cpp index 290d2ba..8aaa22a 100644 --- a/test/unittest/service_test/print_service_stub_test.cpp +++ b/test/unittest/service_test/print_service_stub_test.cpp @@ -94,6 +94,7 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0003, TestSize.Level1) EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); EXPECT_TRUE(data.WriteBool(false)); EXPECT_TRUE(data.WriteBool(false)); + EXPECT_TRUE(data.WriteString("jobId")); auto stub = std::make_shared(); EXPECT_NE(stub, nullptr); @@ -119,7 +120,8 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0004, TestSize.Level1) EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); EXPECT_TRUE(data.WriteBool(testFileList.size() > 0)); EXPECT_TRUE(data.WriteStringVector(testFileList)); - + EXPECT_TRUE(data.WriteBool(false)); + EXPECT_TRUE(data.WriteString("jobId")); auto stub = std::make_shared(); EXPECT_NE(stub, nullptr); @@ -150,6 +152,7 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0005, TestSize.Level1) EXPECT_TRUE(data.WriteStringVector(testFileList)); EXPECT_TRUE(data.WriteBool(testFdList.size() > 0)); EXPECT_TRUE(data.WriteInt32(testFdList.size())); + EXPECT_TRUE(data.WriteString("jobId")); auto stub = std::make_shared(); EXPECT_NE(stub, nullptr); @@ -183,6 +186,7 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0006, TestSize.Level1) for (auto fd : testFdList) { data.WriteFileDescriptor(fd); } + EXPECT_TRUE(data.WriteString("jobId")); auto stub = std::make_shared(); EXPECT_NE(stub, nullptr); @@ -658,7 +662,7 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0026, TestSize.Level1) auto stub = std::make_shared(); EXPECT_NE(stub, nullptr); - ON_CALL(*stub, UpdatePrintJobState).WillByDefault(Return(E_PRINT_NONE)); + ON_CALL(*stub, UpdatePrintJobStateOnlyForSystemApp).WillByDefault(Return(E_PRINT_NONE)); EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); } @@ -1005,5 +1009,273 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0040, TestSize.Level1) ON_CALL(*stub, LoadExtSuccess).WillByDefault(Return(E_PRINT_NONE)); EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); } + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0041, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_UNREG_EXT_CB); + + std::string extensionId = "com.exmpale.ext"; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(extensionId)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, UnregisterAllExtCallback).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0042, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_ADDPRINTERTOCUPS); + + std::string printerUri = "ipp://192.168.186.1:631/ipp/print"; + std::string printerName = "DIRECT-HW_PixLab_V1-1620"; + std::string printerMake = "PixLab V1 - IPP Everywhere"; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(printerUri)); + EXPECT_TRUE(data.WriteString(printerName)); + EXPECT_TRUE(data.WriteString(printerMake)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, AddPrinterToCups).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0043, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_QUERYPRINTERCAPABILITYBYURI); + + std::string printerUri = "ipp://192.168.186.1:631/ipp/print"; + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(printerUri)); + EXPECT_TRUE(data.WriteString(printerId)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, QueryPrinterCapabilityByUri).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0044, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_STARTPRINTJOB_BY_ADAPTER); + + std::string jobName = "com.exmpale.ext"; + PrintAttributes attr; + + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(jobName)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, PrintByAdapter).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0045, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_START_GET_FILE); + + std::string jobId = "1"; + PrintAttributes attr; + uint32_t fd = 56; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(jobId)); + EXPECT_TRUE(data.WriteUint32(fd)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, StartGetPrintFile).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0046, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_NOTIFY_PRINT_SERVICE); + + std::string jobId = ""; + std::string type = ""; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(jobId)); + EXPECT_TRUE(data.WriteString(type)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, NotifyPrintService).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0047, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_START_NATIVE_PRINT); + + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, StartPrint).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0048, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_START_SERVICE); + + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, StartService).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0049, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_REG_PRINTER_CB); + + std::string type = ""; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(type)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, RegisterPrinterCallback).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0050, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_UNREG_PRINTER_CB); + + std::string type = ""; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(type)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, UnregisterPrinterCallback).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0051, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_QUERYPRINTERINFOBYPRINTERID); + + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(printerId)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, QueryPrinterInfoByPrinterId).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0052, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_QUERYADDEDPRINTER); + + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, QueryAddedPrinter).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0053, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_QUERYPRINTERPROPERTIES); + + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-1620"; + std::vector keyList; + keyList.resize(1001); + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(data.WriteString(printerId)); + EXPECT_TRUE(data.WriteStringVector(keyList)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, QueryPrinterProperties).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0054, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_STARTNATIVEPRINTJOB); + + PrintJob testJob; + EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor())); + EXPECT_TRUE(testJob.Marshalling(data)); + + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + ON_CALL(*stub, StartNativePrintJob).WillByDefault(Return(E_PRINT_NONE)); + EXPECT_TRUE(static_cast(stub->OnRemoteRequest(code, data, reply, option))); +} + +/** + * @tc.name: PrintServiceStubTest_0055 + * @tc.desc: Verify the capability function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0055, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + uint32_t code = static_cast(CMD_START_SERVICE); + data.WriteString("nativePrint"); + auto stub = std::make_shared(); + EXPECT_NE(stub, nullptr); + EXPECT_EQ(stub->OnRemoteRequest(code, data, reply, option), E_PRINT_RPC_FAILURE); +} + } // namespace Print } // namespace OHOS diff --git a/test/unittest/service_test/print_system_data_test.cpp b/test/unittest/service_test/print_system_data_test.cpp new file mode 100644 index 0000000..35e95ee --- /dev/null +++ b/test/unittest/service_test/print_system_data_test.cpp @@ -0,0 +1,931 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "printer_info.h" +#define private public +#include "print_system_data.h" +#undef private +#include "print_log.h" +#include "print_constant.h" + +using namespace testing::ext; +using json = nlohmann::json; + +namespace OHOS { +namespace Print { + +class PrintSystemDataTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintSystemDataTest::SetUpTestCase(void) {} + +void PrintSystemDataTest::TearDownTestCase(void) {} + +void PrintSystemDataTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintSystemDataTest_%{public}d", ++testNo); +} + +void PrintSystemDataTest::TearDown(void) {} + +/** + * @tc.name: PrintSystemDataTest_0001 + * @tc.desc: Verify the PrintSystemData function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0001, TestSize.Level1) +{ + auto systemData = std::make_shared(); + EXPECT_EQ(systemData->Init(), false); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0002, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo; + systemData->InsertCupsPrinter(printerId, cupsPrinterInfo, false); + cupsPrinterInfo.name = "HW_PixLab_V1-0105"; + cupsPrinterInfo.uri = "ipp://192.168.186.1:631/ipp/print"; + cupsPrinterInfo.maker = "HW PixLab V1"; + systemData->InsertCupsPrinter(printerId, cupsPrinterInfo, false); + std::map> addedPrinterMap; + addedPrinterMap[printerId] = std::make_shared(cupsPrinterInfo); + EXPECT_EQ(addedPrinterMap.size(), 1); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0003, TestSize.Level1) +{ + auto systemData = std::make_shared(); + EXPECT_EQ(systemData->SaveCupsPrinterMap(), true); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0004, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerName = "Direct Pixlab1620"; + EXPECT_EQ(systemData->QueryPrinterIdByStandardizeName(printerName), ""); + systemData->addedPrinterMap_["1234"] = nullptr; + systemData->QueryPrinterIdByStandardizeName(printerName); + EXPECT_EQ(systemData->SaveCupsPrinterMap(), true); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0005, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerName = "Direct Pixlab1620"; + EXPECT_EQ(systemData->QueryPrinterIdByStandardizeName(printerName), ""); + std::string re = systemData->QueryPrinterIdByStandardizeName(printerName); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "Direct Pixlab1620"; + std::map> addedPrinterMap; + addedPrinterMap[printerId] = std::make_shared(cupsPrinterInfo); + EXPECT_EQ(addedPrinterMap.size(), 1); + if (cupsPrinterInfo.name == printerName) { + re = printerId; + } +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0006, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo1; + cupsPrinterInfo1.name = "Direct Pixlab1620"; + CupsPrinterInfo cupsPrinterInfo2; + EXPECT_EQ(systemData->QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinterInfo2), false); + std::map> addedPrinterMap; + addedPrinterMap[printerId] = std::make_shared(cupsPrinterInfo1); + EXPECT_EQ(addedPrinterMap.size(), 1); + if (addedPrinterMap.count(printerId)) { + cupsPrinterInfo2 = cupsPrinterInfo1; + EXPECT_EQ(cupsPrinterInfo2.name, cupsPrinterInfo1.name); + } +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0007, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + PrinterInfo printerInfo; + systemData->InsertPrinterInfo(printerId, printerInfo); + std::map> addedPrinterInfoList; + addedPrinterInfoList[printerId] = std::make_shared(printerInfo); + EXPECT_EQ(addedPrinterInfoList.size(), 1); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0008, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + EXPECT_EQ(systemData->QueryPrinterInfoByPrinterId(printerId), nullptr); + std::shared_ptr result = std::make_shared(); + systemData->QueryPrinterInfoByPrinterId(printerId); + PrinterInfo printerInfo; + printerInfo.SetPrinterName("123"); + std::map> addedPrinterInfoList; + addedPrinterInfoList[printerId] = std::make_shared(printerInfo); + EXPECT_EQ(addedPrinterInfoList.size(), 1); + if (addedPrinterInfoList.count(printerId)) { + result = addedPrinterInfoList[printerId]; + EXPECT_EQ(result->GetPrinterName(), "123"); + } +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0009, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson = nlohmann::json::array(); + nlohmann::json printerJson; + printerJson["id"] = "com.ohos.spooler:mdns://9e9561ad-0e30-1000-8000-9c9561ad0e30"; + printerJson["maker"] = "HW PixLab V1"; + printerJson["name"] = "HW_PixLab_V1-0105"; + printerJson["uri"] = "ipp://192.168.186.1:631/ipp/print"; + printerMapJson.push_back(printerJson); + nlohmann::json jsonObject; + jsonObject["version"] = "v1"; + jsonObject["printer_list"] = printerMapJson; + EXPECT_EQ(systemData->ParsePrinterListJsonV1(printerMapJson), false); + EXPECT_EQ(systemData->ParsePrinterListJsonV1(jsonObject), true); + std::string printerName = systemData->QueryPrinterIdByStandardizeName("HW_PixLab_V1-0105"); + EXPECT_EQ(systemData->SaveCupsPrinterMap(), true); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0010, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson; + printerMapJson["printer"] = "1234"; + EXPECT_EQ(systemData->ParsePrinterListJsonV1(printerMapJson), false); + printerMapJson["printer_list"] = "1234"; + EXPECT_EQ(systemData->ParsePrinterListJsonV1(printerMapJson), false); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0011, TestSize.Level1) +{ + auto systemData = std::make_shared(); + systemData->addedPrinterMap_["1"] = nullptr; + systemData->SaveCupsPrinterMap(); + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "print"; + cupsPrinterInfo.uri = "123"; + cupsPrinterInfo.maker = "print"; + systemData->addedPrinterMap_["2"] = std::make_shared(cupsPrinterInfo); + systemData->SaveCupsPrinterMap(); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0012, TestSize.Level1) +{ + auto systemData = std::make_shared(); + systemData->addedPrinterMap_["1"] = nullptr; + std::string printerName = "Direct"; + systemData->QueryPrinterIdByStandardizeName(printerName); + systemData->SaveCupsPrinterMap(); + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "Direct"; + cupsPrinterInfo.uri = "123"; + cupsPrinterInfo.maker = "print"; + systemData->addedPrinterMap_["2"] = std::make_shared(cupsPrinterInfo); + systemData->QueryPrinterIdByStandardizeName(printerName); + cupsPrinterInfo.name = "223"; + systemData->addedPrinterMap_["4"] = std::make_shared(cupsPrinterInfo); + systemData->QueryPrinterIdByStandardizeName(printerName); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0013, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo2; + systemData->addedPrinterMap_["1"] = nullptr; + systemData->QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinterInfo2); + systemData->SaveCupsPrinterMap(); + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "Direct Pixlab1620"; + cupsPrinterInfo.uri = "123"; + cupsPrinterInfo.maker = "print"; + systemData->addedPrinterMap_["123"] = std::make_shared(cupsPrinterInfo); + CupsPrinterInfo cupsPrinterInfo3; + systemData->addedPrinterMap_["11"] = std::make_shared(cupsPrinterInfo3); + systemData->QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinterInfo2); + systemData->addedPrinterMap_["1234"] = std::make_shared(cupsPrinterInfo); + systemData->QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinterInfo2); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0014, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + PrinterInfo printerInfo; + systemData->InsertPrinterInfo(printerId, printerInfo); + systemData->addedPrinterMap_["1"] = nullptr; + systemData->InsertPrinterInfo(printerId, printerInfo); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0015, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + PrinterInfo printerInfo; + systemData->addedPrinterInfoList_["1"] = nullptr; + systemData->QueryPrinterInfoByPrinterId(printerId); + systemData->addedPrinterInfoList_["1234"] = std::make_shared(printerInfo); + systemData->QueryPrinterInfoByPrinterId(printerId); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0016, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo; + systemData->InsertCupsPrinter(printerId, cupsPrinterInfo, false); + systemData->addedPrinterMap_["1234"] = nullptr; + systemData->InsertCupsPrinter(printerId, cupsPrinterInfo, false); + systemData->addedPrinterMap_["1234"] = std::make_shared(cupsPrinterInfo); + systemData->InsertCupsPrinter(printerId, cupsPrinterInfo, false); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0017, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson = nlohmann::json::array(); + nlohmann::json printerJson; + printerJson["id"] = 123; + printerJson["maker"] = 123; + printerJson["name"] = 132; + printerJson["uri"] = 123; + printerMapJson.push_back(printerJson); + nlohmann::json jsonObject; + jsonObject["version"] = "v1"; + jsonObject["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0018, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson = nlohmann::json::array(); + nlohmann::json printerJson; + printerMapJson.push_back(printerJson); + nlohmann::json jsonObject; + jsonObject["version"] = "v1"; + jsonObject["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject); + + nlohmann::json printerJson2; + printerJson2["id"] = "123"; + printerMapJson.push_back(printerJson2); + nlohmann::json jsonObject2; + jsonObject2["version"] = "v1"; + jsonObject2["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject2); + + nlohmann::json printerJson3; + printerJson3["id"] = "123"; + printerJson3["name"] = 132; + printerMapJson.push_back(printerJson3); + nlohmann::json jsonObject3; + jsonObject3["version"] = "v1"; + jsonObject3["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject3); + + nlohmann::json printerJson4; + printerJson4["id"] = "123"; + printerJson4["name"] = "132"; + printerMapJson.push_back(printerJson4); + nlohmann::json jsonObject4; + jsonObject4["version"] = "v1"; + jsonObject4["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject4); + + nlohmann::json printerJson5; + printerJson5["id"] = "123"; + printerJson5["name"] = "132"; + printerJson5["uri"] = 123; + printerMapJson.push_back(printerJson5); + nlohmann::json jsonObject5; + jsonObject5["version"] = "v1"; + jsonObject5["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject5); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0019, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson = nlohmann::json::array(); + nlohmann::json printerJson; + printerMapJson.push_back(printerJson); + nlohmann::json jsonObject; + jsonObject["version"] = "v1"; + jsonObject["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject); + + nlohmann::json printerJson6; + printerJson6["id"] = "123"; + printerJson6["name"] = "132"; + printerJson6["uri"] = "123"; + printerMapJson.push_back(printerJson6); + nlohmann::json jsonObject6; + jsonObject6["version"] = "v1"; + jsonObject6["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject6); + + nlohmann::json printerJson7; + printerJson7["id"] = "123"; + printerJson7["name"] = "132"; + printerJson7["uri"] = "123"; + printerJson7["maker"] = 123; + printerMapJson.push_back(printerJson7); + nlohmann::json jsonObject7; + jsonObject7["version"] = "v1"; + jsonObject7["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject7); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0020, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson = nlohmann::json::array(); + nlohmann::json printerJson; + printerJson["id"] = "123"; + printerJson["name"] = "132"; + printerJson["uri"] = "123"; + printerJson["maker"] = 123; + nlohmann::json capsJson = nlohmann::json::array(); + printerJson["capability"] = capsJson; + printerMapJson.push_back(printerJson); + nlohmann::json jsonObject; + jsonObject["version"] = "v1"; + jsonObject["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0021, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json printerMapJson = nlohmann::json::array(); + nlohmann::json printerJson; + printerJson["id"] = "123"; + printerJson["name"] = "132"; + printerJson["uri"] = "123"; + printerJson["maker"] = 123; + nlohmann::json capsJson = nlohmann::json::object(); + printerJson["capability"] = capsJson; + printerMapJson.push_back(printerJson); + nlohmann::json jsonObject; + jsonObject["version"] = "v1"; + jsonObject["printer_list"] = printerMapJson; + systemData->ParsePrinterListJsonV1(jsonObject); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0022, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo; + systemData->addedPrinterMap_["1234"] = std::make_shared(cupsPrinterInfo); + systemData->InsertCupsPrinter(printerId, cupsPrinterInfo, true); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0023, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + CupsPrinterInfo cupsPrinterInfo; + systemData->addedPrinterMap_["1234"] = std::make_shared(cupsPrinterInfo); + systemData->DeleteCupsPrinter(printerId); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0024, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + systemData->addedPrinterMap_["1"] = nullptr; + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "Direct"; + cupsPrinterInfo.uri = "123"; + cupsPrinterInfo.maker = "print"; + systemData->addedPrinterMap_["2"] = std::make_shared(cupsPrinterInfo); + CupsPrinterInfo cupsPrinterInfo2; + cupsPrinterInfo2.name = "Direct"; + cupsPrinterInfo2.uri = "123"; + cupsPrinterInfo2.maker = "print"; + systemData->addedPrinterMap_["1234"] = std::make_shared(cupsPrinterInfo2); + systemData->UpdatePrinterStatus(printerId, PRINTER_STATUS_IDLE); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0025, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::string printerId = "1234"; + systemData->addedPrinterMap_["1"] = nullptr; + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "Direct"; + cupsPrinterInfo.uri = "123"; + cupsPrinterInfo.maker = "print"; + systemData->addedPrinterMap_["2"] = std::make_shared(cupsPrinterInfo); + std::vector printerNameList; + systemData->GetAddedPrinterListFromSystemData(printerNameList); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0026, TestSize.Level1) +{ + auto systemData = std::make_shared(); + std::vector printerNameList; + systemData->GetAddedPrinterListFromSystemData(printerNameList); + systemData->addedPrinterMap_["1"] = nullptr; + systemData->GetAddedPrinterListFromSystemData(printerNameList); + CupsPrinterInfo cupsPrinterInfo; + cupsPrinterInfo.name = "Direct"; + cupsPrinterInfo.uri = "123"; + cupsPrinterInfo.maker = "print"; + systemData->addedPrinterMap_["1"] = std::make_shared(cupsPrinterInfo); + systemData->GetAddedPrinterListFromSystemData(printerNameList); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0027, TestSize.Level1) +{ + auto systemData = std::make_shared(); + PrinterCapability printerCapability; + nlohmann::json capsJson; + systemData->ConvertPrinterCapabilityToJson(printerCapability, capsJson); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0028, TestSize.Level1) +{ + auto systemData = std::make_shared(); + PrinterCapability printerCapability; + PrintMargin minMargin; + printerCapability.SetMinMargin(minMargin); + std::vector resolutionList; + printerCapability.SetResolution(resolutionList); + std::string ops = "test"; + printerCapability.SetOption(ops); + nlohmann::json capsJson; + systemData->ConvertPrinterCapabilityToJson(printerCapability, capsJson); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0029, TestSize.Level1) +{ + auto systemData = std::make_shared(); + PrinterCapability printerCapability; + PrintMargin minMargin; + printerCapability.SetMinMargin(minMargin); + std::vector resolutionList; + printerCapability.SetResolution(resolutionList); + nlohmann::json ops; + ops["key"] = "value"; + printerCapability.SetOption(ops.dump()); + nlohmann::json capsJson; + systemData->ConvertPrinterCapabilityToJson(printerCapability, capsJson); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0030, TestSize.Level1) +{ + auto systemData = std::make_shared(); + PrinterCapability printerCapability; + PrintMargin minMargin; + printerCapability.SetMinMargin(minMargin); + nlohmann::json capsJson; + systemData->ConvertPrintMarginToJson(printerCapability, capsJson); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0031, TestSize.Level1) +{ + auto systemData = std::make_shared(); + PrinterCapability printerCapability; + PrintMargin minMargin; + minMargin.SetTop(100); + minMargin.SetBottom(100); + minMargin.SetLeft(100); + minMargin.SetRight(100); + printerCapability.SetMinMargin(minMargin); + nlohmann::json capsJson; + systemData->ConvertPrintMarginToJson(printerCapability, capsJson); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0032, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + capsJson["colorMode"] = "string"; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + capsJson["colorMode"] = 123; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + capsJson["duplexMode"] = "string"; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + capsJson["duplexMode"] = 123; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json marginJson = nlohmann::json::array(); + capsJson["minMargin"] = marginJson; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json marginJson2 = nlohmann::json::object(); + capsJson["minMargin"] = marginJson2; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json pageSizeJson = nlohmann::json::object(); + capsJson["pageSize"] = pageSizeJson; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json pageSizeJson2 = nlohmann::json::array(); + nlohmann::json pageSize = nlohmann::json::array(); + pageSizeJson2.push_back(pageSize); + capsJson["pageSize"] = pageSizeJson2; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json pageSizeJson3 = nlohmann::json::array(); + capsJson["pageSize"] = pageSizeJson3; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json resolutionJson = nlohmann::json::object(); + capsJson["resolution"] = resolutionJson; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json resolutionJson2 = nlohmann::json::array(); + nlohmann::json resolution = nlohmann::json::array(); + resolutionJson2.push_back(resolution); + capsJson["resolution"] = resolutionJson2; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json resolutionJson3 = nlohmann::json::array(); + capsJson["resolution"] = resolutionJson3; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json opsJson = nlohmann::json::array(); + capsJson["options"] = opsJson; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); + nlohmann::json opsJson2 = nlohmann::json::object(); + capsJson["options"] = opsJson2; + systemData->ConvertJsonToPrinterCapability(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0033, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json resolutionListJson = nlohmann::json::array(); + nlohmann::json resolutionItem = nlohmann::json::array(); + resolutionListJson.push_back(resolutionItem); + capsJson["resolution"] = resolutionListJson; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); + nlohmann::json resolutionListJson2 = nlohmann::json::array(); + nlohmann::json resolutionItem2 = nlohmann::json::object(); + resolutionListJson2.push_back(resolutionItem2); + capsJson["resolution"] = resolutionListJson2; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); + nlohmann::json resolutionListJson3 = nlohmann::json::array(); + nlohmann::json resolutionItem3 = nlohmann::json::object(); + resolutionItem3["id"] = 123; + resolutionListJson3.push_back(resolutionItem3); + capsJson["resolution"] = resolutionListJson3; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); + nlohmann::json resolutionListJson4 = nlohmann::json::array(); + nlohmann::json resolutionItem4 = nlohmann::json::object(); + resolutionItem4["id"] = "123"; + resolutionListJson4.push_back(resolutionItem4); + capsJson["resolution"] = resolutionListJson4; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0034, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json resolutionListJson = nlohmann::json::array(); + nlohmann::json resolutionItem = nlohmann::json::object(); + resolutionItem["id"] = "123"; + resolutionItem["horizontalDpi"] = "123"; + resolutionListJson.push_back(resolutionItem); + capsJson["resolution"] = resolutionListJson; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); + nlohmann::json resolutionListJson2 = nlohmann::json::array(); + nlohmann::json resolutionItem2 = nlohmann::json::object(); + resolutionItem2["id"] = "123"; + resolutionItem2["horizontalDpi"] = 123; + resolutionListJson2.push_back(resolutionItem2); + capsJson["resolution"] = resolutionListJson2; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); + nlohmann::json resolutionListJson3 = nlohmann::json::array(); + nlohmann::json resolutionItem3 = nlohmann::json::object(); + resolutionItem3["id"] = "123"; + resolutionItem3["horizontalDpi"] = "123"; + resolutionItem3["verticalDpi"] = "123"; + resolutionListJson3.push_back(resolutionItem3); + capsJson["resolution"] = resolutionListJson3; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); + nlohmann::json resolutionListJson4 = nlohmann::json::array(); + nlohmann::json resolutionItem4 = nlohmann::json::object(); + resolutionItem4["id"] = "123"; + resolutionItem4["horizontalDpi"] = "123"; + resolutionItem4["verticalDpi"] = 123; + resolutionListJson4.push_back(resolutionItem4); + capsJson["resolution"] = resolutionListJson4; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0035, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json resolutionListJson = nlohmann::json::array(); + capsJson["resolution"] = resolutionListJson; + systemData->ConvertJsonToPrintResolution(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0036, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json pageSizeListJson = nlohmann::json::array(); + capsJson["pageSize"] = pageSizeListJson; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson2 = nlohmann::json::array(); + nlohmann::json pageSizeItem2 = nlohmann::json::array(); + pageSizeListJson2.push_back(pageSizeItem2); + capsJson["pageSize"] = pageSizeListJson2; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson3 = nlohmann::json::array(); + nlohmann::json pageSizeItem3 = nlohmann::json::object(); + pageSizeItem3["id"] = 123; + pageSizeListJson3.push_back(pageSizeItem3); + capsJson["pageSize"] = pageSizeListJson3; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson4 = nlohmann::json::array(); + nlohmann::json pageSizeItem4 = nlohmann::json::object(); + pageSizeItem4["id"] = "123"; + pageSizeListJson4.push_back(pageSizeItem4); + capsJson["pageSize"] = pageSizeListJson4; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0037, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json pageSizeListJson = nlohmann::json::array(); + nlohmann::json pageSizeItem = nlohmann::json::object(); + pageSizeItem["id"] = "123"; + pageSizeItem["name"] = 123; + pageSizeListJson.push_back(pageSizeItem); + capsJson["pageSize"] = pageSizeListJson; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson2 = nlohmann::json::array(); + nlohmann::json pageSizeItem2 = nlohmann::json::object(); + pageSizeItem2["id"] = "123"; + pageSizeItem2["name"] = "123"; + pageSizeListJson2.push_back(pageSizeItem2); + capsJson["pageSize"] = pageSizeListJson2; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson3 = nlohmann::json::array(); + nlohmann::json pageSizeItem3 = nlohmann::json::object(); + pageSizeItem3["id"] = "123"; + pageSizeItem3["name"] = "123"; + pageSizeItem3["width"] = "123"; + pageSizeListJson3.push_back(pageSizeItem3); + capsJson["pageSize"] = pageSizeListJson3; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson4 = nlohmann::json::array(); + nlohmann::json pageSizeItem4 = nlohmann::json::object(); + pageSizeItem4["id"] = "123"; + pageSizeItem4["name"] = "123"; + pageSizeItem4["width"] = 123; + pageSizeListJson4.push_back(pageSizeItem4); + capsJson["pageSize"] = pageSizeListJson4; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0038, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json pageSizeListJson = nlohmann::json::array(); + nlohmann::json pageSizeItem = nlohmann::json::object(); + pageSizeItem["id"] = "123"; + pageSizeItem["name"] = "123"; + pageSizeItem["width"] = 123; + pageSizeItem["height"] = "123"; + pageSizeListJson.push_back(pageSizeItem); + capsJson["pageSize"] = pageSizeListJson; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); + + nlohmann::json pageSizeListJson2 = nlohmann::json::array(); + nlohmann::json pageSizeItem2 = nlohmann::json::object(); + pageSizeItem2["id"] = "123"; + pageSizeItem2["name"] = "123"; + pageSizeItem2["width"] = 123; + pageSizeItem2["height"] = 123; + pageSizeListJson2.push_back(pageSizeItem2); + capsJson["pageSize"] = pageSizeListJson2; + systemData->ConvertJsonToPageSize(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0039, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json marginJson = nlohmann::json::object(); + capsJson["minMargin"] = marginJson; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson2 = nlohmann::json::object(); + marginJson2["top"] = "123"; + capsJson["minMargin"] = marginJson2; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson3 = nlohmann::json::object(); + marginJson3["top"] = 123; + capsJson["minMargin"] = marginJson3; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson4 = nlohmann::json::object(); + marginJson4["top"] = 123; + marginJson4["bottom"] = "123"; + capsJson["minMargin"] = marginJson4; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson5 = nlohmann::json::object(); + marginJson5["top"] = 123; + marginJson5["bottom"] = 123; + capsJson["minMargin"] = marginJson5; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson6 = nlohmann::json::object(); + marginJson6["top"] = 123; + marginJson6["bottom"] = 123; + marginJson6["left"] = "123"; + capsJson["minMargin"] = marginJson6; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson7 = nlohmann::json::object(); + marginJson7["top"] = 123; + marginJson7["bottom"] = 123; + marginJson7["left"] = 123; + capsJson["minMargin"] = marginJson7; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0040, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json capsJson; + PrinterCapability printerCapability; + nlohmann::json marginJson = nlohmann::json::object(); + marginJson["top"] = 123; + marginJson["bottom"] = 123; + marginJson["left"] = 123; + marginJson["right"] = "123"; + capsJson["minMargin"] = marginJson; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); + + nlohmann::json marginJson2 = nlohmann::json::object(); + marginJson2["top"] = 123; + marginJson2["bottom"] = 123; + marginJson2["left"] = 123; + marginJson2["right"] = 123; + capsJson["minMargin"] = marginJson2; + systemData->ConvertJsonToPrintMargin(capsJson, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0041, TestSize.Level1) +{ + auto systemData = std::make_shared(); + CupsPrinterInfo cupsPrinter; + std::string printerId = "123"; + PrinterCapability printerCapability; + systemData->GetPrinterCapabilityFromSystemData(cupsPrinter, printerId, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0042, TestSize.Level1) +{ + auto systemData = std::make_shared(); + CupsPrinterInfo cupsPrinter; + std::string printerId = "123"; + PrinterCapability printerCapability; + PrinterCapability printerCapability2; + nlohmann::json opsJson; + opsJson["key"] = "value"; + printerCapability2.SetOption(opsJson.dump()); + std::vector pageSizeList; + PrintPageSize pageSize; + pageSizeList.push_back(pageSize); + printerCapability2.SetPageSize(pageSizeList); + cupsPrinter.printerCapability = printerCapability2; + systemData->GetPrinterCapabilityFromSystemData(cupsPrinter, printerId, printerCapability); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0043, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json object; + std::string printerId = "123"; + systemData->CheckPrinterInfoJson(object, printerId); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0044, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json object; + object["id"] = 123; + std::string printerId = "123"; + systemData->CheckPrinterInfoJson(object, printerId); + + nlohmann::json object2; + object2["id"] = "12"; + systemData->CheckPrinterInfoJson(object2, printerId); + + nlohmann::json object3; + object3["id"] = "123"; + systemData->CheckPrinterInfoJson(object3, printerId); + + nlohmann::json object4; + object4["id"] = "123"; + object4["name"] = 123; + systemData->CheckPrinterInfoJson(object4, printerId); + + nlohmann::json object5; + object5["id"] = "123"; + object5["name"] = "123"; + systemData->CheckPrinterInfoJson(object5, printerId); + + nlohmann::json object6; + object6["id"] = "123"; + object6["name"] = "123"; + object6["uri"] = 123; + systemData->CheckPrinterInfoJson(object6, printerId); + + nlohmann::json object7; + object7["id"] = "123"; + object7["name"] = "123"; + object7["uri"] = "123"; + systemData->CheckPrinterInfoJson(object7, printerId); +} + +HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0045, TestSize.Level1) +{ + auto systemData = std::make_shared(); + nlohmann::json object; + object["id"] = "123"; + object["name"] = "123"; + object["uri"] = "123"; + object["maker"] = 123; + std::string printerId = "123"; + systemData->CheckPrinterInfoJson(object, printerId); + + nlohmann::json object2; + object2["id"] = "123"; + object2["name"] = "123"; + object2["uri"] = "123"; + object2["maker"] = "123"; + systemData->CheckPrinterInfoJson(object2, printerId); + + nlohmann::json object3; + object3["id"] = "123"; + object3["name"] = "123"; + object3["uri"] = "123"; + object3["maker"] = "123"; + object3["capability"] = "123"; + systemData->CheckPrinterInfoJson(object3, printerId); + + nlohmann::json object4; + object4["id"] = "123"; + object4["name"] = "123"; + object4["uri"] = "123"; + object4["maker"] = "123"; + nlohmann::json capsJson = nlohmann::json::object(); + object4["capability"] = capsJson; + systemData->CheckPrinterInfoJson(object4, printerId); +} +} // namespace Print +} // namespace OHOS diff --git a/test/unittest/service_test/print_usb_manager_test.cpp b/test/unittest/service_test/print_usb_manager_test.cpp new file mode 100644 index 0000000..a7c5091 --- /dev/null +++ b/test/unittest/service_test/print_usb_manager_test.cpp @@ -0,0 +1,354 @@ +/* + * 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 +#define private public +#include "print_usb_manager.h" +#undef private +#include "print_ipp_over_usb_constant.h" +#include "print_log.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Print { +static const std::string IPP_PRINTER = + R"({"busNum":2,"clazz":0,"configs":[{"attributes":192,"id":1,"interfaces":[{"alternateSetting":0,"clazz":7,)"\ + R"("endpoints":[{"address":1,"attributes":2,"direction":0,"interfaceId":0,"interval":0,"maxPacketSize":512,)"\ + R"("number":1,"type":2},{"address":129,"attributes":2,"direction":128,"interfaceId":0,"interval":0,)"\ + R"("maxPacketSize":512,"number":1,"type":2}],"id":0,"name":"","protocol":2,"subClass":1},{"alternateSetting":0,)"\ + R"("clazz":255,"endpoints":[{"address":2,"attributes":2,"direction":0,"interfaceId":1,"interval":0,)"\ + R"("maxPacketSize":512,"number":2,"type":2},{"address":130,"attributes":2,"direction":128,"interfaceId":1,)"\ + R"("interval":0,"maxPacketSize":512,"number":2,"type":2}],"id":1,"name":"","protocol":255,"subClass":255},)"\ + R"({"alternateSetting":0,"clazz":7,"endpoints":[{"address":3,"attributes":2,"direction":0,"interfaceId":2,)"\ + R"("interval":0,"maxPacketSize":512,"number":3,"type":2},{"address":131,"attributes":2,"direction":128,)"\ + R"("interfaceId":2,"interval":0,"maxPacketSize":512,"number":3,"type":2}],"id":2,"name":"","protocol":4,)"\ + R"("subClass":1},{"alternateSetting":0,"clazz":7,"endpoints":[{"address":4,"attributes":2,"direction":0,)"\ + R"("interfaceId":3,"interval":0,"maxPacketSize":512,"number":4,"type":2},{"address":132,"attributes":2,)"\ + R"("direction":128,"interfaceId":3,"interval":0,"maxPacketSize":512,"number":4,"type":2}],"id":3,"name":"",)"\ + R"("protocol":4,"subClass":1},{"alternateSetting":0,"clazz":7,"endpoints":[{"address":5,"attributes":2,)"\ + R"("direction":0,"interfaceId":4,"interval":0,"maxPacketSize":512,"number":5,"type":2},{"address":133,)"\ + R"("attributes":2,"direction":128,"interfaceId":4,"interval":0,"maxPacketSize":512,"number":5,"type":2}],)"\ + R"("id":4,"name":"","protocol":4,"subClass":1},{"alternateSetting":0,"clazz":7,"endpoints":[{"address":6,)"\ + R"("attributes":2,"direction":0,"interfaceId":5,"interval":0,"maxPacketSize":512,"number":6,"type":2},)"\ + R"({"address":134,"attributes":2,"direction":128,"interfaceId":5,"interval":0,"maxPacketSize":512,)"\ + R"("number":6,"type":2}],"id":5,"name":" ","protocol":4,"subClass":1}],"isRemoteWakeup":false,)"\ + R"("isSelfPowered":true,"maxPower":1,"name":" "}],"devAddress":5,"manufacturerName":" ","name":"2-5",)"\ + R"("productId":4293,"productName":" ","protocol":0,"serial":"","subClass":0,"vendorId":4817,"version":"0404"})"; + +static const std::string NON_IPP_PRINTER = + R"({"busNum":2,"clazz":0,"configs":[{"attributes":192,"id":1,"interfaces":[{"alternateSetting":0,"clazz":255,)"\ + R"("endpoints":null,"id":0,"name":" ","protocol":255,"subClass":255}],"isRemoteWakeup":false,)"\ + R"("isSelfPowered":true,"maxPower":0,"name":" "}],"devAddress":4,"manufacturerName":"Microchip Tech\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000","name":"2-4","productId":10048,"productName":"Hub Controller\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)"\ + R"(\u0000", "protocol":0, "serial":"", "subClass":0, "vendorId":1060, "version":"0002"})"; + +class PrintUsbManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintUsbManagerTest::SetUpTestCase(void) +{} + +void PrintUsbManagerTest::TearDownTestCase(void) +{} + +void PrintUsbManagerTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintUsbManagerTest_%{public}d", ++testNo); +} + +void PrintUsbManagerTest::TearDown(void) +{} + +/** + * @tc.name: PrintUsbManagerTest_001 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_001, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + printUsbManager.isInit = true; + printUsbManager.Init(); + EXPECT_EQ(true, printUsbManager.isInit); +} + +/** + * @tc.name: PrintUsbManagerTest_002 + * @tc.desc: Verify the isExistIppOverUsbPrinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_002, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = "HW PixLab V1-0105"; + OHOS::USB::UsbDevice usbDevice; + printUsbManager.printDeviceMap[printerName] = usbDevice; + bool ret = printUsbManager.isExistIppOverUsbPrinter(printerName); + EXPECT_EQ(true, ret); +} + +/** + * @tc.name: PrintUsbManagerTest_003 + * @tc.desc: Verify the isPrintDevice function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_003, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + OHOS::USB::UsbDevice usbDevice; + std::string printerName; + bool ret = printUsbManager.isPrintDevice(usbDevice, printerName); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: PrintUsbManagerTest_004 + * @tc.desc: Verify the RefreshUsbPrinterDevice function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_004, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + printUsbManager.RefreshUsbPrinterDevice(); +} + +/** + * @tc.name: PrintUsbManagerTest_005 + * @tc.desc: Verify the GetProductName function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_005, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + OHOS::USB::UsbDevice usbDevice; + std::string printerName = printUsbManager.GetProductName(usbDevice); + EXPECT_EQ("", printerName); +} + +/** + * @tc.name: PrintUsbManagerTest_006 + * @tc.desc: Verify the QueryPrinterInfoFromStringDescriptor function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_006, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + OHOS::USB::USBDevicePipe usbDevicePipe; + uint16_t indexInStringDescriptor = USB_VALUE_DESCRIPTOR_INDEX_PRODUCT_NAME; + std::string printerInfo = + printUsbManager.QueryPrinterInfoFromStringDescriptor(usbDevicePipe, indexInStringDescriptor); + EXPECT_EQ("", printerInfo); +} + +/** + * @tc.name: PrintUsbManagerTest_007 + * @tc.desc: Verify the ConnectUsbPinter function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_007, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = "HW PixLab V1-0105"; + OHOS::USB::USBDevicePipe usbDevicePipe; + printUsbManager.printPipeMap[printerName] = usbDevicePipe; + OHOS::USB::UsbDevice usbDevice; + printUsbManager.printDeviceMap[printerName] = usbDevice; + bool ret = printUsbManager.ConnectUsbPinter(printerName); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: PrintUsbManagerTest_09 + * @tc.desc: Verify the BulkTransferWrite function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_09, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = "HW PixLab V1-0105"; + std::vector vectorRequestBuffer; + int32_t ret = + printUsbManager.BulkTransferWrite(printerName, Operation::Get_Printer_Attributes, vectorRequestBuffer); + EXPECT_GT(0, ret); + ret = printUsbManager.BulkTransferWrite(printerName, Operation::Send_Document, vectorRequestBuffer); + EXPECT_GT(0, ret); + ret = printUsbManager.BulkTransferWrite(printerName, Operation::Common, vectorRequestBuffer); + EXPECT_GT(0, ret); +} + +/** + * @tc.name: PrintUsbManagerTest_010 + * @tc.desc: Verify the BulkTransferRead function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_010, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = "HW PixLab V1-0105"; + std::vector vectorRequestBuffer; + int32_t ret = printUsbManager.BulkTransferRead(printerName, Operation::Get_Printer_Attributes, vectorRequestBuffer); + EXPECT_GT(0, ret); + ret = printUsbManager.BulkTransferRead(printerName, Operation::Send_Document, vectorRequestBuffer); + EXPECT_GT(0, ret); + ret = printUsbManager.BulkTransferRead(printerName, Operation::Common, vectorRequestBuffer); + EXPECT_GT(0, ret); +} + +/** + * @tc.name: PrintUsbManagerTest_011 + * @tc.desc: Verify the DealUsbDevStatusChange function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_011, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + bool isAttach = true; + std::string devStr = IPP_PRINTER; + std::string devStrNull = ""; + printUsbManager.DealUsbDevStatusChange(devStr, isAttach); + isAttach = false; + printUsbManager.DealUsbDevStatusChange(devStr, isAttach); + printUsbManager.DealUsbDevStatusChange(devStrNull, isAttach); + isAttach = true; + devStr = NON_IPP_PRINTER; + printUsbManager.DealUsbDevStatusChange(NON_IPP_PRINTER, isAttach); +} + +/** + * @tc.name: PrintUsbManagerTest_012 + * @tc.desc: Verify the GetPrinterName function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_012, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string name = "HW PixLab V1-0105"; + std::string printerName = printUsbManager.GetPrinterName(name); + EXPECT_EQ("", printerName); + OHOS::USB::UsbDevice usbDevice; + printUsbManager.printDeviceMap[printerName] = usbDevice; + printUsbManager.GetPrinterName(usbDevice.GetName()); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_013, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string name = "HW PixLab V1-0105"; + OHOS::USB::USBDevicePipe usbDevicePipe; + OHOS::USB::UsbDevice usbDevice; + bool ret = printUsbManager.AllocateInterface(name, usbDevice, usbDevicePipe); + EXPECT_EQ(false, ret); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_014, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string name = "HW PixLab V1-0105"; + OHOS::USB::UsbDevice usbDevice; + printUsbManager.printDeviceMap[name] = usbDevice; + printUsbManager.DisConnectUsbPinter(name); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_015, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string name = "HW PixLab V1-0105"; + OHOS::USB::USBDevicePipe usbDevicePipe; + printUsbManager.printPipeMap[name] = usbDevicePipe; + printUsbManager.DisConnectUsbPinter(name); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_016, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string name = ""; + printUsbManager.DisConnectUsbPinter(name); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_017, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = ""; + OHOS::USB::UsbDevice usbDevice; + printUsbManager.printDeviceMap[printerName] = usbDevice; + bool ret = printUsbManager.ConnectUsbPinter(printerName); + EXPECT_EQ(ret, false); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_018, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = ""; + bool ret = printUsbManager.ConnectUsbPinter(printerName); + EXPECT_EQ(ret, false); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_019, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string printerName = "HW PixLab V1-0105"; + bool ret = printUsbManager.ConnectUsbPinter(printerName); + EXPECT_EQ(ret, false); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_020, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + OHOS::USB::UsbDevice usbDevice; + std::string printerName = "HW PixLab V1-0105"; + printUsbManager.isPrintDevice(usbDevice, printerName); +} + +HWTEST_F(PrintUsbManagerTest, PrintUsbManagerTest_021, TestSize.Level1) +{ + OHOS::Print::PrintUsbManager printUsbManager; + std::string name = ""; + OHOS::USB::USBDevicePipe usbDevicePipe; + OHOS::USB::UsbDevice usbDevice; + bool ret = printUsbManager.AllocateInterface(name, usbDevice, usbDevicePipe); + EXPECT_EQ(false, ret); +} +} // namespace Print +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/service_test/print_user_data_test.cpp b/test/unittest/service_test/print_user_data_test.cpp new file mode 100644 index 0000000..a937c3b --- /dev/null +++ b/test/unittest/service_test/print_user_data_test.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "printer_info.h" +#include "iprint_callback.h" +#define private public +#include "print_user_data.h" +#undef private +#include "print_constant.h" +#include "print_log.h" +#include "mock_print_callback_stub.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Print { + +class PrintUserDataTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PrintUserDataTest::SetUpTestCase(void) {} + +void PrintUserDataTest::TearDownTestCase(void) {} + +void PrintUserDataTest::SetUp(void) +{ + static int32_t testNo = 0; + PRINT_HILOGI("PrintUserDataTest_%{public}d", ++testNo); +} + +void PrintUserDataTest::TearDown(void) {} + +/** + * @tc.name: PrintServiceStubTest_0001 + * @tc.desc: Verify the capability function. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0001, TestSize.Level1) +{ + std::string type = "111"; + sptr listener = nullptr; + auto userData = std::make_shared(); + userData->RegisterPrinterCallback(type, listener); + EXPECT_EQ(userData->registeredListeners_.size(), 1); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0002, TestSize.Level1) +{ + std::string type = "111"; + sptr listener = nullptr; + auto userData = std::make_shared(); + userData->RegisterPrinterCallback(type, listener); + userData->UnregisterPrinterCallback(type); + EXPECT_EQ(userData->registeredListeners_.size(), 0); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0003, TestSize.Level1) +{ + std::string type = "111"; + std::string type2 = "222"; + sptr listener = nullptr; + auto userData = std::make_shared(); + userData->RegisterPrinterCallback(type, listener); + userData->UnregisterPrinterCallback(type2); + EXPECT_EQ(userData->registeredListeners_.size(), 1); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0004, TestSize.Level1) +{ + std::string type = "111"; + sptr listener = nullptr; + PrinterInfo info; + int event = 0; + auto userData = std::make_shared(); + userData->RegisterPrinterCallback(type, listener); + userData->SendPrinterEvent(type, event, info); + EXPECT_EQ(userData->registeredListeners_.size(), 1); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0005, TestSize.Level1) +{ + std::string type = "111"; + std::string type2 = "222"; + sptr listener = nullptr; + PrinterInfo info; + int event = 0; + auto userData = std::make_shared(); + userData->RegisterPrinterCallback(type, listener); + userData->SendPrinterEvent(type2, event, info); + EXPECT_EQ(userData->registeredListeners_.size(), 1); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0006, TestSize.Level1) +{ + std::string type = "111"; + std::string type2 = "222"; + sptr listener = nullptr; + sptr newListener = nullptr; + PrinterInfo info; + int event = 0; + auto userData = std::make_shared(); + userData->RegisterPrinterCallback(type, listener); + userData->RegisterPrinterCallback(type2, newListener); + userData->SendPrinterEvent(type, event, info); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0007, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string jobId = "1"; + PrintJob findPrintJob; + EXPECT_EQ(userData->QueryPrintJobById(jobId, findPrintJob), E_PRINT_INVALID_PRINTJOB); + std::shared_ptr printJob = std::make_shared(); + userData->AddToPrintJobList(jobId, printJob); + EXPECT_EQ(userData->QueryPrintJobById(jobId, findPrintJob), E_PRINT_NONE); + jobId = "2"; + EXPECT_EQ(userData->QueryPrintJobById(jobId, findPrintJob), E_PRINT_INVALID_PRINTJOB); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0008, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string jobOrderId = "0"; + std::string jobId = "1"; + std::shared_ptr printJob = std::make_shared(); + userData->AddToPrintJobList(jobId, printJob); + std::string newJobId = "2"; + userData->UpdateQueuedJobList(newJobId, printJob, jobOrderId); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0009, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string jobOrderId = "0"; + std::string jobId = "1"; + std::shared_ptr printJob = std::make_shared(); + userData->AddToPrintJobList(jobId, printJob); + userData->UpdateQueuedJobList(jobId, printJob, jobOrderId); + std::vector printJobs; + EXPECT_EQ(userData->QueryAllPrintJob(printJobs), E_PRINT_NONE); + printJob = nullptr; + userData->UpdateQueuedJobList(jobId, printJob, jobOrderId); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0010, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string type = "111"; + sptr listener = new (std::nothrow) DummyPrintCallbackStub(); + PrinterInfo info; + int event = 0; + userData->RegisterPrinterCallback(type, listener); + userData->SendPrinterEvent(type, event, info); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0011, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string jobOrderId = "0"; + std::string jobId = "1"; + std::shared_ptr printJob = std::make_shared(); + userData->AddToPrintJobList(jobId, printJob); + userData->UpdateQueuedJobList(jobId, printJob, jobOrderId); + userData->AddToPrintJobList(jobId, printJob); + userData->UpdateQueuedJobList(jobId, printJob, jobOrderId); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0012, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string jobOrderId = "0"; + std::string jobId = "1"; + std::shared_ptr printJob = std::make_shared(); + userData->jobOrderList_.insert(std::make_pair(jobOrderId, jobId)); + std::vector printJobs; + userData->QueryAllPrintJob(printJobs); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0013, TestSize.Level1) +{ + auto userData = std::make_shared(); + int32_t userId = 101; + userData->SetUserId(userId); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0014, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string printerId = "com.ohos.spooler:p2p://DIRECT-HW_PixLab_V1-0105"; + userData->SetLastUsedPrinter(printerId); + std::string printerId2 = ""; + userData->SetLastUsedPrinter(printerId2); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0015, TestSize.Level1) +{ + auto userData = std::make_shared(); + EXPECT_EQ(userData->GetDefaultPrinter(), ""); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0016, TestSize.Level1) +{ + auto userData = std::make_shared(); + userData->ParseUserData(); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0017, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string fileData = ""; + userData->GetFileData(fileData); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0018, TestSize.Level1) +{ + auto userData = std::make_shared(); + userData->SetUserDataToFile(); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0019, TestSize.Level1) +{ + auto userData = std::make_shared(); + EXPECT_EQ(userData->GetLastUsedPrinter(), ""); +} + +HWTEST_F(PrintUserDataTest, PrintUserDataTest_0020, TestSize.Level1) +{ + auto userData = std::make_shared(); + std::string printerId = "com.ohos.spooler:p2p://DIRECT-H_PixLab_V1-0105"; + userData->SetDefaultPrinter(printerId); + std::string printerId2 = ""; + userData->SetDefaultPrinter(printerId2); +} + +} +} \ No newline at end of file diff --git a/utils/include/print_constant.h b/utils/include/print_constant.h index 33a7623..682b0d3 100644 --- a/utils/include/print_constant.h +++ b/utils/include/print_constant.h @@ -25,7 +25,7 @@ namespace OHOS::Print { #define PRINT_CALLBACK_ADAPTER "printCallback_adapter" #define PRINT_GET_FILE_CALLBACK_ADAPTER "getPrintFileCallback_adapter" -#define NEW_PRINT_INTERFACE_SWITCH false +#define NEW_PRINT_INTERFACE_SWITCH true #define PRINT_ASSERT_BASE(env, assertion, message, retVal) \ do { \ @@ -75,6 +75,8 @@ enum PrintErrorCode { E_PRINT_INVALID_PRINTER = 13100005, E_PRINT_INVALID_PRINTJOB = 13100006, E_PRINT_FILE_IO = 13100007, + E_PRINT_INVALID_TOKEN = 13100008, + E_PRINT_INVALID_USERID = 13100009, E_PRINT_UNKNOWN = 13100255, }; @@ -195,7 +197,29 @@ enum PrintPageType { PAGE_INT_DL_ENVELOPE = 10, PAGE_B_TABLOID = 11, }; + +enum ApplicationEvent { + APPLICATION_CREATED = 0, + APPLICATION_CLOSED_FOR_STARTED = 1, + APPLICATION_CLOSED_FOR_CANCELED = 2, +}; + +enum PrinterStatus { + PRINTER_STATUS_IDLE = 0, + PRINTER_STATUS_BUSY = 1, + PRINTER_STATUS_UNAVAILABLE = 2, +}; + +enum PrinterEvent { + PRINTER_EVENT_ADDED = 0, + PRINTER_EVENT_DELETED = 1, + PRINTER_EVENT_STATE_CHANGED = 2, + PRINTER_EVENT_INFO_CHANGED = 3, +}; + const std::string PRINTER_DISCOVER_EVENT_TYPE = "printerDiscover"; const std::string PRINTER_CHANGE_EVENT_TYPE = "printerChange"; +static const std::string PERMISSION_NAME_PRINT = "ohos.permission.PRINT"; +static const std::string PERMISSION_NAME_PRINT_JOB = "ohos.permission.MANAGE_PRINT_JOB"; } // namespace OHOS::Print #endif // PRINT_CONSTANT_H diff --git a/utils/include/print_ipp_over_usb_constant.h b/utils/include/print_ipp_over_usb_constant.h new file mode 100644 index 0000000..9917895 --- /dev/null +++ b/utils/include/print_ipp_over_usb_constant.h @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef IPP_USB_HTTP_CONST_VALUE_H +#define IPP_USB_HTTP_CONST_VALUE_H + +namespace OHOS::Print { +const std::string LOCAL_HOST = "127.0.0.1"; +const std::string HTTP_CONTENT_LENGTH = "Content-Length"; +const std::string HTTP_TRANSFER_ENCODING = "Transfer-Encoding"; +const std::string HTTP_EXPECT = "Expect"; +const std::string HTTP_CHUNKED = "chunked"; +const std::string HTTP_POST = "POST /ipp/print HTTP/1.1\r\n"; +const std::string HTTP_MSG_STRING_R_AND_N = "\r\n"; +const std::string HTTP_MSG_STRING_CHUNK_END = "0\r\n\r\n"; +const std::string HTTP_OPERATION_GET_ATTR = "GetAttr"; +const std::string HTTP_OPERATION_SEND_DOC = "SendDoc"; +const std::string HTTP_OPERATION_COMMON = "Common"; +const std::string PRINTER_ID_PREFIX = "USB-"; +const std::string HTTP_100_CONTINUE = "HTTP/1.1 100"; + +const int HTTP_REQUEST_GET_ATTR = 11; +const int HTTP_REQUEST_SEND_DOC = 6; + +const int HTTP_RESPONSE_STATUS_100 = 100; +const int HTTP_RESPONSE_STATUS_101 = 101; +const int HTTP_RESPONSE_STATUS_102 = 102; +const int HTTP_RESPONSE_STATUS_103 = 103; +const int HTTP_RESPONSE_STATUS_200 = 200; +const int HTTP_RESPONSE_STATUS_201 = 201; +const int HTTP_RESPONSE_STATUS_202 = 202; +const int HTTP_RESPONSE_STATUS_203 = 203; +const int HTTP_RESPONSE_STATUS_204 = 204; +const int HTTP_RESPONSE_STATUS_205 = 205; +const int HTTP_RESPONSE_STATUS_206 = 206; +const int HTTP_RESPONSE_STATUS_207 = 207; +const int HTTP_RESPONSE_STATUS_208 = 208; +const int HTTP_RESPONSE_STATUS_226 = 226; +const int HTTP_RESPONSE_STATUS_300 = 300; +const int HTTP_RESPONSE_STATUS_301 = 301; +const int HTTP_RESPONSE_STATUS_302 = 302; +const int HTTP_RESPONSE_STATUS_303 = 303; +const int HTTP_RESPONSE_STATUS_304 = 304; +const int HTTP_RESPONSE_STATUS_305 = 305; +const int HTTP_RESPONSE_STATUS_306 = 306; +const int HTTP_RESPONSE_STATUS_307 = 307; +const int HTTP_RESPONSE_STATUS_308 = 308; +const int HTTP_RESPONSE_STATUS_400 = 400; +const int HTTP_RESPONSE_STATUS_401 = 401; +const int HTTP_RESPONSE_STATUS_402 = 402; +const int HTTP_RESPONSE_STATUS_403 = 403; +const int HTTP_RESPONSE_STATUS_404 = 404; +const int HTTP_RESPONSE_STATUS_405 = 405; +const int HTTP_RESPONSE_STATUS_406 = 406; +const int HTTP_RESPONSE_STATUS_407 = 407; +const int HTTP_RESPONSE_STATUS_408 = 408; +const int HTTP_RESPONSE_STATUS_409 = 409; +const int HTTP_RESPONSE_STATUS_410 = 410; +const int HTTP_RESPONSE_STATUS_411 = 411; +const int HTTP_RESPONSE_STATUS_412 = 412; +const int HTTP_RESPONSE_STATUS_413 = 413; +const int HTTP_RESPONSE_STATUS_414 = 414; +const int HTTP_RESPONSE_STATUS_415 = 415; +const int HTTP_RESPONSE_STATUS_416 = 416; +const int HTTP_RESPONSE_STATUS_417 = 417; +const int HTTP_RESPONSE_STATUS_418 = 418; +const int HTTP_RESPONSE_STATUS_421 = 421; +const int HTTP_RESPONSE_STATUS_422 = 422; +const int HTTP_RESPONSE_STATUS_423 = 423; +const int HTTP_RESPONSE_STATUS_424 = 424; +const int HTTP_RESPONSE_STATUS_425 = 425; +const int HTTP_RESPONSE_STATUS_426 = 426; +const int HTTP_RESPONSE_STATUS_428 = 428; +const int HTTP_RESPONSE_STATUS_429 = 429; +const int HTTP_RESPONSE_STATUS_431 = 431; +const int HTTP_RESPONSE_STATUS_451 = 451; +const int HTTP_RESPONSE_STATUS_501 = 501; +const int HTTP_RESPONSE_STATUS_502 = 502; +const int HTTP_RESPONSE_STATUS_503 = 503; +const int HTTP_RESPONSE_STATUS_504 = 504; +const int HTTP_RESPONSE_STATUS_505 = 505; +const int HTTP_RESPONSE_STATUS_506 = 506; +const int HTTP_RESPONSE_STATUS_507 = 507; +const int HTTP_RESPONSE_STATUS_508 = 508; +const int HTTP_RESPONSE_STATUS_510 = 510; +const int HTTP_RESPONSE_STATUS_511 = 511; +const int HTTP_RESPONSE_STATUS_500 = 500; + +const int HTTP_COMMON_CONST_VALUE_0 = 0; +const int HTTP_COMMON_CONST_VALUE_1 = 1; +const int HTTP_COMMON_CONST_VALUE_2 = 2; +const int HTTP_COMMON_CONST_VALUE_3 = 3; +const int HTTP_COMMON_CONST_VALUE_4 = 4; +const int HTTP_COMMON_CONST_VALUE_5 = 5; +const int HTTP_COMMON_CONST_VALUE_6 = 6; +const int HTTP_COMMON_CONST_VALUE_8 = 8; +const int HTTP_COMMON_CONST_VALUE_9 = 9; +const int HTTP_COMMON_CONST_VALUE_10 = 10; +const int HTTP_COMMON_CONST_VALUE_11 = 11; +const int HTTP_COMMON_CONST_VALUE_12 = 12; +const int HTTP_COMMON_CONST_VALUE_14 = 14; +const int HTTP_COMMON_CONST_VALUE_15 = 15; +const int HTTP_COMMON_CONST_VALUE_16 = 16; +const int HTTP_COMMON_CONST_VALUE_18 = 18; +const int HTTP_COMMON_CONST_VALUE_25 = 25; +const int HTTP_COMMON_CONST_VALUE_31 = 31; +const int HTTP_COMMON_CONST_VALUE_33 = 33; +const int HTTP_COMMON_CONST_VALUE_47 = 47; +const int HTTP_COMMON_CONST_VALUE_50 = 50; +const int HTTP_COMMON_CONST_VALUE_100 = 100; +const int HTTP_COMMON_CONST_VALUE_300 = 300; +const int HTTP_COMMON_CONST_VALUE_500 = 500; +const int HTTP_COMMON_CONST_VALUE_1000 = 1000; + +const int INDEX_0 = 0; +const int INDEX_1 = 1; +const int INDEX_2 = 2; +const int INDEX_3 = 3; +const int INDEX_4 = 4; +const int INDEX_5 = 5; +const int INDEX_6 = 6; +const int INDEX_7 = 7; +const int INDEX_8 = 8; +const int INDEX_9 = 9; +const int INDEX_10 = 10; +const int INDEX_11 = 11; + +const size_t HTTP_SERVER_MAX_LENGTH = 1024 * 1024 * 512; +const int HTTP_MIN_PORT = 60000; +const int HTTP_MAX_PORT = 65535; +const int HTTP_SERVER_LISTEN_PORT = 60000; +const size_t USB_DATA_MAX_LENGTH = 1024 * 16; +const size_t USB_ENDPOINT_MAX_LENGTH = 512; +const int USB_INTERFACE_MIN_COUNT = 2; +const int INVAILD_VALUE = -1; +const int RESPONSE_RETRY_MAX_TIMES = 300; +const int READ_RETRY_MAX_TIMES = 200; +const int RESPONSE_RETRY_INTERVAL = 100; +const int USB_BULKTRANSFER_WRITE_TIMEOUT = 500; +const int USB_BULKTRANSFER_WRITE_SLEEP = 1000; +const int WRITE_RETRY_MAX_TIMES = 20; +const int USB_BULKTRANSFER_READ_TIMEOUT = 500; +const int USB_READ_INTERVAL = 50; +const int USB_WRITE_INTERVAL = 50; +const int CPP_HTTP_OK = 1; +const int CPP_HTTP_FAIL = 0; +const int REQID_OPERAID_LEN = 8; + +const char HTTP_MSG_CHAR_1 = '1'; +const char HTTP_MSG_CHAR_2E = '.'; +const char HTTP_MSG_CHAR_A = 'A'; +const char HTTP_MSG_CHAR_0 = '0'; +const char HTTP_MSG_CHAR_A_S = 'a'; +const char HTTP_MSG_CHAR_F_S = 'f'; +const char HTTP_MSG_CHAR_F = 'F'; +const char HTTP_MSG_CHAR_R0 = '\0'; +const char HTTP_MSG_CHAR_20 = ' '; +const char HTTP_MSG_CHAR_2B = '+'; +const char HTTP_MSG_CHAR_0D = '\r'; +const char HTTP_MSG_CHAR_0A = '\n'; +const char HTTP_MSG_CHAR_27 = '\''; +const char HTTP_MSG_CHAR_2C = ','; +const char HTTP_MSG_CHAR_3B = ';'; +const char HTTP_MSG_CHAR_BAI_FEN = '%'; +const char SPLIT_VALUE_COLON = ':'; + +const uint8_t HTTP_SPLIT_R_CODE = 13; // '\r' +const uint8_t HTTP_SPLIT_N_CODE = 10; // '\n' +const uint8_t CODE_SPLIT_VALUE_COLON = 58; // ':' 冒号分隔符 +const uint8_t IPP_END_SPLIT_VALUE = 3; // ipp协议分割符号 +const uint8_t HTTP_RESPONSE_H = 72; // 'H' +const uint8_t HTTP_RESPONSE_T = 84; // 'T' +const uint8_t HTTP_RESPONSE_P = 80; // 'P' +const uint8_t HTTP_RESPONSE_VERSION_SPLIT_GANG = 47; // '/' +const int32_t USB_DEVICE_CLASS_PRINT = 7; // class is 7 the device is printer +const int32_t USB_DEVICE_SUBCLASS_PRINT = 1; // subclass is 1 the device is printer +const int32_t USB_DEVICE_PROTOCOL_PRINT = 4; // can support ipp usb +const int32_t USB_DEVICE_INTERFACE_COUNT = 2; // can support ipp usb +const int32_t EORROR_HDF_DEV_ERR_TIME_OUT = -7; +const int32_t EORROR_HDF_DEV_ERR_NO_DEVICE = -202; +const uint8_t USB_REQUESTTYPE_HOST_TO_DEVICE = 0X00; +const uint8_t USB_REQUESTTYPE_DEVICE_TO_HOST = 0X80; +const uint8_t USB_REQUEST_SET_CONFIGURATION = 0X09; +const uint8_t USB_REQUEST_GET_DESCRIPTOR = 0X06; +const uint16_t USB_VALUE_DESCRIPTOR_TYPE_STRING = 0X03; +const uint16_t USB_VALUE_DESCRIPTOR_INDEX_PRODUCT_NAME = 0X02; +const uint16_t USB_VALUE_DESCRIPTOR_INDEX_SERIAL_NUMBER = 0X03; +const uint16_t USB_INDEX_0 = 0X00; +const uint16_t USB_INDEX_LANGUAGE_ID_ENGLISH = 0X409; +} +#endif \ No newline at end of file diff --git a/utils/include/print_ipp_over_usb_util.h b/utils/include/print_ipp_over_usb_util.h new file mode 100644 index 0000000..3cbda42 --- /dev/null +++ b/utils/include/print_ipp_over_usb_util.h @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_IPP_OVER_USB__UTIL_H +#define PRINT_IPP_OVER_USB__UTIL_H +#include +#include +#include +#include "httplib.h" +#include "print_log.h" +#include "print_ipp_over_usb_constant.h" + +#define TAG "HttpUSB" + +namespace OHOS::Print { +using namespace httplib; + +class PrintIppOverUsbUtil { +public: + static std::string Uint8ToHexString(const uint8_t *v, const size_t s); + + static std::string IntToHexString(unsigned int v); + + static void TrimString(std::string &s); + + static bool IsStartWithHttpHeader(uint8_t *data, size_t length); + + static bool IsEndWithHttpResponse(uint8_t *data, size_t length); + + static void MakeHeader(size_t startLine, size_t endline, const uint8_t *data, httplib::Response &httpResponse); + + static void DumpRespCode(const uint8_t *data, size_t dataLength, size_t start, size_t dumpLength); + + static int ConstructHttpResponse(const uint8_t *v, const size_t length, httplib::Response &httpResponse); +}; + +inline std::string PrintIppOverUsbUtil::Uint8ToHexString(const uint8_t *v, const size_t s) +{ + std::stringstream ss; + ss << std::hex << std::setfill('0'); + for (size_t i = 0; i < s; i++) { + ss << std::hex << std::setw(HTTP_COMMON_CONST_VALUE_2) << static_cast(v[i]) << " "; + } + return ss.str(); +} + +inline std::string PrintIppOverUsbUtil::IntToHexString(unsigned int v) +{ + std::stringstream ss; + ss << std::hex << v; + std::string temp; + ss >> temp; + return temp; +} + +inline void PrintIppOverUsbUtil::TrimString(std::string &s) +{ + if (!s.empty()) { + s.erase(0, s.find_first_not_of(" ")); + s.erase(s.find_last_not_of(" ") + 1); + } +} + +inline bool PrintIppOverUsbUtil::IsStartWithHttpHeader(uint8_t *data, size_t length) +{ // 是一段http报文的开头 + if (length > HTTP_COMMON_CONST_VALUE_5 && data[INDEX_0] == HTTP_RESPONSE_H && + data[INDEX_1] == HTTP_RESPONSE_T && data[INDEX_2] == HTTP_RESPONSE_T && + data[INDEX_3] == HTTP_RESPONSE_P && + data[INDEX_4] == HTTP_RESPONSE_VERSION_SPLIT_GANG) { + return true; + } + return false; +} + +inline bool PrintIppOverUsbUtil::IsEndWithHttpResponse(uint8_t *data, size_t length) +{ // 是一段http报文的结尾 + if (data[INDEX_0] == IPP_END_SPLIT_VALUE && length == HTTP_COMMON_CONST_VALUE_1) { + return true; + } else if (length > HTTP_COMMON_CONST_VALUE_6 && data[INDEX_1] == HTTP_RESPONSE_H && + data[INDEX_2] == HTTP_RESPONSE_T && data[INDEX_3] == HTTP_RESPONSE_T && + data[INDEX_4] == HTTP_RESPONSE_P && + data[INDEX_5] == HTTP_RESPONSE_VERSION_SPLIT_GANG) { + return true; + } else { + return false; + } +} + +void PrintIppOverUsbUtil::MakeHeader(size_t startLine, size_t endline, const uint8_t *data, + httplib::Response &httpResponse) +{ + // 提取key和value + size_t theSplitIndex = startLine; // ":" 所在的位置 + while (data[theSplitIndex] != CODE_SPLIT_VALUE_COLON && theSplitIndex < endline) { + theSplitIndex++; + } + std::string keyString; + std::string valueString; + for (size_t i = startLine; i < theSplitIndex; i++) { + keyString += data[i]; + } + for (size_t i = theSplitIndex + 1; i <= endline; i++) { + valueString += data[i]; + } + TrimString(keyString); + TrimString(valueString); + PRINT_HILOGD("keyString :%{public}s, valueString :%{public}s", keyString.c_str(), valueString.c_str()); + if (HTTP_CONTENT_LENGTH != keyString) { + httpResponse.set_header(keyString, valueString); + } +} + +inline void PrintIppOverUsbUtil::DumpRespCode(const uint8_t *data, size_t dataLength, size_t start, size_t dumpLength) +{ + for (size_t i = start; i < dataLength && i < (start + dumpLength); i++) { + PRINT_HILOGE("Resp :%{public}x", data[i]); + } +} + +int PrintIppOverUsbUtil::ConstructHttpResponse(const uint8_t *readBuf, const size_t length, + httplib::Response &httpResponse) +{ + PRINT_HILOGD("start construct_http_response length :%{public}lu", length); + if (length <= HTTP_COMMON_CONST_VALUE_6) { + return INVAILD_VALUE; + } + const uint8_t *bufTmp = readBuf; + size_t index = 0; + size_t startline = index; + size_t endline = index; + while (index < length - INDEX_3) { + bool isHeaerEnd = (bufTmp[index] == HTTP_SPLIT_R_CODE && bufTmp[index + INDEX_1] == HTTP_SPLIT_N_CODE && + bufTmp[index + INDEX_2] == HTTP_SPLIT_R_CODE && + bufTmp[index + INDEX_3] == HTTP_SPLIT_N_CODE); + if (isHeaerEnd) { + break; + } + bool isLineBegin = (index > INDEX_2 && bufTmp[index - INDEX_2] == HTTP_SPLIT_R_CODE && + bufTmp[index - INDEX_1] == HTTP_SPLIT_N_CODE); + if (isLineBegin) { // 识别出一行的第一个字符 + startline = index; + endline = startline; + // 识别出一行的行尾 + while (!(bufTmp[endline + INDEX_1] == HTTP_SPLIT_R_CODE && + bufTmp[endline + INDEX_2] == HTTP_SPLIT_N_CODE)) { + endline++; + } + MakeHeader(startline, endline, readBuf, httpResponse); + index++; + } else { + index++; + } + } + DumpRespCode(bufTmp, length, index + HTTP_COMMON_CONST_VALUE_4, HTTP_COMMON_CONST_VALUE_8); + if (index < length - HTTP_COMMON_CONST_VALUE_4) { + httpResponse.version = "1.1"; + httpResponse.status = HTTP_RESPONSE_STATUS_200; + httpResponse.reason = "OK"; + std::string body; + index = index + HTTP_COMMON_CONST_VALUE_4; + while (index < length) { + body += bufTmp[index]; + index++; + } + httpResponse.body = body; + return 0; + } else { + return INVAILD_VALUE; + } +} +} +#endif // PRINT_IPP_OVER_USB__UTIL_H \ No newline at end of file diff --git a/utils/include/print_log.h b/utils/include/print_log.h index 35cf2b9..b1d0476 100644 --- a/utils/include/print_log.h +++ b/utils/include/print_log.h @@ -42,28 +42,27 @@ #define PRINT_LOG_TAG "printkit" #define PRINT_LOG_DOMAIN 0xD001C00 -static constexpr OHOS::HiviewDFX::HiLogLabel PRINT_LOG_LABEL = {LOG_CORE, PRINT_LOG_DOMAIN, PRINT_LOG_TAG}; #define MAKE_FILE_NAME (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) #define PRINT_HILOGF(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Fatal(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \ + (void)HILOG_IMPL(LOG_CORE, LOG_FATAL, PRINT_LOG_DOMAIN, PRINT_LOG_TAG, "[%{public}s %{public}s %{public}d] " fmt, \ MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__) #define PRINT_HILOGE(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Error(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \ + (void)HILOG_IMPL(LOG_CORE, LOG_ERROR, PRINT_LOG_DOMAIN, PRINT_LOG_TAG, "[%{public}s %{public}s %{public}d] " fmt, \ MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__) #define PRINT_HILOGW(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Warn(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \ + (void)HILOG_IMPL(LOG_CORE, LOG_WARN, PRINT_LOG_DOMAIN, PRINT_LOG_TAG, "[%{public}s %{public}s %{public}d] " fmt, \ MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__) #define PRINT_HILOGD(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Debug(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \ + (void)HILOG_IMPL(LOG_CORE, LOG_DEBUG, PRINT_LOG_DOMAIN, PRINT_LOG_TAG, "[%{public}s %{public}s %{public}d] " fmt, \ MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__) #define PRINT_HILOGI(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Info(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \ + (void)HILOG_IMPL(LOG_CORE, LOG_INFO, PRINT_LOG_DOMAIN, PRINT_LOG_TAG, "[%{public}s %{public}s %{public}d] " fmt, \ MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__) #else diff --git a/utils/include/print_util.h b/utils/include/print_util.h index af8b7e2..1b93e2d 100644 --- a/utils/include/print_util.h +++ b/utils/include/print_util.h @@ -28,6 +28,7 @@ namespace OHOS::Print { const uint32_t MAX_PRINTER_NAME_LENGTH = 127; +const uint32_t MIN_INT_LIST_STRLENGTH = 2; class PrintUtil { public: static std::string ParseListToString(const std::vector &list); @@ -39,8 +40,41 @@ public: static bool CheckContains(const std::string& str, const std::string& content); static std::string StandardizePrinterName(std::string printerName); + + static std::vector Str2Vec(std::string str); + + static void Str2VecStr(std::string& str, std::vector& vec); }; +inline std::vector PrintUtil::Str2Vec(std::string str) +{ + if (str.size() < MIN_INT_LIST_STRLENGTH) { + return {}; + } + str.pop_back(); + str.erase(str.begin()); + std::vector vec; + std::istringstream is(str); + std::string temp; + while (getline(is, temp, ',')) { + vec.push_back(stoi(temp)); + } + return vec; +} + +inline void PrintUtil::Str2VecStr(std::string& str, std::vector& vec) +{ + if (!str.empty()) { + str.pop_back(); + str.erase(str.begin()); + std::istringstream is(str); + std::string temp; + while (getline(is, temp, ',')) { + vec.push_back(temp); + } + } +} + inline std::string PrintUtil::ParseListToString(const std::vector &list) { std::string str;