sync print code

Signed-off-by: 张凯 <zhangkai357@huawei.com>
This commit is contained in:
张凯 2024-06-12 10:22:21 +08:00
parent ffe8d99242
commit 05763567dc
144 changed files with 17610 additions and 1665 deletions

View File

@ -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"
]
}
}

1
cfi_blocklist.txt Normal file
View File

@ -0,0 +1 @@
src:*/base/print/print_fwk/test/unittest/*

View File

@ -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"
]
}
]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -29,6 +29,16 @@ ohos_shared_library("print_helper") {
]
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_print_utils.cpp",
"src/print_attributes_helper.cpp",
@ -57,10 +67,6 @@ ohos_shared_library("print_helper") {
"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",
]

View File

@ -17,9 +17,11 @@
#define NAPI_PRINT_UTILS_H
#include <string>
#include <map>
#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<napi_property_descriptor> &properties);
static size_t GetJsVal(napi_env env, napi_callback_info info, napi_value argv[], size_t length);
static bool VerifyProperty(std::vector<std::string> &names, std::map<std::string, PrintParamStatus> &propertyList);
};
} // namespace OHOS::Print
#endif // NAPI_PRINT_UTILS_H

View File

@ -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<std::string> &names, std::map<std::string, PrintParamStatus> &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

View File

@ -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);
}
}

View File

@ -149,11 +149,6 @@ std::shared_ptr<PrintJob> PrintJobHelper::BuildFromJs(napi_env env, napi_value j
std::shared_ptr<PrintJob> PrintJobHelper::BuildJsWorkerIsLegal(napi_env env, napi_value jsValue, std::string jobId,
uint32_t jobState, uint32_t subState, std::shared_ptr<PrintJob> &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);
}
}

View File

@ -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

View File

@ -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

View File

@ -43,6 +43,10 @@ std::shared_ptr<PrintResolution> 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

View File

@ -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

View File

@ -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

View File

@ -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",
]

View File

@ -28,6 +28,7 @@ public:
std::function<void(std::string, uint32_t)> writeResultCallback);
virtual void onJobStateChanged(const std::string &jobId, uint32_t state);
virtual ~PrintDocumentAdapter() {};
};
}
#endif // PRINT_FWK_IPRINT_ADAPTER_H

View File

@ -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

View File

@ -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<std::string> &fileList,
const std::vector<uint32_t> &fdList, std::string &taskId) = 0;
virtual int32_t StartPrint(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &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<std::string> &extensionList) = 0;
virtual int32_t StopDiscoverPrinter() = 0;
virtual int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &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<PrinterInfo> &printerInfos) = 0;
virtual int32_t RemovePrinters(const std::vector<std::string> &printerIds) = 0;
virtual int32_t UpdatePrinters(const std::vector<PrinterInfo> &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<IPrintCallback> &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<IPrintCallback> &listener) = 0;
virtual int32_t UnregisterPrinterCallback(const std::string &type) = 0;
virtual int32_t RegisterExtCallback(const std::string &extensionCID,
const sptr<IPrintExtensionCallback> &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<IRemoteObject> &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<std::string> &printerNameList) = 0;
virtual int32_t QueryPrinterProperties(const std::string &printerId, const std::vector<std::string> &keyList,
std::vector<std::string> &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

View File

@ -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<void(CallbackParam*)> 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

View File

@ -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 <string>
#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

View File

@ -20,6 +20,7 @@
#include <map>
#include <mutex>
#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<std::string> &fileList,
const std::vector<uint32_t> &fdList, std::string &taskId);
int32_t StopPrint(const std::string &taskId);
int32_t StartPrint(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &token);
int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos);
int32_t StartDiscoverPrinter(const std::vector<std::string> &extensionList);
int32_t StopDiscoverPrinter();
@ -57,10 +56,10 @@ public:
int32_t UpdatePrinters(const std::vector<PrinterInfo> &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<std::string> &printerNameList);
int32_t QueryPrinterProperties(const std::string &printerId, const std::vector<std::string> &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<int32_t(sptr<IPrintService>)> func);

View File

@ -25,28 +25,29 @@ public:
explicit PrintServiceProxy(const sptr<IRemoteObject> &object);
~PrintServiceProxy() = default;
DISALLOW_COPY_AND_MOVE(PrintServiceProxy);
virtual int32_t StartService() override;
int32_t StartPrint(const std::vector<std::string> &fileList,
const std::vector<uint32_t> &fdList, std::string &taskId) override;
int32_t StopPrint(const std::string &taskId) override;
int32_t StartPrint(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &token) override;
int32_t ConnectPrinter(const std::string &printerId) override;
int32_t DisconnectPrinter(const std::string &printerId) override;
int32_t StartDiscoverPrinter(const std::vector<std::string> &extensionList) override;
int32_t StopDiscoverPrinter() override;
int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &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<PrinterInfo> &printerInfos) override;
int32_t RemovePrinters(const std::vector<std::string> &printerIds) override;
int32_t UpdatePrinters(const std::vector<PrinterInfo> &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<IPrintCallback> &listener) override;
int32_t Off(const std::string taskId, const std::string &type) override;
int32_t RegisterPrinterCallback(const std::string &type, const sptr<IPrintCallback> &listener) override;
int32_t UnregisterPrinterCallback(const std::string &type) override;
int32_t RegisterExtCallback(const std::string &extensionCID,
const sptr<IPrintExtensionCallback> &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<IRemoteObject> &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<std::string> &printerNameList) override;
int32_t QueryPrinterProperties(const std::string &printerId, const std::vector<std::string> &keyList,
std::vector<std::string> &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<PrintServiceProxy> delegator_;

View File

@ -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<std::mutex> autoLock(mutex_);
PRINT_HILOGD("callback has been destroyed");
@ -51,7 +54,7 @@ PrintCallback::~PrintCallback()
return;
}
work->data = reinterpret_cast<void*>(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<Param*>(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<void(CallbackParam*)> 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<std::mutex> lock(mutex_);
@ -352,7 +363,13 @@ bool PrintCallback::onBaseCallback(std::function<void(CallbackParam*)> 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);
}
}

View File

@ -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

View File

@ -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> PrintManagerClient::instance_ = nullptr;
@ -109,18 +117,6 @@ int32_t PrintManagerClient::StartPrint(const std::vector<std::string> &fileList,
return ret;
}
int32_t PrintManagerClient::StartPrint(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &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<std::string> &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<IPrintCallback> &listener)
{
PRINT_HILOGD("PrintManagerClient On start.");
@ -461,16 +498,71 @@ int32_t PrintManagerClient::Print(const std::string &printJobName, const sptr<IP
}
int32_t PrintManagerClient::Print(const std::string &printJobName, const sptr<IPrintCallback> &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<IPrintService> 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> adapterParam = std::make_shared<AdapterParam>();
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<OHOS::Ace::UIContent *>(uiContent);
auto callback = std::make_shared<PrintInnerkitModalUICallback>(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<IPrintService> serviceProxy) {
serviceProxy->On("", PRINT_CALLBACK_ADAPTER, listener);
sptr<IRemoteObject> token = static_cast<IRemoteObject*>(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<std::string> 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<int32_t>(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<uint8_t> EncodePng(pdfium::span<const uint8_t> input, int height, int width, int format, int stride)
{
std::vector<uint8_t> 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<uint8_t *>(buffer), stride * height);
std::vector<uint8_t> 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<uint32_t>(FPDF_GetPageWidth(page) * SCALING_RATE);
height = static_cast<uint32_t>(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<uint32_t>(FPDF_GetPageWidth(page) * SCALING_RATE);
uint32_t height = static_cast<uint32_t>(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<int32_t(sptr<IPrintService>)> 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<PrintCallback> 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;

View File

@ -36,42 +36,26 @@ int32_t PrintServiceProxy::GetResult(int retCode, MessageParcel &reply)
return retCode;
}
int32_t PrintServiceProxy::StartPrint(const std::vector<std::string> &fileList,
const std::vector<uint32_t> &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<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &token)
int32_t PrintServiceProxy::StartPrint(const std::vector<std::string> &fileList,
const std::vector<uint32_t> &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<std::string> &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<std::string> &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<PrintExtensionInfo> &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<PrintExtensionInfo> &ex
int32_t PrintServiceProxy::StartDiscoverPrinter(const std::vector<std::string> &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<std::string> &
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<PrinterInfo> &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<PrinterInfo> &printerIn
int32_t PrintServiceProxy::RemovePrinters(const std::vector<std::string> &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<std::string> &printe
int32_t PrintServiceProxy::UpdatePrinters(const std::vector<PrinterInfo> &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<PrinterInfo> &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<std::string> &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<std::string> &keyList, std::vector<std::string> &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<PrintJob> &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<PrintJob> &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<IPrintCallback> &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<IPrintCallback> &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<IPrintExtensionCallback> &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<IRemoteObject> &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);

View File

@ -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"

View File

@ -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");
});
}

View File

@ -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",
]

View File

@ -17,127 +17,10 @@
#define PRINT_PAGESIZE_H
#include <map>
#include <mutex>
#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<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> pageSize_;
static std::mutex pageSizeMapMutex;
};
} // namespace OHOS::Print
#endif // PRINT_PAGESIZE_H

View File

@ -17,8 +17,21 @@
#define PRINT_UTILS_H
#include <string>
#include "want.h"
#include "bundle_mgr_client.h"
#include <nlohmann/json.hpp>
#include <mutex>
#include <print_attributes.h>
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> &adapterParam, AAFwk::Want &want);
static void BuildPrintAttributesParam(const std::shared_ptr<AdapterParam> &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

View File

@ -21,6 +21,7 @@
#include "print_margin.h"
#include "print_page_size.h"
#include "print_resolution.h"
#include <nlohmann/json.hpp>
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<std::string, std::string> printerAttr_group;
};
} // namespace OHOS::Print
#endif // PRINTER_CAPABILITY_H

View File

@ -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<PrinterInfo> 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

View File

@ -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());

View File

@ -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());

View File

@ -16,14 +16,176 @@
#include "print_page_size.h"
#include "print_log.h"
namespace OHOS::Print {
std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> PrintPageSize::pageSize_;
void PrintPageSize::BuildPageSizeMap()
{
PRINT_HILOGD("");
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<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> PrintPageSize::pageSize_;
std::mutex PrintPageSize::pageSizeMapMutex;
void UpdatePageSizeMapIso(std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>>& pageSizeMap)
{
pageSizeMap["ISO_A0"] =
std::make_shared<PrintPageSize>("ISO_A0", "iso_a0_841x1189mm", ISO_A0_WIDTH, ISO_A0_HEIGHT);
pageSizeMap["ISO_A1"] =
std::make_shared<PrintPageSize>("ISO_A1", "iso_a1_594x841mm", ISO_A1_WIDTH, ISO_A1_HEIGHT);
pageSizeMap["ISO_A2"] =
std::make_shared<PrintPageSize>("ISO_A2", "iso_a2_420x594mm", ISO_A2_WIDTH, ISO_A2_HEIGHT);
pageSizeMap["ISO_A3"] =
std::make_shared<PrintPageSize>("ISO_A3", "iso_a3_297x420mm", ISO_A3_WIDTH, ISO_A3_HEIGHT);
pageSizeMap["ISO_A4"] =
std::make_shared<PrintPageSize>("ISO_A4", "iso_a4_210x297mm", ISO_A4_WIDTH, ISO_A4_HEIGHT);
pageSizeMap["ISO_A5"] =
std::make_shared<PrintPageSize>("ISO_A5", "iso_a5_148x210mm", ISO_A5_WIDTH, ISO_A5_HEIGHT);
pageSizeMap["ISO_A6"] =
std::make_shared<PrintPageSize>("ISO_A6", "iso_a6_105x148mm", ISO_A6_WIDTH, ISO_A6_HEIGHT);
pageSizeMap["ISO_B0"] =
std::make_shared<PrintPageSize>("ISO_B0", "iso_b0_1000x1414mm", ISO_B0_WIDTH, ISO_B0_HEIGHT);
pageSizeMap["ISO_B1"] =
std::make_shared<PrintPageSize>("ISO_B1", "iso_b1_707x1000mm", ISO_B1_WIDTH, ISO_B1_HEIGHT);
pageSizeMap["ISO_B2"] =
std::make_shared<PrintPageSize>("ISO_B2", "iso_b2_500x707mm", ISO_B2_WIDTH, ISO_B2_HEIGHT);
pageSizeMap["ISO_B3"] =
std::make_shared<PrintPageSize>("ISO_B3", "iso_b3_353x500mm", ISO_B3_WIDTH, ISO_B3_HEIGHT);
pageSizeMap["ISO_B4"] =
std::make_shared<PrintPageSize>("ISO_B4", "iso_b4_250x353mm", ISO_B4_WIDTH, ISO_B4_HEIGHT);
pageSizeMap["ISO_B5"] =
std::make_shared<PrintPageSize>("ISO_B5", "iso_b5_176x250mm", ISO_B5_WIDTH, ISO_B5_HEIGHT);
pageSizeMap["ISO_C5"] =
std::make_shared<PrintPageSize>("ISO_C5", "iso_c5_162x229mm", ISO_C5_WIDTH, ISO_C5_HEIGHT);
pageSizeMap["ISO_DL"] =
std::make_shared<PrintPageSize>("ISO_DL", "iso_dl_110x220mm", ISO_DL_WIDTH, ISO_DL_HEIGHT);
}
void PrintPageSize::BuildPageSizeMap()
{
UpdatePageSizeMapIso(pageSize_);
pageSize_["NA_LEGAL"] =
std::make_shared<PrintPageSize>("NA_LEGAL", "na_legal_8.5x14in", LEGAL_WIDTH, LEGAL_HEIGHT);
pageSize_["NA_LETTER"] =
std::make_shared<PrintPageSize>("NA_LETTER", "na_letter_8.5x11in", LETTER_WIDTH, LETTER_HEIGHT);
pageSize_["JIS_B5"] =
std::make_shared<PrintPageSize>("JIS_B5", "jis_b5_182x257mm", JIS_B5_WIDTH, JIS_B5_HEIGHT);
pageSize_["JIS_B4"] =
std::make_shared<PrintPageSize>("JIS_B4", "jis_b4_257x364mm", JIS_B4_WIDTH, JIS_B4_HEIGHT);
pageSize_["NA_INDEX_5X7"] =
std::make_shared<PrintPageSize>("NA_INDEX_5X7", "na_5x7_5x7in", PHOTO_5R_WIDTH, PHOTO_5R_HEIGHT);
pageSize_["NA_INDEX_4X6"] =
std::make_shared<PrintPageSize>("NA_INDEX_4X6", "na_index-4x6_4x6in", PHOTO_4R_WIDTH, PHOTO_4R_HEIGHT);
pageSize_["NA_GOVT_LETTER"] = std::make_shared<PrintPageSize>(
"NA_GOVT_LETTER", "na_govt-letter_8x10in", NA_GOVT_LETTER_8IN_WIDTH, NA_GOVT_LETTER_8IN_HEIGHT);
pageSize_["NA_LEDGER"] = std::make_shared<PrintPageSize>(
"NA_LEDGER", "na_ledger_11x17in", NA_LEDGER_11IN_WIDTH, NA_LEDGER_11IN_HEIGHT);
pageSize_["JPN_HAGAKI"] = std::make_shared<PrintPageSize>(
"JPN_HAGAKI", "jpn_hagaki_100x148mm", JPN_HAGAKI_WIDTH, JPN_HAGAKI_HEIGHT);
pageSize_["OM_DSC_PHOTO"] = std::make_shared<PrintPageSize>(
"OM_DSC_PHOTO", "om_dsc-photo_89x119mm", OM_SDC_PHOTO_WIDTH, OM_SDC_PHOTO_HEIGHT);
pageSize_["OM_CARD"] = std::make_shared<PrintPageSize>(
"OM_CARD", "om_card_54x86mm", OM_CARD_WIDTH, OM_CARD_HEIGHT);
pageSize_["OE_PHOTO_L"] = std::make_shared<PrintPageSize>(
"OE_PHOTO_L", "oe_photo-l_3.5x5in", OE_PHOTO_L_WIDTH, OE_PHOTO_L_HEIGHT);
pageSize_["NA_TABLOID"] = std::make_shared<PrintPageSize>(
"NA_TABLOID", "B_TABLOID", B_TABLOID_L_WIDTH, B_TABLOID_L_HEIGHT);
pageSize_["ROC_16K"] = std::make_shared<PrintPageSize>(
"ROC_16K", "roc_16k_7.75x10.75in", ROC_16K_WIDTH, ROC_16K_HEIGHT);
pageSize_["ROC_8K"] = std::make_shared<PrintPageSize>(
"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<std::mutex> 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<std::mutex> 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("");

View File

@ -20,12 +20,29 @@
#include "print_constant.h"
#include "print_log.h"
#include "securec.h"
#include <chrono>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include <random>
#include <ctime>
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<uint32_t, std::string> 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> &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> &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<uint32_t> 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<std::mutex> autoLock(instanceLock_);
auto nowTime = std::chrono::system_clock::now();
auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(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

View File

@ -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

View File

@ -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
} // namespace OHOS::Print

View File

@ -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",
]

View File

@ -26,22 +26,6 @@
using json = nlohmann::json;
namespace OHOS::Print {
static std::vector<uint32_t> Str2Vec(std::string str)
{
if (str.size() <= 1) {
return {};
}
str.pop_back();
str.erase(str.begin());
std::vector<uint32_t> 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<std::string>();
PRINT_HILOGD("supported orientations: %{public}s", orientationArray.c_str());
std::vector<uint32_t> orientationVector = Str2Vec(orientationArray);
std::vector<uint32_t> orientationVector = PrintUtil::Str2Vec(orientationArray);
nativePrinterInfo.capability.supportedOrientations = CopyArray<uint32_t, Print_OrientationMode>(
orientationVector, nativePrinterInfo.capability.supportedOrientationsCount, ConvertOrientationMode);
}

View File

@ -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",

View File

@ -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",

View File

@ -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;

View File

@ -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"

View File

@ -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<PrintExtensionInfo> allExtensionInfos;
std::vector<PrintJob> allPrintJobs;
std::vector<std::string> allPrinters;
std::string previewResult = "";
std::string type = "";
sptr<IPrintCallback> 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<std::string> extensionList;
uint32_t applicationEvent = -1;
std::string printerPreference;
InnerPrintContext() : Context(nullptr, nullptr) {};
InnerPrintContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};

View File

@ -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);

View File

@ -28,7 +28,7 @@ class PrintAsyncCall final {
public:
class Context {
public:
using InputAction = std::function<napi_status(napi_env, size_t, napi_value *, napi_value)>;
using InputAction = std::function<napi_status(napi_env, size_t, napi_value *, napi_value, napi_callback_info)>;
using OutputAction = std::function<napi_status(napi_env, napi_value *)>;
using ExecAction = std::function<void(Context *)>;
Context(InputAction input, OutputAction output) : input_(std::move(input)), output_(std::move(output)) {};
@ -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;

View File

@ -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 <string>
#include <vector>
#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<OHOS::AbilityRuntime::AbilityContext> context = nullptr;
std::shared_ptr<OHOS::AbilityRuntime::UIExtensionContext> 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

View File

@ -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 <string>
#include <uv.h>
#include <js_native_api.h>
#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> 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> baseContext = nullptr;
bool isResultForModal = false;
};
} // namespace Print
} // namespace OHOS
#endif // PRINT_MODAL_UI_CALLBACK_H

View File

@ -21,11 +21,21 @@
#include <string>
#include <vector>
#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> &printAttributes_, const sptr<IRemoteObject> &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> &adapterParam,
bool isPrintByAdapter);
bool ParseAbilityContextReq(napi_env env, const napi_value &obj,
std::shared_ptr<OHOS::AbilityRuntime::AbilityContext> &abilityContext,
std::shared_ptr<OHOS::AbilityRuntime::UIExtensionContext> &uiExtensionContext);
void StartUIExtensionAbility(
std::shared_ptr<BaseContext> asyncContext, const std::shared_ptr<AdapterParam> &adapterParam);
uint32_t StartUIExtensionAbility(OHOS::AAFwk::Want &want, std::shared_ptr<BaseContext> asyncContext);
OHOS::Ace::UIContent* GetUIContent(const BaseContext *asyncContext);
void CreateDefaultAdapterParam(const std::shared_ptr<AdapterParam> &adapterParam);
bool CheckPermission(const std::string &name);
private:
struct TaskEventContext : public PrintAsyncCall::Context {
std::string type = "";

View File

@ -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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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<InnerPrintContext>();
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;

View File

@ -26,7 +26,9 @@ napi_value NapiPrintExt::AddPrinters(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<NapiPrintExtContext>();
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<PrintAsyncCall::Context>(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

View File

@ -44,7 +44,8 @@ napi_value NapiPrintTask::Print(napi_env env, napi_callback_info info)
}
auto context = std::make_shared<PrintTaskContext>();
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<void **>(&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<PrintTaskContext>();
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<void **>(&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");

View File

@ -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<AsyncContext *>(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);

View File

@ -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 <uv.h>
#include <js_native_api.h>
#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> 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<void*>(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<BaseContext*>(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<PrintContext*>(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

View File

@ -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<int32_t>(PRINTER_STATUS_IDLE));
SetEnumProperty(env, object, "PRINTER_STATUS_BUSY", static_cast<int32_t>(PRINTER_STATUS_BUSY));
SetEnumProperty(env, object, "PRINTER_STATUS_UNAVAILABLE", static_cast<int32_t>(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<int32_t>(PRINTER_STATUS_IDLE));
SetEnumProperty(env, object, "PRINTER_EVENT_DELETED", static_cast<int32_t>(PRINTER_STATUS_BUSY));
SetEnumProperty(env, object, "PRINTER_EVENT_STATE_CHANGED", static_cast<int32_t>(PRINTER_STATUS_UNAVAILABLE));
SetEnumProperty(env, object, "PRINTER_EVENT_INFO_CHANGED", static_cast<int32_t>(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);

View File

@ -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<std::string> &innerList, const sptr<IRemoteObject> &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> adapterParam = std::make_shared<AdapterParam>();
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<void*>(callerToken_));
if (callerToken_ != nullptr) {
std::shared_ptr<AdapterParam> adapterParam = std::make_shared<AdapterParam>();
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> &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<BaseContext>();
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<OHOS::AbilityRuntime::AbilityContext> &abilityContext,
std::shared_ptr<OHOS::AbilityRuntime::UIExtensionContext> &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<OHOS::AbilityRuntime::AbilityContext>(context);
if (abilityContext == nullptr) {
PRINT_HILOGE("get abilityContext failed");
uiExtensionContext =
OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::UIExtensionContext>(context);
if (uiExtensionContext == nullptr) {
PRINT_HILOGE("get uiExtensionContext failed");
return false;
}
}
PRINT_HILOGD("end ParseAbilityContextReq");
return true;
}
void PrintTask::StartUIExtensionAbility(
std::shared_ptr<BaseContext> asyncContext, const std::shared_ptr<AdapterParam> &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<int32_t>(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<BaseContext> 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<PrintModalUICallback>(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)
{
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<TaskEventContext>();
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

View File

@ -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",
]
}

View File

@ -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"
}
]

View File

@ -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

View File

@ -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",

View File

@ -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 <string>
#include <vector>
#include <nlohmann/json.hpp>
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<std::string>(),
printerAttr.at("orientation").get<std::string>(),
printerAttr.at("duplex").get<std::string>(),
printerAttr.at("quality").get<std::string>()
};
}
json BuildPreferenceSettingJson() const
{
return json{{"pagesizeId", pagesizeId}, {"orientation", orientation},
{"duplex", duplex}, {"quality", quality}};
}
~PreferenceSetting() {};
};
class PrinterPreference {
public:
std::vector<std::string> pagesizeId;
std::vector<std::string> orientation;
std::vector<std::string> duplex;
std::vector<std::string> quality;
PreferenceSetting defaultSetting;
PreferenceSetting setting;
PrinterPreference() {};
PrinterPreference(std::vector<std::string> pagesizeId, std::vector<std::string> orientation,
std::vector<std::string> duplex, std::vector<std::string> 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<std::vector<std::string>>(),
printerAttrs.at("orientation").get<std::vector<std::string>>(),
printerAttrs.at("duplex").get<std::vector<std::string>>(),
printerAttrs.at("quality").get<std::vector<std::string>>(),
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

View File

@ -32,7 +32,7 @@ public:
virtual ~PrintBMSHelper();
void SetHelper(const std::shared_ptr<PrintServiceHelper> &helper);
void SetHelper(std::shared_ptr<PrintServiceHelper> &helper);
bool QueryExtensionInfos(std::vector<AppExecFwk::ExtensionAbilityInfo> &extensionInfo);

View File

@ -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 <cups/cups-private.h>
#include "printer_capability.h"
namespace OHOS::Print {
void ParsePrinterAttributes(ipp_t *response, PrinterCapability &printerCaps);
} // namespace OHOS::Print
#endif // PRINT_CUPS_ATTRIBUTE_H

View File

@ -20,6 +20,7 @@
#include <string>
#include <functional>
#include <cups/cups-private.h>
#include <cups/ppd.h>
#include <nlohmann/json.hpp>
#include "singleton.h"
@ -30,45 +31,6 @@ namespace OHOS::Print {
using json = nlohmann::json;
typedef std::function<void()> 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<uint32_t> 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<std::string> &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<std::string> &keyList,
std::vector<std::string> &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<std::string> &ppds);

View File

@ -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

View File

@ -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 <string>
#include <queue>
#include <mutex>
#include "singleton.h"
#include "httplib.h"
#include "print_usb_manager.h"
namespace OHOS::Print {
template<class T>
class DoubleBufQue {
public:
void push(T& val)
{
std::lock_guard<std::mutex> mtx_locker(mutexSwap);
writeQueue.emplace(val);
}
bool pop(T& val)
{
if (readQueue.empty()) {
std::lock_guard<std::mutex> mtx_locker(mutexSwap);
if (writeQueue.empty()) {
return false;
}
readQueue.swap(writeQueue);
}
val = readQueue.front();
readQueue.pop();
return true;
}
private:
std::queue<T> writeQueue;
std::queue<T> 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<uint8_t> &readTempBuffer);
void RecordBufByOperation(Operation operation, size_t requestId, const std::vector<uint8_t> &tmVector);
void GetContentLength(const std::vector<uint8_t> &readTempBuffer, size_t index, bool &findContentLength,
size_t &contentLength);
void DumpRespIdCode(const std::vector<uint8_t> &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<uint8_t> &readTempBuffer, size_t index);
size_t CalculateRequestId(std::vector<uint8_t> &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<uint8_t> &tmVector);
private:
bool needWriteData = false;
bool needReadSendDoc = false;
bool needWriteSendDoc = false;
bool deviceOpen = true;
std::map<size_t, size_t> reqIdOperaIdMap; // requestId + operationId
std::map<size_t, std::vector<uint8_t>> readBufMap; // requestId + buffer
std::map<size_t, std::vector<uint8_t>> readSendDocBufMap; // requestId + buffer
std::map<size_t, std::vector<uint8_t>> readGetAttrBufMap; // requestId + buffer
std::string devName;
std::mutex mutexCommon;
std::mutex mutexGetAttr;
std::mutex mutexSendDoc;
DoubleBufQue<std::string> sendDocDataQue;
DoubleBufQue<std::string> ippDataQue;
size_t sendDocTotalLen = 0;
};
}
#endif // PRINT_HTTP_REQUEST_PROCESS_H_
#endif // IPPOVERUSB_ENABLE

View File

@ -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 <string>
#include <map>
#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<PrintHttpServerManager> {
public:
PrintHttpServerManager();
~PrintHttpServerManager();
bool CreateServer(std::string printerName, int32_t &port);
static void StartServer(std::shared_ptr<httplib::Server> svr,
std::shared_ptr<PrintHttpRequestProcess> process);
void StopServer(std::string printerName);
void DealUsbDevDetach(const std::string &devStr);
private:
bool AllocatePort(std::shared_ptr<httplib::Server> svr, int32_t &port);
private:
std::map<std::string, std::shared_ptr<httplib::Server>> printHttpServerMap;
std::map<std::string, int32_t> printHttpPortMap;
std::map<std::string, std::shared_ptr<PrintHttpRequestProcess>> printHttpProcessMap;
};
}
#endif // IPPOVERUSB_ENABLE
#endif // PRINT_HTTP_SERVER_MANAGER_H_

View File

@ -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 <string>
#include "print_event_subscriber.h"
namespace OHOS::Print {
class PrintIppOverUsbManager final : public DelayedSingleton<PrintIppOverUsbManager> {
public:
PrintIppOverUsbManager();
~PrintIppOverUsbManager();
void Init();
bool ConnectPrinter(const std::string printerId, int32_t &port);
void DisConnectPrinter(const std::string printerId);
private:
std::shared_ptr<PrintEventSubscriber> usbDevStatusListener;
bool isInit = false;
};
}
#endif // IPPOVERUSB_ENABLE
#endif // PRINT_IPP_OVER_USB_MANAGER_H_

View File

@ -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;

View File

@ -19,6 +19,7 @@
#include <mutex>
#include <string>
#include <vector>
#include <unordered_map>
#include <nlohmann/json.hpp>
#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<PrintServiceAbility> GetInstance();
int32_t StartService() override;
int32_t StartPrint(const std::vector<std::string> &fileList,
const std::vector<uint32_t> &fdList, std::string &taskId) override;
int32_t StartPrint(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &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<std::string> &extensionList) override;
int32_t StopDiscoverPrinter() override;
int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &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<PrinterInfo> &printerInfos) override;
int32_t RemovePrinters(const std::vector<std::string> &printerIds) override;
int32_t UpdatePrinters(const std::vector<PrinterInfo> &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<IPrintCallback> &listener) override;
int32_t Off(const std::string taskId, const std::string &type) override;
int32_t RegisterPrinterCallback(const std::string &type, const sptr<IPrintCallback> &listener) override;
int32_t UnregisterPrinterCallback(const std::string &type) override;
int32_t RegisterExtCallback(const std::string &extensionCID,
const sptr<IPrintExtensionCallback> &listener) override;
int32_t UnregisterAllExtCallback(const std::string &extensionId) override;
@ -86,11 +84,28 @@ public:
PrinterCapability &printerCaps) override;
void SetHelper(const std::shared_ptr<PrintServiceHelper> &helper);
int32_t PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes,
std::string &taskId, const sptr<IRemoteObject> &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<std::string> &printerNameList) override;
int32_t QueryPrinterProperties(const std::string &printerId, const std::vector<std::string> &keyList,
std::vector<std::string> &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<uint32_t> &fdList, AAFwk::Want &want);
void DestroyExtension(const std::string &printerId);
void NotifyAppJobQueueChanged(const std::string &applyResult);
std::shared_ptr<PrinterInfo> getPrinterInfo(const std::string printerId);
bool isEprint(const std::string &printerId);
void ReportHisysEvent(const std::shared_ptr<PrintJob> &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<std::string> &fileList,
const std::vector<uint32_t> &fdList, std::string &taskId, const std::shared_ptr<AdapterParam> &adapterParam);
int32_t CallSpooler(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
std::string &taskId, const sptr<IRemoteObject> &token, const std::shared_ptr<AdapterParam> &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> &printJob);
void StartPrintJobCB(const std::string &jobId, const std::shared_ptr<PrintJob> &printJob);
void CreateDefaultAdapterParam(const std::shared_ptr<AdapterParam> &adapterParam);
void BuildAdapterParam(
const std::shared_ptr<AdapterParam> &adapterParam, AAFwk::Want &want, const std::string &jobId);
void BuildPrintAttributesParam(const std::shared_ptr<AdapterParam> &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<PrintJob> 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> &printjob);
std::shared_ptr<PrintUserData> GetCurrentUserData();
int32_t GetUserIdByJobId(const std::string jobId);
std::shared_ptr<PrintUserData> 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<std::string>& optAttrs);
void BuildPrinterAttrComponentByJson(std::string& key, nlohmann::json& jsonArrObject,
std::vector<std::string> &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<std::string, PrintExtensionState> extensionStateList_;
std::map<std::string, std::shared_ptr<PrintJob>> printJobList_;
std::map<std::string, std::shared_ptr<PrintJob>> queuedJobList_;
std::map<std::string, std::string, JobIdCmp> jobOrderList_;
std::map<std::string, PrintAttributes> printAttributesList_;
std::map<std::string, std::shared_ptr<PrinterInfo>> printerInfoList_;
@ -162,10 +202,18 @@ private:
std::string spoolerAbilityName_;
std::mutex lock_;
uint64_t currentJobId_;
uint64_t currentJobOrderId_;
std::shared_ptr<PrintServiceHelper> helper_;
bool isJobQueueBlocked_;
std::map<int64_t, std::shared_ptr<PrintUserData>> printUserDataMap_;
PrintSystemData printSystemData_;
std::map<int32_t, std::shared_ptr<PrintUserData>> printUserMap_;
std::map<std::string, int32_t> userJobMap_;
int32_t currentUserId_;
uint32_t printAppCount_;
std::map<std::string, std::string> printerIdAndPreferenceMap_;
};
} // namespace OHOS::Print
#endif // PRINT_SYSTEM_ABILITY_H

View File

@ -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 <string>
#include <vector>
#include <nlohmann/json.hpp>
#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 <typename T>
void AddToUniqueList(std::vector<T> &list, T value)
{
for (auto &item : list) {
if (item == value) {
return;
}
}
list.push_back(value);
}
template <typename T>
std::string ConvertListToJson(const std::vector<T> &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

View File

@ -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<IRemoteObject> GetBundleMgr();
virtual bool QueryAccounts(std::vector<int> &accountList);
virtual bool QueryExtension(sptr<AppExecFwk::IBundleMgr> mgr, int userId,
std::vector<AppExecFwk::ExtensionAbilityInfo> &extensionInfos);
virtual bool QueryNameForUid(sptr<AppExecFwk::IBundleMgr> 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<IRemoteObject> &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<PrintEventSubscriber> userStatusListener;
bool isSubscribeCommonEvent = false;
};
} // namespace OHOS
#endif // PRINT_SERVICE_HELPER_H

View File

@ -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<uint32_t, PrintCmdHandler> cmdMap_;

View File

@ -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 <string>
#include <map>
#include <nlohmann/json.hpp>
#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<PrinterInfo> 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<std::string> &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<std::string, std::shared_ptr<CupsPrinterInfo>> addedPrinterMap_;
std::map<std::string, std::shared_ptr<PrinterInfo>> addedPrinterInfoList_;
};
} // namespace Print
} // namespace OHOS
#endif // PRINT_SYSTEM_DATA_H

View File

@ -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 <map>
#include <string>
#include <utility>
#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<PrintUsbManager> {
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<uint8_t> &vectorRequestBuffer);
int32_t BulkTransferRead(std::string printerName, const Operation operation,
std::vector<uint8_t> &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<std::string, USB::UsbDevice> printDeviceMap;
std::map<std::string, std::vector<std::pair<int32_t, int32_t>>> printerIndexMap;
std::map<std::string, USB::USBDevicePipe> printPipeMap;
std::map<std::string, PrinterTranIndex> printTranIndexMap;
std::string currentPrinterName;
};
}
#endif // IPPOVERUSB_ENABLE
#endif // PRINT_USB_MANAGER_H_

View File

@ -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 <string>
#include <map>
#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<IPrintCallback> &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> &printjob);
void UpdateQueuedJobList(
const std::string &jobId, const std::shared_ptr<PrintJob> &printJob, std::string jobOrderId);
int32_t QueryPrintJobById(std::string &printJobId, PrintJob &printJob);
int32_t QueryAllPrintJob(std::vector<PrintJob> &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<std::string, sptr<IPrintCallback>> registeredListeners_;
std::map<std::string, std::shared_ptr<PrintJob>> printJobList_;
std::map<std::string, std::shared_ptr<PrintJob>> queuedJobList_;
std::map<std::string, std::string, JobIdCmp> jobOrderList_;
private:
std::string defaultPrinterId_ = "";
std::string lastUsedPrinterId_ = "";
int32_t userId_ = 0;
};
} // namespace Print
} // namespace OHOS
#endif // PRINT_USER_DATA_H

View File

@ -27,7 +27,7 @@ PrintBMSHelper::PrintBMSHelper() : sptrBundleMgr_(nullptr), printBMSDeath_(nullp
PrintBMSHelper::~PrintBMSHelper()
{}
void PrintBMSHelper::SetHelper(const std::shared_ptr<PrintServiceHelper> &helper)
void PrintBMSHelper::SetHelper(std::shared_ptr<PrintServiceHelper> &helper)
{
helper_ = helper;
sptrBundleMgr_ = nullptr;

View File

@ -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 <vector>
#include <string>
#include "print_cups_attribute.h"
#include "print_service_converter.h"
#include "print_log.h"
namespace OHOS::Print {
template <typename T>
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 <typename T>
bool ParseAttributesToList(ipp_t *response, const std::string &keyword, std::vector<T> &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<T>(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<DuplexModeCode> list;
ParseAttributesToList(response, keyword, list, ConvertDuplexModeCode);
std::string duplexModeJson = ConvertListToJson<DuplexModeCode>(list, ConvertDuplexModeToJson);
printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), duplexModeJson.c_str());
size_t num = list.size();
if (static_cast<int>(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<DuplexModeCode>(response, keyword, code, ConvertDuplexModeCode)) {
uint32_t value = static_cast<uint32_t>(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<ColorModeCode> supportedColorModes;
ParseAttributesToList<ColorModeCode>(response, keyword, supportedColorModes, ConvertColorModeCode);
std::string colorModeJson = ConvertListToJson<ColorModeCode>(supportedColorModes, ConvertColorModeToJson);
printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), colorModeJson.c_str());
keyword = "print-color-mode-default";
ColorModeCode code;
if (ParseAttributeToValue<ColorModeCode>(response, keyword, code, ConvertColorModeCode)) {
uint32_t mode = static_cast<uint32_t>(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<PrintPageSize> supportedPageSizes;
ParseAttributesToList<PrintPageSize>(response, keyword, supportedPageSizes, ConvertPrintPageSize);
std::string pageSizeJson = ConvertListToJson<PrintPageSize>(supportedPageSizes, ConvertPageSizeToJson);
printerCaps.SetPageSize(supportedPageSizes);
printerCaps.SetPrinterAttrNameAndValue("supportedPageSizeArray", pageSizeJson.c_str());
std::string defaultPageSizeId;
keyword = "media-default";
if (ParseAttributeToValue<std::string>(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<int>(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<int>(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<std::string> 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

View File

@ -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<std::string> IGNORE_STATE_LIST = {
PRINTER_STATE_WAITING_COMPLETE, PRINTER_STATE_NONE, PRINTER_STATE_EMPTY, PRINTER_STATE_WIFI_NOT_CONFIGURED
};
static const std::vector<std::string> 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<string> 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<std::string> &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<std::string> &keyList,
std::vector<std::string> &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<std::string>();
PRINT_HILOGD("QueryPrinterInfoByPrinterId in %{public}s", printerUri.c_str());
if (infoJson.contains("printerName") && infoJson["printerName"].is_string()) {
info.SetPrinterName(infoJson["printerName"].get<std::string>());
}
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<std::string>();
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<PrintPageSize> 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<PrintPageSize>();
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());

View File

@ -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<PrintUsbManager>::GetInstance()->DealUsbDevStatusChange(devStr, true);
} else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED) {
std::string devStr = data.GetData();
DelayedSingleton<PrintHttpServerManager>::GetInstance()->DealUsbDevDetach(devStr);
DelayedSingleton<PrintUsbManager>::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

View File

@ -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 <cmath>
#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<uint8_t> &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<uint8_t> &tmVector)
{
if (operation == Operation::Send_Document) {
std::lock_guard<std::mutex> mtx_locker(mutexSendDoc);
if (readSendDocBufMap.find(requestId) == readSendDocBufMap.end()) {
readSendDocBufMap[requestId] = tmVector;
}
} else {
if (reqIdOperaIdMap[requestId] == HTTP_REQUEST_GET_ATTR) {
std::lock_guard<std::mutex> mtx_locker(mutexGetAttr);
if (readGetAttrBufMap.find(requestId) == readGetAttrBufMap.end()) {
readGetAttrBufMap[requestId] = tmVector;
}
} else {
std::lock_guard<std::mutex> mtx_locker(mutexCommon);
if (readBufMap.find(requestId) == readBufMap.end()) {
readBufMap[requestId] = tmVector;
}
}
}
}
void PrintHttpRequestProcess::GetContentLength(const std::vector<uint8_t> &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<size_t>(std::stoi(lenStr));
PRINT_HILOGD("contentLength = %{public}s, %{public}lu", lenStr.c_str(), contentLength);
}
}
}
void PrintHttpRequestProcess::DumpRespIdCode(const std::vector<uint8_t> &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<uint8_t> &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<uint8_t> &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<uint8_t> readTempBuffer;
int32_t readFromUsbRes =
DelayedSingleton<PrintUsbManager>::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<uint8_t> 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<uint8_t> &tmVector)
{
PRINT_HILOGD("GetAttr again");
std::vector<uint8_t> readBuffer;
int32_t readFromUsbRes =
DelayedSingleton<PrintUsbManager>::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<std::mutex> 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<std::mutex> 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<std::mutex> 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<uint8_t> 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<PrintUsbManager>::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<unsigned int>(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<uint8_t> 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<PrintUsbManager>::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;
}
}

View File

@ -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<httplib::Server> 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<httplib::Server> svr,
std::shared_ptr<PrintHttpRequestProcess> 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<httplib::Server> newServer = std::make_shared<httplib::Server>();
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<PrintHttpRequestProcess> newProcess = std::make_shared<PrintHttpRequestProcess>();
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<PrintUsbManager>::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);
}
}

View File

@ -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<PrintEventSubscriber>(subscribeInfo);
if (!EventFwk::CommonEventManager::SubscribeCommonEvent(usbDevStatusListener)) {
PRINT_HILOGE("subscribe common event failed");
}
DelayedSingleton<PrintUsbManager>::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<PrintUsbManager>::GetInstance()->isExistIppOverUsbPrinter(printerName)) {
if (DelayedSingleton<PrintUsbManager>::GetInstance()->ConnectUsbPinter(printerName)) {
auto ret = DelayedSingleton<PrintHttpServerManager>::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<PrintUsbManager>::GetInstance()->isExistIppOverUsbPrinter(printerName)) {
DelayedSingleton<PrintHttpServerManager>::GetInstance()->StopServer(printerName);
DelayedSingleton<PrintUsbManager>::GetInstance()->DisConnectUsbPinter(printerName);
}
}
}
}

View File

@ -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<uint32_t> 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;

File diff suppressed because it is too large Load Diff

View File

@ -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<int>(code));
return true;
}
bool ConvertDuplexModeToJson(const DuplexModeCode &code, nlohmann::json &jsonObject)
{
jsonObject["duplex"] = std::to_string(static_cast<int>(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

View File

@ -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> 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<PrintEventSubscriber>(subscribeInfo);
if (userStatusListener == nullptr) {
PRINT_HILOGE("create userStatusListener failed.");
return;
}
if (!EventFwk::CommonEventManager::SubscribeCommonEvent(userStatusListener)) {
PRINT_HILOGE("subscribe common event failed");
}
}
} // namespace OHOS

View File

@ -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<IRemoteObject> 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<PrinterInfo> 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<std::string> 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<std::string> keyList;
data.ReadStringVector(&keyList);
std::vector<std::string> 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<PrinterInfo> 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<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
PRINT_HILOGE("PrintServiceStub::OnEventOn remote is nullptr");
reply.WriteInt32(E_PRINT_RPC_FAILURE);
return false;
}
sptr<IPrintCallback> listener = iface_cast<IPrintCallback>(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<IRemoteObject> 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;
}

View File

@ -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 <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <streambuf>
#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<std::string>();
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<char>(ifs)), std::istreambuf_iterator<char>());
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<CupsPrinterInfo>(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>(printerInfo);
}
}
std::shared_ptr<PrinterInfo> 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<std::string> &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<PrintResolution> 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<PrintPageSize> 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<uint32_t>());
if (!capsJson.contains("duplexMode") || !capsJson["duplexMode"].is_number()) {
PRINT_HILOGW("can not find duplexMode");
return false;
}
printerCapability.SetDuplexMode(capsJson["duplexMode"].get<uint32_t>());
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<PrintResolution> 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<uint32_t>());
if (!resolutionJson.contains("verticalDpi") || !resolutionJson["verticalDpi"].is_number()) {
PRINT_HILOGW("can not find verticalDpi");
return false;
}
printResolution.SetVerticalDpi(resolutionJson["verticalDpi"].get<uint32_t>());
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<PrintPageSize> 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<uint32_t>());
if (!pageSizeJson.contains("height") || !pageSizeJson["height"].is_number()) {
PRINT_HILOGW("can not find height");
return false;
}
pageSize.SetHeight(pageSizeJson["height"].get<uint32_t>());
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<uint32_t>());
marginCount++;
}
if (marginJson.contains("bottom") && marginJson["bottom"].is_number()) {
minMargin.SetTop(marginJson["bottom"].get<uint32_t>());
marginCount++;
}
if (marginJson.contains("left") && marginJson["left"].is_number()) {
minMargin.SetLeft(marginJson["left"].get<uint32_t>());
marginCount++;
}
if (marginJson.contains("right") && marginJson["right"].is_number()) {
minMargin.SetRight(marginJson["right"].get<uint32_t>());
marginCount++;
}
if (marginCount) {
printerCapability.SetMinMargin(minMargin);
}
}
bool PrintSystemData::GetPrinterCapabilityFromSystemData(
CupsPrinterInfo &cupsPrinter, std::string printerId, PrinterCapability &printerCapability)
{
PrinterCapability cupsPrinterCaps = cupsPrinter.printerCapability;
std::vector<PrintPageSize> 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<PrintPageSize> 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

View File

@ -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<std::pair<int32_t, int32_t>> 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<int32_t>(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<UsbDevice> 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<uint8_t> 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<uint8_t> 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<uint8_t> &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<uint8_t> &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 "";
}
}

View File

@ -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 <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <streambuf>
#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<IPrintCallback> &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> &printjob)
{
printJobList_.insert(std::make_pair(jobId, printjob));
}
void PrintUserData::UpdateQueuedJobList(
const std::string &jobId, const std::shared_ptr<PrintJob> &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<PrintJob> &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<std::string>() == 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<char>(ifs)), std::istreambuf_iterator<char>());
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<std::string>();
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

View File

@ -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",
]
}

View File

@ -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",
]
}
###############################################################################

View File

@ -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

View File

@ -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<std::string> 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<std::string> 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<std::string> keyList;
keyList.push_back(key);
std::string value = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH);
std::vector<std::string> 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<uint32_t>(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<float>(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<unsigned int>(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;
}

View File

@ -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

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>

View File

@ -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;
}
}

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