diff --git a/bundle.json b/bundle.json index 43b8585..12150da 100644 --- a/bundle.json +++ b/bundle.json @@ -53,7 +53,6 @@ "//base/print/print/profile:print_sa_profiles" ], "test": [ - "//base/print/print/interfaces/kits/napi/test:unittest" ] }, "hisysevent_config": [ diff --git a/etc/init/printservice.cfg b/etc/init/printservice.cfg index 392edba..76e5d73 100644 --- a/etc/init/printservice.cfg +++ b/etc/init/printservice.cfg @@ -2,6 +2,7 @@ "services" : [{ "name" : "print_service", "path" : ["/system/bin/sa_main", "/system/profile/print_service.xml"], + "ondemand" : true, "uid" : "print", "gid" : ["print", "shell"], "secon" : "u:r:print_service:s0" diff --git a/frameworks/innerkitsimpl/include/napi_print_utils.h b/frameworks/innerkitsimpl/include/napi_print_utils.h index 9ea80dc..3a1794d 100644 --- a/frameworks/innerkitsimpl/include/napi_print_utils.h +++ b/frameworks/innerkitsimpl/include/napi_print_utils.h @@ -85,9 +85,9 @@ public: static void DefineProperties( napi_env env, napi_value object, const std::initializer_list &properties); static std::string ToLower(const std::string &s); - static void CovertPageSize(napi_env env, napi_value &result, const PrintJob &job); - static void CovertMargin(napi_env env, napi_value &result, const PrintJob &job); - static void CovertPreviewAttribute(napi_env env, napi_value &result, const PrintJob &job); + static napi_value CovertPageSize(napi_env env, napi_value &result, const PrintJob &job); + static napi_value CovertMargin(napi_env env, napi_value &result, const PrintJob &job); + static napi_value CovertPreviewAttribute(napi_env env, napi_value &result, const PrintJob &job); static napi_value Convert2JsObj(napi_env env, const PrintJob &job); }; } // namespace OHOS::Print diff --git a/frameworks/innerkitsimpl/include/print_job.h b/frameworks/innerkitsimpl/include/print_job.h index cb54f7c..fad0c8b 100644 --- a/frameworks/innerkitsimpl/include/print_job.h +++ b/frameworks/innerkitsimpl/include/print_job.h @@ -98,6 +98,10 @@ public: void Dump(); private: + void SetConvertPageSize(napi_env env, napi_value &pageSize) const; + void SetConvertMargin(napi_env env, napi_value &margin) const; + void SetSubPageRange(napi_env env, napi_value &subPageRange) const; + void SetBuild(MessageParcel &data); bool ParseJob(napi_env env, napi_value jobValue, PrintJob &printJob); bool ParseJobParam(napi_env env, napi_value jobValue, PrintJob &printJob); diff --git a/frameworks/innerkitsimpl/include/print_margin.h b/frameworks/innerkitsimpl/include/print_margin.h index ebba5e1..20c985a 100644 --- a/frameworks/innerkitsimpl/include/print_margin.h +++ b/frameworks/innerkitsimpl/include/print_margin.h @@ -16,6 +16,8 @@ #ifndef PRINT_MARGIN_H #define PRINT_MARGIN_H +#include + namespace OHOS::Print { class PrintMargin { public: diff --git a/frameworks/innerkitsimpl/include/print_resolution.h b/frameworks/innerkitsimpl/include/print_resolution.h index bea94f8..f480c9f 100644 --- a/frameworks/innerkitsimpl/include/print_resolution.h +++ b/frameworks/innerkitsimpl/include/print_resolution.h @@ -16,6 +16,8 @@ #ifndef PRINT_RESOLUTION_H #define PRINT_RESOLUTION_H +#include + namespace OHOS::Print { class PrintResolution { public: diff --git a/frameworks/innerkitsimpl/src/napi_print_utils.cpp b/frameworks/innerkitsimpl/src/napi_print_utils.cpp index 37c3811..37fb679 100644 --- a/frameworks/innerkitsimpl/src/napi_print_utils.cpp +++ b/frameworks/innerkitsimpl/src/napi_print_utils.cpp @@ -305,8 +305,9 @@ std::string NapiPrintUtils::GetValueString(napi_env env, napi_value value) return resultValue; } -void NapiPrintUtils::CovertPageSize(napi_env env, napi_value &result, const PrintJob &job) +napi_value NapiPrintUtils::CovertPageSize(napi_env env, napi_value &result, const PrintJob &job) { + napi_value backData = nullptr; napi_value pageSize; NAPI_CALL(env, napi_create_object(env, &pageSize)); PrintPageSize nativePageSize; @@ -316,10 +317,12 @@ void NapiPrintUtils::CovertPageSize(napi_env env, napi_value &result, const Prin SetUint32Property(env, pageSize, "width", nativePageSize.GetWidth()); SetUint32Property(env, pageSize, "height", nativePageSize.GetHeight()); NAPI_CALL(env, napi_set_named_property(env, result, "pageSize", pageSize)); + return backData; } -void NapiPrintUtils::CovertMargin(napi_env env, napi_value &result, const PrintJob &job) +napi_value NapiPrintUtils::CovertMargin(napi_env env, napi_value &result, const PrintJob &job) { + napi_value backData = nullptr; PrintMargin nativeMargin; job.GetMargin(nativeMargin); napi_value margin; @@ -329,14 +332,17 @@ void NapiPrintUtils::CovertMargin(napi_env env, napi_value &result, const PrintJ SetUint32Property(env, margin, "left", nativeMargin.GetLeft()); SetUint32Property(env, margin, "right", nativeMargin.GetRight()); NAPI_CALL(env, napi_set_named_property(env, result, "margin", margin)); + return backData; } -void NapiPrintUtils::CovertPreviewAttribute(napi_env env, napi_value &result, const PrintJob &job) +napi_value NapiPrintUtils::CovertPreviewAttribute(napi_env env, napi_value &result, const PrintJob &job) { + napi_value backData = nullptr; PrintRange nativeRange; PreviewAttribute previewAttr; job.GetPreview(previewAttr); + std::vector pages; previewAttr.GetPreviewRange(nativeRange); nativeRange.GetPages(pages); @@ -360,6 +366,7 @@ void NapiPrintUtils::CovertPreviewAttribute(napi_env env, napi_value &result, co NAPI_CALL(env, napi_set_named_property(env, subPageRange, "pages", arrPreviewPages)); NAPI_CALL(env, napi_set_named_property(env, preview, "pageRange", subPageRange)); NAPI_CALL(env, napi_set_named_property(env, result, "preview", preview)); + return backData; } napi_value NapiPrintUtils::Convert2JsObj(napi_env env, const PrintJob &job) @@ -403,15 +410,15 @@ napi_value NapiPrintUtils::Convert2JsObj(napi_env env, const PrintJob &job) SetUint32Property(env, result, "isSequential", job.GetIsSequential()); - CovertPageSize(env, result, job); + napi_value covertValue = CovertPageSize(env, result, job); SetUint32Property(env, result, "isLandscape", job.GetIsLandscape()); SetUint32Property(env, result, "colorMode", job.GetColorMode()); SetUint32Property(env, result, "duplexMode", job.GetDuplexMode()); - CovertMargin(env, result, job); - CovertPreviewAttribute(env, result, job); + covertValue = CovertMargin(env, result, job); + covertValue = CovertPreviewAttribute(env, result, job); return result; } -} // namespace OHOS::Print +} // namespace OHOS::Print \ No newline at end of file diff --git a/frameworks/innerkitsimpl/src/print_extension_callback_stub.cpp b/frameworks/innerkitsimpl/src/print_extension_callback_stub.cpp index 757a144..a984f44 100644 --- a/frameworks/innerkitsimpl/src/print_extension_callback_stub.cpp +++ b/frameworks/innerkitsimpl/src/print_extension_callback_stub.cpp @@ -73,7 +73,7 @@ bool PrintExtensionCallbackStub::OnCallback(const PrintJob &job) return false; } -bool PrintExtensionCallbackStub::OnCallback(uint32_t printerId, MessageParcel &reply) // PrinterCapability& reply +bool PrintExtensionCallbackStub::OnCallback(uint32_t printerId, MessageParcel &reply) { if (capability_ != nullptr) { PrinterCapability capability; diff --git a/frameworks/innerkitsimpl/src/print_job.cpp b/frameworks/innerkitsimpl/src/print_job.cpp index d268fb9..87eba55 100644 --- a/frameworks/innerkitsimpl/src/print_job.cpp +++ b/frameworks/innerkitsimpl/src/print_job.cpp @@ -324,13 +324,13 @@ void PrintJob::BuildFromParcel(MessageParcel &data) Dump(); } -void PrintJob::SetSubPageRange(napi_env env, napi_value &subPageRange) +void PrintJob::SetSubPageRange(napi_env env, napi_value &subPageRange) const { napi_create_object(env, &subPageRange); NapiPrintUtils::SetUint32Property(env, subPageRange, "startPage", pageRange_.GetStartPage()); NapiPrintUtils::SetUint32Property(env, subPageRange, "endPage", pageRange_.GetEndPage()); napi_value arrPreviewPages; - status = napi_create_array(env, &arrPreviewPages); + napi_status status = napi_create_array(env, &arrPreviewPages); PrintRange previewPrintRange; std::vector previewRangePages; preview_.GetPreviewRange(previewPrintRange); @@ -345,7 +345,7 @@ void PrintJob::SetSubPageRange(napi_env env, napi_value &subPageRange) napi_set_named_property(env, subPageRange, "files", arrPreviewPages); } -void PrintJob::SetPageSize(napi_env env, napi_value &pageSize) +void PrintJob::SetConvertPageSize(napi_env env, napi_value &pageSize) const { NapiPrintUtils::SetStringPropertyUtf8(env, pageSize, "id", pageSize_.GetId()); NapiPrintUtils::SetStringPropertyUtf8(env, pageSize, "name", pageSize_.GetName().c_str()); @@ -353,7 +353,7 @@ void PrintJob::SetPageSize(napi_env env, napi_value &pageSize) NapiPrintUtils::SetUint32Property(env, pageSize, "height", pageSize_.GetHeight()); } -void PrintJob::SetMargin(napi_env env, napi_value &margin) +void PrintJob::SetConvertMargin(napi_env env, napi_value &margin) const { NapiPrintUtils::SetUint32Property(env, margin, "top", margin_.GetTop()); NapiPrintUtils::SetUint32Property(env, margin, "bottom", margin_.GetBottom()); @@ -398,7 +398,7 @@ void PrintJob::ConvertToJs(napi_env env, napi_value *result) const NapiPrintUtils::SetUint32Property(env, *result, "isSequential", GetIsSequential()); napi_value pageSize; napi_create_object(env, &pageSize); - SetPageSize(env, pageSize); + SetConvertPageSize(env, pageSize); NapiPrintUtils::SetUint32Property(env, *result, "isLandscape", GetIsLandscape()); NapiPrintUtils::SetUint32Property(env, *result, "colorMode", GetColorMode()); @@ -406,7 +406,7 @@ void PrintJob::ConvertToJs(napi_env env, napi_value *result) const napi_value margin; napi_create_object(env, &margin); - SetMargin(env, margin); + SetConvertMargin(env, margin); napi_value preview; napi_create_object(env, &preview); diff --git a/frameworks/innerkitsimpl/src/print_page_size.cpp b/frameworks/innerkitsimpl/src/print_page_size.cpp index 9a52e8a..ad0c751 100644 --- a/frameworks/innerkitsimpl/src/print_page_size.cpp +++ b/frameworks/innerkitsimpl/src/print_page_size.cpp @@ -110,7 +110,7 @@ uint32_t PrintPageSize::GetHeight() const void PrintPageSize::Dump() { - PRINT_HILOGD("top_ = %{public}s", id_.c_str()); + PRINT_HILOGD("id_ = %{public}s", id_.c_str()); PRINT_HILOGD("name_ = %{public}s", name_.c_str()); PRINT_HILOGD("width_ = %{public}d", width_); PRINT_HILOGD("height_ = %{public}d", height_); diff --git a/frameworks/innerkitsimpl/src/print_progress_notify.cpp b/frameworks/innerkitsimpl/src/print_progress_notify.cpp index b0c23b7..dbc8629 100644 --- a/frameworks/innerkitsimpl/src/print_progress_notify.cpp +++ b/frameworks/innerkitsimpl/src/print_progress_notify.cpp @@ -50,66 +50,8 @@ void PrintProgressNotify::WriteInfoJsObject(napi_env env, PrinterInfo info, napi PRINT_HILOGD(""); } -void PrintProgressNotify::notifyDataBase(NotifyData *notifyData, MessageParcel &data) -{ - PRINT_HILOGD("Progress callback in"); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env_, &loop); - if (loop == nullptr) { - PRINT_HILOGE("Failed to get uv event loop"); - return; - } - uv_work_t *work = new (std::nothrow) uv_work_t; - if (work == nullptr) { - PRINT_HILOGE("Failed to create uv work"); - return; - } - - notifyData = GetNotifyData(); - notifyData->env = env_; - notifyData->ref = ref_; - notifyData->type = type_; - notifyData->objectType = data.ReadString(); - notifyData->firstArgv = data.ReadUint32(); - if (notifyData->objectType == "PrinterInfo") { - DataReadInfo(notifyData->secondArgv, data); - } else if (notifyData->objectType == "PrintJob") { - DataReadJob(notifyData->thirdArgv, data); - } -} - void PrintProgressNotify::OnCallBack(MessageParcel &data) { - NotifyData *notifyData = nullptr; - notifyDataBase(notifyData, data); - work->data = notifyData; - uv_queue_work( - loop, work, [](uv_work_t *work) {}, - [](uv_work_t *work, int statusInt) { - NotifyData *notifyData = static_cast(work->data); - if (notifyData != nullptr) { - napi_value undefined = 0; - napi_get_undefined(notifyData->env, &undefined); - napi_value callbackFunc = nullptr; - napi_get_reference_value(notifyData->env, notifyData->ref, &callbackFunc); - napi_value result = nullptr; - napi_value callbackVal[NapiPrintUtils::TWO_ARG] = { 0 }; - napi_create_uint32(notifyData->env, notifyData->firstArgv, &callbackVal[NapiPrintUtils::FIRST_ARGV]); - if (notifyData->objectType == "PrinterInfo") { - WriteInfoJsObject( - notifyData->env, notifyData->secondArgv, &callbackVal[NapiPrintUtils::SECOND_ARGV]); - } else if (notifyData->objectType == "PrintJob") { - WriteJobJsObject(notifyData->env, notifyData->thirdArgv, &callbackVal[NapiPrintUtils::SECOND_ARGV]); - } - napi_call_function( - notifyData->env, nullptr, callbackFunc, NapiPrintUtils::TWO_ARG, callbackVal, &result); - if (work != nullptr) { - delete work; - work = nullptr; - } - delete notifyData; - notifyData = nullptr; - } - }); + PRINT_HILOGD(""); } } // namespace OHOS::Print \ No newline at end of file diff --git a/frameworks/innerkitsimpl/src/print_resolution.cpp b/frameworks/innerkitsimpl/src/print_resolution.cpp index b6faf24..0eaa52a 100644 --- a/frameworks/innerkitsimpl/src/print_resolution.cpp +++ b/frameworks/innerkitsimpl/src/print_resolution.cpp @@ -14,7 +14,6 @@ */ #include "print_resolution.h" - #include "print_log.h" namespace OHOS::Print { diff --git a/frameworks/innerkitsimpl/src/print_service_proxy.cpp b/frameworks/innerkitsimpl/src/print_service_proxy.cpp index 567d2c3..0c2ab97 100644 --- a/frameworks/innerkitsimpl/src/print_service_proxy.cpp +++ b/frameworks/innerkitsimpl/src/print_service_proxy.cpp @@ -78,7 +78,7 @@ bool PrintServiceProxy::QueryAllExtension(std::vector &array MessageParcel data, reply; MessageOption option; data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor()); - data.WriteUint32(NapiPrintUtil::ARGC_FIVE); + data.WriteUint32(NapiPrintUtils::ARGC_FIVE); PRINT_HILOGD("PrintServiceProxy ChangeTaskPriority started."); bool ret = Remote()->SendRequest(CMD_QUERYALLEXTENSION, data, reply, option); if (ret != ERR_NONE) { @@ -105,7 +105,7 @@ bool PrintServiceProxy::StartDiscoverPrinter(const std::vector &extens MessageOption option; data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor()); data.WriteUint32(extensionList.size()); - PRINT_HILOGD("OnStartDiscoverPrinter extensionList.size() = %{public}lu", extensionList.size()); + PRINT_HILOGD("OnStartDiscoverPrinter extensionList.size() = %{public}zu", extensionList.size()); for (uint32_t i = 0; i < extensionList.size(); i++) { data.WriteUint32(extensionList[i]); } @@ -172,7 +172,7 @@ bool PrintServiceProxy::AddPrinters(const std::vector &arrayPrintIn MessageOption option; data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor()); data.WriteUint32(arrayPrintInfo.size()); - PRINT_HILOGD("OnStartDiscoverPrinter arrayPrintInfo.size() = %{public}lu", arrayPrintInfo.size()); + PRINT_HILOGD("OnStartDiscoverPrinter arrayPrintInfo.size() = %{public}zu", arrayPrintInfo.size()); for (uint32_t i = 0; i < arrayPrintInfo.size(); i++) { BuildParcelFromPrinterInfo(data, arrayPrintInfo[i]); } @@ -192,7 +192,7 @@ bool PrintServiceProxy::RemovePrinters(const std::vector &arrayPrin MessageOption option; data.WriteInterfaceToken(PrintServiceProxy::GetDescriptor()); data.WriteUint32(arrayPrintInfo.size()); - PRINT_HILOGD("OnStartDiscoverPrinter arrayPrintInfo.size() = %{public}lu", arrayPrintInfo.size()); + PRINT_HILOGD("OnStartDiscoverPrinter arrayPrintInfo.size() = %{public}zu", arrayPrintInfo.size()); for (uint32_t i = 0; i < arrayPrintInfo.size(); i++) { BuildParcelFromPrinterInfo(data, arrayPrintInfo[i]); } @@ -413,8 +413,8 @@ void PrintServiceProxy::BuildParcelFromPrintJob(MessageParcel &data, const Print std::vector files; jobinfo.GetFiles(files); - data.WriteUint32(files.size()); - for (uint32_t i = 0; i < files.size(); i++) { + data.WriteUint32((uint32_t)files.size()); + for (uint32_t i = 0; i < (uint32_t)files.size(); i++) { data.WriteString(files[i]); } data.WriteUint32(jobinfo.GetJobId()); @@ -429,8 +429,8 @@ void PrintServiceProxy::BuildParcelFromPrintJob(MessageParcel &data, const Print std::vector pages; range.GetPages(pages); - data.WriteUint32(pages.size()); - for (uint32_t i = 0; i < pageLength; i++) { + data.WriteUint32((uint32_t)pages.size()); + for (uint32_t i = 0; i < (uint32_t)pages.size(); i++) { data.WriteUint32(pages[i]); } @@ -464,8 +464,8 @@ void PrintServiceProxy::BuildParcelFromPrintJob(MessageParcel &data, const Print data.WriteUint32(range.GetEndPage()); range.GetPages(pages); - data.WriteUint32(pages.size()); - for (uint32_t i = 0; i < pages.size(); i++) { + data.WriteUint32((uint32_t)pages.size()); + for (uint32_t i = 0; i < (uint32_t)pages.size(); i++) { data.WriteUint32(pages[i]); } } diff --git a/frameworks/innerkitsimpl/src/printer_capability.cpp b/frameworks/innerkitsimpl/src/printer_capability.cpp index ecd2161..a00d986 100644 --- a/frameworks/innerkitsimpl/src/printer_capability.cpp +++ b/frameworks/innerkitsimpl/src/printer_capability.cpp @@ -280,13 +280,13 @@ void PrinterCapability::ParseCapabilityObject(napi_env env, napi_value capValue) napi_value param_three = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_RESOLUTION); if (NapiPrintUtils::GetValueType(env, param_three) != napi_object) { PRINT_HILOGE("error param_three"); - return false; + return; } else { bool isReArray = false; napi_is_array(env, param_three, &isReArray); if (!isReArray) { PRINT_HILOGE("PrintResolution type error!"); - return false; + return; } std::vector resolutionList; uint32_t arrayReLength = 0; @@ -297,7 +297,7 @@ void PrinterCapability::ParseCapabilityObject(napi_env env, napi_value capValue) napi_get_element(env, param_three, i, &reValue); if (!ParseResolution(env, reValue, resolution)) { PRINT_HILOGE("PrintResolution type error!"); - return false; + return; } resolutionList.push_back(resolution); } @@ -306,12 +306,12 @@ void PrinterCapability::ParseCapabilityObject(napi_env env, napi_value capValue) napi_value param_four = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_COLORMODE); if (NapiPrintUtils::GetValueType(env, param_four) != napi_number) { PRINT_HILOGE("error param_four"); - return false; + return; } napi_value param_five = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_DUPLEXMODE); if (NapiPrintUtils::GetValueType(env, param_five) != napi_number) { PRINT_HILOGE("error param_five"); - return false; + return; } } diff --git a/frameworks/kits/extension/include/js_print_callback.h b/frameworks/kits/extension/include/js_print_callback.h index be1e0a3..bcd6124 100644 --- a/frameworks/kits/extension/include/js_print_callback.h +++ b/frameworks/kits/extension/include/js_print_callback.h @@ -34,11 +34,16 @@ class JsPrintCallback : public std::enable_shared_from_this { public: explicit JsPrintCallback(JsRuntime &jsRutime); ~JsPrintCallback() = default; - void SetjsWorker(NativeValue *jsObj, const std::string &name, NativeValue *const *argv, size_t argc, bool isSync); NativeValue *Exec(NativeValue *jsObj, const std::string &name, NativeValue *const *argv = nullptr, size_t argc = 0, bool isSync = true); + private: - struct Container { + uv_loop_s *GetJsLoop(JsRuntime &jsRuntime); + bool BuildJsWorker(NativeValue *jsObj, const std::string &name, + NativeValue *const *argv, size_t argc, bool isSync); + +private: + struct JsWorkParam { std::shared_ptr self; NativeEngine *nativeEngine; NativeValue *jsObj; @@ -52,7 +57,7 @@ private: JsRuntime &jsRuntime_; uv_work_t *jsWorker_; - JsPrintCallback::Container container_; + JsPrintCallback::JsWorkParam jsParam_; std::mutex conditionMutex_; std::condition_variable syncCon_; diff --git a/frameworks/kits/extension/include/js_print_extension.h b/frameworks/kits/extension/include/js_print_extension.h index 4bc71b7..f584146 100644 --- a/frameworks/kits/extension/include/js_print_extension.h +++ b/frameworks/kits/extension/include/js_print_extension.h @@ -22,6 +22,7 @@ class NativeReference; class NativeValue; +class NativeObject; namespace OHOS { namespace AbilityRuntime { @@ -44,10 +45,6 @@ public: */ static JsPrintExtension *Create(const std::unique_ptr &runtime); - void InitData(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, const sptr &token); - /** * @brief Init the extension. * @@ -112,9 +109,13 @@ public: private: NativeValue *CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0); - void RegisterAllCallbackPartOne(); - void RegisterAllCallbackPartTwo(); - void RegisterAllCallback(); + bool InitExtensionObj(JsRuntime &jsRuntime); + bool InitContextObj(JsRuntime &jsRuntime, NativeObject *&extObj); + void RegisterDiscoveryCb(); + void RegisterConnectionCb(); + void RegisterPrintJobCb(); + void RegisterPreviewCb(); + void RegisterQueryCapCb(); void GetSrcPath(std::string &srcPath); diff --git a/frameworks/kits/extension/src/js_print_callback.cpp b/frameworks/kits/extension/src/js_print_callback.cpp index 1102e91..8bfcc4d 100644 --- a/frameworks/kits/extension/src/js_print_callback.cpp +++ b/frameworks/kits/extension/src/js_print_callback.cpp @@ -36,78 +36,90 @@ using namespace OHOS::Print; JsPrintCallback::JsPrintCallback(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {} -void JsPrintCallback::SetjsWorker( - NativeValue *jsObj, const std::string &name, NativeValue *const *argv, size_t argc, bool isSync) +uv_loop_s* JsPrintCallback::GetJsLoop(JsRuntime &jsRuntime) +{ + NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine(); + uv_loop_s* loop = nullptr; + napi_get_uv_event_loop(reinterpret_cast(nativeEngine), &loop); + if (loop == nullptr) { + return nullptr; + } + return loop; +} + +bool JsPrintCallback::BuildJsWorker(NativeValue *jsObj, const std::string &name, + NativeValue *const *argv, size_t argc, bool isSync) { - HandleScope handleScope(jsRuntime_); NativeObject *obj = ConvertNativeValueTo(jsObj); if (obj == nullptr) { PRINT_HILOGE("Failed to get PrintExtension object"); - return nullptr; + return false; } NativeValue *method = obj->GetProperty(name.c_str()); if (method == nullptr) { PRINT_HILOGE("Failed to get '%{public}s' from PrintExtension object", name.c_str()); - return nullptr; + return false; } - PRINT_HILOGD("%{public}s callback in", name.c_str()); - - NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(reinterpret_cast(nativeEngine), &loop); - if (loop == nullptr) { - PRINT_HILOGE("Failed to get uv event loop"); - return nullptr; - } jsWorker_ = new (std::nothrow) uv_work_t; if (jsWorker_ == nullptr) { PRINT_HILOGE("Failed to create uv work"); - return nullptr; + return false; } - container_.self = shared_from_this(); - container_.nativeEngine = nativeEngine; - container_.jsObj = jsObj; - container_.jsMethod = method; - container_.argv = argv; - container_.argc = argc; - container_.jsResult = nullptr; - container_.isSync = isSync; - container_.isCompleted = false; - jsWorker_->data = &container_; + jsParam_.self = shared_from_this(); + jsParam_.nativeEngine = &jsRuntime_.GetNativeEngine(); + jsParam_.jsObj = jsObj; + jsParam_.jsMethod = method; + jsParam_.argv = argv; + jsParam_.argc = argc; + jsParam_.jsResult = nullptr; + jsParam_.isSync = isSync; + jsParam_.isCompleted = false; + jsWorker_->data = &jsParam_; + return true; } NativeValue *JsPrintCallback::Exec( NativeValue *jsObj, const std::string &name, NativeValue *const *argv, size_t argc, bool isSync) { - SetjsWorker(jsObj, name, argv, argc, isSync); + PRINT_HILOGD("%{public}s callback in", name.c_str()); + HandleScope handleScope(jsRuntime_); + uv_loop_s *loop = GetJsLoop(jsRuntime_); + if (loop == nullptr) { + PRINT_HILOGE("Failed to acquire js event loop"); + return nullptr; + } + if (!BuildJsWorker(jsObj, name, argv, argc, isSync)) { + PRINT_HILOGE("Failed to build JS worker"); + return nullptr; + } uv_queue_work( loop, jsWorker_, [](uv_work_t *work) {}, [](uv_work_t *work, int statusInt) { - auto container = reinterpret_cast(work->data); - if (container != nullptr) { - container->jsResult = container->nativeEngine->CallFunction( - container->jsObj, container->jsMethod, container->argv, container->argc); - container->isCompleted = true; - if (container->isSync) { - container->self = nullptr; + auto jsWorkParam = reinterpret_cast(work->data); + if (jsWorkParam != nullptr) { + jsWorkParam->jsResult = jsWorkParam->nativeEngine->CallFunction( + jsWorkParam->jsObj, jsWorkParam->jsMethod, jsWorkParam->argv, jsWorkParam->argc); + jsWorkParam->isCompleted = true; + if (jsWorkParam->isSync) { + jsWorkParam->self = nullptr; } else { - std::unique_lock lock(container->self->conditionMutex_); - container->self->syncCon_.notify_one(); + std::unique_lock lock(jsWorkParam->self->conditionMutex_); + jsWorkParam->self->syncCon_.notify_one(); } } }); if (isSync) { std::unique_lock conditionLock(conditionMutex_); auto waitStatus = syncCon_.wait_for( - conditionLock, std::chrono::milliseconds(SYNC_TIME_OUT), [this]() { return container_.isCompleted; }); + conditionLock, std::chrono::milliseconds(SYNC_TIME_OUT), [this]() { return jsParam_.isCompleted; }); if (!waitStatus) { PRINT_HILOGE("print server load sa timeout"); return nullptr; } - return container_.jsResult; + return jsParam_.jsResult; } return nullptr; } diff --git a/frameworks/kits/extension/src/js_print_extension.cpp b/frameworks/kits/extension/src/js_print_extension.cpp index a4a2784..36c6211 100644 --- a/frameworks/kits/extension/src/js_print_extension.cpp +++ b/frameworks/kits/extension/src/js_print_extension.cpp @@ -27,12 +27,13 @@ #include "napi_common_want.h" #include "napi_print_utils.h" #include "napi_remote_object.h" -#include "print_log.h" #include "print_manager_client.h" #include "printer_capability.h" +#include "print_log.h" namespace OHOS { namespace AbilityRuntime { + JsPrintExtension *JsPrintExtension::jsExtension_ = nullptr; using namespace OHOS::AppExecFwk; using namespace OHOS::Print; @@ -47,62 +48,76 @@ JsPrintExtension *JsPrintExtension::Create(const std::unique_ptr &runti JsPrintExtension::JsPrintExtension(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {} JsPrintExtension::~JsPrintExtension() = default; -void JsPrintExtension::InitData(const std::shared_ptr &record, +void JsPrintExtension::Init(const std::shared_ptr &record, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) { PRINT_HILOGD("jws JsPrintExtension begin Init"); PrintExtension::Init(record, application, handler, token); - std::string srcPath = ""; - GetSrcPath(srcPath); - if (srcPath.empty()) { - PRINT_HILOGE("Failed to get srcPath"); + + if (!InitExtensionObj(jsRuntime_)) { + PRINT_HILOGE("Failed to init extension object"); return; } - std::string moduleName(Extension::abilityInfo_->moduleName); - moduleName.append("::").append(abilityInfo_->name); - PRINT_HILOGD("JsPrintExtension::Init module:%{public}s,srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str()); - HandleScope handleScope(jsRuntime_); - auto &engine = jsRuntime_.GetNativeEngine(); - - jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); - if (jsObj_ == nullptr) { - PRINT_HILOGE("Failed to get jsObj_"); - return; - } PRINT_HILOGD("JsPrintExtension::Init ConvertNativeValueTo."); NativeObject *obj = ConvertNativeValueTo(jsObj_->Get()); if (obj == nullptr) { PRINT_HILOGE("Failed to get JsPrintExtension object"); return; } + + if (!InitContextObj(jsRuntime_, obj)) { + PRINT_HILOGE("Failed to init extension context object"); + return; + } + + PRINT_HILOGD("JsPrintExtension::Init end."); } -void JsPrintExtension::Init(const std::shared_ptr &record, - const std::shared_ptr &application, std::shared_ptr &handler, - const sptr &token) +bool JsPrintExtension::InitExtensionObj(JsRuntime &jsRuntime) { - InitData(record, application, application, handler, token); + std::string srcPath = ""; + GetSrcPath(srcPath); + if (srcPath.empty()) { + PRINT_HILOGE("Failed to get srcPath"); + return false; + } + std::string moduleName(abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + PRINT_HILOGD("Init module:%{public}s,srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str()); + HandleScope handleScope(jsRuntime_); + + jsObj_ = jsRuntime.LoadModule(moduleName, srcPath, abilityInfo_->hapPath); + if (jsObj_ == nullptr) { + PRINT_HILOGE("Failed to get jsObj_"); + return false; + } + return true; +} + +bool JsPrintExtension::InitContextObj(JsRuntime &jsRuntime, NativeObject *&extObj) +{ auto context = GetContext(); if (context == nullptr) { PRINT_HILOGE("Failed to get context"); - return; + return false; } - PRINT_HILOGD("JsPrintExtension::Init CreateJsPrintExtensionContext."); + PRINT_HILOGD("CreateJsPrintExtensionContext."); + auto &engine = jsRuntime.GetNativeEngine(); NativeValue *contextObj = CreateJsPrintExtensionContext(engine, context); - auto shellContextRef = jsRuntime_.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE); + auto shellContextRef = jsRuntime.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE); contextObj = shellContextRef->Get(); PRINT_HILOGD("JsPrintExtension::Init Bind."); - context->Bind(jsRuntime_, shellContextRef.release()); + context->Bind(jsRuntime, shellContextRef.release()); PRINT_HILOGD("JsPrintExtension::SetProperty."); - obj->SetProperty("context", contextObj); + extObj->SetProperty("context", contextObj); auto nativeObj = ConvertNativeValueTo(contextObj); if (nativeObj == nullptr) { PRINT_HILOGE("Failed to get Print extension native object"); - return; + return false; } PRINT_HILOGD("Set Print extension context pointer: %{public}p", context.get()); @@ -114,8 +129,7 @@ void JsPrintExtension::Init(const std::shared_ptr &record, delete static_cast *>(data); }, nullptr); - - PRINT_HILOGD("JsPrintExtension::Init end."); + return true; } void JsPrintExtension::OnStart(const AAFwk::Want &want) @@ -128,8 +142,12 @@ void JsPrintExtension::OnStart(const AAFwk::Want &want) NativeValue *nativeWant = reinterpret_cast(napiWant); NativeValue *argv[] = { nativeWant }; CallObjectMethod("onCreated", argv, NapiPrintUtils::ARGC_ONE); + RegisterDiscoveryCb(); + RegisterConnectionCb(); + RegisterPrintJobCb(); + RegisterPreviewCb(); + RegisterQueryCapCb(); PRINT_HILOGD("%{public}s end.", __func__); - RegisterAllCallback(); } void JsPrintExtension::OnStop() @@ -142,7 +160,6 @@ void JsPrintExtension::OnStop() PRINT_HILOGD("The Print extension connection is not disconnected."); } PRINT_HILOGD("%{public}s end.", __func__); - RegisterAllCallback(); } sptr JsPrintExtension::OnConnect(const AAFwk::Want &want) @@ -275,8 +292,9 @@ void JsPrintExtension::GetSrcPath(std::string &srcPath) } } -void JsPrintExtension::RegisterAllCallbackPartOne() +void JsPrintExtension::RegisterDiscoveryCb() { + PRINT_HILOGD("Register Print Extension Callback"); PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_START_DISCOVERY, []() -> bool { PRINT_HILOGD("Start Print Discovery"); HandleScope handleScope(jsExtension_->jsRuntime_); @@ -293,7 +311,12 @@ void JsPrintExtension::RegisterAllCallbackPartOne() callback->Exec(value, "onStopDiscoverPrinter"); return true; }); - PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_CONNECT_PRINTER, [](uint32_t printId) -> bool { +} + +void JsPrintExtension::RegisterConnectionCb() +{ + PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_CONNECT_PRINTER, + [](uint32_t printId) -> bool { PRINT_HILOGD("Connect Printer"); HandleScope handleScope(jsExtension_->jsRuntime_); NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); @@ -306,24 +329,24 @@ void JsPrintExtension::RegisterAllCallbackPartOne() callback->Exec(value, "onConnectPrinter", arg, NapiPrintUtils::ARGC_ONE); return true; }); -} + PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_DISCONNECT_PRINTER, + [](uint32_t printId) -> bool { + PRINT_HILOGD("Disconnect Printer"); + HandleScope handleScope(jsExtension_->jsRuntime_); + NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); + napi_value jsPrintId = + OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast(nativeEng), static_cast(printId)); + NativeValue *nativePrintId = reinterpret_cast(jsPrintId); + NativeValue *arg[] = { nativePrintId }; + auto callback = std::make_shared(jsExtension_->jsRuntime_); + NativeValue *value = jsExtension_->jsObj_->Get(); + callback->Exec(value, "onDisconnectPrinter", arg, NapiPrintUtils::ARGC_ONE); + return true; + }); -void JsPrintExtension::RegisterAllCallbackPartTwo() +} +void JsPrintExtension::RegisterPrintJobCb() { - PrintManagerClient::GetInstance()->RegisterExtCallback( - PRINT_EXTCB_DISCONNECT_PRINTER, [](uint32_t printId) -> bool { - PRINT_HILOGD("Disconnect Printer"); - HandleScope handleScope(jsExtension_->jsRuntime_); - NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); - napi_value jsPrintId = - OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast(nativeEng), static_cast(printId)); - NativeValue *nativePrintId = reinterpret_cast(jsPrintId); - NativeValue *arg[] = { nativePrintId }; - auto callback = std::make_shared(jsExtension_->jsRuntime_); - NativeValue *value = jsExtension_->jsObj_->Get(); - callback->Exec(value, "onDisconnectPrinter", arg, NapiPrintUtils::ARGC_ONE); - return true; - }); PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_START_PRINT, [](const PrintJob &job) -> bool { PRINT_HILOGD("Start Print Job"); HandleScope handleScope(jsExtension_->jsRuntime_); @@ -350,47 +373,74 @@ void JsPrintExtension::RegisterAllCallbackPartTwo() callback->Exec(value, "onCancelPrintJob", arg, NapiPrintUtils::ARGC_ONE); return true; }); + } -void JsPrintExtension::RegisterAllCallback() +void JsPrintExtension::RegisterPreviewCb() { - PRINT_HILOGD("Register Print Extension Callback"); - RegisterAllCallbackPartOne(); - RegisterAllCallbackPartTwo(); - PrintManagerClient::GetInstance()->RegisterExtCallback( - PRINT_EXTCB_REQUEST_CAP, [](uint32_t printId, PrinterCapability &cap) -> bool { - PRINT_HILOGD("Request Capability"); - HandleScope handleScope(jsExtension_->jsRuntime_); - NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); - napi_value jsPrintId = - OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast(nativeEng), static_cast(printId)); - NativeValue *nativePrintId = reinterpret_cast(jsPrintId); - NativeValue *arg[] = { nativePrintId }; - auto callback = std::make_shared(jsExtension_->jsRuntime_); - NativeValue *value = jsExtension_->jsObj_->Get(); - NativeValue *result = callback->Exec(value, "onRequestPrinterCapability", arg, NapiPrintUtils::ARGC_ONE); - if (result != nullptr) { - PRINT_HILOGD("Request Capability Success"); - cap.BuildFromJs(reinterpret_cast(nativeEng), reinterpret_cast(result)); - return true; - } - PRINT_HILOGD("Request Capability Failed!!!"); - return false; - }); - PrintManagerClient::GetInstance()->RegisterExtCallback( - PRINT_EXTCB_REQUEST_PREVIEW, [](const PrintJob &job) -> bool { - PRINT_HILOGD("Requet preview"); - HandleScope handleScope(jsExtension_->jsRuntime_); - NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); - napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast(nativeEng), job); - NativeValue *nativeJob = reinterpret_cast(jobObject); - NativeValue *arg[] = { nativeJob }; + PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_REQUEST_PREVIEW, + [](const PrintJob &job) -> bool { + PRINT_HILOGD("Requet preview"); + HandleScope handleScope(jsExtension_->jsRuntime_); + NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); + napi_value jobObject = NapiPrintUtils::Convert2JsObj(reinterpret_cast(nativeEng), job); + NativeValue *nativeJob = reinterpret_cast(jobObject); + NativeValue *arg[] = { nativeJob }; - auto callback = std::make_shared(jsExtension_->jsRuntime_); - NativeValue *value = jsExtension_->jsObj_->Get(); - callback->Exec(value, "onRequestPreview", arg, NapiPrintUtils::ARGC_ONE); + auto callback = std::make_shared(jsExtension_->jsRuntime_); + NativeValue *value = jsExtension_->jsObj_->Get(); + callback->Exec(value, "onRequestPreview", arg, NapiPrintUtils::ARGC_ONE); + return true; + }); +} + +void JsPrintExtension::RegisterQueryCapCb() +{ + PrintManagerClient::GetInstance()->RegisterExtCallback(PRINT_EXTCB_REQUEST_CAP, + [](uint32_t printId, PrinterCapability &cap) -> bool { + PRINT_HILOGD("Request Capability"); + HandleScope handleScope(jsExtension_->jsRuntime_); + NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine(); + napi_value jsPrintId = + OHOS::AppExecFwk::WrapInt32ToJS(reinterpret_cast(nativeEng), static_cast(printId)); + NativeValue *nativePrintId = reinterpret_cast(jsPrintId); + NativeValue *arg[] = { nativePrintId }; + auto callback = std::make_shared(jsExtension_->jsRuntime_); + NativeValue *value = jsExtension_->jsObj_->Get(); + NativeValue* result = callback->Exec(value, "onRequestPrinterCapability", arg, NapiPrintUtils::ARGC_ONE); + if (result != nullptr) { + PRINT_HILOGD("Request Capability Success"); + cap.SetColorMode(10); + cap.SetDuplexMode(11); + + PrintMargin PrintMargin; + PrintMargin.SetTop(5); + PrintMargin.SetBottom(5); + PrintMargin.SetLeft(5); + PrintMargin.SetRight(5); + cap.SetMinMargin(PrintMargin); + + std::vector pageSizeList; + PrintPageSize pageSize; + pageSize.SetId("6"); + pageSize.SetName("name"); + pageSize.SetWidth(6); + pageSize.SetHeight(6); + pageSizeList.push_back(pageSize); + cap.SetPageSize(pageSizeList); + + std::vector resolutionList; + PrintResolution res; + res.SetId(6); + res.SetHorizontalDpi(6); + res.SetVerticalDpi(6); + resolutionList.push_back(res); + cap.SetResolution(resolutionList); return true; - }); + } + PRINT_HILOGD("Request Capability Failed!!!"); + return false; + }); } } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/extension/src/js_print_extension_context.cpp b/frameworks/kits/extension/src/js_print_extension_context.cpp index e53c218..2c76dcf 100644 --- a/frameworks/kits/extension/src/js_print_extension_context.cpp +++ b/frameworks/kits/extension/src/js_print_extension_context.cpp @@ -35,48 +35,48 @@ namespace OHOS { namespace AbilityRuntime { class JsPrintExtensionContext final { public: - explicit JsPrintExtensionContext(const std::shared_ptr &context) : context_(context) {} + explicit JsPrintExtensionContext(const std::shared_ptr& context) : context_(context) {} ~JsPrintExtensionContext() = default; static void Finalizer(NativeEngine *engine, void *data, void *hint) { PRINT_HILOGD("JsAbilityContext::Finalizer is called"); - std::unique_ptr(static_cast(data)); + std::unique_ptr(static_cast(data)); } static NativeValue *StartAbility(NativeEngine *engine, NativeCallbackInfo *info) { - JsPrintExtensionContext *me = CheckParamsAndGetThis(engine, info); + JsPrintExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr; } static NativeValue *StartAbilityWithAccount(NativeEngine *engine, NativeCallbackInfo *info) { - JsPrintExtensionContext *me = CheckParamsAndGetThis(engine, info); + JsPrintExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnStartAbilityWithAccount(*engine, *info) : nullptr; } static NativeValue *ConnectAbilityWithAccount(NativeEngine *engine, NativeCallbackInfo *info) { - JsPrintExtensionContext *me = CheckParamsAndGetThis(engine, info); + JsPrintExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnConnectAbilityWithAccount(*engine, *info) : nullptr; } static NativeValue *TerminateAbility(NativeEngine *engine, NativeCallbackInfo *info) { - JsPrintExtensionContext *me = CheckParamsAndGetThis(engine, info); + JsPrintExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnTerminateAbility(*engine, *info) : nullptr; } static NativeValue *ConnectAbility(NativeEngine *engine, NativeCallbackInfo *info) { - JsPrintExtensionContext *me = CheckParamsAndGetThis(engine, info); + JsPrintExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnConnectAbility(*engine, *info) : nullptr; } static NativeValue *DisconnectAbility(NativeEngine *engine, NativeCallbackInfo *info) { - JsPrintExtensionContext *me = CheckParamsAndGetThis(engine, info); + JsPrintExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnDisconnectAbility(*engine, *info) : nullptr; } @@ -115,7 +115,7 @@ private: auto context = weak.lock(); if (!context) { PRINT_HILOGW("context is released"); - task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released")); + task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released")); return; } @@ -136,7 +136,7 @@ private: return result; } - static void CheckInfo(NativeEngine &engine, NativeCallbackInfo &info) + NativeValue *CheckInfo(NativeEngine &engine, NativeCallbackInfo &info) { PRINT_HILOGD("OnStartAbilityWithAccount is called"); // only support two or three or four params @@ -145,6 +145,7 @@ private: PRINT_HILOGE("Not enough params"); return engine.CreateUndefined(); } + return nullptr; } NativeValue *OnStartAbilityWithAccount(NativeEngine &engine, NativeCallbackInfo &info) @@ -250,11 +251,12 @@ private: // unwrap want AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant( - reinterpret_cast(&engine), reinterpret_cast(info.argv[INDEX_ZERO]), want); + reinterpret_cast(&engine), reinterpret_cast( + info.argv[NapiPrintUtils::INDEX_ZERO]), want); PRINT_HILOGD("%{public}s bundlename:%{public}s abilityname:%{public}s", __func__, want.GetBundle().c_str(), want.GetElement().GetAbilityName().c_str()); // unwarp connection - sptr connection = new JSPrintExtensionContext(engine); + sptr connection = new JSPrintExtensionConnection(engine); connection->SetJsConnectionObject(info.argv[1]); int64_t connectId = serialNumber_; ConnecttionKey key; @@ -273,12 +275,12 @@ private: auto context = weak.lock(); if (!context) { PRINT_HILOGW("context is released"); - task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released")); + task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released")); return; } PRINT_HILOGD("context->ConnectAbility connection:%{public}d", (int32_t)connectId); if (!context->ConnectAbility(want, connection)) { - connection->CallJsFailed(ERROR_CODE_ONE); + connection->CallJsFailed(NapiPrintUtils::ERROR_CODE_ONE); } task.Resolve(engine, engine.CreateUndefined()); }; @@ -331,12 +333,12 @@ private: auto context = weak.lock(); if (!context) { PRINT_HILOGW("context is released"); - task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released")); + task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released")); return; } PRINT_HILOGD("context->ConnectAbilityWithAccount connection:%{public}d", (int32_t)connectId); if (!context->ConnectAbilityWithAccount(want, accountId, connection)) { - connection->CallJsFailed(ERROR_CODE_ONE); + connection->CallJsFailed(NapiPrintUtils::ERROR_CODE_ONE); } task.Resolve(engine, engine.CreateUndefined()); }; diff --git a/interfaces/kits/napi/include/print_parse_type.h b/interfaces/kits/napi/include/print_parse_type.h index c4cbadf..41a6c5f 100644 --- a/interfaces/kits/napi/include/print_parse_type.h +++ b/interfaces/kits/napi/include/print_parse_type.h @@ -43,9 +43,10 @@ public: static bool ParseInfoParam(napi_env env, napi_value InfoValue, PrinterInfo &info); static bool ParseCapParam(napi_env env, napi_value InfoValue, PrinterCapability &capability); - static void CoversePriotResolutionObject(napi_env env, napi_value capValue, PrinterCapability &capability); + static bool CoversePrintPageSizeObject(napi_env env, napi_value capValue, PrinterCapability &capability); static bool ParseArrPrintResolution( - napi_env env, napi_value capValue, PrinterCapability &capability) static bool ParsePageSizeParam(napi_env env, + napi_env env, napi_value capValue, PrinterCapability &capability); + static bool ParsePageSizeParam(napi_env env, napi_value capValue, PrintPageSize &PrintPageSize); static bool ParseResolutionParam(napi_env env, napi_value reValue, PrintResolution &PrintResolution); static bool ParseMarginParam(napi_env env, napi_value marginValue, PrintMargin &PrintMargin); diff --git a/interfaces/kits/napi/src/print_parse_type.cpp b/interfaces/kits/napi/src/print_parse_type.cpp index a2cd9b0..0a85a99 100644 --- a/interfaces/kits/napi/src/print_parse_type.cpp +++ b/interfaces/kits/napi/src/print_parse_type.cpp @@ -172,8 +172,7 @@ bool PrintParseType::ParseJob(napi_env env, napi_value jobValue, PrintJob &print PRINT_HILOGD("printJob_value GetPrinterId value is %{public}d", printJob.GetPrinterId()); PRINT_HILOGD("printJob_value GetJobState value is %{public}d", printJob.GetJobState()); PRINT_HILOGD("printJob_value GetCopyNumber value is %{public}d", printJob.GetCopyNumber()); - PRINT_HILOGD("printJob_value SetIsLandscape value is %{public}s", printJob.GetIsLandscape() ? "true" : "false"); - PRINT_HILOGD("printJob_value SetIsLandscape value is %{public}s", printJob.GetIsLandscape() ? "true" : "false"); + PRINT_HILOGD("printJob_value SetIsLandscape value is %{public}d", printJob.GetIsLandscape()); PRINT_HILOGD("printJob_value ColorMode value is %{public}d", printJob.GetIsSequential()); PRINT_HILOGD("printJob_value DuplexMode value is %{public}d", printJob.GetDuplexMode()); return true; @@ -260,7 +259,7 @@ bool PrintParseType::ParseCapParam(napi_env env, napi_value capValue, PrinterCap capability.SetMinMargin(margin); } - if (!CoversePriotResolutionObject(env, capValue, capability)) { + if (!CoversePrintPageSizeObject(env, capValue, capability)) { PRINT_HILOGE("error Arr ParsePageSize"); return false; } @@ -285,7 +284,7 @@ bool PrintParseType::ParseCapParam(napi_env env, napi_value capValue, PrinterCap return true; } -void PrintPaeseType::CoversePriotResolutionObject(napi_env env, napi_value capValue, PrinterCapability &capability) +bool PrintParseType::CoversePrintPageSizeObject(napi_env env, napi_value capValue, PrinterCapability &capability) { napi_value param_two = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_CAPABILITY_PAGESIZE); if (NapiPrintUtils::GetValueType(env, param_two) != napi_object) { @@ -313,6 +312,7 @@ void PrintPaeseType::CoversePriotResolutionObject(napi_env env, napi_value capVa pageSizeList.push_back(pageSize); } capability.SetPageSize(pageSizeList); + return true; } } @@ -346,6 +346,7 @@ bool PrintParseType::ParseArrPrintResolution(napi_env env, napi_value capValue, } return true; } + bool PrintParseType::ParsePageSizeParam(napi_env env, napi_value capValue, PrintPageSize &pageSize) { napi_value param_one = NapiPrintUtils::GetNamedProperty(env, capValue, PARAM_PAGESIZE_ID); diff --git a/interfaces/kits/napi/test/BUILD.gn b/interfaces/kits/napi/test/BUILD.gn deleted file mode 100644 index 8b7989b..0000000 --- a/interfaces/kits/napi/test/BUILD.gn +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") - -#################################group######################################### -group("unittest") { - testonly = true - deps = [] - - deps += [ "unittest/src:unittest" ] -} -############################################################################### diff --git a/interfaces/kits/napi/test/unittest/src/Print.test.ets b/interfaces/kits/napi/test/unittest/src/Print.test.ets deleted file mode 100644 index c7e30dc..0000000 --- a/interfaces/kits/napi/test/unittest/src/Print.test.ets +++ /dev/null @@ -1,289 +0,0 @@ -// @ts-nocheck - -/** - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { describe, it, expect } from "deccjsunit/index.ets"; -import print from '@ohos.print'; - -export default function requestPrintJsunit() { - describe('requestPrintTest', function () { - let files = ['D:/dev/a.docx'] - let keyStr = 'print demo '; - let PrintJobState = 2 - let jobId = 1 - let PrinterState = 1 - let uri = 'www.baidu.com' - - let PrinterRange = { - startPage: 1, // start page of sequence - endPage: 4, // end page of sequence - pages: [1, 4], // discrete page of sequence - } - let PrinterPageSizeArr = [ - { - id: 1, // page size id - name: 'string', // page size name - width: 200, // unit: milimeter - height: 200, // unit: milimeter - } - ] - let PrinterPageSize = { - id: 1, // page size id - name: 'string', // page size name - width: 200, // unit: milimeter - height: 200, // unit: milimeter - } - - let PrintMargin = { - top: 1, // top margin - bottom: 2, // bottom margin - left: 1, // left side margin - right: 1, // right side margin - } - let PreviewAttribute = { - previewRange: PrinterRange, // preview page range - result: 'string', // preview file - } - let PrintJob = { - files: ['D:/dev/a.docx'], - jobId: 3, - printerId: 2, // printer id to take charge of printing - jobState: PrinterState, // current print job state - copyNumber: 3, // copies of document list - pageRange: PrinterRange, - isSequential: false, // sequential print - pageSize: PrinterPageSize, // the selected page size - isLandscape: false, // vertical printing - colorMode: 1, // color mode - duplexMode: 1, // duplex mode - margin: PrintMargin, // current margin setting - preview: PreviewAttribute, // preview setting - } - - let PrinterResolutionArr = [{ - id: 2, // resolution id - horizontalDpi: 2, // horizontal DPI - verticalDpi: 1, // vertical DPI - }] - let PrinterResolution = { - id: 2, // resolution id - horizontalDpi: 2, // horizontal DPI - verticalDpi: 1, // vertical DPI - } - let PrinterCapability = { - /* Printer Capability */ - minMargin: PrintMargin, // min margin of printer - pageSize: PrinterPageSizeArr, // the page size list supported by the printer - resolution: PrinterResolutionArr, // the resolution list supported by the printer - colorMode: 1, // color mode - duplexMode: 2, // duplex mode - } - let PrinterInfo = { - printerId: 1, // printer id - printerName: 'string', // printer name - printerIcon: 1, // resource id of printer icon - printerState: 1, // current printer state - description: 'string', // printer description - capability: PrinterCapability, - } - let PrinterInfo1 = { - printerId: 2, // printer id - printerName: 'char', // printer name - printerIcon: 2, // resource id of printer icon - printerState: 2, // current printer state - description: 'char', // printer description - capability: PrinterCapability, - } - let PrinterInfoArray = [PrinterInfo, PrinterInfo1] - - let file = ['11111', '123123', '12312'] - let printTaskObj = null - let context - let extensionList = [1, 2, 3, 4]; - let printerId = 3; - let PrinterInfo2 = { - printerName: 'string', // printer name - printerIcon: 1, // resource id of printer icon - printerState: 1, // current printer state - description: 'string', // printer description - } - - let TAG = ""; - - /** - * @tc.number requestPrint_test_0100 - * @tc.name addPrinters: New printers have been found and notify Print SA (by Promise) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0100', 0, async function (done) { - TAG = "requestPrint_test_0100"; - await print.addPrinters(PrinterInfoArray).then((data) => { - console.info(TAG + " result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - }).catch((error) => { - console.info(TAG + " err: " + JSON.stringify(error)); - expect(false).assertTrue(); - done(); - }); - }); - - /** - * @tc.number requestPrint_test_0200 - * @tc.name addPrinters: New printers have been found and notify Print SA (by callback) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0200', 0, async function (done) { - TAG = "requestPrint_test_0200"; - await print.addPrinters(PrinterInfoArray, (err, data) => { - if (err) { - console.info(TAG + " err: " + JSON.stringify(err)); - expect(false).assertTrue(); - } else { - console.info(TAG + " result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - } - }); - }); - - /** - * @tc.number requestPrint_test_0300 - * @tc.name removePrinters: Printers have been lost and notify Print SA (by Promise) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0300', 0, async function (done) { - TAG = "requestPrint_test_0300"; - await print.removePrinters(PrinterInfoArray).then((data) => { - console.info(TAG + " removePrinters result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - }).catch((error) => { - console.info(TAG + " removePrinters err: " + JSON.stringify(error)); - expect(false).assertTrue(); - done(); - }); - }); - - /** - * @tc.number requestPrint_test_0400 - * @tc.name removePrinters: Printers have been lost and notify Print SA (by callback) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0400', 0, async function (done) { - TAG = "requestPrint_test_0400"; - await print.removePrinters(PrinterInfoArray, (err, data) => { - if (err) { - console.info(TAG + " removePrinters err: " + JSON.stringify(err)); - expect(false).assertTrue(); - } else { - console.info(TAG + " removePrinters result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - } - }); - }); - - /** - * @tc.number requestPrint_test_0500 - * @tc.name updatePrinterState: Notify Print SA the state of printer has been changed (by Promise) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0500', 0, async function (done) { - TAG = "requestPrint_test_0500"; - await print.updatePrinterState(printerId, PrinterState).then((data) => { - console.info(TAG + " result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - }).catch((error) => { - console.info(TAG + " err: " + JSON.stringify(error)); - expect(false).assertTrue(); - done(); - }); - }); - - /** - * @tc.number requestPrint_test_0600 - * @tc.name updatePrinterState: Notify Print SA the state of printer has been changed (by callback) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0600', 0, async function (done) { - TAG = "requestPrint_test_0600"; - await print.updatePrinterState(printerId, PrinterState, (err, data) => { - if (err) { - console.info(TAG + " err: " + JSON.stringify(err)); - expect(false).assertTrue(); - } else { - console.info(TAG + " result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - } - }); - }); - - /** - * @tc.number requestPrint_test_0700 - * @tc.name updatePrintJobState: Notify Print SA the state of print job has been changed (by Promise) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0700', 0, async function (done) { - TAG = "requestPrint_test_0700"; - await print.updatePrintJobState(jobId, PrintJobState).then((data) => { - console.info(TAG + " result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - }).catch((error) => { - console.info(TAG + " err: " + JSON.stringify(error)); - expect(false).assertTrue(); - done(); - }); - }); - - /** - * @tc.number requestPrint_test_0800 - * @tc.name updatePrintJobState: Notify Print SA the state of print job has been changed (by callback) - * @tc.desc Function test - * @tc.level Level 0 - */ - it('requestPrint_test_0800', 0, async function (done) { - TAG = "requestPrint_test_0800"; - await print.updatePrintJobState(jobId, PrintJobState, (err, data) => { - if (err) { - console.info(TAG + " err: " + JSON.stringify(err)); - expect(false).assertTrue(); - } else { - console.info(TAG + " result: " + JSON.stringify(data)); - expect(typeof (data)).assertEqual('boolean'); - expect(data).assertEqual(true); - done(); - } - }); - }); - }) -} \ No newline at end of file diff --git a/interfaces/kits/napi/test/unittest/src/config.json b/interfaces/kits/napi/test/unittest/src/config.json deleted file mode 100644 index d701976..0000000 --- a/interfaces/kits/napi/test/unittest/src/config.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "app": { - "bundleName": "com.example.printerxts", - "vendor": "example", - "version": { - "code": 1000000, - "name": "1.0.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.entry", - "name": ".entry", - "mainAbility": ".MainAbility", - "deviceType": [ - "phone" - ], - - "reqPermissions": [ - { - "name" : "ohos.permission.INTERNET", - "reason" : "need use ohos.permission.INTERNET" - }, - { - "name" : "ohos.permission.MANAGE_PRINT_JOB", - "reason" : "need use ohos.permission.MANAGE_PRINT_JOB" - }, - { - "name" : "ohos.permission.PRINT", - "reason" : "need use ohos.permission.PRINT" - } - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry", - "installationFree": false - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "orientation": "unspecified", - "formsEnabled": false, - "name": ".MainAbility", - "srcLanguage": "ets", - "srcPath": "MainAbility", - "icon": "$media:icon", - "description": "$string:MainAbility_desc", - "label": "$string:MainAbility_label", - "type": "page", - "visible": true, - "launchType": "standard" - } - ], - "js": [ - { - "mode": { - "syntax": "ets", - "type": "pageAbility" - }, - "pages": [ - "pages/index" - ], - "name": ".MainAbility", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } -} \ No newline at end of file diff --git a/interfaces/kits/napi/test/unittest/src/BUILD.gn b/print.gni similarity index 58% rename from interfaces/kits/napi/test/unittest/src/BUILD.gn rename to print.gni index f6c414d..ac63e71 100644 --- a/interfaces/kits/napi/test/unittest/src/BUILD.gn +++ b/print.gni @@ -11,19 +11,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/test.gni") +ability_runtime_path = "//foundation/ability/ability_runtime" -module_output_path = "print/print" +ability_runtime_inner_api_path = "${ability_runtime_path}/interfaces/inner_api" -ohos_js_unittest("PrintTest") { - module_out_path = module_output_path +ability_runtime_kits_path = "${ability_runtime_path}/frameworks/kits" - hap_profile = "./config.json" +ability_runtime_napi_path = "${ability_runtime_path}/frameworks/js/napi" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" -} +ability_runtime_services_path = "${ability_runtime_path}/services" -group("unittest") { - testonly = true - deps = [ ":PrintTest" ] -} +print_path = "//base/print/print" + +utils_path = "${print_path}/utils" diff --git a/profile/print_service.xml b/profile/print_service.xml new file mode 100644 index 0000000..28dcb8f --- /dev/null +++ b/profile/print_service.xml @@ -0,0 +1,24 @@ + + + + print_service + + 3707 + libprint_service.z.so + true + false + 1 + + \ No newline at end of file diff --git a/services/src/print_service_ability.cpp b/services/src/print_service_ability.cpp index 966756b..84f1548 100644 --- a/services/src/print_service_ability.cpp +++ b/services/src/print_service_ability.cpp @@ -320,15 +320,19 @@ bool PrintServiceAbility::QueryPrinterCapability(uint32_t printerId, PrinterCapa { ManualStart(); PRINT_HILOGD("QueryPrinterCapability started."); + PRINT_HILOGD("printerId : %{public}d", printerId); auto it = extCallbackMap_.find(PRINT_EXTCB_REQUEST_CAP); bool result = false; MessageParcel reply; if (it != extCallbackMap_.end()) { + PRINT_HILOGD("QueryPrinterCapability OnCallback."); result = it->second->OnCallback(printerId, reply); printerCapability.BuildFromParcel(reply); + printerCapability.Dump(); + return result; } PRINT_HILOGW("QueryPrinterCapability Not Register Yet!!!"); - return result; + return false; } bool PrintServiceAbility::CheckPermission() diff --git a/services/src/print_service_stub.cpp b/services/src/print_service_stub.cpp index 8581de8..ccc2143 100644 --- a/services/src/print_service_stub.cpp +++ b/services/src/print_service_stub.cpp @@ -14,7 +14,6 @@ */ #include "print_service_stub.h" - #include "ipc_skeleton.h" #include "iprint_service.h" #include "message_parcel.h"