Add 3th 0909 code

Signed-off-by: @chuangda_1 <fangwanning@huawei.com>
This commit is contained in:
@chuangda_1 2022-09-09 16:13:26 +08:00
parent 2de06cf736
commit 1232d2eaa4
16 changed files with 223 additions and 575 deletions

View File

@ -53,7 +53,6 @@
"//base/print/print/profile:print_sa_profiles"
],
"test": [
"//base/print/print/interfaces/kits/napi/test:unittest"
]
},
"hisysevent_config": [

View File

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

View File

@ -421,4 +421,4 @@ napi_value NapiPrintUtils::Convert2JsObj(napi_env env, const PrintJob &job)
return result;
}
} // namespace OHOS::Print
} // namespace OHOS::Print

View File

@ -14,7 +14,6 @@
*/
#include "print_resolution.h"
#include "print_log.h"
namespace OHOS::Print {

View File

@ -105,7 +105,7 @@ bool PrintServiceProxy::StartDiscoverPrinter(const std::vector<uint32_t> &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<PrinterInfo> &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<PrinterInfo> &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]);
}

View File

@ -34,12 +34,16 @@ class JsPrintCallback : public std::enable_shared_from_this<JsPrintCallback> {
public:
explicit JsPrintCallback(JsRuntime &jsRutime);
~JsPrintCallback() = default;
void SetjsWorker(NativeValue *jsObj, const std::string &name,
uv_loop_s *loop, 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<JsPrintCallback> self;
NativeEngine *nativeEngine;
NativeValue *jsObj;
@ -53,7 +57,7 @@ private:
JsRuntime &jsRuntime_;
uv_work_t *jsWorker_;
JsPrintCallback::Container container_;
JsPrintCallback::JsWorkParam jsParam_;
std::mutex conditionMutex_;
std::condition_variable syncCon_;

View File

@ -22,6 +22,7 @@
class NativeReference;
class NativeValue;
class NativeObject;
namespace OHOS {
namespace AbilityRuntime {
@ -44,11 +45,6 @@ public:
*/
static JsPrintExtension *Create(const std::unique_ptr<Runtime> &runtime);
void InitData(const std::shared_ptr<AppExecFwk::AbilityLocalRecord> &record,
const std::shared_ptr<AppExecFwk::OHOSApplication> &application,
std::shared_ptr<AppExecFwk::AbilityHandler> &handler, const sptr<IRemoteObject> &token,
std::string &srcPath, std::string &moduleName);
/**
* @brief Init the extension.
*
@ -113,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);

View File

@ -36,79 +36,90 @@ using namespace OHOS::Print;
JsPrintCallback::JsPrintCallback(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {}
void JsPrintCallback::SetjsWorker(
NativeValue *jsObj, const std::string &name,
uv_loop_s *loop, 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<napi_env>(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<NativeObject>(jsObj);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return;
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;
return false;
}
PRINT_HILOGD("%{public}s callback in", name.c_str());
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_get_uv_event_loop(reinterpret_cast<napi_env>(nativeEngine), &loop);
if (loop == nullptr) {
PRINT_HILOGE("Failed to get uv event loop");
return;
}
jsWorker_ = new (std::nothrow) uv_work_t;
if (jsWorker_ == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return;
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)
{
uv_loop_s *loop = nullptr;
SetjsWorker(jsObj, name, loop, 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<JsPrintCallback::Container *>(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<JsPrintCallback::JsWorkParam*>(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<std::mutex> lock(container->self->conditionMutex_);
container->self->syncCon_.notify_one();
std::unique_lock<std::mutex> lock(jsWorkParam->self->conditionMutex_);
jsWorkParam->self->syncCon_.notify_one();
}
}
});
if (isSync) {
std::unique_lock<std::mutex> 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;
}

View File

@ -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,60 +48,76 @@ JsPrintExtension *JsPrintExtension::Create(const std::unique_ptr<Runtime> &runti
JsPrintExtension::JsPrintExtension(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {}
JsPrintExtension::~JsPrintExtension() = default;
void JsPrintExtension::InitData(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token, std::string &srcPath, std::string &moduleName)
{
PRINT_HILOGD("jws JsPrintExtension begin Init");
PrintExtension::Init(record, application, handler, token);
GetSrcPath(srcPath);
if (srcPath.empty()) {
PRINT_HILOGE("Failed to get srcPath");
return;
}
moduleName.append("::").append(abilityInfo_->name);
PRINT_HILOGD("JsPrintExtension::Init module:%{public}s,srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str());
HandleScope handleScope(jsRuntime_);
}
void JsPrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
std::string srcPath = "";
std::string moduleName(Extension::abilityInfo_->moduleName);
InitData(record, application, handler, token, srcPath, moduleName);
auto &engine = jsRuntime_.GetNativeEngine();
jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath, abilityInfo_->hapPath);
if (jsObj_ == nullptr) {
PRINT_HILOGE("Failed to get jsObj_");
PRINT_HILOGD("jws JsPrintExtension begin Init");
PrintExtension::Init(record, application, handler, token);
if (!InitExtensionObj(jsRuntime_)) {
PRINT_HILOGE("Failed to init extension object");
return;
}
PRINT_HILOGD("JsPrintExtension::Init ConvertNativeValueTo.");
NativeObject *obj = ConvertNativeValueTo<NativeObject>(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.");
}
bool JsPrintExtension::InitExtensionObj(JsRuntime &jsRuntime)
{
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<NativeObject>(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());
@ -112,8 +129,7 @@ void JsPrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
delete static_cast<std::weak_ptr<AbilityRuntime::Context> *>(data);
},
nullptr);
PRINT_HILOGD("JsPrintExtension::Init end.");
return true;
}
void JsPrintExtension::OnStart(const AAFwk::Want &want)
@ -126,8 +142,12 @@ void JsPrintExtension::OnStart(const AAFwk::Want &want)
NativeValue *nativeWant = reinterpret_cast<NativeValue *>(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()
@ -140,7 +160,6 @@ void JsPrintExtension::OnStop()
PRINT_HILOGD("The Print extension connection is not disconnected.");
}
PRINT_HILOGD("%{public}s end.", __func__);
RegisterAllCallback();
}
sptr<IRemoteObject> JsPrintExtension::OnConnect(const AAFwk::Want &want)
@ -273,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_);
@ -291,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();
@ -304,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<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(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<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(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_);
@ -348,47 +373,49 @@ 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<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(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<napi_env>(nativeEng), reinterpret_cast<napi_value>(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<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(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<napi_env>(nativeEng), job);
NativeValue *nativeJob = reinterpret_cast<NativeValue *>(jobObject);
NativeValue *arg[] = { nativeJob };
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onRequestPreview", arg, NapiPrintUtils::ARGC_ONE);
auto callback = std::make_shared<JsPrintCallback>(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<napi_env>(nativeEng), static_cast<int32_t>(printId));
NativeValue *nativePrintId = reinterpret_cast<NativeValue *>(jsPrintId);
NativeValue *arg[] = { nativePrintId };
auto callback = std::make_shared<JsPrintCallback>(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<napi_env>(nativeEng), reinterpret_cast<napi_value>(result));
return true;
});
}
PRINT_HILOGD("Request Capability Failed!!!");
return false;
});
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -35,7 +35,7 @@ namespace OHOS {
namespace AbilityRuntime {
class JsPrintExtensionContext final {
public:
explicit JsPrintExtensionContext(const std::shared_ptr<PrintExtensionContext>& context) : context_(context) {}
explicit JsPrintExtensionContext(const std::shared_ptr<PrintExtensionContext>& context) : context_(context){}
~JsPrintExtensionContext() = default;
static void Finalizer(NativeEngine *engine, void *data, void *hint)
@ -251,8 +251,7 @@ private:
// unwrap want
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(
reinterpret_cast<napi_env>(&engine), reinterpret_cast<napi_value>(
info.argv[NapiPrintUtils::INDEX_ZERO]), want);
reinterpret_cast<napi_env>(&engine), reinterpret_cast<napi_value>(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
@ -472,6 +471,7 @@ NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine, std::shared_ptr
// make handler
handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
#if 1
const char *moduleName = "JsPrintExtensionContext";
BindNativeFunction(engine, *object, "startAbility", moduleName, JsPrintExtensionContext::StartAbility);
BindNativeFunction(engine, *object, "terminateSelf", moduleName, JsPrintExtensionContext::TerminateAbility);
@ -481,6 +481,16 @@ NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine, std::shared_ptr
engine, *object, "startAbilityWithAccount", moduleName, JsPrintExtensionContext::StartAbilityWithAccount);
BindNativeFunction(
engine, *object, "connectAbilityWithAccount", moduleName, JsPrintExtensionContext::ConnectAbilityWithAccount);
#else
BindNativeFunction(engine, *object, "startAbility", JsPrintExtensionContext::StartAbility);
BindNativeFunction(engine, *object, "terminateSelf", JsPrintExtensionContext::TerminateAbility);
BindNativeFunction(engine, *object, "connectAbility", JsPrintExtensionContext::ConnectAbility);
BindNativeFunction(engine, *object, "disconnectAbility", JsPrintExtensionContext::DisconnectAbility);
BindNativeFunction(
engine, *object, "startAbilityWithAccount", JsPrintExtensionContext::StartAbilityWithAccount);
BindNativeFunction(
engine, *object, "connectAbilityWithAccount", JsPrintExtensionContext::ConnectAbilityWithAccount);
#endif
if (context) {
PRINT_HILOGD("Set ExtensionAbilityInfo Property");
auto abilityInfo = context->GetAbilityInfo();

View File

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

View File

@ -1,29 +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")
module_output_path = "print/print"
ohos_js_unittest("PrintTest") {
module_out_path = module_output_path
hap_profile = "./config.json"
certificate_profile = "//test/developertest/signature/openharmony_sx.p7b"
}
group("unittest") {
testonly = true
deps = [ ":PrintTest" ]
}

View File

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

View File

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

24
profile/print_service.xml Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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.
-->
<info>
<process>print_service</process>
<systemability>
<name>3707</name>
<libpath>libprint_service.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

View File

@ -14,7 +14,6 @@
*/
#include "print_service_stub.h"
#include "ipc_skeleton.h"
#include "iprint_service.h"
#include "message_parcel.h"