!302 支持厂商拓展云打印

Merge pull request !302 from 郑志豪/master
This commit is contained in:
openharmony_ci 2024-08-24 11:15:29 +00:00 committed by Gitee
commit 39b77ead76
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
41 changed files with 2081 additions and 554 deletions

View File

@ -15,22 +15,102 @@
#ifndef PRINTER_CAPABILITY_HELPER_H
#define PRINTER_CAPABILITY_HELPER_H
#define MAX_ARRAY_LENGTH 128
#include <map>
#include "napi/native_api.h"
#include "printer_capability.h"
#include "print_log.h"
#include "napi_print_utils.h"
namespace OHOS::Print {
class PrinterCapabilityHelper {
public:
static napi_value MakeJsObject(napi_env env, const PrinterCapability &cap);
static std::shared_ptr<PrinterCapability> BuildFromJs(napi_env env, napi_value jsValue);
static std::shared_ptr<PrinterCapability> BuildFromJsSecond(napi_env env, napi_value jsValue,
napi_value jsPageSizes, std::shared_ptr<PrinterCapability> nativeObj);
static bool BuildSimplePropertyFromJs(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool BuildArrayPropertyFromJs(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
private:
static bool CreatePageSizeList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool CreateResolutionList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool CreateSupportedColorModeList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool CreateSupportedDuplexModeList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool CreateSupportedMediaTypeList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool CreateSupportedQualityList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool CreateSupportedOrientationList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap);
static bool buildSupportedPageSizes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool buildSupportedResolutions(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool buildSupportedColorModes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool buildSupportedDuplexModes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool buildSupportedQualities(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool buildSupportedMediaTypes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool buildSupportedOrientations(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj);
static bool ValidateProperty(napi_env env, napi_value object);
template<typename T>
static bool ProcessJsArrayProperty(napi_env env, napi_value jsValue, const char *propertyName,
std::function<void(const std::vector<T> &)> setFunction,
std::function<std::shared_ptr<T>(napi_env, napi_value)> buildFunction)
{
if (!setFunction) {
PRINT_HILOGE("setFunction is illegal");
return false;
}
if (!buildFunction) {
PRINT_HILOGE("buildFunction is illegal");
return false;
}
napi_value jsArray;
bool hasProperty = NapiPrintUtils::HasNamedProperty(env, jsValue, propertyName);
if (!hasProperty) {
return true;
}
napi_status status = napi_get_named_property(env, jsValue, propertyName, &jsArray);
if (status != napi_ok) {
return false;
}
bool isArray = false;
napi_is_array(env, jsArray, &isArray);
if (!isArray) {
PRINT_HILOGE("Can not get an array for property %{public}s", propertyName);
return false;
}
uint32_t length = 0;
napi_get_array_length(env, jsArray, &length);
if (length > MAX_ARRAY_LENGTH) {
PRINT_HILOGE("the array length is over %{public}d", MAX_ARRAY_LENGTH);
return false;
}
std::vector<T> items;
items.reserve(length);
for (uint32_t i = 0; i < length; ++i) {
napi_value jsItem;
napi_get_element(env, jsArray, i, &jsItem);
auto item = buildFunction(env, jsItem);
if (!item) {
PRINT_HILOGE("Failed to build item for property %{public}s", propertyName);
return false;
}
items.push_back(*item);
}
setFunction(items);
return true;
}
};
} // namespace OHOS::Print
#endif // PRINTER_CAPABILITY_HELPER_H

View File

@ -328,7 +328,7 @@ size_t NapiPrintUtils::GetJsVal(napi_env env, napi_callback_info info, napi_valu
bool NapiPrintUtils::VerifyProperty(
std::vector<std::string> &names, std::map<std::string, PrintParamStatus> &propertyList)
{
for (auto name : names) {
for (const auto& name : names) {
if (propertyList.find(name) == propertyList.end()) {
PRINT_HILOGE("Invalid property: %{public}s", name.c_str());
return false;
@ -336,9 +336,9 @@ bool NapiPrintUtils::VerifyProperty(
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());
for (const auto& propertyItem : propertyList) {
if (propertyItem.second == PRINT_PARAM_NOT_SET) {
PRINT_HILOGE("Missing Property: %{public}s", propertyItem.first.c_str());
return false;
}
}

View File

@ -16,6 +16,7 @@
#include "napi_print_utils.h"
#include "print_constant.h"
#include "print_log.h"
#include "print_utils.h"
#include "print_margin_helper.h"
#include "print_page_size_helper.h"
#include "print_resolution_helper.h"
@ -27,6 +28,12 @@ static constexpr const char *PARAM_CAPABILITY_PAGESIZE = "pageSize";
static constexpr const char *PARAM_CAPABILITY_RESOLUTION = "resolution";
static constexpr const char *PARAM_CAPABILITY_MINMARGIN = "minMargin";
static constexpr const char *PARAM_CAPABILITY_OPTION = "options";
static constexpr const char *PARAM_CAPABILITY_SUPPORTED_PAGESIZES = "supportedPageSizes";
static constexpr const char *PARAM_CAPABILITY_SUPPORTED_COLORMODES = "supportedColorModes";
static constexpr const char *PARAM_CAPABILITY_SUPPORTED_DUPLEXMODES = "supportedDuplexModes";
static constexpr const char *PARAM_CAPABILITY_SUPPORTED_MEDIA_TYPES = "supportedMediaTypes";
static constexpr const char *PARAM_CAPABILITY_SUPPORTED_QUALITIES = "supportedQualities";
static constexpr const char *PARAM_CAPABILITY_SUPPORTED_ORIENTATIONS = "supportedOrientations";
napi_value PrinterCapabilityHelper::MakeJsObject(napi_env env, const PrinterCapability &cap)
{
@ -41,114 +48,56 @@ napi_value PrinterCapabilityHelper::MakeJsObject(napi_env env, const PrinterCapa
CreateResolutionList(env, jsObj, cap);
}
if (cap.HasSupportedColorMode()) {
CreateSupportedColorModeList(env, jsObj, cap);
}
if (cap.HasSupportedDuplexMode()) {
CreateSupportedDuplexModeList(env, jsObj, cap);
}
if (cap.HasSupportedMediaType()) {
CreateSupportedMediaTypeList(env, jsObj, cap);
}
if (cap.HasSupportedQuality()) {
CreateSupportedQualityList(env, jsObj, cap);
}
if (cap.HasSupportedOrientation()) {
CreateSupportedOrientationList(env, jsObj, cap);
}
if (cap.HasMargin()) {
PrintMargin margin;
cap.GetMinMargin(margin);
napi_value jsMargin = PrintMarginHelper::MakeJsObject(env, margin);
PRINT_CALL(env, napi_set_named_property(env, jsObj, PARAM_CAPABILITY_MINMARGIN, jsMargin));
}
if (cap.HasOption()) {
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_CAPABILITY_OPTION, cap.GetOption());
}
return jsObj;
}
std::shared_ptr<PrinterCapability> PrinterCapabilityHelper::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrinterCapability>();
if (!ValidateProperty(env, jsValue)) {
PRINT_HILOGE("Invalid property of printer capability");
return nullptr;
}
uint32_t colorMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_CAPABILITY_COLORMODE);
uint32_t duplexMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_CAPABILITY_DUPLEXMODE);
nativeObj->SetColorMode(colorMode);
nativeObj->SetDuplexMode(duplexMode);
napi_value jsPageSizes = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_PAGESIZE);
bool isArray = false;
napi_is_array(env, jsPageSizes, &isArray);
if (!isArray) {
PRINT_HILOGE("Invalid list of page size");
return nullptr;
}
std::vector<PrintPageSize> pageSizes;
uint32_t arrayLength = 0;
napi_get_array_length(env, jsPageSizes, &arrayLength);
for (uint32_t index = 0; index < arrayLength; index++) {
napi_value jsPageSize;
napi_get_element(env, jsPageSizes, index, &jsPageSize);
auto pageSizePtr = PrintPageSizeHelper::BuildFromJs(env, jsPageSize);
if (pageSizePtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return nullptr;
}
pageSizes.emplace_back(*pageSizePtr);
}
nativeObj->SetPageSize(pageSizes);
auto jsOption = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_OPTION);
if (jsOption != nullptr) {
nativeObj->SetOption(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_CAPABILITY_OPTION));
}
PRINT_HILOGI("Build Print Capability succeed");
return BuildFromJsSecond(env, jsValue, jsPageSizes, nativeObj);
}
std::shared_ptr<PrinterCapability> PrinterCapabilityHelper::BuildFromJsSecond(napi_env env, napi_value jsValue,
napi_value jsPageSizes, std::shared_ptr<PrinterCapability> nativeObj)
{
napi_value jsResolutionList = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_RESOLUTION);
if (jsResolutionList != nullptr) {
bool isArray = false;
napi_is_array(env, jsResolutionList, &isArray);
if (!isArray) {
PRINT_HILOGE("Invalid list of print resolution");
return nullptr;
}
std::vector<PrintResolution> resolutionList;
uint32_t arrayLength = 0;
napi_get_array_length(env, jsPageSizes, &arrayLength);
for (uint32_t index = 0; index < arrayLength; index++) {
napi_value jsResolution;
napi_get_element(env, jsResolutionList, index, &jsResolution);
auto resolutionPtr = PrintResolutionHelper::BuildFromJs(env, jsResolution);
if (resolutionPtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return nullptr;
}
resolutionList.emplace_back(*resolutionPtr);
}
nativeObj->SetResolution(resolutionList);
}
napi_value jsMargin = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_MINMARGIN);
if (jsMargin != nullptr) {
auto marginPtr = PrintMarginHelper::BuildFromJs(env, jsMargin);
if (marginPtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return nullptr;
}
nativeObj->SetMinMargin(*marginPtr);
}
return nativeObj;
}
bool PrinterCapabilityHelper::CreatePageSizeList(napi_env env, napi_value &jsPrinterCap, const PrinterCapability &cap)
{
napi_value jsPageSizes = nullptr;
PRINT_CALL_BASE(env, napi_create_array(env, &jsPageSizes), false);
std::vector<PrintPageSize> pageSizeList;
cap.GetPageSize(pageSizeList);
cap.GetSupportedPageSize(pageSizeList);
uint32_t arrLength = pageSizeList.size();
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = PrintPageSizeHelper::MakeJsObject(env, pageSizeList[index]);
PRINT_CALL_BASE(env, napi_set_element(env, jsPageSizes, index, value), false);
}
PRINT_CALL_BASE(env, napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_PAGESIZE, jsPageSizes), false);
PRINT_CALL_BASE(
env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_SUPPORTED_PAGESIZES, jsPageSizes),
false);
return true;
}
@ -168,18 +117,263 @@ bool PrinterCapabilityHelper::CreateResolutionList(napi_env env, napi_value &jsP
return true;
}
bool PrinterCapabilityHelper::CreateSupportedColorModeList(napi_env env, napi_value& jsPrinterCap,
const PrinterCapability& cap)
{
napi_value jsSupportedColorModeList = nullptr;
PRINT_CALL_BASE(env, napi_create_array(env, &jsSupportedColorModeList), false);
std::vector<uint32_t> supportedColorModeList;
cap.GetSupportedColorMode(supportedColorModeList);
uint32_t arrLength = static_cast<uint32_t>(supportedColorModeList.size());
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = NapiPrintUtils::CreateUint32(env, supportedColorModeList[index]);
PRINT_CALL_BASE(env, napi_set_element(env, jsSupportedColorModeList, index, value), false);
}
PRINT_CALL_BASE(
env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_SUPPORTED_COLORMODES, jsSupportedColorModeList),
false);
return true;
}
bool PrinterCapabilityHelper::CreateSupportedDuplexModeList(napi_env env, napi_value& jsPrinterCap,
const PrinterCapability& cap)
{
napi_value jsSupportedDuplexModeList = nullptr;
PRINT_CALL_BASE(env, napi_create_array(env, &jsSupportedDuplexModeList), false);
std::vector<uint32_t> supportedDuplexModeList;
cap.GetSupportedDuplexMode(supportedDuplexModeList);
uint32_t arrLength = static_cast<uint32_t>(supportedDuplexModeList.size());
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = NapiPrintUtils::CreateUint32(env, supportedDuplexModeList[index]);
PRINT_CALL_BASE(env, napi_set_element(env, jsSupportedDuplexModeList, index, value), false);
}
PRINT_CALL_BASE(
env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_SUPPORTED_DUPLEXMODES, jsSupportedDuplexModeList),
false);
return true;
}
bool PrinterCapabilityHelper::CreateSupportedMediaTypeList(napi_env env, napi_value& jsPrinterCap,
const PrinterCapability& cap)
{
napi_value jsSupportedMediaTypeList = nullptr;
PRINT_CALL_BASE(env, napi_create_array(env, &jsSupportedMediaTypeList), false);
std::vector<std::string> supportedMediaTypeList;
cap.GetSupportedMediaType(supportedMediaTypeList);
uint32_t arrLength = static_cast<uint32_t>(supportedMediaTypeList.size());
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = NapiPrintUtils::CreateStringUtf8(env, supportedMediaTypeList[index]);
PRINT_CALL_BASE(env, napi_set_element(env, jsSupportedMediaTypeList, index, value), false);
}
PRINT_CALL_BASE(
env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_SUPPORTED_MEDIA_TYPES, jsSupportedMediaTypeList),
false);
return true;
}
bool PrinterCapabilityHelper::CreateSupportedQualityList(napi_env env, napi_value& jsPrinterCap,
const PrinterCapability& cap)
{
napi_value jsSupportedQualitiesList = nullptr;
PRINT_CALL_BASE(env, napi_create_array(env, &jsSupportedQualitiesList), false);
std::vector<uint32_t> supportedQualitiesList;
cap.GetSupportedQuality(supportedQualitiesList);
uint32_t arrLength = static_cast<uint32_t>(supportedQualitiesList.size());
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = NapiPrintUtils::CreateUint32(env, supportedQualitiesList[index]);
PRINT_CALL_BASE(env, napi_set_element(env, jsSupportedQualitiesList, index, value), false);
}
PRINT_CALL_BASE(
env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_SUPPORTED_QUALITIES, jsSupportedQualitiesList),
false);
return true;
}
bool PrinterCapabilityHelper::CreateSupportedOrientationList(napi_env env, napi_value& jsPrinterCap,
const PrinterCapability& cap)
{
napi_value jsSupportedOrientationList = nullptr;
PRINT_CALL_BASE(env, napi_create_array(env, &jsSupportedOrientationList), false);
std::vector<uint32_t> supportedOrientationList;
cap.GetSupportedQuality(supportedOrientationList);
uint32_t arrLength = static_cast<uint32_t>(supportedOrientationList.size());
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = NapiPrintUtils::CreateUint32(env, supportedOrientationList[index]);
PRINT_CALL_BASE(env, napi_set_element(env, jsSupportedOrientationList, index, value), false);
}
PRINT_CALL_BASE(
env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_SUPPORTED_ORIENTATIONS, jsSupportedOrientationList),
false);
return true;
}
std::shared_ptr<PrinterCapability> PrinterCapabilityHelper::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrinterCapability>();
if (!ValidateProperty(env, jsValue)) {
PRINT_HILOGE("Invalid property of printer capability");
return nullptr;
}
if (!BuildSimplePropertyFromJs(env, jsValue, nativeObj)) {
PRINT_HILOGE("BuildSimplePropertyFromJs error");
return nullptr;
}
if (!BuildArrayPropertyFromJs(env, jsValue, nativeObj)) {
PRINT_HILOGE("BuildArrayPropertyFromJs error");
return nullptr;
}
PRINT_HILOGI("Build Print Capability succeed");
return nativeObj;
}
bool PrinterCapabilityHelper::BuildSimplePropertyFromJs(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
uint32_t colorMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_CAPABILITY_COLORMODE);
if (colorMode) {
nativeObj->SetColorMode(colorMode);
}
uint32_t duplexMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_CAPABILITY_DUPLEXMODE);
if (duplexMode) {
nativeObj->SetDuplexMode(duplexMode);
}
napi_value jsMargin = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_MINMARGIN);
if (jsMargin != nullptr) {
auto marginPtr = PrintMarginHelper::BuildFromJs(env, jsMargin);
if (marginPtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return false;
}
nativeObj->SetMinMargin(*marginPtr);
}
auto jsOption = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_OPTION);
if (jsOption != nullptr) {
nativeObj->SetOption(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_CAPABILITY_OPTION));
}
return true;
}
bool PrinterCapabilityHelper::BuildArrayPropertyFromJs(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
if (!buildSupportedPageSizes(env, jsValue, nativeObj) ||
!buildSupportedResolutions(env, jsValue, nativeObj) ||
!buildSupportedColorModes(env, jsValue, nativeObj) ||
!buildSupportedDuplexModes(env, jsValue, nativeObj) ||
!buildSupportedQualities(env, jsValue, nativeObj) ||
!buildSupportedMediaTypes(env, jsValue, nativeObj) ||
!buildSupportedOrientations(env, jsValue, nativeObj)) {
return false;
}
return true;
}
bool PrinterCapabilityHelper::buildSupportedPageSizes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<PrintPageSize>(env, jsValue, PARAM_CAPABILITY_SUPPORTED_PAGESIZES,
[&](const std::vector<PrintPageSize>& pageSizes) {
nativeObj->SetSupportedPageSize(pageSizes);
},
PrintPageSizeHelper::BuildFromJs);
}
bool PrinterCapabilityHelper::buildSupportedResolutions(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<PrintResolution>(env, jsValue, PARAM_CAPABILITY_RESOLUTION,
[&](const std::vector<PrintResolution>& resolutions) {
nativeObj->SetResolution(resolutions);
},
PrintResolutionHelper::BuildFromJs);
}
bool PrinterCapabilityHelper::buildSupportedColorModes(napi_env env, napi_value jsValue,
std::shared_ptr <PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<uint32_t>(env, jsValue, PARAM_CAPABILITY_SUPPORTED_COLORMODES,
[&](const std::vector<uint32_t>& colorModes) { nativeObj->SetSupportedColorMode(colorModes); },
[](napi_env env, napi_value jsValue) -> std::shared_ptr<uint32_t> {
uint32_t colorMode = NapiPrintUtils::GetUint32FromValue(env, jsValue);
return std::make_shared<uint32_t>(colorMode);
});
}
bool PrinterCapabilityHelper::buildSupportedDuplexModes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<uint32_t>(env, jsValue, PARAM_CAPABILITY_SUPPORTED_DUPLEXMODES,
[&](const std::vector<uint32_t>& duplexModes) {
nativeObj->SetSupportedDuplexMode(duplexModes);
},
[](napi_env env, napi_value jsValue) -> std::shared_ptr<uint32_t> {
return std::make_shared<uint32_t>(NapiPrintUtils::GetUint32FromValue(env, jsValue));
});
}
bool PrinterCapabilityHelper::buildSupportedQualities(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<uint32_t>(env, jsValue, PARAM_CAPABILITY_SUPPORTED_QUALITIES,
[&](const std::vector<uint32_t>& qualities) {
nativeObj->SetSupportedQuality(qualities);
},
[](napi_env env, napi_value jsValue) -> std::shared_ptr<uint32_t> {
return std::make_shared<uint32_t>(NapiPrintUtils::GetUint32FromValue(env, jsValue));
});
}
bool PrinterCapabilityHelper::buildSupportedMediaTypes(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<std::string>(env, jsValue, PARAM_CAPABILITY_SUPPORTED_MEDIA_TYPES,
[&](const std::vector<std::string>& mediaTypes) {
nativeObj->SetSupportedMediaType(mediaTypes);
},
[](napi_env env, napi_value jsValue) -> std::shared_ptr<std::string> {
return std::make_shared<std::string>(NapiPrintUtils::GetStringFromValueUtf8(env, jsValue));
});
}
bool PrinterCapabilityHelper::buildSupportedOrientations(napi_env env, napi_value jsValue,
std::shared_ptr<PrinterCapability> nativeObj)
{
return ProcessJsArrayProperty<uint32_t>(env, jsValue, PARAM_CAPABILITY_SUPPORTED_ORIENTATIONS,
[&](const std::vector<uint32_t>& orientations) {
nativeObj->SetSupportedOrientation(orientations);
},
[](napi_env env, napi_value jsValue) -> std::shared_ptr<uint32_t> {
return std::make_shared<uint32_t>(NapiPrintUtils::GetUint32FromValue(env, jsValue));
});
}
bool PrinterCapabilityHelper::ValidateProperty(napi_env env, napi_value object)
{
std::map<std::string, PrintParamStatus> propertyList = {
{PARAM_CAPABILITY_COLORMODE, PRINT_PARAM_NOT_SET},
{PARAM_CAPABILITY_DUPLEXMODE, PRINT_PARAM_NOT_SET},
{PARAM_CAPABILITY_PAGESIZE, PRINT_PARAM_NOT_SET},
{PARAM_CAPABILITY_COLORMODE, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_DUPLEXMODE, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_PAGESIZE, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_RESOLUTION, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_MINMARGIN, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_OPTION, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_SUPPORTED_PAGESIZES, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_SUPPORTED_COLORMODES, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_SUPPORTED_DUPLEXMODES, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_SUPPORTED_MEDIA_TYPES, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_SUPPORTED_QUALITIES, PRINT_PARAM_OPT},
{PARAM_CAPABILITY_SUPPORTED_ORIENTATIONS, PRINT_PARAM_OPT},
};
auto names = NapiPrintUtils::GetPropertyNames(env, object);
return NapiPrintUtils::VerifyProperty(names, propertyList);
}
} // namespace OHOS::Print
} // namespace OHOS::Print

