diff --git a/bundle.json b/bundle.json index 05035d0..59389f3 100644 --- a/bundle.json +++ b/bundle.json @@ -70,7 +70,8 @@ "//base/print/print_fwk/frameworks/kits/extension:print_extension_module", "//base/print/print_fwk/frameworks/innerkitsimpl/print_impl:print_client", "//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/models/print_models:print_models", + "//base/print/print_fwk/frameworks/ohprint:ohprint" ], "service_group":[ "//base/print/print_fwk/services/print_service:print_service", diff --git a/frameworks/innerkitsimpl/print_impl/include/print_extension_callback_stub.h b/frameworks/innerkitsimpl/print_impl/include/print_extension_callback_stub.h index b3af3f8..429681a 100644 --- a/frameworks/innerkitsimpl/print_impl/include/print_extension_callback_stub.h +++ b/frameworks/innerkitsimpl/print_impl/include/print_extension_callback_stub.h @@ -22,12 +22,14 @@ #include "iremote_stub.h" #include "print_job.h" #include "printer_capability.h" +#include "printer_info.h" namespace OHOS::Print { using PrintExtCallback = bool (*)(); using PrintJobCallback = bool (*)(const PrintJob&); using PrinterCallback = bool (*)(const std::string&); using PrinterCapabilityCallback = bool (*)(const std::string&, PrinterCapability&); +using NativePrinterChangeCallback = bool (*)(uint32_t event, const OHOS::Print::PrinterInfo &info); class PrintExtensionCallbackStub : public IRemoteStub { public: diff --git a/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h b/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h index 970e013..3b5e3af 100644 --- a/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h +++ b/frameworks/innerkitsimpl/print_impl/include/print_manager_client.h @@ -42,6 +42,8 @@ public: void OnRemoteSaDied(const wptr &object); + int32_t Init(); + int32_t Release(); int32_t StartPrint(const std::vector &fileList, const std::vector &fdList, std::string &taskId); int32_t StopPrint(const std::string &taskId); @@ -68,6 +70,13 @@ public: const std::string &printerMake); int32_t QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId, PrinterCapability &printerCaps); + int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info); + int32_t QueryAddedPrinter(std::vector &printerNameList); + int32_t QueryPrinterProperties(const std::string &printerId, const std::vector &keyList, + std::vector &valueList); + int32_t StartNativePrintJob(PrintJob &printJob); + int32_t GetPrinterPreference(const std::string &printerId, std::string &printerPreference); + int32_t SetPrinterPreference(const std::string &printerId, const std::string &printerPreference); int32_t On(const std::string &taskId, const std::string &type, const sptr &listener); int32_t Off(const std::string &taskId, const std::string &type); @@ -102,6 +111,8 @@ public: int32_t UnregisterAllExtCallback(const std::string &extensionId); int32_t LoadExtSuccess(const std::string &extensionId); + int32_t SetNativePrinterChangeCallback(const std::string &type, NativePrinterChangeCallback cb); + void LoadServerSuccess(); void LoadServerFail(); void SetProxy(const sptr &obj); diff --git a/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp b/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp index 70b6eed..a4d1a09 100644 --- a/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp +++ b/frameworks/innerkitsimpl/print_impl/src/print_manager_client.cpp @@ -297,6 +297,67 @@ int32_t PrintManagerClient::QueryPrinterCapability(const std::string &printerId) return ret; } +int32_t PrintManagerClient::QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) +{ + PRINT_HILOGD("PrintManagerClient QueryPrinterInfoByPrinterId start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + PRINT_HILOGD("PrintManagerClient QueryPrinterInfoByPrinterId out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::QueryAddedPrinter(std::vector &printerNameList) +{ + PRINT_HILOGD("PrintManagerClient QueryAddedPrinter start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + PRINT_HILOGD("PrintManagerClient QueryAddedPrinter out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::QueryPrinterProperties(const std::string &printerId, + const std::vector &keyList, std::vector &valueList) +{ + PRINT_HILOGD("PrintManagerClient QueryPrinterProperties start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + PRINT_HILOGD("PrintManagerClient QueryPrinterProperties out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::StartNativePrintJob(PrintJob &printJob) +{ + PRINT_HILOGD("PrintManagerClient StartNativePrintJob start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + PRINT_HILOGD("PrintManagerClient QueryPrinterProperties out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::GetPrinterPreference(const std::string &printerId, std::string &printerPreference) +{ + PRINT_HILOGI("PrintManagerClient GetPrinterPreference start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + PRINT_HILOGI("PrintManagerClient GetPrinterPreference out ret = [%{public}d].", ret); + } + return ret; +} + +int32_t PrintManagerClient::SetPrinterPreference(const std::string &printerId, const std::string &printerPreference) +{ + PRINT_HILOGI("PrintManagerClient SetPrinterPreference start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + PRINT_HILOGI("PrintManagerClient SetPrinterPreference out ret = [%{public}d].", ret); + } + return ret; +} + int32_t PrintManagerClient::QueryAllPrintJob(std::vector &printJobs) { PRINT_HILOGD("PrintManagerClient QueryAllPrintJob start."); @@ -834,6 +895,16 @@ int32_t PrintManagerClient::UnregisterAllExtCallback(const std::string &extensio return ret; } +int32_t PrintManagerClient::SetNativePrinterChangeCallback(const std::string &type, NativePrinterChangeCallback cb) +{ + int32_t ret = E_PRINT_RPC_FAILURE; + PRINT_HILOGI("PrintManagerClient SetNativePrinterChangeCallback start"); + if (LoadServer() && GetPrintServiceProxy()) { + } + PRINT_HILOGD("PrintManagerClient SetNativePrinterChangeCallback out ret = [%{public}d].", ret); + return ret; +} + int32_t PrintManagerClient::LoadExtSuccess(const std::string &extensionId) { PRINT_HILOGD("PrintManagerClient LoadExtSuccess start."); @@ -919,4 +990,21 @@ void PrintManagerClient::ResetProxy() { printServiceProxy_ = nullptr; } + +int32_t PrintManagerClient::Init() +{ + PRINT_HILOGI("nativePrint Init start."); + int32_t ret = E_PRINT_RPC_FAILURE; + if (LoadServer() && GetPrintServiceProxy()) { + } + PRINT_HILOGD("PrintManagerClient Init out ret = [%{public}d].", ret); + return ret; +} + +int32_t PrintManagerClient::Release() +{ + SetNativePrinterChangeCallback(PRINTER_DISCOVER_EVENT_TYPE, nullptr); + SetNativePrinterChangeCallback(PRINTER_CHANGE_EVENT_TYPE, nullptr); + return E_PRINT_NONE; +} } // namespace OHOS::Print diff --git a/frameworks/ohprint/BUILD.gn b/frameworks/ohprint/BUILD.gn new file mode 100755 index 0000000..d1cc6d4 --- /dev/null +++ b/frameworks/ohprint/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//base/print/print_fwk/print.gni") +import("//build/ohos.gni") + +config("print_ndk_config") { + visibility = [ ":*" ] + include_dirs = [] + + cflags_cc = [ "-fno-exceptions" ] +} +ohos_shared_library("ohprint") { + include_dirs = [ + "${print_path}/frameworks/ohprint/include", + "${print_utils_path}/include", + "${print_path}/frameworks/helper/print_helper/include", + "${print_path}/frameworks/models/print_models/include", + "${print_path}/services/print_service/include", + ] + public_configs = [ ":print_ndk_config" ] + + sources = [ + "src/print_capi.cpp", + "src/print_converter.cpp", + "src/print_helper.cpp", + ] + + deps = [ + "${print_path}/frameworks/helper/print_helper:print_helper", + "${print_path}/frameworks/innerkitsimpl/print_impl:print_client", + "${print_path}/frameworks/models/print_models:print_models", + "${print_path}/services/print_service:print_service", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:data_ability_helper", + "ability_runtime:napi_base_context", + "c_utils:utils", + "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", + ] + + relative_install_dir = "ndk" + output_name = "ohprint" + output_extension = "so" + + install_enable = true + subsystem_name = "print" + part_name = "print_fwk" +} diff --git a/frameworks/ohprint/include/ohprint.h b/frameworks/ohprint/include/ohprint.h new file mode 100755 index 0000000..7dd9684 --- /dev/null +++ b/frameworks/ohprint/include/ohprint.h @@ -0,0 +1,667 @@ +/* + * 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. + */ + +/** + * @addtogroup OH_Print + * @{ + * + * @brief Provides the definition of the C interface for the print module. + * + * @syscap SystemCapability.Print.PrintFramework + * + * @since 12 + * @version 1.0 + */ + +/** + * @file ohprint.h + * + * @brief Declares the APIs to discover and connect printers, print files from a printer, + * query the list of the added printers and the printer information within it, and so on. + * + * @library libohprint.so + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + * @version 1.0 + */ + +#ifndef OH_PRINT_H +#define OH_PRINT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Defines error codes. + * + * @since 12 + * @version 1.0 + */ +typedef enum { + /** @error The operation is successful. */ + PRINT_ERROR_NONE = 0, + /** @error Permission verification failed. */ + PRINT_ERROR_NO_PERMISSION = 201, + /** @error Invalid parameter. */ + PRINT_ERROR_INVALID_PARAMETER = 401, + /** @error General internal error. */ + PRINT_ERROR_GENERIC_FAILURE = 24300001, + /** @error RPC communication error. */ + PRINT_ERROR_RPC_FAILURE = 24300002, + /** @error Server error. */ + PRINT_ERROR_SERVER_FAILURE = 24300003, + /** @error Invalid extension. */ + PRINT_ERROR_INVALID_EXTENSION = 24300004, + /** @error Invalid printer. */ + PRINT_ERROR_INVALID_PRINTER = 24300005, + /** @error Invalid print job. */ + PRINT_ERROR_INVALID_PRINT_JOB = 24300006, + /** @error Failed to read or write files. */ + PRINT_ERROR_FILE_IO = 24300007, + /** @error Unknown error. */ + PRINT_ERROR_UNKNOWN = 24300255, +} Print_ErrorCode; + +/** + * @brief Indicates printer states. + * + * @since 12 + */ +typedef enum { + /** Printer idle. */ + PRINTER_IDLE, + /** Printer busy. */ + PRINTER_BUSY, + /** Printer not available. */ + PRINTER_UNAVAILABLE, +} Print_PrinterState; + +/** + * @brief Indicate printer discovery events. + * + * @since 12 + */ +typedef enum { + /** Printer discovered. */ + PRINTER_DISCOVERED = 0, + /** Printer lost. */ + PRINTER_LOST = 1, + /** Printer connecting. */ + PRINTER_CONNECTING = 2, + /** Printer connected. */ + PRINTER_CONNECTED = 3, +} Print_DiscoveryEvent; + +/** + * @brief Indicate printer change events. + * + * @since 12 + */ +typedef enum { + /** Printer added. */ + PRINTER_ADDED = 0, + /** Printer deleted. */ + PRINTER_DELETED = 1, + /** Printer state changed. */ + PRINTER_STATE_CHANGED = 2, + /** Printer info changed. */ + PRINTER_INFO_CHANGED = 3, +} Print_PrinterEvent; + +/** + * @brief Indicates string list. + * + * @since 12 + */ +typedef struct { + /** Number of string. */ + uint32_t count; + /** String pointer array. */ + char **list; +} Print_StringList; + +/** + * @brief Indicates printer property. + * + * @since 12 + */ +typedef struct { + /** Property keyword. */ + char *key; + /** Property value. */ + char *value; +} Print_Property; + +/** + * @brief List of printer properties. + * + * @since 12 + */ +typedef struct { + /** Number of properties. */ + uint32_t count; + /** Property pointer array. */ + Print_Property *list; +} Print_PropertyList; + +/** + * @brief Indicates print resolution in dpi unit. + * + * @since 12 + */ +typedef struct { + uint32_t horizontalDpi; + uint32_t verticalDpi; +} Print_Resolution; + +/** + * @brief Indicates printing margin + * + * @since 12 + */ +typedef struct { + /** Left margin. */ + uint32_t leftMargin; + /** Top margin. */ + uint32_t topMargin; + /** Right margin. */ + uint32_t rightMargin; + /** Bottom margin. */ + uint32_t bottomMargin; +} Print_Margin; + +/** + * @brief Indicates paper size info. + * + * @since 12 + */ +typedef struct { + /** Paper id. */ + char *id; + /** Paper name. */ + char *name; + /** Paper width. */ + uint32_t width; + /** Paper height. */ + uint32_t height; +} Print_PageSize; + +/** + * @brief Indicates DuplexMode + * + * @since 12 + */ +typedef enum { + /** One sided duplex mode. */ + DUPLEX_MODE_ONE_SIDED = 0, + /** Long edge two sided duplex mode. */ + DUPLEX_MODE_TWO_SIDED_LONG_EDGE = 1, + /** Short edge two sided duplex mode. */ + DUPLEX_MODE_TWO_SIDED_SHORT_EDGE = 2, +} Print_DuplexMode; + +/** + * @brief Indicates ColorMode + * + * @since 12 + */ +typedef enum { + /** Monochrome mode. */ + COLOR_MODE_MONOCHROME = 0, + /** Color mode. */ + COLOR_MODE_COLOR = 1, + /** Auto mode. */ + COLOR_MODE_AUTO = 2, +} Print_ColorMode; + +/** + * @brief Indicates OrientationMode + * + * @since 12 + */ +typedef enum { + /** Portrait mode. */ + ORIENTATION_MODE_PORTRAIT = 0, + /** Landscape mode. */ + ORIENTATION_MODE_LANDSCAPE = 1, + /** Reverse landscape mode. */ + ORIENTATION_MODE_REVERSE_LANDSCAPE = 2, + /** Reverse portrait mode. */ + ORIENTATION_MODE_REVERSE_PORTRAIT = 3, + /** Not specified. */ + ORIENTATION_MODE_NONE = 4, +} Print_OrientationMode; + +/** + * @brief Indicates printing qulity + * + * @since 12 + */ +typedef enum { + /** Draft quality mode */ + PRINT_QUALITY_DRAFT = 3, + /** Normal quality mode */ + PRINT_QUALITY_NORMAL = 4, + /** High quality mode */ + PRINT_QUALITY_HIGH = 5 +} Print_Quality; + +/** + * @brief Indicates the MIME media type of the document. + * + * @since 12 + */ +typedef enum { + /** MIME: application/octet-stream. */ + DOCUMENT_FORMAT_AUTO, + /** MIME: image/jpeg. */ + DOCUMENT_FORMAT_JPEG, + /** MIME: application/pdf. */ + DOCUMENT_FORMAT_PDF, + /** MIME: application/postscript. */ + DOCUMENT_FORMAT_POSTSCRIPT, + /** MIME: text/plain. */ + DOCUMENT_FORMAT_TEXT, +} Print_DocumentFormat; + +/** + * @brief Indicates printer capabilities. + * + * @since 12 + */ +typedef struct { + /** Array of supported color mode. */ + Print_ColorMode *supportedColorModes; + /** Number of supported color mode. */ + uint32_t supportedColorModesCount; + /** Array of supported duplex printing modes. */ + Print_DuplexMode *supportedDuplexModes; + /** Number of supported duplex printing mode. */ + uint32_t supportedDuplexModesCount; + /** Array of supported print paper sizes. */ + Print_PageSize *supportedPageSizes; + /** Number of supported print paper sizes. */ + uint32_t supportedPageSizesCount; + /** Supported print media types in json string array format. */ + char *supportedMediaTypes; + /** Array of supported print qulities. */ + Print_Quality *supportedQualities; + /** Number of supported print qulities. */ + uint32_t supportedQualitiesCount; + /** Supported paper sources in json string array format. */ + char *supportedPaperSources; + /** Supported copies. */ + uint32_t supportedCopies; + /** Array of supported printer resolutions. */ + Print_Resolution *supportedResolutions; + /** Number of supported printer resolutions. */ + uint32_t supportedResolutionsCount; + /** Array of supported orientation. */ + Print_OrientationMode *supportedOrientations; + /** Number of supported orientation. */ + uint32_t supportedOrientationsCount; + /** Advanced capability in json format. */ + char *advancedCapability; +} Print_PrinterCapability; + +/** + * @brief Indicates current properties + * + * @since 12 + */ +typedef struct { + /** Default color mode. */ + Print_ColorMode defaultColorMode; + /** Default duplex mode. */ + Print_DuplexMode defaultDuplexMode; + /** Default media type. */ + char *defaultMediaType; + /** Default page size id. */ + char *defaultPageSizeId; + /** Default margin. */ + Print_Margin defaultMargin; + /** Default paper source. */ + char *defaultPaperSource; + /** Default print quality */ + Print_Quality defaultPrintQuality; + /** Default copies. */ + uint32_t defaultCopies; + /** Default printer resolution. */ + Print_Resolution defaultResolution; + /** Default orientation. */ + Print_OrientationMode defaultOrientation; + /** Other default values in json format. */ + char *otherDefaultValues; +} Print_DefaultValue; + +/** + * @brief Indicates printer information. + * + * @since 12 + */ +typedef struct { + /** Printer state. */ + Print_PrinterState printerState; + /** Printer capabilities. */ + Print_PrinterCapability capability; + /** Printer current properties. */ + Print_DefaultValue defaultValue; + /** Default printer. */ + bool isDefaultPrinter; + /** Printer id. */ + char *printerId; + /** Printer name. */ + char *printerName; + /** Printer description. */ + char *description; + /** Printer location. */ + char *location; + /** Printer make and model information. */ + char *makeAndModel; + /** Printer Uri. */ + char *printerUri; + /** Detail information in json format. */ + char *detailInfo; +} Print_PrinterInfo; + +/** + * @brief Indicates PrintJob Structure. + * + * @since 12 + */ +typedef struct { + /** Job name. */ + char *jobName; + /** Array of file descriptors to print. */ + uint32_t *fdList; + /** Number of file descriptors to print. */ + uint32_t fdListCount; + /** Printer id. */ + char *printerId; + /** Number of copies printed. */ + uint32_t copyNumber; + /** Paper source. */ + char *paperSource; + /** Media type. */ + char *mediaType; + /** Paper size id. */ + char *pageSizeId; + /** Color mode. */ + Print_ColorMode colorMode; + /** Duplex source. */ + Print_DuplexMode duplexMode; + /** Print resolution in dpi. */ + Print_Resolution resolution; + /** Print margin. */ + Print_Margin printMargin; + /** Borderless. */ + bool borderless; + /** Orientation mode. */ + Print_OrientationMode orientationMode; + /** Print quality. */ + Print_Quality printQuality; + /** Document format. */ + Print_DocumentFormat documentFormat; + /** Advanced options in json format. */ + char *advancedOptions; +} Print_PrintJob; + +/** + * @brief Printer discovery callback. + * + * @param event The printer discovery event during printer discovery. + * @param printerInfo The printer infomation at the time of the discovery event. + * @since 12 + */ +typedef void (*Print_PrinterDiscoveryCallback)(Print_DiscoveryEvent event, const Print_PrinterInfo *printerInfo); + +/** + * @brief Printer change callback. + * + * @param event The printer change event while the printer service is running. + * @param printerInfo The printer infomation at the time of the change event. + * @since 12 + */ +typedef void (*Print_PrinterChangeCallback)(Print_PrinterEvent event, const Print_PrinterInfo *printerInfo); + +/** + * @brief This API checks and pulls up the print service, initializes the print client, + * and establishes a connection to the print service. + * + * @permission {@code ohos.permission.PRINT} + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * {@link PRINT_ERROR_SERVER_FAILURE} The cups service cannot be started. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_Init(); + +/** + * @brief This API closes the connection from the print service, dissolves the previous callback, + * and releases the print client resources. + * + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * Currently no other error codes will be returned. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_Release(); + +/** + * @brief This API starts discovering printers. + * + * @permission {@code ohos.permission.PRINT} + * @param callback The {@link Print_PrinterDiscoveryCallback} of printer discovery event. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * {@link PRINT_ERROR_SERVER_FAILURE} Failed to query print extension list from BMS. + * {@link PRINT_ERROR_INVALID_EXTENSION} No available print extensions found. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_StartPrinterDiscovery(Print_PrinterDiscoveryCallback callback); + +/** + * @brief This API stops discovering printers. + * + * @permission {@code ohos.permission.PRINT} + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_StopPrinterDiscovery(); + +/** + * @brief This API connects to the printer using the printer id. + * + * @permission {@code ohos.permission.PRINT} + * @param printerId The id of the printer to be connected. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * {@link PRINT_ERROR_INVALID_PRINTER} The printer should be in the list of discovered printers. + * {@link PRINT_ERROR_SERVER_FAILURE} Unable to find an extension responsible for the printer. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_ConnectPrinter(const char *printerId); + +/** + * @brief This API starts initiating a print job. + * + * @permission {@code ohos.permission.PRINT} + * @param printJob A pointer to a {@link Print_PrintJob} instance that specifies the information for the print job. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * {@link PRINT_ERROR_INVALID_PRINTER} The printer should be in the list of connected printers. + * {@link PRINT_ERROR_SERVER_FAILURE} Unable to create print job in the print service. + * {@link PRINT_ERROR_INVALID_PRINT_JOB} Unable to find the job int the job queue. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_StartPrintJob(const Print_PrintJob *printJob); + +/** + * @brief This API registers the callback for printer changes. + * + * @permission {@code ohos.permission.PRINT} + * @param callback The {@link Print_PrinterChangeCallback} to be registered. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_RegisterPrinterChangeListener(Print_PrinterChangeCallback callback); + +/** + * @brief This API unregisters the callback for printer changes. + * + * @permission {@code ohos.permission.PRINT} + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +void OH_Print_UnregisterPrinterChangeListener(); + +/** + * @brief This API queries for a list of added printers. + * + * @permission {@code ohos.permission.PRINT} + * @param printerIdList A pointer to a {@link Print_StringList} instance to store the queried printer id list. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_INVALID_PARAMETER} printerIdList is NULL. + * {@link PRINT_ERROR_INVALID_PRINTER} Unable to query any connected printers. + * {@link PRINT_ERROR_GENERIC_FAILURE} Unable to copy the printer id list. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_QueryPrinterList(Print_StringList *printerIdList); + +/** + * @brief This API frees up the printer list memory for the query. + * + * @param printerIdList The queried printer id list to be released. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +void OH_Print_ReleasePrinterList(Print_StringList *printerIdList); + +/** + * @brief This API queries printer information based on the printer id. + * + * @permission {@code ohos.permission.PRINT} + * @param printerId The id of the printer to be queried. + * @param printerInfo A pointer to a {@link Print_PrinterInfo} pointer to store the printer infomation. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * {@link PRINT_ERROR_INVALID_PARAMETER} printerId is NULL or printerInfo is NULL. + * {@link PRINT_ERROR_INVALID_PRINTER} Unable to find the printer in the connected printer list. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_QueryPrinterInfo(const char *printerId, Print_PrinterInfo **printerInfo); + +/** + * @brief This API frees up the printer infomation memory for the query. + * + * @param printerInfo The pointer of the queried printer infomation to be released. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +void OH_Print_ReleasePrinterInfo(Print_PrinterInfo *printerInfo); + +/** + * @brief This API launches the system's printer management window. + * + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_GENERIC_FAILURE} Unable to launch the printer manager window. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_LaunchPrinterManager(); + +/** + * @brief This API queries the corresponding printer property values based on the list of property keywords. + * + * @permission {@code ohos.permission.PRINT} + * @param printerId The id of the printer to be queried. + * @param propertyKeyList The list of property keywords to be queried + * @param propertyList The list of printer property values queried. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_INVALID_PARAMETER} One of the params is NULL or the keyword list is empty. + * {@link PRINT_ERROR_INVALID_PRINTER} The printer properties for the specified printer could not be found. + * {@link PRINT_ERROR_GENERIC_FAILURE} Unable to copy the printer properties. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_QueryPrinterProperties(const char *printerId, const Print_StringList *propertyKeyList, + Print_PropertyList *propertyList); + +/** + * @brief This API frees up the property list memory for the query. + * + * @param propertyList The pointer of the queried printer property values to be released. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +void OH_Print_ReleasePrinterProperties(Print_PropertyList *propertyList); + +/** + * @brief This API sets printer properties based on a list of property key-value pairs. + * + * @permission {@code ohos.permission.PRINT} + * @param printerId The id of the printer to be set. + * @param propertyList The list of printer property values to be set. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_UpdatePrinterProperties(const char *printerId, const Print_PropertyList *propertyList); + +/** + * @brief This API restores printer properties to default settings based on the list of property keywords. + * + * @permission {@code ohos.permission.PRINT} + * @param printerId The id of the printer to be restored. + * @param propertyKeyList The list of property keywords to be restored. + * @return Returns {@link Print_ErrorCode#PRINT_ERROR_NONE} if the execution is successful. + * {@link PRINT_ERROR_NO_PERMISSION} The permission {@code ohos.permission.PRINT} is needed. + * {@link PRINT_ERROR_RPC_FAILURE} Unable to connect to the print service. + * @syscap SystemCapability.Print.PrintFramework + * @since 12 + */ +Print_ErrorCode OH_Print_RestorePrinterProperties(const char *printerId, const Print_StringList *propertyKeyList); + +#ifdef __cplusplus +} +#endif + +#endif // OH_PRINT_H +/** @} */ diff --git a/frameworks/ohprint/include/print_converter.h b/frameworks/ohprint/include/print_converter.h new file mode 100755 index 0000000..744678d --- /dev/null +++ b/frameworks/ohprint/include/print_converter.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NATIVE_PRINT_CONVERTER_H +#define NATIVE_PRINT_CONVERTER_H + +#include +#include + +#include "ohprint.h" + +namespace OHOS::Print { +#define SAFE_DELETE(address) \ + { \ + if ((address) != nullptr) { \ + delete (address); \ + (address) = nullptr; \ + } \ + } + +#define SAFE_DELETE_ARRAY(address) \ + { \ + if ((address) != nullptr) { \ + delete[] (address); \ + (address) = nullptr; \ + } \ + } + +inline bool IsValidString(const char *address) +{ + if (address == nullptr || address[0] == '\0') { + return false; + } + return true; +} + +template +T *CopyArray(const std::vector &list, uint32_t &count) +{ + count = 0; + size_t len = list.size(); + if (len <= 0) { + return nullptr; + } + T *dest = new (std::nothrow) T[len]; + if (dest == nullptr) { + return nullptr; + } + if (memset_s(dest, len * sizeof(T), 0, len * sizeof(T)) != 0) { + delete[] dest; + dest = nullptr; + return nullptr; + } + for (size_t i = 0; i < len; i++) { + *(dest + i) = list[i]; + } + count = len; + return dest; +} + +template +T2 *CopyArray(const std::vector &list, uint32_t &count, bool (*ConvertFunction)(const T1 &src, T2 &dst)) +{ + count = 0; + size_t len = list.size(); + if (len <= 0) { + return nullptr; + } + T2 *dest = new (std::nothrow) T2[len]; + if (dest == nullptr) { + return nullptr; + } + if (memset_s(dest, len * sizeof(T2), 0, len * sizeof(T2)) != 0) { + delete[] dest; + dest = nullptr; + return nullptr; + } + for (size_t i = 0; i < len; i++) { + if (ConvertFunction(list[i], *(dest + count))) { + count++; + } + } + return dest; +} + +Print_ErrorCode ConvertToNativeErrorCode(int32_t errorCode); +Print_PrinterState ConvertPrinterState(uint32_t state); +bool ConvertStringToInt(const char *src, int &dst); +bool ConvertOrientationMode(const uint32_t &src, Print_OrientationMode &dst); +bool ConvertColorMode(const uint32_t &src, Print_ColorMode &dst); +bool ConvertDuplexMode(const uint32_t &src, Print_DuplexMode &dst); +bool ConvertQuality(const uint32_t &src, Print_Quality &dst); +std::string GetDocumentFormatString(Print_DocumentFormat format); +std::string GetResolutionString(Print_Resolution resolution); +} // namespace OHOS::Print +#endif // NATIVE_PRINT_CONVERTER_H \ No newline at end of file diff --git a/frameworks/ohprint/include/print_helper.h b/frameworks/ohprint/include/print_helper.h new file mode 100755 index 0000000..0e1726a --- /dev/null +++ b/frameworks/ohprint/include/print_helper.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NATIVE_PRINT_HELPER_H +#define NATIVE_PRINT_HELPER_H + +#include + +#include "ohprint.h" +#include "printer_info.h" +#include "print_job.h" + +namespace OHOS::Print { +char *CopyString(const std::string &source); +void ReleasePrinterInfo(Print_PrinterInfo &printerInfo); +Print_PrinterInfo *ConvertToNativePrinterInfo(const PrinterInfo &info); +int32_t ConvertNativeJobToPrintJob(const Print_PrintJob &nativePrintJob, PrintJob &printJob); +Print_ErrorCode ConvertStringVectorToPropertyList(const std::vector &valueList, + Print_PropertyList *propertyList); +} // namespace OHOS::Print +#endif // NATIVE_PRINT_HELPER_H \ No newline at end of file diff --git a/frameworks/ohprint/src/print_capi.cpp b/frameworks/ohprint/src/print_capi.cpp new file mode 100755 index 0000000..0014fc1 --- /dev/null +++ b/frameworks/ohprint/src/print_capi.cpp @@ -0,0 +1,327 @@ +/* + * 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 "ohprint.h" +#include "print_manager_client.h" +#include "print_constant.h" +#include "print_log.h" +#include "ability_manager_client.h" +#include "print_util.h" +#include "print_callback.h" +#include "print_converter.h" +#include "print_helper.h" + +using namespace OHOS::Print; + +static Print_PrinterDiscoveryCallback printerDiscoverCallback = nullptr; +static Print_PrinterChangeCallback printerInfoCallback = nullptr; + +static bool NativePrinterDiscoverFunction(uint32_t event, const PrinterInfo &info) +{ + PRINT_HILOGD("NativePrinterDiscoverFunction event: %{public}d, printerId: [%{public}s]", + event, info.GetPrinterId().c_str()); + if (printerDiscoverCallback == nullptr) { + PRINT_HILOGW("printerDiscoverCallback is null"); + return false; + } + Print_PrinterInfo *nativePrinterInfo = ConvertToNativePrinterInfo(info); + if (nativePrinterInfo == nullptr) { + PRINT_HILOGW("nativePrinterInfo is null."); + return false; + } + printerDiscoverCallback(static_cast(event), nativePrinterInfo); + OH_Print_ReleasePrinterInfo(nativePrinterInfo); + nativePrinterInfo = nullptr; + return true; +} + +static bool NativePrinterInfoFunction(uint32_t event, const PrinterInfo &info) +{ + PRINT_HILOGD("NativePrinterInfoFunction event: [%{public}d, printerId: [%{public}s]", + event, info.GetPrinterId().c_str()); + if (printerInfoCallback == nullptr) { + PRINT_HILOGW("printerInfoCallback is null"); + return false; + } + Print_PrinterInfo *nativePrinterInfo = ConvertToNativePrinterInfo(info); + if (nativePrinterInfo == nullptr) { + PRINT_HILOGW("nativePrinterInfo is null."); + return false; + } + printerInfoCallback(static_cast(event), nativePrinterInfo); + OH_Print_ReleasePrinterInfo(nativePrinterInfo); + nativePrinterInfo = nullptr; + return true; +} + +// 初始化 +Print_ErrorCode OH_Print_Init() +{ + int32_t ret = PrintManagerClient::GetInstance()->Init(); + PRINT_HILOGI("OH_Print_Init ret = [%{public}d]", ret); + return ConvertToNativeErrorCode(ret); +} + +// 反初始化 +Print_ErrorCode OH_Print_Release() +{ + int32_t ret = PrintManagerClient::GetInstance()->Release(); + PRINT_HILOGI("OH_Print_Release ret = [%{public}d]", ret); + return ConvertToNativeErrorCode(ret); +} + +Print_ErrorCode OH_Print_StartPrinterDiscovery(Print_PrinterDiscoveryCallback callback) +{ + printerDiscoverCallback = callback; + std::vector extensionInfos; + int32_t ret = PrintManagerClient::GetInstance()->QueryAllExtension(extensionInfos); + PRINT_HILOGI("QueryAllExtension ret = [%{public}d]", ret); + if (ret == PRINT_ERROR_NONE) { + std::vector extensionIds; + for (auto &extensionInfo : extensionInfos) { + extensionIds.emplace_back(extensionInfo.GetExtensionId()); + } + PRINT_HILOGI("extensionIds size = [%{public}zu]", extensionIds.size()); + PrintManagerClient::GetInstance()->SetNativePrinterChangeCallback( + PRINTER_DISCOVER_EVENT_TYPE, NativePrinterDiscoverFunction); + ret = PrintManagerClient::GetInstance()->StartDiscoverPrinter(extensionIds); + PRINT_HILOGI("StartDiscoverPrinter ret = [%{public}d]", ret); + } + return ConvertToNativeErrorCode(ret); +} + +Print_ErrorCode OH_Print_StopPrinterDiscovery() +{ + PrintManagerClient::GetInstance()->SetNativePrinterChangeCallback(PRINTER_DISCOVER_EVENT_TYPE, nullptr); + printerDiscoverCallback = nullptr; + int32_t ret = PrintManagerClient::GetInstance()->StopDiscoverPrinter(); + PRINT_HILOGI("StopDiscoverPrinter ret = [%{public}d]", ret); + return ConvertToNativeErrorCode(ret); +} + +Print_ErrorCode OH_Print_ConnectPrinter(const char *printerId) +{ + if (printerId == nullptr) { + PRINT_HILOGW("printerId is null."); + return PRINT_ERROR_INVALID_PRINTER; + } + std::string nativePrinterId = printerId; + int32_t ret = PrintManagerClient::GetInstance()->ConnectPrinter(nativePrinterId); + PRINT_HILOGI("ConnectPrinter ret = [%{public}d]", ret); + return ConvertToNativeErrorCode(ret); +} + +Print_ErrorCode OH_Print_StartPrintJob(const Print_PrintJob *printJob) +{ + if (printJob == nullptr) { + PRINT_HILOGI("printJob is null."); + return PRINT_ERROR_INVALID_PRINT_JOB; + } + PrintJob curPrintJob; + int32_t ret = ConvertNativeJobToPrintJob(*printJob, curPrintJob); + if (ret != 0) { + PRINT_HILOGW("ConvertNativeJobToPrintJob fail."); + return PRINT_ERROR_INVALID_PRINT_JOB; + } + ret = PrintManagerClient::GetInstance()->StartNativePrintJob(curPrintJob); + PRINT_HILOGI("StartNativePrintJob ret = [%{public}d]", ret); + return ConvertToNativeErrorCode(ret); +} + +Print_ErrorCode OH_Print_RegisterPrinterChangeListener(Print_PrinterChangeCallback callback) +{ + printerInfoCallback = callback; + PrintManagerClient::GetInstance()->SetNativePrinterChangeCallback( + PRINTER_CHANGE_EVENT_TYPE, NativePrinterInfoFunction); + return PRINT_ERROR_NONE; +} + +void OH_Print_UnregisterPrinterChangeListener() +{ + PrintManagerClient::GetInstance()->SetNativePrinterChangeCallback(PRINTER_CHANGE_EVENT_TYPE, nullptr); + printerInfoCallback = nullptr; +} + +Print_ErrorCode OH_Print_QueryPrinterList(Print_StringList *printerIdList) +{ + if (printerIdList == nullptr) { + PRINT_HILOGW("printerIdList is null."); + return PRINT_ERROR_INVALID_PARAMETER; + } + std::vector printerNameList; + int32_t ret = PrintManagerClient::GetInstance()->QueryAddedPrinter(printerNameList); + size_t count = printerNameList.size(); + PRINT_HILOGI("OH_Print_QueryPrinterList ret = %{public}d, count = %{public}zu.", ret, count); + if (ret != 0 || count <= 0) { + return PRINT_ERROR_INVALID_PRINTER; + } + printerIdList->list = new (std::nothrow) char *[count]; + if (printerIdList->list == nullptr) { + PRINT_HILOGW("printerIdList->list is null"); + return PRINT_ERROR_GENERIC_FAILURE; + } + if (memset_s(printerIdList->list, count * sizeof(char *), 0, count * sizeof(char *)) != 0) { + PRINT_HILOGW("memset_s fail"); + return PRINT_ERROR_GENERIC_FAILURE; + } + for (size_t i = 0; i < count; ++i) { + printerIdList->list[i] = CopyString(printerNameList[i]); + } + printerIdList->count = count; + return PRINT_ERROR_NONE; +} + +void OH_Print_ReleasePrinterList(Print_StringList *printerIdList) +{ + if (printerIdList == nullptr) { + PRINT_HILOGW("printerIdList is null."); + return; + } + if (printerIdList->list != nullptr) { + for (uint32_t i = 0; i < printerIdList->count; i++) { + SAFE_DELETE_ARRAY(printerIdList->list[i]); + } + SAFE_DELETE_ARRAY(printerIdList->list); + } + printerIdList->count = 0; +} + +Print_ErrorCode OH_Print_QueryPrinterInfo(const char *printerId, Print_PrinterInfo **printerInfo) +{ + if (printerId == nullptr || printerInfo == nullptr) { + PRINT_HILOGW("Invalid parameter."); + return PRINT_ERROR_INVALID_PARAMETER; + } + std::string id(printerId); + PrinterInfo info; + int32_t ret = PrintManagerClient::GetInstance()->QueryPrinterInfoByPrinterId(id, info); + PRINT_HILOGI("QueryPrinterInfoByPrinterId ret = %{public}d", ret); + if (info.GetPrinterId() != id || info.GetPrinterName().empty()) { + PRINT_HILOGI("QueryPrinterInfoByPrinterId invalid printer"); + return PRINT_ERROR_INVALID_PRINTER; + } + Print_PrinterInfo *nativePrinterInfo = ConvertToNativePrinterInfo(info); + if (nativePrinterInfo != nullptr) { + if (ret != 0) { + nativePrinterInfo->printerState = PRINTER_UNAVAILABLE; + } + *printerInfo = nativePrinterInfo; + } + return ConvertToNativeErrorCode(ret); +} + +void OH_Print_ReleasePrinterInfo(Print_PrinterInfo *printerInfo) +{ + if (printerInfo == nullptr) { + PRINT_HILOGW("printerInfo is null."); + return; + } + ReleasePrinterInfo(*printerInfo); + delete printerInfo; + printerInfo = nullptr; +} + +Print_ErrorCode OH_Print_LaunchPrinterManager() +{ + OHOS::AAFwk::AbilityManagerClient::GetInstance()->Connect(); + OHOS::AAFwk::Want want; + want.SetElementName("com.ohos.spooler", "PrinterManagerAbility"); + auto ret = OHOS::AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + PRINT_HILOGI("StartAbility ret = %{public}d", ret); + if (ret != 0) { + PRINT_HILOGW("Failed to start PrinterManagerAbility"); + return PRINT_ERROR_GENERIC_FAILURE; + } + PRINT_HILOGI("Succeed to start PrinterManagerAbility"); + return PRINT_ERROR_NONE; +} + +int32_t OH_Print_LaunchPrinterPreference(const char* printerName, const char* printerId) +{ + OHOS::AAFwk::AbilityManagerClient::GetInstance()->Connect(); + OHOS::AAFwk::Want want; + want.SetElementName(printerId, "com.ohos.spooler", "PreferencesAbility", ""); + want.SetParam("printerName", printerName); + want.SetParam("printerId", printerId); + std::string thirdAppFlag = "window"; + want.SetParam("thirdApp", thirdAppFlag.c_str()); + auto ret = OHOS::AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + PRINT_HILOGI("StartAbility ret = %{public}d", ret); + if (ret != 0) { + PRINT_HILOGW("Failed to start PreferencesAbility"); + return PRINT_ERROR_GENERIC_FAILURE; + } + PRINT_HILOGI("Succeed to start PreferencesAbility"); + return PRINT_ERROR_NONE; +} + +Print_ErrorCode OH_Print_QueryPrinterProperties( + const char *printerId, const Print_StringList *propertyKeyList, Print_PropertyList *propertyList) +{ + if (printerId == nullptr || propertyKeyList == nullptr || propertyKeyList->list == nullptr || + propertyList == nullptr) { + PRINT_HILOGW("OH_Print_QueryPrinterProperties invalid parameter."); + return PRINT_ERROR_INVALID_PRINTER; + } + std::vector keyList; + for (uint32_t i = 0; i < propertyKeyList->count; i++) { + if (propertyKeyList->list[i] == nullptr) { + continue; + } + std::string key(propertyKeyList->list[i]); + if (key.empty()) { + continue; + } + keyList.emplace_back(key); + } + if (keyList.size() == 0) { + PRINT_HILOGW("empty keyList"); + return PRINT_ERROR_INVALID_PARAMETER; + } + std::vector valueList; + int32_t ret = PrintManagerClient::GetInstance()->QueryPrinterProperties(printerId, keyList, valueList); + PRINT_HILOGI("QueryPrinterProperties ret = %{public}d", ret); + if (ret != 0) { + PRINT_HILOGW("QueryPrinterProperties fail"); + return PRINT_ERROR_INVALID_PRINTER; + } + return ConvertStringVectorToPropertyList(valueList, propertyList); +} + +void OH_Print_ReleasePrinterProperties(Print_PropertyList *propertyList) +{ + if (propertyList == nullptr) { + PRINT_HILOGW("propertyList is null"); + return; + } + if (propertyList->list != nullptr) { + for (uint32_t i = 0; i < propertyList->count; ++i) { + SAFE_DELETE_ARRAY(propertyList->list[i].key); + SAFE_DELETE_ARRAY(propertyList->list[i].value); + } + SAFE_DELETE_ARRAY(propertyList->list); + } + propertyList->count = 0; +} + +Print_ErrorCode OH_Print_UpdatePrinterProperties(const char *printerId, const Print_PropertyList *propertyList) +{ + return PRINT_ERROR_NONE; +} + +Print_ErrorCode OH_Print_RestorePrinterProperties(const char *printerId, const Print_StringList *propertyKeyList) +{ + return PRINT_ERROR_NONE; +} \ No newline at end of file diff --git a/frameworks/ohprint/src/print_converter.cpp b/frameworks/ohprint/src/print_converter.cpp new file mode 100755 index 0000000..7347437 --- /dev/null +++ b/frameworks/ohprint/src/print_converter.cpp @@ -0,0 +1,128 @@ +/* + * 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_converter.h" +#include "print_constant.h" +#include "print_log.h" +#include "print_util.h" + +namespace { +const uint32_t ORIENTATION_OFFSET = 3; +} // namespace +namespace OHOS::Print { +Print_ErrorCode ConvertToNativeErrorCode(int32_t errorCode) +{ + if (errorCode >= E_PRINT_GENERIC_FAILURE && errorCode <= E_PRINT_UNKNOWN) { + return static_cast(errorCode + PRINT_ERROR_GENERIC_FAILURE - E_PRINT_GENERIC_FAILURE); + } + return static_cast(errorCode); +} + +Print_PrinterState ConvertPrinterState(uint32_t state) +{ + switch (state) { + case PRINTER_ADDED: + return PRINTER_UNAVAILABLE; + case PRINTER_REMOVED: + return PRINTER_UNAVAILABLE; + case PRINTER_UPDATE_CAP: + return PRINTER_UNAVAILABLE; + case PRINTER_CONNECTED: + return PRINTER_IDLE; + case PRINTER_DISCONNECTED: + return PRINTER_UNAVAILABLE; + case PRINTER_RUNNING: + return PRINTER_BUSY; + default: + return PRINTER_UNAVAILABLE; + } +} + +bool ConvertStringToInt(const char *src, int &dst) +{ + if (src == nullptr) { + return false; + } + dst = atoi(src); + if (errno == ERANGE) { + PRINT_HILOGW("ConvertStringToInt fail: %{public}s", src); + return false; + } + return true; +} + +bool ConvertOrientationMode(const uint32_t &src, Print_OrientationMode &dst) +{ + if (src >= ORIENTATION_OFFSET && src - ORIENTATION_OFFSET <= static_cast(ORIENTATION_MODE_NONE)) { + dst = static_cast(src - ORIENTATION_OFFSET); + return true; + } else { + return false; + } +} + +bool ConvertColorMode(const uint32_t &src, Print_ColorMode &dst) +{ + if (src >= 0 && src <= static_cast(COLOR_MODE_AUTO)) { + dst = static_cast(src); + return true; + } else { + return false; + } +} + +bool ConvertDuplexMode(const uint32_t &src, Print_DuplexMode &dst) +{ + if (src >= 0 && src <= static_cast(DUPLEX_MODE_SHORT_EDGE)) { + dst = static_cast(src); + return true; + } else { + return false; + } +} + +bool ConvertQuality(const uint32_t &src, Print_Quality &dst) +{ + if (src >= static_cast(PRINT_QUALITY_DRAFT) && src <= static_cast(PRINT_QUALITY_HIGH)) { + dst = static_cast(src); + return true; + } else { + return false; + } +} + +std::string GetDocumentFormatString(Print_DocumentFormat format) +{ + switch (format) { + case DOCUMENT_FORMAT_JPEG: + return "image/jpeg"; + case DOCUMENT_FORMAT_PDF: + return "application/pdf"; + case DOCUMENT_FORMAT_POSTSCRIPT: + return "application/postscript"; + case DOCUMENT_FORMAT_TEXT: + return "text/plain"; + case DOCUMENT_FORMAT_AUTO: + return "application/octet-stream"; + default: + return "application/octet-stream"; + } +} + +std::string GetResolutionString(Print_Resolution resolution) +{ + return std::to_string(resolution.horizontalDpi) + "x" + std::to_string(resolution.verticalDpi) + "dpi"; +} +} // namespace OHOS::Print diff --git a/frameworks/ohprint/src/print_helper.cpp b/frameworks/ohprint/src/print_helper.cpp new file mode 100755 index 0000000..c552830 --- /dev/null +++ b/frameworks/ohprint/src/print_helper.cpp @@ -0,0 +1,600 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "print_helper.h" +#include "print_constant.h" +#include "print_log.h" +#include "print_util.h" +#include "ability_manager_client.h" +#include "print_converter.h" + +using json = nlohmann::json; + +namespace OHOS::Print { +static std::vector Str2Vec(std::string str) +{ + if (str.size() <= 1) { + return {}; + } + str.pop_back(); + str.erase(str.begin()); + std::vector vec; + std::istringstream is(str); + std::string temp; + while (getline(is, temp, ',')) { + vec.push_back(stoi(temp)); + } + return vec; +} + +char *CopyString(const std::string &source) +{ + auto len = source.length(); + char *dest = new (std::nothrow) char[len + 1]; + if (dest == nullptr) { + PRINT_HILOGW("allocate failed"); + return nullptr; + } + if (strcpy_s(dest, len + 1, source.c_str()) != 0) { + PRINT_HILOGW("CopyString strcpy_s failed"); + } + dest[len] = '\0'; + return dest; +} + +void AddJsonFieldStringToJsonObject(const nlohmann::json &cupsOpt, const std::string &keyword, + nlohmann::json &advancedCapJson) +{ + PRINT_HILOGD("AddJsonFieldStringToJsonObject %{public}s", keyword.c_str()); + if (!cupsOpt.contains(keyword)) { + PRINT_HILOGW("missing keyword"); + return; + } + if (!cupsOpt[keyword].is_string()) { + PRINT_HILOGW("not string type"); + return; + } + std::string optionString = cupsOpt[keyword].get(); + PRINT_HILOGD("AddJsonFieldStringToJsonObject %{public}s", optionString.c_str()); + advancedCapJson[keyword] = optionString; +} + +void ParseJsonFieldAsArrayOpt(const nlohmann::json &cupsOpt, const std::string &key, + Print_PrinterInfo &nativePrinterInfo, void (*arrayOpteration)(const nlohmann::json &, Print_PrinterInfo &)) +{ + PRINT_HILOGD("ParseJsonFieldAsArrayOpt: %{public}s", key.c_str()); + if (arrayOpteration == nullptr) { + PRINT_HILOGW("arrayOpteration is null"); + return; + } + if (!cupsOpt.contains(key)) { + PRINT_HILOGW("key missing"); + return; + } + if (!cupsOpt[key].is_string()) { + PRINT_HILOGW("not string"); + return; + } + std::string arrayJson = cupsOpt[key].get(); + if (!nlohmann::json::accept(arrayJson)) { + PRINT_HILOGW("accept fail"); + return; + } + nlohmann::json arrayOpt = nlohmann::json::parse(arrayJson); + if (!arrayOpt.is_array()) { + PRINT_HILOGW("not array"); + return; + } + arrayOpteration(arrayOpt, nativePrinterInfo); +} + +bool ParseJsonFieldAsInt(const nlohmann::json &cupsOpt, const std::string &key, int &value) +{ + if (!cupsOpt.contains(key)) { + PRINT_HILOGW("key missing"); + return false; + } + if (cupsOpt[key].is_number()) { + value = cupsOpt[key]; + return true; + } + if (!cupsOpt[key].is_string()) { + PRINT_HILOGW("incorrect type"); + return false; + } + std::string jsonString = cupsOpt[key].get(); + if (ConvertStringToInt(jsonString.c_str(), value)) { + return true; + } + return false; +} + +void ConvertJsonArrayToIntList(const nlohmann::json &jsonArray, const std::string &key, std::vector &list) +{ + PRINT_HILOGD("ConvertJsonArrayToIntList %{public}s, %{public}zu", key.c_str(), jsonArray.size()); + for (auto &item : jsonArray) { + int value = 0; + if (!ParseJsonFieldAsInt(item, key, value)) { + continue; + } + list.push_back(static_cast(value)); + } +} + +void ReleaseCapabilityPageSizes(Print_PrinterCapability &capability) +{ + if (capability.supportedPageSizes != nullptr) { + for (uint32_t i = 0; i < capability.supportedPageSizesCount; i++) { + SAFE_DELETE_ARRAY(capability.supportedPageSizes[i].id); + SAFE_DELETE_ARRAY(capability.supportedPageSizes[i].name); + } + SAFE_DELETE_ARRAY(capability.supportedPageSizes); + } + capability.supportedPageSizesCount = 0; +} + +void ReleaseCapability(Print_PrinterCapability &capability) +{ + ReleaseCapabilityPageSizes(capability); + SAFE_DELETE_ARRAY(capability.supportedColorModes); + capability.supportedColorModesCount = 0; + SAFE_DELETE_ARRAY(capability.supportedDuplexModes); + capability.supportedDuplexModesCount = 0; + SAFE_DELETE_ARRAY(capability.supportedMediaTypes); + SAFE_DELETE_ARRAY(capability.supportedQualities); + capability.supportedQualitiesCount = 0; + SAFE_DELETE_ARRAY(capability.supportedPaperSources); + SAFE_DELETE_ARRAY(capability.supportedResolutions); + capability.supportedResolutionsCount = 0; + SAFE_DELETE_ARRAY(capability.supportedOrientations); + capability.supportedOrientationsCount = 0; + SAFE_DELETE_ARRAY(capability.advancedCapability); +} + +void ReleaseDefaultValue(Print_DefaultValue &defaultValue) +{ + SAFE_DELETE_ARRAY(defaultValue.defaultPageSizeId); + SAFE_DELETE_ARRAY(defaultValue.defaultMediaType); + SAFE_DELETE_ARRAY(defaultValue.defaultPaperSource); + SAFE_DELETE_ARRAY(defaultValue.otherDefaultValues); +} + +void ReleasePrinterInfo(Print_PrinterInfo &printerInfo) +{ + SAFE_DELETE_ARRAY(printerInfo.printerId); + SAFE_DELETE_ARRAY(printerInfo.printerName); + SAFE_DELETE_ARRAY(printerInfo.description); + SAFE_DELETE_ARRAY(printerInfo.location); + SAFE_DELETE_ARRAY(printerInfo.makeAndModel); + SAFE_DELETE_ARRAY(printerInfo.printerUri); + SAFE_DELETE_ARRAY(printerInfo.detailInfo); + ReleaseCapability(printerInfo.capability); + ReleaseDefaultValue(printerInfo.defaultValue); +} + +void PageSizeArrayConvert(const nlohmann::json &pageSizeJsonArray, Print_PrinterInfo &nativePrinterInfo) +{ + ReleaseCapabilityPageSizes(nativePrinterInfo.capability); + PRINT_HILOGI("pageSizeJsonArray size = %{public}zu", pageSizeJsonArray.size()); + std::vector pageSizeVector; + for (auto &item : pageSizeJsonArray) { + Print_PageSize pageSize = {0}; + if (!item.contains("id") || !item.contains("name") || !item.contains("width") || !item.contains("height")) { + PRINT_HILOGW("field missing"); + continue; + } + if (!item["id"].is_string() || !item["name"].is_string() || !item["width"].is_number() || + !item["height"].is_number()) { + PRINT_HILOGW("incorrect type"); + continue; + } + pageSize.id = CopyString(item["id"].get()); + pageSize.name = CopyString(item["name"].get()); + pageSize.width = item["width"]; + pageSize.height = item["height"]; + pageSizeVector.push_back(pageSize); + } + nativePrinterInfo.capability.supportedPageSizes = CopyArray(pageSizeVector, + nativePrinterInfo.capability.supportedPageSizesCount); +} + +void ParseDefaultPageMargin(const nlohmann::json &cupsOpt, Print_Margin &defaultMargin) +{ + int leftMargin = 0; + int topMargin = 0; + int rightMargin = 0; + int bottomMargin = 0; + if (cupsOpt.contains("media-left-margin-supported")) { + std::string mediaLeftMargin = cupsOpt["media-left-margin-supported"].get(); + ConvertStringToInt(mediaLeftMargin.c_str(), leftMargin); + } + if (cupsOpt.contains("media-top-margin-supported")) { + std::string mediaTopMargin = cupsOpt["media-top-margin-supported"].get(); + ConvertStringToInt(mediaTopMargin.c_str(), topMargin); + } + if (cupsOpt.contains("media-right-margin-supported")) { + std::string mediaRightMargin = cupsOpt["media-right-margin-supported"].get(); + ConvertStringToInt(mediaRightMargin.c_str(), rightMargin); + } + if (cupsOpt.contains("media-bottom-margin-supported")) { + std::string mediaBottomMargin = cupsOpt["media-bottom-margin-supported"].get(); + ConvertStringToInt(mediaBottomMargin.c_str(), bottomMargin); + } + defaultMargin.leftMargin = static_cast(leftMargin); + defaultMargin.topMargin = static_cast(topMargin); + defaultMargin.rightMargin = static_cast(rightMargin); + defaultMargin.bottomMargin = static_cast(bottomMargin); +} + +void ParseMediaOpt(const nlohmann::json &cupsOpt, Print_PrinterInfo &nativePrinterInfo) +{ + if (cupsOpt.contains("defaultPageSizeId")) { + std::string defaultPageSizeId = cupsOpt["defaultPageSizeId"].get(); + PRINT_HILOGD("defaultPageSizeId %{public}s", defaultPageSizeId.c_str()); + nativePrinterInfo.defaultValue.defaultPageSizeId = CopyString(defaultPageSizeId); + } + if (cupsOpt.contains("media-type-supported")) { + std::string mediaTypeSupported = cupsOpt["media-type-supported"].get(); + PRINT_HILOGD("cupsOptionsStr media-type-supported %{public}s", mediaTypeSupported.c_str()); + nativePrinterInfo.capability.supportedMediaTypes = CopyString(mediaTypeSupported); + } + if (cupsOpt.contains("media-type-default")) { + std::string mediaTypeDefault = cupsOpt["media-type-default"].get(); + PRINT_HILOGD("cupsOptionsStr media-type-default %{public}s", mediaTypeDefault.c_str()); + nativePrinterInfo.defaultValue.defaultMediaType = CopyString(mediaTypeDefault); + } + if (cupsOpt.contains("media-source-default")) { + std::string mediaSourceDefault = cupsOpt["media-source-default"].get(); + PRINT_HILOGD("cupsOptionsStr media-source-default %{public}s", mediaSourceDefault.c_str()); + nativePrinterInfo.defaultValue.defaultPaperSource = CopyString(mediaSourceDefault); + } + if (cupsOpt.contains("media-source-supported")) { + std::string mediaSourceSupported = cupsOpt["media-source-supported"].get(); + PRINT_HILOGD("cupsOptionsStr media-source-supported %{public}s", mediaSourceSupported.c_str()); + nativePrinterInfo.capability.supportedPaperSources = CopyString(mediaSourceSupported); + } +} + +void ParseColorModeArray(const nlohmann::json &arrayObject, Print_PrinterInfo &nativePrinterInfo) +{ + std::vector list; + std::string key = "color"; + ConvertJsonArrayToIntList(arrayObject, key, list); + nativePrinterInfo.capability.supportedColorModes = CopyArray( + list, nativePrinterInfo.capability.supportedColorModesCount, ConvertColorMode); +} + +void ParseDuplexModeArray(const nlohmann::json &arrayObject, Print_PrinterInfo &nativePrinterInfo) +{ + std::vector list; + std::string key = "duplex"; + ConvertJsonArrayToIntList(arrayObject, key, list); + nativePrinterInfo.capability.supportedDuplexModes = CopyArray( + list, nativePrinterInfo.capability.supportedDuplexModesCount, ConvertDuplexMode); +} + +void ParseQualityArray(const nlohmann::json &arrayObject, Print_PrinterInfo &nativePrinterInfo) +{ + std::vector list; + std::string key = "quality"; + ConvertJsonArrayToIntList(arrayObject, key, list); + nativePrinterInfo.capability.supportedQualities = + CopyArray(list, nativePrinterInfo.capability.supportedQualitiesCount, ConvertQuality); +} + +bool ParseResolutionObject(const nlohmann::json &jsonObject, Print_Resolution &resolution) +{ + if (!jsonObject.contains("horizontalDpi")) { + PRINT_HILOGW("horizontalDpi missing"); + return false; + } + if (!jsonObject["horizontalDpi"].is_number()) { + PRINT_HILOGW("horizontalDpi is not string"); + return false; + } + int xDpi = jsonObject["horizontalDpi"]; + if (!jsonObject.contains("verticalDpi")) { + PRINT_HILOGW("verticalDpi missing"); + return false; + } + if (!jsonObject["verticalDpi"].is_number()) { + PRINT_HILOGW("verticalDpi is not string"); + return false; + } + int yDpi = jsonObject["verticalDpi"]; + resolution.horizontalDpi = static_cast(xDpi); + resolution.verticalDpi = static_cast(yDpi); + return true; +} + +void ParseResolutionArray(const nlohmann::json &arrayObject, Print_PrinterInfo &nativePrinterInfo) +{ + std::vector list; + PRINT_HILOGI("ParseResolutionArray arrayObject size = %{public}zu", arrayObject.size()); + for (auto &item : arrayObject) { + Print_Resolution resolution; + if (!ParseResolutionObject(item, resolution)) { + PRINT_HILOGW("ParseResolutionObject fail"); + continue; + } + list.push_back(resolution); + } + nativePrinterInfo.capability.supportedResolutions = + CopyArray(list, nativePrinterInfo.capability.supportedResolutionsCount); +} + +void ParsePrinterOpt(const nlohmann::json &cupsOpt, Print_PrinterInfo &nativePrinterInfo) +{ + if (cupsOpt.contains("printer-location")) { + std::string pLocation = cupsOpt["printer-location"].get(); + PRINT_HILOGD("printer-location: %{public}s", pLocation.c_str()); + nativePrinterInfo.location = CopyString(pLocation); + } + std::string keyword = "orientation-requested-supported"; + if (cupsOpt.contains(keyword)) { + std::string orientationArray = cupsOpt[keyword].get(); + PRINT_HILOGD("supported orientations: %{public}s", orientationArray.c_str()); + std::vector orientationVector = Str2Vec(orientationArray); + nativePrinterInfo.capability.supportedOrientations = CopyArray( + orientationVector, nativePrinterInfo.capability.supportedOrientationsCount, ConvertOrientationMode); + } + keyword = "orientation-requested-default"; + if (cupsOpt.contains(keyword)) { + std::string orientationString = cupsOpt[keyword].get(); + PRINT_HILOGD("default orientation: %{public}s", orientationString.c_str()); + int orientationValue = 0; + if (ConvertStringToInt(orientationString.c_str(), orientationValue)) { + uint32_t defaultOrientation = static_cast(orientationValue); + ConvertOrientationMode(defaultOrientation, nativePrinterInfo.defaultValue.defaultOrientation); + } + } + keyword = "printer-resolution-supported"; + ParseJsonFieldAsArrayOpt(cupsOpt, keyword, nativePrinterInfo, ParseResolutionArray); + keyword = "printer-resolution-default"; + if (cupsOpt.contains(keyword)) { + std::string resolutionString = cupsOpt[keyword].get(); + if (json::accept(resolutionString)) { + nlohmann::json resolutionJson = json::parse(resolutionString); + if (!ParseResolutionObject(resolutionJson, nativePrinterInfo.defaultValue.defaultResolution)) { + PRINT_HILOGW("ParseResolutionObject fail"); + } + } + } + keyword = "print-color-mode-supported"; + ParseJsonFieldAsArrayOpt(cupsOpt, keyword, nativePrinterInfo, ParseColorModeArray); +} + +void ParseCupsCopyOpt(const nlohmann::json &cupsOpt, Print_PrinterInfo &nativePrinterInfo) +{ + std::string keyword = "sides-supported"; + ParseJsonFieldAsArrayOpt(cupsOpt, keyword, nativePrinterInfo, ParseDuplexModeArray); + + keyword = "print-quality-supported"; + ParseJsonFieldAsArrayOpt(cupsOpt, keyword, nativePrinterInfo, ParseQualityArray); + if (cupsOpt.contains("copies-default")) { + std::string defaultCopies = cupsOpt["copies-default"].get(); + nativePrinterInfo.defaultValue.defaultCopies = std::stoul(defaultCopies); + PRINT_HILOGD("ParseCupsCopyOpt copies-default: %{public}s", defaultCopies.c_str()); + } + if (cupsOpt.contains("copies-supported")) { + std::string copySupport = cupsOpt["copies-supported"].get(); + nativePrinterInfo.capability.supportedCopies = std::stoul(copySupport); + PRINT_HILOGD("ParseCupsCopyOpt copies-supported: %{public}s", copySupport.c_str()); + } +} + +void ParseCupsOptions(const nlohmann::json &cupsOpt, Print_PrinterInfo &nativePrinterInfo) +{ + ParsePrinterOpt(cupsOpt, nativePrinterInfo); + ParseDefaultPageMargin(cupsOpt, nativePrinterInfo.defaultValue.defaultMargin); + ParseCupsCopyOpt(cupsOpt, nativePrinterInfo); + ParseMediaOpt(cupsOpt, nativePrinterInfo); + std::string keyword = "supportedPageSizeArray"; + ParseJsonFieldAsArrayOpt(cupsOpt, keyword, nativePrinterInfo, PageSizeArrayConvert); + nlohmann::json advancedCapJson; + keyword = "multiple-document-handling-supported"; + AddJsonFieldStringToJsonObject(cupsOpt, keyword, advancedCapJson); + nativePrinterInfo.capability.advancedCapability = CopyString(advancedCapJson.dump().c_str()); +} + +int32_t ParseInfoOption(const std::string &infoOption, Print_PrinterInfo &nativePrinterInfo) +{ + if (!json::accept(infoOption)) { + PRINT_HILOGW("infoOption can not parse to json object"); + return E_PRINT_INVALID_PARAMETER; + } + nlohmann::json infoJson = json::parse(infoOption); + if (!infoJson.contains("printerUri") || !infoJson.contains("make")) { + PRINT_HILOGW("The infoJson does not have a necessary attribute."); + return E_PRINT_INVALID_PARAMETER; + } + nativePrinterInfo.makeAndModel = CopyString(infoJson["make"].get()); + nativePrinterInfo.printerUri = CopyString(infoJson["printerUri"].get()); + if (!infoJson.contains("cupsOptions")) { + PRINT_HILOGW("The infoJson does not have a cupsOptions attribute."); + return E_PRINT_NONE; + } + nlohmann::json cupsOpt = infoJson["cupsOptions"]; + ParseCupsOptions(cupsOpt, nativePrinterInfo); + return E_PRINT_NONE; +} +Print_PrinterInfo *ConvertToNativePrinterInfo(const PrinterInfo &info) +{ + Print_PrinterInfo *nativePrinterInfo = new (std::nothrow) Print_PrinterInfo; + if (nativePrinterInfo == nullptr) { + PRINT_HILOGW("Print_PrinterInfo allocate fail."); + return nullptr; + } + if (memset_s(nativePrinterInfo, sizeof(Print_PrinterInfo), 0, sizeof(Print_PrinterInfo)) != 0) { + PRINT_HILOGW("Print_PrinterInfo memset_s fail."); + delete nativePrinterInfo; + nativePrinterInfo = nullptr; + return nullptr; + } + nativePrinterInfo->printerId = CopyString(info.GetPrinterId()); + nativePrinterInfo->printerName = CopyString(info.GetPrinterName()); + nativePrinterInfo->description = CopyString(info.GetDescription()); + nativePrinterInfo->detailInfo = nullptr; + nativePrinterInfo->printerState = ConvertPrinterState(info.GetPrinterState()); + OHOS::Print::PrinterCapability cap; + info.GetCapability(cap); + ConvertColorMode(cap.GetColorMode(), nativePrinterInfo->defaultValue.defaultColorMode); + ConvertDuplexMode(cap.GetDuplexMode(), nativePrinterInfo->defaultValue.defaultDuplexMode); + if (info.HasOption()) { + std::string infoOpt = info.GetOption(); + PRINT_HILOGW("infoOpt json object: %{public}s", infoOpt.c_str()); + ParseInfoOption(infoOpt, *nativePrinterInfo); + } + return nativePrinterInfo; +} + +void SetPrintOrientationInPrintJob(const Print_PrintJob &nativePrintJob, PrintJob &printJob) +{ + uint32_t ori = static_cast(nativePrintJob.orientationMode); + if (ori == ORIENTATION_MODE_PORTRAIT || ori == ORIENTATION_MODE_REVERSE_PORTRAIT) { + printJob.SetIsLandscape(false); + printJob.SetIsSequential(true); + } else if (ori == ORIENTATION_MODE_LANDSCAPE || ori == ORIENTATION_MODE_REVERSE_LANDSCAPE) { + printJob.SetIsLandscape(true); + printJob.SetIsSequential(false); + } +} + +void SetPrintMarginInPrintJob(const Print_PrintJob &nativePrintJob, PrintJob &printJob) +{ + PrintMargin margin; + if (nativePrintJob.printMargin.topMargin > 0) { + margin.SetTop(nativePrintJob.printMargin.topMargin); + } else { + margin.SetTop(0); + } + if (nativePrintJob.printMargin.rightMargin > 0) { + margin.SetRight(nativePrintJob.printMargin.rightMargin); + } else { + margin.SetRight(0); + } + if (nativePrintJob.printMargin.bottomMargin > 0) { + margin.SetBottom(nativePrintJob.printMargin.bottomMargin); + } else { + margin.SetBottom(0); + } + if (nativePrintJob.printMargin.leftMargin > 0) { + margin.SetLeft(nativePrintJob.printMargin.leftMargin); + } else { + margin.SetLeft(0); + } + printJob.SetMargin(margin); +} + +bool SetPrintPageSizeInPrintJob(const Print_PrintJob &nativePrintJob, PrintJob &printJob) +{ + PRINT_HILOGI("SetPrintPageSizeInPrintJob in."); + if (nativePrintJob.pageSizeId == nullptr) { + PRINT_HILOGW("page size is null."); + return false; + } + std::string pageSizeId(nativePrintJob.pageSizeId); + PrintPageSize pageSize; + printJob.SetPageSize(pageSize); + PRINT_HILOGI("SetPrintPageSizeInPrintJob out."); + return true; +} + +void SetOptionInPrintJob(const Print_PrintJob &nativePrintJob, PrintJob &printJob) +{ + PRINT_HILOGI("SetOptionInPrintJob in."); + nlohmann::json jsonOptions; + if (nativePrintJob.jobName != nullptr) { + jsonOptions["jobName"] = std::string(nativePrintJob.jobName); + } + if (nativePrintJob.mediaType != nullptr) { + jsonOptions["mediaType"] = std::string(nativePrintJob.mediaType); + } + jsonOptions["borderless"] = nativePrintJob.borderless ? "true" : "false"; + jsonOptions["printQuality"] = nativePrintJob.printQuality; + jsonOptions["documentFormat"] = GetDocumentFormatString(nativePrintJob.documentFormat); + if (nativePrintJob.advancedOptions != nullptr) { + jsonOptions["cupsOptions"] = std::string(nativePrintJob.advancedOptions); + } + std::string option = jsonOptions.dump(); + PRINT_HILOGD("SetOptionInPrintJob %{public}s", option.c_str()); + printJob.SetOption(option); + PRINT_HILOGI("SetOptionInPrintJob out."); +} + +int32_t ConvertNativeJobToPrintJob(const Print_PrintJob &nativePrintJob, PrintJob &printJob) +{ + if (nativePrintJob.fdList == nullptr || nativePrintJob.copyNumber <= 0) { + PRINT_HILOGW("ConvertNativeJobToPrintJob invalid param error."); + return E_PRINT_INVALID_PARAMETER; + } + if (!IsValidString(nativePrintJob.printerId)) { + PRINT_HILOGW("ConvertNativeJobToPrintJob string empty error."); + return E_PRINT_INVALID_PARAMETER; + } + std::vector fdList; + for (uint32_t i = 0; i < nativePrintJob.fdListCount; i++) { + fdList.emplace_back(nativePrintJob.fdList[i]); + } + printJob.SetFdList(fdList); + printJob.SetPrinterId(std::string(nativePrintJob.printerId)); + printJob.SetCopyNumber(nativePrintJob.copyNumber); + printJob.SetDuplexMode(static_cast(nativePrintJob.duplexMode)); + printJob.SetColorMode(static_cast(nativePrintJob.colorMode)); + + SetPrintOrientationInPrintJob(nativePrintJob, printJob); + SetPrintMarginInPrintJob(nativePrintJob, printJob); + SetPrintPageSizeInPrintJob(nativePrintJob, printJob); + SetOptionInPrintJob(nativePrintJob, printJob); + return E_PRINT_NONE; +} + +Print_ErrorCode ConvertStringVectorToPropertyList(const std::vector &valueList, + Print_PropertyList *propertyList) +{ + if (valueList.size() == 0) { + PRINT_HILOGW("empty valueList"); + return PRINT_ERROR_INVALID_PRINTER; + } + propertyList->list = new (std::nothrow) Print_Property[valueList.size()]; + if (propertyList->list == nullptr) { + PRINT_HILOGW("propertyList->list is null"); + return PRINT_ERROR_GENERIC_FAILURE; + } + if (memset_s(propertyList->list, valueList.size() * sizeof(Print_Property), 0, + valueList.size() * sizeof(Print_Property)) != 0) { + PRINT_HILOGW("memset_s fail"); + delete[] propertyList->list; + propertyList->list = nullptr; + return PRINT_ERROR_GENERIC_FAILURE; + } + uint32_t count = 0; + for (size_t i = 0; i < valueList.size(); i++) { + std::string keyVal = valueList[i]; + auto index = keyVal.find('&'); + if (index == keyVal.npos) { + continue; + } + propertyList->list[count].key = CopyString(keyVal.substr(0, index)); + propertyList->list[count].value = CopyString(keyVal.substr(index + 1)); + count++; + } + propertyList->count = count; + return PRINT_ERROR_NONE; +} +} // namespace OHOS::Print diff --git a/utils/include/print_constant.h b/utils/include/print_constant.h index eea0ffd..33a7623 100644 --- a/utils/include/print_constant.h +++ b/utils/include/print_constant.h @@ -195,5 +195,7 @@ enum PrintPageType { PAGE_INT_DL_ENVELOPE = 10, PAGE_B_TABLOID = 11, }; +const std::string PRINTER_DISCOVER_EVENT_TYPE = "printerDiscover"; +const std::string PRINTER_CHANGE_EVENT_TYPE = "printerChange"; } // namespace OHOS::Print -#endif // PRINT_CONSTANT_H \ No newline at end of file +#endif // PRINT_CONSTANT_H