View File

@ -22,7 +22,7 @@
namespace OHOS::Print {
static constexpr const char *PARAM_INFO_PRINTERID = "printerId";
static constexpr const char *PARAM_INFO_PRINTERNAME = "printerName";
static constexpr const char *PARAM_INFO_PRINTERSTATE = "printerState";
static constexpr const char *PARAM_INFO_PRINTERSTATE = "printerState"; // Property in API 10, deprecated in API 12
static constexpr const char *PARAM_INFO_PRINTERICON = "printerIcon";
static constexpr const char *PARAM_INFO_DESCRIPTION = "description";
static constexpr const char *PARAM_INFO_CAPABILITY = "capability";
@ -30,6 +30,8 @@ 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";
static constexpr const char *PARAM_INFO_PRINTER_MAKE = "printerMake";
static constexpr const char *PARAM_INFO_URI = "uri";
napi_value PrinterInfoHelper::MakeJsObject(napi_env env, const PrinterInfo &info)
{
@ -54,6 +56,14 @@ napi_value PrinterInfoHelper::MakeJsObject(napi_env env, const PrinterInfo &info
PRINT_CALL(env, napi_set_named_property(env, jsObj, PARAM_INFO_CAPABILITY, jsCapability));
}
if (info.HasPrinterMake()) {
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_INFO_PRINTER_MAKE, info.GetPrinterMake());
}
if (info.HasUri()) {
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_INFO_URI, info.GetUri());
}
if (info.HasOption()) {
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_JOB_OPTION, info.GetOption());
}
@ -91,13 +101,6 @@ std::shared_ptr<PrinterInfo> PrinterInfoHelper::BuildFromJs(napi_env env, napi_v
nativeObj->SetPrinterId(printerId);
nativeObj->SetPrinterName(printerName);
uint32_t printerState = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_INFO_PRINTERSTATE);
if (printerState >= PRINTER_UNKNOWN) {
PRINT_HILOGE("Invalid printer state");
return nullptr;
}
nativeObj->SetPrinterState(printerState);
auto jsIcon = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_INFO_PRINTERICON);
if (jsIcon != nullptr) {
nativeObj->SetPrinterIcon(NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_INFO_PRINTERICON));
@ -118,6 +121,16 @@ std::shared_ptr<PrinterInfo> PrinterInfoHelper::BuildFromJs(napi_env env, napi_v
nativeObj->SetCapability(*capabilityPtr);
}
auto jsPrinterMake = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_INFO_PRINTER_MAKE);
if (jsPrinterMake != nullptr) {
nativeObj->SetPrinterMake(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_INFO_PRINTER_MAKE));
}
auto jsUri = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_INFO_URI);
if (jsUri != nullptr) {
nativeObj->SetUri(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_INFO_URI));
}
auto jsOption = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_OPTION);
if (jsOption != nullptr) {
nativeObj->SetOption(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_JOB_OPTION));
@ -130,11 +143,13 @@ bool PrinterInfoHelper::ValidateProperty(napi_env env, napi_value object)
std::map<std::string, PrintParamStatus> propertyList = {
{PARAM_INFO_PRINTERID, PRINT_PARAM_NOT_SET},
{PARAM_INFO_PRINTERNAME, PRINT_PARAM_NOT_SET},
{PARAM_INFO_PRINTERSTATE, PRINT_PARAM_NOT_SET},
{PARAM_INFO_PRINTERSTATE, PRINT_PARAM_OPT},
{PARAM_INFO_PRINTERICON, PRINT_PARAM_OPT},
{PARAM_INFO_DESCRIPTION, PRINT_PARAM_OPT},
{PARAM_INFO_CAPABILITY, PRINT_PARAM_OPT},
{PARAM_JOB_OPTION, PRINT_PARAM_OPT},
{PARAM_INFO_PRINTER_MAKE, PRINT_PARAM_OPT},
{PARAM_INFO_URI, PRINT_PARAM_OPT},
};
auto names = NapiPrintUtils::GetPropertyNames(env, object);

View File

@ -61,6 +61,9 @@ namespace OHOS::Print {
CMD_SET_DEFAULT_PRINTERID,
CMD_DELETE_PRINTER_FROM_CUPS,
CMD_DISCOVER_USB_PRINTERS,
CMD_ADDPRINTERTODISCOVERY,
CMD_UPDATEPRINTERINDISCOVERY,
CMD_REMOVEPRINTERFROMDISCOVERY,
};
} // namespace OHOS:Print
#endif // PRINT_SERVICE_INTERFACE_H

View File

@ -82,6 +82,9 @@ public:
virtual int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName,
const std::string &printerMake) = 0;
virtual int32_t DiscoverUsbPrinters(std::vector<PrinterInfo> &printers) = 0;
virtual int32_t AddPrinterToDiscovery(const PrinterInfo &printerInfo) = 0;
virtual int32_t UpdatePrinterInDiscovery(const PrinterInfo &printerInfo) = 0;
virtual int32_t RemovePrinterFromDiscovery(const std::string &printerId) = 0;
};
} // namespace OHOS::Print
#endif // PRINT_SERVICE_INTERFACE_H

View File

@ -81,6 +81,9 @@ public:
int32_t GetPrinterPreference(const std::string &printerId, std::string &printerPreference);
int32_t SetPrinterPreference(const std::string &printerId, const std::string &printerPreference);
int32_t DiscoverUsbPrinters(std::vector<PrinterInfo> &printers);
int32_t AddPrinterToDiscovery(const PrinterInfo &printerInfo);
int32_t UpdatePrinterInDiscovery(const PrinterInfo &printerInfo);
int32_t RemovePrinterFromDiscovery(const std::string &printerId);
int32_t On(const std::string &taskId, const std::string &type, const sptr<IPrintCallback> &listener);
int32_t Off(const std::string &taskId, const std::string &type);

View File

@ -63,6 +63,9 @@ public:
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 AddPrinterToDiscovery(const PrinterInfo &printerInfo) override;
int32_t UpdatePrinterInDiscovery(const PrinterInfo &printerInfo) override;
int32_t RemovePrinterFromDiscovery(const std::string &printerId) override;
int32_t QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info) override;
int32_t QueryAddedPrinter(std::vector<std::string> &printerNameList) override;

View File

@ -376,6 +376,43 @@ int32_t PrintManagerClient::SetPrinterPreference(const std::string &printerId, c
return ret;
}
int32_t PrintManagerClient::AddPrinterToDiscovery(const PrinterInfo &printerInfo)
{
std::lock_guard<std::recursive_mutex> lock(proxyLock_);
PRINT_HILOGD("PrintManagerClient AddPrinterToDiscovery start.");
int32_t ret = E_PRINT_RPC_FAILURE;
if (LoadServer() && GetPrintServiceProxy()) {
ret = printServiceProxy_->AddPrinterToDiscovery(printerInfo);
PRINT_HILOGD("PrintManagerClient AddPrinterToDiscovery out ret = [%{public}d].", ret);
}
return ret;
}
int32_t PrintManagerClient::UpdatePrinterInDiscovery(const PrinterInfo &printerInfo)
{
std::lock_guard<std::recursive_mutex> lock(proxyLock_);
printerInfo.Dump();
int32_t ret = E_PRINT_RPC_FAILURE;
if (LoadServer() && GetPrintServiceProxy()) {
ret = printServiceProxy_->UpdatePrinterInDiscovery(printerInfo);
PRINT_HILOGD("PrintManagerClient UpdatePrinterInDiscovery out ret = [%{public}d].", ret);
}
return ret;
}
int32_t PrintManagerClient::RemovePrinterFromDiscovery(const std::string &printerId)
{
std::lock_guard<std::recursive_mutex> lock(proxyLock_);
PRINT_HILOGD("PrintManagerClient RemovePrinterFromDiscovery start.");
int32_t ret = E_PRINT_RPC_FAILURE;
if (LoadServer() && GetPrintServiceProxy()) {
ret = printServiceProxy_->RemovePrinterFromDiscovery(printerId);
PRINT_HILOGD("PrintManagerClient RemovePrinterFromDiscovery out ret = [%{public}d].", ret);
}
return ret;
}
int32_t PrintManagerClient::QueryAllPrintJob(std::vector<PrintJob> &printJobs)
{
std::lock_guard<std::recursive_mutex> lock(proxyLock_);
@ -560,12 +597,12 @@ int32_t PrintManagerClient::Print(const std::string &printJobName, const sptr<IP
auto printUiContent = static_cast<OHOS::Ace::UIContent *>(uiContent);
auto callback = std::make_shared<PrintInnerkitModalUICallback>(printUiContent);
OHOS::Ace::ModalUIExtensionCallbacks extensionCallbacks = {
[callback](int32_t releaseCode) { callback->OnRelease(releaseCode); },
[callback](int32_t resultCode, const OHOS::AAFwk::Want& result) {
[&callback](int32_t releaseCode) { callback->OnRelease(releaseCode); },
[&callback](int32_t resultCode, const OHOS::AAFwk::Want& result) {
callback->OnResultForModal(resultCode, result);
},
[callback](const OHOS::AAFwk::WantParams& request) { callback->OnReceive(request); },
[callback](int32_t code, const std::string& name, const std::string& message) {
[&callback](const OHOS::AAFwk::WantParams& request) { callback->OnReceive(request); },
[&callback](int32_t code, const std::string& name, const std::string& message) {
callback->OnError(code, name, message);
}
};

View File

@ -756,6 +756,48 @@ int32_t PrintServiceProxy::NotifyPrintService(const std::string &jobId, const st
return ret;
}
int32_t PrintServiceProxy::AddPrinterToDiscovery(const PrinterInfo &printerInfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
printerInfo.Marshalling(data);
PRINT_HILOGD("PrintServiceProxy AddPrinterToDiscovery started.");
int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_ADDPRINTERTODISCOVERY,
data, reply, option);
ret = GetResult(ret, reply);
PRINT_HILOGD("PrintServiceProxy AddPrinterToDiscovery out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UpdatePrinterInDiscovery(const PrinterInfo& printerInfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
printerInfo.Marshalling(data);
PRINT_HILOGD("PrintServiceProxy UpdatePrinterInDiscovery started.");
int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTERINDISCOVERY,
data, reply, option);
ret = GetResult(ret, reply);
PRINT_HILOGD("PrintServiceProxy UpdatePrinterInDiscovery out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::RemovePrinterFromDiscovery(const std::string &printerId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
PRINT_HILOGD("PrintServiceProxy RemovePrinterFromDiscovery started.");
int32_t ret = Remote()->SendRequest(OHOS::Print::IPrintInterfaceCode::CMD_REMOVEPRINTERFROMDISCOVERY,
data, reply, option);
ret = GetResult(ret, reply);
PRINT_HILOGD("PrintServiceProxy RemovePrinterFromDiscovery out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UnregisterAllExtCallback(const std::string &extensionId)
{
PRINT_HILOGD("PrintServiceProxy::UnregisterAllExtCallback in");

View File

@ -61,7 +61,7 @@ public:
static std::shared_ptr<PrintMargin> Unmarshalling(Parcel &parcel);
void Dump();
void Dump() const;
private:
void ReadFromParcel(Parcel &parcel);

View File

@ -48,7 +48,7 @@ public:
static std::shared_ptr<PrintResolution> Unmarshalling(Parcel &parcel);
void Dump();
void Dump() const;
private:
void ReadFromParcel(Parcel &parcel);

View File

@ -19,6 +19,8 @@
#include <string>
#include "want.h"
#include "bundle_mgr_client.h"
#include "print_constant.h"
#include "print_log.h"
#include <nlohmann/json.hpp>
#include <mutex>
@ -36,8 +38,8 @@ class PrintUtils {
public:
static std::string ToLower(const std::string &s);
static std::string GetExtensionId(const std::string &globalId);
static std::string GetGlobalId(const std::string& extensionId, const std::string& localId);
static std::string GetLocalId(const std::string& globalId, const std::string& extensionId);
static std::string GetGlobalId(const std::string &extensionId, const std::string &localId);
static std::string GetLocalId(const std::string &globalId, const std::string &extensionId);
static std::string EncodeExtensionCid(const std::string &extensionId, uint32_t callbackId);
static bool DecodeExtensionCid(const std::string &cid, std::string &extensionId, uint32_t &callbackId);
static std::string GetTaskEventId(const std::string &taskId, const std::string &type);
@ -53,6 +55,71 @@ public:
static std::string GetPrintJobId();
static std::string GetEventTypeWithToken(int64_t id, const std::string &type);
static std::string GetEventType(const std::string &type);
template <typename T, typename ReadFunc>
static bool readListFromParcel(Parcel &parcel, std::vector<T> &supportedList, const ReadFunc &readFunc)
{
uint32_t vecSize = parcel.ReadUint32();
CHECK_IS_EXCEED_PRINT_RANGE_BOOL(vecSize);
supportedList.clear();
supportedList.reserve(vecSize); // Allocate the required memory all at once to speed up processing efficiency.
for (uint32_t index = 0; index < vecSize; index++) {
auto item = readFunc(parcel);
if (item.has_value()) {
supportedList.emplace_back(std::move(*item));
} else {
PRINT_HILOGE("Failed on the %{public}d-th read of the list.", index);
return false;
}
}
return true;
}
template <typename T, typename ReadFunc>
static bool readListFromParcel(Parcel &parcel, std::vector<T> &supportedList, const ReadFunc &readFunc,
bool *hasSupportedPtr)
{
if (hasSupportedPtr) {
*hasSupportedPtr = parcel.ReadBool();
if (*hasSupportedPtr) {
return readListFromParcel(parcel, supportedList, readFunc);
}
} else {
PRINT_HILOGE("Func readListFromParcel error! Ptr: hasSupportedPtr is null");
return false;
}
return true;
}
template <typename T, typename WriteFunc>
static void WriteListToParcel(Parcel &parcel, const std::vector<T> &list, WriteFunc writeFunc)
{
uint32_t vecSize = static_cast<uint32_t>(list.size());
parcel.WriteUint32(vecSize);
for (uint32_t index = 0; index < vecSize; index++) {
writeFunc(parcel, list[index]);
}
}
template <typename T, typename WriteFunc>
static void WriteListToParcel(Parcel &parcel, const std::vector<T> &list, WriteFunc writeFunc, bool hasFlag)
{
parcel.WriteBool(hasFlag);
if (hasFlag) {
WriteListToParcel(parcel, list, writeFunc);
}
}
template<typename T>
static bool CheckJsonType(const nlohmann::json &j)
{
if constexpr (std::is_same_v<T, int> || std::is_same_v<T, unsigned int> || std::is_same_v<T, uint32_t>) {
return j.is_number_integer();
} else if constexpr (std::is_same_v<T, std::string>) {
return j.is_string();
} else if constexpr (std::is_same_v<T, bool>) {
return j.is_boolean();
} else {
return true; // For complex types, we'll do the check in the conversion function
}
}
private:
static std::mutex instanceLock_;

View File

@ -56,21 +56,55 @@ public:
[[nodiscard]] std::string GetOption() const;
void SetMinMargin(const PrintMargin &minMargin);
[[nodiscard]] bool HasSupportedPageSize() const;
void SetPageSize(const std::vector<PrintPageSize> &pageSizeList);
[[nodiscard]] bool HasSupportedColorMode() const;
void SetResolution(const std::vector<PrintResolution> &resolutionList);
[[nodiscard]] bool HasSupportedDuplexMode() const;
[[nodiscard]] bool HasSupportedMediaType() const;
[[nodiscard]] bool HasSupportedQuality() const;
[[nodiscard]] bool HasSupportedOrientation() const;
void GetSupportedPageSize(std::vector<PrintPageSize>& supportedPageSize) const;
void GetSupportedColorMode(std::vector<uint32_t>& supportedColorModeList) const;
void GetSupportedDuplexMode(std::vector<uint32_t>& supportedDuplexModeList) const;
void GetSupportedMediaType(std::vector<std::string>& supportedMediaTypeList) const;
void GetSupportedQuality(std::vector<uint32_t>& supportedQualityList) const;
void GetSupportedOrientation(std::vector<uint32_t>& supportedOrientationList) const;
void SetMinMargin(const PrintMargin& minMargin);
void SetResolution(const std::vector<PrintResolution>& resolutionList);
void SetColorMode(uint32_t colorMode);
void SetDuplexMode(uint32_t duplexMode);
virtual bool Marshalling(Parcel &parcel) const override;
void SetSupportedColorMode(const std::vector<uint32_t>& supportedColorModeList);
static std::shared_ptr<PrinterCapability> Unmarshalling(Parcel &parcel);
void SetSupportedPageSize(const std::vector<PrintPageSize>& supportedPageSizeList);
void Dump();
void SetSupportedDuplexMode(const std::vector<uint32_t>& supportedDuplexModeList);
void SetSupportedMediaType(const std::vector<std::string>& supportedMediaTypeList);
void SetSupportedQuality(const std::vector<uint32_t>& supportedQualityList);
void SetSupportedOrientation(const std::vector<uint32_t>& supportedOrientationList);
virtual bool Marshalling(Parcel& parcel) const override;
static std::shared_ptr<PrinterCapability> Unmarshalling(Parcel& parcel);
void Dump() const;
const char* GetPrinterAttrValue(const char* name);
@ -84,13 +118,31 @@ private:
bool ReadFromParcel(Parcel &parcel);
private:
uint32_t colorMode_;
uint32_t duplexMode_;
uint32_t colorMode_; // Property in API 10, deprecated in API 12
uint32_t duplexMode_; // Property in API 10, deprecated in API 12
std::vector<PrintPageSize> pageSizeList_;
bool hasResolution_;
std::vector<PrintResolution> resolutionList_;
std::vector<PrintPageSize> supportedPageSizeList_;
bool hasSupportedColorMode_;
std::vector<uint32_t> supportedColorModeList_;
bool hasSupportedDuplexMode_;
std::vector<uint32_t> supportedDuplexModeList_;
bool hasSupportedMediaType_;
std::vector<std::string> supportedMediaTypeList_;
bool hasSupportedQuality_;
std::vector<uint32_t> supportedQualityList_;
bool hasSupportedOrientation_;
std::vector<uint32_t> supportedOrientationList_;
bool hasMargin_;
PrintMargin minMargin_;

View File

@ -42,6 +42,10 @@ public:
void SetCapability(const PrinterCapability &capability);
void SetUri(const std::string &uri);
void SetPrinterMake(const std::string &printerMake);
void SetOption(const std::string &option);
void SetIsDefaultPrinter(bool isDefaultPrinter);
@ -53,17 +57,29 @@ public:
[[nodiscard]] const std::string &GetPrinterId() const;
[[nodiscard]] const std::string &GetPrinterName() const;
[[nodiscard]] bool HasPrinterIcon() const;
[[nodiscard]] uint32_t GetPrinterIcon() const;
[[nodiscard]] uint32_t GetPrinterState() const;
[[nodiscard]] bool HasDescription() const;
[[nodiscard]] const std::string &GetDescription() const;
[[nodiscard]] bool HasCapability() const;
void GetCapability(PrinterCapability &cap) const;
[[nodiscard]] bool HasUri() const;
[[nodiscard]] std::string GetUri() const;
[[nodiscard]] bool HasPrinterMake() const;
[[nodiscard]] std::string GetPrinterMake() const;
[[nodiscard]] bool HasOption() const;
[[nodiscard]] std::string GetOption() const;
@ -84,11 +100,15 @@ public:
static std::shared_ptr<PrinterInfo> Unmarshalling(Parcel &parcel);
void Dump();
void Dump() const;
private:
bool ReadFromParcel(Parcel &parcel);
void ReadInnerPropertyFromParcel(PrinterInfo& right, Parcel& parcel);
bool ValidateAll();
private:
std::string printerId_;
@ -96,29 +116,41 @@ private:
uint32_t printerState_;
bool hasPrinterIcon_;
uint32_t printerIcon_;
bool hasDescription_;
std::string description_;
bool hasPrinterStatus_;
uint32_t printerStatus_;
bool hasCapability_;
PrinterCapability capability_;
bool hasUri_;
std::string uri_;
bool hasPrinterMake_;
std::string printerMake_;
bool hasOption_;
std::string option_;
bool hasIsDefaultPrinter_;
bool hasIsDefaultPrinter_; // Deprecated, to be removed in a future version.
bool isDefaultPrinter_;
bool isDefaultPrinter_; // Deprecated, to be removed in a future version.
bool hasIsLastUsedPrinter_;
bool hasIsLastUsedPrinter_; // Deprecated, to be removed in a future version.
bool isLastUsedPrinter_;
bool hasPrinterStatus_;
uint32_t printerStatus_;
bool isLastUsedPrinter_; // Deprecated, to be removed in a future version.
};
} // namespace OHOS::Print
#endif // PRINTER_INFO_H

View File

@ -180,7 +180,7 @@ std::shared_ptr<PrintMargin> PrintMargin::Unmarshalling(Parcel &parcel)
return nativeObj;
}
void PrintMargin::Dump()
void PrintMargin::Dump() const
{
if (hasTop_) {
PRINT_HILOGD("top_ = %{public}d", top_);

View File

@ -100,7 +100,7 @@ std::shared_ptr<PrintResolution> PrintResolution::Unmarshalling(Parcel &parcel)
return nativeObj;
}
void PrintResolution::Dump()
void PrintResolution::Dump() const
{
PRINT_HILOGD("id_ = %{public}s", id_.c_str());
PRINT_HILOGD("horizontalDpi_ = %{public}d", horizontalDpi_);

View File

@ -17,8 +17,6 @@
#include <fcntl.h>
#include "ability.h"
#include "print_constant.h"
#include "print_log.h"
#include "securec.h"
#include <chrono>
#include <sstream>

View File

@ -16,28 +16,38 @@
#include "printer_capability.h"
#include "print_constant.h"
#include "print_log.h"
#include "print_utils.h"
using json = nlohmann::json;
namespace OHOS::Print {
PrinterCapability::PrinterCapability() : colorMode_(0), duplexMode_(0),
hasResolution_(false), hasMargin_(false), hasOption_(false), option_("")
PrinterCapability::PrinterCapability()
: colorMode_(0),
duplexMode_(0),
hasResolution_(false),
hasSupportedColorMode_(false),
hasSupportedDuplexMode_(false),
hasSupportedMediaType_(false),
hasSupportedQuality_(false),
hasSupportedOrientation_(false),
hasMargin_(false),
hasOption_(false),
option_("")
{
pageSizeList_.clear();
resolutionList_.clear();
minMargin_.Reset();
supportedPageSizeList_.clear();
supportedColorModeList_.clear();
supportedDuplexModeList_.clear();
supportedMediaTypeList_.clear();
supportedQualityList_.clear();
supportedOrientationList_.clear();
printerAttr_group.clear();
}
PrinterCapability::PrinterCapability(const PrinterCapability &right)
{
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
pageSizeList_.assign(right.pageSizeList_.begin(), right.pageSizeList_.end());
hasResolution_ = right.hasResolution_;
resolutionList_.assign(right.resolutionList_.begin(), right.resolutionList_.end());
hasMargin_ = right.hasMargin_;
minMargin_ = right.minMargin_;
hasOption_ = right.hasOption_;
option_= right.option_;
*this = right;
}
PrinterCapability &PrinterCapability::operator=(const PrinterCapability &right)
@ -52,13 +62,23 @@ PrinterCapability &PrinterCapability::operator=(const PrinterCapability &right)
minMargin_ = right.minMargin_;
hasOption_ = right.hasOption_;
option_ = right.option_;
hasSupportedColorMode_ = right.hasSupportedColorMode_;
hasSupportedDuplexMode_ = right.hasSupportedDuplexMode_;
hasSupportedMediaType_ = right.hasSupportedMediaType_;
hasSupportedQuality_ = right.hasSupportedQuality_;
hasSupportedOrientation_ = right.hasSupportedOrientation_;
supportedPageSizeList_.assign(right.supportedPageSizeList_.begin(), right.supportedPageSizeList_.end());
supportedColorModeList_.assign(right.supportedColorModeList_.begin(), right.supportedColorModeList_.end());
supportedDuplexModeList_.assign(right.supportedDuplexModeList_.begin(), right.supportedDuplexModeList_.end());
supportedMediaTypeList_.assign(right.supportedMediaTypeList_.begin(), right.supportedMediaTypeList_.end());
supportedQualityList_.assign(right.supportedQualityList_.begin(), right.supportedQualityList_.end());
supportedOrientationList_.assign(right.supportedOrientationList_.begin(),
right.supportedOrientationList_.end());
}
return *this;
}
PrinterCapability::~PrinterCapability()
{
}
PrinterCapability::~PrinterCapability() {}
void PrinterCapability::Reset()
{
@ -69,6 +89,17 @@ void PrinterCapability::Reset()
resolutionList_.clear();
hasMargin_ = false;
minMargin_.Reset();
hasSupportedColorMode_ = false;
hasSupportedDuplexMode_ = false;
hasSupportedMediaType_ = false;
hasSupportedQuality_ = false;
hasSupportedOrientation_ = false;
supportedPageSizeList_.clear();
supportedColorModeList_.clear();
supportedDuplexModeList_.clear();
supportedMediaTypeList_.clear();
supportedQualityList_.clear();
supportedOrientationList_.clear();
}
void PrinterCapability::SetMinMargin(const PrintMargin &minMargin)
@ -77,11 +108,6 @@ void PrinterCapability::SetMinMargin(const PrintMargin &minMargin)
minMargin_ = minMargin;
}
void PrinterCapability::SetPageSize(const std::vector<PrintPageSize> &pageSizeList)
{
pageSizeList_.assign(pageSizeList.begin(), pageSizeList.end());
}
void PrinterCapability::SetResolution(const std::vector<PrintResolution> &resolutionList)
{
hasResolution_ = true;
@ -144,6 +170,96 @@ bool PrinterCapability::HasOption() const
return hasOption_;
}
bool PrinterCapability::HasSupportedColorMode() const
{
return hasSupportedColorMode_;
}
bool PrinterCapability::HasSupportedDuplexMode() const
{
return hasSupportedDuplexMode_;
}
bool PrinterCapability::HasSupportedMediaType() const
{
return hasSupportedMediaType_;
}
bool PrinterCapability::HasSupportedQuality() const
{
return hasSupportedQuality_;
}
bool PrinterCapability::HasSupportedOrientation() const
{
return hasSupportedOrientation_;
}
void PrinterCapability::GetSupportedPageSize(std::vector<PrintPageSize> &supportedPageSizeList) const
{
supportedPageSizeList.assign(supportedPageSizeList_.begin(), supportedPageSizeList_.end());
}
void PrinterCapability::GetSupportedColorMode(std::vector<uint32_t> &supportedColorModeList) const
{
supportedColorModeList.assign(supportedColorModeList_.begin(), supportedColorModeList_.end());
}
void PrinterCapability::GetSupportedDuplexMode(std::vector<uint32_t> &supportedDuplexModeList) const
{
supportedDuplexModeList.assign(supportedDuplexModeList_.begin(), supportedDuplexModeList_.end());
}
void PrinterCapability::GetSupportedMediaType(std::vector<std::string> &supportedMediaTypeList) const
{
supportedMediaTypeList.assign(supportedMediaTypeList_.begin(), supportedMediaTypeList_.end());
}
void PrinterCapability::GetSupportedQuality(std::vector<uint32_t> &supportedQualityList) const
{
supportedQualityList.assign(supportedQualityList_.begin(), supportedQualityList_.end());
}
void PrinterCapability::GetSupportedOrientation(std::vector<uint32_t> &supportedOrientationList) const
{
supportedOrientationList.assign(supportedOrientationList_.begin(), supportedOrientationList_.end());
}
void PrinterCapability::SetSupportedPageSize(const std::vector<PrintPageSize> &supportedPageSizeList)
{
supportedPageSizeList_.assign(supportedPageSizeList.begin(), supportedPageSizeList.end());
}
void PrinterCapability::SetSupportedColorMode(const std::vector<uint32_t> &supportedColorModeList)
{
hasSupportedColorMode_ = true;
supportedColorModeList_.assign(supportedColorModeList.begin(), supportedColorModeList.end());
}
void PrinterCapability::SetSupportedDuplexMode(const std::vector<uint32_t> &supportedDuplexModeList)
{
hasSupportedDuplexMode_ = true;
supportedDuplexModeList_.assign(supportedDuplexModeList.begin(), supportedDuplexModeList.end());
}
void PrinterCapability::SetSupportedMediaType(const std::vector<std::string> &supportedMediaTypeList)
{
hasSupportedMediaType_ = true;
supportedMediaTypeList_.assign(supportedMediaTypeList.begin(), supportedMediaTypeList.end());
}
void PrinterCapability::SetSupportedQuality(const std::vector<uint32_t> &supportedQualityList)
{
hasSupportedQuality_ = true;
supportedQualityList_.assign(supportedQualityList.begin(), supportedQualityList.end());
}
void PrinterCapability::SetSupportedOrientation(const std::vector<uint32_t> &supportedOrientationList)
{
hasSupportedOrientation_ = true;
supportedOrientationList_.assign(supportedOrientationList.begin(), supportedOrientationList.end());
}
std::string PrinterCapability::GetOption() const
{
return option_;
@ -151,46 +267,62 @@ std::string PrinterCapability::GetOption() const
bool PrinterCapability::ReadFromParcel(Parcel &parcel)
{
SetColorMode(parcel.ReadUint32());
SetDuplexMode(parcel.ReadUint32());
PrinterCapability right;
right.SetColorMode(parcel.ReadUint32());
right.SetDuplexMode(parcel.ReadUint32());
uint32_t vecSize = parcel.ReadUint32();
CHECK_IS_EXCEED_PRINT_RANGE_BOOL(vecSize);
std::vector<PrintPageSize> pageSizeList;
for (uint32_t index = 0; index < vecSize; index++) {
auto pageSizePtr = PrintPageSize::Unmarshalling(parcel);
if (pageSizePtr != nullptr) {
pageSizeList.emplace_back(*pageSizePtr);
}
}
SetPageSize(pageSizeList);
hasResolution_ = parcel.ReadBool();
if (hasResolution_) {
std::vector<PrintResolution> resolutionList;
vecSize = parcel.ReadUint32();
CHECK_IS_EXCEED_PRINT_RANGE_BOOL(vecSize);
for (uint32_t index = 0; index < vecSize; index++) {
auto resolutionPtr = PrintResolution::Unmarshalling(parcel);
if (resolutionPtr != nullptr) {
resolutionList.emplace_back(*resolutionPtr);
PrintUtils::readListFromParcel<PrintPageSize>(parcel, right.supportedPageSizeList_,
[](Parcel& p) -> std::optional<PrintPageSize> {
auto ptr = PrintPageSize::Unmarshalling(p);
if (ptr) {
return std::optional<PrintPageSize>(*ptr);
}
}
SetResolution(resolutionList);
}
return std::nullopt;
});
hasMargin_ = parcel.ReadBool();
if (hasMargin_) {
PrintUtils::readListFromParcel<PrintResolution>(parcel, right.resolutionList_,
[](Parcel& p) -> std::optional<PrintResolution> {
auto ptr = PrintResolution::Unmarshalling(p);
if (ptr) {
return std::optional<PrintResolution>(*ptr);
}
return std::nullopt;
}, &right.hasResolution_);
PrintUtils::readListFromParcel<uint32_t>(
parcel, right.supportedColorModeList_, [](Parcel &p) { return std::make_optional(p.ReadUint32()); },
&right.hasSupportedColorMode_);
PrintUtils::readListFromParcel<uint32_t>(
parcel, right.supportedDuplexModeList_, [](Parcel &p) { return std::make_optional(p.ReadUint32()); },
&right.hasSupportedDuplexMode_);
PrintUtils::readListFromParcel<std::string>(
parcel, right.supportedMediaTypeList_, [](Parcel &p) { return std::make_optional(p.ReadString()); },
&right.hasSupportedMediaType_);
PrintUtils::readListFromParcel<uint32_t>(
parcel, right.supportedQualityList_, [](Parcel &p) { return std::make_optional(p.ReadUint32()); },
&right.hasSupportedQuality_);
PrintUtils::readListFromParcel<uint32_t>(
parcel, right.supportedOrientationList_, [](Parcel &p) { return std::make_optional(p.ReadUint32()); },
&right.hasSupportedOrientation_);
right.hasMargin_ = parcel.ReadBool();
if (right.hasMargin_) {
auto marginPtr = PrintMargin::Unmarshalling(parcel);
if (marginPtr != nullptr) {
minMargin_ = *marginPtr;
right.SetMinMargin(*marginPtr);
}
}
hasOption_ = parcel.ReadBool();
if (hasOption_) {
SetOption(parcel.ReadString());
right.hasOption_ = parcel.ReadBool();
if (right.hasOption_) {
right.SetOption(parcel.ReadString());
}
*this = right;
return true;
}
@ -199,20 +331,33 @@ bool PrinterCapability::Marshalling(Parcel &parcel) const
parcel.WriteUint32(GetColorMode());
parcel.WriteUint32(GetDuplexMode());
uint32_t vecSize = static_cast<uint32_t>(pageSizeList_.size());
parcel.WriteUint32(vecSize);
for (uint32_t index = 0; index < vecSize; index++) {
pageSizeList_[index].Marshalling(parcel);
}
PrintUtils::WriteListToParcel(
parcel, supportedPageSizeList_,
[](Parcel &p, const PrintPageSize& item) { item.Marshalling(p); });
parcel.WriteBool(hasResolution_);
if (hasResolution_) {
vecSize = static_cast<uint32_t>(resolutionList_.size());
parcel.WriteUint32(vecSize);
for (uint32_t index = 0; index < vecSize; index++) {
resolutionList_[index].Marshalling(parcel);
}
}
PrintUtils::WriteListToParcel(
parcel, resolutionList_, [](Parcel& p, const PrintResolution& item) { item.Marshalling(p); },
hasResolution_);
PrintUtils::WriteListToParcel(
parcel, supportedColorModeList_, [](Parcel& p, const int& item) { p.WriteUint32(item); },
hasSupportedColorMode_);
PrintUtils::WriteListToParcel(
parcel, supportedDuplexModeList_, [](Parcel& p, const int& item) { p.WriteUint32(item); },
hasSupportedDuplexMode_);
PrintUtils::WriteListToParcel(
parcel, supportedMediaTypeList_, [](Parcel& p, const std::string& item) { p.WriteString(item); },
hasSupportedMediaType_);
PrintUtils::WriteListToParcel(
parcel, supportedQualityList_, [](Parcel& p, const int& item) { p.WriteUint32(item); },
hasSupportedQuality_);
PrintUtils::WriteListToParcel(
parcel, supportedOrientationList_, [](Parcel& p, const int& item) { p.WriteUint32(item); },
hasSupportedOrientation_);
parcel.WriteBool(hasMargin_);
if (hasMargin_) {
@ -232,12 +377,12 @@ std::shared_ptr<PrinterCapability> PrinterCapability::Unmarshalling(Parcel &parc
return nativeObj;
}
void PrinterCapability::Dump()
void PrinterCapability::Dump() const
{
PRINT_HILOGD("colorMode_ = %{public}d", colorMode_);
PRINT_HILOGD("duplexMode_ = %{public}d", duplexMode_);
for (auto pageItem : pageSizeList_) {
for (auto pageItem : supportedPageSizeList_) {
pageItem.Dump();
}
@ -247,6 +392,36 @@ void PrinterCapability::Dump()
}
}
if (hasSupportedColorMode_) {
for (auto item : supportedColorModeList_) {
PRINT_HILOGD("supportedColorModeItem = %{public}d", item);
}
}
if (hasSupportedDuplexMode_) {
for (auto item : supportedDuplexModeList_) {
PRINT_HILOGD("supportedDuplexModeItem = %{public}d", item);
}
}
if (hasSupportedMediaType_) {
for (auto item : supportedMediaTypeList_) {
PRINT_HILOGD("supportedMediaTypeItem = %{public}s", item.c_str());
}
}
if (hasSupportedQuality_) {
for (auto item : supportedQualityList_) {
PRINT_HILOGD("supportedQualityItem = %{public}d", item);
}
}
if (hasSupportedOrientation_) {
for (auto item : supportedOrientationList_) {
PRINT_HILOGD("supportedOrientationItem = %{public}d", item);
}
}
if (hasMargin_) {
minMargin_.Dump();
}
@ -255,7 +430,7 @@ void PrinterCapability::Dump()
}
}
const char* PrinterCapability::GetPrinterAttrValue(const char* name)
const char *PrinterCapability::GetPrinterAttrValue(const char *name)
{
auto iter = printerAttr_group.find(name);
if (iter != printerAttr_group.end()) {
@ -264,19 +439,19 @@ const char* PrinterCapability::GetPrinterAttrValue(const char* name)
return "";
}
}
void PrinterCapability::SetPrinterAttrNameAndValue(const char* name, const char* value)
void PrinterCapability::SetPrinterAttrNameAndValue(const char *name, const char *value)
{
printerAttr_group[name] = value;
}
nlohmann::json PrinterCapability::GetPrinterAttrGroupJson()
{
nlohmann::json printerAttrGroupJson;
if (printerAttr_group.size() < 1) {
PRINT_HILOGI("no printerAttr_group");
return printerAttrGroupJson;
return "";
}
nlohmann::json printerAttrGroupJson;
for (auto iter = printerAttr_group.begin(); iter != printerAttr_group.end(); iter++) {
printerAttrGroupJson[iter->first] = iter->second;
}

View File

@ -19,44 +19,71 @@
namespace OHOS::Print {
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)
: printerId_(""),
printerName_(""),
printerState_(PRINTER_UNKNOWN),
hasPrinterIcon_(false),
printerIcon_(PRINT_INVALID_ID),
hasDescription_(false),
description_(""),
hasPrinterStatus_(false),
printerStatus_(PRINTER_STATUS_UNAVAILABLE),
hasCapability_(false),
hasUri_(false),
uri_(""),
hasPrinterMake_(false),
printerMake_(""),
hasOption_(false),
option_(""),
hasIsDefaultPrinter_(false),
isDefaultPrinter_(false),
hasIsLastUsedPrinter_(false),
isLastUsedPrinter_(false)
{
capability_.Reset();
}
PrinterInfo::PrinterInfo(const PrinterInfo &right)
: printerId_(right.printerId_),
printerName_(right.printerName_),
printerState_(right.printerState_),
hasPrinterIcon_(right.hasPrinterIcon_),
printerIcon_(right.printerIcon_),
hasDescription_(right.hasDescription_),
description_(right.description_),
hasPrinterStatus_(right.hasPrinterStatus_),
printerStatus_(right.printerStatus_),
hasCapability_(right.hasCapability_),
capability_(right.capability_),
hasUri_(right.hasUri_),
uri_(right.uri_),
hasPrinterMake_(right.hasPrinterMake_),
printerMake_(right.printerMake_),
hasOption_(right.hasOption_),
option_(right.option_),
hasIsDefaultPrinter_(right.hasIsDefaultPrinter_),
isDefaultPrinter_(right.isDefaultPrinter_),
hasIsLastUsedPrinter_(right.hasIsLastUsedPrinter_),
isLastUsedPrinter_(right.isLastUsedPrinter_)
{
printerId_ = right.printerId_;
printerName_ = right.printerName_;
printerState_ = right.printerState_;
printerIcon_ = right.printerIcon_;
description_ = right.description_;
hasCapability_ = right.hasCapability_;
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)
{
if (this != &right) {
printerId_ = right.printerId_;
printerName_ = right.printerName_;
printerState_ = right.printerState_;
hasPrinterIcon_ = right.hasPrinterIcon_;
printerIcon_ = right.printerIcon_;
hasDescription_ = right.hasDescription_;
description_ = right.description_;
hasCapability_ = right.hasCapability_;
capability_ = right.capability_;
hasOption_ = right.hasOption_;
hasUri_ = right.hasUri_;
uri_ = right.uri_;
hasPrinterMake_ = right.hasPrinterMake_;
printerMake_ = right.printerMake_;
option_ = right.option_;
hasIsDefaultPrinter_ = right.hasIsDefaultPrinter_;
isDefaultPrinter_ = right.isDefaultPrinter_;
@ -68,9 +95,7 @@ PrinterInfo &PrinterInfo::operator=(const PrinterInfo &right)
return *this;
}
PrinterInfo::~PrinterInfo()
{
}
PrinterInfo::~PrinterInfo() {}
void PrinterInfo::SetPrinterId(const std::string &printerId)
{
@ -103,6 +128,18 @@ void PrinterInfo::SetCapability(const PrinterCapability &capability)
capability_ = capability;
}
void PrinterInfo::SetUri(const std::string &uri)
{
hasUri_ = true;
uri_ = uri;
}
void PrinterInfo::SetPrinterMake(const std::string &printerMake)
{
hasPrinterMake_ = true;
printerMake_ = printerMake;
}
void PrinterInfo::SetOption(const std::string &option)
{
hasOption_ = true;
@ -162,6 +199,26 @@ void PrinterInfo::GetCapability(PrinterCapability &cap) const
cap = capability_;
}
bool PrinterInfo::HasUri() const
{
return hasUri_;
}
std::string PrinterInfo::GetUri() const
{
return uri_;
}
bool PrinterInfo::HasPrinterMake() const
{
return hasPrinterMake_;
}
std::string PrinterInfo::GetPrinterMake() const
{
return printerMake_;
}
bool PrinterInfo::HasOption() const
{
return hasOption_;
@ -204,79 +261,95 @@ uint32_t PrinterInfo::GetPrinterStatus() const
bool PrinterInfo::ReadFromParcel(Parcel &parcel)
{
PrinterInfo right;
if (parcel.GetReadableBytes() == 0) {
PRINT_HILOGE("no data in parcel");
return false;
}
SetPrinterId(parcel.ReadString());
SetPrinterName(parcel.ReadString());
SetPrinterState(parcel.ReadUint32());
right.SetPrinterId(parcel.ReadString());
right.SetPrinterName(parcel.ReadString());
right.SetPrinterState(parcel.ReadUint32());
uint32_t iconId = PRINT_INVALID_ID;
if (parcel.ReadBool()) {
right.hasPrinterIcon_ = parcel.ReadBool();
if (right.hasPrinterIcon_) {
iconId = parcel.ReadUint32();
}
SetPrinterIcon(iconId);
right.SetPrinterIcon(iconId);
std::string desc = "";
if (parcel.ReadBool()) {
desc = parcel.ReadString();
right.hasDescription_ = parcel.ReadBool();
if (right.hasDescription_) {
right.SetDescription(parcel.ReadString());
}
SetDescription(desc);
hasCapability_ = parcel.ReadBool();
if (hasCapability_) {
right.hasPrinterStatus_ = parcel.ReadBool();
if (right.hasPrinterStatus_) {
right.SetPrinterStatus(parcel.ReadUint32());
}
right.hasCapability_ = parcel.ReadBool();
if (right.hasCapability_) {
auto capPtr = PrinterCapability::Unmarshalling(parcel);
if (capPtr == nullptr) {
PRINT_HILOGE("failed to build capability from printer info");
return false;
}
capability_ = *capPtr;
right.SetCapability(*capPtr);
}
hasOption_ = parcel.ReadBool();
if (hasOption_) {
SetOption(parcel.ReadString());
right.hasUri_ = parcel.ReadBool();
if (right.hasUri_) {
right.SetUri(parcel.ReadString());
}
hasIsDefaultPrinter_ = parcel.ReadBool();
if (hasIsDefaultPrinter_) {
isDefaultPrinter_ = parcel.ReadBool();
right.hasPrinterMake_ = parcel.ReadBool();
if (right.hasPrinterMake_) {
right.SetPrinterMake(parcel.ReadString());
}
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());
right.hasOption_ = parcel.ReadBool();
if (right.hasOption_) {
right.SetOption(parcel.ReadString());
}
ReadInnerPropertyFromParcel(right, parcel);
right.Dump();
*this = right;
return true;
}
void PrinterInfo::ReadInnerPropertyFromParcel(PrinterInfo& right, Parcel& parcel)
{
right.hasIsDefaultPrinter_ = parcel.ReadBool();
if (right.hasIsDefaultPrinter_) {
right.isDefaultPrinter_ = parcel.ReadBool();
}
right.hasIsLastUsedPrinter_ = parcel.ReadBool();
if (right.hasIsLastUsedPrinter_) {
right.isLastUsedPrinter_ = parcel.ReadBool();
}
}
bool PrinterInfo::Marshalling(Parcel &parcel) const
{
parcel.WriteString(GetPrinterId());
parcel.WriteString(GetPrinterName());
parcel.WriteUint32(GetPrinterState());
if (GetPrinterIcon() != PRINT_INVALID_ID) {
parcel.WriteBool(true);
parcel.WriteBool(hasPrinterIcon_);
if (hasPrinterIcon_) {
parcel.WriteUint32(GetPrinterIcon());
} else {
parcel.WriteBool(false);
}
if (GetDescription() != "") {
parcel.WriteBool(true);
parcel.WriteBool(hasDescription_);
if (hasDescription_) {
parcel.WriteString(GetDescription());
} else {
parcel.WriteBool(false);
}
parcel.WriteBool(hasPrinterStatus_);
if (hasPrinterStatus_) {
parcel.WriteUint32(GetPrinterStatus());
}
parcel.WriteBool(hasCapability_);
@ -284,6 +357,16 @@ bool PrinterInfo::Marshalling(Parcel &parcel) const
capability_.Marshalling(parcel);
}
parcel.WriteBool(hasUri_);
if (hasUri_) {
parcel.WriteString(GetUri());
}
parcel.WriteBool(hasPrinterMake_);
if (hasPrinterMake_) {
parcel.WriteString(GetPrinterMake());
}
parcel.WriteBool(hasOption_);
if (hasOption_) {
parcel.WriteString(GetOption());
@ -299,12 +382,6 @@ bool PrinterInfo::Marshalling(Parcel &parcel) const
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;
}
@ -315,19 +392,31 @@ std::shared_ptr<PrinterInfo> PrinterInfo::Unmarshalling(Parcel &parcel)
return nativeObj;
}
void PrinterInfo::Dump()
void PrinterInfo::Dump() const
{
PRINT_HILOGD("printerId: %{private}s", printerId_.c_str());
PRINT_HILOGD("printerName: %{private}s", printerName_.c_str());
PRINT_HILOGD("printerIcon: %{public}d", printerIcon_);
PRINT_HILOGD("printerState: %{public}d", printerState_);
if (description_ != "") {
if (hasPrinterIcon_) {
PRINT_HILOGD("printerIcon: %{public}d", printerIcon_);
}
if (hasDescription_) {
PRINT_HILOGD("description: %{private}s", description_.c_str());
}
PRINT_HILOGD("description: %{private}s", description_.c_str());
if (hasPrinterStatus_) {
PRINT_HILOGD("printerStatus: %{public}d", printerStatus_);
}
if (hasCapability_) {
capability_.Dump();
}
if (hasUri_) {
PRINT_HILOGD("uri: %{private}s", option_.c_str());
}
if (hasPrinterMake_) {
PRINT_HILOGD("printerMake: %{private}s", option_.c_str());
}
if (hasOption_) {
PRINT_HILOGD("option: %{private}s", option_.c_str());
}
@ -337,8 +426,5 @@ void PrinterInfo::Dump()
if (hasIsLastUsedPrinter_) {
PRINT_HILOGD("isLastUsedPrinter: %{public}d", isLastUsedPrinter_);
}
if (hasPrinterStatus_) {
PRINT_HILOGD("printerStatus: %{public}d", printerStatus_);
}
}
} // namespace OHOS::Print

View File

@ -53,6 +53,7 @@ public:
static napi_value GetPrinterPreference(napi_env env, napi_callback_info info);
static napi_value SetPrinterPreference(napi_env env, napi_callback_info info);
static napi_value SetDefaultPrinter(napi_env env, napi_callback_info info);
static napi_value GetAddedPrinterInfoById(napi_env env, napi_callback_info info);
private:
static bool IsSupportType(const std::string& type);

View File

@ -39,6 +39,9 @@ public:
static napi_value QueryPrinterCapabilityByUri(napi_env env, napi_callback_info info);
static napi_value DeletePrinterFromCups(napi_env env, napi_callback_info info);
static napi_value DiscoverUsbPrinters(napi_env env, napi_callback_info info);
static napi_value AddPrinterToDiscovery(napi_env env, napi_callback_info info);
static napi_value UpdatePrinterInDiscovery(napi_env env, napi_callback_info info);
static napi_value RemovePrinterFromDiscovery(napi_env env, napi_callback_info info);
private:
static bool IsValidPrinterState(uint32_t state);

View File

@ -829,6 +829,41 @@ napi_value NapiInnerPrint::SetDefaultPrinter(napi_env env, napi_callback_info in
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::GetAddedPrinterInfoById(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter GetAddedPrinterInfoById---->");
auto context = std::make_shared<InnerPrintContext>();
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);
PRINT_ASSERT_BASE(env, valuetype == napi_string, "printerId number is not a string", napi_string_expected);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
context->printerId = printerId;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
PRINT_HILOGD("ouput enter---->");
*result = PrinterInfoHelper::MakeJsObject(env, context->printerInfo);
return napi_ok;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret =
PrintManagerClient::GetInstance()->QueryPrinterInfoByPrinterId(context->printerId, context->printerInfo);
context->result = ret == E_PRINT_NONE;
if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to query printerInfo from printerList");
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 NapiInnerPrint::IsSupportType(const std::string &type)
{
if (type == PRINTER_EVENT_TYPE || type == PRINTJOB_EVENT_TYPE || type == EXTINFO_EVENT_TYPE ||

View File

@ -511,6 +511,147 @@ napi_value NapiPrintExt::DiscoverUsbPrinters(napi_env env, napi_callback_info in
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::AddPrinterToDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter AddPrinterToDiscovery---->");
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_ONE, " should have 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype);
PRINT_ASSERT_BASE(env, valuetype == napi_object, " parameter is not an object!", napi_invalid_arg);
auto printerInfoPtr = PrinterInfoHelper::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]);
if (printerInfoPtr == nullptr) {
context->SetErrorIndex(E_PRINT_INVALID_PARAMETER);
PRINT_HILOGE("PrinterInfo format error!");
return napi_invalid_arg;
}
context->printerInfos.emplace_back(*printerInfoPtr);
PRINT_HILOGD("printerInfoPtr->GetPrinterId() = %{public}s", printerInfoPtr->GetPrinterId().c_str());
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) {
if (context->printerInfos.empty()) {
context->result = false;
PRINT_HILOGE("printerInfos is empty!");
return;
}
int32_t ret = PrintManagerClient::GetInstance()->AddPrinterToDiscovery(context->printerInfos.front());
context->result = ret == E_PRINT_NONE;
if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to add 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);
}
napi_value NapiPrintExt::UpdatePrinterInDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter UpdatePrinterInDiscovery---->");
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_ONE, " should have 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype);
PRINT_ASSERT_BASE(env, valuetype == napi_object, " parameter is not an object!", napi_invalid_arg);
auto printerInfoPtr = PrinterInfoHelper::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]);
if (printerInfoPtr == nullptr) {
context->SetErrorIndex(E_PRINT_INVALID_PARAMETER);
PRINT_HILOGE("PrinterInfo format error!");
return napi_invalid_arg;
}
context->printerInfos.emplace_back(*printerInfoPtr);
PRINT_HILOGD("printerInfoPtr->GetPrinterId() = %{public}s", printerInfoPtr->GetPrinterId().c_str());
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) {
if (context->printerInfos.empty()) {
context->result = false;
PRINT_HILOGE("printerInfos is empty!");
return;
}
int32_t ret = PrintManagerClient::GetInstance()->UpdatePrinterInDiscovery(context->printerInfos.front());
context->result = ret == E_PRINT_NONE;
if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to update printer");
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::RemovePrinterFromDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter RemovePrinterFromDiscovery---->");
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_ONE, " should have 1 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, "printerId is not a string", napi_string_expected);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printerId : %{private}s", printerId.c_str());
context->printerId = printerId;
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()->RemovePrinterFromDiscovery(context->printerId);
context->result = ret == E_PRINT_NONE;
if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to add 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) {

View File

@ -57,6 +57,10 @@ static constexpr const char *FUNCTION_SET_PRINTER_PREFERENCE = "setPrinterPrefer
static constexpr const char *FUNCTION_SET_DEFAULT_PRINTER = "setDefaultPrinter";
static constexpr const char *FUNCTION_DELETE_PRINTER_FROM_CUPS = "deletePrinterFromCups";
static constexpr const char *FUNCTION_DISCOVER_USB_PRINTERS = "discoverUsbPrinters";
static constexpr const char *FUNCTION_ADD_PRINTER_TO_DISCOVERY = "addPrinterToDiscovery";
static constexpr const char *FUNCTION_UPDATE_PRINTER_IN_DISCOVERY = "updatePrinterInDiscovery";
static constexpr const char *FUNCTION_REMOVE_PRINTER_FROM_DISCOVERY = "removePrinterFromDiscovery";
static constexpr const char *FUNCTION_GET_ADDED_PRINTER_INFO_BY_ID = "getAddedPrinterInfoById";
#define PRINT_NAPI_METHOD(name, func) \
{ \
@ -104,6 +108,16 @@ static napi_value NapiCreateDuplexModeEnum(napi_env env)
return object;
}
static napi_value NapiCreateQualityEnum(napi_env env)
{
napi_value object = nullptr;
napi_create_object(env, &object);
SetEnumProperty(env, object, "QUALITY_DRAFT", static_cast<int32_t>(PRINT_QUALITY_DRAFT));
SetEnumProperty(env, object, "QUALITY_NORMAL", static_cast<int32_t>(PRINT_QUALITY_NORMAL));
SetEnumProperty(env, object, "QUALITY_HIGH", static_cast<int32_t>(PRINT_QUALITY_HIGH));
return object;
}
static napi_value NapiCreatePageTypeEnum(napi_env env)
{
napi_value object = nullptr;
@ -289,6 +303,7 @@ static napi_value Init(napi_env env, napi_value exports)
PRINT_NAPI_PROPERTY("PrintDirectionMode", NapiCreateDirectionModeEnum(env)),
PRINT_NAPI_PROPERTY("PrintColorMode", NapiCreateColorModeEnum(env)),
PRINT_NAPI_PROPERTY("PrintDuplexMode", NapiCreateDuplexModeEnum(env)),
PRINT_NAPI_PROPERTY("PrintQuality", NapiCreateQualityEnum(env)),
PRINT_NAPI_PROPERTY("PrintPageType", NapiCreatePageTypeEnum(env)),
PRINT_NAPI_PROPERTY("PrintDocumentAdapterState", NapiCreateDocumentAdapterStateEnum(env)),
PRINT_NAPI_PROPERTY("PrintFileCreationState", NapiCreateFileCreationStateEnum(env)),
@ -334,6 +349,10 @@ static napi_value Init(napi_env env, napi_value exports)
PRINT_NAPI_METHOD(FUNCTION_SET_DEFAULT_PRINTER, NapiInnerPrint::SetDefaultPrinter),
PRINT_NAPI_METHOD(FUNCTION_DELETE_PRINTER_FROM_CUPS, NapiPrintExt::DeletePrinterFromCups),
PRINT_NAPI_METHOD(FUNCTION_DISCOVER_USB_PRINTERS, NapiPrintExt::DiscoverUsbPrinters),
PRINT_NAPI_METHOD(FUNCTION_ADD_PRINTER_TO_DISCOVERY, NapiPrintExt::AddPrinterToDiscovery),
PRINT_NAPI_METHOD(FUNCTION_UPDATE_PRINTER_IN_DISCOVERY, NapiPrintExt::UpdatePrinterInDiscovery),
PRINT_NAPI_METHOD(FUNCTION_REMOVE_PRINTER_FROM_DISCOVERY, NapiPrintExt::RemovePrinterFromDiscovery),
PRINT_NAPI_METHOD(FUNCTION_GET_ADDED_PRINTER_INFO_BY_ID, NapiInnerPrint::GetAddedPrinterInfoById),
};
napi_status status = napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc);

View File

@ -106,6 +106,9 @@ public:
int32_t DeletePrinterFromCups(const std::string &printerUri, const std::string &printerName,
const std::string &printerMake) override;
int32_t DiscoverUsbPrinters(std::vector<PrinterInfo> &printers) override;
int32_t AddPrinterToDiscovery(const PrinterInfo &printerInfo) override;
int32_t UpdatePrinterInDiscovery(const PrinterInfo &printerInfo) override;
int32_t RemovePrinterFromDiscovery(const std::string &printerId) override;
protected:
void OnStart() override;
@ -178,13 +181,16 @@ private:
PrintJobState DetermineUserJobStatus(const std::map<std::string, std::shared_ptr<PrintJob>> &jobList);
void NotifyAppDeletePrinterWithDefaultPrinter(const std::string &printerId);
void ChangeDefaultPrinterForDelete(std::shared_ptr<PrintUserData> &userData, const std::string &printerId);
bool UpdatePrinterCapability(const std::string &printerId, PrinterInfo &info);
bool UpdatePrinterSystemData(const std::string &printerId, PrinterInfo &info);
bool UpdatePrinterCapability(const std::string &printerId, const PrinterInfo &info);
bool UpdatePrinterSystemData(const std::string &printerId, const PrinterInfo &info);
uint32_t GetListeningState(const uint32_t subState);
uint32_t GetListeningState(uint32_t state, uint32_t subState);
std::string QueryPrinterIdByStandardizeName(const std::string &printerName);
bool CheckPrintJob(PrintJob &jobInfo);
bool CheckPrinterUriDifferent(const std::shared_ptr<PrinterInfo> &info);
int32_t AddSinglePrinterInfo(const PrinterInfo &info, const std::string &extensionId);
bool UpdateSinglePrinterInfo(const PrinterInfo &info, const std::string &extensionId);
bool RemoveSinglePrinterInfo(const std::string &printerId);
private:
PrintSecurityGuardManager securityGuardManager_;

View File

@ -35,12 +35,6 @@ enum ColorModeCode {
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

View File

@ -73,6 +73,9 @@ private:
bool OnSetDefaultPrinter(MessageParcel &data, MessageParcel &reply);
bool OnDeletePrinterFromCups(MessageParcel &data, MessageParcel &reply);
bool OnDiscoverUsbPrinters(MessageParcel &data, MessageParcel &reply);
bool OnAddPrinterToDiscovery(MessageParcel &data, MessageParcel &reply);
bool OnUpdatePrinterInDiscovery(MessageParcel &data, MessageParcel &reply);
bool OnRemovePrinterFromDiscovery(MessageParcel &data, MessageParcel &reply);
private:
using PrintCmdHandler = bool (PrintServiceStub::*)(MessageParcel &, MessageParcel &);

View File

@ -23,6 +23,8 @@
#include "printer_info.h"
#include "printer_capability.h"
#include "print_constant.h"
#include "print_utils.h"
#include "print_log.h"
namespace OHOS {
namespace Print {
@ -63,10 +65,19 @@ private:
void ConvertPrintMarginToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
void ConvertPageSizeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
void ConvertPrintResolutionToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
void ConvertSupportedColorModeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
void ConvertSupportedDuplexModeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
void ConvertSupportedMediaTypeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
void ConvertSupportedQualityToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson);
bool ConvertJsonToPrinterCapability(nlohmann::json &capsJson, PrinterCapability &printerCapability);
void ConvertJsonToPrintMargin(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToPrintMargin(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToPageSize(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToPrintResolution(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToSupportedColorMode(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToSupportedDuplexMode(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToSupportedMediaType(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToSupportedQuality(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool ConvertJsonToSupportedOrientation(nlohmann::json &capsJson, PrinterCapability &printerCapability);
bool GetPrinterCapabilityFromFile(std::string printerId, PrinterCapability &printerCapability);
bool CheckPrinterInfoJson(nlohmann::json &object, std::string &printerId);
bool GetPrinterCapabilityFromJson(
@ -74,6 +85,39 @@ private:
bool ParseUserListJsonV1(
nlohmann::json &jsonObject, std::vector<int32_t> &allPrintUserList);
template<typename T>
bool ProcessJsonToCapabilityList(nlohmann::json &capsJson,
const std::string &key,
PrinterCapability &printerCapability,
void (PrinterCapability::*setter)(const std::vector <T> &),
std::function<bool(const nlohmann::json &, T &)> converter)
{
if (!capsJson.contains(key) || !capsJson[key].is_array()) {
PRINT_HILOGW("Cannot find %{public}s or it's not an array", key.c_str());
return true;
}
PRINT_HILOGD("find Capability %{public}s success", key.c_str());
std::vector<T> resultList;
for (const auto &item: capsJson[key]) {
if (!PrintUtils::CheckJsonType<T>(item)) {
PRINT_HILOGE("%{public}s item has incorrect type", key.c_str());
return false;
}
T object;
bool ret = converter(item, object);
if (!ret) {
PRINT_HILOGE("Invalid format,key is %{public}s", key.c_str());
return false;
}
resultList.push_back(object);
}
if (!resultList.empty()) {
(printerCapability.*setter)(resultList);
}
PRINT_HILOGD("processCapabilityList success, %{public}s", key.c_str());
return true;
}
private:
std::map<std::string, std::shared_ptr<CupsPrinterInfo>> addedPrinterMap_;
std::map<uint32_t, std::string> addedPrinterOrderList_;

View File

@ -141,6 +141,7 @@ void ParseDuplexModeAttributes(ipp_t *response, PrinterCapability &printerCaps)
} else {
printerCaps.SetDuplexMode((uint32_t)DUPLEX_MODE_TWO_SIDED_LONG_EDGE);
}
printerCaps.SetSupportedDuplexMode(std::vector<uint32_t>(list.begin(), list.end()));
keyword = "sides-default";
DuplexModeCode code;
@ -170,6 +171,7 @@ void ParseColorModeAttributes(ipp_t *response, PrinterCapability &printerCaps)
break;
}
}
printerCaps.SetSupportedColorMode(std::vector<uint32_t>(supportedColorModes.begin(), supportedColorModes.end()));
}
void ParsePageSizeAttributes(ipp_t *response, PrinterCapability &printerCaps)
@ -178,7 +180,7 @@ void ParsePageSizeAttributes(ipp_t *response, PrinterCapability &printerCaps)
std::vector<PrintPageSize> supportedPageSizes;
ParseAttributesToList<PrintPageSize>(response, keyword, supportedPageSizes, ConvertPrintPageSize);
std::string pageSizeJson = ConvertListToJson<PrintPageSize>(supportedPageSizes, ConvertPageSizeToJson);
printerCaps.SetPageSize(supportedPageSizes);
printerCaps.SetSupportedPageSize(supportedPageSizes);
printerCaps.SetPrinterAttrNameAndValue("supportedPageSizeArray", pageSizeJson.c_str());
std::string defaultPageSizeId;
@ -197,14 +199,18 @@ void ParseQualityAttributes(ipp_t *response, PrinterCapability &printerCaps)
return;
}
nlohmann::json supportedQualities = nlohmann::json::array();
std::vector<uint32_t> list;
for (int i = 0; i < ippGetCount(attrPtr); i++) {
nlohmann::json jsonObject;
jsonObject["quality"] = ippGetInteger(attrPtr, i);
uint32_t value = ippGetInteger(attrPtr, i);
jsonObject["quality"] = value;
supportedQualities.push_back(jsonObject);
list.emplace_back(value);
}
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());
printerCaps.SetSupportedQuality(list);
}
void ParseCopiesAttributes(ipp_t *response, PrinterCapability &printerCaps)
@ -234,6 +240,7 @@ void ParseSupportedResolutionAttribute(ipp_t *response, PrinterCapability &print
int num = ippGetCount(attrPtr);
PRINT_HILOGD("number of values %{public}d", num);
nlohmann::json resolutionArray = nlohmann::json::array();
std::vector<PrintResolution> list;
for (int i = 0; i < num; i++) {
ipp_res_t units = IPP_RES_PER_INCH;
int xres = 0;
@ -252,8 +259,13 @@ void ParseSupportedResolutionAttribute(ipp_t *response, PrinterCapability &print
nlohmann::json object;
object["horizontalDpi"] = xres;
object["verticalDpi"] = yres;
PrintResolution printResolution;
printResolution.SetHorizontalDpi(xres);
printResolution.SetVerticalDpi(yres);
list.emplace_back(printResolution);
resolutionArray.push_back(object);
}
printerCaps.SetResolution(list);
printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), resolutionArray.dump().c_str());
}
@ -364,12 +376,16 @@ void ParseOrientationAttributes(ipp_t *response, PrinterCapability &printerCaps)
int num = ippGetCount(attrPtr);
if (num > 0) {
nlohmann::json supportedOrientationArray = nlohmann::json::array();
std::vector<uint32_t> supportedOrientations;
supportedOrientations.reserve(num);
for (int i = 0; i < ippGetCount(attrPtr); i++) {
int orientationEnum = ippGetInteger(attrPtr, i);
supportedOrientationArray.push_back(orientationEnum);
supportedOrientations.emplace_back(orientationEnum);
PRINT_HILOGD("orientation-supported found: %{public}d", orientationEnum);
}
printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), supportedOrientationArray.dump().c_str());
printerCaps.SetSupportedOrientation(supportedOrientations);
}
}
}
@ -405,9 +421,26 @@ void SetOptionAttribute(ipp_t *response, PrinterCapability &printerCaps)
options["printerName"] = ippGetString(attrPtr, 0, NULL);
}
std::string keyword = "media-type-supported";
std::string supportTypes = ConvertIppAttributesToJsonString(response, keyword);
std::string supportTypes;
std::vector<std::string> list;
attrPtr = ippFindAttribute(response, keyword.c_str(), IPP_TAG_KEYWORD);
if (attrPtr == nullptr) {
supportTypes = "";
} else {
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);
list.emplace_back(attrString);
}
supportTypes = jsonArray.dump();
}
PRINT_HILOGD("%{public}s: %{public}s", keyword.c_str(), supportTypes.c_str());
if (!supportTypes.empty()) {
printerCaps.SetSupportedMediaType(list);
printerCaps.SetPrinterAttrNameAndValue(keyword.c_str(), supportTypes.c_str());
}

View File

@ -121,9 +121,15 @@ std::chrono::time_point<std::chrono::high_resolution_clock> PrintServiceAbility:
std::string PrintServiceAbility::ingressPackage;
PrintServiceAbility::PrintServiceAbility(int32_t systemAbilityId, bool runOnCreate)
: SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START),
spoolerBundleName_(SPOOLER_BUNDLE_NAME), spoolerAbilityName_(SPOOLER_ABILITY_NAME), currentJobOrderId_(0),
helper_(nullptr), isJobQueueBlocked_(false), currentUserId_(-1), printAppCount_(0), unloadCount_(0)
: SystemAbility(systemAbilityId, runOnCreate),
state_(ServiceRunningState::STATE_NOT_START),
spoolerBundleName_(SPOOLER_BUNDLE_NAME),
spoolerAbilityName_(SPOOLER_ABILITY_NAME),
currentJobOrderId_(0),
helper_(nullptr),
isJobQueueBlocked_(false),
currentUserId_(-1),
printAppCount_(0)
{}
PrintServiceAbility::~PrintServiceAbility()
@ -632,26 +638,25 @@ int32_t PrintServiceAbility::QueryPrinterInfoByPrinterId(const std::string &prin
PRINT_HILOGD("QueryPrinterInfoByPrinterId started %{public}s", printerId.c_str());
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
info.SetPrinterId(printerId);
bool findCapsInSystemData = false;
OHOS::Print::CupsPrinterInfo cupsPrinter;
if (printSystemData_.QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinter)) {
info.SetPrinterName(PrintUtil::RemoveUnderlineFromPrinterName(cupsPrinter.name));
nlohmann::json option;
option["printerName"] = cupsPrinter.name;
option["printerUri"] = cupsPrinter.uri;
option["make"] = cupsPrinter.maker;
option["printerUri"] = cupsPrinter.uri; // Deprecated, to be removed in a future version.
option["make"] = cupsPrinter.maker; // Deprecated, to be removed in a future version.
option["alias"] = cupsPrinter.alias;
info.SetOption(option.dump());
PrinterCapability printerCapability;
if (printSystemData_.GetPrinterCapabilityFromSystemData(cupsPrinter, printerId, printerCapability)) {
findCapsInSystemData = true;
info.SetCapability(printerCapability);
if (!cupsPrinter.uri.empty()) {
info.SetUri(cupsPrinter.uri);
}
if (!cupsPrinter.maker.empty()) {
info.SetPrinterMake(cupsPrinter.maker);
}
info.SetOption(option.dump());
info.SetCapability(cupsPrinter.printerCapability);
info.SetPrinterStatus(cupsPrinter.printerStatus);
PRINT_HILOGI("QueryPrinterInfoByPrinterId printerStatus: %{public}d", info.GetPrinterStatus());
}
PRINT_HILOGD("QueryPrinterInfoByPrinterId printerName = %{public}s", info.GetPrinterName().c_str());
if (!findCapsInSystemData) {
} else {
#ifdef CUPS_ENABLE
int32_t ret = DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPrinterInfoByPrinterId(printerId, info);
if (ret != 0) {
@ -660,9 +665,7 @@ int32_t PrintServiceAbility::QueryPrinterInfoByPrinterId(const std::string &prin
}
#endif // CUPS_ENABLE
}
if (info.HasCapability()) {
printSystemData_.InsertPrinterInfo(printerId, info);
}
PRINT_HILOGD("QueryPrinterInfoByPrinterId printerName = %{public}s", info.GetPrinterName().c_str());
if (CheckIsDefaultPrinter(printerId)) {
PRINT_HILOGI("is default printer");
info.SetIsDefaultPrinter(true);
@ -745,31 +748,6 @@ int32_t PrintServiceAbility::AddPrinterToCups(const std::string &printerUri, con
return ret;
}
#endif // CUPS_ENABLE
std::string id = QueryPrinterIdByStandardizeName(printerName);
if (id.empty()) {
PRINT_HILOGE("can not find the printer");
return E_PRINT_INVALID_PRINTER;
}
CupsPrinterInfo info;
info.name = printerName;
info.uri = printerUri;
info.maker = printerMake;
info.printerStatus = PRINTER_STATUS_IDLE;
ret = QueryPrinterCapabilityByUri(printerUri, id, info.printerCapability);
if (ret != 0) {
PRINT_HILOGE("AddPrinterToCups QueryPrinterCapabilityByUri fail");
return ret;
}
if (!printSystemData_.IsPrinterAdded(id)) {
printSystemData_.InsertCupsPrinter(id, info, true);
printSystemData_.SaveCupsPrinterMap();
PrinterInfo printerInfo;
printSystemData_.QueryPrinterInfoById(id, printerInfo);
printerInfo.SetIsLastUsedPrinter(true);
SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, printerInfo);
SendPrinterChangeEvent(PRINTER_EVENT_ADDED, printerInfo);
SetLastUsedPrinter(id);
}
PRINT_HILOGD("AddPrinterToCups End.");
return E_PRINT_NONE;
}
@ -933,7 +911,7 @@ int32_t PrintServiceAbility::BuildPrinterPreference(PrinterCapability &cap, Prin
return E_PRINT_NONE;
}
void PrintServiceAbility::BuildPrinterAttrComponentByJson(std::string& key, nlohmann::json& jsonArrObject,
void PrintServiceAbility::BuildPrinterAttrComponentByJson(std::string &key, nlohmann::json &jsonArrObject,
std::vector<std::string> &printerAttrs)
{
if (!jsonArrObject.is_array()) {
@ -1190,11 +1168,11 @@ int32_t PrintServiceAbility::StartNativePrintJob(PrintJob &printJob)
UpdateQueuedJobList(jobId, nativePrintJob);
printerJobMap_[printerId].insert(std::make_pair(jobId, true));
#ifdef CUPS_ENABLE
if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(printJob);
CallStatusBar();
return E_PRINT_NONE;
if (cid.find(PRINT_EXTENSION_BUNDLE_NAME) == string::npos) {
NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(printJob);
CallStatusBar();
return E_PRINT_NONE;
}
#endif // CUPS_ENABLE
auto cbFunc = extCallbackMap_[cid];
@ -1238,11 +1216,11 @@ int32_t PrintServiceAbility::StartPrintJob(PrintJob &jobInfo)
UpdateQueuedJobList(jobId, printJob);
printerJobMap_[printerId].insert(std::make_pair(jobId, true));
#ifdef CUPS_ENABLE
if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(jobInfo);
CallStatusBar();
return E_PRINT_NONE;
if (cid.find(PRINT_EXTENSION_BUNDLE_NAME) == string::npos) {
NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(jobInfo);
CallStatusBar();
return E_PRINT_NONE;
}
#endif // CUPS_ENABLE
auto cbFunc = extCallbackMap_[cid];
@ -1380,7 +1358,7 @@ int32_t PrintServiceAbility::CancelPrintJob(const std::string &jobId)
return E_PRINT_SERVER_FAILURE;
}
#ifdef CUPS_ENABLE
if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
if (cid.find(PRINT_EXTENSION_BUNDLE_NAME) == string::npos) {
DelayedSingleton<PrintCupsClient>::GetInstance()->CancelCupsJob(jobIt->second->GetJobId());
return E_PRINT_NONE;
}
@ -1500,9 +1478,9 @@ void PrintServiceAbility::SendQueuePrintJob(const std::string &printerId)
auto extensionId = PrintUtils::GetExtensionId(printerId);
std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT);
#ifdef CUPS_ENABLE
if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
PRINT_HILOGD("default spooler extension, no need SendQueuePrintJob");
return;
if (cid.find(PRINT_EXTENSION_BUNDLE_NAME) != string::npos) {
PRINT_HILOGD("not eprint extension, no need SendQueuePrintJob");
return;
}
#endif // CUPS_ENABLE
@ -1546,38 +1524,16 @@ int32_t PrintServiceAbility::AddPrinters(const std::vector<PrinterInfo> &printer
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
PRINT_HILOGD("AddPrinters started. Total size is %{public}zd", printerInfoList_.size());
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
PRINT_HILOGD("AddPrinters started. Total size is %{public}zd", printerInfoList_.size());
std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
for (auto info : printerInfos) {
if (printerInfoList_.find(info.GetPrinterId()) != printerInfoList_.end()) {
PRINT_HILOGW("duplicate printer id, ignore it");
continue;
}
auto printerInfo = std::make_shared<PrinterInfo>(info);
printerInfo->SetPrinterId(PrintUtils::GetGlobalId(extensionId, printerInfo->GetPrinterId()));
PRINT_HILOGD("AddPrinters printerId = %{public}s", printerInfo->GetPrinterId().c_str());
printerInfo->SetPrinterState(PRINTER_ADDED);
printerInfoList_[printerInfo->GetPrinterId()] = printerInfo;
SendPrinterDiscoverEvent(PRINTER_ADDED, *printerInfo);
SendPrinterEvent(*printerInfo);
SendQueuePrintJob(printerInfo->GetPrinterId());
if (printSystemData_.IsPrinterAdded(printerInfo->GetPrinterId()) &&
!printSystemData_.CheckPrinterBusy(printerInfo->GetPrinterId())) {
if (CheckPrinterUriDifferent(printerInfo)) {
PRINT_HILOGW("different printer uri, ignore it");
} else {
printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE);
printSystemData_.UpdatePrinterStatus(printerInfo->GetPrinterId(), PRINTER_STATUS_IDLE);
SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
}
}
for (auto &info : printerInfos) {
AddSinglePrinterInfo(info, extensionId);
}
PRINT_HILOGD("AddPrinters end. Total size is %{public}zd", printerInfoList_.size());
return E_PRINT_NONE;
}
@ -1597,30 +1553,21 @@ int32_t PrintServiceAbility::RemovePrinters(const std::vector<std::string> &prin
std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
for (auto printerId : printerIds) {
printerId = PrintUtils::GetGlobalId(extensionId, printerId);
PRINT_HILOGD("RemovePrinters printerId = %{public}s", printerId.c_str());
auto printerIt = printerInfoList_.find(printerId);
if (printerIt == printerInfoList_.end()) {
PRINT_HILOGE("invalid printer id, ingore it");
continue;
}
PrinterInfo info = *printerIt->second;
info.SetPrinterState(PRINTER_REMOVED);
SendPrinterDiscoverEvent(PRINTER_REMOVED, info);
SendPrinterEvent(info);
printerInfoList_.erase(printerIt);
if (printSystemData_.IsPrinterAdded(info.GetPrinterId())) {
info.SetPrinterStatus(PRINTER_STATUS_UNAVAILABLE);
printSystemData_.UpdatePrinterStatus(info.GetPrinterId(), PRINTER_STATUS_UNAVAILABLE);
SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, info);
SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, info);
bool anyPrinterRemoved = false;
for (const auto& printerId : printerIds) {
std::string globalPrinterId = PrintUtils::GetGlobalId(extensionId, printerId);
PRINT_HILOGD("RemovePrinters printerId = %{public}s", globalPrinterId.c_str());
if (RemoveSinglePrinterInfo(globalPrinterId)) {
anyPrinterRemoved = true;
}
}
if (count == printerInfoList_.size()) {
if (!anyPrinterRemoved) {
PRINT_HILOGE("Invalid printer ids");
return E_PRINT_INVALID_PARAMETER;
}
PRINT_HILOGD("RemovePrinters end. Total size is %{public}zd", printerInfoList_.size());
return E_PRINT_NONE;
}
@ -1635,46 +1582,26 @@ int32_t PrintServiceAbility::UpdatePrinters(const std::vector<PrinterInfo> &prin
PRINT_HILOGD("UpdatePrinters started. Total size is %{public}zd", printerInfoList_.size());
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
std::vector<std::shared_ptr<PrinterInfo>> updatedPrinters;
bool isChanged = false;
for (auto info: printerInfos) {
std::string printExtId = info.GetPrinterId();
if (printExtId.find(SPOOLER_PACKAGE_NAME) == std::string::npos &&
printExtId.find(PRINT_EXTENSION_BUNDLE_NAME) == std::string::npos) {
printExtId = PrintUtils::GetGlobalId(extensionId, printExtId);
}
if (UpdatePrinterSystemData(printExtId, info)) {
isChanged = true;
}
auto printerIt = printerInfoList_.find(printExtId);
if (printerIt == printerInfoList_.end()) {
PRINT_HILOGE("invalid printer id, ignore it");
continue;
}
*printerIt->second = info;
printerIt->second->SetPrinterState(PRINTER_UPDATE_CAP);
printerIt->second->SetPrinterId(printExtId);
if (printerIt->second->HasCapability()) {
if (UpdatePrinterCapability(printExtId, info)) {
isChanged = true;
}
updatedPrinters.push_back(printerIt->second);
}
bool isAnyPrinterChanged = false;
for (const auto &info : printerInfos) {
bool isPrinterChanged = UpdateSinglePrinterInfo(info, extensionId);
isAnyPrinterChanged |= isPrinterChanged;
}
if (isChanged) {
if (isAnyPrinterChanged) {
printSystemData_.SaveCupsPrinterMap();
}
for (const auto &printerInfo: updatedPrinters) {
SendPrinterDiscoverEvent(PRINTER_UPDATE_CAP, *printerInfo);
SendPrinterEvent(*printerInfo);
}
PRINT_HILOGD("UpdatePrinters end. Total size is %{private}zd", printerInfoList_.size());
return E_PRINT_NONE;
}
bool PrintServiceAbility::UpdatePrinterSystemData(const std::string &printerId, PrinterInfo &info)
bool PrintServiceAbility::UpdatePrinterSystemData(const std::string &printerId, const PrinterInfo &info)
{
std::string option = info.GetOption();
if (json::accept(option)) {
@ -1689,7 +1616,7 @@ bool PrintServiceAbility::UpdatePrinterSystemData(const std::string &printerId,
return false;
}
bool PrintServiceAbility::UpdatePrinterCapability(const std::string &printerId, PrinterInfo &info)
bool PrintServiceAbility::UpdatePrinterCapability(const std::string &printerId, const PrinterInfo &info)
{
PRINT_HILOGI("UpdatePrinterCapability Enter");
if (printerId.compare(0, EPRINTER_ID.size(), EPRINTER_ID) == 0) {
@ -1699,22 +1626,21 @@ bool PrintServiceAbility::UpdatePrinterCapability(const std::string &printerId,
info.GetCapability(printerCaps);
WriteEprinterPreference(printerId, printerCaps);
}
if (printerId.compare(0, SPOOLER_PACKAGE_NAME.size(), SPOOLER_PACKAGE_NAME) != 0) {
CupsPrinterInfo cupsPrinterInfo;
cupsPrinterInfo.name = info.GetPrinterName();
info.GetCapability(cupsPrinterInfo.printerCapability);
cupsPrinterInfo.printerStatus = PRINTER_STATUS_IDLE;
printSystemData_.InsertCupsPrinter(printerId, cupsPrinterInfo, true);
info.SetIsLastUsedPrinter(true);
info.SetPrinterStatus(PRINTER_STATUS_IDLE);
info.SetPrinterId(printerId);
SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, info);
SendPrinterChangeEvent(PRINTER_EVENT_ADDED, info);
SetLastUsedPrinter(printerId);
return true;
}
return false;
CupsPrinterInfo cupsPrinterInfo;
auto output = info;
cupsPrinterInfo.name = info.GetPrinterName();
cupsPrinterInfo.uri = info.GetUri();
cupsPrinterInfo.maker = info.GetPrinterMake();
cupsPrinterInfo.printerStatus = PRINTER_STATUS_IDLE;
info.GetCapability(cupsPrinterInfo.printerCapability);
printSystemData_.InsertCupsPrinter(printerId, cupsPrinterInfo, true);
output.SetIsLastUsedPrinter(true);
output.SetPrinterStatus(PRINTER_STATUS_IDLE);
output.SetPrinterId(printerId);
SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, output);
SendPrinterChangeEvent(PRINTER_EVENT_ADDED, output);
SetLastUsedPrinter(printerId);
return true;
}
int32_t PrintServiceAbility::UpdatePrinterState(const std::string &printerId, uint32_t state)
@ -2212,7 +2138,7 @@ int32_t PrintServiceAbility::UnregisterPrinterCallback(const std::string &type)
int32_t PrintServiceAbility::RegisterExtCallback(const std::string &extensionCID,
const sptr<IPrintExtensionCallback> &listener)
{
if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
if (!CheckPermission(PERMISSION_NAME_PRINT)) {
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
@ -2261,7 +2187,7 @@ int32_t PrintServiceAbility::RegisterExtCallback(const std::string &extensionCID
int32_t PrintServiceAbility::UnregisterAllExtCallback(const std::string &extensionId)
{
if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
if (!CheckPermission(PERMISSION_NAME_PRINT)) {
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
@ -2281,12 +2207,12 @@ int32_t PrintServiceAbility::UnregisterAllExtCallback(const std::string &extensi
int32_t PrintServiceAbility::LoadExtSuccess(const std::string &extensionId)
{
if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
if (!CheckPermission(PERMISSION_NAME_PRINT)) {
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
PRINT_HILOGD("PrintServiceAbility::LoadExtSuccess started.");
PRINT_HILOGD("PrintServiceAbility::LoadExtSuccess started. extensionId=%{public}s:", extensionId.c_str());
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
if (extensionStateList_.find(extensionId) == extensionStateList_.end()) {
PRINT_HILOGE("Invalid extension id");
@ -2326,6 +2252,7 @@ int32_t PrintServiceAbility::On(const std::string taskId, const std::string &typ
}
if (type == PRINTER_CHANGE_EVENT_TYPE) {
permission = PERMISSION_NAME_PRINT;
int32_t callerPid = IPCSkeleton::GetCallingPid();
eventType = PrintUtils::GetEventTypeWithToken(callerPid, type);
}
@ -2375,6 +2302,7 @@ int32_t PrintServiceAbility::Off(const std::string taskId, const std::string &ty
eventType = PrintUtils::GetTaskEventId(taskId, type);
}
if (type == PRINTER_CHANGE_EVENT_TYPE) {
permission = PERMISSION_NAME_PRINT;
int32_t callerPid = IPCSkeleton::GetCallingPid();
eventType = PrintUtils::GetEventTypeWithToken(callerPid, type);
}
@ -2442,6 +2370,7 @@ void PrintServiceAbility::SendPrinterChangeEvent(int event, const PrinterInfo &i
}
}
}
void PrintServiceAbility::SendPrinterEvent(const PrinterInfo &info)
{
PRINT_HILOGD("PrintServiceAbility::SendPrinterEvent type %{private}s, %{public}d",
@ -2963,6 +2892,60 @@ int32_t PrintServiceAbility::DeletePrinterFromCups(
return E_PRINT_NONE;
}
int32_t PrintServiceAbility::AddPrinterToDiscovery(const PrinterInfo &printerInfo)
{
ManualStart();
if (!CheckPermission(PERMISSION_NAME_PRINT)) {
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
PRINT_HILOGD("AddPrinterToDiscovery started. Current total size is %{public}zd", printerInfoList_.size());
std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
int32_t result = AddSinglePrinterInfo(printerInfo, extensionId);
PRINT_HILOGD("AddPrinterToDiscovery end. New total size is %{public}zd", printerInfoList_.size());
return result;
}
int32_t PrintServiceAbility::UpdatePrinterInDiscovery(const PrinterInfo &printerInfo)
{
ManualStart();
if (!CheckPermission(PERMISSION_NAME_PRINT)) {
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
int32_t ret = AddPrinterToCups(printerInfo.GetUri(), printerInfo.GetPrinterName(), printerInfo.GetPrinterMake());
if (ret == E_PRINT_NONE) {
UpdateSinglePrinterInfo(printerInfo, extensionId);
}
return E_PRINT_NONE;
}
int32_t PrintServiceAbility::RemovePrinterFromDiscovery(const std::string &printerId)
{
ManualStart();
if (!CheckPermission(PERMISSION_NAME_PRINT)) {
PRINT_HILOGE("no permission to access print service");
return E_PRINT_NO_PERMISSION;
}
std::lock_guard<std::recursive_mutex> lock(apiMutex_);
std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
bool result = RemoveSinglePrinterInfo(PrintUtils::GetGlobalId(extensionId, printerId));
return result ? E_PRINT_NONE : E_PRINT_INVALID_PRINTER;
}
void PrintServiceAbility::DeletePrinterFromUserData(const std::string &printerId)
{
std::vector<int32_t> allPrintUserList;
@ -3072,4 +3055,87 @@ int32_t PrintServiceAbility::DiscoverUsbPrinters(std::vector<PrinterInfo> &print
PRINT_HILOGD("DiscoverUsbDevices printers size: %{public}zu", printers.size());
return E_PRINT_NONE;
}
int32_t PrintServiceAbility::AddSinglePrinterInfo(const PrinterInfo &info, const std::string &extensionId)
{
if (printerInfoList_.find(info.GetPrinterId()) != printerInfoList_.end()) {
PRINT_HILOGE("duplicate printer id, ignore it");
return E_PRINT_INVALID_PRINTER;
}
auto infoPtr = std::make_shared<PrinterInfo>(info);
infoPtr->SetPrinterId(PrintUtils::GetGlobalId(extensionId, infoPtr->GetPrinterId()));
PRINT_HILOGD("Printer ID = %{public}s", infoPtr->GetPrinterId().c_str());
infoPtr->SetPrinterState(PRINTER_ADDED);
printerInfoList_[infoPtr->GetPrinterId()] = infoPtr;
SendPrinterDiscoverEvent(PRINTER_ADDED, *infoPtr);
SendPrinterEvent(*infoPtr);
SendQueuePrintJob(infoPtr->GetPrinterId());
if (printSystemData_.IsPrinterAdded(infoPtr->GetPrinterId()) &&
!printSystemData_.CheckPrinterBusy(infoPtr->GetPrinterId())) {
infoPtr->SetPrinterStatus(PRINTER_STATUS_IDLE);
printSystemData_.UpdatePrinterStatus(infoPtr->GetPrinterId(), PRINTER_STATUS_IDLE);
SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *infoPtr);
SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *infoPtr);
}
return E_PRINT_NONE;
}
bool PrintServiceAbility::UpdateSinglePrinterInfo(const PrinterInfo &info, const std::string &extensionId)
{
std::string printExtId = info.GetPrinterId();
printExtId = PrintUtils::GetGlobalId(extensionId, printExtId);
bool isSystemDataUpdated = UpdatePrinterSystemData(printExtId, info);
auto printerIt = printerInfoList_.find(printExtId);
if (printerIt == printerInfoList_.end()) {
PRINT_HILOGE("invalid printer id, ignore it");
return false;
}
*printerIt->second = info;
printerIt->second->SetPrinterState(PRINTER_UPDATE_CAP);
printerIt->second->SetPrinterId(printExtId);
printerIt->second->Dump();
bool isCapabilityUpdated = false;
if (printerIt->second->HasCapability()) {
isCapabilityUpdated = UpdatePrinterCapability(printExtId, info);
}
bool isChanged = isSystemDataUpdated || isCapabilityUpdated;
if (isChanged) {
SendPrinterEvent(*printerIt->second);
SendPrinterDiscoverEvent(PRINTER_UPDATE_CAP, *printerIt->second);
printSystemData_.SaveCupsPrinterMap();
}
return isChanged;
}
bool PrintServiceAbility::RemoveSinglePrinterInfo(const std::string &printerId)
{
auto printerIt = printerInfoList_.find(printerId);
if (printerIt == printerInfoList_.end()) {
PRINT_HILOGE("invalid printer id, ignore it");
return false;
}
PrinterInfo info = *printerIt->second;
info.SetPrinterState(PRINTER_REMOVED);
SendPrinterDiscoverEvent(PRINTER_REMOVED, info);
SendPrinterEvent(info);
printerInfoList_.erase(printerIt);
if (printSystemData_.IsPrinterAdded(info.GetPrinterId())) {
info.SetPrinterStatus(PRINTER_STATUS_UNAVAILABLE);
printSystemData_.UpdatePrinterStatus(info.GetPrinterId(), PRINTER_STATUS_UNAVAILABLE);
SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, info);
SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, info);
}
return true;
}
} // namespace OHOS::Print

View File

@ -78,6 +78,11 @@ PrintServiceStub::PrintServiceStub()
cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_DELETE_PRINTER_FROM_CUPS] =
&PrintServiceStub::OnDeletePrinterFromCups;
cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_DISCOVER_USB_PRINTERS] = &PrintServiceStub::OnDiscoverUsbPrinters;
cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_ADDPRINTERTODISCOVERY] = &PrintServiceStub::OnAddPrinterToDiscovery;
cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_UPDATEPRINTERINDISCOVERY] =
&PrintServiceStub::OnUpdatePrinterInDiscovery;
cmdMap_[OHOS::Print::IPrintInterfaceCode::CMD_REMOVEPRINTERFROMDISCOVERY] =
&PrintServiceStub::OnRemovePrinterFromDiscovery;
}
int32_t PrintServiceStub::OnRemoteRequest(
@ -720,4 +725,55 @@ bool PrintServiceStub::OnNotifyPrintService(MessageParcel &data, MessageParcel &
PRINT_HILOGD("PrintServiceStub::OnNotifyPrintService out");
return ret == E_PRINT_NONE;
}
bool PrintServiceStub::OnAddPrinterToDiscovery(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnAddPrinterToDiscovery in");
auto infoPtr = PrinterInfo::Unmarshalling(data);
if (infoPtr == nullptr) {
PRINT_HILOGW("invalid printer object");
reply.WriteInt32(E_PRINT_RPC_FAILURE);
PRINT_HILOGD("PrintServiceStub::OnAddPrinterToDiscovery out with failure");
return false;
}
infoPtr->Dump();
int32_t ret = AddPrinterToDiscovery(*infoPtr);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnAddPrinterToDiscovery out with ret = %{public}d", ret);
return ret == E_PRINT_NONE;
}
bool PrintServiceStub::OnUpdatePrinterInDiscovery(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnUpdatePrinterInDiscovery in");
auto infoPtr = PrinterInfo::Unmarshalling(data);
if (infoPtr == nullptr) {
PRINT_HILOGE("Failed to unmarshall printer info");
reply.WriteInt32(E_PRINT_RPC_FAILURE);
return false;
}
infoPtr->Dump();
int32_t ret = UpdatePrinterInDiscovery(*infoPtr);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnUpdatePrinterInDiscovery out");
return ret == E_PRINT_NONE;
}
bool PrintServiceStub::OnRemovePrinterFromDiscovery(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnRemovePrinterFromDiscovery in");
std::string printerId = data.ReadString();
int32_t ret = RemovePrinterFromDiscovery(printerId);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnRemovePrinterFromDiscovery out");
return ret == E_PRINT_NONE;
}
} // namespace OHOS::Print

View File

@ -355,13 +355,34 @@ void PrintSystemData::ConvertPrinterCapabilityToJson(PrinterCapability &printerC
{
capsJson["colorMode"] = printerCapability.GetColorMode();
capsJson["duplexMode"] = printerCapability.GetDuplexMode();
ConvertPageSizeToJson(printerCapability, capsJson);
if (printerCapability.HasMargin()) {
ConvertPrintMarginToJson(printerCapability, capsJson);
}
ConvertPageSizeToJson(printerCapability, capsJson);
if (printerCapability.HasResolution()) {
ConvertPrintResolutionToJson(printerCapability, capsJson);
}
if (printerCapability.HasSupportedColorMode()) {
ConvertSupportedColorModeToJson(printerCapability, capsJson);
}
if (printerCapability.HasSupportedDuplexMode()) {
ConvertSupportedDuplexModeToJson(printerCapability, capsJson);
}
if (printerCapability.HasSupportedMediaType()) {
ConvertSupportedMediaTypeToJson(printerCapability, capsJson);
}
if (printerCapability.HasSupportedQuality()) {
ConvertSupportedQualityToJson(printerCapability, capsJson);
}
if (printerCapability.HasOption()) {
std::string options = printerCapability.GetOption();
if (!nlohmann::json::accept(options)) {
@ -387,11 +408,55 @@ void PrintSystemData::ConvertPrintResolutionToJson(PrinterCapability &printerCap
capsJson["resolution"] = resolutionListJson;
}
void PrintSystemData::ConvertSupportedColorModeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson)
{
nlohmann::json SupportedColorModeListJson = nlohmann::json::array();
std::vector<uint32_t> SupportedColorModeList;
printerCapability.GetSupportedColorMode(SupportedColorModeList);
for (auto iter : SupportedColorModeList) {
SupportedColorModeListJson.push_back(iter);
}
capsJson["supportedColorMode"] = SupportedColorModeListJson;
}
void PrintSystemData::ConvertSupportedDuplexModeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson)
{
nlohmann::json supportedDuplexModeListJson = nlohmann::json::array();
std::vector<uint32_t> supportedDuplexModeList;
printerCapability.GetSupportedDuplexMode(supportedDuplexModeList);
for (auto iter : supportedDuplexModeList) {
supportedDuplexModeListJson.push_back(iter);
}
capsJson["supportedDuplexMode"] = supportedDuplexModeListJson;
}
void PrintSystemData::ConvertSupportedMediaTypeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson)
{
nlohmann::json supportedMediaTypeListJson = nlohmann::json::array();
std::vector<std::string> supportedMediaTypeList;
printerCapability.GetSupportedMediaType(supportedMediaTypeList);
for (auto iter : supportedMediaTypeList) {
supportedMediaTypeListJson.push_back(iter);
}
capsJson["supportedMediaType"] = supportedMediaTypeListJson;
}
void PrintSystemData::ConvertSupportedQualityToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson)
{
nlohmann::json supportedQualityListJson = nlohmann::json::array();
std::vector<uint32_t> supportedQualityList;
printerCapability.GetSupportedQuality(supportedQualityList);
for (auto iter : supportedQualityList) {
supportedQualityListJson.push_back(iter);
}
capsJson["supportedQuality"] = supportedQualityListJson;
}
void PrintSystemData::ConvertPageSizeToJson(PrinterCapability &printerCapability, nlohmann::json &capsJson)
{
nlohmann::json pageSizeListJson = nlohmann::json::array();
std::vector<PrintPageSize> pageSizeList;
printerCapability.GetPageSize(pageSizeList);
printerCapability.GetSupportedPageSize(pageSizeList);
for (auto iter : pageSizeList) {
nlohmann::json pageSizeJson = nlohmann::json::object();
pageSizeJson["id"] = iter.GetId();
@ -429,12 +494,13 @@ bool PrintSystemData::ConvertJsonToPrinterCapability(nlohmann::json &capsJson, P
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.SetColorMode(capsJson["colorMode"].get<uint32_t>());
printerCapability.SetDuplexMode(capsJson["duplexMode"].get<uint32_t>());
if (capsJson.contains("minMargin") && capsJson["minMargin"].is_object()) {
@ -442,140 +508,166 @@ bool PrintSystemData::ConvertJsonToPrinterCapability(nlohmann::json &capsJson, P
ConvertJsonToPrintMargin(capsJson, printerCapability);
}
if (!capsJson.contains("pageSize") || !capsJson["pageSize"].is_array()) {
PRINT_HILOGW("can not find pageSize");
if (!ConvertJsonToPrintResolution(capsJson, printerCapability)) {
PRINT_HILOGW("convert json to print resolution failed");
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 (!ConvertJsonToSupportedColorMode(capsJson, printerCapability)) {
PRINT_HILOGW("convert json to supportedColorMode failed.");
return false;
}
if (!ConvertJsonToSupportedDuplexMode(capsJson, printerCapability)) {
PRINT_HILOGW("convert json to supportedDuplexMode failed.");
return false;
}
if (!ConvertJsonToSupportedMediaType(capsJson, printerCapability)) {
PRINT_HILOGW("convert json to supportedMediaType failed.");
return false;
}
if (!ConvertJsonToSupportedQuality(capsJson, printerCapability)) {
PRINT_HILOGW("convert json to supportedQuality failed.");
return false;
}
if (!ConvertJsonToSupportedOrientation(capsJson, printerCapability)) {
PRINT_HILOGW("convert json to supportedOrientation 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;
return ProcessJsonToCapabilityList<PrintPageSize>(
capsJson, "pageSize", printerCapability, &PrinterCapability::SetSupportedPageSize,
[](const nlohmann::json &item, PrintPageSize &pageSize) -> bool {
if (!item.is_object() ||
!item.contains("id") ||!PrintUtils::CheckJsonType<std::string>(item["id"]) ||
!item.contains("name") ||!PrintUtils::CheckJsonType<std::string>(item["name"]) ||
!item.contains("width") ||!PrintUtils::CheckJsonType<uint32_t>(item["width"]) ||
!item.contains("height") ||!PrintUtils::CheckJsonType<uint32_t>(item["height"])) {
return false;
}
pageSize.SetId(item["id"].get<std::string>());
pageSize.SetName(item["name"].get<std::string>());
pageSize.SetWidth(item["width"].get<uint32_t>());
pageSize.SetHeight(item["height"].get<uint32_t>());
return true;
}
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)
bool PrintSystemData::ConvertJsonToPrintResolution(nlohmann::json &capsJson, PrinterCapability &printerCapability)
{
return ProcessJsonToCapabilityList<PrintResolution>(capsJson, "resolution", printerCapability,
&PrinterCapability::SetResolution,
[](const nlohmann::json &item, PrintResolution &resolution) -> bool {
if (!item.is_object() ||
!item.contains("id") || !PrintUtils::CheckJsonType<std::string>(item["id"]) ||
!item.contains("horizontalDpi") || !PrintUtils::CheckJsonType<uint32_t>(item["horizontalDpi"]) ||
!item.contains("verticalDpi") || !PrintUtils::CheckJsonType<uint32_t>(item["verticalDpi"])) {
return false;
}
resolution.SetId(item["id"].get<std::string>());
resolution.SetHorizontalDpi(item["horizontalDpi"].get<uint32_t>());
resolution.SetVerticalDpi(item["verticalDpi"].get<uint32_t>());
return true;
}
);
}
bool PrintSystemData::ConvertJsonToSupportedColorMode(nlohmann::json &capsJson, PrinterCapability &printerCapability)
{
return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedColorMode", printerCapability,
&PrinterCapability::SetSupportedColorMode,
[](const nlohmann::json &item, uint32_t &colorMode) -> bool {
colorMode = item.get<uint32_t>();
return true;
});
}
bool PrintSystemData::ConvertJsonToSupportedDuplexMode(nlohmann::json &capsJson, PrinterCapability &printerCapability)
{
return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedDuplexMode", printerCapability,
&PrinterCapability::SetSupportedColorMode,
[](const nlohmann::json &item, uint32_t &colorMode) -> bool {
colorMode = item.get<uint32_t>();
return true;
});
}
bool PrintSystemData::ConvertJsonToSupportedMediaType(nlohmann::json &capsJson, PrinterCapability &printerCapability)
{
return ProcessJsonToCapabilityList<std::string>(capsJson, "supportedMediaType", printerCapability,
&PrinterCapability::SetSupportedMediaType,
[](const nlohmann::json &item, std::string &colorMode) -> bool {
colorMode = item.get<std::string>();
return true;
});
}
bool PrintSystemData::ConvertJsonToSupportedQuality(nlohmann::json &capsJson, PrinterCapability &printerCapability)
{
return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedQuality", printerCapability,
&PrinterCapability::SetSupportedQuality,
[](const nlohmann::json &item, uint32_t &colorMode) -> bool {
colorMode = item.get<uint32_t>();
return true;
});
}
bool PrintSystemData::ConvertJsonToSupportedOrientation(nlohmann::json &capsJson, PrinterCapability &printerCapability)
{
return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedOrientation", printerCapability,
&PrinterCapability::SetSupportedOrientation,
[](const nlohmann::json &item, uint32_t &colorMode) -> bool {
colorMode = item.get<uint32_t>();
return true;
});
}
bool 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);
if (!marginJson.is_object() ||
!marginJson.contains("top") || !PrintUtils::CheckJsonType<std::string>(marginJson["top"]) ||
!marginJson.contains("bottom") || !PrintUtils::CheckJsonType<std::string>(marginJson["bottom"]) ||
!marginJson.contains("left") || !PrintUtils::CheckJsonType<uint32_t>(marginJson["left"]) ||
!marginJson.contains("right") || !PrintUtils::CheckJsonType<uint32_t>(marginJson["right"])) {
PRINT_HILOGE("Invalid format,key is minMargin");
return false;
}
minMargin.SetTop(marginJson["top"].get<uint32_t>());
minMargin.SetTop(marginJson["bottom"].get<uint32_t>());
minMargin.SetLeft(marginJson["left"].get<uint32_t>());
minMargin.SetRight(marginJson["right"].get<uint32_t>());
printerCapability.SetMinMargin(minMargin);
PRINT_HILOGD("ProcessJsonToCapabilityList success, key is minMargin");
return true;
}
bool PrintSystemData::GetPrinterCapabilityFromSystemData(
CupsPrinterInfo &cupsPrinter, std::string printerId, PrinterCapability &printerCapability)
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) {
if (!pageSizeList.empty()) {
PRINT_HILOGI("find printer capability in system data");
printerCapability = cupsPrinterCaps;
return true;

View File

@ -2613,5 +2613,50 @@ HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0157, TestSize.Level1)
EXPECT_EQ(ret, E_PRINT_NO_PERMISSION);
}
/**
* @tc.name: PrintManagerClientTest_0023
* @tc.desc: AddPrinterToDiscovery failed case.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0158, TestSize.Level1)
{
PrinterInfo info;
PrintManagerClient::GetInstance()->LoadServerFail();
PrintManagerClient::GetInstance()->ResetProxy();
int32_t ret = PrintManagerClient::GetInstance()->AddPrinterToDiscovery(info);
EXPECT_EQ(ret, E_PRINT_NO_PERMISSION);
}
/**
* @tc.name: PrintManagerClientTest_0023
* @tc.desc: UpdatePrinterInDiscovery failed case.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0159, TestSize.Level1)
{
PrinterInfo info;
PrintManagerClient::GetInstance()->LoadServerFail();
PrintManagerClient::GetInstance()->ResetProxy();
int32_t ret = PrintManagerClient::GetInstance()->UpdatePrinterInDiscovery(info);
EXPECT_EQ(ret, E_PRINT_NO_PERMISSION);
}
/**
* @tc.name: PrintManagerClientTest_0160
* @tc.desc: UpdatePrinterInDiscovery failed case.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PrintManagerClientTest, PrintManagerClientTest_0160, TestSize.Level1)
{
std::string printerId = "test";
PrintManagerClient::GetInstance()->LoadServerFail();
PrintManagerClient::GetInstance()->ResetProxy();
int32_t ret = PrintManagerClient::GetInstance()->RemovePrinterFromDiscovery(printerId);
EXPECT_EQ(ret, E_PRINT_NO_PERMISSION);
}
} // namespace Print
} // namespace OHOS

View File

@ -869,5 +869,76 @@ HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0029, TestSize.Level1)
proxy->DiscoverUsbPrinters(testPrinters);
}
HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0030, TestSize.Level1)
{
OHOS::Print::PrinterInfo testInfo1;
testInfo1.SetOption("option-1");
sptr<MockRemoteObject> obj = new MockRemoteObject();
EXPECT_NE(obj, nullptr);
auto proxy = std::make_shared<PrintServiceProxy>(obj);
EXPECT_NE(proxy, nullptr);
auto service = std::make_shared<MockPrintService>();
EXPECT_NE(service, nullptr);
EXPECT_CALL(*service, AddPrinterToDiscovery(_)).Times(Exactly(1)).WillOnce(
[&testInfo1](const PrinterInfo &printerInfo) {
EXPECT_EQ(testInfo1.GetOption(), printerInfo.GetOption());
return E_PRINT_NONE;
});
EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1);
ON_CALL(*obj, SendRequest)
.WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) {
service->OnRemoteRequest(code, data, reply, option);
return E_PRINT_NONE;
});
proxy->AddPrinterToDiscovery(testInfo1);
}
HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0031, TestSize.Level1)
{
OHOS::Print::PrinterInfo testInfo1;
testInfo1.SetOption("option-1");
sptr<MockRemoteObject> obj = new MockRemoteObject();
EXPECT_NE(obj, nullptr);
auto proxy = std::make_shared<PrintServiceProxy>(obj);
EXPECT_NE(proxy, nullptr);
auto service = std::make_shared<MockPrintService>();
EXPECT_NE(service, nullptr);
EXPECT_CALL(*service, UpdatePrinterInDiscovery(_)).Times(Exactly(1)).WillOnce(
[&testInfo1](const PrinterInfo &printerInfo) {
EXPECT_EQ(testInfo1.GetOption(), printerInfo.GetOption());
return E_PRINT_NONE;
});
EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1);
ON_CALL(*obj, SendRequest)
.WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) {
service->OnRemoteRequest(code, data, reply, option);
return E_PRINT_NONE;
});
proxy->UpdatePrinterInDiscovery(testInfo1);
}
HWTEST_F(PrintServiceProxyTest, PrintServiceProxyTest_0032, TestSize.Level1)
{
std::string testPrinterId = "111";
sptr<MockRemoteObject> obj = new MockRemoteObject();
EXPECT_NE(obj, nullptr);
auto proxy = std::make_shared<PrintServiceProxy>(obj);
EXPECT_NE(proxy, nullptr);
auto service = std::make_shared<MockPrintService>();
EXPECT_NE(service, nullptr);
EXPECT_CALL(*service, RemovePrinterFromDiscovery(_)).Times(Exactly(1)).WillOnce(
[&testPrinterId](const std::string &printerId) {
EXPECT_EQ(testPrinterId, printerId);
return E_PRINT_NONE;
});
EXPECT_CALL(*obj, SendRequest(_, _, _, _)).Times(1);
ON_CALL(*obj, SendRequest)
.WillByDefault([&service](uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) {
service->OnRemoteRequest(code, data, reply, option);
return E_PRINT_NONE;
});
proxy->RemovePrinterFromDiscovery(testPrinterId);
}
} // namespace Print
} // namespace OHOS

View File

@ -106,7 +106,7 @@ HWTEST_F(PrinterCapabilityTest, PrinterCapabilityTest_0005, TestSize.Level1)
PrintPageSize testPagesize;
testPagesize.SetWidth(1);
pagesize.emplace_back(testPagesize);
capability.SetPageSize(pagesize);
capability.SetSupportedPageSize(pagesize);
capability.GetPageSize(getPagesize);
EXPECT_EQ(pagesize.size(), getPagesize.size());
}
@ -185,7 +185,7 @@ HWTEST_F(PrinterCapabilityTest, PrinterCapabilityTest_0010, TestSize.Level1)
capability.SetDuplexMode(6);
capability.SetMinMargin(margin);
capability.SetPageSize(pagesize);
capability.SetSupportedPageSize(pagesize);
capability.SetResolution(resolutionList);
Parcel parcel;
EXPECT_EQ(capability.Marshalling(parcel), true);
@ -205,7 +205,7 @@ HWTEST_F(PrinterCapabilityTest, PrinterCapabilityTest_0011, TestSize.Level1)
std::vector<PrintPageSize> pagesize;
capability.SetColorMode(6);
capability.SetDuplexMode(6);
capability.SetPageSize(pagesize);
capability.SetSupportedPageSize(pagesize);
Parcel parcel;
EXPECT_EQ(capability.Marshalling(parcel), true);
}
@ -225,7 +225,7 @@ HWTEST_F(PrinterCapabilityTest, PrinterCapabilityTest_0012, TestSize.Level1)
capability.SetColorMode(6);
capability.SetDuplexMode(6);
capability.SetMinMargin(margin);
capability.SetPageSize(pagesize);
capability.SetSupportedPageSize(pagesize);
capability.SetResolution(resolutionList);
Parcel parcel;
capability.Marshalling(parcel);

View File

@ -1155,7 +1155,7 @@ HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0064, TestSize.Level1)
std::vector<PrintPageSize> pageSizeList;
PrintPageSize pageSize;
pageSizeList.push_back(pageSize);
caps.SetPageSize(pageSizeList);
caps.SetSupportedPageSize(pageSizeList);
printerInfo->printerCapability = caps;
service->printSystemData_.addedPrinterMap_[printerId] = printerInfo;
EXPECT_EQ(service->QueryPrinterInfoByPrinterId(printerId, info), E_PRINT_NONE);
@ -1960,4 +1960,33 @@ HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0129, TestSize.Level1)
service->DiscoverUsbPrinters(printers);
}
HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0130, TestSize.Level1)
{
auto service = std::make_shared<PrintServiceAbility>(PRINT_SERVICE_ID, true);
PrinterInfo info;
info.SetPrinterId(DEFAULT_EXT_PRINTER_ID);
EXPECT_EQ(service->AddPrinterToDiscovery(info), E_PRINT_NONE);
EXPECT_EQ(service->UpdatePrinterInDiscovery(info), E_PRINT_NONE);
info.SetPrinterId("1234");
EXPECT_EQ(service->UpdatePrinterInDiscovery(info), E_PRINT_NONE);
std::shared_ptr<PrinterInfo> info1 = std::make_shared<PrinterInfo>();
info1->SetPrinterId(DEFAULT_EXT_PRINTER_ID);
service->printerInfoList_[DEFAULT_EXT_PRINTER_ID] = info1;
EXPECT_EQ(service->RemovePrinterFromDiscovery(DEFAULT_EXT_PRINTER_ID), E_PRINT_NONE);
EXPECT_EQ(service->RemovePrinterFromDiscovery(DEFAULT_EXT_PRINTER_ID), E_PRINT_INVALID_PRINTER);
}
HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0131, TestSize.Level1)
{
auto service = std::make_shared<PrintServiceAbility>(PRINT_SERVICE_ID, true);
std::string printerId = "com.ohos.spooler:p2p://DIRECT-PixLab_V1-1620";
std::string printerExtId = PrintUtils::GetGlobalId("", printerId);
service->printerIdAndPreferenceMap_[printerExtId] = "test";
PrinterCapability printerCaps;
printerCaps.SetOption("test");
std::string printerUri = "usb:ipp://192.168.186.1:631/ipp/print";
EXPECT_EQ(service->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps), E_PRINT_NONE);
}
} // namespace OHOS::Print

View File

@ -199,6 +199,18 @@ public:
{
return E_PRINT_NONE;
}
int32_t AddPrinterToDiscovery(const PrinterInfo& printerInfo) override
{
return E_PRINT_NONE;
}
int32_t UpdatePrinterInDiscovery(const PrinterInfo& printerInfo) override
{
return E_PRINT_NONE;
}
int32_t RemovePrinterFromDiscovery(const std::string& printerId) override
{
return E_PRINT_NONE;
}
};
class MockPrintService final : public DummyPrintServiceStub {
@ -233,6 +245,9 @@ public:
MOCK_METHOD2(SetDefaultPrinter, int32_t(const std::string&, uint32_t));
MOCK_METHOD3(DeletePrinterFromCups, int32_t(const std::string&, const std::string&, const std::string&));
MOCK_METHOD1(DiscoverUsbPrinters, int32_t(std::vector<PrinterInfo>&));
MOCK_METHOD1(AddPrinterToDiscovery, int32_t(const PrinterInfo&));
MOCK_METHOD1(UpdatePrinterInDiscovery, int32_t(const PrinterInfo&));
MOCK_METHOD1(RemovePrinterFromDiscovery, int32_t(const std::string&));
};
} // namespace Print
} // namespace OHOS

View File

@ -1369,5 +1369,83 @@ HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0059, TestSize.Level1)
EXPECT_TRUE(static_cast<bool>(stub->OnRemoteRequest(code, data, reply, option)));
}
/**
* @tc.name: PrintServiceStubTest_0060
* @tc.desc: Verify the capability function.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0060, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
uint32_t code = static_cast<uint32_t>(CMD_ADDPRINTERTODISCOVERY);
PrinterInfo testInfo;
std::string testPrinterId = "com.sample.ext:1";
testInfo.SetPrinterId(testPrinterId);
EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor()));
testInfo.Marshalling(data);
auto stub = std::make_shared<MockPrintService>();
EXPECT_NE(stub, nullptr);
ON_CALL(*stub, AddPrinterToDiscovery).WillByDefault(Return(E_PRINT_NONE));
EXPECT_TRUE(static_cast<bool>(stub->OnRemoteRequest(code, data, reply, option)));
}
/**
* @tc.name: PrintServiceStubTest_0061
* @tc.desc: Verify the capability function.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0061, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
uint32_t code = static_cast<uint32_t>(CMD_UPDATEPRINTERINDISCOVERY);
PrinterInfo testInfo;
std::string testPrinterId = "com.sample.ext:1";
testInfo.SetPrinterId(testPrinterId);
EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor()));
testInfo.Marshalling(data);
auto stub = std::make_shared<MockPrintService>();
EXPECT_NE(stub, nullptr);
ON_CALL(*stub, UpdatePrinterInDiscovery).WillByDefault(Return(E_PRINT_NONE));
EXPECT_TRUE(static_cast<bool>(stub->OnRemoteRequest(code, data, reply, option)));
}
/**
* @tc.name: PrintServiceStubTest_0062
* @tc.desc: Verify the capability function.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PrintServiceStubTest, PrintServiceStubTest_0062, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
uint32_t code = static_cast<uint32_t>(CMD_REMOVEPRINTERFROMDISCOVERY);
std::string testPrinterId = "com.sample.ext:1";
EXPECT_TRUE(data.WriteInterfaceToken(IPrintCallback::GetDescriptor()));
EXPECT_TRUE(data.WriteString(testPrinterId));
auto stub = std::make_shared<MockPrintService>();
EXPECT_NE(stub, nullptr);
ON_CALL(*stub, RemovePrinterFromDiscovery).WillByDefault(Return(E_PRINT_NONE));
EXPECT_TRUE(static_cast<bool>(stub->OnRemoteRequest(code, data, reply, option)));
}
} // namespace Print
} // namespace OHOS

View File

@ -882,7 +882,7 @@ HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0042, TestSize.Level1)
std::vector<PrintPageSize> pageSizeList;
PrintPageSize pageSize;
pageSizeList.push_back(pageSize);
printerCapability2.SetPageSize(pageSizeList);
printerCapability2.SetSupportedPageSize(pageSizeList);
cupsPrinter.printerCapability = printerCapability2;
systemData->GetPrinterCapabilityFromSystemData(cupsPrinter, printerId, printerCapability);
}
@ -1082,7 +1082,7 @@ HWTEST_F(PrintSystemDataTest, PrintSystemDataTest_0051, TestSize.Level1)
std::vector<PrintPageSize> pageSizeList;
PrintPageSize pageSize;
pageSizeList.push_back(pageSize);
printerCapability.SetPageSize(pageSizeList);
printerCapability.SetSupportedPageSize(pageSizeList);
nlohmann::json opsJson;
opsJson["printerName"] = "123";
printerCapability.SetOption(opsJson.dump());

View File

@ -183,6 +183,12 @@ enum PrintDuplexMode {
DUPLEX_MODE_SHORT_EDGE = 2,
};
enum PrintQualityCode {
PRINT_QUALITY_DRAFT = 3,
PRINT_QUALITY_NORMAL = 4,
PRINT_QUALITY_HIGH = 5
};
enum PrintPageType {
PAGE_ISO_A3 = 0,
PAGE_ISO_A4 = 1,