Add 1011 code

Signed-off-by: @chuangda_1 <fangwanning@huawei.com>
This commit is contained in:
@chuangda_1 2022-10-11 20:42:15 +08:00
parent 3b16f449e8
commit 612c92506f
99 changed files with 13453 additions and 0 deletions

23
profile/etc/init/BUILD.gn Normal file
View File

@ -0,0 +1,23 @@
# 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/ohos.gni")
################################################################################
ohos_prebuilt_etc("printservice.rc") {
source = "printservice.cfg"
relative_install_dir = "init"
part_name = "print"
subsystem_name = "print"
}

View File

@ -0,0 +1,11 @@
{
"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

@ -0,0 +1,20 @@
# 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.
on boot
start print_service
service print_service /system/bin/sa_main /system/profile/print_service.xml
class z_core
user system
group system shell
seclabel u:r:print_service:s0

View File

@ -0,0 +1,84 @@
# 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("//base/request/request/request_aafwk.gni")
import("//build/ohos.gni")
config("print_interfaces_kits_napi_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags_cc = [ "-fexceptions" ]
}
ohos_shared_library("print_client") {
include_dirs = [
"//foundation/arkui/ace_engine/frameworks/base/utils",
"//foundation/arkui/napi",
"//foundation/arkui/napi/interfaces/kits",
"//foundation/arkui/napi/interfaces/inner_api",
"//third_party/node/src",
"//third_party/curl/include",
"${ability_runtime_services_path}/common/include",
"//utils/system/safwk/native/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/app/",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_services_path}/abilitymgr/include",
"${ability_runtime_inner_api_path}/ability_manager/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/Isamgr",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//base/print/print/utils/include",
]
public_configs = [ ":print_interfaces_kits_napi_config" ]
sources = [
"src/napi_print_utils.cpp",
"src/print_callback_stub.cpp",
"src/print_extension_callback_stub.cpp",
"src/print_extension_info.cpp",
"src/print_callback.cpp",
"src/print_job.cpp",
"src/print_manager_client.cpp",
"src/print_margin.cpp",
"src/print_page_size.cpp",
"src/print_preview_attribute.cpp",
"src/print_range.cpp",
"src/print_resolution.cpp",
"src/print_sa_death_recipient.cpp",
"src/print_service_proxy.cpp",
"src/print_sync_load_callback.cpp",
"src/printer_capability.cpp",
"src/printer_info.cpp",
]
deps = [
"//foundation/arkui/napi:ace_napi",
"//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"ability_runtime:data_ability_helper",
"ability_runtime:napi_base_context",
"c_utils:utils",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"preferences:native_preferences",
"relational_store:native_appdatafwk",
"relational_store:native_dataability",
"relational_store:native_rdb",
]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -0,0 +1,41 @@
/*
* 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.
*/
#ifndef IPRINT_CALLBACK_H
#define IPRINT_CALLBACK_H
#include "iremote_broker.h"
#include "iremote_object.h"
#include "printer_info.h"
#include "print_job.h"
namespace OHOS::Print {
class IPrintCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print.IPrintCallback");
virtual bool OnCallback() = 0;
virtual bool OnCallback(uint32_t state, const PrinterInfo &info) = 0;
virtual bool OnCallback(uint32_t state, const PrintJob &info) = 0;
virtual bool OnCallback(const std::string &extensionId, const std::string &info) = 0;
};
enum {
PRINT_CALLBACK_TASK,
PRINT_CALLBACK_PRINTER,
PRINT_CALLBACK_PRINT_JOB,
PRINT_CALLBACK_EXTINFO,
};
} // namespace OHOS::Print
#endif // IPRINT_CALLBACK_H

View File

@ -0,0 +1,52 @@
/*
* 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.
*/
#ifndef IPRINT_EXTENSION_CALLBACK_H
#define IPRINT_EXTENSION_CALLBACK_H
#include "iremote_broker.h"
#include "iremote_object.h"
#include "print_job.h"
namespace OHOS::Print {
class IPrintExtensionCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print.IPrintExtensionCallback");
virtual bool OnCallback() = 0;
virtual bool OnCallback(const std::string &printerId) = 0;
virtual bool OnCallback(const PrintJob &job) = 0;
virtual bool OnCallback(const std::string &printerId, MessageParcel &reply) = 0;
};
enum {
PRINT_EXTCB,
PRINT_EXTCB_PRINTER,
PRINT_EXTCB_PRINTJOB,
PRINT_EXTCB_PRINTCAPABILITY,
};
enum {
PRINT_EXTCB_START_DISCOVERY,
PRINT_EXTCB_STOP_DISCOVERY,
PRINT_EXTCB_CONNECT_PRINTER,
PRINT_EXTCB_DISCONNECT_PRINTER,
PRINT_EXTCB_START_PRINT,
PRINT_EXTCB_CANCEL_PRINT,
PRINT_EXTCB_REQUEST_CAP,
PRINT_EXTCB_REQUEST_PREVIEW,
PRINT_EXTCB_MAX,
};
} // namespace OHOS::Print
#endif // IPRINT_EXTCB_H

View File

@ -0,0 +1,83 @@
/*
* 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.
*/
#ifndef PRINT_SERVICE_INTERFACE_H
#define PRINT_SERVICE_INTERFACE_H
#include <string>
#include <vector>
#include "iprint_callback.h"
#include "iprint_extension_callback.h"
#include "iremote_broker.h"
#include "print_extension_info.h"
#include "print_job.h"
#include "printer_info.h"
namespace OHOS::Print {
class IPrintService : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Print.IPrintService");
virtual int32_t StartPrint(const std::vector<std::string> &fileList, std::string &taskId) = 0;
virtual int32_t StopPrint(const std::string &taskId) = 0;
virtual int32_t ConnectPrinter(const std::string &printerId) = 0;
virtual int32_t DisconnectPrinter(const std::string &printerId) = 0;
virtual int32_t StartDiscoverPrinter(const std::vector<std::string> &extensionList) = 0;
virtual int32_t StopDiscoverPrinter() = 0;
virtual int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos) = 0;
virtual int32_t StartPrintJob(const PrintJob &jobInfo) = 0;
virtual int32_t CancelPrintJob(const PrintJob &jobInfo) = 0;
virtual int32_t AddPrinters(const std::vector<PrinterInfo> &printerInfos) = 0;
virtual int32_t RemovePrinters(const std::vector<std::string> &printerIds) = 0;
virtual int32_t UpdatePrinters(const std::vector<PrinterInfo> &printerInfos) = 0;
virtual int32_t UpdatePrinterState(const std::string &printerId, uint32_t state) = 0;
virtual int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) = 0;
virtual int32_t UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo) = 0;
virtual int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult) = 0;
virtual int32_t QueryPrinterCapability(const std::string &printerId, PrinterCapability &printerCapability) = 0;
virtual int32_t On(const std::string &type, const sptr<IPrintCallback> &listener) = 0;
virtual int32_t Off(const std::string &type) = 0;
virtual int32_t RegisterExtCallback(const std::string extensionCID,
const sptr<IPrintExtensionCallback> &listener) = 0;
virtual int32_t UnregisterAllExtCallback(const std::string &extensionId) = 0;
virtual int32_t Read(std::vector<uint8_t> &fileRead, const std::string &uri, uint32_t offset, uint32_t max) = 0;
};
enum {
CMD_START_PRINT,
CMD_STOP_PRINT,
CMD_CONNECTPRINTER,
CMD_DISCONNECTPRINTER,
CMD_STARTDISCOVERPRINTER,
CMD_STOPDISCOVERPRINTER,
CMD_QUERYALLEXTENSION,
CMD_STARTPRINTJOB,
CMD_CANCELPRINTJOB,
CMD_ADDPRINTERS,
CMD_REMOVEPRINTERS,
CMD_UPDATEPRINTERS,
CMD_UPDATEPRINTERSTATE,
CMD_UPDATEPRINTJOBSTATE,
CMD_UPDATEEXTENSIONINFO,
CMD_REQUESTPREVIEW,
CMD_QUERYPRINTERCAPABILITY,
CMD_ON,
CMD_OFF,
CMD_REG_EXT_CB,
CMD_UNREG_EXT_CB,
CMD_READ_DATA,
};
} // namespace OHOS::Print
#endif // PRINT_SERVICE_INTERFACE_H

View File

@ -0,0 +1,96 @@
/*
* 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.
*/
#ifndef NAPI_PRINT_UTILS_H
#define NAPI_PRINT_UTILS_H
#include <string>
#include <vector>
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "print_job.h"
#include "print_resolution.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
class NapiPrintUtils {
public:
static constexpr size_t MAX_ARGC = 6;
static constexpr size_t ARGC_ZERO = 0;
static constexpr size_t ARGC_ONE = 1;
static constexpr size_t ARGC_TWO = 2;
static constexpr size_t ARGC_THREE = 3;
static constexpr size_t ARGC_FOUR = 4;
static constexpr size_t ARGC_FIVE = 5;
static constexpr size_t ARGC_SIX = 6;
static constexpr int32_t INDEX_ZERO = 0;
static constexpr int32_t INDEX_ONE = 1;
static constexpr int32_t INDEX_TWO = 2;
static constexpr int32_t INDEX_THREE = 3;
static constexpr int32_t INDEX_FOUR = 4;
static constexpr int32_t INDEX_FIVE = 5;
static constexpr int32_t ERROR_CODE_ONE = 1;
static constexpr int32_t ERROR_CODE_TWO = 2;
static constexpr int32_t MAX_NUMBER_BYTES = 8;
static constexpr int32_t MAX_LEN = 4096;
static constexpr int32_t MAX_JOBSTRING_LENGTH = 10;
static napi_valuetype GetValueType(napi_env env, napi_value value);
static bool HasNamedProperty(napi_env env, napi_value object, const std::string &propertyName);
static napi_value GetNamedProperty(napi_env env, napi_value object, const std::string &propertyName);
static void SetNamedProperty(napi_env env, napi_value object, const std::string &name, napi_value value);
static std::vector<std::string> GetPropertyNames(napi_env env, napi_value object);
static napi_value CreateUint32(napi_env env, uint32_t code);
static uint32_t GetUint32FromValue(napi_env env, napi_value value);
static uint32_t GetUint32Property(napi_env env, napi_value object, const std::string &propertyName);
static void SetUint32Property(napi_env env, napi_value object, const std::string &name, uint32_t value);
static napi_value CreateInt32(napi_env env, int32_t code);
static int32_t GetInt32FromValue(napi_env env, napi_value value);
static int32_t GetInt32Property(napi_env env, napi_value object, const std::string &propertyName);
static void SetInt32Property(napi_env env, napi_value object, const std::string &name, int32_t value);
static napi_value CreateStringUtf8(napi_env env, const std::string &str);
static std::string GetStringFromValueUtf8(napi_env env, napi_value value);
static std::string GetStringPropertyUtf8(napi_env env, napi_value object, const std::string &propertyName);
static void SetStringPropertyUtf8(
napi_env env, napi_value object, const std::string &name, const std::string &value);
static std::string GetValueString(napi_env env, napi_value value);
static bool ValueIsArrayBuffer(napi_env env, napi_value value);
static void *GetInfoFromArrayBufferValue(napi_env env, napi_value value, size_t *length);
static napi_value CreateArrayBuffer(napi_env env, size_t length, void **data);
static napi_value CreateObject(napi_env env);
static napi_value GetUndefined(napi_env env);
static napi_value CallFunction(napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value *argv);
static napi_value CreateFunction(napi_env env, const std::string &name, napi_callback func, void *arg);
static napi_ref CreateReference(napi_env env, napi_value callback);
static napi_value GetReference(napi_env env, napi_ref callbackRef);
static void DeleteReference(napi_env env, napi_ref callbackRef);
static bool GetBooleanProperty(napi_env env, napi_value object, const std::string &propertyName);
static void SetBooleanProperty(napi_env env, napi_value object, const std::string &name, bool value);
static void DefineProperties(
napi_env env, napi_value object, const std::initializer_list<napi_property_descriptor> &properties);
static std::string ToLower(const std::string &s);
static std::string GetExtensionId(napi_env env, napi_value *argv);
static std::string GetGlobalId(const std::string &extensionId, const std::string &id);
static std::string GetLocalId(const std::string &extensionId, const std::string &id);
static std::string EncodeExtensionCID(const std::string &extensionId, uint32_t callbackId);
static bool DecodeExtensionCID(const std::string &cid, std::string &extensionId, uint32_t &callbackId);
};
} // namespace OHOS::Print
#endif /* NAPI_PRINT_UTILS_H */

View File

@ -0,0 +1,39 @@
/*
* 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.
*/
#ifndef PRINT_CALLBACK_H
#define PRINT_CALLBACK_H
#include <mutex>
#include "print_callback_stub.h"
#include "napi/native_api.h"
namespace OHOS::Print {
class PrintCallback : public PrintCallbackStub {
public:
PrintCallback(napi_env env, napi_ref ref);
virtual ~PrintCallback();
bool OnCallback() override;
bool OnCallback(uint32_t state, const PrinterInfo &info) override;
bool OnCallback(uint32_t state, const PrintJob &info) override;
bool OnCallback(const std::string &extensionId, const std::string &info) override;
private:
napi_env env_;
napi_ref ref_;
std::mutex mutex_;
};
} // namespace OHOS::Print
#endif // IPRINT_CALLBACK_H

View File

@ -0,0 +1,42 @@
/*
* 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.
*/
#ifndef PRINT_CALLBACK_STUB_H
#define PRINT_CALLBACK_STUB_H
#include <map>
#include "iprint_callback.h"
#include "iremote_stub.h"
namespace OHOS::Print {
class PrintCallbackStub : public IRemoteStub<IPrintCallback> {
public:
PrintCallbackStub();
virtual ~PrintCallbackStub() = default;
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
bool HandlePrintTaskEvent(MessageParcel &data, MessageParcel &reply);
bool HandlePrinterEvent(MessageParcel &data, MessageParcel &reply);
bool HandlePrintJobEvent(MessageParcel &data, MessageParcel &reply);
bool HandleExtEvent(MessageParcel &data, MessageParcel &reply);
private:
using PRINT_EVENT_HANDLER = bool (PrintCallbackStub::*)(MessageParcel &, MessageParcel &);
std::map<uint32_t, PRINT_EVENT_HANDLER> cmdMap_;
};
} // namespace OHOS::Print
#endif // PRINT_CALLBACK_STUB_H

View File

@ -0,0 +1,63 @@
/*
* 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.
*/
#ifndef PRINT_EXTENSION_CALLBACK_STUB_H
#define PRINT_EXTENSION_CALLBACK_STUB_H
#include <memory>
#include "iprint_extension_callback.h"
#include "iremote_stub.h"
#include "print_job.h"
#include "printer_capability.h"
namespace OHOS::Print {
using PrintExtCallback = bool (*)();
using PrintJobCallback = bool (*)(const PrintJob&);
using PrinterCallback = bool (*)(const std::string&);
using PrinterCapabilityCallback = bool (*)(const std::string&, PrinterCapability&);
class PrintExtensionCallbackStub : public IRemoteStub<IPrintExtensionCallback> {
public:
explicit PrintExtensionCallbackStub();
virtual ~PrintExtensionCallbackStub() = default;
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
bool OnCallback() override;
bool OnCallback(const std::string &printerId) override;
bool OnCallback(const PrintJob &job) override;
bool OnCallback(const std::string &printerId, MessageParcel &reply) override;
void SetExtCallback(PrintExtCallback cb);
void SetPrintJobCallback(PrintJobCallback cb);
void SetPrinterCallback(PrinterCallback cb);
void SetCapabilityCallback(PrinterCapabilityCallback cb);
private:
bool HandleExtCallback(MessageParcel &data, MessageParcel &reply);
bool HandlePrinterCallback(MessageParcel &data, MessageParcel &reply);
bool HandlePrintJobCallback(MessageParcel &data, MessageParcel &reply);
bool HandleCapabilityCallback(MessageParcel &data, MessageParcel &reply);
void dataReadJob(MessageParcel &data, PrintJob &job);
private:
using PRINT_EXT_HANDLER = bool (PrintExtensionCallbackStub::*)(MessageParcel &, MessageParcel &);
PrintExtCallback extCb_;
PrintJobCallback jobCb_;
PrinterCallback cb_;
PrinterCapabilityCallback capability_;
std::map<uint32_t, PRINT_EXT_HANDLER> cmdMap_;
};
} // namespace OHOS::Print
#endif // PRINT_EXTCB_STUB_H

View File

@ -0,0 +1,67 @@
/*
* 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.
*/
#ifndef PRINT_EXTENSION_INFO_H
#define PRINT_EXTENSION_INFO_H
#include "parcel.h"
namespace OHOS::Print {
class PrintExtensionInfo final : public Parcelable {
public:
explicit PrintExtensionInfo();
PrintExtensionInfo(const PrintExtensionInfo &right);
~PrintExtensionInfo() = default;
PrintExtensionInfo &operator=(const PrintExtensionInfo &right);
void SetExtensionId(const std::string &extensionId);
void SetVendorId(const std::string &vendorId);
void SetVendorName(const std::string &vendorName);
void SetVendorIcon(uint32_t vendorIcon);
void SetVersion(const std::string &version);
[[nodiscard]] const std::string &GetExtensionId() const;
[[nodiscard]] const std::string &GetVendorId() const;
[[nodiscard]] const std::string &GetVendorName() const;
[[nodiscard]] uint32_t GetVendorIcon() const;
[[nodiscard]] const std::string &GetVersion() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintExtensionInfo> Unmarshalling(Parcel &parcel);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
std::string extensionId_;
std::string vendorId_;
std::string vendorName_;
uint32_t vendorIcon_;
std::string version_;
};
} // namespace OHOS::Print
#endif // PRINT_EXTENSION_INFO_H

View File

@ -0,0 +1,137 @@
/*
* 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.
*/
#ifndef PRINT_PRINT_JOB_H
#define PRINT_PRINT_JOB_H
#include <map>
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "napi/native_api.h"
#include "parcel.h"
#include "print_margin.h"
#include "print_page_size.h"
#include "print_preview_attribute.h"
#include "print_range.h"
namespace OHOS::Print {
class PrintJob final : public Parcelable {
public:
explicit PrintJob();
PrintJob(const PrintJob &right);
PrintJob &operator=(const PrintJob &right);
~PrintJob();
void SetFiles(const std::vector<std::string> &files);
void SetJobId(const std::string &jobId);
void SetPrinterId(const std::string &printerid);
void SetJobState(uint32_t jobState);
void SetSubState(uint32_t jobSubState);
void SetCopyNumber(uint32_t copyNumber);
void SetPageRange(const PrintRange &pageRange);
void SetIsSequential(bool isSequential);
void SetPageSize(const PrintPageSize &pageSize);
void SetIsLandscape(bool isLandscape);
void SetColorMode(uint32_t colorMode);
void SetDuplexMode(uint32_t duplexmode);
void SetMargin(const PrintMargin &margin);
void SetOption(const std::string &option);
void SetPreview(const PrintPreviewAttribute &preview);
void GetFiles(std::vector<std::string> &fileList) const;
[[nodiscard]] const std::string &GetJobId() const;
[[nodiscard]] const std::string &GetPrinterId() const;
[[nodiscard]] uint32_t GetJobState() const;
[[nodiscard]] uint32_t GetSubState() const;
[[nodiscard]] uint32_t GetCopyNumber() const;
void GetPageRange(PrintRange &range) const;
[[nodiscard]] bool GetIsSequential() const;
void GetPageSize(PrintPageSize &printPageSize) const;
[[nodiscard]] bool GetIsLandscape() const;
[[nodiscard]] uint32_t GetColorMode() const;
[[nodiscard]] uint32_t GetDuplexMode() const;
void GetMargin(PrintMargin &printMargin) const;
void GetPreview(PrintPreviewAttribute &previewAttr) const;
[[nodiscard]] const std::string &GetOption() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintJob> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrintJob> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
bool CreateFileList(napi_env env, napi_value &jsPrintJob) const;
bool CreatePageRange(napi_env env, napi_value &jsPrintJob) const;
bool CreatePageSize(napi_env env, napi_value &jsPrintJob) const;
bool CreateMargin(napi_env env, napi_value &jsPrintJob) const;
bool CreatePreview(napi_env env, napi_value &jsPrintJob) const;
bool ParseJob(napi_env env, napi_value jsPrintJob, PrintJob &printJob);
bool ParseJobParam(napi_env env, napi_value jsPrintJob, PrintJob &printJob);
private:
std::vector<std::string> files_;
std::string jobId_;
std::string printerId_;
uint32_t jobState_;
uint32_t subState_;
uint32_t copyNumber_;
PrintRange pageRange_;
bool isSequential_;
PrintPageSize pageSize_;
bool isLandscape_;
int32_t colorMode_;
int32_t duplexMode_;
PrintMargin margin_;
PrintPreviewAttribute preview_;
bool hasOption_;
std::string option_;
};
} // namespace OHOS::Print
#endif /* PRINT_PRINT_JOB_H */

View File

@ -0,0 +1,94 @@
/*
* 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.
*/
#ifndef PRINT_MANAGER_CLIENT_H
#define PRINT_MANAGER_CLIENT_H
#include <condition_variable>
#include <map>
#include <mutex>
#include "iprint_callback.h"
#include "iprint_service.h"
#include "iremote_object.h"
#include "print_extension_callback_stub.h"
#include "print_extension_info.h"
#include "print_job.h"
#include "print_sa_death_recipient.h"
#include "printer_info.h"
#include "refbase.h"
namespace OHOS::Print {
class PrintManagerClient : public RefBase {
public:
PrintManagerClient();
~PrintManagerClient();
static sptr<PrintManagerClient> GetInstance();
void OnRemoteSaDied(const wptr<IRemoteObject> &object);
// Client Napi
int32_t StartPrint(const std::vector<std::string> &fileList, std::string &taskId);
int32_t StopPrint(const std::string &taskId);
int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos);
int32_t StartDiscoverPrinter(const std::vector<std::string> &extensionList);
int32_t StopDiscoverPrinter();
int32_t AddPrinters(const std::vector<PrinterInfo> &printerInfos);
int32_t RemovePrinters(const std::vector<std::string> &printerIds);
int32_t UpdatePrinters(const std::vector<PrinterInfo> &printerInfos);
int32_t ConnectPrinter(const std::string &printerId);
int32_t DisconnectPrinter(const std::string &printerId);
int32_t StartPrintJob(const PrintJob &jobinfo);
int32_t CancelPrintJob(const PrintJob &jobinfo);
int32_t UpdatePrinterState(const std::string &printerId, uint32_t state);
int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState);
int32_t UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo);
int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult);
int32_t QueryPrinterCapability(const std::string &printerId, PrinterCapability &printerCapability);
int32_t On(const std::string &type, const sptr<IPrintCallback> &listener);
int32_t Off(const std::string &type);
int32_t Read(std::vector<uint8_t> &fileRead, const std::string &uri, uint32_t offset, uint32_t max);
int32_t RegisterExtCallback(const std::string &extensionId, uint32_t callbackId, PrintExtCallback cb);
int32_t RegisterExtCallback(const std::string &extensionId, uint32_t callbackId, PrintJobCallback cb);
int32_t RegisterExtCallback(const std::string &extensionId, uint32_t callbackId, PrinterCallback cb);
int32_t RegisterExtCallback(const std::string &extensionId, uint32_t callbackId, PrinterCapabilityCallback cb);
int32_t UnregisterAllExtCallback(const std::string &extensionId);
void LoadServerSuccess();
void LoadServerFail();
private:
bool LoadServer();
sptr<IPrintService> GetPrintServiceProxy();
private:
static std::mutex instanceLock_;
static sptr<PrintManagerClient> instance_;
sptr<IPrintService> printServiceProxy_;
sptr<PrintSaDeathRecipient> deathRecipient_;
std::map<std::string, sptr<PrintExtensionCallbackStub>> extCallbackMap_;
std::mutex loadMutex_;
std::mutex conditionMutex_;
std::condition_variable syncCon_;
bool ready_ = false;
static constexpr int LOAD_SA_TIMEOUT_MS = 15000;
};
} // namespace OHOS::Print
#endif // PRINT_MANAGER_CLIENT_H

View File

@ -0,0 +1,66 @@
/*
* 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.
*/
#ifndef PRINT_MARGIN_H
#define PRINT_MARGIN_H
#include "napi/native_api.h"
#include "parcel.h"
namespace OHOS::Print {
class PrintMargin final : public Parcelable {
public:
explicit PrintMargin();
PrintMargin(const PrintMargin &right);
PrintMargin &operator=(const PrintMargin &right);
~PrintMargin();
void SetTop(uint32_t top);
void SetBottom(uint32_t bottom);
void SetLeft(uint32_t left);
void SetRight(uint32_t right);
[[nodiscard]] uint32_t GetTop() const;
[[nodiscard]] uint32_t GetBottom() const;
[[nodiscard]] uint32_t GetLeft() const;
[[nodiscard]] uint32_t GetRight() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintMargin> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrintMargin> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
uint32_t top_;
uint32_t bottom_;
uint32_t left_;
uint32_t right_;
};
} // namespace OHOS::Print
#endif // PRINT_MARGIN_H

View File

@ -0,0 +1,35 @@
/*
* 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.
*/
#ifndef PRINT_NOTIFY_H
#define PRINT_NOTIFY_H
#include <string>
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_callback_stub.h"
namespace OHOS::Print {
class PrintNotify final : public PrintCallbackStub {
public:
ACE_DISALLOW_COPY_AND_MOVE(PrintNotify);
explicit PrintNotify();
virtual ~PrintNotify();
void OnCallBack(MessageParcel &data) override;
};
} // namespace OHOS::Print
#endif // PRINT_NOTIFY_H

View File

@ -0,0 +1,254 @@
/*
* 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.
*/
#ifndef PRINT_PAGESIZE_H
#define PRINT_PAGESIZE_H
#include <map>
#include "napi/native_api.h"
#include "parcel.h"
namespace OHOS::Print {
enum PageSizeId {
ISO_A0,
ISO_A1,
ISO_A2,
ISO_A3,
ISO_A4,
ISO_A5,
ISO_A6,
ISO_A7,
ISO_A8,
ISO_A9,
ISO_A10,
ISO_B0,
ISO_B1,
ISO_B2,
ISO_B3,
ISO_B4,
ISO_B5,
ISO_B6,
ISO_B7,
ISO_B8,
ISO_B9,
ISO_B10,
ISO_C0,
ISO_C1,
ISO_C2,
ISO_C3,
ISO_C4,
ISO_C5,
ISO_C6,
ISO_C7,
ISO_C8,
ISO_C9,
ISO_C10,
NA_LETTER,
NA_GOVT_LETTER,
NA_LEGAL,
NA_JUNIOR_LEGAL,
NA_LEDGER,
NA_TABLOID,
NA_INDEX_3X5,
NA_INDEX_4X6,
NA_INDEX_5X8,
NA_MONARCH,
NA_QUARTO,
NA_FOOLSCAP,
ROC_8K,
ROC_16K,
PRC_1,
PRC_2,
PRC_3,
PRC_4,
PRC_5,
PRC_6,
PRC_7,
PRC_8,
PRC_9,
PRC_10,
PRC_16K,
OM_PA_KAI,
OM_DAI_PA_KAI,
OM_JUURO_KU_KAI,
JIS_B10,
JIS_B9,
JIS_B8,
JIS_B7,
JIS_B6,
JIS_B5,
JIS_B4,
JIS_B3,
JIS_B2,
JIS_B1,
JIS_B0,
JIS_EXEC,
JPN_CHOU4,
JPN_CHOU3,
JPN_CHOU2,
JPN_HAGAKI,
JPN_OUFUKU,
JPN_KAHU,
JPN_KAKU2,
JPN_YOU4,
};
const std::string PAGE_SIZE_TABLE[] = {
"ISO_A0",
"ISO_A1",
"ISO_A2",
"ISO_A3",
"ISO_A4",
"ISO_A5",
"ISO_A6",
"ISO_A7",
"ISO_A8",
"ISO_A9",
"ISO_A10",
"ISO_B0",
"ISO_B1",
"ISO_B2",
"ISO_B3",
"ISO_B4",
"ISO_B5",
"ISO_B6",
"ISO_B7",
"ISO_B8",
"ISO_B9",
"ISO_B10",
"ISO_C0",
"ISO_C1",
"ISO_C2",
"ISO_C3",
"ISO_C4",
"ISO_C5",
"ISO_C6",
"ISO_C7",
"ISO_C8",
"ISO_C9",
"ISO_C10",
"NA_LETTER",
"NA_GOVT_LETTER",
"NA_LEGAL",
"NA_JUNIOR_LEGAL",
"NA_LEDGER",
"NA_TABLOID",
"NA_INDEX_3X5",
"NA_INDEX_4X6",
"NA_INDEX_5X8",
"NA_MONARCH",
"NA_QUARTO",
"NA_FOOLSCAP",
"ROC_8K",
"ROC_16K",
"PRC_1",
"PRC_2",
"PRC_3",
"PRC_4",
"PRC_5",
"PRC_6",
"PRC_7",
"PRC_8",
"PRC_9",
"PRC_10",
"PRC_16K",
"OM_PA_KAI",
"OM_DAI_PA_KAI",
"OM_JUURO_KU_KAI",
"JIS_B10",
"JIS_B9",
"JIS_B8",
"JIS_B7",
"JIS_B6",
"JIS_B5",
"JIS_B4",
"JIS_B3",
"JIS_B2",
"JIS_B1",
"JIS_B0",
"JIS_EXEC",
"JPN_CHOU4",
"JPN_CHOU3",
"JPN_CHOU2",
"JPN_HAGAKI",
"JPN_OUFUKU",
"JPN_KAHU",
"JPN_KAKU2",
"JPN_YOU4",
};
using DiscreteId = std::string;
using DiscretePageName = std::string;
using PAGE_SIZE_ID = std::string;
class PrintPageSize final : public Parcelable {
public:
static void BuildPageSizeMap();
static PrintPageSize GetPageSize(PageSizeId id);
explicit PrintPageSize();
PrintPageSize(PAGE_SIZE_ID id, DiscretePageName name, uint32_t width, uint32_t height);
PrintPageSize(const PrintPageSize &right);
PrintPageSize &operator=(const PrintPageSize &right);
~PrintPageSize();
void SetId(const std::string &id);
void SetName(const std::string &name);
void SetWidth(uint32_t width);
void SetHeight(uint32_t height);
[[nodiscard]] const std::string &GetId() const;
[[nodiscard]] const std::string &GetName() const;
[[nodiscard]] uint32_t GetWidth() const;
[[nodiscard]] uint32_t GetHeight() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintPageSize> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrintPageSize> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
std::string id_;
std::string name_;
uint32_t width_;
uint32_t height_;
static std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> pageSize_;
};
} // namespace OHOS::Print
#endif // PRINT_PAGESIZE_H

View File

@ -0,0 +1,56 @@
/*
* 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.
*/
#ifndef PRINT_PREVIEW_ATTRIBUTE_H
#define PRINT_PREVIEW_ATTRIBUTE_H
#include "napi/native_api.h"
#include "parcel.h"
#include "print_range.h"
namespace OHOS::Print {
class PrintPreviewAttribute final : public Parcelable {
public:
explicit PrintPreviewAttribute();
PrintPreviewAttribute(const PrintPreviewAttribute &right);
PrintPreviewAttribute &operator=(const PrintPreviewAttribute &PrintPreviewAttribute);
~PrintPreviewAttribute();
void SetResult(const std::string &result);
void SetPreviewRange(const PrintRange &previewRange);
[[nodiscard]] const std::string &GetResult() const;
void GetPreviewRange(PrintRange &previewRange) const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintPreviewAttribute> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrintPreviewAttribute> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
std::string result_;
PrintRange previewRange_;
};
} // namespace OHOS::Print
#endif // PRINT_PREVIEW_ATTRIBUTE_H

View File

@ -0,0 +1,63 @@
/*
* 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.
*/
#ifndef PRINT_RANGE_H
#define PRINT_RANGE_H
#include "napi/native_api.h"
#include "parcel.h"
namespace OHOS::Print {
class PrintRange final : public Parcelable {
public:
explicit PrintRange();
PrintRange(const PrintRange &right);
PrintRange &operator=(const PrintRange &right);
~PrintRange();
void SetStartPage(uint32_t startPage);
void SetEndPage(uint32_t endPage);
void SetPages(const std::vector<uint32_t> &pages);
void Reset();
[[nodiscard]] uint32_t GetStartPage() const;
[[nodiscard]] uint32_t GetEndPage() const;
void GetPages(std::vector<uint32_t> &pages) const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintRange> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrintRange> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
uint32_t startPage_;
uint32_t endPage_;
std::vector<uint32_t> pages_;
};
} // namespace OHOS::Print
#endif // PRINT_RANGE_H

View File

@ -0,0 +1,61 @@
/*
* 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.
*/
#ifndef PRINT_RESOLUTION_H
#define PRINT_RESOLUTION_H
#include "napi/native_api.h"
#include "parcel.h"
namespace OHOS::Print {
class PrintResolution final : public Parcelable {
public:
explicit PrintResolution();
PrintResolution(const PrintResolution &right);
PrintResolution &operator=(const PrintResolution &right);
~PrintResolution();
void SetId(const std::string &id);
void SetHorizontalDpi(uint32_t horizontalDpi);
void SetVerticalDpi(uint32_t verticalDpi);
[[nodiscard]] const std::string &GetId() const;
[[nodiscard]] uint32_t GetHorizontalDpi() const;
[[nodiscard]] uint32_t GetVerticalDpi() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrintResolution> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrintResolution> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
std::string id_;
uint32_t horizontalDpi_;
uint32_t verticalDpi_;
};
} // namespace OHOS::Print
#endif // PRINT_RESOLUTION_H

View File

@ -0,0 +1,30 @@
/*
* 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.
*/
#ifndef PRINT_SA_DEATH_RECIPIENT_H
#define PRINT_SA_DEATH_RECIPIENT_H
#include "iremote_object.h"
#include "refbase.h"
namespace OHOS::Print {
class PrintSaDeathRecipient : public IRemoteObject::DeathRecipient {
public:
explicit PrintSaDeathRecipient();
~PrintSaDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
};
} // namespace OHOS::Print
#endif // PRINT_SA_DEATH_RECIPIENT_H

View File

@ -0,0 +1,56 @@
/*
* 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.
*/
#ifndef PRINT_SERVICE_PROXY_H
#define PRINT_SERVICE_PROXY_H
#include "iprint_service.h"
#include "iremote_proxy.h"
namespace OHOS::Print {
class PrintServiceProxy : public IRemoteProxy<IPrintService> {
public:
explicit PrintServiceProxy(const sptr<IRemoteObject> &object);
~PrintServiceProxy() = default;
DISALLOW_COPY_AND_MOVE(PrintServiceProxy);
int32_t StartPrint(const std::vector<std::string> &fileList, std::string &taskId) override;
int32_t StopPrint(const std::string &taskId) override;
int32_t ConnectPrinter(const std::string &printerId) override;
int32_t DisconnectPrinter(const std::string &printerId) override;
int32_t StartDiscoverPrinter(const std::vector<std::string> &extensionList) override;
int32_t StopDiscoverPrinter() override;
int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos) override;
int32_t StartPrintJob(const PrintJob &jobinfo) override;
int32_t CancelPrintJob(const PrintJob &jobinfo) override;
int32_t AddPrinters(const std::vector<PrinterInfo> &printerInfos) override;
int32_t RemovePrinters(const std::vector<std::string> &printerIds) override;
int32_t UpdatePrinters(const std::vector<PrinterInfo> &printerInfos) override;
int32_t UpdatePrinterState(const std::string &printerId, uint32_t state) override;
int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) override;
int32_t UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo) override;
int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult) override;
int32_t QueryPrinterCapability(const std::string &printerId, PrinterCapability &printerCapability) override;
int32_t On(const std::string &type, const sptr<IPrintCallback> &listener) override;
int32_t Off(const std::string &type) override;
int32_t RegisterExtCallback(const std::string extensionCID,
const sptr<IPrintExtensionCallback> &listener) override;
int32_t UnregisterAllExtCallback(const std::string &extensionId) override;
int32_t Read(std::vector<uint8_t> &fileRead, const std::string &uri, uint32_t offset, uint32_t max) override;
private:
static inline BrokerDelegator<PrintServiceProxy> delegator_;
};
} // namespace OHOS::Print
#endif // PRINT_SERVICE_PROXY_H

View File

@ -0,0 +1,28 @@
/*
* 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.
*/
#ifndef PRINT_SYNC_LOAD_CALLBACK_H
#define PRINT_SYNC_LOAD_CALLBACK_H
#include "system_ability_load_callback_stub.h"
namespace OHOS::Print {
class PrintSyncLoadCallback : public SystemAbilityLoadCallbackStub {
public:
void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject> &remoteObject) override;
void OnLoadSystemAbilityFail(int32_t systemAbilityId) override;
};
} // namespace OHOS::Print
#endif // PRINT_SYNC_LOAD_CALLBACK_H

View File

@ -0,0 +1,79 @@
/*
* 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.
*/
#ifndef PRINTER_CAPABILITY_H
#define PRINTER_CAPABILITY_H
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "napi/native_api.h"
#include "parcel.h"
#include "print_margin.h"
#include "print_page_size.h"
#include "print_resolution.h"
namespace OHOS::Print {
class PrinterCapability final : public Parcelable {
public:
explicit PrinterCapability();
PrinterCapability(const PrinterCapability &right);
PrinterCapability &operator=(const PrinterCapability &right);
~PrinterCapability();
void SetMinMargin(const PrintMargin &minMargin);
void SetPageSize(const std::vector<PrintPageSize> &pageSizeList);
void SetResolution(const std::vector<PrintResolution> &resolutionList);
void SetColorMode(uint32_t colorMode);
void SetDuplexMode(uint32_t duplexMode);
void GetMinMargin(PrintMargin &margin) const;
void GetPageSize(std::vector<PrintPageSize> &pageSizeList) const;
void GetResolution(std::vector<PrintResolution> &resolutionList) const;
[[nodiscard]] uint32_t GetColorMode() const;
[[nodiscard]] uint32_t GetDuplexMode() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrinterCapability> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrinterCapability> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
bool CreatePageSizeList(napi_env env, napi_value &jsPrinterCap) const;
bool CreateResolutionList(napi_env env, napi_value &jsPrinterCap) const;
private:
PrintMargin minMargin_;
std::vector<PrintPageSize> pageSizeList_;
std::vector<PrintResolution> resolutionList_;
uint32_t colorMode_;
uint32_t duplexMode_;
};
} // namespace OHOS::Print
#endif // PRINTER_CAPABILITY_H

View File

@ -0,0 +1,88 @@
/*
* 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.
*/
#ifndef PRINTER_INFO_H
#define PRINTER_INFO_H
#include "napi/native_api.h"
#include "parcel.h"
#include "printer_capability.h"
namespace OHOS::Print {
class PrinterInfo final : public Parcelable {
public:
explicit PrinterInfo();
PrinterInfo(const PrinterInfo &right);
PrinterInfo &operator=(const PrinterInfo &PrinterInfo);
~PrinterInfo();
void SetPrinterId(const std::string &printerId);
void SetPrinterName(std::string printerName);
void SetPrinterIcon(uint32_t printIcon);
void SetPrinterState(uint32_t printerState);
void SetDescription(std::string description);
void SetCapability(PrinterCapability capability);
void SetOption(const std::string &option);
[[nodiscard]] const std::string &GetPrinterId() const;
[[nodiscard]] const std::string &GetPrinterName() const;
[[nodiscard]] uint32_t GetPrinterIcon() const;
[[nodiscard]] uint32_t GetPrinterState() const;
[[nodiscard]] const std::string &GetDescription() const;
void GetCapability(PrinterCapability &cap) const;
[[nodiscard]] std::string GetOption() const;
virtual bool Marshalling(Parcel &parcel) const override;
static std::shared_ptr<PrinterInfo> Unmarshalling(Parcel &parcel);
napi_value ToJsObject(napi_env env) const;
static std::shared_ptr<PrinterInfo> BuildFromJs(napi_env env, napi_value jsValue);
void Dump();
private:
bool ReadFromParcel(Parcel &parcel);
private:
std::string printerId_;
std::string printerName_;
uint32_t printerIcon_;
uint32_t printerState_;
std::string description_;
std::shared_ptr<PrinterCapability> capability_;
std::string option_;
};
} // namespace OHOS::Print
#endif // PRINTER_INFO_H

View File

@ -0,0 +1,380 @@
/*
* 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.
*/
#include "napi_print_utils.h"
#include "ability.h"
#include "napi_base_context.h"
#include "print_log.h"
#include "securec.h"
namespace OHOS::Print {
static constexpr const int MAX_STRING_LENGTH = 65536;
const std::string EXTENSION_ID_DELIMITER = ":";
napi_valuetype NapiPrintUtils::GetValueType(napi_env env, napi_value value)
{
if (value == nullptr) {
return napi_undefined;
}
napi_valuetype valueType = napi_undefined;
NAPI_CALL_BASE(env, napi_typeof(env, value, &valueType), napi_undefined);
return valueType;
}
/* named property */
bool NapiPrintUtils::HasNamedProperty(napi_env env, napi_value object, const std::string &propertyName)
{
bool hasProperty = false;
NAPI_CALL_BASE(env, napi_has_named_property(env, object, propertyName.c_str(), &hasProperty), false);
return hasProperty;
}
napi_value NapiPrintUtils::GetNamedProperty(napi_env env, napi_value object, const std::string &propertyName)
{
napi_value value = nullptr;
bool hasProperty = false;
NAPI_CALL(env, napi_has_named_property(env, object, propertyName.c_str(), &hasProperty));
if (!hasProperty) {
return value;
}
NAPI_CALL(env, napi_get_named_property(env, object, propertyName.c_str(), &value));
return value;
}
void NapiPrintUtils::SetNamedProperty(napi_env env, napi_value object, const std::string &name, napi_value value)
{
(void)napi_set_named_property(env, object, name.c_str(), value);
}
std::vector<std::string> NapiPrintUtils::GetPropertyNames(napi_env env, napi_value object)
{
std::vector<std::string> ret;
napi_value names = nullptr;
NAPI_CALL_BASE(env, napi_get_property_names(env, object, &names), ret);
uint32_t length = 0;
NAPI_CALL_BASE(env, napi_get_array_length(env, names, &length), ret);
for (uint32_t index = 0; index < length; ++index) {
napi_value name = nullptr;
if (napi_get_element(env, names, index, &name) != napi_ok) {
continue;
}
if (GetValueType(env, name) != napi_string) {
continue;
}
ret.emplace_back(GetStringFromValueUtf8(env, name));
}
return ret;
}
/* UINT32 */
napi_value NapiPrintUtils::CreateUint32(napi_env env, uint32_t code)
{
napi_value value = nullptr;
if (napi_create_uint32(env, code, &value) != napi_ok) {
return nullptr;
}
return value;
}
uint32_t NapiPrintUtils::GetUint32FromValue(napi_env env, napi_value value)
{
uint32_t ret = 0;
NAPI_CALL_BASE(env, napi_get_value_uint32(env, value, &ret), 0);
return ret;
}
uint32_t NapiPrintUtils::GetUint32Property(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return 0;
}
napi_value value = GetNamedProperty(env, object, propertyName);
return GetUint32FromValue(env, value);
}
void NapiPrintUtils::SetUint32Property(napi_env env, napi_value object, const std::string &name, uint32_t value)
{
napi_value jsValue = CreateUint32(env, value);
if (GetValueType(env, jsValue) != napi_number) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* INT32 */
napi_value NapiPrintUtils::CreateInt32(napi_env env, int32_t code)
{
napi_value value = nullptr;
if (napi_create_int32(env, code, &value) != napi_ok) {
return nullptr;
}
return value;
}
int32_t NapiPrintUtils::GetInt32FromValue(napi_env env, napi_value value)
{
int32_t ret = 0;
NAPI_CALL_BASE(env, napi_get_value_int32(env, value, &ret), 0);
return ret;
}
int32_t NapiPrintUtils::GetInt32Property(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return 0;
}
napi_value value = GetNamedProperty(env, object, propertyName);
return GetInt32FromValue(env, value);
}
void NapiPrintUtils::SetInt32Property(napi_env env, napi_value object, const std::string &name, int32_t value)
{
napi_value jsValue = CreateInt32(env, value);
if (GetValueType(env, jsValue) != napi_number) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* String UTF8 */
napi_value NapiPrintUtils::CreateStringUtf8(napi_env env, const std::string &str)
{
napi_value value = nullptr;
if (napi_create_string_utf8(env, str.c_str(), strlen(str.c_str()), &value) != napi_ok) {
return nullptr;
}
return value;
}
std::string NapiPrintUtils::GetStringFromValueUtf8(napi_env env, napi_value value)
{
std::string result;
std::vector<char> str(MAX_STRING_LENGTH + 1, '\0');
size_t length = 0;
NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, value, &str[0], MAX_STRING_LENGTH, &length), result);
if (length > 0) {
return result.append(&str[0], length);
}
return result;
}
std::string NapiPrintUtils::GetStringPropertyUtf8(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return "";
}
napi_value value = GetNamedProperty(env, object, propertyName);
return GetStringFromValueUtf8(env, value);
}
void NapiPrintUtils::SetStringPropertyUtf8(
napi_env env, napi_value object, const std::string &name, const std::string &value)
{
napi_value jsValue = CreateStringUtf8(env, value);
if (GetValueType(env, jsValue) != napi_string) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* array buffer */
napi_value NapiPrintUtils::CreateArrayBuffer(napi_env env, size_t length, void **data)
{
napi_value object = nullptr;
NAPI_CALL(env, napi_create_arraybuffer(env, length, data, &object));
return object;
}
bool NapiPrintUtils::ValueIsArrayBuffer(napi_env env, napi_value value)
{
bool isArrayBuffer = false;
NAPI_CALL_BASE(env, napi_is_arraybuffer(env, value, &isArrayBuffer), false);
return isArrayBuffer;
}
void *NapiPrintUtils::GetInfoFromArrayBufferValue(napi_env env, napi_value value, size_t *length)
{
if (length == nullptr) {
return nullptr;
}
void *data = nullptr;
NAPI_CALL(env, napi_get_arraybuffer_info(env, value, &data, length));
return data;
}
/* object */
napi_value NapiPrintUtils::CreateObject(napi_env env)
{
napi_value object = nullptr;
NAPI_CALL(env, napi_create_object(env, &object));
return object;
}
/* undefined */
napi_value NapiPrintUtils::GetUndefined(napi_env env)
{
napi_value undefined = nullptr;
NAPI_CALL(env, napi_get_undefined(env, &undefined));
return undefined;
}
/* function */
napi_value NapiPrintUtils::CallFunction(
napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value *argv)
{
napi_value res = nullptr;
NAPI_CALL(env, napi_call_function(env, recv, func, argc, argv, &res));
return res;
}
/* reference */
napi_ref NapiPrintUtils::CreateReference(napi_env env, napi_value callback)
{
napi_ref callbackRef = nullptr;
NAPI_CALL(env, napi_create_reference(env, callback, 1, &callbackRef));
return callbackRef;
}
napi_value NapiPrintUtils::GetReference(napi_env env, napi_ref callbackRef)
{
napi_value callback = nullptr;
NAPI_CALL(env, napi_get_reference_value(env, callbackRef, &callback));
return callback;
}
void NapiPrintUtils::DeleteReference(napi_env env, napi_ref callbackRef)
{
(void)napi_delete_reference(env, callbackRef);
}
/* boolean */
bool NapiPrintUtils::GetBooleanProperty(napi_env env, napi_value object, const std::string &propertyName)
{
if (!HasNamedProperty(env, object, propertyName)) {
return false;
}
napi_value value = GetNamedProperty(env, object, propertyName);
bool ret = false;
NAPI_CALL_BASE(env, napi_get_value_bool(env, value, &ret), false);
return ret;
}
void NapiPrintUtils::SetBooleanProperty(napi_env env, napi_value object, const std::string &name, bool value)
{
napi_value jsValue = nullptr;
NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, value, &jsValue));
if (GetValueType(env, jsValue) != napi_boolean) {
return;
}
napi_set_named_property(env, object, name.c_str(), jsValue);
}
/* define properties */
void NapiPrintUtils::DefineProperties(
napi_env env, napi_value object, const std::initializer_list<napi_property_descriptor> &properties)
{
napi_property_descriptor descriptors[properties.size()];
std::copy(properties.begin(), properties.end(), descriptors);
(void)napi_define_properties(env, object, properties.size(), descriptors);
}
std::string NapiPrintUtils::ToLower(const std::string &s)
{
std::string res = s;
std::transform(res.begin(), res.end(), res.begin(), tolower);
return res;
}
std::string NapiPrintUtils::GetValueString(napi_env env, napi_value value)
{
std::string resultValue = "";
char value_string[256];
size_t value_size = 256;
size_t result;
napi_get_value_string_utf8(env, value, value_string, value_size, &result);
resultValue = value_string;
return resultValue;
}
std::string NapiPrintUtils::GetExtensionId(napi_env env, napi_value *argv)
{
std::string defaultExtId = "com.open.harmony.packagemag";
if (argv == nullptr) {
return defaultExtId;
}
bool stageMode = false;
std::shared_ptr<OHOS::AbilityRuntime::Context> context = nullptr;
napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[0], stageMode);
PRINT_HILOGE("status = %{public}d, stageMode = %{public}d", status == napi_ok, stageMode);
if (status != napi_ok || !stageMode) {
auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env);
if (ability == nullptr) {
PRINT_HILOGE("GetCurrentAbility ability == nullptr.");
return defaultExtId;
}
context = ability->GetAbilityContext();
} else {
context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[0]);
if (context == nullptr) {
PRINT_HILOGE("GetStageModeContext contextRtm == nullptr.");
return defaultExtId;
}
}
if (context == nullptr) {
PRINT_HILOGE("GetContext failed. context is nullptr.");
return defaultExtId;
}
return context->GetBundleName();
}
std::string NapiPrintUtils::GetGlobalId(const std::string &extensionId, const std::string &id)
{
return extensionId + EXTENSION_ID_DELIMITER + id;
}
std::string NapiPrintUtils::GetLocalId(const std::string &extensionId, const std::string &id)
{
auto pos1 = id.find(extensionId);
auto pos2 = id.find(EXTENSION_ID_DELIMITER);
if (pos1 == std::string::npos || pos2 == std::string::npos) {
return "";
}
return id.substr(pos2 + 1);
}
std::string NapiPrintUtils::EncodeExtensionCID(const std::string &extensionId, uint32_t callbackId)
{
return extensionId + EXTENSION_ID_DELIMITER + std::to_string(callbackId);
}
bool NapiPrintUtils::DecodeExtensionCID(const std::string &cid, std::string &extensionId, uint32_t &callbackId)
{
auto pos = cid.find(EXTENSION_ID_DELIMITER);
if (pos == std::string::npos) {
return false;
}
extensionId = cid.substr(0, pos - 1);
callbackId = atoi(cid.substr(pos + 1).c_str());
return true;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,253 @@
/*
* 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.
*/
#include "print_callback.h"
#include <uv.h>
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
struct CallbackParam {
napi_env env;
napi_ref ref;
std::mutex* mutexPtr;
uint32_t state;
PrinterInfo printerInfo;
PrintJob jobInfo;
std::string extensionId;
std::string info;
};
PrintCallback::PrintCallback(napi_env env, napi_ref ref) : env_(env), ref_(ref)
{
}
PrintCallback::~PrintCallback()
{
std::lock_guard<std::mutex> autoLock(mutex_);
PRINT_HILOGD("callback has been destroyed");
NapiPrintUtils::DeleteReference(env_, ref_);
ref_ = nullptr;
}
bool PrintCallback::OnCallback()
{
PRINT_HILOGD("Print Task 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 false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return false;
}
CallbackParam *param = new (std::nothrow) CallbackParam;
if (param == nullptr) {
PRINT_HILOGE("Failed to create callback parameter");
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
param->env = env_;
param->ref = ref_;
param->mutexPtr = &mutex_;
}
work->data = param;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
CallbackParam *cbParam = static_cast<CallbackParam*>(work->data);
if (cbParam != nullptr) {
std::lock_guard<std::mutex> autoLock(*cbParam->mutexPtr);
napi_value callbackFunc = NapiPrintUtils::GetReference(cbParam->env, cbParam->ref);
napi_value callbackResult = nullptr;
napi_value callbackValues[NapiPrintUtils::ARGC_ONE] = { 0 };
callbackValues[NapiPrintUtils::ARGC_ZERO] = NapiPrintUtils::GetUndefined(cbParam->env);
napi_call_function(cbParam->env, nullptr, callbackFunc, NapiPrintUtils::ARGC_ZERO,
callbackValues, &callbackResult);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete cbParam;
cbParam = nullptr;
}
});
return true;
}
bool PrintCallback::OnCallback(uint32_t state, const PrinterInfo &info)
{
PRINT_HILOGD("Print Task 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 false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return false;
}
CallbackParam *param = new (std::nothrow) CallbackParam;
if (param == nullptr) {
PRINT_HILOGE("Failed to create callback parameter");
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
param->env = env_;
param->ref = ref_;
param->mutexPtr = &mutex_;
param->state = state;
param->printerInfo = info;
}
work->data = param;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
CallbackParam *cbParam = static_cast<CallbackParam*>(work->data);
if (cbParam != nullptr) {
std::lock_guard<std::mutex> autoLock(*cbParam->mutexPtr);
napi_value callbackFunc = NapiPrintUtils::GetReference(cbParam->env, cbParam->ref);
napi_value callbackResult = nullptr;
napi_value callbackValues[NapiPrintUtils::ARGC_TWO] = { 0 };
callbackValues[NapiPrintUtils::INDEX_ZERO] = NapiPrintUtils::CreateUint32(cbParam->env, cbParam->state);
callbackValues[NapiPrintUtils::INDEX_ONE] = cbParam->printerInfo.ToJsObject(cbParam->env);
napi_call_function(cbParam->env, nullptr, callbackFunc, NapiPrintUtils::ARGC_TWO,
callbackValues, &callbackResult);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete cbParam;
cbParam = nullptr;
}
});
return true;
}
bool PrintCallback::OnCallback(uint32_t state, const PrintJob &info)
{
PRINT_HILOGD("Print Task 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 false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return false;
}
CallbackParam *param = new (std::nothrow) CallbackParam;
if (param == nullptr) {
PRINT_HILOGE("Failed to create callback parameter");
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
param->env = env_;
param->ref = ref_;
param->mutexPtr = &mutex_;
param->state = state;
param->jobInfo = info;
}
work->data = param;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
CallbackParam *cbParam = static_cast<CallbackParam*>(work->data);
if (cbParam != nullptr) {
std::lock_guard<std::mutex> autoLock(*cbParam->mutexPtr);
napi_value callbackFunc = NapiPrintUtils::GetReference(cbParam->env, cbParam->ref);
napi_value callbackResult = nullptr;
napi_value callbackValues[NapiPrintUtils::ARGC_TWO] = { 0 };
callbackValues[NapiPrintUtils::INDEX_ZERO] = NapiPrintUtils::CreateUint32(cbParam->env, cbParam->state);
callbackValues[NapiPrintUtils::INDEX_ONE] = cbParam->jobInfo.ToJsObject(cbParam->env);
napi_call_function(cbParam->env, nullptr, callbackFunc, NapiPrintUtils::ARGC_TWO,
callbackValues, &callbackResult);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete cbParam;
cbParam = nullptr;
}
});
return true;
}
bool PrintCallback::OnCallback(const std::string &extensionId, const std::string &info)
{
PRINT_HILOGD("Ext Info 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 false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return false;
}
CallbackParam *param = new (std::nothrow) CallbackParam;
if (param == nullptr) {
PRINT_HILOGE("Failed to create callback parameter");
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
param->env = env_;
param->ref = ref_;
param->mutexPtr = &mutex_;
param->extensionId = extensionId;
param->info = info;
}
work->data = param;
uv_queue_work(
loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int statusInt) {
CallbackParam *cbParam = static_cast<CallbackParam*>(work->data);
if (cbParam != nullptr) {
std::lock_guard<std::mutex> autoLock(*cbParam->mutexPtr);
napi_value callbackFunc = NapiPrintUtils::GetReference(cbParam->env, cbParam->ref);
napi_value callbackResult = nullptr;
napi_value callbackValues[NapiPrintUtils::ARGC_TWO] = { 0 };
callbackValues[NapiPrintUtils::INDEX_ZERO] =
NapiPrintUtils::CreateStringUtf8(cbParam->env, cbParam->extensionId);
callbackValues[NapiPrintUtils::INDEX_ONE] =
NapiPrintUtils::CreateStringUtf8(cbParam->env, cbParam->info);
napi_call_function(cbParam->env, nullptr, callbackFunc, NapiPrintUtils::ARGC_TWO,
callbackValues, &callbackResult);
if (work != nullptr) {
delete work;
work = nullptr;
}
delete cbParam;
cbParam = nullptr;
}
});
return true;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,93 @@
/*
* 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.
*/
#include "print_callback_stub.h"
#include "print_constant.h"
#include "print_log.h"
namespace OHOS::Print {
PrintCallbackStub::PrintCallbackStub()
{
cmdMap_[PRINT_CALLBACK_TASK] = &PrintCallbackStub::HandlePrintTaskEvent;
cmdMap_[PRINT_CALLBACK_PRINTER] = &PrintCallbackStub::HandlePrinterEvent;
cmdMap_[PRINT_CALLBACK_PRINT_JOB] = &PrintCallbackStub::HandlePrintJobEvent;
cmdMap_[PRINT_CALLBACK_EXTINFO] = &PrintCallbackStub::HandleExtEvent;
}
int32_t PrintCallbackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
PRINT_HILOGD("OnRemoteRequest started, code = %{public}d", code);
auto descriptorToken = data.ReadInterfaceToken();
if (descriptorToken != GetDescriptor()) {
PRINT_HILOGE("Remote descriptor not the same as local descriptor.");
return ERROR_RPC_FAIL;
}
auto itFunc = cmdMap_.find(code);
if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second;
if (requestFunc != nullptr) {
return (this->*requestFunc)(data, reply);
}
}
PRINT_HILOGW("default case, need check.");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
bool PrintCallbackStub::HandlePrintTaskEvent(MessageParcel &data, MessageParcel &reply)
{
bool result = OnCallback();
reply.WriteBool(result);
return true;
}
bool PrintCallbackStub::HandlePrinterEvent(MessageParcel &data, MessageParcel &reply)
{
uint32_t state = data.ReadUint32();
auto info = PrinterInfo::Unmarshalling(data);
if (info == nullptr) {
PRINT_HILOGE("invalid printer info object");
return false;
}
bool result = OnCallback(state, *info);
reply.WriteBool(result);
return true;
}
bool PrintCallbackStub::HandlePrintJobEvent(MessageParcel &data, MessageParcel &reply)
{
uint32_t state = data.ReadUint32();
auto info = PrintJob::Unmarshalling(data);
if (info == nullptr) {
PRINT_HILOGE("invalid print job object");
return false;
}
bool result = OnCallback(state, *info);
reply.WriteBool(result);
return true;
}
bool PrintCallbackStub::HandleExtEvent(MessageParcel &data, MessageParcel &reply)
{
std::string extensionId = data.ReadString();
std::string info = data.ReadString();
bool result = OnCallback(extensionId, info);
reply.WriteBool(result);
return true;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,154 @@
/*
* 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.
*/
#include "print_extension_callback_stub.h"
#include "print_constant.h"
#include "print_log.h"
#include "print_resolution.h"
namespace OHOS::Print {
PrintExtensionCallbackStub::PrintExtensionCallbackStub() : extCb_(nullptr), jobCb_(nullptr), cb_(nullptr)
{
cmdMap_[PRINT_EXTCB] = &PrintExtensionCallbackStub::HandleExtCallback;
cmdMap_[PRINT_EXTCB_PRINTER] = &PrintExtensionCallbackStub::HandlePrinterCallback;
cmdMap_[PRINT_EXTCB_PRINTJOB] = &PrintExtensionCallbackStub::HandlePrintJobCallback;
cmdMap_[PRINT_EXTCB_PRINTCAPABILITY] = &PrintExtensionCallbackStub::HandleCapabilityCallback;
}
int32_t PrintExtensionCallbackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
PRINT_HILOGD("OnRemoteRequest started, code = %{public}d", code);
auto descriptorToken = data.ReadInterfaceToken();
if (descriptorToken != GetDescriptor()) {
PRINT_HILOGE("Remote descriptor not the same as local descriptor.");
return ERROR_RPC_FAIL;
}
auto itFunc = cmdMap_.find(code);
if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second;
if (requestFunc != nullptr) {
return (this->*requestFunc)(data, reply);
}
}
PRINT_HILOGW("default case, need check.");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
bool PrintExtensionCallbackStub::OnCallback()
{
if (extCb_ != nullptr) {
return extCb_();
}
return false;
}
bool PrintExtensionCallbackStub::OnCallback(const std::string &printerId)
{
if (cb_ != nullptr) {
return cb_(printerId);
}
return false;
}
bool PrintExtensionCallbackStub::OnCallback(const PrintJob &job)
{
if (jobCb_ != nullptr) {
return jobCb_(job);
}
return false;
}
bool PrintExtensionCallbackStub::OnCallback(const std::string &printerId, MessageParcel &reply)
{
if (capability_ != nullptr) {
PrinterCapability capability;
if (capability_(printerId, capability)) {
capability.Marshalling(reply);
return true;
}
}
return false;
}
void PrintExtensionCallbackStub::SetExtCallback(PrintExtCallback cb)
{
extCb_ = cb;
}
void PrintExtensionCallbackStub::SetPrintJobCallback(PrintJobCallback cb)
{
jobCb_ = cb;
}
void PrintExtensionCallbackStub::SetPrinterCallback(PrinterCallback cb)
{
cb_ = cb;
}
void PrintExtensionCallbackStub::SetCapabilityCallback(PrinterCapabilityCallback cb)
{
capability_ = cb;
}
bool PrintExtensionCallbackStub::HandleExtCallback(MessageParcel &data, MessageParcel &reply)
{
bool result = OnCallback();
if (!result) {
PRINT_HILOGE("Handle Print Extension Callback error");
}
reply.WriteBool(result);
return result;
}
bool PrintExtensionCallbackStub::HandlePrinterCallback(MessageParcel &data, MessageParcel &reply)
{
std::string printerId = data.ReadString();
bool result = OnCallback(printerId);
if (!result) {
PRINT_HILOGE("Handle Printer Extension Callback error");
}
reply.WriteBool(result);
return result;
}
bool PrintExtensionCallbackStub::HandlePrintJobCallback(MessageParcel &data, MessageParcel &reply)
{
auto printJobPtr = PrintJob::Unmarshalling(data);
if (printJobPtr == nullptr) {
PRINT_HILOGE("Restore print job object failed");
return false;
}
bool result = OnCallback(*printJobPtr);
if (!result) {
PRINT_HILOGE("Handle Print Job Extension Callback error");
}
reply.WriteBool(result);
return result;
}
bool PrintExtensionCallbackStub::HandleCapabilityCallback(MessageParcel &data, MessageParcel &reply)
{
std::string printerId = data.ReadString();
bool result = OnCallback(printerId, reply);
if (!result) {
PRINT_HILOGE("Handle Printer Capability Extension Callback error");
}
reply.WriteBool(result);
return result;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,137 @@
/*
* 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.
*/
#include "print_extension_info.h"
#include "print_log.h"
namespace OHOS::Print {
PrintExtensionInfo::PrintExtensionInfo() : extensionId_(""), vendorId_(""), vendorName_("PrintExtensionInfo"),
vendorIcon_(0), version_("PrintExtensionInfo") {
}
PrintExtensionInfo::PrintExtensionInfo(const PrintExtensionInfo &right)
{
extensionId_ = right.extensionId_;
vendorId_ = right.vendorId_;
vendorName_ = right.vendorName_;
vendorIcon_ = right.vendorIcon_;
version_ = right.version_;
}
PrintExtensionInfo &PrintExtensionInfo::operator=(const PrintExtensionInfo &right)
{
if (this != &right) {
extensionId_ = right.extensionId_;
vendorId_ = right.vendorId_;
vendorName_ = right.vendorName_;
vendorIcon_ = right.vendorIcon_;
version_ = right.version_;
}
return *this;
}
void PrintExtensionInfo::SetExtensionId(const std::string &extensionId)
{
extensionId_ = extensionId;
}
void PrintExtensionInfo::SetVendorId(const std::string &vendorId)
{
vendorId_ = vendorId;
}
void PrintExtensionInfo::SetVendorName(const std::string &vendorName)
{
vendorName_ = vendorName;
}
void PrintExtensionInfo::SetVendorIcon(uint32_t vendorIcon)
{
vendorIcon_ = vendorIcon;
}
void PrintExtensionInfo::SetVersion(const std::string &version)
{
version_ = version;
}
const std::string &PrintExtensionInfo::GetExtensionId() const
{
return extensionId_;
}
const std::string &PrintExtensionInfo::GetVendorId() const
{
return vendorId_;
}
const std::string &PrintExtensionInfo::GetVendorName() const
{
return vendorName_;
}
uint32_t PrintExtensionInfo::GetVendorIcon() const
{
return vendorIcon_;
}
const std::string &PrintExtensionInfo::GetVersion() const
{
return version_;
}
bool PrintExtensionInfo::ReadFromParcel(Parcel &parcel)
{
SetExtensionId(parcel.ReadString());
SetVendorId(parcel.ReadString());
SetVendorName(parcel.ReadString());
SetVendorIcon(parcel.ReadUint32());
SetVersion(parcel.ReadString());
return true;
}
bool PrintExtensionInfo::Marshalling(Parcel &parcel) const
{
parcel.WriteString(GetExtensionId());
parcel.WriteString(GetVendorId());
parcel.WriteString(GetVendorName());
parcel.WriteUint32(GetVendorIcon());
parcel.WriteString(GetVersion());
return true;
}
std::shared_ptr<PrintExtensionInfo> PrintExtensionInfo::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintExtensionInfo>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print extension info object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling print extension info object");
return nullptr;
}
return nativeObj;
}
void PrintExtensionInfo::Dump()
{
PRINT_HILOGD("extensionId = %{public}s", extensionId_.c_str());
PRINT_HILOGD("vendorId_ = %{public}s", vendorId_.c_str());
PRINT_HILOGD("vendorName_ = %{public}s", vendorName_.c_str());
PRINT_HILOGD("vendorIcon_ = %{public}d", vendorIcon_);
PRINT_HILOGD("version_ = %{public}s", version_.c_str());
}
} // namespace OHOS::Print

View File

@ -0,0 +1,602 @@
/*
* 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.
*/
#include "print_job.h"
#include "napi_print_utils.h"
#include "print_constant.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_JOB_FILES = "files";
static constexpr const char *PARAM_JOB_JOBID = "jobId";
static constexpr const char *PARAM_JOB_PRINTERID = "printerId";
static constexpr const char *PARAM_JOB_JOBSTATE = "jobState";
static constexpr const char *PARAM_JOB_SUBSTATE = "jobSubState";
static constexpr const char *PARAM_JOB_COPYNUMBER = "copyNumber";
static constexpr const char *PARAM_JOB_PAGERANGE = "pageRange";
static constexpr const char *PARAM_JOB_ISSEQUENTIAL = "isSequential";
static constexpr const char *PARAM_JOB_PAGESIZE = "pageSize";
static constexpr const char *PARAM_JOB_ISLANDSCAPE = "isLandscape";
static constexpr const char *PARAM_JOB_COLORMODE = "colorMode";
static constexpr const char *PARAM_JOB_DUPLEXMODE = "duplexMode";
static constexpr const char *PARAM_JOB_MARGIN = "margin";
static constexpr const char *PARAM_JOB_PREVIEW = "preview";
static constexpr const char *PARAM_JOB_OPTION = "option";
PrintJob::PrintJob() : jobId_(""), printerId_(""), jobState_(PRINT_JOB_PREPARED), subState_(PRINT_JOB_BLOCKED_UNKNOWN),
copyNumber_(0), isSequential_(false), isLandscape_(false), colorMode_(0), duplexMode_(0), option_("") {
}
PrintJob::PrintJob(const PrintJob &right)
{
files_.clear();
files_.assign(right.files_.begin(), right.files_.end());
printerId_ = right.printerId_;
jobId_ = right.jobId_;
jobState_ = right.jobState_;
copyNumber_ = right.copyNumber_;
pageRange_ = right.pageRange_;
isSequential_ = right.isSequential_;
pageSize_ = right.pageSize_;
isLandscape_ = right.isLandscape_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
margin_ = right.margin_;
preview_ = right.preview_;
option_ = right.option_;
}
PrintJob &PrintJob::operator=(const PrintJob &right)
{
if (this != &right) {
files_.clear();
files_.assign(right.files_.begin(), right.files_.end());
printerId_ = right.printerId_;
jobId_ = right.jobId_;
jobState_ = right.jobState_;
copyNumber_ = right.copyNumber_;
pageRange_ = right.pageRange_;
isSequential_ = right.isSequential_;
pageSize_ = right.pageSize_;
isLandscape_ = right.isLandscape_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
margin_ = right.margin_;
preview_ = right.preview_;
option_ = right.option_;
}
return *this;
}
PrintJob::~PrintJob()
{
}
void PrintJob::SetFiles(const std::vector<std::string> &files)
{
files_.clear();
files_.assign(files.begin(), files.end());
}
void PrintJob::SetJobId(const std::string &jobId)
{
jobId_ = jobId;
}
void PrintJob::SetPrinterId(const std::string &printerid)
{
printerId_ = printerid;
}
void PrintJob::SetJobState(uint32_t jobState)
{
if (jobState < PRINT_JOB_UNKNOWN) {
jobState_ = jobState;
}
}
void PrintJob::SetSubState(uint32_t subState)
{
if (jobState_ == PRINT_JOB_COMPLETED && subState <= PRINT_JOB_COMPLETED_FILE_CORRUPT) {
subState_ = subState;
}
if (jobState_ == PRINT_JOB_BLOCKED &&
(subState < PRINT_JOB_BLOCKED_UNKNOWN && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT)) {
subState_ = subState;
}
}
void PrintJob::SetCopyNumber(uint32_t copyNumber)
{
copyNumber_ = copyNumber;
}
void PrintJob::SetPageRange(const PrintRange &pageRange)
{
pageRange_ = pageRange;
}
void PrintJob::SetIsSequential(bool isSequential)
{
isSequential_ = isSequential;
}
void PrintJob::SetPageSize(const PrintPageSize &pageSize)
{
pageSize_ = pageSize;
}
void PrintJob::SetIsLandscape(bool isLandscape)
{
isLandscape_ = isLandscape;
}
void PrintJob::SetColorMode(uint32_t colorMode)
{
colorMode_ = colorMode;
}
void PrintJob::SetDuplexMode(uint32_t duplexmode)
{
duplexMode_ = duplexmode;
}
void PrintJob::SetMargin(const PrintMargin &margin)
{
margin_ = margin;
}
void PrintJob::SetOption(const std::string &option)
{
option_ = option;
}
void PrintJob::SetPreview(const PrintPreviewAttribute &preview)
{
preview_ = preview;
}
void PrintJob::GetFiles(std::vector<std::string> &files) const
{
files.clear();
files.assign(files_.begin(), files_.end());
}
const std::string &PrintJob::GetJobId() const
{
return jobId_;
}
const std::string &PrintJob::GetPrinterId() const
{
return printerId_;
}
uint32_t PrintJob::GetJobState() const
{
return jobState_;
}
uint32_t PrintJob::GetSubState() const
{
return subState_;
}
uint32_t PrintJob::GetCopyNumber() const
{
return copyNumber_;
}
void PrintJob::GetPageRange(PrintRange &range) const
{
range = pageRange_;
}
bool PrintJob::GetIsSequential() const
{
return isSequential_;
}
void PrintJob::GetPageSize(PrintPageSize &pageSize) const
{
pageSize = pageSize_;
}
bool PrintJob::GetIsLandscape() const
{
return isLandscape_;
}
uint32_t PrintJob::GetColorMode() const
{
return colorMode_;
}
uint32_t PrintJob::GetDuplexMode() const
{
return duplexMode_;
}
void PrintJob::GetMargin(PrintMargin &margin) const
{
margin = margin_;
}
void PrintJob::GetPreview(PrintPreviewAttribute &previewAttr) const
{
previewAttr = preview_;
}
const std::string &PrintJob::GetOption() const
{
return option_;
}
bool PrintJob::ReadFromParcel(Parcel &parcel)
{
if (!parcel.ReadStringVector(&files_)) {
PRINT_HILOGE("Failed to restore file list");
return false;
}
SetJobId(parcel.ReadString());
SetPrinterId(parcel.ReadString());
SetJobState(parcel.ReadUint32());
SetSubState(parcel.ReadUint32());
SetCopyNumber(parcel.ReadUint32());
auto rangePtr = PrintRange::Unmarshalling(parcel);
if (rangePtr == nullptr) {
PRINT_HILOGE("Failed to restore page range");
return false;
}
SetPageRange(*rangePtr);
SetIsSequential(parcel.ReadBool());
auto pageSizePtr = PrintPageSize::Unmarshalling(parcel);
if (pageSizePtr == nullptr) {
PRINT_HILOGE("Failed to restore page size");
return false;
}
SetPageSize(*pageSizePtr);
SetIsLandscape(parcel.ReadBool());
SetColorMode(parcel.ReadUint32());
SetDuplexMode(parcel.ReadUint32());
auto marginPtr = PrintMargin::Unmarshalling(parcel);
if (marginPtr == nullptr) {
PRINT_HILOGE("Failed to restore margin");
return false;
}
SetMargin(*marginPtr);
auto previewPtr = PrintPreviewAttribute::Unmarshalling(parcel);
if (previewPtr == nullptr) {
PRINT_HILOGE("Failed to restore preview attribute");
return false;
}
SetPreview(*previewPtr);
if (parcel.ReadBool()) {
SetOption(parcel.ReadString());
} else {
SetOption("");
}
return true;
}
bool PrintJob::Marshalling(Parcel &parcel) const
{
if (!parcel.WriteStringVector(files_)) {
PRINT_HILOGE("Failed to save file list");
return false;
}
if (!parcel.WriteString(GetJobId())) {
PRINT_HILOGE("Failed to save job id");
return false;
}
if (!parcel.WriteString(GetPrinterId())) {
PRINT_HILOGE("Failed to save printer id");
return false;
}
if (!parcel.WriteUint32(GetJobState())) {
PRINT_HILOGE("Failed to save job state");
return false;
}
if (!parcel.WriteUint32(GetSubState())) {
PRINT_HILOGE("Failed to save job substate");
return false;
}
if (!parcel.WriteUint32(GetCopyNumber())) {
PRINT_HILOGE("Failed to save copy number");
return false;
}
if (!pageRange_.Marshalling(parcel)) {
PRINT_HILOGE("Failed to save page range");
return false;
}
if (!parcel.WriteBool(GetIsSequential())) {
PRINT_HILOGE("Failed to save sequential mode");
return false;
}
if (!pageSize_.Marshalling(parcel)) {
PRINT_HILOGE("Failed to save page size");
return false;
}
if (!parcel.WriteBool(GetIsLandscape())) {
PRINT_HILOGE("Failed to save printer id");
return false;
}
if (!parcel.WriteUint32(GetColorMode())) {
PRINT_HILOGE("Failed to save color mode");
return false;
}
if (!parcel.WriteUint32(GetDuplexMode())) {
PRINT_HILOGE("Failed to save duplex mode");
return false;
}
if (!margin_.Marshalling(parcel)) {
PRINT_HILOGE("Failed to save margin");
return false;
}
if (!preview_.Marshalling(parcel)) {
PRINT_HILOGE("Failed to save preview");
return false;
}
if (GetOption() != "") {
parcel.WriteBool(true);
parcel.WriteString(GetOption());
} else {
parcel.WriteBool(false);
}
return true;
}
std::shared_ptr<PrintJob> PrintJob::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintJob>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print job object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling printjob");
return nullptr;
}
return nativeObj;
}
bool PrintJob::CreateFileList(napi_env env, napi_value &jsPrintJob) const
{
napi_value arrFiles = nullptr;
NAPI_CALL_BASE(env, napi_create_array(env, &arrFiles), false);
uint32_t arrFilesLength = files_.size();
for (uint32_t i = 0; i < arrFilesLength; i++) {
napi_value value;
NAPI_CALL_BASE(env, napi_create_string_utf8(env, files_[i].c_str(), NAPI_AUTO_LENGTH, &value), false);
NAPI_CALL_BASE(env, napi_set_element(env, arrFiles, i, value), false);
}
NAPI_CALL_BASE(env, napi_set_named_property(env, jsPrintJob, PARAM_JOB_FILES, arrFiles), false);
return true;
}
bool PrintJob::CreatePageRange(napi_env env, napi_value &jsPrintJob) const
{
napi_value jsPageRange = pageRange_.ToJsObject(env);
NAPI_CALL_BASE(env, napi_set_named_property(env, jsPrintJob, PARAM_JOB_PAGERANGE, jsPageRange), false);
return true;
}
bool PrintJob::CreatePageSize(napi_env env, napi_value &jsPrintJob) const
{
napi_value jsPageSize = pageSize_.ToJsObject(env);
NAPI_CALL_BASE(env, napi_set_named_property(env, jsPrintJob, PARAM_JOB_PAGESIZE, jsPageSize), false);
return true;
}
bool PrintJob::CreateMargin(napi_env env, napi_value &jsPrintJob) const
{
napi_value jsMargin = margin_.ToJsObject(env);
NAPI_CALL_BASE(env, napi_set_named_property(env, jsPrintJob, PARAM_JOB_MARGIN, jsMargin), false);
return true;
}
bool PrintJob::CreatePreview(napi_env env, napi_value &jsPrintJob) const
{
napi_value jsPreview = preview_.ToJsObject(env);
NAPI_CALL_BASE(env, napi_set_named_property(env, jsPrintJob, PARAM_JOB_PREVIEW, jsPreview), false);
return true;
}
napi_value PrintJob::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
if (!CreateFileList(env, jsObj)) {
PRINT_HILOGE("Failed to create files property of print job");
return nullptr;
}
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_JOB_JOBID, GetJobId());
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_JOB_PRINTERID, GetPrinterId());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_JOBSTATE, GetJobState());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_SUBSTATE, GetSubState());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_COPYNUMBER, GetCopyNumber());
if (!CreatePageRange(env, jsObj)) {
PRINT_HILOGE("Failed to create page range property of print job");
return nullptr;
}
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_ISSEQUENTIAL, GetIsSequential());
if (!CreatePageSize(env, jsObj)) {
PRINT_HILOGE("Failed to create page size property of print job");
return nullptr;
}
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_ISLANDSCAPE, GetIsLandscape());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_COLORMODE, GetColorMode());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_JOB_DUPLEXMODE, GetDuplexMode());
if (!CreateMargin(env, jsObj)) {
PRINT_HILOGE("Failed to create margin property of print job");
return nullptr;
}
if (!CreatePreview(env, jsObj)) {
PRINT_HILOGE("Failed to create preview property of print job");
return nullptr;
}
if (GetOption() != "") {
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_JOB_OPTION, GetOption());
}
return jsObj;
}
std::shared_ptr<PrintJob> PrintJob::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrintJob>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print job object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
napi_value jsFiles = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_FILES);
bool isFileArray = false;
napi_is_array(env, jsFiles, &isFileArray);
if (isFileArray) {
std::vector<std::string> printFiles;
uint32_t arrayReLength = 0;
napi_get_array_length(env, jsFiles, &arrayReLength);
for (uint32_t index = 0; index < arrayReLength; index++) {
napi_value filesValue;
napi_get_element(env, jsFiles, index, &filesValue);
std::string files = NapiPrintUtils::GetStringFromValueUtf8(env, filesValue);
PRINT_HILOGD("printJob_value jsFiles %{public}s", files.c_str());
printFiles.emplace_back(files);
}
nativeObj->SetFiles(printFiles);
}
std::string jobId = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_JOB_JOBID);
std::string printerId = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_JOB_PRINTERID);
uint32_t jobState = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_JOB_JOBSTATE);
uint32_t subState = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_JOB_SUBSTATE);
uint32_t copyNumber = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_JOB_COPYNUMBER);
bool isSequential = NapiPrintUtils::GetBooleanProperty(env, jsValue, PARAM_JOB_ISSEQUENTIAL);
bool isLandscape = NapiPrintUtils::GetBooleanProperty(env, jsValue, PARAM_JOB_ISLANDSCAPE);
uint32_t colorMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_JOB_COLORMODE);
uint32_t duplexMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_JOB_DUPLEXMODE);
nativeObj->SetJobId(jobId);
nativeObj->SetPrinterId(printerId);
nativeObj->SetJobState(jobState);
nativeObj->SetSubState(subState);
nativeObj->SetCopyNumber(copyNumber);
nativeObj->SetIsSequential(isSequential);
nativeObj->SetIsLandscape(isLandscape);
nativeObj->SetColorMode(colorMode);
nativeObj->SetDuplexMode(duplexMode);
napi_value jsPageRange = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_PAGERANGE);
auto pageRangePtr = PrintRange::BuildFromJs(env, jsPageRange);
if (pageRangePtr == nullptr) {
PRINT_HILOGE("Failed to build print job object from js");
return nullptr;
}
nativeObj->SetPageRange(*pageRangePtr);
napi_value jsPageSize = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_PAGESIZE);
auto pageSizePtr = PrintPageSize::BuildFromJs(env, jsPageSize);
if (pageSizePtr == nullptr) {
PRINT_HILOGE("Failed to build print job object from js");
return nullptr;
}
nativeObj->SetPageSize(*pageSizePtr);
napi_value jsMargin = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_MARGIN);
auto marginPtr = PrintMargin::BuildFromJs(env, jsMargin);
if (marginPtr == nullptr) {
PRINT_HILOGE("Failed to build print job object from js");
return nullptr;
}
nativeObj->SetMargin(*marginPtr);
napi_value jsPreview = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_PREVIEW);
auto previewPtr = PrintPreviewAttribute::BuildFromJs(env, jsPreview);
if (previewPtr == nullptr) {
PRINT_HILOGE("Failed to build print job object from js");
return nullptr;
}
nativeObj->SetPreview(*previewPtr);
napi_value jsOption = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_OPTION);
if (jsOption != nullptr) {
nativeObj->SetOption(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_JOB_OPTION));
}
nativeObj->Dump();
return nativeObj;
}
void PrintJob::Dump()
{
uint32_t fileLength = files_.size();
for (uint32_t i = 0; i < fileLength; i++) {
PRINT_HILOGD("files_ = %{public}s", files_[i].c_str());
}
PRINT_HILOGD("jobId_ = %{public}s", jobId_.c_str());
PRINT_HILOGD("printerId_ = %{public}s", printerId_.c_str());
PRINT_HILOGD("jobState_ = %{public}d", jobState_);
PRINT_HILOGD("subState_ = %{public}d", subState_);
PRINT_HILOGD("copyNumber_ = %{public}d", copyNumber_);
PRINT_HILOGD("isSequential_ = %{public}d", isSequential_);
PRINT_HILOGD("isLandscape_ = %{public}d", isLandscape_);
PRINT_HILOGD("colorMode_ = %{public}d", colorMode_);
PRINT_HILOGD("duplexMode_ = %{public}d", duplexMode_);
pageRange_.Dump();
pageSize_.Dump();
margin_.Dump();
preview_.Dump();
if (option_ != "") {
PRINT_HILOGD("option: %{public}s", option_.c_str());
}
}
} // namespace OHOS::Print

View File

@ -0,0 +1,747 @@
/*
* 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.
*/
#include "print_manager_client.h"
#include "iservice_registry.h"
#include "napi_print_utils.h"
#include "print_constant.h"
#include "print_extension_callback_stub.h"
#include "print_log.h"
#include "print_sync_load_callback.h"
#include "system_ability_definition.h"
namespace OHOS::Print {
std::mutex PrintManagerClient::instanceLock_;
sptr<PrintManagerClient> PrintManagerClient::instance_ = nullptr;
PrintManagerClient::PrintManagerClient() : printServiceProxy_(nullptr), deathRecipient_(nullptr) {}
PrintManagerClient::~PrintManagerClient() {}
sptr<PrintManagerClient> PrintManagerClient::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> autoLock(instanceLock_);
if (instance_ == nullptr) {
instance_ = new PrintManagerClient;
}
}
return instance_;
}
sptr<IPrintService> PrintManagerClient::GetPrintServiceProxy()
{
sptr<ISystemAbilityManager> systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (systemAbilityManager == nullptr) {
PRINT_HILOGE("Getting SystemAbilityManager failed.");
return nullptr;
}
auto systemAbility = systemAbilityManager->GetSystemAbility(PRINT_SERVICE_ID, "");
if (systemAbility == nullptr) {
PRINT_HILOGE("Get SystemAbility failed.");
return nullptr;
}
deathRecipient_ = new PrintSaDeathRecipient();
systemAbility->AddDeathRecipient(deathRecipient_);
sptr<IPrintService> serviceProxy = iface_cast<IPrintService>(systemAbility);
if (serviceProxy == nullptr) {
PRINT_HILOGE("Get PrintManagerClientProxy from SA failed.");
return nullptr;
}
PRINT_HILOGD("Getting PrintManagerClientProxy succeeded.");
return serviceProxy;
}
void PrintManagerClient::OnRemoteSaDied(const wptr<IRemoteObject> &remote)
{
printServiceProxy_ = GetPrintServiceProxy();
}
int32_t PrintManagerClient::StartPrint(const std::vector<std::string> &fileList, std::string &taskId)
{
PRINT_HILOGD("PrintManagerClient StartPrint start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StartPrint quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->StartPrint(fileList, taskId);
PRINT_HILOGD("PrintManagerClient StartPrint out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::StopPrint(const std::string &taskId)
{
PRINT_HILOGD("PrintManagerClient StopPrint start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StopPrint quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->StopPrint(taskId);
PRINT_HILOGD("PrintManagerClient StopPrint out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::ConnectPrinter(const std::string &printerId)
{
PRINT_HILOGD("PrintManagerClient ConnectPrinter start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("ConnectPrinter quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->ConnectPrinter(printerId);
PRINT_HILOGD("PrintManagerClient ConnectPrinter out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::DisconnectPrinter(const std::string &printerId)
{
PRINT_HILOGD("PrintManagerClient DisconnectPrinter start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("DisconnectPrinter quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->DisconnectPrinter(printerId);
PRINT_HILOGD("PrintManagerClient DisconnectPrinter out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos)
{
PRINT_HILOGD("PrintManagerClient QueryAllExtension start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("QueryAllExtension quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->QueryAllExtension(extensionInfos);
PRINT_HILOGD("PrintManagerClient QueryAllExtension out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::StartDiscoverPrinter(const std::vector<std::string> &extensionList)
{
PRINT_HILOGD("PrintManagerClient StartDiscoverPrinter start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StartDiscoverPrinter quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->StartDiscoverPrinter(extensionList);
PRINT_HILOGD("PrintManagerClient StartDiscoverPrinter out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::StopDiscoverPrinter()
{
PRINT_HILOGD("PrintManagerClient StopDiscoverPrinter start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StopDiscoverPrinter quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->StopDiscoverPrinter();
PRINT_HILOGD("PrintManagerClient StopDiscoverPrinter out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::StartPrintJob(const PrintJob &jobinfo)
{
PRINT_HILOGD("PrintManagerClient StartPrintJob start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("StartPrintJob quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->StartPrintJob(jobinfo);
PRINT_HILOGD("PrintManagerClient StartPrintJob out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::CancelPrintJob(const PrintJob &jobinfo)
{
PRINT_HILOGD("PrintManagerClient CancelPrintJob start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("CancelPrintJob quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->CancelPrintJob(jobinfo);
PRINT_HILOGD("PrintManagerClient CancelPrintJob out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::AddPrinters(const std::vector<PrinterInfo> &printerInfos)
{
PRINT_HILOGD("PrintManagerClient AddPrinters start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("AddPrinters quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->AddPrinters(printerInfos);
PRINT_HILOGD("PrintManagerClient AddPrinters out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::RemovePrinters(const std::vector<std::string> &printerIds)
{
PRINT_HILOGD("PrintManagerClient RemovePrinters start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RemovePrinters quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->RemovePrinters(printerIds);
PRINT_HILOGD("PrintManagerClient RemovePrinters out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::UpdatePrinters(const std::vector<PrinterInfo> &printerInfos)
{
PRINT_HILOGD("PrintManagerClient UpdatePrinters start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("UpdatePrinters quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->UpdatePrinters(printerInfos);
PRINT_HILOGD("PrintManagerClient UpdatePrinters out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::UpdatePrinterState(const std::string &printerId, uint32_t state)
{
PRINT_HILOGD("PrintManagerClient UpdatePrinterState start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("UpdatePrinterState quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->UpdatePrinterState(printerId, state);
PRINT_HILOGD("PrintManagerClient UpdatePrinterState out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState)
{
PRINT_HILOGD("PrintManagerClient UpdatePrintJobState start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("UpdatePrintJobState quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->UpdatePrintJobState(jobId, state, subState);
PRINT_HILOGD("PrintManagerClient UpdatePrintJobState out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo)
{
PRINT_HILOGD("PrintManagerClient UpdateExtensionInfo start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("UpdateExtensionInfo quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->UpdateExtensionInfo(extensionId, extInfo);
PRINT_HILOGD("PrintManagerClient UpdateExtensionInfo out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::RequestPreview(const PrintJob &jobinfo, std::string &previewResult)
{
PRINT_HILOGD("PrintManagerClient RequestPreview start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RequestPreview quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->RequestPreview(jobinfo, previewResult);
PRINT_HILOGD("PrintManagerClient RequestPreview out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::QueryPrinterCapability(const std::string &printerId,
PrinterCapability &printerCapability)
{
PRINT_HILOGD("PrintManagerClient QueryPrinterCapability start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("QueryPrinterCapability quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->QueryPrinterCapability(printerId, printerCapability);
PRINT_HILOGD("PrintManagerClient QueryPrinterCapability out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::On(const std::string &type, const sptr<IPrintCallback> &listener)
{
PRINT_HILOGD("PrintManagerClient On start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("On quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->On(type, listener);
PRINT_HILOGD("PrintManagerClient On out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::Off(const std::string &type)
{
PRINT_HILOGD("PrintManagerClient Off start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Off quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->Off(type);
PRINT_HILOGD("PrintManagerClient Off out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::Read(std::vector<uint8_t> &fileRead,
const std::string &uri, uint32_t offset, uint32_t max)
{
PRINT_HILOGD("PrintManagerClient Read start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Read quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->Read(fileRead, uri, offset, max);
PRINT_HILOGD("PrintManagerClient Read out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::RegisterExtCallback(const std::string &extensionId,
uint32_t callbackId, PrintExtCallback cb)
{
PRINT_HILOGD("PrintManagerClient RegisterExtCallback start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RegisterExtCallback quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return ERROR_INVALID_PARAMETER;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
std::string extensionCID = NapiPrintUtils::EncodeExtensionCID(extensionId, callbackId);
auto it = extCallbackMap_.find(extensionCID);
if (it == extCallbackMap_.end()) {
callbackStub = new (std::nothrow) PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return ERROR_GENERIC_FAIL;
}
callbackStub->SetExtCallback(cb);
extCallbackMap_.insert(std::make_pair(extensionCID, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetExtCallback(cb);
}
int32_t ret = printServiceProxy_->RegisterExtCallback(extensionCID, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::RegisterExtCallback(const std::string &extensionId,
uint32_t callbackId, PrintJobCallback cb)
{
PRINT_HILOGD("PrintManagerClient RegisterExtCallback start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RegisterExtCallback quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return ERROR_INVALID_PARAMETER;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
std::string extensionCID = NapiPrintUtils::EncodeExtensionCID(extensionId, callbackId);
auto it = extCallbackMap_.find(extensionCID);
if (it == extCallbackMap_.end()) {
callbackStub = new (std::nothrow) PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return ERROR_GENERIC_FAIL;
}
callbackStub->SetPrintJobCallback(cb);
extCallbackMap_.insert(std::make_pair(extensionCID, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetPrintJobCallback(cb);
}
int32_t ret = printServiceProxy_->RegisterExtCallback(extensionCID, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::RegisterExtCallback(const std::string &extensionId,
uint32_t callbackId, PrinterCapabilityCallback cb)
{
PRINT_HILOGD("PrintManagerClient RegisterExtCallback start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RegisterExtCallback quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return ERROR_INVALID_PARAMETER;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
std::string extensionCID = NapiPrintUtils::EncodeExtensionCID(extensionId, callbackId);
auto it = extCallbackMap_.find(extensionCID);
if (it == extCallbackMap_.end()) {
callbackStub = new (std::nothrow) PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return ERROR_GENERIC_FAIL;
}
callbackStub->SetCapabilityCallback(cb);
extCallbackMap_.insert(std::make_pair(extensionCID, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetCapabilityCallback(cb);
}
int32_t ret = printServiceProxy_->RegisterExtCallback(extensionCID, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::RegisterExtCallback(const std::string &extensionId,
uint32_t callbackId, PrinterCallback cb)
{
PRINT_HILOGD("PrintManagerClient RegisterExtCallback start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("RegisterExtCallback quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id [%{public}d].", callbackId);
return ERROR_INVALID_PARAMETER;
}
sptr<PrintExtensionCallbackStub> callbackStub = nullptr;
std::string extensionCID = NapiPrintUtils::EncodeExtensionCID(extensionId, callbackId);
auto it = extCallbackMap_.find(extensionCID);
if (it == extCallbackMap_.end()) {
callbackStub = new (std::nothrow) PrintExtensionCallbackStub;
if (callbackStub == nullptr) {
PRINT_HILOGE("Invalid callback stub object.");
return ERROR_GENERIC_FAIL;
}
callbackStub->SetPrinterCallback(cb);
extCallbackMap_.insert(std::make_pair(extensionCID, callbackStub));
} else {
callbackStub = it->second;
callbackStub->SetPrinterCallback(cb);
}
int32_t ret = printServiceProxy_->RegisterExtCallback(extensionCID, callbackStub);
PRINT_HILOGD("PrintManagerClient RegisterExtCallback out ret = [%{public}d].", ret);
return ret;
}
int32_t PrintManagerClient::UnregisterAllExtCallback(const std::string &extensionId)
{
PRINT_HILOGD("PrintManagerClient UnregisterAllExtCallback start.");
if (!LoadServer()) {
PRINT_HILOGE("load print server fail");
return ERROR_RPC_FAIL;
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGW("Redo GetPrintServiceProxy");
printServiceProxy_ = GetPrintServiceProxy();
}
if (printServiceProxy_ == nullptr) {
PRINT_HILOGE("Resume quit because redoing GetPrintServiceProxy failed.");
return ERROR_RPC_FAIL;
}
int32_t ret = printServiceProxy_->UnregisterAllExtCallback(extensionId);
PRINT_HILOGD("PrintManagerClient UnregisterAllExtCallback out ret = [%{public}d].", ret);
extCallbackMap_.clear();
return ret;
}
bool PrintManagerClient::LoadServer()
{
if (ready_) {
return true;
}
std::lock_guard<std::mutex> lock(loadMutex_);
if (ready_) {
return true;
}
auto sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sm == nullptr) {
PRINT_HILOGE("GetSystemAbilityManager return null");
return false;
}
sptr<PrintSyncLoadCallback> loadCallback_ = new (std::nothrow) PrintSyncLoadCallback();
if (loadCallback_ == nullptr) {
PRINT_HILOGE("new PrintSyncLoadCallback fail");
return false;
}
int32_t result = sm->LoadSystemAbility(PRINT_SERVICE_ID, loadCallback_);
if (result != ERR_OK) {
PRINT_HILOGE("LoadSystemAbility %{public}d failed, result: %{public}d", PRINT_SERVICE_ID, result);
return false;
}
{
std::unique_lock<std::mutex> conditionLock(conditionMutex_);
auto waitStatus = syncCon_.wait_for(
conditionLock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), [this]() { return ready_; });
if (!waitStatus) {
PRINT_HILOGE("print server load sa timeout");
return false;
}
}
return true;
}
void PrintManagerClient::LoadServerSuccess()
{
std::unique_lock<std::mutex> lock(conditionMutex_);
ready_ = true;
syncCon_.notify_one();
PRINT_HILOGD("load print server success");
}
void PrintManagerClient::LoadServerFail()
{
ready_ = false;
PRINT_HILOGE("load print server fail");
}
} // namespace OHOS::Print

View File

@ -0,0 +1,165 @@
/*
* 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.
*/
#include "print_margin.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_MARGIN_TOP = "top";
static constexpr const char *PARAM_MARGIN_BOTTOM = "bottom";
static constexpr const char *PARAM_MARGIN_LEFT = "left";
static constexpr const char *PARAM_MARGIN_RIGHT = "right";
PrintMargin::PrintMargin() : top_(0), bottom_(0), left_(0), right_(0) {}
PrintMargin::PrintMargin(const PrintMargin &right)
{
top_ = right.top_;
bottom_ = right.bottom_;
left_ = right.left_;
right_ = right.right_;
}
PrintMargin &PrintMargin::operator=(const PrintMargin &right)
{
if (this != &right) {
top_ = right.top_;
bottom_ = right.bottom_;
left_ = right.left_;
right_ = right.right_;
}
return *this;
}
PrintMargin::~PrintMargin() {}
void PrintMargin::SetTop(uint32_t top)
{
top_ = top;
}
void PrintMargin::SetBottom(uint32_t bottom)
{
bottom_ = bottom;
}
void PrintMargin::SetLeft(uint32_t left)
{
left_ = left;
}
void PrintMargin::SetRight(uint32_t right)
{
right_ = right;
}
uint32_t PrintMargin::GetTop() const
{
return top_;
}
uint32_t PrintMargin::GetBottom() const
{
return bottom_;
}
uint32_t PrintMargin::GetLeft() const
{
return left_;
}
uint32_t PrintMargin::GetRight() const
{
return right_;
}
bool PrintMargin::ReadFromParcel(Parcel &parcel)
{
SetTop(parcel.ReadUint32());
SetBottom(parcel.ReadUint32());
SetLeft(parcel.ReadUint32());
SetRight(parcel.ReadUint32());
return true;
}
bool PrintMargin::Marshalling(Parcel &parcel) const
{
parcel.WriteUint32(GetTop());
parcel.WriteUint32(GetBottom());
parcel.WriteUint32(GetLeft());
parcel.WriteUint32(GetRight());
return true;
}
std::shared_ptr<PrintMargin> PrintMargin::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintMargin>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print margin object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling print margin");
return nullptr;
}
return nativeObj;
}
napi_value PrintMargin::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_MARGIN_TOP, GetTop());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_MARGIN_BOTTOM, GetBottom());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_MARGIN_LEFT, GetLeft());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_MARGIN_RIGHT, GetRight());
return jsObj;
}
std::shared_ptr<PrintMargin> PrintMargin::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrintMargin>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print margin object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
uint32_t top = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_MARGIN_TOP);
uint32_t bottom = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_MARGIN_BOTTOM);
uint32_t left = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_MARGIN_LEFT);
uint32_t right = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_MARGIN_RIGHT);
nativeObj->SetTop(top);
nativeObj->SetBottom(bottom);
nativeObj->SetLeft(left);
nativeObj->SetRight(right);
PRINT_HILOGE("Build Print Margin succeed");
return nativeObj;
}
void PrintMargin::Dump()
{
PRINT_HILOGD("top_ = %{public}d", top_);
PRINT_HILOGD("bottom_ = %{public}d", bottom_);
PRINT_HILOGD("left_ = %{public}d", left_);
PRINT_HILOGD("right_ = %{public}d", right_);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,35 @@
/*
* 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.
*/
#include "print_notify.h"
#include <uv.h>
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
PrintNotify::PrintNotify() {}
PrintNotify::~PrintNotify()
{
PRINT_HILOGD("");
}
void PrintNotify::OnCallBack(MessageParcel &data)
{
PRINT_HILOGD("Failed callback in");
}
} // namespace OHOS::Print

View File

@ -0,0 +1,193 @@
/*
* 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.
*/
#include "print_page_size.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_PAGESIZE_ID = "id";
static constexpr const char *PARAM_PAGESIZE_NAME = "name";
static constexpr const char *PARAM_PAGESIZE_WIDTH = "width";
static constexpr const char *PARAM_PAGESIZE_HEIGHT = "height";
std::map<PAGE_SIZE_ID, std::shared_ptr<PrintPageSize>> PrintPageSize::pageSize_;
void PrintPageSize::BuildPageSizeMap()
{
PRINT_HILOGD("");
}
PrintPageSize::PrintPageSize() : id_(""), name_("PrintPageSize"), width_(0), height_(0) {}
PrintPageSize::PrintPageSize(PAGE_SIZE_ID id, DiscretePageName name, uint32_t width, uint32_t height)
{
id_ = id;
name_ = name;
width_ = width;
height_ = height;
}
PrintPageSize PrintPageSize::GetPageSize(PageSizeId id)
{
uint32_t pageSizeId = (uint32_t)id;
if (pageSizeId < (uint32_t)sizeof(PAGE_SIZE_TABLE)) {
auto iter = pageSize_.find(PAGE_SIZE_TABLE[pageSizeId]);
if (iter != pageSize_.end()) {
return *(iter->second);
}
}
PrintPageSize printPageSize;
return printPageSize;
}
PrintPageSize::PrintPageSize(const PrintPageSize &right)
{
id_ = right.id_;
name_ = right.name_;
width_ = right.width_;
height_ = right.height_;
}
PrintPageSize &PrintPageSize::operator=(const PrintPageSize &right)
{
if (this != &right) {
id_ = right.id_;
name_ = right.name_;
width_ = right.width_;
height_ = right.height_;
}
return *this;
}
PrintPageSize::~PrintPageSize() {}
void PrintPageSize::SetId(const std::string &id)
{
id_ = id;
}
void PrintPageSize::SetName(const std::string &name)
{
name_ = name;
}
void PrintPageSize::SetWidth(uint32_t width)
{
width_ = width;
}
void PrintPageSize::SetHeight(uint32_t height)
{
height_ = height;
}
const std::string &PrintPageSize::GetId() const
{
return id_;
}
const std::string &PrintPageSize::GetName() const
{
return name_;
}
uint32_t PrintPageSize::GetWidth() const
{
return width_;
}
uint32_t PrintPageSize::GetHeight() const
{
return height_;
}
bool PrintPageSize::ReadFromParcel(Parcel &parcel)
{
SetId(parcel.ReadString());
SetName(parcel.ReadString());
SetWidth(parcel.ReadUint32());
SetHeight(parcel.ReadUint32());
return true;
}
bool PrintPageSize::Marshalling(Parcel &parcel) const
{
parcel.WriteString(GetId());
parcel.WriteString(GetName());
parcel.WriteUint32(GetWidth());
parcel.WriteUint32(GetHeight());
return true;
}
std::shared_ptr<PrintPageSize> PrintPageSize::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintPageSize>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print page size object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling print page size");
return nullptr;
}
return nativeObj;
}
napi_value PrintPageSize::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_PAGESIZE_ID, GetId());
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_PAGESIZE_NAME, GetName());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_PAGESIZE_WIDTH, GetWidth());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_PAGESIZE_HEIGHT, GetHeight());
return jsObj;
}
std::shared_ptr<PrintPageSize> PrintPageSize::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrintPageSize>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print range object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
std::string id = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_PAGESIZE_ID);
std::string name = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_PAGESIZE_NAME);
uint32_t width = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_PAGESIZE_WIDTH);
uint32_t height = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_PAGESIZE_HEIGHT);
nativeObj->SetId(id);
nativeObj->SetName(name);
nativeObj->SetWidth(width);
nativeObj->SetHeight(height);
PRINT_HILOGE("Build Page Size succeed");
return nativeObj;
}
void PrintPageSize::Dump()
{
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_);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,143 @@
/*
* 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.
*/
#include "print_preview_attribute.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_PREATTRIBUTE_RANGE = "previewRange";
static constexpr const char *PARAM_PREATTRIBUTE_RESULT = "result";
PrintPreviewAttribute::PrintPreviewAttribute() : result_("") {
}
PrintPreviewAttribute::PrintPreviewAttribute(const PrintPreviewAttribute &right)
{
result_ = right.result_;
previewRange_ = right.previewRange_;
}
PrintPreviewAttribute &PrintPreviewAttribute::operator=(const PrintPreviewAttribute &right)
{
if (this != &right) {
result_ = right.result_;
previewRange_ = right.previewRange_;
}
return *this;
}
PrintPreviewAttribute::~PrintPreviewAttribute()
{
}
void PrintPreviewAttribute::SetResult(const std::string &result)
{
result_ = result;
}
void PrintPreviewAttribute::SetPreviewRange(const PrintRange &previewRange)
{
previewRange_ = previewRange;
}
const std::string &PrintPreviewAttribute::GetResult() const
{
return result_;
}
void PrintPreviewAttribute::GetPreviewRange(PrintRange &previewRange) const
{
previewRange = previewRange_;
}
bool PrintPreviewAttribute::ReadFromParcel(Parcel &parcel)
{
SetResult(parcel.ReadString());
auto rangePtr = PrintRange::Unmarshalling(parcel);
if (rangePtr == nullptr) {
return false;
}
SetPreviewRange(*rangePtr);
return true;
}
bool PrintPreviewAttribute::Marshalling(Parcel &parcel) const
{
parcel.WriteString(GetResult());
if (!previewRange_.Marshalling(parcel)) {
PRINT_HILOGE("Failed to marshalling preview attribute object");
return false;
}
return true;
}
std::shared_ptr<PrintPreviewAttribute> PrintPreviewAttribute::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintPreviewAttribute>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print preview attribute object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling print preview attribute");
return nullptr;
}
return nativeObj;
}
napi_value PrintPreviewAttribute::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_PREATTRIBUTE_RESULT, GetResult());
napi_value jsPreviewRange = previewRange_.ToJsObject(env);
NAPI_CALL(env, napi_set_named_property(env, jsObj, PARAM_PREATTRIBUTE_RANGE, jsPreviewRange));
return jsObj;
}
std::shared_ptr<PrintPreviewAttribute> PrintPreviewAttribute::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrintPreviewAttribute>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print preview attribute object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
napi_value jsPreviewRange = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_PREATTRIBUTE_RANGE);
auto previewRangePtr = PrintRange::BuildFromJs(env, jsPreviewRange);
if (previewRangePtr == nullptr) {
PRINT_HILOGE("Failed to build print preview attribute object from js");
return nullptr;
}
nativeObj->SetPreviewRange(*previewRangePtr);
std::string result = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_PREATTRIBUTE_RESULT);
nativeObj->SetResult(result);
PRINT_HILOGE("Build Print Preview Attribute succeed");
return nativeObj;
}
void PrintPreviewAttribute::Dump()
{
PRINT_HILOGD("result_: %{public}s", result_.c_str());
previewRange_.Dump();
}
} // namespace OHOS::Print

View File

@ -0,0 +1,203 @@
/*
* 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.
*/
#include "print_range.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_RANGE_STARTPAGE = "startPage";
static constexpr const char *PARAM_RANGE_ENDPAGE = "endPage";
static constexpr const char *PARAM_RANGE_PAGES = "pages";
PrintRange::PrintRange() : startPage_(0), endPage_(0)
{
pages_.clear();
}
PrintRange::PrintRange(const PrintRange &right)
{
startPage_ = right.startPage_;
endPage_ = right.endPage_;
pages_.clear();
pages_.assign(right.pages_.begin(), right.pages_.end());
}
PrintRange &PrintRange::operator=(const PrintRange &right)
{
if (this != &right) {
startPage_ = right.startPage_;
endPage_ = right.endPage_;
pages_.clear();
pages_.assign(right.pages_.begin(), right.pages_.end());
}
return *this;
}
PrintRange::~PrintRange()
{
pages_.clear();
}
void PrintRange::SetStartPage(uint32_t startpage)
{
startPage_ = startpage;
}
void PrintRange::SetEndPage(uint32_t endpage)
{
endPage_ = endpage;
}
void PrintRange::SetPages(const std::vector<uint32_t> &pages)
{
pages_.clear();
pages_.assign(pages.begin(), pages.end());
}
void PrintRange::Reset()
{
startPage_ = 0;
endPage_ = 0;
pages_.clear();
}
uint32_t PrintRange::GetStartPage() const
{
return startPage_;
}
uint32_t PrintRange::GetEndPage() const
{
return endPage_;
}
void PrintRange::GetPages(std::vector<uint32_t> &pages) const
{
pages.clear();
pages.assign(pages_.begin(), pages_.end());
}
bool PrintRange::ReadFromParcel(Parcel &parcel)
{
SetStartPage(parcel.ReadUint32());
SetEndPage(parcel.ReadUint32());
std::vector<uint32_t> pages;
if (!parcel.ReadUInt32Vector(&pages)) {
PRINT_HILOGE("Failed to read print range object from parcel");
return false;
}
SetPages(pages);
return true;
}
bool PrintRange::Marshalling(Parcel &parcel) const
{
parcel.WriteUint32(GetStartPage());
parcel.WriteUint32(GetEndPage());
if (!parcel.WriteUInt32Vector(pages_)) {
PRINT_HILOGE("Failed to marshalling print range object");
return false;
}
return true;
}
std::shared_ptr<PrintRange> PrintRange::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintRange>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print range object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling print rage");
return nullptr;
}
return nativeObj;
}
napi_value PrintRange::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_RANGE_STARTPAGE, GetStartPage());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_RANGE_ENDPAGE, GetEndPage());
napi_value arrPages = nullptr;
NAPI_CALL(env, napi_create_array(env, &arrPages));
uint32_t arrPagesLength = pages_.size();
for (uint32_t i = 0; i < arrPagesLength; i++) {
napi_value value;
NAPI_CALL(env, napi_create_uint32(env, pages_[i], &value));
NAPI_CALL(env, napi_set_element(env, arrPages, i, value));
}
NAPI_CALL(env, napi_set_named_property(env, jsObj, PARAM_RANGE_PAGES, arrPages));
return jsObj;
}
std::shared_ptr<PrintRange> PrintRange::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrintRange>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print range object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
uint32_t startPage = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_RANGE_STARTPAGE);
uint32_t endPage = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_RANGE_ENDPAGE);
nativeObj->SetStartPage(startPage);
nativeObj->SetEndPage(endPage);
napi_value jsPages = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_RANGE_PAGES);
if (jsPages == nullptr) {
PRINT_HILOGE("invalid pages object");
return nullptr;
}
bool isArray = false;
NAPI_CALL(env, napi_is_array(env, jsPages, &isArray));
std::vector<uint32_t> pages;
if (isArray) {
uint32_t arrayLength = 0;
NAPI_CALL(env, napi_get_array_length(env, jsPages, &arrayLength));
for (uint32_t index = 0; index < arrayLength; index++) {
napi_value jsPage;
uint32_t pageNo;
NAPI_CALL(env, napi_get_element(env, jsPages, index, &jsPage));
NAPI_CALL(env, napi_get_value_uint32(env, jsPage, &pageNo));
pages.push_back(pageNo);
}
nativeObj->SetPages(pages);
}
PRINT_HILOGE("Build Page Range succeed");
return nativeObj;
}
void PrintRange::Dump()
{
PRINT_HILOGD("startPage_ = %{public}d", startPage_);
PRINT_HILOGD("endPage_ = %{public}d", endPage_);
uint32_t pageLength = pages_.size();
for (uint32_t i = 0; i < pageLength; i++) {
PRINT_HILOGD("pages_ = %{public}d", pages_[i]);
}
}
} // namespace OHOS::Print

View File

@ -0,0 +1,143 @@
/*
* 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.
*/
#include "print_resolution.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_RESOLUTION_ID = "id";
static constexpr const char *PARAM_RESOLUTION_HORIZONTALDPI = "horizontalDpi";
static constexpr const char *PARAM_RESOLUTION_VERTICALDPI = "verticalDpi";
PrintResolution::PrintResolution() : id_(""), horizontalDpi_(0), verticalDpi_(0) {
}
PrintResolution::PrintResolution(const PrintResolution &right)
{
SetId(right.id_);
SetHorizontalDpi(right.horizontalDpi_);
SetVerticalDpi(right.verticalDpi_);
}
PrintResolution &PrintResolution::operator=(const PrintResolution &right)
{
if (this != &right) {
SetId(right.id_);
SetHorizontalDpi(right.horizontalDpi_);
SetVerticalDpi(right.verticalDpi_);
}
return *this;
}
PrintResolution::~PrintResolution()
{
}
void PrintResolution::SetId(const std::string &id)
{
id_ = id;
}
void PrintResolution::SetHorizontalDpi(uint32_t horizontalDpi)
{
horizontalDpi_ = horizontalDpi;
}
void PrintResolution::SetVerticalDpi(uint32_t verticalDpi)
{
verticalDpi_ = verticalDpi;
}
const std::string &PrintResolution::GetId() const
{
return id_;
}
uint32_t PrintResolution::GetHorizontalDpi() const
{
return horizontalDpi_;
}
uint32_t PrintResolution::GetVerticalDpi() const
{
return verticalDpi_;
}
bool PrintResolution::ReadFromParcel(Parcel &parcel)
{
SetId(parcel.ReadString());
SetHorizontalDpi(parcel.ReadUint32());
SetVerticalDpi(parcel.ReadUint32());
return true;
}
bool PrintResolution::Marshalling(Parcel &parcel) const
{
parcel.WriteString(GetId());
parcel.WriteUint32(GetHorizontalDpi());
parcel.WriteUint32(GetVerticalDpi());
return true;
}
std::shared_ptr<PrintResolution> PrintResolution::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrintResolution>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print resolution object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling print resolution");
return nullptr;
}
return nativeObj;
}
napi_value PrintResolution::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_RESOLUTION_ID, GetId());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_RESOLUTION_HORIZONTALDPI, GetHorizontalDpi());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_RESOLUTION_VERTICALDPI, GetVerticalDpi());
return jsObj;
}
std::shared_ptr<PrintResolution> PrintResolution::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrintResolution>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create print range object");
return nullptr;
}
std::string id = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_RESOLUTION_ID);
uint32_t horizontalDpi = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_RESOLUTION_HORIZONTALDPI);
uint32_t verticalDpi = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_RESOLUTION_VERTICALDPI);
nativeObj->SetId(id);
nativeObj->SetHorizontalDpi(horizontalDpi);
nativeObj->SetVerticalDpi(verticalDpi);
return nativeObj;
}
void PrintResolution::Dump()
{
PRINT_HILOGD("id_ = %{public}s", id_.c_str());
PRINT_HILOGD("horizontalDpi_ = %{public}d", horizontalDpi_);
PRINT_HILOGD("verticalDpi_ = %{public}d", verticalDpi_);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,29 @@
/*
* 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.
*/
#include "print_sa_death_recipient.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS::Print {
PrintSaDeathRecipient::PrintSaDeathRecipient() {}
void PrintSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
{
PRINT_HILOGE("PrintSaDeathRecipient on remote systemAbility died.");
PrintManagerClient::GetInstance()->OnRemoteSaDied(object);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,489 @@
/*
* 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.
*/
#include "print_service_proxy.h"
#include "iremote_broker.h"
#include "napi_print_utils.h"
#include "print_constant.h"
#include "print_job.h"
#include "print_log.h"
#include "printer_info.h"
namespace OHOS::Print {
using namespace OHOS::HiviewDFX;
PrintServiceProxy::PrintServiceProxy(const sptr<IRemoteObject> &object) : IRemoteProxy<IPrintService>(object) {}
int32_t PrintServiceProxy::StartPrint(const std::vector<std::string> &fileList, std::string &taskId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteStringVector(fileList);
PRINT_HILOGD("PrintServiceProxy StartPrint started.");
int32_t ret = Remote()->SendRequest(CMD_START_PRINT, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("StartPrint, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
taskId = reply.ReadString();
PRINT_HILOGD("PrintServiceProxy StartPrint ret = [%{public}d] TaskId = %{public}s", ret, taskId.c_str());
return ret;
}
int32_t PrintServiceProxy::StopPrint(const std::string &taskId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(taskId);
PRINT_HILOGD("PrintServiceProxy StopPrint started.");
int32_t ret = Remote()->SendRequest(CMD_STOP_PRINT, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("StopPrint, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy StopPrint out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::ConnectPrinter(const std::string &printerId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
PRINT_HILOGD("PrintServiceProxy ConnectPrinter started.");
int32_t ret = Remote()->SendRequest(CMD_CONNECTPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("ConnectPrinter, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy ConnectPrinter out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::DisconnectPrinter(const std::string &printerId)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
PRINT_HILOGD("PrintServiceProxy DisconnectPrinter started.");
int32_t ret = Remote()->SendRequest(CMD_DISCONNECTPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("DisconnectPrinter, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy DisconnectPrinter out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
PRINT_HILOGD("PrintServiceProxy QueryAllExtension started.");
int32_t ret = Remote()->SendRequest(CMD_QUERYALLEXTENSION, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("QueryAllExtension, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
if (ret != ERROR_NONE) {
PRINT_HILOGD("PrintServiceProxy QueryAllExtension Failed.");
return ERROR_SERVER_FAIL;
}
uint32_t len = reply.ReadUint32();
for (uint32_t i = 0; i < len; i++) {
auto infoPtr = PrintExtensionInfo::Unmarshalling(reply);
if (infoPtr == nullptr) {
PRINT_HILOGE("wrong information from data");
return ERROR_GENERIC_FAIL;
}
extensionInfos.emplace_back(*infoPtr);
}
PRINT_HILOGD("PrintServiceProxy QueryAllExtension succeeded.");
return ERROR_NONE;
}
int32_t PrintServiceProxy::StartDiscoverPrinter(const std::vector<std::string> &extensionList)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteStringVector(extensionList);
PRINT_HILOGD("PrintServiceProxy StartDiscoverPrinter started.");
int32_t ret = Remote()->SendRequest(CMD_STARTDISCOVERPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("StartDiscoverPrinter, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy StartDiscoverPrinter out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::StopDiscoverPrinter()
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
PRINT_HILOGD("PrintServiceProxy StopDiscoverPrinter started.");
int32_t ret = Remote()->SendRequest(CMD_STOPDISCOVERPRINTER, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("StopDiscoverPrinter, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy StopDiscoverPrinter out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::StartPrintJob(const PrintJob &jobinfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
jobinfo.Marshalling(data);
PRINT_HILOGD("PrintServiceProxy StartPrintJob started.");
int32_t ret = Remote()->SendRequest(CMD_STARTPRINTJOB, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("StartPrintJob, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy StartPrintJob out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::CancelPrintJob(const PrintJob &jobinfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
jobinfo.Marshalling(data);
PRINT_HILOGD("PrintServiceProxy CancelPrintJob started.");
int32_t ret = Remote()->SendRequest(CMD_CANCELPRINTJOB, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("CancelPrintJob, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy CancelPrintJob out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::AddPrinters(const std::vector<PrinterInfo> &printerInfos)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteUint32(printerInfos.size());
PRINT_HILOGD("AddPrinters printerInfos.size() = %{public}zu", printerInfos.size());
for (uint32_t i = 0; i < printerInfos.size(); i++) {
printerInfos[i].Marshalling(data);
}
PRINT_HILOGD("PrintServiceProxy AddPrinters started.");
int32_t ret = Remote()->SendRequest(CMD_ADDPRINTERS, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("AddPrinters, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy AddPrinters out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::RemovePrinters(const std::vector<std::string> &printerIds)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteStringVector(printerIds);
PRINT_HILOGD("PrintServiceProxy RemovePrinters started.");
int32_t ret = Remote()->SendRequest(CMD_REMOVEPRINTERS, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("RemovePrinters, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy RemovePrinters out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UpdatePrinters(const std::vector<PrinterInfo> &printerInfos)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteUint32(printerInfos.size());
PRINT_HILOGD("UpdatePrinters printerInfos.size() = %{public}zu", printerInfos.size());
for (uint32_t i = 0; i < printerInfos.size(); i++) {
printerInfos[i].Marshalling(data);
}
PRINT_HILOGD("PrintServiceProxy UpdatePrinters started.");
int32_t ret = Remote()->SendRequest(CMD_UPDATEPRINTERS, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("UpdatePrinters, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy UpdatePrinters out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UpdatePrinterState(const std::string &printerId, uint32_t state)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
data.WriteUint32(state);
PRINT_HILOGD("PrintServiceProxy UpdatePrinterState started.");
int32_t ret = Remote()->SendRequest(CMD_UPDATEPRINTERSTATE, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("UpdatePrinterState, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy UpdatePrinterState out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(jobId);
data.WriteUint32(state);
data.WriteUint32(subState);
PRINT_HILOGD("PrintServiceProxy UpdatePrintJobState started.");
int32_t ret = Remote()->SendRequest(CMD_UPDATEPRINTJOBSTATE, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("UpdatePrintJobState, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy UpdatePrintJobState out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(extensionId);
data.WriteString(extInfo);
PRINT_HILOGD("PrintServiceProxy UpdateExtensionInfo started.");
int32_t ret = Remote()->SendRequest(CMD_UPDATEEXTENSIONINFO, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("UpdateExtensionInfo, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy UpdateExtensionInfo out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::RequestPreview(const PrintJob &jobinfo, std::string &previewResult)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
jobinfo.Marshalling(data);
PRINT_HILOGD("PrintServiceProxy RequestPreview started.");
int32_t ret = Remote()->SendRequest(CMD_REQUESTPREVIEW, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("RequestPreview, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
previewResult = reply.ReadString();
PRINT_HILOGD("PrintServiceProxy RequestPreview ret = [%{public}d] previewResult = %{public}s",
ret, previewResult.c_str());
return ret;
}
int32_t PrintServiceProxy::QueryPrinterCapability(const std::string &printerId, PrinterCapability &printerCapability)
{
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
PRINT_HILOGD("PrintServiceProxy QueryPrinterCapability started.");
int32_t ret = Remote()->SendRequest(CMD_QUERYPRINTERCAPABILITY, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("QueryPrinterCapability, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy QueryPrinterCapability out. ret = [%{public}d]", ret);
if (ret == ERROR_NONE) {
auto capPtr = PrinterCapability::Unmarshalling(reply);
if (capPtr == nullptr) {
PRINT_HILOGE("invalid printer capability object");
return ERROR_GENERIC_FAIL;
}
printerCapability = *capPtr;
}
return ret;
}
int32_t PrintServiceProxy::On(const std::string &type, const sptr<IPrintCallback> &listener)
{
PRINT_HILOGD("PrintServiceProxy::On listener=%{public}p", listener.GetRefPtr());
if (listener == nullptr) {
PRINT_HILOGE("listener is nullptr");
return ERROR_INVALID_PARAMETER;
}
if (type.empty()) {
PRINT_HILOGE("PrintServiceProxy::On type is null.");
return ERROR_INVALID_PARAMETER;
}
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(type);
data.WriteRemoteObject(listener->AsObject().GetRefPtr());
int32_t ret = Remote()->SendRequest(CMD_ON, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("On, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy On out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::Off(const std::string &type)
{
PRINT_HILOGD("PrintServiceProxy::Off in");
if (type.empty()) {
PRINT_HILOGE("PrintServiceProxy::On type is null.");
return ERROR_INVALID_PARAMETER;
}
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(type);
int32_t ret = Remote()->SendRequest(CMD_OFF, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("On, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy Off out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::RegisterExtCallback(const std::string extensionCID,
const sptr<IPrintExtensionCallback> &listener)
{
PRINT_HILOGD("PrintServiceProxy::RegisterExtCallback in");
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(extensionCID);
data.WriteRemoteObject(listener->AsObject().GetRefPtr());
int32_t ret = Remote()->SendRequest(CMD_REG_EXT_CB, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("RegisterExtCallback, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy RegisterExtCallback out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::UnregisterAllExtCallback(const std::string &extensionId)
{
PRINT_HILOGD("PrintServiceProxy::UnregisterAllExtCallback in");
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(extensionId);
int32_t ret = Remote()->SendRequest(CMD_UNREG_EXT_CB, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("UnregisterAllExtCallback, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy UnregisterAllExtCallback out. ret = [%{public}d]", ret);
return ret;
}
int32_t PrintServiceProxy::Read(std::vector<uint8_t> &fileRead, const std::string &uri, uint32_t offset, uint32_t max)
{
PRINT_HILOGD("PrintServiceProxy::Read in");
MessageParcel data, reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(uri);
data.WriteUint32(offset);
data.WriteUint32(max);
int32_t ret = Remote()->SendRequest(CMD_READ_DATA, data, reply, option);
if (ret != ERR_NONE) {
PRINT_HILOGE("Read, rpc error code = %{public}d", ret);
return ERROR_RPC_FAIL;
}
ret = reply.ReadInt32();
PRINT_HILOGD("PrintServiceProxy Read out. ret = [%{public}d]", ret);
if (ret == ERROR_NONE) {
reply.ReadUInt8Vector(&fileRead);
PRINT_HILOGD("PrintServiceProxy Read succeeded.");
}
return ret;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,42 @@
/*
* 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.
*/
#include "print_sync_load_callback.h"
#include "iservice_registry.h"
#include "isystem_ability_load_callback.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "system_ability_definition.h"
namespace OHOS::Print {
void PrintSyncLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject> &remoteObject)
{
if (systemAbilityId != PRINT_SERVICE_ID) {
PRINT_HILOGE("start systemAbilityId is not print server");
return;
}
PrintManagerClient::GetInstance()->LoadServerSuccess();
}
void PrintSyncLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId)
{
if (systemAbilityId != PRINT_SERVICE_ID) {
PRINT_HILOGE("start systemAbilityId is not print server");
return;
}
PrintManagerClient::GetInstance()->LoadServerFail();
}
} // namespace OHOS::Print

View File

@ -0,0 +1,320 @@
/*
* 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.
*/
#include "printer_capability.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_CAPABILITY_MINMARGIN = "minMargin";
static constexpr const char *PARAM_CAPABILITY_PAGESIZE = "pageSize";
static constexpr const char *PARAM_CAPABILITY_RESOLUTION = "resolution";
static constexpr const char *PARAM_CAPABILITY_COLORMODE = "colorMode";
static constexpr const char *PARAM_CAPABILITY_DUPLEXMODE = "duplexMode";
PrinterCapability::PrinterCapability() : minMargin_(), colorMode_(0), duplexMode_(0) {
pageSizeList_.clear();
resolutionList_.clear();
}
PrinterCapability::PrinterCapability(const PrinterCapability &right)
{
minMargin_ = right.minMargin_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
SetPageSize(right.pageSizeList_);
SetResolution(right.resolutionList_);
}
PrinterCapability &PrinterCapability::operator=(const PrinterCapability &right)
{
if (this != &right) {
minMargin_ = right.minMargin_;
colorMode_ = right.colorMode_;
duplexMode_ = right.duplexMode_;
SetPageSize(right.pageSizeList_);
SetResolution(right.resolutionList_);
}
return *this;
}
PrinterCapability::~PrinterCapability()
{
}
void PrinterCapability::SetMinMargin(const PrintMargin &minMargin)
{
minMargin_ = minMargin;
}
void PrinterCapability::SetPageSize(const std::vector<PrintPageSize> &pageSizeList)
{
pageSizeList_.clear();
pageSizeList_.assign(pageSizeList.begin(), pageSizeList.end());
}
void PrinterCapability::SetResolution(const std::vector<PrintResolution> &resolutionList)
{
resolutionList_.clear();
resolutionList_.assign(resolutionList.begin(), resolutionList.end());
}
void PrinterCapability::SetColorMode(uint32_t colorMode)
{
colorMode_ = colorMode;
}
void PrinterCapability::SetDuplexMode(uint32_t duplexMode)
{
duplexMode_ = duplexMode;
}
void PrinterCapability::GetMinMargin(PrintMargin &margin) const
{
margin = minMargin_;
}
void PrinterCapability::GetPageSize(std::vector<PrintPageSize> &pageSizeList) const
{
pageSizeList.clear();
pageSizeList.assign(pageSizeList_.begin(), pageSizeList_.end());
}
void PrinterCapability::GetResolution(std::vector<PrintResolution> &resolutionList) const
{
resolutionList.clear();
resolutionList.assign(resolutionList_.begin(), resolutionList_.end());
}
uint32_t PrinterCapability::GetColorMode() const
{
return colorMode_;
}
uint32_t PrinterCapability::GetDuplexMode() const
{
return duplexMode_;
}
bool PrinterCapability::ReadFromParcel(Parcel &parcel)
{
auto marginPtr = PrintMargin::Unmarshalling(parcel);
if (marginPtr == nullptr) {
PRINT_HILOGE("Failed to read page margin from parcel");
return false;
}
SetMinMargin(*marginPtr);
std::vector<PrintPageSize> pageSizeList;
std::vector<PrintResolution> resolutionList;
uint32_t vecSize = parcel.ReadUint32();
for (uint32_t index = 0; index < vecSize; index++) {
auto pageSizePtr = PrintPageSize::Unmarshalling(parcel);
if (pageSizePtr == nullptr) {
PRINT_HILOGE("Failed to read page size from parcel");
return false;
}
pageSizeList.emplace_back(*pageSizePtr);
}
SetPageSize(pageSizeList);
vecSize = parcel.ReadUint32();
for (uint32_t index = 0; index < vecSize; index++) {
auto resolutionPtr = PrintResolution::Unmarshalling(parcel);
if (resolutionPtr == nullptr) {
PRINT_HILOGE("Failed to read print resolution from parcel");
return false;
}
resolutionList.emplace_back(*resolutionPtr);
}
SetResolution(resolutionList);
SetColorMode(parcel.ReadUint32());
SetDuplexMode(parcel.ReadUint32());
return true;
}
bool PrinterCapability::Marshalling(Parcel &parcel) const
{
if (!minMargin_.Marshalling(parcel)) {
return false;
}
uint32_t vecSize = static_cast<uint32_t>(pageSizeList_.size());
parcel.WriteUint32(vecSize);
for (uint32_t index = 0; index < vecSize; index++) {
pageSizeList_[index].Marshalling(parcel);
}
vecSize = static_cast<uint32_t>(resolutionList_.size());
parcel.WriteUint32(vecSize);
for (uint32_t index = 0; index < vecSize; index++) {
resolutionList_[index].Marshalling(parcel);
}
parcel.WriteUint32(GetColorMode());
parcel.WriteUint32(GetDuplexMode());
return true;
}
std::shared_ptr<PrinterCapability> PrinterCapability::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrinterCapability>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create printer capability object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling Printer capability");
return nullptr;
}
return nativeObj;
}
bool PrinterCapability::CreatePageSizeList(napi_env env, napi_value &jsPrinterCap) const
{
napi_value jsPageSizes = nullptr;
NAPI_CALL_BASE(env, napi_create_array(env, &jsPageSizes), false);
uint32_t arrLength = pageSizeList_.size();
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = pageSizeList_[index].ToJsObject(env);
NAPI_CALL_BASE(env, napi_set_element(env, jsPageSizes, index, value), false);
}
NAPI_CALL_BASE(env, napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_PAGESIZE, jsPageSizes), false);
return true;
}
bool PrinterCapability::CreateResolutionList(napi_env env, napi_value &jsPrinterCap) const
{
napi_value jsResolutionList = nullptr;
NAPI_CALL_BASE(env, napi_create_array(env, &jsResolutionList), false);
uint32_t arrLength = resolutionList_.size();
for (uint32_t index = 0; index < arrLength; index++) {
napi_value value = resolutionList_[index].ToJsObject(env);
NAPI_CALL_BASE(env, napi_set_element(env, jsResolutionList, index, value), false);
}
NAPI_CALL_BASE(env,
napi_set_named_property(env, jsPrinterCap, PARAM_CAPABILITY_RESOLUTION, jsResolutionList), false);
return true;
}
napi_value PrinterCapability::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
napi_value jsMargin = minMargin_.ToJsObject(env);
NAPI_CALL(env, napi_set_named_property(env, jsObj, PARAM_CAPABILITY_MINMARGIN, jsMargin));
if (!CreatePageSizeList(env, jsObj)) {
PRINT_HILOGE("Failed to create page size list property of printer capability");
return nullptr;
}
if (!CreateResolutionList(env, jsObj)) {
PRINT_HILOGE("Failed to create resolution list property of printer capability");
return nullptr;
}
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_CAPABILITY_COLORMODE, GetColorMode());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_CAPABILITY_DUPLEXMODE, GetDuplexMode());
return jsObj;
}
std::shared_ptr<PrinterCapability> PrinterCapability::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrinterCapability>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create printer capability object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
napi_value jsMargin = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_MINMARGIN);
auto marginPtr = PrintMargin::BuildFromJs(env, jsMargin);
if (marginPtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return nullptr;
}
nativeObj->SetMinMargin(*marginPtr);
napi_value jsPageSizes = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_PAGESIZE);
bool isArray = false;
napi_is_array(env, jsPageSizes, &isArray);
if (isArray) {
std::vector<PrintPageSize> pageSizes;
uint32_t arrayLength = 0;
napi_get_array_length(env, jsPageSizes, &arrayLength);
for (uint32_t index = 0; index < arrayLength; index++) {
napi_value jsPageSize;
napi_get_element(env, jsPageSizes, index, &jsPageSize);
auto pageSizePtr = PrintPageSize::BuildFromJs(env, jsPageSize);
if (pageSizePtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return nullptr;
}
pageSizes.emplace_back(*pageSizePtr);
}
nativeObj->SetPageSize(pageSizes);
}
napi_value jsResolutionList = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_CAPABILITY_RESOLUTION);
isArray = false;
napi_is_array(env, jsResolutionList, &isArray);
if (isArray) {
std::vector<PrintResolution> resolutionList;
uint32_t arrayLength = 0;
napi_get_array_length(env, jsPageSizes, &arrayLength);
for (uint32_t index = 0; index < arrayLength; index++) {
napi_value jsResolution;
napi_get_element(env, jsResolutionList, index, &jsResolution);
auto resolutionPtr = PrintResolution::BuildFromJs(env, jsResolution);
if (resolutionPtr == nullptr) {
PRINT_HILOGE("Failed to build printer capability object from js");
return nullptr;
}
resolutionList.emplace_back(*resolutionPtr);
}
nativeObj->SetResolution(resolutionList);
}
uint32_t colorMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_CAPABILITY_COLORMODE);
uint32_t duplexMode = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_CAPABILITY_DUPLEXMODE);
nativeObj->SetColorMode(colorMode);
nativeObj->SetDuplexMode(duplexMode);
PRINT_HILOGE("Build Print Capability succeed");
return nativeObj;
}
void PrinterCapability::Dump()
{
PRINT_HILOGD("colorMode_ = %{public}d", colorMode_);
PRINT_HILOGD("duplexMode_ = %{public}d", duplexMode_);
minMargin_.Dump();
auto pageIt = pageSizeList_.begin();
while (pageIt != pageSizeList_.end()) {
pageIt->Dump();
pageIt++;
}
auto resIt = resolutionList_.begin();
while (resIt != resolutionList_.end()) {
resIt->Dump();
resIt++;
}
}
} // namespace OHOS::Print

View File

@ -0,0 +1,277 @@
/*
* 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.
*/
#include "printer_info.h"
#include "napi_print_utils.h"
#include "print_constant.h"
#include "print_log.h"
namespace OHOS::Print {
static constexpr const char *PARAM_INFO_PRINTERID = "printerId";
static constexpr const char *PARAM_INFO_PRINTERNAME = "printerName";
static constexpr const char *PARAM_INFO_PRINTERICON = "printerIcon";
static constexpr const char *PARAM_INFO_PRINTERSTATE = "printerState";
static constexpr const char *PARAM_INFO_DESCRIPTION = "description";
static constexpr const char *PARAM_INFO_CAPABILITY = "capability";
static constexpr const char *PARAM_JOB_OPTION = "option";
PrinterInfo::PrinterInfo() : printerId_(""), printerName_(""), printerIcon_(0), printerState_(PRINTER_UNKNOWN),
description_(""), capability_(nullptr), option_("") {
}
PrinterInfo::PrinterInfo(const PrinterInfo &right)
{
printerId_ = right.printerId_;
printerName_ = right.printerName_;
printerState_ = right.printerState_;
description_ = right.description_;
capability_ = right.capability_;
option_= right.option_;
}
PrinterInfo &PrinterInfo::operator=(const PrinterInfo &right)
{
if (this != &right) {
printerId_ = right.printerId_;
printerName_ = right.printerName_;
printerState_ = right.printerState_;
description_ = right.description_;
capability_ = right.capability_;
option_= right.option_;
}
return *this;
}
PrinterInfo::~PrinterInfo()
{
}
void PrinterInfo::SetPrinterId(const std::string &printerId)
{
printerId_ = printerId;
}
void PrinterInfo::SetPrinterName(std::string printerName)
{
printerName_ = printerName;
}
void PrinterInfo::SetPrinterIcon(uint32_t printIcon)
{
printerIcon_ = printIcon;
}
void PrinterInfo::SetPrinterState(uint32_t printerState)
{
printerState_ = printerState;
}
void PrinterInfo::SetDescription(std::string description)
{
description_ = description;
}
void PrinterInfo::SetCapability(PrinterCapability capability)
{
if (capability_ != nullptr) {
*capability_ = capability;
return;
}
capability_ = std::make_shared<PrinterCapability>(capability);
}
void PrinterInfo::SetOption(const std::string &option)
{
option_ = option;
}
const std::string &PrinterInfo::GetPrinterId() const
{
return printerId_;
}
const std::string &PrinterInfo::GetPrinterName() const
{
return printerName_;
}
uint32_t PrinterInfo::GetPrinterIcon() const
{
return printerIcon_;
}
uint32_t PrinterInfo::GetPrinterState() const
{
return printerState_;
}
const std::string &PrinterInfo::GetDescription() const
{
return description_;
}
void PrinterInfo::GetCapability(PrinterCapability &cap) const
{
cap = *capability_;
}
std::string PrinterInfo::GetOption() const
{
return option_;
}
bool PrinterInfo::ReadFromParcel(Parcel &parcel)
{
SetPrinterId(parcel.ReadString());
SetPrinterName(parcel.ReadString());
SetPrinterIcon(parcel.ReadUint32());
SetPrinterState(parcel.ReadUint32());
SetDescription(parcel.ReadString());
// check capability
if (parcel.ReadBool()) {
capability_ = PrinterCapability::Unmarshalling(parcel);
if (capability_ == nullptr) {
return false;
}
} else {
capability_ = nullptr;
}
// check option
if (parcel.ReadBool()) {
SetOption(parcel.ReadString());
} else {
SetOption("");
}
return true;
}
bool PrinterInfo::Marshalling(Parcel &parcel) const
{
parcel.WriteString(GetPrinterId());
parcel.WriteString(GetPrinterName());
parcel.WriteUint32(GetPrinterIcon());
parcel.WriteUint32(GetPrinterState());
parcel.WriteString(GetDescription());
if (capability_ != nullptr) {
parcel.WriteBool(true);
capability_->Marshalling(parcel);
} else {
parcel.WriteBool(false);
}
if (GetOption() != "") {
parcel.WriteBool(true);
parcel.WriteString(GetOption());
} else {
parcel.WriteBool(false);
}
return true;
}
std::shared_ptr<PrinterInfo> PrinterInfo::Unmarshalling(Parcel &parcel)
{
auto nativeObj = std::make_shared<PrinterInfo>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create printer info object");
return nullptr;
}
if (!nativeObj->ReadFromParcel(parcel)) {
PRINT_HILOGE("Failed to unmarshalling printer info");
return nullptr;
}
return nativeObj;
}
napi_value PrinterInfo::ToJsObject(napi_env env) const
{
napi_value jsObj = nullptr;
NAPI_CALL(env, napi_create_object(env, &jsObj));
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_INFO_PRINTERID, GetPrinterId());
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_INFO_PRINTERNAME, GetPrinterName());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_INFO_PRINTERICON, GetPrinterIcon());
NapiPrintUtils::SetUint32Property(env, jsObj, PARAM_INFO_PRINTERSTATE, GetPrinterState());
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_INFO_DESCRIPTION, GetDescription());
if (capability_ != nullptr) {
napi_value jsCapability = capability_->ToJsObject(env);
NAPI_CALL(env, napi_set_named_property(env, jsObj, PARAM_INFO_CAPABILITY, jsCapability));
}
if (GetOption() != "") {
NapiPrintUtils::SetStringPropertyUtf8(env, jsObj, PARAM_JOB_OPTION, GetOption());
}
return jsObj;
}
std::shared_ptr<PrinterInfo> PrinterInfo::BuildFromJs(napi_env env, napi_value jsValue)
{
auto nativeObj = std::make_shared<PrinterInfo>();
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to create printer info object");
return nullptr;
}
auto names = NapiPrintUtils::GetPropertyNames(env, jsValue);
for (auto name : names) {
PRINT_HILOGD("Property: %{public}s", name.c_str());
}
std::string printerId = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_INFO_PRINTERID);
std::string printerName = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_INFO_PRINTERNAME);
uint32_t printerIcon = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_INFO_PRINTERICON);
uint32_t printerState = NapiPrintUtils::GetUint32Property(env, jsValue, PARAM_INFO_PRINTERSTATE);
std::string description = NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_INFO_DESCRIPTION);
nativeObj->SetPrinterId(printerId);
nativeObj->SetPrinterName(printerName);
nativeObj->SetPrinterIcon(printerIcon);
nativeObj->SetPrinterState(printerState);
nativeObj->SetDescription(description);
napi_value jsCapability = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_INFO_CAPABILITY);
if (jsCapability != nullptr) {
auto capabilityPtr = PrinterCapability::BuildFromJs(env, jsCapability);
if (capabilityPtr == nullptr) {
PRINT_HILOGE("Failed to build printer info object from js");
return nullptr;
}
nativeObj->SetCapability(*capabilityPtr);
}
napi_value jsOption = NapiPrintUtils::GetNamedProperty(env, jsValue, PARAM_JOB_OPTION);
if (jsOption != nullptr) {
nativeObj->SetOption(NapiPrintUtils::GetStringPropertyUtf8(env, jsValue, PARAM_JOB_OPTION));
}
nativeObj->Dump();
return nativeObj;
}
void PrinterInfo::Dump()
{
PRINT_HILOGD("printerId: %{public}s", printerId_.c_str());
PRINT_HILOGD("printerName: %{public}s", printerName_.c_str());
PRINT_HILOGD("printerIcon: %{public}d", printerIcon_);
PRINT_HILOGD("printerState: %{public}d", printerState_);
PRINT_HILOGD("description: %{public}s", description_.c_str());
if (capability_ != nullptr) {
capability_->Dump();
}
if (option_ != "") {
PRINT_HILOGD("option: %{public}s", option_.c_str());
}
}
} // namespace OHOS::Print

View File

@ -0,0 +1,165 @@
# 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("//base/print/print/print.gni")
import("//build/ohos.gni")
ABILITY_RUNTIME_INNERKITS_PATH = "${ability_runtime_inner_api_path}"
config("ability_config") {
visibility = [ ":*" ]
include_dirs = [
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/frameworks/kits/extension/include",
"//base/print/print/utils/include",
"//commonlibrary/c_utils/base/include",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ABILITY_RUNTIME_INNERKITS_PATH}/app_manager/include/appmgr",
"${ABILITY_RUNTIME_INNERKITS_PATH}/ability_manager/include",
"${ability_runtime_services_path}/abilitymgr/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ability_runtime_kits_path}/fmskit/native/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ability_runtime_services_path}/common/include",
#"//foundation/systemabilitymgr/dmsfwk/services/dtbschedmgr/include",
"//base/global/resource_management/interfaces/inner_api/include",
"${ability_runtime_napi_path}/featureAbility",
"//foundation/arkui/napi/interfaces/kits",
"//third_party/node/src",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core/include",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/remote_register_service",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed",
"${ability_runtime_path}/interfaces/kits/native/ability/native/distributed_ability_runtime",
"${ABILITY_RUNTIME_INNERKITS_PATH}/ability_manager/include/continuation",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits",
"${ability_runtime_path}/interfaces/kits/native/appkit/app/task",
"${ability_runtime_napi_path}/inner/napi_common",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"Ability\"",
"LOG_DOMAIN = 0xD002200",
]
}
config("ability_public_config") {
visibility = [ ":*" ]
include_dirs = [
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/frameworks/kits/extension/include",
"${ABILITY_RUNTIME_INNERKITS_PATH}/base/include",
"${ability_runtime_path}/interfaces/kits/native",
"${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app",
"${ability_runtime_path}/interfaces/kits/native/appkit/app",
"${ability_runtime_path}/interfaces/kits/native/ability_runtime",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"//third_party/libuv/include",
"${ability_runtime_path}/interfaces/kits/native/ability_runtime/context",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/remote_register_service",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed",
"${ability_runtime_path}/interfaces/kits/native/ability/native/distributed_ability_runtime",
"${ABILITY_RUNTIME_INNERKITS_PATH}/ability_manager/include/continuation",
"//base/global/resource_management/interfaces/inner_api/include",
"${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits",
"${ability_runtime_kits_path}/fmskit/native/include",
"//third_party/jsoncpp/include",
"//third_party/json/include",
]
}
ohos_shared_library("print_extension") {
include_dirs = [
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/frameworks/kits/extension/include",
"//base/global/i18n/frameworks/intl/include",
]
sources = [
"src/js_print_extension.cpp",
"src/js_print_extension_context.cpp",
"src/print_extension.cpp",
"src/print_extension_context.cpp",
"src/js_print_callback.cpp",
"src/js_print_extension_connection.cpp",
]
configs = [ ":ability_config" ]
public_configs = [
":ability_public_config",
"${ability_runtime_path}/frameworks/native/ability:ability_context_public_config",
]
deps = [
"${ability_runtime_path}/frameworks/native/appkit:app_context",
"//base/print/print/frameworks/innerkitsimpl:print_client",
]
external_deps = [
"ability_base:want",
"ability_runtime:ability_context_native",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"ability_runtime:runtime",
"c_utils:utils",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
"ipc_js:rpc",
]
public_deps = [
"//base/global/i18n/frameworks/intl:intl_util",
"//base/global/resource_management/frameworks/resmgr:global_resmgr",
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//foundation/arkui/napi:ace_napi",
]
subsystem_name = "print"
part_name = "print"
}
ohos_shared_library("print_extension_module") {
include_dirs = [
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime",
]
sources = [ "//base/print/print/frameworks/kits/extension/src/print_extension_module_loader.cpp" ]
configs = [ ":ability_config" ]
public_configs = [ ":ability_public_config" ]
deps = [
":print_extension",
"${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native",
]
external_deps = [
"ability_base:base",
"ability_base:want",
"ability_base:zuri",
"ability_runtime:runtime",
"c_utils:utils",
"hisysevent_native:libhisysevent",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
]
subsystem_name = "print"
part_name = "print"
}

View File

@ -0,0 +1,68 @@
/*
* 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.
*/
#ifndef JS_PRINT_CALLBACK_H
#define JS_PRINT_CALLBACK_H
#include <memory>
#include <mutex>
#include <uv.h>
#include <vector>
#include "napi/native_api.h"
class NativeValue;
class NativeEngine;
namespace OHOS {
namespace AbilityRuntime {
class JsRuntime;
class JsPrintCallback : public std::enable_shared_from_this<JsPrintCallback> {
public:
explicit JsPrintCallback(JsRuntime &jsRutime);
~JsPrintCallback() = default;
NativeValue *Exec(NativeValue *jsObj, const std::string &name, NativeValue *const *argv = nullptr, size_t argc = 0,
bool isSync = true);
private:
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;
NativeValue *jsMethod;
NativeValue *const *argv;
size_t argc;
NativeValue *jsResult;
bool isSync;
bool isCompleted;
};
JsRuntime &jsRuntime_;
uv_work_t *jsWorker_;
JsPrintCallback::JsWorkParam jsParam_;
std::mutex conditionMutex_;
std::condition_variable syncCon_;
static constexpr int SYNC_TIME_OUT = 1000;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_CALLBACK_H

View File

@ -0,0 +1,129 @@
/*
* 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.
*/
#ifndef JS_PRINT_EXTENSION_H
#define JS_PRINT_EXTENSION_H
#include "napi/native_api.h"
#include "print_extension.h"
#include "print_job.h"
class NativeReference;
class NativeValue;
class NativeObject;
namespace OHOS {
namespace AbilityRuntime {
class PrintExtension;
class JsRuntime;
/**
* @brief Basic Print components.
*/
class JsPrintExtension : public PrintExtension, public std::enable_shared_from_this<JsPrintExtension> {
public:
JsPrintExtension(JsRuntime &jsRuntime);
virtual ~JsPrintExtension() override;
/**
* @brief Create JsPrintExtension.
*
* @param runtime The runtime.
* @return The JsPrintExtension instance.
*/
static JsPrintExtension *Create(const std::unique_ptr<Runtime> &runtime);
/**
* @brief Init the extension.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
*/
virtual void Init(const std::shared_ptr<AppExecFwk::AbilityLocalRecord> &record,
const std::shared_ptr<AppExecFwk::OHOSApplication> &application,
std::shared_ptr<AppExecFwk::AbilityHandler> &handler, const sptr<IRemoteObject> &token) override;
/**
* @brief Called when this extension is started. You must override this function if you want to perform some
* initialization operations during extension startup.
*
* This function can be called only once in the entire lifecycle of an extension.
* @param Want Indicates the {@link Want} structure containing startup information about the extension.
*/
virtual void OnStart(const AAFwk::Want &want) override;
/**
* @brief Called when this Print extension is connected for the first time.
*
* You can override this function to implement your own processing logic.
*
* @param want Indicates the {@link Want} structure containing connection information about the Print extension.
* @return Returns a pointer to the <b>sid</b> of the connected Print extension.
*/
virtual sptr<IRemoteObject> OnConnect(const AAFwk::Want &want) override;
/**
* @brief Called when all abilities connected to this Print extension are disconnected.
*
* You can override this function to implement your own processing logic.
*
*/
virtual void OnDisconnect(const AAFwk::Want &want) override;
/**
* @brief Called back when Print is started.
* This method can be called only by Print. You can use the StartAbility(ohos.aafwk.content.Want) method
* to start Print. Then the system calls back the current method to use the transferred want parameter
* to execute its own logic.
*
* @param want Indicates the want of Print to start.
* @param restart Indicates the startup mode. The value true indicates that Print is restarted after being
* destroyed, and the value false indicates a normal startup.
* @param startId Indicates the number of times the Print extension has been started. The startId is incremented
* by 1 every time the extension is started. For example, if the extension has been started for six times, the
* value of startId is 6.
*/
virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override;
/**
* @brief Called when this extension enters the <b>STATE_STOP</b> state.
*
* The extension in the <b>STATE_STOP</b> is being destroyed.
* You can override this function to implement your own processing logic.
*/
virtual void OnStop() override;
private:
NativeValue *CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0);
bool InitExtensionObj(JsRuntime &jsRuntime);
bool InitContextObj(JsRuntime &jsRuntime, NativeObject *&extObj, std::string &extensionId);
void RegisterDiscoveryCb();
void RegisterConnectionCb();
void RegisterPrintJobCb();
void RegisterPreviewCb();
void RegisterQueryCapCb();
void GetSrcPath(std::string &srcPath);
JsRuntime &jsRuntime_;
std::unique_ptr<NativeReference> jsObj_;
static JsPrintExtension *jsExtension_;
std::string extensionId_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_EXTENSION_H

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JS_PRINT_EXTENSION_CONNECTION_H
#define JS_PRINT_EXTENSION_CONNECTION_H
#include <memory>
#include "ability_connect_callback.h"
#include "print_extension_context.h"
#include "event_handler.h"
class NativeEngine;
class NativeValue;
class NativeReference;
namespace OHOS {
namespace AbilityRuntime {
class JSPrintExtensionConnection : public AbilityConnectCallback {
public:
explicit JSPrintExtensionConnection(NativeEngine& engine);
~JSPrintExtensionConnection();
void OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override;
void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override;
void HandleOnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode);
void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode);
void SetJsConnectionObject(NativeValue* jsConnectionObject);
void CallJsFailed(int32_t errorCode);
private:
NativeEngine& engine_;
std::unique_ptr<NativeReference> jsConnectionObject_ = nullptr;
};
struct ConnecttionKey {
AAFwk::Want want;
int64_t id;
};
struct key_compare {
bool operator()(const ConnecttionKey &key1, const ConnecttionKey &key2) const
{
if (key1.id < key2.id) {
return true;
}
return false;
}
};
static std::map<ConnecttionKey, sptr<JSPrintExtensionConnection>, key_compare> connects_;
static int64_t serialNumber_ = 0;
static std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_EXTENSION_CONNECTION_H

View File

@ -0,0 +1,35 @@
/*
* 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.
*/
#ifndef JS_PRINT_EXTENSION_CONTEXT_H
#define JS_PRINT_EXTENSION_CONTEXT_H
#include <memory>
#include "ability_connect_callback.h"
#include "event_handler.h"
#include "print_extension_context.h"
class NativeEngine;
class NativeValue;
class NativeReference;
namespace OHOS {
namespace AbilityRuntime {
NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine,
std::shared_ptr<PrintExtensionContext> context, std::string &extensionId);
} // namespace AbilityRuntime
} // namespace OHOS
#endif // JS_PRINT_EXTENSION_CONTEXT_H

View File

@ -0,0 +1,69 @@
/*
* 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.
*/
#ifndef PRINT_EXTENSION_H
#define PRINT_EXTENSION_H
#include "extension_base.h"
namespace OHOS {
namespace AbilityRuntime {
class PrintExtensionContext;
class Runtime;
/**
* @brief Basic Print components.
*/
class PrintExtension : public ExtensionBase<PrintExtensionContext>,
public std::enable_shared_from_this<PrintExtension> {
public:
PrintExtension() = default;
virtual ~PrintExtension() = default;
/**
* @brief Create and init context.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
* @return The created context.
*/
virtual std::shared_ptr<PrintExtensionContext> CreateAndInitContext(
const std::shared_ptr<AbilityLocalRecord> &record, const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token) override;
/**
* @brief Init the extension.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
*/
virtual void Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token) override;
/**
* @brief Create Extension.
*
* @param runtime The runtime.
* @return The PrintExtension instance.
*/
static PrintExtension *Create(const std::unique_ptr<Runtime> &runtime);
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // PRINT_EXTENSION_H

View File

@ -0,0 +1,129 @@
/*
* 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.
*/
#ifndef PRINT_EXTENSION_CONTEXT_H
#define PRINT_EXTENSION_CONTEXT_H
#include "ability_connect_callback.h"
#include "connection_manager.h"
#include "extension_context.h"
#include "start_options.h"
#include "want.h"
namespace OHOS {
namespace AbilityRuntime {
/**
* @brief context supply for Print
*
*/
class PrintExtensionContext : public ExtensionContext {
public:
PrintExtensionContext() = default;
virtual ~PrintExtensionContext() = default;
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.Print or AbilityInfo.AbilityType.PAGE template uses this method
* to start a specific ability. The system locates the target ability from installed abilities based on the value
* of the want parameter and then starts it. You can specify the ability to start using the want parameter.
*
* @param want Indicates the Want containing information about the target ability to start.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode StartAbility(const AAFwk::Want &want) const;
ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const;
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.Print template.
*
* @param want Indicates the want containing information about the ability to connect
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure
*/
bool ConnectAbility(const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const;
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.Print or AbilityInfo.AbilityType.PAGE template uses this method
* to start a specific ability. The system locates the target ability from installed abilities based on the value
* of the want parameter and then starts it. You can specify the ability to start using the want parameter.
*
* @param want Indicates the Want containing information about the target ability to start.
* @param accountId caller user.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode StartAbilityWithAccount(const AAFwk::Want &want, int accountId) const;
ErrCode StartAbilityWithAccount(
const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions) const;
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.Print template.
*
* @param want Indicates the want containing information about the ability to connect.
*
* @param accountId caller user.
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure.
*/
bool ConnectAbilityWithAccount(
const AAFwk::Want &want, int accountId, const sptr<AbilityConnectCallback> &connectCallback) const;
/**
* @brief Disconnects the current ability from an ability.
*
* @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
* is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode DisconnectAbility(const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const;
/**
* @brief Destroys the current ability.
*
* @return errCode ERR_OK on success, others on failure.
*/
ErrCode TerminateAbility();
using SelfType = PrintExtensionContext;
static const size_t CONTEXT_TYPE_ID;
protected:
bool IsContext(size_t contextTypeId) override
{
return contextTypeId == CONTEXT_TYPE_ID || ExtensionContext::IsContext(contextTypeId);
}
private:
static int ILLEGAL_REQUEST_CODE;
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // PRINT_EXTENSION_CONTEXT_H

View File

@ -0,0 +1,36 @@
/*
* 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.
*/
#ifndef PRINT_EXTENSION_MODULE_LOADER_H
#define PRINT_EXTENSION_MODULE_LOADER_H
#include "extension_module_loader.h"
namespace OHOS::AbilityRuntime {
class PrintExtensionModuleLoader : public ExtensionModuleLoader, public Singleton<PrintExtensionModuleLoader> {
DECLARE_SINGLETON(PrintExtensionModuleLoader);
public:
/**
* @brief Create Extension.
*
* @param runtime The runtime.
* @return The Extension instance.
*/
virtual Extension *Create(const std::unique_ptr<Runtime> &runtime) const override;
virtual std::map<std::string, std::string> GetParams() override;
};
} // namespace OHOS::AbilityRuntime
#endif // PRINT_EXTENSION_MODULE_LOADER_H

View File

@ -0,0 +1,127 @@
/*
* 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.
*/
#include "js_print_callback.h"
#include "ability_info.h"
#include "iprint_extension_callback.h"
#include "js_print_extension_context.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_print_utils.h"
#include "napi_remote_object.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS {
namespace AbilityRuntime {
using namespace OHOS::AppExecFwk;
using namespace OHOS::Print;
JsPrintCallback::JsPrintCallback(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {}
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)
{
NativeObject *obj = ConvertNativeValueTo<NativeObject>(jsObj);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
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 false;
}
jsWorker_ = new (std::nothrow) uv_work_t;
if (jsWorker_ == nullptr) {
PRINT_HILOGE("Failed to create uv work");
return false;
}
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)
{
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 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(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 jsParam_.isCompleted; });
if (!waitStatus) {
PRINT_HILOGE("print server load sa timeout");
return nullptr;
}
return jsParam_.jsResult;
}
return nullptr;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,450 @@
/*
* 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.
*/
#include "js_print_extension.h"
#include "ability_info.h"
#include "iprint_extension_callback.h"
#include "js_print_callback.h"
#include "js_print_extension_context.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_print_utils.h"
#include "napi_remote_object.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;
JsPrintExtension *JsPrintExtension::Create(const std::unique_ptr<Runtime> &runtime)
{
PRINT_HILOGD("jws JsPrintExtension begin Create");
jsExtension_ = new JsPrintExtension(static_cast<JsRuntime &>(*runtime));
return jsExtension_;
}
JsPrintExtension::JsPrintExtension(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime), extensionId_("") {}
JsPrintExtension::~JsPrintExtension() = default;
void JsPrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
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, extensionId_)) {
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, std::string &extensionId)
{
auto context = GetContext();
if (context == nullptr) {
PRINT_HILOGE("Failed to get context");
return false;
}
PRINT_HILOGD("CreateJsPrintExtensionContext.");
auto &engine = jsRuntime.GetNativeEngine();
NativeValue *contextObj = CreateJsPrintExtensionContext(engine, context, extensionId);
auto shellContextRef = jsRuntime.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE);
contextObj = shellContextRef->Get();
PRINT_HILOGD("JsPrintExtension::Init Bind.");
context->Bind(jsRuntime, shellContextRef.release());
PRINT_HILOGD("JsPrintExtension::SetProperty.");
extObj->SetProperty("context", contextObj);
auto nativeObj = ConvertNativeValueTo<NativeObject>(contextObj);
if (nativeObj == nullptr) {
PRINT_HILOGE("Failed to get Print extension native object");
return false;
}
PRINT_HILOGD("Set Print extension context pointer: %{public}p", context.get());
nativeObj->SetNativePointer(
new std::weak_ptr<AbilityRuntime::Context>(context),
[](NativeEngine *, void *data, void *) {
PRINT_HILOGD("Finalizer for weak_ptr Print extension context is called");
delete static_cast<std::weak_ptr<AbilityRuntime::Context> *>(data);
},
nullptr);
return true;
}
void JsPrintExtension::OnStart(const AAFwk::Want &want)
{
Extension::OnStart(want);
PRINT_HILOGD("jws JsPrintExtension OnStart begin..");
HandleScope handleScope(jsRuntime_);
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(nativeEngine), 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__);
}
void JsPrintExtension::OnStop()
{
PrintExtension::OnStop();
PRINT_HILOGD("jws JsPrintExtension OnStop begin.");
CallObjectMethod("onDestroy");
bool ret = ConnectionManager::GetInstance().DisconnectCaller(GetContext()->GetToken());
if (ret) {
PRINT_HILOGD("The Print extension connection is not disconnected.");
}
PRINT_HILOGD("%{public}s end.", __func__);
}
sptr<IRemoteObject> JsPrintExtension::OnConnect(const AAFwk::Want &want)
{
PRINT_HILOGD("jws JsPrintExtension OnConnect begin.");
Extension::OnConnect(want);
PRINT_HILOGD("%{public}s begin.", __func__);
HandleScope handleScope(jsRuntime_);
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(nativeEngine), want);
NativeValue *nativeWant = reinterpret_cast<NativeValue *>(napiWant);
NativeValue *argv[] = { nativeWant };
if (!jsObj_) {
PRINT_HILOGW("Not found PrintExtension.js");
return nullptr;
}
NativeValue *value = jsObj_->Get();
NativeObject *obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return nullptr;
}
NativeValue *method = obj->GetProperty("onConnect");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onConnect from PrintExtension object");
return nullptr;
}
PRINT_HILOGD("JsPrintExtension::CallFunction onConnect, success");
NativeValue *remoteNative = nativeEngine->CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
if (remoteNative == nullptr) {
PRINT_HILOGE("remoteNative nullptr.");
}
auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject(
reinterpret_cast<napi_env>(nativeEngine), reinterpret_cast<napi_value>(remoteNative));
if (remoteObj == nullptr) {
PRINT_HILOGE("remoteObj nullptr.");
}
return remoteObj;
}
void JsPrintExtension::OnDisconnect(const AAFwk::Want &want)
{
PRINT_HILOGD("jws JsPrintExtension OnDisconnect begin.");
Extension::OnDisconnect(want);
PRINT_HILOGD("%{public}s begin.", __func__);
HandleScope handleScope(jsRuntime_);
NativeEngine *nativeEngine = &jsRuntime_.GetNativeEngine();
napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(nativeEngine), want);
NativeValue *nativeWant = reinterpret_cast<NativeValue *>(napiWant);
NativeValue *argv[] = { nativeWant };
if (!jsObj_) {
PRINT_HILOGW("Not found PrintExtension.js");
return;
}
NativeValue *value = jsObj_->Get();
NativeObject *obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return;
}
NativeValue *method = obj->GetProperty("onDisconnect");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onDisconnect from PrintExtension object");
return;
}
nativeEngine->CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
PRINT_HILOGD("%{public}s end.", __func__);
}
void JsPrintExtension::OnCommand(const AAFwk::Want &want, bool restart, int startId)
{
PRINT_HILOGD("jws JsPrintExtension OnCommand begin.");
Extension::OnCommand(want, restart, startId);
PRINT_HILOGD(
"%{public}s begin restart=%{public}s,startId=%{public}d.", __func__, restart ? "true" : "false", startId);
PRINT_HILOGD("%{public}s end.", __func__);
}
NativeValue *JsPrintExtension::CallObjectMethod(const char *name, NativeValue *const *argv, size_t argc)
{
PRINT_HILOGD("jws JsPrintExtension::CallObjectMethod(%{public}s), begin", name);
if (!jsObj_) {
PRINT_HILOGW("Not found PrintExtension.js");
return nullptr;
}
HandleScope handleScope(jsRuntime_);
auto &nativeEngine = jsRuntime_.GetNativeEngine();
NativeValue *value = jsObj_->Get();
NativeObject *obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get PrintExtension object");
return nullptr;
}
NativeValue *method = obj->GetProperty(name);
if (method == nullptr) {
PRINT_HILOGE("Failed to get '%{public}s' from PrintExtension object", name);
return nullptr;
}
PRINT_HILOGD("JsPrintExtension::CallFunction(%{public}s), success", name);
return nativeEngine.CallFunction(value, method, argv, argc);
}
void JsPrintExtension::GetSrcPath(std::string &srcPath)
{
PRINT_HILOGD("jws JsPrintExtension GetSrcPath begin.");
if (!Extension::abilityInfo_->isModuleJson) {
/* temporary compatibility api8 + config.json */
srcPath.append(Extension::abilityInfo_->package);
srcPath.append("/assets/js/");
if (!Extension::abilityInfo_->srcPath.empty()) {
srcPath.append(Extension::abilityInfo_->srcPath);
}
srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc");
return;
}
if (!Extension::abilityInfo_->srcEntrance.empty()) {
srcPath.append(Extension::abilityInfo_->moduleName + "/");
srcPath.append(Extension::abilityInfo_->srcEntrance);
srcPath.erase(srcPath.rfind('.'));
srcPath.append(".abc");
}
}
void JsPrintExtension::RegisterDiscoveryCb()
{
PRINT_HILOGD("Register Print Extension Callback");
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_START_DISCOVERY,
[]() -> bool {
PRINT_HILOGD("Start Print Discovery");
HandleScope handleScope(jsExtension_->jsRuntime_);
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onStartDiscoverPrinter");
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_STOP_DISCOVERY,
[]() -> bool {
PRINT_HILOGD("Stop Print Discovery");
HandleScope handleScope(jsExtension_->jsRuntime_);
auto callback = std::make_shared<JsPrintCallback>(jsExtension_->jsRuntime_);
NativeValue *value = jsExtension_->jsObj_->Get();
callback->Exec(value, "onStopDiscoverPrinter");
return true;
});
}
void JsPrintExtension::RegisterConnectionCb()
{
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_CONNECT_PRINTER,
[](const std::string &printId) -> bool {
PRINT_HILOGD("Connect Printer");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jsPrintId =
OHOS::AppExecFwk::WrapStringToJS(reinterpret_cast<napi_env>(nativeEng), 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, "onConnectPrinter", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_DISCONNECT_PRINTER,
[](const std::string &printId) -> bool {
PRINT_HILOGD("Disconnect Printer");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jsPrintId =
OHOS::AppExecFwk::WrapStringToJS(reinterpret_cast<napi_env>(nativeEng), 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::RegisterPrintJobCb()
{
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_START_PRINT,
[](const PrintJob &job) -> bool {
PRINT_HILOGD("Start Print Job");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jobObject = job.ToJsObject(reinterpret_cast<napi_env>(nativeEng));
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, "onStartPrintJob", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_CANCEL_PRINT,
[](const PrintJob &job) -> bool {
PRINT_HILOGD("Cancel Print Job");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jobObject = job.ToJsObject(reinterpret_cast<napi_env>(nativeEng));
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, "onCancelPrintJob", arg, NapiPrintUtils::ARGC_ONE);
return true;
});
}
void JsPrintExtension::RegisterPreviewCb()
{
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_REQUEST_PREVIEW,
[](const PrintJob &job) -> bool {
PRINT_HILOGD("Requet preview");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jobObject = job.ToJsObject(reinterpret_cast<napi_env>(nativeEng));
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);
return true;
});
}
void JsPrintExtension::RegisterQueryCapCb()
{
PrintManagerClient::GetInstance()->RegisterExtCallback(extensionId_, PRINT_EXTCB_REQUEST_CAP,
[](const std::string &printId, PrinterCapability &cap) -> bool {
PRINT_HILOGD("Request Capability");
HandleScope handleScope(jsExtension_->jsRuntime_);
NativeEngine *nativeEng = &(jsExtension_->jsRuntime_).GetNativeEngine();
napi_value jsPrintId =
OHOS::AppExecFwk::WrapStringToJS(reinterpret_cast<napi_env>(nativeEng), 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.SetColorMode(10);
cap.SetDuplexMode(11);
PrintMargin PrintMargin;
PrintMargin.SetTop(5);
PrintMargin.SetBottom(5);
PrintMargin.SetLeft(5);
PrintMargin.SetRight(5);
cap.SetMinMargin(PrintMargin);
std::vector<PrintPageSize> pageSizeList;
PrintPageSize pageSize;
pageSize.SetId("6");
pageSize.SetName("name");
pageSize.SetWidth(6);
pageSize.SetHeight(6);
pageSizeList.emplace_back(pageSize);
cap.SetPageSize(pageSizeList);
std::vector<PrintResolution> resolutionList;
PrintResolution res;
res.SetId("6");
res.SetHorizontalDpi(6);
res.SetVerticalDpi(6);
resolutionList.emplace_back(res);
cap.SetResolution(resolutionList);
return true;
}
PRINT_HILOGD("Request Capability Failed!!!");
return false;
});
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,185 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "js_print_extension_connection.h"
#include "js_extension_context.h"
#include "js_data_struct_converter.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi_common_want.h"
#include "napi_common_util.h"
#include "napi_remote_object.h"
#include "napi_common_start_options.h"
#include "start_options.h"
#include "napi_print_utils.h"
#include "print_log.h"
using namespace OHOS::Print;
namespace OHOS {
namespace AbilityRuntime {
JSPrintExtensionConnection::JSPrintExtensionConnection(NativeEngine& engine) : engine_(engine) {}
JSPrintExtensionConnection::~JSPrintExtensionConnection() = default;
void JSPrintExtensionConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &element,
const sptr<IRemoteObject> &remoteObject, int resultCode)
{
PRINT_HILOGD("OnAbilityConnectDone begin, resultCode:%{public}d", resultCode);
if (handler_ == nullptr) {
PRINT_HILOGD("handler_ nullptr");
return;
}
wptr<JSPrintExtensionConnection> connection = this;
auto task = [connection, element, remoteObject, resultCode]() {
sptr<JSPrintExtensionConnection> connectionSptr = connection.promote();
if (!connectionSptr) {
PRINT_HILOGD("connectionSptr nullptr");
return;
}
connectionSptr->HandleOnAbilityConnectDone(element, remoteObject, resultCode);
};
handler_->PostTask(task, "OnAbilityConnectDone");
}
void JSPrintExtensionConnection::HandleOnAbilityConnectDone(const AppExecFwk::ElementName &element,
const sptr<IRemoteObject> &remoteObject, int resultCode)
{
PRINT_HILOGD("HandleOnAbilityConnectDone begin, resultCode:%{public}d", resultCode);
// wrap ElementName
napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast<napi_env>(&engine_), element);
NativeValue* nativeElementName = reinterpret_cast<NativeValue*>(napiElementName);
// wrap RemoteObject
PRINT_HILOGD("OnAbilityConnectDone begin NAPI_ohos_rpc_CreateJsRemoteObject");
napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(
reinterpret_cast<napi_env>(&engine_), remoteObject);
NativeValue* nativeRemoteObject = reinterpret_cast<NativeValue*>(napiRemoteObject);
NativeValue* argv[] = {nativeElementName, nativeRemoteObject};
if (jsConnectionObject_ == nullptr) {
PRINT_HILOGE("jsConnectionObject_ nullptr");
return;
}
NativeValue* value = jsConnectionObject_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get object");
return;
}
NativeValue* methodOnConnect = obj->GetProperty("onConnect");
if (methodOnConnect == nullptr) {
PRINT_HILOGE("Failed to get onConnect from object");
return;
}
PRINT_HILOGD("JSPrintExtensionConnection::CallFunction onConnect, success");
engine_.CallFunction(value, methodOnConnect, argv, NapiPrintUtils::ARGC_TWO);
PRINT_HILOGD("OnAbilityConnectDone end");
}
void JSPrintExtensionConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode)
{
PRINT_HILOGD("OnAbilityDisconnectDone begin, resultCode:%{public}d", resultCode);
if (handler_ == nullptr) {
PRINT_HILOGD("handler_ nullptr");
return;
}
wptr<JSPrintExtensionConnection> connection = this;
auto task = [connection, element, resultCode]() {
sptr<JSPrintExtensionConnection> connectionSptr = connection.promote();
if (!connectionSptr) {
PRINT_HILOGD("connectionSptr nullptr");
return;
}
connectionSptr->HandleOnAbilityDisconnectDone(element, resultCode);
};
handler_->PostTask(task, "OnAbilityDisconnectDone");
}
void JSPrintExtensionConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element,
int resultCode)
{
PRINT_HILOGD("HandleOnAbilityDisconnectDone begin, resultCode:%{public}d", resultCode);
napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast<napi_env>(&engine_), element);
NativeValue* nativeElementName = reinterpret_cast<NativeValue*>(napiElementName);
NativeValue* argv[] = {nativeElementName};
if (jsConnectionObject_ == nullptr) {
PRINT_HILOGE("jsConnectionObject_ nullptr");
return;
}
NativeValue* value = jsConnectionObject_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get object");
return;
}
NativeValue* method = obj->GetProperty("onDisconnect");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onDisconnect from object");
return;
}
// release connect
PRINT_HILOGD("OnAbilityDisconnectDone connects_.size:%{public}zu", connects_.size());
std::string bundleName = element.GetBundleName();
std::string abilityName = element.GetAbilityName();
auto item = std::find_if(connects_.begin(),
connects_.end(),
[bundleName, abilityName](
const std::map<ConnecttionKey, sptr<JSPrintExtensionConnection>>::value_type &obj) {
return (bundleName == obj.first.want.GetBundle()) &&
(abilityName == obj.first.want.GetElement().GetAbilityName());
});
if (item != connects_.end()) {
// match bundlename && abilityname
connects_.erase(item);
PRINT_HILOGD("OnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size());
}
PRINT_HILOGD("OnAbilityDisconnectDone CallFunction success");
engine_.CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
}
void JSPrintExtensionConnection::SetJsConnectionObject(NativeValue* jsConnectionObject)
{
jsConnectionObject_ = std::unique_ptr<NativeReference>(engine_.CreateReference(jsConnectionObject, 1));
}
void JSPrintExtensionConnection::CallJsFailed(int32_t errorCode)
{
PRINT_HILOGD("CallJsFailed begin");
if (jsConnectionObject_ == nullptr) {
PRINT_HILOGE("jsConnectionObject_ nullptr");
return;
}
NativeValue* value = jsConnectionObject_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
PRINT_HILOGE("Failed to get object");
return;
}
NativeValue* method = obj->GetProperty("onFailed");
if (method == nullptr) {
PRINT_HILOGE("Failed to get onFailed from object");
return;
}
NativeValue* argv[] = {engine_.CreateNumber(errorCode)};
PRINT_HILOGD("CallJsFailed CallFunction success");
engine_.CallFunction(value, method, argv, NapiPrintUtils::ARGC_ONE);
PRINT_HILOGD("CallJsFailed end");
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,509 @@
/*
* 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.
*/
#include "js_print_extension_context.h"
#include "js_data_struct_converter.h"
#include "js_extension_context.h"
#include "js_print_extension_connection.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi_common_start_options.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_print_utils.h"
#include "napi_remote_object.h"
#include "print_log.h"
#include "start_options.h"
using namespace OHOS::Print;
namespace OHOS {
namespace AbilityRuntime {
class JsPrintExtensionContext final {
public:
explicit JsPrintExtensionContext(const std::shared_ptr<PrintExtensionContext>& context) : context_(context) {}
~JsPrintExtensionContext() = default;
static void Finalizer(NativeEngine *engine, void *data, void *hint)
{
PRINT_HILOGD("JsAbilityContext::Finalizer is called");
std::unique_ptr<JsPrintExtensionContext>(static_cast<JsPrintExtensionContext*>(data));
}
static NativeValue *StartAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext* me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr;
}
static NativeValue *StartAbilityWithAccount(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext* me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnStartAbilityWithAccount(*engine, *info) : nullptr;
}
static NativeValue *ConnectAbilityWithAccount(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext* me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnConnectAbilityWithAccount(*engine, *info) : nullptr;
}
static NativeValue *TerminateAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext* me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnTerminateAbility(*engine, *info) : nullptr;
}
static NativeValue *ConnectAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext* me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnConnectAbility(*engine, *info) : nullptr;
}
static NativeValue *DisconnectAbility(NativeEngine *engine, NativeCallbackInfo *info)
{
JsPrintExtensionContext* me = CheckParamsAndGetThis<JsPrintExtensionContext>(engine, info);
return (me != nullptr) ? me->OnDisconnectAbility(*engine, *info) : nullptr;
}
private:
std::weak_ptr<PrintExtensionContext> context_;
NativeValue *OnStartAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnStartAbility is called");
// only support one or two or three params
if (info.argc != NapiPrintUtils::ARGC_ONE && info.argc != NapiPrintUtils::ARGC_TWO &&
info.argc != NapiPrintUtils::ARGC_THREE) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
decltype(info.argc) unwrapArgc = 0;
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(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());
unwrapArgc++;
AAFwk::StartOptions startOptions;
if (info.argc > NapiPrintUtils::ARGC_ONE && info.argv[NapiPrintUtils::INDEX_ONE]->TypeOf() == NATIVE_OBJECT) {
PRINT_HILOGD("OnStartAbility start options is used.");
AppExecFwk::UnwrapStartOptions(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ONE]), startOptions);
unwrapArgc++;
}
AsyncTask::CompleteCallback complete = [weak = context_, want, startOptions, unwrapArgc](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("startAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
ErrCode errcode = ERR_OK;
(unwrapArgc == 1) ? errcode = context->StartAbility(want)
: errcode = context->StartAbility(want, startOptions);
if (errcode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed."));
}
};
NativeValue *lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnStartAbility", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
NativeValue *CheckInfo(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnStartAbilityWithAccount is called");
// only support two or three or four params
if (info.argc != NapiPrintUtils::ARGC_TWO && info.argc != NapiPrintUtils::ARGC_THREE &&
info.argc != NapiPrintUtils::ARGC_FOUR) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
return nullptr;
}
NativeValue *OnStartAbilityWithAccount(NativeEngine &engine, NativeCallbackInfo &info)
{
CheckInfo(engine, info);
decltype(info.argc) unwrapArgc = 0;
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(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());
unwrapArgc++;
int32_t accountId = 0;
if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ONE]), accountId)) {
PRINT_HILOGD("%{public}s called, the second parameter is invalid.", __func__);
return engine.CreateUndefined();
}
PRINT_HILOGD("%{public}d accountId:", accountId);
unwrapArgc++;
AAFwk::StartOptions startOptions;
if (info.argc > NapiPrintUtils::ARGC_TWO && info.argv[NapiPrintUtils::INDEX_TWO]->TypeOf() == NATIVE_OBJECT) {
PRINT_HILOGD("OnStartAbilityWithAccount start options is used.");
AppExecFwk::UnwrapStartOptions(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_TWO]), startOptions);
unwrapArgc++;
}
AsyncTask::CompleteCallback complete = [weak = context_, want, accountId, startOptions, unwrapArgc](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("startAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
ErrCode errcode = ERR_OK;
(unwrapArgc == NapiPrintUtils::ARGC_TWO)
? errcode = context->StartAbilityWithAccount(want, accountId)
: errcode = context->StartAbilityWithAccount(want, accountId, startOptions);
if (errcode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed."));
}
};
NativeValue *lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnStartAbilityWithAccount", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
NativeValue *OnTerminateAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnTerminateAbility is called");
// only support one or zero params
if (info.argc != NapiPrintUtils::ARGC_ZERO && info.argc != NapiPrintUtils::ARGC_ONE) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
AsyncTask::CompleteCallback complete = [weak = context_](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("TerminateAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
auto errcode = context->TerminateAbility();
if (errcode == 0) {
task.Resolve(engine, engine.CreateUndefined());
} else {
task.Reject(engine, CreateJsError(engine, errcode, "Terminate Ability failed."));
}
};
NativeValue *lastParam =
(info.argc == NapiPrintUtils::ARGC_ZERO) ? nullptr : info.argv[NapiPrintUtils::INDEX_ZERO];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnTerminateAbility", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
NativeValue *OnConnectAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnConnectAbility is called");
// only support two params
if (info.argc != NapiPrintUtils::ARGC_TWO) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
// unwrap want
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(
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
sptr<JSPrintExtensionConnection> connection = new JSPrintExtensionConnection(engine);
connection->SetJsConnectionObject(info.argv[1]);
int64_t connectId = serialNumber_;
ConnecttionKey key;
key.id = serialNumber_;
key.want = want;
connects_.emplace(key, connection);
if (serialNumber_ < INT64_MAX) {
serialNumber_++;
} else {
serialNumber_ = 0;
}
PRINT_HILOGD("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr());
AsyncTask::CompleteCallback complete = [weak = context_, want, connection, connectId](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("OnConnectAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("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(NapiPrintUtils::ERROR_CODE_ONE);
}
task.Resolve(engine, engine.CreateUndefined());
};
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnConnectAbility", engine,
CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result));
return engine.CreateNumber(connectId);
}
NativeValue *OnConnectAbilityWithAccount(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnConnectAbilityWithAccount is called");
// only support three params
if (info.argc != NapiPrintUtils::ARGC_THREE) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
// unwrap want
AAFwk::Want want;
OHOS::AppExecFwk::UnwrapWant(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());
int32_t accountId = 0;
if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ONE]), accountId)) {
PRINT_HILOGD("%{public}s called, the second parameter is invalid.", __func__);
return engine.CreateUndefined();
}
// unwarp connection
sptr<JSPrintExtensionConnection> connection = new JSPrintExtensionConnection(engine);
connection->SetJsConnectionObject(info.argv[1]);
int64_t connectId = serialNumber_;
ConnecttionKey key;
key.id = serialNumber_;
key.want = want;
connects_.emplace(key, connection);
if (serialNumber_ < INT64_MAX) {
serialNumber_++;
} else {
serialNumber_ = 0;
}
PRINT_HILOGD("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr());
AsyncTask::CompleteCallback complete = [weak = context_, want, accountId, connection, connectId](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("OnConnectAbilityWithAccount begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("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(NapiPrintUtils::ERROR_CODE_ONE);
}
task.Resolve(engine, engine.CreateUndefined());
};
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnConnectAbilityWithAccount", engine,
CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result));
return engine.CreateNumber(connectId);
}
NativeValue *OnDisconnectAbility(NativeEngine &engine, NativeCallbackInfo &info)
{
PRINT_HILOGD("OnDisconnectAbility is called");
// only support one or two params
if (info.argc != NapiPrintUtils::ARGC_ONE && info.argc != NapiPrintUtils::ARGC_TWO) {
PRINT_HILOGE("Not enough params");
return engine.CreateUndefined();
}
// unwrap want
AAFwk::Want want;
// unwrap connectId
int64_t connectId = -1;
sptr<JSPrintExtensionConnection> connection = nullptr;
napi_get_value_int64(reinterpret_cast<napi_env>(&engine),
reinterpret_cast<napi_value>(info.argv[NapiPrintUtils::INDEX_ZERO]), &connectId);
PRINT_HILOGD("OnDisconnectAbility connection:%{public}d", (int32_t)connectId);
auto item = std::find_if(connects_.begin(), connects_.end(),
[&connectId](const std::map<ConnecttionKey, sptr<JSPrintExtensionConnection>>::value_type &obj) {
return connectId == obj.first.id;
});
if (item != connects_.end()) {
// match id
want = item->first.want;
connection = item->second;
PRINT_HILOGD("%{public}s find conn ability:%{public}p exist", __func__, item->second.GetRefPtr());
} else {
PRINT_HILOGD("%{public}s not find conn exist.", __func__);
}
// begin disconnect
AsyncTask::CompleteCallback complete = [weak = context_, want, connection](
NativeEngine &engine, AsyncTask &task, int32_t status) {
PRINT_HILOGD("OnDisconnectAbility begin");
auto context = weak.lock();
if (!context) {
PRINT_HILOGW("context is released");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_ONE, "Context is released"));
return;
}
if (connection == nullptr) {
PRINT_HILOGW("connection nullptr");
task.Reject(engine, CreateJsError(engine, NapiPrintUtils::ERROR_CODE_TWO, "not found connection"));
return;
}
PRINT_HILOGD("context->DisconnectAbility");
auto errcode = context->DisconnectAbility(want, connection);
errcode == 0 ? task.Resolve(engine, engine.CreateUndefined())
: task.Reject(engine, CreateJsError(engine, errcode, "Disconnect Ability failed."));
};
NativeValue *lastParam =
(info.argc == NapiPrintUtils::ARGC_ONE) ? nullptr : info.argv[NapiPrintUtils::INDEX_ONE];
NativeValue *result = nullptr;
AsyncTask::Schedule("PrintExtensionContext::OnDisconnectAbility", engine,
CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
};
NativeValue *CreateJsMetadata(NativeEngine &engine, const AppExecFwk::Metadata &Info)
{
PRINT_HILOGD("CreateJsMetadata");
NativeValue *objValue = engine.CreateObject();
NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
object->SetProperty("name", CreateJsValue(engine, Info.name));
object->SetProperty("value", CreateJsValue(engine, Info.value));
object->SetProperty("resource", CreateJsValue(engine, Info.resource));
return objValue;
}
NativeValue *CreateJsMetadataArray(NativeEngine &engine, const std::vector<AppExecFwk::Metadata> &info)
{
PRINT_HILOGD("CreateJsMetadataArray");
NativeValue *arrayValue = engine.CreateArray(info.size());
NativeArray *array = ConvertNativeValueTo<NativeArray>(arrayValue);
uint32_t index = 0;
for (const auto &item : info) {
array->SetElement(index++, CreateJsMetadata(engine, item));
}
return arrayValue;
}
NativeValue *CreateJsExtensionAbilityInfo(NativeEngine &engine, const AppExecFwk::ExtensionAbilityInfo &info)
{
PRINT_HILOGD("CreateJsExtensionAbilityInfo");
NativeValue *objValue = engine.CreateObject();
NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
object->SetProperty("bundleName", CreateJsValue(engine, info.bundleName));
object->SetProperty("moduleName", CreateJsValue(engine, info.moduleName));
object->SetProperty("name", CreateJsValue(engine, info.name));
object->SetProperty("labelId", CreateJsValue(engine, info.labelId));
object->SetProperty("descriptionId", CreateJsValue(engine, info.descriptionId));
object->SetProperty("iconId", CreateJsValue(engine, info.iconId));
object->SetProperty("isVisible", CreateJsValue(engine, info.visible));
object->SetProperty("extensionAbilityType", CreateJsValue(engine, info.type));
NativeValue *permissionArrayValue = engine.CreateArray(info.permissions.size());
NativeArray *permissionArray = ConvertNativeValueTo<NativeArray>(permissionArrayValue);
if (permissionArray != nullptr) {
int index = 0;
for (auto permission : info.permissions) {
permissionArray->SetElement(index++, CreateJsValue(engine, permission));
}
}
object->SetProperty("permissions", permissionArrayValue);
object->SetProperty("applicationInfo", CreateJsApplicationInfo(engine, info.applicationInfo));
object->SetProperty("metadata", CreateJsMetadataArray(engine, info.metadata));
object->SetProperty("enabled", CreateJsValue(engine, info.enabled));
object->SetProperty("readPermission", CreateJsValue(engine, info.readPermission));
object->SetProperty("writePermission", CreateJsValue(engine, info.writePermission));
return objValue;
}
NativeValue *CreateJsPrintExtensionContext(NativeEngine &engine,
std::shared_ptr<PrintExtensionContext> context, std::string &extensionId)
{
PRINT_HILOGD("CreateJsPrintExtensionContext begin");
NativeValue *objValue = CreateJsExtensionContext(engine, context);
NativeObject *object = ConvertNativeValueTo<NativeObject>(objValue);
std::unique_ptr<JsPrintExtensionContext> jsContext = std::make_unique<JsPrintExtensionContext>(context);
object->SetNativePointer(jsContext.release(), JsPrintExtensionContext::Finalizer, nullptr);
// make handler
handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
const char *moduleName = "JsPrintExtensionContext";
BindNativeFunction(engine, *object, "startAbility", moduleName, JsPrintExtensionContext::StartAbility);
BindNativeFunction(engine, *object, "terminateSelf", moduleName, JsPrintExtensionContext::TerminateAbility);
BindNativeFunction(engine, *object, "connectAbility", moduleName, JsPrintExtensionContext::ConnectAbility);
BindNativeFunction(engine, *object, "disconnectAbility", moduleName, JsPrintExtensionContext::DisconnectAbility);
BindNativeFunction(
engine, *object, "startAbilityWithAccount", moduleName, JsPrintExtensionContext::StartAbilityWithAccount);
BindNativeFunction(
engine, *object, "connectAbilityWithAccount", moduleName, JsPrintExtensionContext::ConnectAbilityWithAccount);
if (context) {
PRINT_HILOGD("Set ExtensionAbilityInfo Property");
auto abilityInfo = context->GetAbilityInfo();
auto hapModuleInfo = context->GetHapModuleInfo();
if (abilityInfo && hapModuleInfo) {
extensionId = abilityInfo->bundleName;
PRINT_HILOGD("Set ExtensionAbilityInfo Property: extensionId = %{public}s", extensionId.c_str());
auto isExist = [&abilityInfo](const AppExecFwk::ExtensionAbilityInfo &info) {
PRINT_HILOGD("%{public}s, %{public}s", info.bundleName.c_str(), info.name.c_str());
return info.bundleName == abilityInfo->bundleName && info.name == abilityInfo->name;
};
auto infoIter =
std::find_if(hapModuleInfo->extensionInfos.begin(), hapModuleInfo->extensionInfos.end(), isExist);
if (infoIter == hapModuleInfo->extensionInfos.end()) {
PRINT_HILOGD("Get target fail.");
return objValue;
}
object->SetProperty("extensionAbilityInfo", CreateJsExtensionAbilityInfo(engine, *infoIter));
}
}
return objValue;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,67 @@
/*
* 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.
*/
#include "print_extension.h"
#include "ability_loader.h"
#include "connection_manager.h"
#include "js_print_extension.h"
#include "print_extension_context.h"
#include "print_log.h"
#include "runtime.h"
namespace OHOS {
namespace AbilityRuntime {
using namespace OHOS::AppExecFwk;
PrintExtension *PrintExtension::Create(const std::unique_ptr<Runtime> &runtime)
{
PRINT_HILOGD("jws PrintExtension::Create runtime");
if (!runtime) {
return new PrintExtension();
}
PRINT_HILOGD("jws PrintExtension::Create runtime");
switch (runtime->GetLanguage()) {
case Runtime::Language::JS:
return JsPrintExtension::Create(runtime);
default:
return new PrintExtension();
}
}
void PrintExtension::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
PRINT_HILOGD("jws PrintExtension begin init context");
ExtensionBase<PrintExtensionContext>::Init(record, application, handler, token);
PRINT_HILOGD("PrintExtension begin init context");
}
std::shared_ptr<PrintExtensionContext> PrintExtension::CreateAndInitContext(
const std::shared_ptr<AbilityLocalRecord> &record, const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token)
{
PRINT_HILOGD("jws PrintExtension begin init context");
std::shared_ptr<PrintExtensionContext> context =
ExtensionBase<PrintExtensionContext>::CreateAndInitContext(record, application, handler, token);
if (context == nullptr) {
PRINT_HILOGE("PrintExtension::CreateAndInitContext context is nullptr");
return context;
}
return context;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,128 @@
/*
* 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.
*/
#include "print_extension_context.h"
#include "ability_connection.h"
#include "ability_manager_client.h"
#include "print_log.h"
namespace OHOS {
namespace AbilityRuntime {
const size_t PrintExtensionContext::CONTEXT_TYPE_ID(std::hash<const char *> {}("PrintExtensionContext"));
int PrintExtensionContext::ILLEGAL_REQUEST_CODE(-1);
ErrCode PrintExtensionContext::StartAbility(const AAFwk::Want &want) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE);
PRINT_HILOGD("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbility is failed %{public}d", err);
}
return err;
}
ErrCode PrintExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err =
AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, ILLEGAL_REQUEST_CODE);
PRINT_HILOGD("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbility is failed %{public}d", err);
}
return err;
}
bool PrintExtensionContext::ConnectAbility(
const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode ret = ConnectionManager::GetInstance().ConnectAbility(token_, want, connectCallback);
PRINT_HILOGD("PrintExtensionContext::ConnectAbility ErrorCode = %{public}d", ret);
return ret == ERR_OK;
}
ErrCode PrintExtensionContext::StartAbilityWithAccount(const AAFwk::Want &want, int accountId) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
PRINT_HILOGD("%{public}d accountId:", accountId);
ErrCode err =
AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE, accountId);
PRINT_HILOGD("%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbilityWithAccount is failed %{public}d", err);
}
return err;
}
ErrCode PrintExtensionContext::StartAbilityWithAccount(
const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(
want, startOptions, token_, ILLEGAL_REQUEST_CODE, accountId);
PRINT_HILOGD("%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::StartAbilityWithAccount is failed %{public}d", err);
}
return err;
}
bool PrintExtensionContext::ConnectAbilityWithAccount(
const AAFwk::Want &want, int accountId, const sptr<AbilityConnectCallback> &connectCallback) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode ret = ConnectionManager::GetInstance().ConnectAbilityWithAccount(token_, want, accountId, connectCallback);
PRINT_HILOGD("PrintExtensionContext::ConnectAbilityWithAccount ErrorCode = %{public}d", ret);
return ret == ERR_OK;
}
ErrCode PrintExtensionContext::DisconnectAbility(
const AAFwk::Want &want, const sptr<AbilityConnectCallback> &connectCallback) const
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode ret = ConnectionManager::GetInstance().DisconnectAbility(token_, want.GetElement(), connectCallback);
if (ret != ERR_OK) {
PRINT_HILOGE("%{public}s end DisconnectAbility error, ret=%{public}d", __func__, ret);
}
PRINT_HILOGD("%{public}s end DisconnectAbility", __func__);
return ret;
}
ErrCode PrintExtensionContext::TerminateAbility()
{
PRINT_HILOGD("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr);
if (err != ERR_OK) {
PRINT_HILOGE("PrintExtensionContext::TerminateAbility is failed %{public}d", err);
}
PRINT_HILOGD("%{public}s end.", __func__);
return err;
}
AppExecFwk::AbilityType PrintExtensionContext::GetAbilityInfoType() const
{
std::shared_ptr<AppExecFwk::AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
PRINT_HILOGE("PrintExtensionContext::GetAbilityInfoType info == nullptr");
return AppExecFwk::AbilityType::UNKNOWN;
}
return info->type;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,43 @@
/*
* 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.
*/
#include "print_extension_module_loader.h"
#include "print_extension.h"
#include "print_log.h"
namespace OHOS::AbilityRuntime {
PrintExtensionModuleLoader::PrintExtensionModuleLoader() = default;
PrintExtensionModuleLoader::~PrintExtensionModuleLoader() = default;
Extension *PrintExtensionModuleLoader::Create(const std::unique_ptr<Runtime> &runtime) const
{
PRINT_HILOGD("jws PrintExtension::Create runtime");
return PrintExtension::Create(runtime);
}
std::map<std::string, std::string> PrintExtensionModuleLoader::GetParams()
{
std::map<std::string, std::string> params;
params.insert(std::pair<std::string, std::string>("type", "15"));
params.insert(std::pair<std::string, std::string>("name", "PrintExtension"));
return params;
}
extern "C" __attribute__((visibility("default"))) void *OHOS_EXTENSION_GetExtensionModule()
{
return &PrintExtensionModuleLoader::GetInstance();
}
} // namespace OHOS::AbilityRuntime

View File

@ -0,0 +1,137 @@
/*
* 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.
*/
/**
* class of print extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @StageModelOnly
*/
declare class PrintExtensionAbility {
/**
* Called once to initialize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onCreated(want: Want): void;
/**
* Called once to start to discover the printers connected with the device.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onStartDiscoverPrinter(): void;
/**
* Called once to stop discovering the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onStopDiscoverPrinter(): void;
/**
* Called once to connect to the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onConnectPrinter(printerId: number): void;
/**
* Called once to disconnect the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onDisconnectPrinter(printerId: number): void;
/**
* Called once to start print job.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onStartPrintJob(jobInfo: PrintJob): void;
/**
* Called once to remove the print job has been started.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onCancelPrintJob(jobInfo: PrintJob): void;
/**
* Called once to request the capability of the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onRequestPrinterCapability(printerId: number): PrinterCapability;
/**
* Called once to request preview and send result to Print SA.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onRequestPreview(jobInfo: PrintJob): Uri;
/**
* Called once to finalize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Print.print
* @return -
* @StageModelOnly
*/
onDestroy(): void;
}
export default PrintExtensionAbility;

View File

@ -0,0 +1,472 @@
/*
* 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 {AsyncCallback} from './basic';
import {ExtensionAbilityInfo} from './bundle/extensionAbilityInfo';
/**
* System print
* @sysCap SystemCapability.Print.print
* @import import print from '@ohos.app.print';
* @since 9
*/
declare namespace print {
interface PrintTask {
/**
* Register event callback when the current print task is in process.
* @since 9
* @param type blocked Indicates the print task has been blocked.
* type success Indicates the print task succeed.
* type failed Indicates the print task has completed with failure.
* type cancelled Indicates the print task has been cancelled.
* @param callback The callback function for print task change event
* @permission {@code ohos.permission.PRINT}
* @return -
*/
on(type: 'blocked' | 'success' | 'failed' | 'cancelled', callback: () => void): void;
/**
* Unregister event callback when the current print task is in process.
* @since 9
* @param type block Indicates the print task has been blocked.
* type success Indicates the print task succeed.
* type fail Indicates the print task has completed with failure.
* type cancel Indicates the print task has been cancelled.
* @param callback The callback function for print task change event
* @permission {@code ohos.permission.PRINT}
* @return -
*/
off(type: 'blocked' | 'success' | 'failed' | 'cancelled', callback?: (boolean) => void): void;
}
/**
* Start new print task for App.
* @since 9
* @param files Indicates the filepath list to be printed. Only pdf and picture filetypes are supported.
* @param callback The callback function for print task.
* @permission {@code ohos.permission.PRINT}
* @return -
*/
function print(files: Array<string>, callback: AsyncCallback<PrintTask>): void;
function print(files: Array<string>): Promise<PrintTask>;
interface PrintMargin {
top: number; // top margin
bottom: number; // bottom margin
left: number; // left side margin
right: number; // right side margin
}
interface PrinterRange {
startPage: number; // start page of sequence
endPage: number; // end page of sequence
pages: Array<number>; // discrete page of sequence
}
interface PreviewAttribute {
previewRange: PrinterRange; // preview page range
result: string; // preview file
}
interface PrinterResolution {
id: string; // resolution id
horizontalDpi: number // horizontal DPI
verticalDpi: number; // vertical DPI
}
interface PrinterPageSize {
id: string; // page size id
name: string; // page size name
width: number; // unit: milimeter
height: number; // unit: milimeter
}
interface PrinterCapability {
/* Printer Capability */
minMargin: PrintMargin; // min margin of printer
pageSize: Array<PrinterPageSize>; // the page size list supported by the printer
resolution: Array<PrinterResolution>; // the resolution list supported by the printer
colorMode: number; // color mode
duplexMode: number; // duplex mode
}
interface PrinterInfo {
printerId: string; // printer id
printerName: string; // printer name
printerIcon: number; // resource id of printer icon
printerState: PrinterState; // current printer state
description: string; // printer description
capability?: PrinterCapability; // printer capability
option?:string; // json object string
}
interface PrintJob {
files: Array<string>; // document list to be printed
jobId: string; // job id
printerId: string; // printer id to take charge of printing
jobState: PrintJobState; // current print job state
copyNumber: number; // copies of document list
pageRange: PrinterRange; // range size to be printed
isSequential: boolean; // sequential print
pageSize: PrinterPageSize; // the selected page size
isLandscape: boolean; // vertical printing
colorMode: number; // color mode
duplexMode: number; // duplex mode
margin: PrintMargin; // current margin setting
preview: PreviewAttribute; // preview setting
option?:string; // json object string
}
enum PrinterState {
PRINTER_ADDED = 0, // new printers arrival
PRINTER_REMOVED = 1, // printers lost
PRINTER_UPDATE_CAP = 2, // printers update
PRINTER_CONNECTED = 3, // printer has been connected
PRINTER_DISCONNECTED = 4, // printer has been disconnected
PRINTER_RUNNING = 5, // printer is working
PRINTER_UNKNOWN = 6, // unknown printer state
}
enum PrintJobState {
PRINT_JOB_PREPARE = 0, // initial state of print job
PRINT_JOB_QUEUED = 1, // deliver print job to the printer
PRINT_JOB_RUNNING = 2, // executing print job
PRINT_JOB_BLOCKED = 3, // print job has been blocked
PRINT_JOB_COMPLETED = 4, // print job ocmpleted
PRINT_JOB_UNKNOWN = 5, // unknown state of print job
}
enum PrintJobSubState {
PRINT_JOB_COMPLETED_SUCCESS = 0, // print job succeed
PRINT_JOB_COMPLETED_FAILED = 1, // print job fail
PRINT_JOB_COMPLETED_CANCELLED = 2, // print job has been cancelled
PRINT_JOB_COMPLETED_FILE_CORRUPT = 3, // print job has been corrupted
PRINT_JOB_BLOCK_OFFLINE = 4, // printer is offline
PRINT_JOB_BLOCK_BUSY = 5, // printer is occupied by other process
PRINT_JOB_BLOCK_CANCELLED = 6, // print job has been canncelled
PRINT_JOB_BLOCK_OUT_OF_PAPER = 7, // out of paper
PRINT_JOB_BLOCK_OUT_OF_INK = 8, // out of ink
PRINT_JOB_BLOCK_OUT_OF_TONER = 9, // out of toner
PRINT_JOB_BLOCK_JAMMED = 10, // paper jam
PRINT_JOB_BLOCK_DOOR_OPEN = 11, // cover open
PRINT_JOB_BLOCK_SERVICE_REQUEST = 12, // service request
PRINT_JOB_BLOCK_LOW_ON_INK = 13, // low on ink
PRINT_JOB_BLOCK_LOW_ON_TONER = 14, // low on toner
PRINT_JOB_BLOCK_REALLY_LOW_ON_INK = 15, // really low on ink
PRINT_JOB_BLOCK_BAD_CERTIFICATE = 16, // bad certification
PRINT_JOB_BLOCK_UNKNOWN = 17, // unknown issue
}
interface PrinterExtensionInfo extends ExtensionAbilityInfo {
extensionId: string; // extesion id of printer extension
vendorId: string; // vendor id of extension
vendorName: string; // vendor name
vendorIcon: number; // resource id of vendor
version: string; // version of current printer extension
}
/**
* Get all printer extension installed.
*
* @since 9
* @param callback The callback function for handling the extension list found.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function queryAllPrinterExtensionInfos(callback: AsyncCallback<Array<PrinterExtensionInfo>>): void;
function queryAllPrinterExtensionInfos(): Promise<Array<PrinterExtensionInfo>>;
/**
* Load the specific printer extension and start to discover printer.
*
* @since 9
* @param extensionList Indicates the list of printer extension.
* empty list of extensionList Indicates to find printer with all installed extension.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function startDiscoverPrinter(extensionList: Array<string>, callback: AsyncCallback<boolean>): void;
function startDiscoverPrinter(extensionList: Array<string>): Promise<boolean>;
/**
* Stop discovering the printer with specific printer extension.
*
* @since 9
* @param extensionList Indicates the list of printer extension.
* empty list of extensionList Indicates to find printer with all installed extension.
* @param callback The callback function for indcating the result of API execution.
* @permission {@ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function stopDiscoverPrinter(callback: AsyncCallback<boolean>): void;
function stopDiscoverPrinter(): Promise<boolean>;
/**
* Connect the specific printer.
*
* @since 9
* @param printerId Indicates id of the printer.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function connectPrinter(printerId: string, callback: AsyncCallback<boolean>): void;
function connectPrinter(printerId: string): Promise<boolean>;
/**
* Disconnect the specific printer.
*
* @since 9
* @param printerId Indicates id of the printer.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function disconnectPrinter(printerId: string, callback: AsyncCallback<boolean>): void;
function disconnectPrinter(printerId: string): Promise<boolean>;
/**
* Query capability for the specific printer.
*
* @since 9
* @param printerId Indicates id of the printer.
* @param callback The callback function for capability from printer.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function queryPrinterCapability(printerId: string, callback: AsyncCallback<PrinterCapability>): void;
function queryPrinterCapability(printerId: string): Promise<PrinterCapability>
/**
* Start print job.
*
* @since 9
* @param jobInfo Indicates the information of print job.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function startPrintJob(jobInfo: PrintJob, callback: AsyncCallback<boolean>): void;
function startPrintJob(jobInfo: PrintJob): Promise<boolean>;
/**
* Cancel the print job has been sent to printer.
*
* @since 9
* @param jobInfo Indicates the information of print job.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function cancelPrintJob(jobInfo: PrintJob, callback: AsyncCallback<boolean>): void;
function cancelPrintJob(jobInfo: PrintJob): Promise<boolean>;
/**
* Request preview of the print job.
*
* @since 9
* @param jobInfo Indicates the information of print job.
* @param callback The callback function for preview result from printer.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function requestPrintPreview(jobInfo: PrintJob, callback: (result: string) => void): void;
function requestPrintPreview(jobInfo: PrintJob): Promise<string>;
/**
* Register event callback for the state change of printer.
*
* @since 9
* @param printerStateChange Indicates state change of printer.
* @param callback The callback function for state change of printer.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function on(type: 'printerStateChange', callback: (state: PrinterState, info: PrinterInfo) => void): void;
/**
* Unregister event callback for the state change of printer.
*
* @since 9
* @param printerStateChange Indicates state change of printer.
* @param callback The callback function for state change of printer.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function off(type: 'printerStateChange', callback?: (boolean) => void): void;
/**
* Register event callback for the state change of print job.
*
* @since 9
* @param jobStateChange Indicates state change of print job.
* @param callback The callback function for state change of print job.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function on(type: 'jobStateChange', callback: (state: PrintJobState, job: PrintJob) => void): void;
/**
* Unregister event callback for the state change of print job.
*
* @since 9
* @param printerStateChange Indicates state change of print job.
* @param callback The callback function for state change of print job.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function off(type: 'jobStateChange', callback?: (boolean) => void): void;
/**
* Register event callback for the information change of print extension.
*
* @since 9
* @param extInfoChange Indicates information change of print extension.
* @param callback The callback function for information change of print extension.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function on(type: 'extInfoChange', callback: (extensionId: string, info: string) => void): void;
/**
* Unregister event callback for the information change of print extension.
*
* @since 9
* @param extInfoChange Indicates information change of print extension.
* @param callback The callback function for information change of print extension.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function off(type: 'extInfoChange', callback?: (boolean) => void): void;
/**
* New printers have been found and notify Print SA.
*
* @since 9
* @param printers Indicates new arrived printer lists.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function addPrinters(printers: Array<PrinterInfo>, callback: AsyncCallback<boolean>): void;
function addPrinters(printers: Array<PrinterInfo>): Promise<boolean>;
/**
* Printers have been lost and notify Print SA.
*
* @since 9
*
* @param printerIds Indicates the lost printer lists.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function removePrinters(printerIds: Array<string>, callback: AsyncCallback<boolean>): void;
function removePrinters(printerIds: Array<string>): Promise<boolean>;
/**
* Update the information of the specific printers
*
* @since 9
* @param printers Indicates to be updaetd printer lists.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function updatePrinters(printers: Array<PrinterInfo>, callback: AsyncCallback<boolean>): void;
function updatePrinters(printers: Array<PrinterInfo>): Promise<boolean>;
/**
* Notify Print SA the state of printer has been changed.
*
* @since 9
* @param printerId Indicates id of the printer.
* @param state Indicates new state of printer.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function updatePrinterState(printerId: string, state: PrinterState, callback: AsyncCallback<boolean>): void;
function updatePrinterState(printerId: string, state: PrinterState): Promise<boolean>;
/**
* Notify Print SA the state of print job has been changed.
*
* @since 9
* @param jobId Indicates id of the print job.
* @param state Indicates new state of print job.
* @param subState Indicates sub state of print job.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function updatePrintJobState(jobId: string, state: PrintJobState, subState: PrintJobSubState, callback: AsyncCallback<boolean>): void;
function updatePrintJobState(jobId: string, state: PrintJobState, subState: PrintJobSubState): Promise<boolean>;
/**
* Notify Print SA the state of print extension has been changed.
*
* @since 9
* @param info Indicates changed information of print extension.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function updateExtensionInfo(info: string, callback: AsyncCallback<boolean>): void;
function updateExtensionInfo(info: string): Promise<boolean>;
interface ReadConfig {
file: string; // file uri
offset?: number; // offset from the head of file
max?: number; // max size of read operation
};
/**
* Read file content of the specific file.
*
* @since 9
* @param config Indicates read configuration.
* @param callback The callback function for indcating the result of API execution.
* @permission {@code ohos.permission.MANAGE_PRINT_JOB}
* @systemapi Hide this for inner system use.
* @return -
*/
function readFile(config: ReadConfig, callback: AsyncCallback<ArrayBuffer>): void;
function readFile(config: ReadConfig): Promise<ArrayBuffer>;
}
export default print;

View File

@ -0,0 +1,137 @@
/*
* 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.
*/
/**
* class of print extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @StageModelOnly
*/
declare class printExtension {
/**
* Called once to initialize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onCreated(want: object): void;
/**
* Called once to start to discover the printers connected with the device.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onStartDiscoverPrinter(): void;
/**
* Called once to stop discovering the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onStopDiscoverPrinter(): void;
/**
* Called once to connect to the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onConnectPrinter(printerId: number): void;
/**
* Called once to disconnect the specific printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onDisconnectPrinter(printerId: number): void;
/**
* Called once to start print job.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onStartJob(jobInfo: PrintJob): void;
/**
* Called once to remove the print job has been started.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onCancelJob(jobInfo: PrintJob): void;
/**
* Called once to request the capability of the printer.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onRequestCapability(printerId: number): PrinterCapability;
/**
* Called once to request preview and send result to Print SA.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onRequestPreview(jobInfo: PrintJob): Uri;
/**
* Called once to finalize the extension.
*
* @systemapi Hide this for inner system use.
* @since 9
* @sysCap SystemCapability.Miscservices.print
* @return -
* @StageModelOnly
*/
onDestroy(): void;
}
export default printExtension;

View File

@ -0,0 +1,69 @@
/*
* 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 Extension from '@ohos.PrintExtensionAbility'
import print from '@ohos.print'
let MODULE_TAG = "hwprintext"
export default class PrintExtAbility extends Extension {
Array<PrinterInfo> printerList
onCreated(want) {
console.info(MODULE_TAG + 'ability on created start');
}
onStartDiscoverPrinter() {
console.info(MODULE_TAG + "ability start to discover printer";
if (hasFoundDevice) {
print.addPrinters(printerList);
}
}
onStopDiscoverPrinter() {
console.info(MODULE_TAG + 'ability stop discovering printer');
}
onDestroy() {
console.info(MODULE_TAG + 'ability on destroy');
}
onConnectPrinter(printerId) {
console.info(MODULE_TAG + 'ability connect the speci1 printer');
}
onDisconnectPrinter(printerId) {
console.info(MODULE_TAG + 'ability disconnect the speci1 printer');
}
onStartPrintJob(jobInfo) {
console.info(MODULE_TAG + 'ability start Print Job');
}
onCancelPrintJob(jobInfo) {
console.info(MODULE_TAG + 'ability cancel Print Job');
}
onRequestPrinterCapability(printerId) {
console.info(MODULE_TAG + 'ability request printer capability');
var capability = GetDeviceCapability(printerId);
return capability;
}
onRequestPreview(jobInfo) {
console.info(MODULE_TAG + 'ability request printer preview');
FileDescriptor fd = print.OpenFile(jobInfo.preview.result);
SavePreviewToFile(fd);
return jobInfo.preview.result;
}
};

View File

@ -0,0 +1,34 @@
/*
* 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 printmanager from '@ohos.app.print';
// start print
export async function startPrint() {
Array<string> fileList = ['./data/printsample.pdf', './data/photo.jpg'];
await printmanager.print(fileList).then(async (task) => {
task.on('block', () => {
console.info('[block] event is called');
});
task.on('success', () => {
console.info('[success] event is called');
});
task.on('fail', () => {
console.info('[fail] event is called');
});
task.on('cancel', () => {
console.info('[cancel] event is called');
});
});
}

View File

@ -0,0 +1,50 @@
# 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("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_print_extension_abc") {
src_js = rebase_path("print_extension.js")
dst_file = rebase_path(target_out_dir + "/print_extension.abc")
in_puts = [ "print_extension.js" ]
out_puts = [ target_out_dir + "/print_extension.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("print_extension_js") {
input = "print_extension.js"
output = target_out_dir + "/print_extension.o"
}
gen_js_obj("print_extension_abc") {
input = get_label_info(":gen_print_extension_abc", "target_out_dir") +
"/print_extension.abc"
output = target_out_dir + "/print_extension_abc.o"
dep = ":gen_print_extension_abc"
}
ohos_shared_library("printextension_napi") {
sources = [ "print_extension_module.cpp" ]
deps = [
":print_extension_abc",
":print_extension_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -0,0 +1,58 @@
/*
* 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.
*/
class PrintExtension {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
onStartDiscoverPrinter() {
console.log('onStartDiscoverPrinter');
}
onStopDiscoverPrinter() {
console.log('onStopDiscoverPrinter');
}
onConnectPrinter(printerId) {
console.log('onConnectPrinter:' + printerId);
}
onDisconnectPrinter(printerId) {
console.log('onDisconnectPrinter');
}
onStartPrintJob(jobInfo) {
console.log('onStartPrintJob');
}
onCancelPrintJob(jobInfo) {
console.log('onCancelPrintJob');
}
onRequestPrinterCapability(printerId) {
console.log('onRequestPrinterCapability:' + printerId);
}
onRequestPreview(jobInfo) {
console.log('onRequestPreview');
}
onDestroy() {
console.log('onDestroy');
}
}
export default PrintExtension

View File

@ -0,0 +1,54 @@
/*
* 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.
*/
#include "native_engine/native_engine.h"
extern const char _binary_print_extension_js_start[];
extern const char _binary_print_extension_js_end[];
extern const char _binary_print_extension_abc_start[];
extern const char _binary_print_extension_abc_end[];
extern "C" __attribute__((constructor)) void NAPI_PrintExtension_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "PrintExtension",
.fileName = "libprintextension_napi.so/PrintExtension.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtension_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_print_extension_js_end - _binary_print_extension_js_start;
}
}
// print_extension JS register
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtension_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_print_extension_abc_end - _binary_print_extension_abc_start;
}
}

View File

@ -0,0 +1,50 @@
# 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("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_print_extension_context_abc") {
src_js = rebase_path("print_extension_context.js")
dst_file = rebase_path(target_out_dir + "/print_extension_context.abc")
in_puts = [ "print_extension_context.js" ]
out_puts = [ target_out_dir + "/print_extension_context.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("print_extension_context_js") {
input = "print_extension_context.js"
output = target_out_dir + "/print_extension_context.o"
}
gen_js_obj("print_extension_context_abc") {
input = get_label_info(":gen_print_extension_context_abc",
"target_out_dir") + "/print_extension_context.abc"
output = target_out_dir + "/print_extension_context_abc.o"
dep = ":gen_print_extension_context_abc"
}
ohos_shared_library("printextensioncontext_napi") {
sources = [ "print_extension_context_module.cpp" ]
deps = [
":print_extension_context_abc",
":print_extension_context_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -0,0 +1,55 @@
/*
* 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.
*/
var ExtensionContext = requireNapi("application.ExtensionContext")
class PrintExtensionContext extends ExtensionContext {
constructor(obj) {
super(obj);
this.extensionAbilityInfo = obj.extensionAbilityInfo
}
startAbility(want, options, callback) {
console.log("startAbility");
return this.__context_impl__.startAbility(want, options, callback);
}
connectAbility(want, options) {
console.log("connectAbility");
return this.__context_impl__.connectAbility(want, options);
}
startAbilityWithAccount(want, accountId, options, callback) {
console.log("startAbilityWithAccount");
return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback);
}
connectAbilityWithAccount(want, accountId, options) {
console.log("connectAbilityWithAccount");
return this.__context_impl__.connectAbilityWithAccount(want, accountId, options);
}
disconnectAbility(connection, callback) {
console.log("disconnectAbility");
return this.__context_impl__.disconnectAbility(connection, callback);
}
terminateSelf(callback) {
console.log("terminateSelf");
return this.__context_impl__.terminateSelf(callback);
}
}
export default PrintExtensionContext

View File

@ -0,0 +1,56 @@
/*
* 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.
*/
#include "native_engine/native_engine.h"
extern const char _binary_print_extension_context_js_start[];
extern const char _binary_print_extension_context_js_end[];
extern const char _binary_print_extension_context_abc_start[];
extern const char _binary_print_extension_context_abc_end[];
extern "C" __attribute__((constructor)) void NAPI_PrintExtensionContext_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "PrintExtensionContext",
.fileName = "libprintextensioncontext_napi.so/PrintExtensionContext.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtensionContext_GetJSCode(
const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_context_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_print_extension_context_js_end - _binary_print_extension_context_js_start;
}
}
// print_extension_context JS register
extern "C" __attribute__((visibility("default"))) void NAPI_PrintExtensionContext_GetABCCode(
const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_print_extension_context_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_print_extension_context_abc_end - _binary_print_extension_context_abc_start;
}
}

View File

@ -0,0 +1,75 @@
# 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("//base/request/request/request_aafwk.gni")
import("//build/ohos.gni")
config("print_interfaces_kits_napi_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags_cc = [ "-fexceptions" ]
}
ohos_shared_library("print_napi") {
include_dirs = [
"//foundation/arkui/ace_engine/frameworks/base/utils",
"//foundation/arkui/napi",
"//foundation/arkui/napi/interfaces/kits",
"//foundation/arkui/napi/interfaces/inner_api",
"//third_party/node/src",
"//third_party/curl/include",
"${ability_runtime_services_path}/common/include",
"//utils/system/safwk/native/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/app/",
"${ability_runtime_path}/interfaces/kits/native/ability/native",
"${ability_runtime_services_path}/abilitymgr/include",
"${ability_runtime_inner_api_path}/ability_manager/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/Isamgr",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//base/print/print/utils/include",
"//base/print/print/frameworks/innerkitsimpl/include",
]
public_configs = [ ":print_interfaces_kits_napi_config" ]
sources = [
"src/print_module.cpp",
"src/napi_print_task.cpp",
"src/napi_inner_print.cpp",
"src/napi_print_ext.cpp",
"src/print_async_call.cpp",
"src/print_task.cpp",
]
deps = [
"//foundation/arkui/napi:ace_napi",
"//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//base/print/print/frameworks/innerkitsimpl:print_client",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"ability_runtime:data_ability_helper",
"ability_runtime:napi_base_context",
"c_utils:utils",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"preferences:native_preferences",
"relational_store:native_appdatafwk",
"relational_store:native_dataability",
"relational_store:native_rdb",
]
relative_install_dir = "module"
subsystem_name = "print"
part_name = "print"
}

View File

@ -0,0 +1,74 @@
/*
* 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.
*/
#ifndef NAPI_INNER_PRINT_H
#define NAPI_INNER_PRINT_H
#include <string>
#include <vector>
#include "iprint_callback.h"
#include "napi/native_api.h"
#include "print_async_call.h"
#include "print_job.h"
#include "print_task.h"
#include "printer_info.h"
#include "print_extension_info.h"
namespace OHOS::Print {
class NapiInnerPrint {
public:
static napi_value QueryExtensionInfo(napi_env env, napi_callback_info info);
static napi_value StartDiscovery(napi_env env, napi_callback_info info);
static napi_value StopDiscovery(napi_env env, napi_callback_info info);
static napi_value ConnectPrinter(napi_env env, napi_callback_info info);
static napi_value DisconnectPrinter(napi_env env, napi_callback_info info);
static napi_value StartPrintJob(napi_env env, napi_callback_info info);
static napi_value CancelPrintJob(napi_env env, napi_callback_info info);
static napi_value RequestPreview(napi_env env, napi_callback_info info);
static napi_value QueryCapability(napi_env env, napi_callback_info info);
static napi_value On(napi_env env, napi_callback_info info);
static napi_value Off(napi_env env, napi_callback_info info);
static napi_value ReadFile(napi_env env, napi_callback_info info);
private:
static bool IsSupportType(const std::string& type);
private:
struct InnerPrintContext : public PrintAsyncCall::Context {
std::vector<PrintExtensionInfo> allExtensionInfos;
uint32_t state;
std::string previewResult = "";
std::string type = "";
sptr<IPrintCallback> callback = nullptr;
std::string fileUri = "";
uint32_t fileOffset = 0;
uint32_t fileMaxRead = -1;
std::vector<uint8_t> fileRead;
PrinterCapability printerCapability;
bool result = false;
std::string stateType_ = "";
PrintJob printJob;
std::string printerId = "";
std::vector<std::string> extensionList;
InnerPrintContext() : Context(nullptr, nullptr) {};
InnerPrintContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~InnerPrintContext() {};
};
};
} // namespace OHOS::Print
#endif // NAPI_INNER_PRINT_H

View File

@ -0,0 +1,66 @@
/*
* 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.
*/
#ifndef NAPI_PRINT_EXT_H
#define NAPI_PRINT_EXT_H
#include "napi/native_api.h"
#include "noncopyable.h"
#include "print_async_call.h"
#include "print_margin.h"
#include "print_page_size.h"
#include "print_resolution.h"
#include "print_task.h"
#include "printer_capability.h"
#include "printer_info.h"
namespace OHOS::Print {
class NapiPrintExt {
public:
static napi_value AddPrinters(napi_env env, napi_callback_info info);
static napi_value RemovePrinters(napi_env env, napi_callback_info info);
static napi_value UpdatePrinters(napi_env env, napi_callback_info info);
static napi_value UpdatePrinterState(napi_env env, napi_callback_info info);
static napi_value UpdatePrintJobState(napi_env env, napi_callback_info info);
static napi_value UpdateExtensionInfo(napi_env env, napi_callback_info info);
private:
static bool IsValidPrinterState(uint32_t state);
static bool IsValidPrintJobState(uint32_t state);
static bool IsValidPrintJobSubState(uint32_t subState);
private:
struct NapiPrintExtContext : public PrintAsyncCall::Context {
bool result = true;
std::vector<PrinterInfo> printerInfos;
std::vector<std::string> printerIds;
std::string printerId = "";
uint32_t printerState = 0;
std::string printJobId = "";
uint32_t printJobState = 0;
uint32_t jobSubState = 0;
std::string extensionId = "";
std::string extInfo = "";
NapiPrintExtContext() : Context(nullptr, nullptr) {};
NapiPrintExtContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~NapiPrintExtContext() {};
};
};
} // namespace OHOS::Print
#endif // NAPI_PRINT_EXT_H

View File

@ -0,0 +1,35 @@
/*
* 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.
*/
#ifndef NAPI_PRINT_TASK_H
#define NAPI_PRINT_TASK_H
#include "napi/native_common.h"
#include "napi/native_api.h"
namespace OHOS::Print {
class NapiPrintTask {
public:
static napi_value Print(napi_env env, napi_callback_info info);
private:
static napi_value GetCtor(napi_env env);
static napi_value Initialize(napi_env env, napi_callback_info info);
private:
static __thread napi_ref globalCtor;
};
} // namespace OHOS::Print
#endif // NAPI_PRINT_TASK_H

View File

@ -0,0 +1,116 @@
/*
* 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.
*/
#ifndef PRINT_ASYNC_CALL_H
#define PRINT_ASYNC_CALL_H
#include <functional>
#include <memory>
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
#include "print_constant.h"
namespace OHOS::Print {
class PrintAsyncCall final {
public:
class Context {
public:
using InputAction = std::function<napi_status(napi_env, size_t, napi_value *, napi_value)>;
using OutputAction = std::function<napi_status(napi_env, napi_value *)>;
using ExecAction = std::function<void(Context *)>;
Context(InputAction input, OutputAction output) : input_(std::move(input)), output_(std::move(output)) {};
virtual ~Context() {};
void SetAction(InputAction input, OutputAction output = nullptr)
{
input_ = input;
output_ = output;
}
void SetAction(OutputAction output)
{
SetAction(nullptr, std::move(output));
}
virtual napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self)
{
if (input_ == nullptr) {
return napi_ok;
}
return input_(env, argc, argv, self);
}
virtual napi_status operator()(napi_env env, napi_value *result)
{
if (output_ == nullptr) {
*result = nullptr;
return napi_ok;
}
return output_(env, result);
}
virtual void Exec()
{
if (exec_ == nullptr) {
return;
}
exec_(this);
};
void SetErrorIndex(uint32_t errorIndex)
{
errorIndex_ = errorIndex;
}
uint32_t GetErrorIndex()
{
return errorIndex_;
}
protected:
friend class PrintAsyncCall;
InputAction input_ = nullptr;
OutputAction output_ = nullptr;
ExecAction exec_ = nullptr;
uint32_t errorIndex_ = ERROR_NONE;
};
// The default AsyncCallback in the parameters is at the end position.
static constexpr size_t ASYNC_DEFAULT_POS = -1;
PrintAsyncCall(napi_env env, napi_callback_info info, std::shared_ptr<Context> context, size_t pos = ASYNC_DEFAULT_POS);
~PrintAsyncCall();
napi_value Call(napi_env env, Context::ExecAction exec = nullptr);
napi_value SyncCall(napi_env env, Context::ExecAction exec = nullptr);
private:
enum { ARG_ERROR, ARG_DATA, ARG_BUTT };
static void OnExecute(napi_env env, void *data);
static void OnComplete(napi_env env, napi_status status, void *data);
struct AsyncContext {
std::shared_ptr<Context> ctx = nullptr;
napi_ref callback = nullptr;
napi_ref self = nullptr;
napi_deferred defer = nullptr;
napi_async_work work = nullptr;
};
static void DeleteContext(napi_env env, AsyncContext *context);
AsyncContext *context_ = nullptr;
napi_env env_ = nullptr;
};
} // namespace OHOS::Print
#endif // REQUEST_ASYNC_CALL_H

View File

@ -0,0 +1,59 @@
/*
* 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.
*/
#ifndef PRINT_TASK_H
#define PRINT_TASK_H
#include <map>
#include <mutex>
#include <string>
#include <vector>
#include "print_async_call.h"
#include "iprint_callback.h"
#include "napi/native_api.h"
#include "napi/native_common.h"
namespace OHOS::Print {
class PrintTask {
public:
explicit PrintTask(const std::vector<std::string> &fileList);
~PrintTask();
uint32_t Start();
void Stop();
const std::string &GetId() const;
static napi_value On(napi_env env, napi_callback_info info);
static napi_value Off(napi_env env, napi_callback_info info);
bool IsSupportType(const std::string &type) const;
private:
struct PrintTaskContext : public PrintAsyncCall::Context {
std::string type = "";
sptr<IPrintCallback> callback = nullptr;
bool result = false;
napi_status status = napi_generic_failure;
PrintTaskContext() : Context(nullptr, nullptr) {};
PrintTaskContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~PrintTaskContext() {};
};
std::string taskId_;
std::vector<std::string> fileList_;
std::map<std::string, bool> supportEvents_;
};
} // namespace OHOS::Print
#endif // PRINT_TASK_H

View File

@ -0,0 +1,459 @@
/*
* 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.
*/
#include "napi_inner_print.h"
#include "napi_print_utils.h"
#include "print_callback.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "print_task.h"
namespace OHOS::Print {
const std::string PRINTER_EVENT_TYPE = "printerStateChange";
const std::string PRINTJOB_EVENT_TYPE = "jobStateChange";
const std::string EXTINFO_EVENT_TYPE = "extInfoChange";
napi_value NapiInnerPrint::QueryExtensionInfo(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ZERO, " should 0 parameter!", napi_invalid_arg);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
PRINT_HILOGD("ouput enter---->");
napi_status status = napi_create_array(env, result);
uint32_t index = 0;
for (auto extInfo : context->allExtensionInfos) {
PRINT_HILOGD("ExtensionId = %{public}s", extInfo.GetExtensionId().c_str());
PRINT_HILOGD("VendorId = %{public}s", extInfo.GetVendorId().c_str());
PRINT_HILOGD("VendorName = %{public}s", extInfo.GetVendorName().c_str());
PRINT_HILOGD("VendorIcon = %{public}d", extInfo.GetVendorIcon());
PRINT_HILOGD("Version = %{public}s", extInfo.GetVersion().c_str());
napi_value printerInfo;
napi_create_object(env, &printerInfo);
NapiPrintUtils::SetStringPropertyUtf8(env, printerInfo, "extensionId", extInfo.GetExtensionId());
NapiPrintUtils::SetStringPropertyUtf8(env, printerInfo, "vendorId", extInfo.GetVendorId());
NapiPrintUtils::SetStringPropertyUtf8(env, printerInfo, "vendorName", extInfo.GetVendorName().c_str());
NapiPrintUtils::SetUint32Property(env, printerInfo, "vendorIcon", extInfo.GetVendorIcon());
NapiPrintUtils::SetStringPropertyUtf8(env, printerInfo, "version", extInfo.GetVersion().c_str());
status = napi_set_element(env, *result, index++, printerInfo);
}
return napi_ok;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->QueryAllExtension(context->allExtensionInfos);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to query all ext info");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::StartDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter StartDiscovery---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
bool isArray = false;
napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_array_expected);
uint32_t len = 0;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &len);
for (uint32_t index = 0; index < len; index++) {
napi_value value;
napi_get_element(env, argv[NapiPrintUtils::INDEX_ZERO], index, &value);
std::string extensionId = NapiPrintUtils::GetStringFromValueUtf8(env, value);
PRINT_HILOGD("output for :---- extensionList value is :[%{public}s]", extensionId.c_str());
if (extensionId != "") {
context->extensionList.emplace_back(extensionId);
}
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->StartDiscoverPrinter(context->extensionList);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to start discover printer");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::StopDiscovery(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter StopDiscovery---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ZERO, " should 0 parameter!", napi_invalid_arg);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->StopDiscoverPrinter();
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to stop discover printer");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::ConnectPrinter(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ConnectPrinter---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "printerId is not a string", napi_string_expected);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
context->printerId = printerId;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->ConnectPrinter(context->printerId);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to connect the printer");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::DisconnectPrinter(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter DisconnectPrinter---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "printerId is not a string", napi_string_expected);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
context->printerId = printerId;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->DisconnectPrinter(context->printerId);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to connect the printer");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::StartPrintJob(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter StartPrintJob---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
auto printJobPtr = PrintJob::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]);
if (printJobPtr == nullptr) {
PRINT_HILOGE("ParseJob type error!");
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->printJob = *printJobPtr;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
context->printJob.Dump();
int32_t ret = PrintManagerClient::GetInstance()->StartPrintJob(context->printJob);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to start print job");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::CancelPrintJob(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter CancelPrintJob---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
auto printJobPtr = PrintJob::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]);
if (printJobPtr == nullptr) {
PRINT_HILOGE("ParseJob type error!");
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->printJob = *printJobPtr;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
context->printJob.Dump();
int32_t ret = PrintManagerClient::GetInstance()->CancelPrintJob(context->printJob);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to start print job");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context), 0);
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::RequestPreview(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
auto printJobPtr = PrintJob::BuildFromJs(env, argv[NapiPrintUtils::INDEX_ZERO]);
if (printJobPtr == nullptr) {
PRINT_HILOGE("ParseJob type error!");
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->printJob = *printJobPtr;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_create_string_utf8(env, context->previewResult.c_str(), NAPI_AUTO_LENGTH, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
PRINT_HILOGD("exec----");
context->printJob.Dump();
int32_t ret = PrintManagerClient::GetInstance()->RequestPreview(context->printJob, context->previewResult);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to request preview of print job");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::QueryCapability(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter QueryCapability---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "printerId number is not a string", napi_string_expected);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
context->printerId = printerId;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
*result = context->printerCapability.ToJsObject(env);
return napi_ok;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->QueryPrinterCapability(context->printerId,
context->printerCapability);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to query capability of printer");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::On(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
napi_value thisVal = nullptr;
void *data = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVal, &data));
NAPI_ASSERT(env, argc == NapiPrintUtils::ARGC_TWO, "need 2 parameter!");
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "type is not a string");
std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("type : %{public}s", type.c_str());
if (!NapiInnerPrint::IsSupportType(type)) {
PRINT_HILOGE("Event On type : %{public}s not support", type.c_str());
return nullptr;
}
valuetype = napi_undefined;
napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype);
NAPI_ASSERT(env, valuetype == napi_function, "callback is not a function");
napi_ref callbackRef = NapiPrintUtils::CreateReference(env, argv[NapiPrintUtils::INDEX_ONE]);
sptr<IPrintCallback> callback = new (std::nothrow) PrintCallback(env, callbackRef);
if (callback == nullptr) {
PRINT_HILOGE("create print callback object fail");
return nullptr;
}
int32_t ret = PrintManagerClient::GetInstance()->On(type, callback);
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to register event");
return nullptr;
}
return nullptr;
}
napi_value NapiInnerPrint::Off(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "type is not a string", napi_string_expected);
std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
if (!NapiInnerPrint::IsSupportType(type)) {
PRINT_HILOGE("Event Off type : %{public}s not support", context->type.c_str());
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->type = type;
PRINT_HILOGD("event type : %{public}s", context->type.c_str());
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("context->result = %{public}d, result = %{public}p", context->result, result);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->Off(context->type);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to unregister event");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiInnerPrint::ReadFile(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<InnerPrintContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_object, "type is not an object", napi_object_expected);
context->fileUri = NapiPrintUtils::GetStringPropertyUtf8(env, argv[NapiPrintUtils::INDEX_ZERO], "file");
context->fileOffset = NapiPrintUtils::GetUint32Property(env, argv[NapiPrintUtils::INDEX_ZERO], "offset");
context->fileMaxRead = NapiPrintUtils::GetUint32Property(env, argv[NapiPrintUtils::INDEX_ZERO], "max");
PRINT_HILOGD("file uri : %{public}s", context->fileUri.c_str());
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
void* data = nullptr;
*result = NapiPrintUtils::CreateArrayBuffer(env, context->fileRead.size(), &data);
memcpy(data, &context->fileRead[0], context->fileRead.size());
PRINT_HILOGD("context->result = %{public}d, result = %{public}p", context->result, result);
return napi_ok;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->Read(context->fileRead, context->fileUri,
context->fileOffset, context->fileMaxRead);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to read file");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
bool NapiInnerPrint::IsSupportType(const std::string& type)
{
if (type == PRINTER_EVENT_TYPE || type == PRINTJOB_EVENT_TYPE || type == EXTINFO_EVENT_TYPE) {
return true;
}
return false;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,351 @@
/*
* 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.
*/
#include "napi_print_ext.h"
#include "napi_print_utils.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS::Print {
napi_value NapiPrintExt::AddPrinters(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
auto extensionId = NapiPrintUtils::GetExtensionId(env, argv);
PRINT_HILOGD("context->extensionId = %{public}s", extensionId.c_str());
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
bool isArray = false;
napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_array_expected);
uint32_t len = 0;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &len);
for (uint32_t index = 0; index < len; index++) {
napi_value value;
napi_get_element(env, argv[NapiPrintUtils::INDEX_ZERO], index, &value);
auto printerInfoPtr = PrinterInfo::BuildFromJs(env, value);
if (printerInfoPtr == nullptr) {
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
PRINT_HILOGE("PrinterInfo is format error!");
return napi_invalid_arg;
}
printerInfoPtr->SetPrinterId(NapiPrintUtils::GetGlobalId(extensionId, printerInfoPtr->GetPrinterId()));
context->printerInfos.emplace_back(*printerInfoPtr);
}
if (context->printerInfos.empty()) {
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
PRINT_HILOGE("no valid printer info exists!");
return napi_invalid_arg;
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->AddPrinters(context->printerInfos);
context->result = ret == ERROR_NONE;
if (context->result != ERROR_NONE) {
PRINT_HILOGE("Failed to add printers");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::RemovePrinters(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
auto extensionId = NapiPrintUtils::GetExtensionId(env, argv);
PRINT_HILOGD("context->extensionId = %{public}s", extensionId.c_str());
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
bool isArray = false;
napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_array_expected);
uint32_t len = 0;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &len);
for (uint32_t index = 0; index < len; index++) {
napi_value value;
napi_get_element(env, argv[NapiPrintUtils::INDEX_ZERO], index, &value);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, value);
if (printerId != "") {
context->printerIds.emplace_back(NapiPrintUtils::GetGlobalId(extensionId, printerId));
}
}
if (context->printerIds.empty()) {
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
PRINT_HILOGE("no valid printer info exists!");
return napi_invalid_arg;
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->RemovePrinters(context->printerIds);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to remove printers");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::UpdatePrinters(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
auto extensionId = NapiPrintUtils::GetExtensionId(env, argv);
PRINT_HILOGD("context->extensionId = %{public}s", extensionId.c_str());
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
bool isArray = false;
napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isArray);
NAPI_ASSERT_BASE(env, isArray, " is not array!", napi_array_expected);
uint32_t len = 0;
napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &len);
for (uint32_t index = 0; index < len; index++) {
napi_value value;
napi_get_element(env, argv[NapiPrintUtils::INDEX_ZERO], index, &value);
auto printerInfoPtr = PrinterInfo::BuildFromJs(env, value);
if (printerInfoPtr == nullptr) {
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
PRINT_HILOGE("PrinterInfo is format error!");
return napi_invalid_arg;
}
printerInfoPtr->SetPrinterId(NapiPrintUtils::GetGlobalId(extensionId, printerInfoPtr->GetPrinterId()));
context->printerInfos.emplace_back(*printerInfoPtr);
}
if (context->printerInfos.empty()) {
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
PRINT_HILOGE("no valid printer info exists!");
return napi_invalid_arg;
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->UpdatePrinters(context->printerInfos);
context->result = ret == ERROR_NONE;
if (context->result != ERROR_NONE) {
PRINT_HILOGE("Failed to update printers");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::UpdatePrinterState(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
auto extensionId = NapiPrintUtils::GetExtensionId(env, argv);
PRINT_HILOGD("context->extensionId = %{public}s", extensionId.c_str());
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_TWO, " should 2 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "printerId is not a string", napi_string_expected);
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "printerStateis not a number", napi_number_expected);
std::string printerId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
uint32_t printerState = NapiPrintUtils::GetUint32FromValue(env, argv[NapiPrintUtils::INDEX_ONE]);
PRINT_HILOGD("printerState : %{public}d", printerState);
if (printerId == "" || !IsValidPrinterState(printerState)) {
PRINT_HILOGE("invalid printer id or printer state");
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->printerId = NapiPrintUtils::GetGlobalId(extensionId, printerId);
PRINT_HILOGD("context->printerId : %{public}s", context->printerId.c_str());
context->printerState = printerState;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->UpdatePrinterState(context->printerId, context->printerState);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to update state of printer");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::UpdatePrintJobState(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_THREE, " should 3 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "printJobId is not a string", napi_string_expected);
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "printJobState is not a number", napi_number_expected);
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_TWO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_number, "reason is not a number", napi_number_expected);
std::string printJobId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("printJobId : %{public}s", printJobId.c_str());
uint32_t printJobState = NapiPrintUtils::GetUint32FromValue(env, argv[NapiPrintUtils::INDEX_ONE]);
PRINT_HILOGD("printerJobState : %{public}d", printJobState);
uint32_t jobSubState = NapiPrintUtils::GetUint32FromValue(env, argv[NapiPrintUtils::INDEX_TWO]);
PRINT_HILOGD("jobSubState : %{public}d", jobSubState);
if (printJobId == "" || !IsValidPrintJobState(printJobState) || !IsValidPrintJobSubState(jobSubState)) {
PRINT_HILOGE("invalid job id, job state or job substate");
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->printJobId = printJobId;
context->printJobState = printJobState;
context->jobSubState = jobSubState;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->UpdatePrintJobState(context->printJobId,
context->printJobState, context->jobSubState);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to update state of print job");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiPrintExt::UpdateExtensionInfo(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<NapiPrintExtContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
auto extensionId = NapiPrintUtils::GetExtensionId(env, argv);
PRINT_HILOGD("context->extensionId = %{public}s", extensionId.c_str());
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "extInfo is not a string", napi_string_expected);
std::string extInfo = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("extInfo : %{public}s", extInfo.c_str());
if (extensionId == "" || extInfo != "") {
PRINT_HILOGE("invalid extension id or extension information");
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->extensionId = extensionId;
context->extInfo = extInfo;
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("output ---- [%{public}s], status[%{public}d]", context->result ? "true" : "false", status);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->UpdateExtensionInfo(context->extensionId, context->extInfo);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to update extension information");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
bool NapiPrintExt::IsValidPrinterState(uint32_t state)
{
if (state >= PRINTER_ADDED || state < PRINTER_UNKNOWN) {
return true;
}
return false;
}
bool NapiPrintExt::IsValidPrintJobState(uint32_t state)
{
if (state >= PRINT_JOB_PREPARED || state <= PRINT_JOB_UNKNOWN) {
return true;
}
return false;
}
bool NapiPrintExt::IsValidPrintJobSubState(uint32_t subState)
{
if (subState >= PRINT_JOB_COMPLETED_SUCCESS || subState <= PRINT_JOB_BLOCKED_UNKNOWN ) {
return true;
}
return false;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,149 @@
/*
* 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.
*/
#include "napi_print_task.h"
#include <mutex>
#include "napi_print_utils.h"
#include "print_async_call.h"
#include "print_log.h"
#include "print_manager_client.h"
#include "print_task.h"
static constexpr const char *FUNCTION_ON = "on";
static constexpr const char *FUNCTION_OFF = "off";
namespace OHOS::Print {
__thread napi_ref NapiPrintTask::globalCtor = nullptr;
std::mutex printTaskMutex_;
struct PrintTaskContext : public PrintAsyncCall::Context {
napi_ref ref = nullptr;
PrintTaskContext() : Context(nullptr, nullptr) {}
PrintTaskContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~PrintTaskContext() {}
};
napi_value NapiPrintTask::Print(napi_env env, napi_callback_info info) // PrintTask
{
PRINT_HILOGD("Enter print JsMain.");
auto context = std::make_shared<PrintTaskContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
PRINT_HILOGD("print parser to native params %{public}d!", static_cast<int>(argc));
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, "need 1 parameter!", napi_invalid_arg);
bool isFileArray = false;
napi_is_array(env, argv[NapiPrintUtils::INDEX_ZERO], &isFileArray);
NAPI_ASSERT_BASE(env, isFileArray == true, "files isn't list", napi_invalid_arg);
uint32_t len = 0;
NAPI_CALL_BASE(env, napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &len), napi_invalid_arg);
if (!isFileArray || len == 0) {
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
napi_value proxy = nullptr;
napi_status status = napi_new_instance(env, GetCtor(env), argc, argv, &proxy);
if ((proxy == nullptr) || (status != napi_ok)) {
PRINT_HILOGE("Failed to create print task");
context->SetErrorIndex(ERROR_GENERIC_FAIL);
return napi_generic_failure;
}
PrintTask *task;
NAPI_CALL_BASE(env, napi_unwrap(env, proxy, reinterpret_cast<void **>(&task)), napi_invalid_arg);
uint32_t ret = ERROR_GENERIC_FAIL;
if (task != nullptr) {
ret = task->Start();
}
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to start print task");
context->SetErrorIndex(ret);
return napi_generic_failure;
}
napi_create_reference(env, proxy, 1, &(context->ref));
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
if (context->ref == nullptr) {
*result = NapiPrintUtils::GetUndefined(env);
return napi_generic_failure;
}
napi_status status = napi_get_reference_value(env, context->ref, result);
napi_delete_reference(env, context->ref);
return status;
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env);
}
napi_value NapiPrintTask::GetCtor(napi_env env)
{
std::lock_guard<std::mutex> lock(printTaskMutex_);
napi_value cons;
if (globalCtor != nullptr) {
NAPI_CALL(env, napi_get_reference_value(env, globalCtor, &cons));
return cons;
}
napi_property_descriptor clzDes[] = {
{ FUNCTION_ON, 0, PrintTask::On, 0, 0, 0, napi_default, 0 },
{ FUNCTION_OFF, 0, PrintTask::Off, 0, 0, 0, napi_default, 0 },
};
NAPI_CALL(env, napi_define_class(env, "NapiPrintTask", NAPI_AUTO_LENGTH, Initialize, nullptr,
sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons));
NAPI_CALL(env, napi_create_reference(env, cons, 1, &globalCtor));
return cons;
}
napi_value NapiPrintTask::Initialize(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("constructor print task!");
napi_value self = nullptr;
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
std::vector<std::string> printfiles;
uint32_t arrayReLength = 0;
NAPI_CALL(env, napi_get_array_length(env, argv[NapiPrintUtils::INDEX_ZERO], &arrayReLength));
for (uint32_t index = 0; index < arrayReLength; index++) {
napi_value filesValue;
napi_get_element(env, argv[NapiPrintUtils::INDEX_ZERO], index, &filesValue);
std::string files = NapiPrintUtils::GetStringFromValueUtf8(env, filesValue);
PRINT_HILOGD("file[%{public}d] %{public}s", index, files.c_str());
printfiles.emplace_back(files);
}
auto task = new PrintTask(printfiles);
if (task == nullptr) {
PRINT_HILOGE("print task fail");
return nullptr;
}
auto finalize = [](napi_env env, void *data, void *hint) {
PRINT_HILOGD("destructed print task");
PrintTask *task = reinterpret_cast<PrintTask *>(data);
delete task;
};
if (napi_wrap(env, self, task, finalize, nullptr, nullptr) != napi_ok) {
finalize(env, task, nullptr);
return nullptr;
}
PRINT_HILOGD("Succeed to allocate print task");
return self;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,176 @@
/*
* 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.
*/
#include "print_async_call.h"
#include "napi_print_utils.h"
#include "print_log.h"
namespace OHOS::Print {
PrintAsyncCall::PrintAsyncCall(napi_env env, napi_callback_info info,
std::shared_ptr<Context> context, size_t pos) : env_(env)
{
context_ = new AsyncContext();
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value self = nullptr;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
pos = ((pos == ASYNC_DEFAULT_POS) ? (argc - 1) : pos);
if (pos >= 0 && pos < argc) {
napi_valuetype valueType = napi_undefined;
napi_typeof(env, argv[pos], &valueType);
if (valueType == napi_function) {
napi_create_reference(env, argv[pos], 1, &context_->callback);
argc = pos;
}
}
NAPI_CALL_RETURN_VOID(env, (*context)(env, argc, argv, self));
context_->ctx = std::move(context);
napi_create_reference(env, self, 1, &context_->self);
}
PrintAsyncCall::~PrintAsyncCall()
{
if (context_ == nullptr) {
return;
}
DeleteContext(env_, context_);
}
napi_value PrintAsyncCall::Call(napi_env env, Context::ExecAction exec)
{
if ((context_ == nullptr) || (context_->ctx == nullptr)) {
PRINT_HILOGE("context_ or context_->ctx is null");
return nullptr;
}
PRINT_HILOGD("async call exec");
context_->ctx->exec_ = std::move(exec);
napi_value promise = nullptr;
if (context_->callback == nullptr) {
napi_create_promise(env, &context_->defer, &promise);
} else {
napi_get_undefined(env, &promise);
}
napi_async_work work = context_->work;
napi_value resource = nullptr;
napi_create_string_utf8(env, "PrintAsyncCall", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env, nullptr, resource, PrintAsyncCall::OnExecute,
PrintAsyncCall::OnComplete, context_, &work);
context_->work = work;
context_ = nullptr;
napi_queue_async_work(env, work);
PRINT_HILOGD("async call exec");
return promise;
}
napi_value PrintAsyncCall::SyncCall(napi_env env, PrintAsyncCall::Context::ExecAction exec)
{
if ((context_ == nullptr) || (context_->ctx == nullptr)) {
PRINT_HILOGE("context_ or context_->ctx is null");
return nullptr;
}
context_->ctx->exec_ = std::move(exec);
napi_value promise = nullptr;
if (context_->callback == nullptr) {
napi_create_promise(env, &context_->defer, &promise);
} else {
napi_get_undefined(env, &promise);
}
PrintAsyncCall::OnExecute(env, context_);
PrintAsyncCall::OnComplete(env, napi_ok, context_);
return promise;
}
void PrintAsyncCall::OnExecute(napi_env env, void *data)
{
AsyncContext *context = reinterpret_cast<AsyncContext *>(data);
if ((context == nullptr) || (context->ctx == nullptr)) {
PRINT_HILOGE("context or context->ctx is null");
return;
}
PRINT_HILOGD("run the async runnable");
if (context->ctx->GetErrorIndex() == ERROR_NONE) {
context->ctx->Exec();
}
}
void PrintAsyncCall::OnComplete(napi_env env, napi_status status, void *data)
{
AsyncContext *context = reinterpret_cast<AsyncContext *>(data);
if ((context == nullptr) || (context->ctx == nullptr)) {
PRINT_HILOGE("context or context->ctx is null");
return;
}
PRINT_HILOGD("run the js callback function");
if (context->ctx->GetErrorIndex() != ERROR_NONE) {
status = napi_generic_failure;
}
napi_value output = nullptr;
napi_status runStatus = (*context->ctx)(env, &output);
PRINT_HILOGD("runStatus: [%{public}d], status: [%{public}d]", runStatus, status);
napi_value result[ARG_BUTT] = { 0 };
if (status == napi_ok && runStatus == napi_ok) {
napi_get_undefined(env, &result[ARG_ERROR]);
if (output != nullptr) {
result[ARG_DATA] = output;
PRINT_HILOGD("async call napi_ok.");
} else {
napi_get_undefined(env, &result[ARG_DATA]);
PRINT_HILOGD("async call napi_ok, but output is nullptr.");
}
} else {
napi_value message = nullptr;
uint32_t errorIndex = context->ctx->GetErrorIndex();
PRINT_HILOGD("ErrorMessage: [%{public}s], ErrorIndex:[%{public}d]",
ErrorMessage[errorIndex].c_str(), errorIndex);
napi_create_uint32(env, errorIndex, &message);
PRINT_HILOGD("async call failed. creating errors...");
result[ARG_ERROR] = message;
napi_get_undefined(env, &result[ARG_DATA]);
}
if (context->defer != nullptr) {
// promise
if (status == napi_ok && runStatus == napi_ok) {
PRINT_HILOGD("async_call napi_resolve_deferred is running.");
napi_resolve_deferred(env, context->defer, result[ARG_DATA]);
} else {
PRINT_HILOGD("async_call napi_reject_deferred is running.");
napi_reject_deferred(env, context->defer, result[ARG_ERROR]);
}
} else {
// callback
napi_value callback = nullptr;
PRINT_HILOGD("async_call napi_get_reference_value is running.");
napi_get_reference_value(env, context->callback, &callback);
napi_value returnValue;
napi_call_function(env, nullptr, callback, ARG_BUTT, result, &returnValue);
}
DeleteContext(env, context);
}
void PrintAsyncCall::DeleteContext(napi_env env, AsyncContext *context)
{
if (env != nullptr) {
napi_delete_reference(env, context->callback);
napi_delete_reference(env, context->self);
napi_delete_async_work(env, context->work);
}
delete context;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,89 @@
/*
* 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.
*/
#include "napi_inner_print.h"
#include "napi_print_ext.h"
#include "napi_print_task.h"
#include "print_log.h"
using namespace OHOS::Print;
static constexpr const char *FUNCTION_PRINT = "print";
static constexpr const char *FUNCTION_QUERY_EXT = "queryAllPrinterExtensionInfos";
static constexpr const char *FUNCTION_START_DISCOVERY = "startDiscoverPrinter";
static constexpr const char *FUNCTION_STOP_DISCOVERY = "stopDiscoverPrinter";
static constexpr const char *FUNCTION_CONNECT_PRINT = "connectPrinter";
static constexpr const char *FUNCTION_DISCONNECT_PRINT = "disconnectPrinter";
static constexpr const char *FUNCTION_START_PRINT = "startPrintJob";
static constexpr const char *FUNCTION_CANCEL_PRINT = "cancelPrintJob";
static constexpr const char *FUNCTION_REQUEST_PREVIEW = "requestPrintPreview";
static constexpr const char *FUNCTION_QUERY_CAPABILITY = "queryPrinterCapability";
static constexpr const char *FUNCTION_REGISTER_EVENT = "on";
static constexpr const char *FUNCTION_UNREGISTER_EVENT = "off";
static constexpr const char *FUNCTION_ADD_PRINTER = "addPrinters";
static constexpr const char *FUNCTION_REMOVE_PRINTER = "removePrinters";
static constexpr const char *FUNCTION_UPDATE_PRINTER = "updatePrinters";
static constexpr const char *FUNCTION_UPDATE_PRINTER_STATE = "updatePrinterState";
static constexpr const char *FUNCTION_UPDATE_JOB_STATE = "updatePrintJobState";
static constexpr const char *FUNCTION_UPDATE_EXTENSION_INFO = "updateExtensionInfo";
static constexpr const char *FUNCTION_READ_FILE = "readFile";
#define DECLARE_NAPI_METHOD(name, func) \
{ \
name, 0, func, 0, 0, 0, napi_default, 0 \
}
static napi_value Init(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_METHOD(FUNCTION_PRINT, NapiPrintTask::Print),
DECLARE_NAPI_METHOD(FUNCTION_QUERY_EXT, NapiInnerPrint::QueryExtensionInfo),
DECLARE_NAPI_METHOD(FUNCTION_START_DISCOVERY, NapiInnerPrint::StartDiscovery),
DECLARE_NAPI_METHOD(FUNCTION_STOP_DISCOVERY, NapiInnerPrint::StopDiscovery),
DECLARE_NAPI_METHOD(FUNCTION_CONNECT_PRINT, NapiInnerPrint::ConnectPrinter),
DECLARE_NAPI_METHOD(FUNCTION_DISCONNECT_PRINT, NapiInnerPrint::DisconnectPrinter),
DECLARE_NAPI_METHOD(FUNCTION_START_PRINT, NapiInnerPrint::StartPrintJob),
DECLARE_NAPI_METHOD(FUNCTION_CANCEL_PRINT, NapiInnerPrint::CancelPrintJob),
DECLARE_NAPI_METHOD(FUNCTION_REQUEST_PREVIEW, NapiInnerPrint::RequestPreview),
DECLARE_NAPI_METHOD(FUNCTION_QUERY_CAPABILITY, NapiInnerPrint::QueryCapability),
DECLARE_NAPI_METHOD(FUNCTION_REGISTER_EVENT, NapiInnerPrint::On),
DECLARE_NAPI_METHOD(FUNCTION_UNREGISTER_EVENT, NapiInnerPrint::Off),
DECLARE_NAPI_METHOD(FUNCTION_READ_FILE, NapiInnerPrint::ReadFile),
DECLARE_NAPI_METHOD(FUNCTION_ADD_PRINTER, NapiPrintExt::AddPrinters),
DECLARE_NAPI_METHOD(FUNCTION_REMOVE_PRINTER, NapiPrintExt::RemovePrinters),
DECLARE_NAPI_METHOD(FUNCTION_UPDATE_PRINTER, NapiPrintExt::UpdatePrinters),
DECLARE_NAPI_METHOD(FUNCTION_UPDATE_PRINTER_STATE, NapiPrintExt::UpdatePrinterState),
DECLARE_NAPI_METHOD(FUNCTION_UPDATE_JOB_STATE, NapiPrintExt::UpdatePrintJobState),
DECLARE_NAPI_METHOD(FUNCTION_UPDATE_EXTENSION_INFO, NapiPrintExt::UpdateExtensionInfo),
};
napi_status status = napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc);
PRINT_HILOGD("init upload %{public}d", status);
return exports;
}
static __attribute__((constructor)) void RegisterModule()
{
static napi_module module = { .nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "print",
.nm_priv = ((void *)0),
.reserved = { 0 } };
napi_module_register(&module);
PRINT_HILOGD("module register print");
}

View File

@ -0,0 +1,147 @@
/*
* 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.
*/
#include "print_task.h"
#include "napi/native_common.h"
#include "napi_print_utils.h"
#include "print_callback.h"
#include "print_log.h"
#include "print_manager_client.h"
namespace OHOS::Print {
const std::string EVENT_BLOCK = "blocked";
const std::string EVENT_SUCCESS = "success";
const std::string EVENT_FAIL = "failed";
const std::string EVENT_CANCEL = "cancelled";
PrintTask::PrintTask(const std::vector<std::string> &fileList)
: taskId_(""), fileList_(fileList)
{
supportEvents_[EVENT_BLOCK] = true;
supportEvents_[EVENT_SUCCESS] = true;
supportEvents_[EVENT_FAIL] = true;
supportEvents_[EVENT_CANCEL] = true;
}
PrintTask::~PrintTask()
{
supportEvents_.clear();
Stop();
}
uint32_t PrintTask::Start()
{
return PrintManagerClient::GetInstance()->StartPrint(fileList_, taskId_);
}
void PrintTask::Stop()
{
PrintManagerClient::GetInstance()->StopPrint(taskId_);
taskId_ = "";
}
const std::string &PrintTask::GetId() const
{
return taskId_;
}
napi_value PrintTask::On(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
napi_value thisVal = nullptr;
void *data = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVal, &data));
NAPI_ASSERT(env, argc == NapiPrintUtils::ARGC_TWO, "need 2 parameter!");
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "type is not a string");
std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PRINT_HILOGD("type : %{public}s", type.c_str());
valuetype = napi_undefined;
napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype);
NAPI_ASSERT(env, valuetype == napi_function, "callback is not a function");
PrintTask *task;
NAPI_CALL(env, napi_unwrap(env, thisVal, reinterpret_cast<void **>(&task)));
if (task == nullptr || !task->IsSupportType(type)) {
PRINT_HILOGE("Event On type : %{public}s not support", type.c_str());
return nullptr;
}
type = task->taskId_ + type;
PRINT_HILOGD("event type : %{public}s", type.c_str());
napi_ref callbackRef = NapiPrintUtils::CreateReference(env, argv[NapiPrintUtils::INDEX_ONE]);
sptr<IPrintCallback> callback = new (std::nothrow) PrintCallback(env, callbackRef);
if (callback == nullptr) {
PRINT_HILOGE("create print callback object fail");
return nullptr;
}
int32_t ret = PrintManagerClient::GetInstance()->On(type, callback);
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to register event");
return nullptr;
}
return nullptr;
}
napi_value PrintTask::Off(napi_env env, napi_callback_info info)
{
PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<PrintTaskContext>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, "need 1 parameter!", napi_invalid_arg);
napi_valuetype valuetype;
NAPI_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
NAPI_ASSERT_BASE(env, valuetype == napi_string, "type is not a string", napi_string_expected);
std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]);
PrintTask *task;
NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast<void **>(&task)), napi_invalid_arg);
if (task == nullptr || !task->IsSupportType(type)) {
PRINT_HILOGE("Event On type : %{public}s not support", type.c_str());
context->SetErrorIndex(ERROR_INVALID_PARAMETER);
return napi_invalid_arg;
}
context->type = task->taskId_ + type;
PRINT_HILOGD("event type : %{public}s", context->type.c_str());
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result);
PRINT_HILOGD("context->result = %{public}d, result = %{public}p", context->result, result);
return status;
};
auto exec = [context](PrintAsyncCall::Context *ctx) {
int32_t ret = PrintManagerClient::GetInstance()->Off(context->type);
context->result = ret == ERROR_NONE;
if (ret != ERROR_NONE) {
PRINT_HILOGE("Failed to unregistered event");
context->SetErrorIndex(ret);
}
};
context->SetAction(std::move(input), std::move(output));
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
bool PrintTask::IsSupportType(const std::string &type) const
{
return supportEvents_.find(type) != supportEvents_.end();
}
} // namespace OHOS::Print

24
profile/profile/3707.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>false</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

19
profile/profile/BUILD.gn Normal file
View File

@ -0,0 +1,19 @@
# 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/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("print_sa_profiles") {
sources = [ "3707.xml" ]
part_name = "print"
}

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>

81
profile/services/BUILD.gn Normal file
View File

@ -0,0 +1,81 @@
# 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/ohos.gni")
config("print_service_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
]
cflags_cc = [ "-fexceptions" ]
}
ohos_shared_library("print_service") {
sources = [
"src/print_service_ability.cpp",
"src/print_service_stub.cpp",
"src/print_callback_proxy.cpp",
"src/print_extension_callback_proxy.cpp",
"src/print_bms_death_recipient.cpp",
"src/print_bms_helper.cpp",
]
public_configs = [
"//commonlibrary/c_utils/base:utils_config",
":print_service_config",
]
include_dirs = [
"//commonlibrary/c_utils/base/include",
"//utils/system/safwk/native/include",
"//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient/include",
"//base/notification/distributed_notification_service/interfaces/inner_api",
"//base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include",
"//base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter",
"//base/print/print/frameworks/innerkitsimpl/include",
"//base/print/print/utils/include",
]
deps = [
"//base/notification/distributed_notification_service/frameworks/ans:ans_innerkits",
"//base/telephony/core_service/interfaces/innerkits:tel_core_service_api",
"//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient:net_conn_manager_if",
"//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//base/print/print/frameworks/innerkitsimpl:print_client",
]
external_deps = [
"ability_base:base",
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_manager",
"ability_runtime:abilitykit_native",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"drivers_interface_ril:hril_innerkits",
"eventhandler:libeventhandler",
"hisysevent_native:libhisysevent",
"hitrace_native:hitrace_meter",
"hiviewdfx_hilog_native:libhilog",
"init:libbegetutil",
"ipc:ipc_core",
"multimedia_image_standard:image_native",
"os_account:os_account_innerkits",
"relational_store:native_rdb",
]
subsystem_name = "print"
part_name = "print"
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PRINT_BMS_DEATH_RECIPIENT_H
#define PRINT_BMS_DEATH_RECIPIENT_H
#include "iremote_object.h"
namespace OHOS::Print {
class PrintBMSDeathRecipient : public IRemoteObject::DeathRecipient {
public:
/**
* Called back when the remote object is died..
*
* @param wptrDeath Indicates the died object.
*/
virtual void OnRemoteDied(const wptr<IRemoteObject> &wptrDeath);
};
} // namespace OHOS
#endif // PRINT_BMS_DEATH_RECIPIENT_H

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2021-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.
*/
#ifndef PRINT_BMS_HELPER_H
#define PRINT_BMS_HELPER_H
#include <string>
#include <vector>
#include "print_bms_death_recipient.h"
#include "bundle_mgr_interface.h"
#include "extension_ability_info.h"
#include "iremote_object.h"
#include "refbase.h"
#include "singleton.h"
#include "want.h"
namespace OHOS::Print {
class PrintBMSHelper : public DelayedSingleton<PrintBMSHelper> {
public:
using IBundleMgr = OHOS::AppExecFwk::IBundleMgr;
explicit PrintBMSHelper();
virtual ~PrintBMSHelper();
bool QueryExtensionInfos(std::vector<AppExecFwk::ExtensionAbilityInfo> &extensionInfo);
void ResetProxy();
private:
bool GetProxy();
private:
sptr<IBundleMgr> sptrBundleMgr_;
std::mutex mutex_;
sptr<PrintBMSDeathRecipient> printBMSDeath_;
};
} // namespace OHOS
#endif // PRINT_BMS_HELPER_H

View File

@ -0,0 +1,37 @@
/*
* 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.
*/
#ifndef PRINT_NOTIFY_PROXY_H
#define PRINT_NOTIFY_PROXY_H
#include "iprint_callback.h"
#include "iremote_proxy.h"
namespace OHOS::Print {
class PrintCallbackProxy : public IRemoteProxy<IPrintCallback> {
public:
explicit PrintCallbackProxy(const sptr<IRemoteObject> &impl);
~PrintCallbackProxy() = default;
bool OnCallback() override;
bool OnCallback(uint32_t state, const PrinterInfo &info) override;
bool OnCallback(uint32_t state, const PrintJob &info) override;
bool OnCallback(const std::string &extensionId, const std::string &info) override;
private:
static inline BrokerDelegator<PrintCallbackProxy> delegator_;
};
} // namespace OHOS::Print
#endif // PRINT_NOTIFY_PROXY_H

View File

@ -0,0 +1,37 @@
/*
* 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.
*/
#ifndef PRINT_EXTENSION_CALLBACK_PROXY_H
#define PRINT_EXTENSION_CALLBACK_PROXY_H
#include "iprint_extension_callback.h"
#include "iremote_proxy.h"
namespace OHOS::Print {
class PrintExtensionCallbackProxy : public IRemoteProxy<IPrintExtensionCallback> {
public:
explicit PrintExtensionCallbackProxy(const sptr<IRemoteObject> &impl);
~PrintExtensionCallbackProxy() = default;
bool OnCallback() override;
bool OnCallback(const std::string &printerId) override;
bool OnCallback(const PrintJob &job) override;
bool OnCallback(const std::string &printerId, MessageParcel &reply) override;
private:
static inline BrokerDelegator<PrintExtensionCallbackProxy> delegator_;
};
} // namespace OHOS::Print
#endif // PRINT_EXTENSION_CALLBACK_PROXY_H

View File

@ -0,0 +1,104 @@
/*
* 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.
*/
#ifndef PRINT_SERVICE_ABILITY_H
#define PRINT_SERVICE_ABILITY_H
#include <mutex>
#include <string>
#include <vector>
#include "ability_manager_client.h"
#include "event_handler.h"
#include "extension_ability_info.h"
#include "iprint_callback.h"
#include "iremote_object.h"
#include "print_service_stub.h"
#include "system_ability.h"
namespace OHOS::Print {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class IKeyguardStateCallback;
class PrintServiceAbility : public SystemAbility, public PrintServiceStub {
DECLARE_SYSTEM_ABILITY(PrintServiceAbility);
public:
DISALLOW_COPY_AND_MOVE(PrintServiceAbility);
PrintServiceAbility(int32_t systemAbilityId, bool runOnCreate);
PrintServiceAbility();
~PrintServiceAbility();
static sptr<PrintServiceAbility> GetInstance();
int32_t StartPrint(const std::vector<std::string> &fileList, std::string &taskId) override;
int32_t StopPrint(const std::string &taskId) override;
int32_t ConnectPrinter(const std::string &printerId) override;
int32_t DisconnectPrinter(const std::string &printerId) override;
int32_t StartDiscoverPrinter(const std::vector<std::string> &extensionList) override;
int32_t StopDiscoverPrinter() override;
int32_t QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos) override;
int32_t StartPrintJob(const PrintJob &jobinfo) override;
int32_t CancelPrintJob(const PrintJob &jobinfo) override;
int32_t AddPrinters(const std::vector<PrinterInfo> &printerInfos) override;
int32_t RemovePrinters(const std::vector<std::string> &printerIds) override;
int32_t UpdatePrinters(const std::vector<PrinterInfo> &printerInfos) override;
int32_t UpdatePrinterState(const std::string &printerId, uint32_t state) override;
int32_t UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState) override;
int32_t UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo) override;
int32_t RequestPreview(const PrintJob &jobinfo, std::string &previewResult) override;
int32_t QueryPrinterCapability(const std::string &printerId, PrinterCapability &printerCapability) override;
int32_t On(const std::string &type, const sptr<IPrintCallback> &listener) override;
int32_t Off(const std::string &type) override;
int32_t RegisterExtCallback(const std::string extensionCID,
const sptr<IPrintExtensionCallback> &listener) override;
int32_t UnregisterAllExtCallback(const std::string &extensionId) override;
int32_t Read(std::vector<uint8_t> &fileRead, const std::string &uri, uint32_t offset, uint32_t max) override;
protected:
void OnStart() override;
void OnStop() override;
private:
int32_t Init();
void InitServiceHandler();
void ManualStart();
std::string GetPrintJobId();
bool StartAbility(const AAFwk::Want &want);
PrintExtensionInfo ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo &extInfo);
bool DelayStartDiscovery();
void SendPrinterEvent(const PrinterInfo &info);
void SendPrintJobEvent(const PrintJob &jobInfo);
void SendExtensionEvent(const std::string &extensionId, const std::string &extInfo);
bool CheckPermission();
private:
ServiceRunningState state_;
static std::mutex instanceLock_;
static sptr<PrintServiceAbility> instance_;
static std::shared_ptr<AppExecFwk::EventHandler> serviceHandler_;
std::mutex mapMutex_;
std::map<std::string, sptr<IPrintCallback>> registeredListeners_;
std::map<std::string, sptr<IPrintExtensionCallback>> extCallbackMap_;
std::map<std::string, AppExecFwk::ExtensionAbilityInfo> extensionList_;
std::map<std::string, std::shared_ptr<PrintJob>> printJobList_;
std::map<std::string, std::shared_ptr<PrinterInfo>> printerInfoList_;
std::mutex lock_;
uint64_t currentJobId_;
};
} // namespace OHOS::Print
#endif // PRINT_SYSTEM_ABILITY_H

View File

@ -0,0 +1,61 @@
/*
* 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.
*/
#ifndef PRINT_SERVICE_STUB_H
#define PRINT_SERVICE_STUB_H
#include "iprint_service.h"
#include "iremote_stub.h"
namespace OHOS::Print {
class PrintServiceStub : public IRemoteStub<IPrintService> {
public:
explicit PrintServiceStub();
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
bool OnStartPrint(MessageParcel &data, MessageParcel &reply);
bool OnStopPrint(MessageParcel &data, MessageParcel &reply);
bool OnEventOn(MessageParcel &data, MessageParcel &reply);
bool OnEventOff(MessageParcel &data, MessageParcel &reply);
bool OnFindPrinterExtension(MessageParcel &data, MessageParcel &reply);
bool OnRegisterEvent(MessageParcel &data, MessageParcel &reply);
bool OnQueryAllExtension(MessageParcel &data, MessageParcel &reply);
bool OnLoadExtension(MessageParcel &data, MessageParcel &reply);
bool OnStartDiscoverPrinter(MessageParcel &data, MessageParcel &reply);
bool OnStopDiscoverPrint(MessageParcel &data, MessageParcel &reply);
bool OnAddPrinters(MessageParcel &data, MessageParcel &reply);
bool OnRemovePrinters(MessageParcel &data, MessageParcel &reply);
bool OnUpdatePrinters(MessageParcel &data, MessageParcel &reply);
bool OnConnectPrinter(MessageParcel &data, MessageParcel &reply);
bool OnDisconnectPrinter(MessageParcel &data, MessageParcel &reply);
bool OnRequestCapability(MessageParcel &data, MessageParcel &reply);
bool OnStartPrintJob(MessageParcel &data, MessageParcel &reply);
bool OnCancelPrintJob(MessageParcel &data, MessageParcel &reply);
bool OnUpdatePrinterState(MessageParcel &data, MessageParcel &reply);
bool OnUpdatePrintJobState(MessageParcel &data, MessageParcel &reply);
bool OnUpdateExtensionInfo(MessageParcel &data, MessageParcel &reply);
bool OnRequestPreview(MessageParcel &data, MessageParcel &reply);
bool OnQueryPrinterCapability(MessageParcel &data, MessageParcel &reply);
bool OnRegisterExtCallback(MessageParcel &data, MessageParcel &reply);
bool OnUnregisterAllExtCallback(MessageParcel &data, MessageParcel &reply);
bool OnRead(MessageParcel &data, MessageParcel &reply);
private:
using PrintCmdHandler = bool (PrintServiceStub::*)(MessageParcel &, MessageParcel &);
std::map<uint32_t, PrintCmdHandler> cmdMap_;
};
} // namespace OHOS::Print
#endif // PRINT_SERVICE_STUB_H

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2021-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.
*/
#include "print_bms_death_recipient.h"
#include "print_bms_helper.h"
#include "print_log.h"
namespace OHOS::Print {
void PrintBMSDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &wptrDeath)
{
PRINT_HILOGD("bundle manager service died, remove the proxy object");
if (wptrDeath == nullptr) {
PRINT_HILOGE("wptrDeath is null");
return;
}
sptr<IRemoteObject> object = wptrDeath.promote();
if (!object) {
PRINT_HILOGE("object is null");
return;
}
DelayedSingleton<PrintBMSHelper>::GetInstance()->ResetProxy();
}
} // namespace OHOS

View File

@ -0,0 +1,111 @@
/*
* Copyright (c) 2021-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.
*/
#include "print_bms_helper.h"
#include "bundle_constants.h"
#include "bundle_mgr_client.h"
#include "print_log.h"
#include "iservice_registry.h"
#include "nlohmann/json.hpp"
#include "os_account_manager.h"
#include "system_ability_definition.h"
namespace OHOS::Print {
using namespace OHOS::AppExecFwk::Constants;
PrintBMSHelper::PrintBMSHelper() : sptrBundleMgr_(nullptr), printBMSDeath_(nullptr)
{}
PrintBMSHelper::~PrintBMSHelper()
{}
bool PrintBMSHelper::QueryExtensionInfos(std::vector<AppExecFwk::ExtensionAbilityInfo> &extensionInfos)
{
std::lock_guard<std::mutex> lock(mutex_);
/*
if (!GetProxy()) {
return false;
}
*/
std::vector<int> osAccountIds;
if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(osAccountIds) != ERR_OK) {
PRINT_HILOGE("failed to QueryActiveOsAccountIds!");
return false;
}
if (osAccountIds.size() == 0) {
PRINT_HILOGE("no os account acquired!");
return false;
}
for (auto userId : osAccountIds) {
PRINT_HILOGE("active userId = %{public}d", userId);
AppExecFwk::ExtensionAbilityInfo extInfo;
extInfo.bundleName = "com.open.harmony.packagemag";
extInfo.name = "com.open.harmony.packagemag.ServiceAbility2";
extensionInfos.emplace_back(extInfo);
//sptrBundleMgr_->QueryExtensionAbilityInfos(AppExecFwk::ExtensionAbilityType::PRINT,
// userId, extensionInfos);
}
return true;
}
bool PrintBMSHelper::GetProxy()
{
if (!sptrBundleMgr_) {
sptr<ISystemAbilityManager> systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!systemAbilityManager) {
PRINT_HILOGE("Failed to get system ability mgr.");
return false;
}
sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
if (!remoteObject) {
PRINT_HILOGE("Failed to get bundle manager service.");
return false;
}
sptrBundleMgr_ = iface_cast<IBundleMgr>(remoteObject);
if ((!sptrBundleMgr_) || (!sptrBundleMgr_->AsObject())) {
PRINT_HILOGE("Failed to get system bundle manager services ability");
return false;
}
printBMSDeath_ = new PrintBMSDeathRecipient();
if (!printBMSDeath_) {
PRINT_HILOGE("Failed to create death Recipient ptr BMSDeathRecipient");
return false;
}
if (!sptrBundleMgr_->AsObject()->AddDeathRecipient(printBMSDeath_)) {
PRINT_HILOGW("Failed to add death recipient");
}
}
return true;
}
void PrintBMSHelper::ResetProxy()
{
std::lock_guard<std::mutex> lock(mutex_);
if ((sptrBundleMgr_ != nullptr) && (sptrBundleMgr_->AsObject() != nullptr)) {
sptrBundleMgr_->AsObject()->RemoveDeathRecipient(printBMSDeath_);
}
sptrBundleMgr_ = nullptr;
}
} // namespace OHOS

View File

@ -0,0 +1,118 @@
/*
* 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.
*/
#include "print_callback_proxy.h"
#include "message_parcel.h"
#include "print_log.h"
namespace OHOS::Print {
PrintCallbackProxy::PrintCallbackProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IPrintCallback>(impl) {}
bool PrintCallbackProxy::OnCallback()
{
PRINT_HILOGD("PrintCallbackProxy::OnCallback Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE("write descriptor failed");
return false;
}
int error = Remote()->SendRequest(PRINT_CALLBACK_TASK, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintCallbackProxy::OnCallback End");
return true;
}
bool PrintCallbackProxy::OnCallback(uint32_t state, const PrinterInfo &info)
{
PRINT_HILOGD("PrintCallbackProxy::OnCallback Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE("write descriptor failed");
return false;
}
PRINT_HILOGD("Printer Event argument:[%{public}d], printerId [%{public}s]", state, info.GetPrinterId().c_str());
data.WriteUint32(state);
info.Marshalling(data);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINTER, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintCallbackProxy::OnCallback End");
return true;
}
bool PrintCallbackProxy::OnCallback(uint32_t state, const PrintJob &info)
{
PRINT_HILOGD("PrintCallbackProxy::OnCallback Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE("write descriptor failed");
return false;
}
PRINT_HILOGD("PrintJob Event argument:[%{public}d], printerId [%{public}s]", state, info.GetJobId().c_str());
data.WriteUint32(state);
info.Marshalling(data);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINT_JOB, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintCallbackProxy::OnCallback End");
return true;
}
bool PrintCallbackProxy::OnCallback(const std::string &extensionId, const std::string &info)
{
PRINT_HILOGD("PrintCallbackProxy::OnCallback Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
PRINT_HILOGE("write descriptor failed");
return false;
}
data.WriteString(extensionId);
data.WriteString(info);
int error = Remote()->SendRequest(PRINT_CALLBACK_EXTINFO, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintCallbackProxy::OnCallback End");
return true;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,92 @@
/*
* 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.
*/
#include "print_extension_callback_proxy.h"
#include "message_parcel.h"
#include "print_log.h"
namespace OHOS::Print {
PrintExtensionCallbackProxy::PrintExtensionCallbackProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IPrintExtensionCallback>(impl)
{}
bool PrintExtensionCallbackProxy::OnCallback()
{
PRINT_HILOGD("PrintExtensionCallbackProxy::OnCallBack Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
int error = Remote()->SendRequest(PRINT_EXTCB, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintExtensionCallbackProxy::OnCallBack End");
return true;
}
bool PrintExtensionCallbackProxy::OnCallback(const std::string &printerId)
{
PRINT_HILOGD("PrintExtensionCallbackProxy::OnCallBack Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
int error = Remote()->SendRequest(PRINT_EXTCB_PRINTER, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintExtensionCallbackProxy::OnCallBack End");
return true;
}
bool PrintExtensionCallbackProxy::OnCallback(const PrintJob &job)
{
PRINT_HILOGD("PrintExtensionCallbackProxy::OnCallBack Start");
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
job.Marshalling(data);
int error = Remote()->SendRequest(PRINT_EXTCB_PRINTJOB, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintExtensionCallbackProxy::OnCallBack End");
return true;
}
bool PrintExtensionCallbackProxy::OnCallback(const std::string &printerId, MessageParcel &reply)
{
PRINT_HILOGD("PrintExtcbProxy::OnCallBack Start");
MessageParcel data;
MessageOption option;
data.WriteInterfaceToken(GetDescriptor());
data.WriteString(printerId);
int error = Remote()->SendRequest(PRINT_EXTCB_PRINTCAPABILITY, data, reply, option);
if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false;
}
PRINT_HILOGD("PrintExtcbProxy::OnCallBack End");
return true;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,768 @@
/*
* 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.
*/
#include "print_service_ability.h"
#include <cerrno>
#include <ctime>
#include <string>
#include <sys/time.h>
#include <thread>
#include <unistd.h>
#include "accesstoken_kit.h"
#include "core_service_client.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "print_constant.h"
#include "print_log.h"
#include "printer_info.h"
#include "system_ability.h"
#include "system_ability_definition.h"
#include "print_bms_helper.h"
namespace OHOS::Print {
using namespace std;
using namespace OHOS::HiviewDFX;
using namespace Security::AccessToken;
const uint32_t MAX_RETRY_TIMES = 10;
const uint32_t START_ABILITY_INTERVAL = 6;
const uint32_t START_DISCOVERY_DELAY = 5000;
const int64_t INIT_INTERVAL = 5000L;
static const std::string PRINTEXT_BUNDLE_NAME = "com.open.harmony.packagemag";
static const std::string PRINTEXT_ABILITY_NAME = "com.open.harmony.packagemag.ServiceAbility2";
static const std::string SPOOLER_BUNDLE_NAME = "com.example.spoolerdemo";
static const std::string SPOOLER_ABILITY_NAME = "com.example.spoolerdemo.MainAbility";
static const std::string LAUNCH_PARAMETER_JOB_ID = "jobId";
static const std::string LAUNCH_PARAMETER_FILE_LIST = "fileList";
static const std::string PRINT_PERMISSION_NAME_INTERNET = "ohos.permission.PRINT";
static const std::string PRINT_PERMISSION_NAME_SESSION = "ohos.permission.PRINT_SESSION_MANAGER";
const std::string PRINTER_EVENT_TYPE = "printerStateChange";
const std::string PRINTJOB_EVENT_TYPE = "jobStateChange";
const std::string EXTINFO_EVENT_TYPE = "extInfoChange";
const std::string EVENT_BLOCK = "blocked";
const std::string EVENT_SUCCESS = "success";
const std::string EVENT_FAIL = "failed";
const std::string EVENT_CANCEL = "cancelled";
REGISTER_SYSTEM_ABILITY_BY_ID(PrintServiceAbility, PRINT_SERVICE_ID, true);
std::mutex PrintServiceAbility::instanceLock_;
sptr<PrintServiceAbility> PrintServiceAbility::instance_;
std::shared_ptr<AppExecFwk::EventHandler> PrintServiceAbility::serviceHandler_;
PrintServiceAbility::PrintServiceAbility(int32_t systemAbilityId, bool runOnCreate)
: SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START), currentJobId_(0)
{}
PrintServiceAbility::~PrintServiceAbility()
{
PRINT_HILOGE("~PrintServiceAbility state_ is %{public}d.", static_cast<int>(state_));
}
sptr<PrintServiceAbility> PrintServiceAbility::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> autoLock(instanceLock_);
if (instance_ == nullptr) {
instance_ = new PrintServiceAbility(PRINT_SERVICE_ID, true);
PRINT_HILOGE("PrintServiceAbility instance_ create,addr=%{public}p", instance_.GetRefPtr());
}
}
return instance_;
}
#if 1
int32_t PrintServiceAbility::Init()
{
bool ret = Publish(PrintServiceAbility::GetInstance());
if (!ret) {
PRINT_HILOGE("PrintServiceAbility Publish failed.");
return ERROR_SERVER_FAIL;
}
state_ = ServiceRunningState::STATE_RUNNING;
uint32_t threadNum = 4;
PRINT_HILOGI("Start Print Service Manager with %{public}d threas", threadNum);
PRINT_HILOGE("state_ is %{public}d.", static_cast<int>(state_));
PRINT_HILOGI("Init PrintServiceAbility success.");
return ERR_OK;
}
void PrintServiceAbility::OnStart()
{
PRINT_HILOGI("PrintServiceAbility::Enter OnStart.");
if (instance_ == nullptr) {
instance_ = this;
}
if (state_ == ServiceRunningState::STATE_RUNNING) {
PRINT_HILOGI("PrintServiceAbility is already running.");
return;
}
InitServiceHandler();
int32_t ret = Init();
if (ret != ERR_OK) {
auto callback = [=]() { Init(); };
serviceHandler_->PostTask(callback, INIT_INTERVAL);
PRINT_HILOGE("PrintServiceAbility Init failed. Try again 5s later");
return;
}
state_ = ServiceRunningState::STATE_RUNNING;
return;
}
void PrintServiceAbility::InitServiceHandler()
{
PRINT_HILOGI("InitServiceHandler started.");
if (serviceHandler_ != nullptr) {
PRINT_HILOGI("InitServiceHandler already init.");
return;
}
std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("PrintServiceAbility");
serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
PRINT_HILOGI("InitServiceHandler succeeded.");
}
void PrintServiceAbility::ManualStart()
{
if (state_ != ServiceRunningState::STATE_RUNNING) {
PRINT_HILOGI("PrintServiceAbility restart.");
OnStart();
}
}
std::string PrintServiceAbility::GetPrintJobId()
{
std::lock_guard<std::mutex> autoLock(instanceLock_);
return std::to_string(currentJobId_++);
}
void PrintServiceAbility::OnStop()
{
PRINT_HILOGI("OnStop started.");
if (state_ != ServiceRunningState::STATE_RUNNING) {
return;
}
serviceHandler_ = nullptr;
state_ = ServiceRunningState::STATE_NOT_START;
PRINT_HILOGI("OnStop end.");
}
int32_t PrintServiceAbility::StartPrint(const std::vector<std::string> &fileList, std::string &taskId)
{
ManualStart();
PRINT_HILOGD("PrintServiceAbility StartPrint started.");
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::string jobId = GetPrintJobId();
auto printJob = std::make_shared<PrintJob>();
if (printJob == nullptr) {
PRINT_HILOGE("fail to create print job");
return ERROR_GENERIC_FAIL;
}
printJob->SetFiles(fileList);
printJob->SetJobId(jobId);
printJob->SetJobState(PRINT_JOB_PREPARED);
AAFwk::Want want;
want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_ABILITY_NAME);
want.SetParam(LAUNCH_PARAMETER_JOB_ID, jobId);
want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList);
if (!StartAbility(want)) {
PRINT_HILOGE("Failed to start spooler ability");
return ERROR_SERVER_FAIL;
}
printJobList_.insert(std::make_pair(jobId, printJob));
taskId = jobId;
return ERROR_NONE;
}
int32_t PrintServiceAbility::StopPrint(const std::string &taskId)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("PrintServiceAbility StopPrint started.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::ConnectPrinter(const std::string &printerId)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("ConnectPrinter started.");
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_CONNECT_PRINTER);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback(printerId);
}
*/
PRINT_HILOGW("ConnectPrinter Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
int32_t PrintServiceAbility::DisconnectPrinter(const std::string &printerId)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("DisconnectPrinter started.");
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_DISCONNECT_PRINTER);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback(printerId);
}
*/
PRINT_HILOGW("DisconnectPrinter Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
int32_t PrintServiceAbility::StartDiscoverPrinter(const std::vector<std::string> &extensionList)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("StartDiscoverPrinter started.");
std::vector<AppExecFwk::ExtensionAbilityInfo> abilityList;
for (auto extensionId : extensionList) {
if (extensionList_.find(extensionId) != extensionList_.end()) {
abilityList.emplace_back(extensionList_[extensionId]);
}
}
if (abilityList.empty()) {
for (auto it : extensionList_) {
abilityList.emplace_back(it.second);
}
}
if (abilityList.empty()) {
PRINT_HILOGW("No valid extension found");
return ERROR_INVALID_EXTENSION;
}
for (auto ability : abilityList) {
AAFwk::Want want;
want.SetElementName(ability.bundleName, ability.name);
if (!StartAbility(want)) {
PRINT_HILOGE("Failed to load extension %{public}s", ability.name.c_str());
}
}
auto callback = [=]() { DelayStartDiscovery(); };
serviceHandler_->PostTask(callback, START_DISCOVERY_DELAY);
PRINT_HILOGD("StartDiscoverPrinter end.");
return ERROR_NONE;
}
bool PrintServiceAbility::DelayStartDiscovery()
{
PRINT_HILOGD("DelayStartDiscovery started.");
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_START_DISCOVERY);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback();
}
*/
PRINT_HILOGW("StartDiscoverPrinter Not Register Yet!!!");
return false;
}
int32_t PrintServiceAbility::StopDiscoverPrinter()
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("StopDiscoverPrinter started.");
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_STOP_DISCOVERY);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback();
}
*/
PRINT_HILOGW("StopDiscoverPrinter Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
int32_t PrintServiceAbility::QueryAllExtension(std::vector<PrintExtensionInfo> &arrayExtensionInfo)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("QueryAllExtension started.");
std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfo;
if (!DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryExtensionInfos(extensionInfo)) {
PRINT_HILOGE("Failed to query extension");
return ERROR_SERVER_FAIL;
}
extensionList_.clear();
for (auto extInfo : extensionInfo) {
PRINT_HILOGD("bundleName = %{public}s", extInfo.bundleName.c_str());
PRINT_HILOGD("moduleName = %{public}s", extInfo.moduleName.c_str());
PRINT_HILOGD("name = %{public}s", extInfo.name.c_str());
PrintExtensionInfo printExtInfo = ConvertToPrintExtensionInfo(extInfo);
arrayExtensionInfo.emplace_back(printExtInfo);
extensionList_.insert(std::make_pair(printExtInfo.GetExtensionId(), extInfo));
}
PRINT_HILOGE("QueryAllExtension End.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::StartPrintJob(const PrintJob &jobInfo)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("StartPrintJob started.");
/*
if (printJobList_.find(jobInfo.GetJobId()) != printJobList_.end()) {
}
auto it = extCallbackMap_.find(PRINT_EXTCB_START_PRINT);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback(jobInfo);
}
*/
PRINT_HILOGW("StartPrintJob Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
int32_t PrintServiceAbility::CancelPrintJob(const PrintJob &jobInfo)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("CancelPrintJob started.");
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_CANCEL_PRINT);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback(jobInfo);
}
*/
PRINT_HILOGW("CancelPrintJob Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
int32_t PrintServiceAbility::AddPrinters(const std::vector<PrinterInfo> &printerInfos)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("AddPrinters started. Total size is %{public}d", printerInfoList_.size());
for (auto info : printerInfos) {
if (printerInfoList_.find(info.GetPrinterId()) != printerInfoList_.end()) {
PRINT_HILOGE("duplicate printer id, ingore it");
continue;
}
auto printerInfo = std::make_shared<PrinterInfo>(info);
if (printerInfo == nullptr) {
PRINT_HILOGE("fail to create printer info object");
continue;
}
printerInfo->SetPrinterState(PRINTER_ADDED);
printerInfoList_.insert(std::make_pair(printerInfo->GetPrinterId(), printerInfo));
SendPrinterEvent(*printerInfo);
}
PRINT_HILOGD("AddPrinters end. Total size is %{public}d", printerInfoList_.size());
return ERROR_NONE;
}
int32_t PrintServiceAbility::RemovePrinters(const std::vector<std::string> &printerIds)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("RemovePrinters started. Total size is %{public}d", printerInfoList_.size());
for (auto printerId : printerIds) {
auto printerIt = printerInfoList_.find(printerId);
if (printerIt == printerInfoList_.end()) {
PRINT_HILOGE("invalid printer id, ingore it");
continue;
}
PrinterInfo info = *printerIt->second;
info.SetPrinterState(PRINTER_REMOVED);
SendPrinterEvent(info);
printerInfoList_.erase(printerIt);
}
PRINT_HILOGD("RemovePrinters end. Total size is %{public}d", printerInfoList_.size());
return ERROR_NONE;
}
int32_t PrintServiceAbility::UpdatePrinters(const std::vector<PrinterInfo> &printerInfos)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("UpdatePrinters started. Total size is %{public}d", printerInfoList_.size());
for (auto info : printerInfos) {
auto printerIt = printerInfoList_.find(info.GetPrinterId());
if (printerIt == printerInfoList_.end()) {
PRINT_HILOGE("invalid printer id, ingore it");
continue;
}
*printerIt->second = info;
printerIt->second->SetPrinterState(PRINTER_UPDATE_CAP);
SendPrinterEvent(*printerIt->second);
}
PRINT_HILOGD("UpdatePrinters end. Total size is %{public}d", printerInfoList_.size());
return ERROR_NONE;
}
int32_t PrintServiceAbility::UpdatePrinterState(const std::string &printerId, uint32_t state)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
if (state > PRINTER_UNKNOWN) {
return ERROR_INVALID_PARAMETER;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("UpdatePrinterState started. %{printerId}s, state [%{public}d]", printerId.c_str(), state);
if (printerInfoList_.find(printerId) == printerInfoList_.end()) {
return ERROR_INVALID_PRINTER;
}
auto printerInfo = printerInfoList_[printerId];
printerInfo->SetPrinterState(state);
SendPrinterEvent(*printerInfo);
PRINT_HILOGD("UpdatePrinterState end.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
if (state > PRINT_JOB_UNKNOWN) {
return ERROR_INVALID_PARAMETER;
}
if (state == PRINT_JOB_BLOCKED && (subState < PRINT_JOB_BLOCKED_OFFLINE || subState > PRINT_JOB_BLOCKED_UNKNOWN)) {
return ERROR_INVALID_PARAMETER;
}
if (state == PRINT_JOB_COMPLETED && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT) {
return ERROR_INVALID_PARAMETER;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("UpdatePrintJobState started. %{public}s, state [%{public}d]", jobId.c_str(), state);
if (printJobList_.find(jobId) == printJobList_.end()) {
return ERROR_INVALID_PRINTJOB;
}
auto printJob = printJobList_[jobId];
printJob->SetJobState(state);
printJob->SetSubState(subState);
SendPrintJobEvent(*printJob);
PRINT_HILOGD("UpdatePrintJobState end.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::UpdateExtensionInfo(const std::string &extensionId, const std::string &extInfo)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("UpdateExtensionInfo started. %{public}s, extInfo [%{public}s]",
extensionId.c_str(), extInfo.c_str());
if (extensionList_.find(extensionId) == extensionList_.end()) {
return ERROR_INVALID_EXTENSION;
}
SendExtensionEvent(extensionId, extInfo);
PRINT_HILOGD("UpdateExtensionInfo end.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::RequestPreview(const PrintJob &jobInfo, std::string &previewResult)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("RequestPreview started.");
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_REQUEST_PREVIEW);
if (it != extCallbackMap_.end()) {
return it->second->OnCallback(jobInfo);
}
*/
PRINT_HILOGW("RequestPreview Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
int32_t PrintServiceAbility::QueryPrinterCapability(const std::string &printerId, PrinterCapability &printerCapability)
{
ManualStart();
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("QueryPrinterCapability started.");
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
/*
auto it = extCallbackMap_.find(PRINT_EXTCB_REQUEST_CAP);
MessageParcel reply;
if (it != extCallbackMap_.end()) {
PRINT_HILOGD("QueryPrinterCapability OnCallback.");
if (!it->second->OnCallback(printerId, reply)) {
PRINT_HILOGE("Failed to get printer capability");
return ERROR_SERVER_FAIL;
}
auto capPtr = PrinterCapability::Unmarshalling(reply);
if (capPtr == nullptr) {
PRINT_HILOGE("Failed to get printer capability");
return ERROR_SERVER_FAIL;
}
printerCapability = *capPtr;
printerCapability.Dump();
return ERROR_NONE;
}
*/
PRINT_HILOGW("QueryPrinterCapability Not Register Yet!!!");
return ERROR_SERVER_FAIL;
}
bool PrintServiceAbility::CheckPermission()
{
return true;
}
int32_t PrintServiceAbility::RegisterExtCallback(const std::string extensionCID,
const sptr<IPrintExtensionCallback> &listener)
{
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
/*
PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback started. callbackId=%{public}d", callbackId);
if (callbackId >= PRINT_EXTCB_MAX) {
PRINT_HILOGE("Invalid callback id");
return ERROR_INVALID_PARAMETER;
}
std::lock_guard<std::mutex> lock(mapMutex_);
auto it = extCallbackMap_.find(callbackId);
if (it == extCallbackMap_.end()) {
extCallbackMap_.insert(std::make_pair(callbackId, listener));
} else {
PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback Replace listener.");
extCallbackMap_[callbackId] = listener;
}
*/
PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback end.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::UnregisterAllExtCallback(const std::string &extensionId)
{
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback started.");
std::lock_guard<std::mutex> lock(mapMutex_);
extCallbackMap_.clear();
PRINT_HILOGD("PrintServiceAbility::UnregisterAllExtCallback end.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::Read(std::vector<uint8_t> &fileRead, const std::string &uri, uint32_t offset, uint32_t max)
{
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
return ERROR_NONE;
}
int32_t PrintServiceAbility::On(const std::string &type, const sptr<IPrintCallback> &listener)
{
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("PrintServiceAbility::On started. type=%{public}s", type.c_str());
auto iter = registeredListeners_.find(type);
if (iter == registeredListeners_.end()) {
const auto temp = registeredListeners_.insert(std::make_pair(type, listener));
if (!temp.second) {
PRINT_HILOGE("PrintServiceAbility::On insert type=%{public}s object fail.", type.c_str());
return ERROR_SERVER_FAIL;
}
} else {
PRINT_HILOGD("PrintServiceAbility::On Replace listener.");
registeredListeners_[type] = listener;
}
PRINT_HILOGD("PrintServiceAbility::On end.");
return ERROR_NONE;
}
int32_t PrintServiceAbility::Off(const std::string &type)
{
if (!CheckPermission()) {
PRINT_HILOGE("no permission to access print service");
return ERROR_NO_PERMISSION;
}
std::lock_guard<std::mutex> lock(mapMutex_);
PRINT_HILOGD("PrintServiceAbility::Off started.");
auto iter = registeredListeners_.find(type);
if (iter != registeredListeners_.end()) {
PRINT_HILOGD("PrintServiceAbility::Off delete type=%{public}s object message.", type.c_str());
registeredListeners_.erase(iter);
return ERROR_NONE;
}
return ERROR_INVALID_PARAMETER;
}
bool PrintServiceAbility::StartAbility(const AAFwk::Want &want)
{
AppExecFwk::ElementName element = want.GetElement();
AAFwk::AbilityManagerClient::GetInstance()->Connect();
uint32_t retry = 0;
while (retry++ < MAX_RETRY_TIMES) {
PRINT_HILOGD("PrintServiceAbility::StartAbility %{public}s %{public}s",
element.GetBundleName().c_str(), element.GetAbilityName().c_str());
if (AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want) == 0) {
break;
}
break;
std::this_thread::sleep_for(std::chrono::seconds(START_ABILITY_INTERVAL));
PRINT_HILOGD("PrintServiceAbility::StartAbility %{public}d", retry);
}
if (retry > MAX_RETRY_TIMES) {
PRINT_HILOGE("PrintServiceAbility::StartAbility --> failed ");
return false;
}
return true;
}
PrintExtensionInfo PrintServiceAbility::ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo &extInfo)
{
PrintExtensionInfo printExtInfo;
printExtInfo.SetExtensionId(extInfo.bundleName);
printExtInfo.SetVendorId(extInfo.bundleName);
printExtInfo.SetVendorName(extInfo.bundleName);
printExtInfo.SetVendorIcon(0);
printExtInfo.SetVersion("1.0.0");
return printExtInfo;
}
void PrintServiceAbility::SendPrinterEvent(const PrinterInfo &info)
{
PRINT_HILOGD("PrintServiceAbility::SendPrinterEvent type %{public}s, %{public}d",
info.GetPrinterId().c_str(), info.GetPrinterState());
auto eventIt = registeredListeners_.find(PRINTER_EVENT_TYPE);
if (eventIt != registeredListeners_.end()) {
eventIt->second->OnCallback(info.GetPrinterState(), info);
}
}
void PrintServiceAbility::SendPrintJobEvent(const PrintJob &jobInfo)
{
PRINT_HILOGD("PrintServiceAbility::SendPrintJobEvent type %{public}s, %{public}d",
jobInfo.GetJobId().c_str(), jobInfo.GetJobState());
auto eventIt = registeredListeners_.find(PRINTJOB_EVENT_TYPE);
if (eventIt != registeredListeners_.end()) {
eventIt->second->OnCallback(jobInfo.GetJobState(), jobInfo);
}
std::string stateInfo = "";
if (jobInfo.GetJobState() == PRINT_JOB_BLOCKED) {
stateInfo = EVENT_BLOCK;
} else {
switch (jobInfo.GetSubState()) {
case PRINT_JOB_COMPLETED_SUCCESS:
stateInfo = EVENT_SUCCESS;
break;
case PRINT_JOB_COMPLETED_FAILED:
stateInfo = EVENT_FAIL;
break;
case PRINT_JOB_COMPLETED_CANCELLED:
stateInfo = EVENT_CANCEL;
break;
default:
break;
}
}
std::string taskEvent = jobInfo.GetJobId() + stateInfo;
auto taskEventIt = registeredListeners_.find(taskEvent);
if (taskEventIt != registeredListeners_.end()) {
taskEventIt->second->OnCallback();
}
}
void PrintServiceAbility::SendExtensionEvent(const std::string &extensionId, const std::string &extInfo)
{
PRINT_HILOGD("PrintServiceAbility::SendExtensionEvent type %{public}s", extInfo.c_str());
auto eventIt = registeredListeners_.find(EXTINFO_EVENT_TYPE);
if (eventIt != registeredListeners_.end()) {
eventIt->second->OnCallback(extensionId, extInfo);
}
}
#endif
} // namespace OHOS::Print

View File

@ -0,0 +1,432 @@
/*
* 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.
*/
#include "print_service_stub.h"
#include "ipc_skeleton.h"
#include "iprint_service.h"
#include "message_parcel.h"
#include "print_constant.h"
#include "print_extension_info.h"
#include "print_job.h"
#include "print_log.h"
namespace OHOS::Print {
using namespace OHOS::HiviewDFX;
PrintServiceStub::PrintServiceStub()
{
cmdMap_[CMD_START_PRINT] = &PrintServiceStub::OnStartPrint;
cmdMap_[CMD_STOP_PRINT] = &PrintServiceStub::OnStopPrint;
cmdMap_[CMD_CONNECTPRINTER] = &PrintServiceStub::OnConnectPrinter;
cmdMap_[CMD_DISCONNECTPRINTER] = &PrintServiceStub::OnDisconnectPrinter;
cmdMap_[CMD_STARTDISCOVERPRINTER] = &PrintServiceStub::OnStartDiscoverPrinter;
cmdMap_[CMD_STOPDISCOVERPRINTER] = &PrintServiceStub::OnStopDiscoverPrint;
cmdMap_[CMD_QUERYALLEXTENSION] = &PrintServiceStub::OnQueryAllExtension;
cmdMap_[CMD_STARTPRINTJOB] = &PrintServiceStub::OnStartPrintJob;
cmdMap_[CMD_CANCELPRINTJOB] = &PrintServiceStub::OnCancelPrintJob;
cmdMap_[CMD_ADDPRINTERS] = &PrintServiceStub::OnAddPrinters;
cmdMap_[CMD_REMOVEPRINTERS] = &PrintServiceStub::OnRemovePrinters;
cmdMap_[CMD_UPDATEPRINTERS] = &PrintServiceStub::OnUpdatePrinters;
cmdMap_[CMD_UPDATEPRINTERSTATE] = &PrintServiceStub::OnUpdatePrinterState;
cmdMap_[CMD_UPDATEPRINTJOBSTATE] = &PrintServiceStub::OnUpdatePrintJobState;
cmdMap_[CMD_UPDATEEXTENSIONINFO] = &PrintServiceStub::OnUpdateExtensionInfo;
cmdMap_[CMD_REQUESTPREVIEW] = &PrintServiceStub::OnRequestPreview;
cmdMap_[CMD_QUERYPRINTERCAPABILITY] = &PrintServiceStub::OnQueryPrinterCapability;
cmdMap_[CMD_ON] = &PrintServiceStub::OnEventOn;
cmdMap_[CMD_OFF] = &PrintServiceStub::OnEventOff;
cmdMap_[CMD_REG_EXT_CB] = &PrintServiceStub::OnRegisterExtCallback;
cmdMap_[CMD_UNREG_EXT_CB] = &PrintServiceStub::OnUnregisterAllExtCallback;
cmdMap_[CMD_READ_DATA] = &PrintServiceStub::OnRead;
}
int32_t PrintServiceStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
PRINT_HILOGD("OnRemoteRequest started, code = %{public}d", code);
auto descriptorToken = data.ReadInterfaceToken();
if (descriptorToken != GetDescriptor()) {
PRINT_HILOGE("Remote descriptor not the same as local descriptor.");
return ERROR_RPC_FAIL;
}
auto itFunc = cmdMap_.find(code);
if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second;
if (requestFunc != nullptr) {
return (this->*requestFunc)(data, reply);
}
}
PRINT_HILOGW("default case, need check.");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
bool PrintServiceStub::OnStartPrint(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnStartPrint in");
std::vector<std::string> fileList;
reply.ReadStringVector(&fileList);
std::string result = "";
int32_t ret = StartPrint(fileList, result);
reply.WriteInt32(ret);
reply.WriteString(result);
PRINT_HILOGD("PrintServiceStub::OnStartPrint out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnStopPrint(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnStopPrint in");
std::string taskId = reply.ReadString();
int32_t ret = StopPrint(taskId);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnStopPrint out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnConnectPrinter(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnConnectPrinter in");
int32_t ret = ConnectPrinter(data.ReadString());
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnConnectPrinter out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnDisconnectPrinter(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnDisconnectPrinter in");
int32_t ret = DisconnectPrinter(data.ReadString());
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnDisconnectPrinter out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnStartDiscoverPrinter(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnStartDiscoverPrinter in");
std::vector<std::string> extensionList;
data.ReadStringVector(&extensionList);
int32_t ret = StartDiscoverPrinter(extensionList);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnStartDiscoverPrinter out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnStopDiscoverPrint(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnStopDiscoverPrint in");
int32_t ret = StopDiscoverPrinter();
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnStopDiscoverPrint out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnQueryAllExtension(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnQueryAllExtension in");
std::vector<PrintExtensionInfo> printerInfo;
int32_t ret = QueryAllExtension(printerInfo);
reply.WriteInt32(ret);
if (ret == ERROR_NONE) {
uint32_t size = static_cast<uint32_t>(printerInfo.size());
reply.WriteUint32(size);
for (uint32_t index = 0; index < size; index++) {
printerInfo[index].Marshalling(reply);
}
}
PRINT_HILOGD("PrintServiceStub::OnQueryAllExtension out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnStartPrintJob(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnStartPrintJob in");
int32_t ret = ERROR_RPC_FAIL;
auto jobInfoPtr = PrintJob::Unmarshalling(data);
if (jobInfoPtr != nullptr) {
jobInfoPtr->Dump();
ret = StartPrintJob(*jobInfoPtr);
}
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnStartPrintJob out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnCancelPrintJob(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnCancelPrintJob in");
int32_t ret = ERROR_RPC_FAIL;
auto jobInfoPtr = PrintJob::Unmarshalling(data);
if (jobInfoPtr != nullptr) {
jobInfoPtr->Dump();
ret = CancelPrintJob(*jobInfoPtr);
}
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnStartPrintJob out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnAddPrinters(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnAddPrinters in");
std::vector<PrinterInfo> printerInfos;
uint32_t len = data.ReadUint32();
PRINT_HILOGD("OnStartDiscoverPrinter len = %{public}d", len);
for (uint32_t i = 0; i < len; i++) {
auto infoPtr = PrinterInfo::Unmarshalling(data);
if (infoPtr == nullptr) {
PRINT_HILOGW("invalid printer object");
continue;
}
infoPtr->Dump();
printerInfos.emplace_back(*infoPtr);
}
int32_t ret = ERROR_RPC_FAIL;
if (printerInfos.size() > 0) {
ret = AddPrinters(printerInfos);
}
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnAddPrinters out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnRemovePrinters(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnRemovePrinters in");
std::vector<std::string> printerIds;
data.ReadStringVector(&printerIds);
PRINT_HILOGD("OnStartDiscoverPrinter len = %{public}zd", printerIds.size());
int32_t ret = RemovePrinters(printerIds);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnRemovePrinters out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnUpdatePrinters(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnUpdatePrinters in");
std::vector<PrinterInfo> printerInfos;
uint32_t len = data.ReadUint32();
PRINT_HILOGD("OnStartDiscoverPrinter len = %{public}d", len);
for (uint32_t i = 0; i < len; i++) {
auto infoPtr = PrinterInfo::Unmarshalling(data);
if (infoPtr == nullptr) {
PRINT_HILOGW("invalid printer object");
continue;
}
infoPtr->Dump();
printerInfos.emplace_back(*infoPtr);
}
int32_t ret = ERROR_RPC_FAIL;
if (printerInfos.size() > 0) {
ret = UpdatePrinters(printerInfos);
}
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnUpdatePrinters out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnUpdatePrinterState(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnUpdatePrinterState in");
std::string printerId = data.ReadString();
uint32_t state = data.ReadUint32();
int32_t ret = UpdatePrinterState(printerId, state);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnUpdatePrinterState out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnUpdatePrintJobState(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnUpdatePrintJobState in");
std::string jobId = data.ReadString();
uint32_t state = data.ReadUint32();
uint32_t subState = data.ReadUint32();
PRINT_HILOGD("OnUpdatePrintJobState jobId = %{public}s", jobId.c_str());
PRINT_HILOGD("OnUpdatePrintJobState state = %{public}d", state);
PRINT_HILOGD("OnUpdatePrintJobState subState = %{public}d", subState);
int32_t ret = UpdatePrintJobState(jobId, state, subState);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnUpdatePrintJobState out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnUpdateExtensionInfo(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnUpdateExtensionInfo in");
std::string extensionId = data.ReadString();
std::string extInfo = data.ReadString();
PRINT_HILOGD("OnUpdateExtensionInfo extensionId = %{public}s", extensionId.c_str());
PRINT_HILOGD("OnUpdateExtensionInfo extInfo = %{public}s", extInfo.c_str());
int32_t ret = UpdateExtensionInfo(extensionId, extInfo);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnUpdateExtensionInfo out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnRequestPreview(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnRequestPreview in");
int32_t ret = ERROR_RPC_FAIL;
std::string previewResult = "";
auto jobInfoPtr = PrintJob::Unmarshalling(data);
if (jobInfoPtr != nullptr) {
jobInfoPtr->Dump();
ret = RequestPreview(*jobInfoPtr, previewResult);
}
reply.WriteInt32(ret);
reply.WriteString(previewResult);
PRINT_HILOGD("PrintServiceStub::OnRequestPreview out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnQueryPrinterCapability(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnQueryPrinterCapability in");
std::string printerId = data.ReadString();
PRINT_HILOGD("printerId : %{public}s", printerId.c_str());
PrinterCapability printerCapability;
int32_t ret = QueryPrinterCapability(printerId, printerCapability);
reply.WriteInt32(ret);
printerCapability.Marshalling(reply);
PRINT_HILOGD("PrintServiceStub::OnQueryPrinterCapability out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnEventOn(MessageParcel &data, MessageParcel &reply)
{
std::string type = data.ReadString();
PRINT_HILOGD("PrintServiceStub::OnEventOn type=%{public}s ", type.c_str());
if (type.empty()) {
PRINT_HILOGE("PrintServiceStub::OnEventOn type is null.");
reply.WriteInt32(ERROR_RPC_FAIL);
return false;
}
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
PRINT_HILOGE("PrintServiceStub::OnEventOn remote is nullptr");
reply.WriteInt32(ERROR_RPC_FAIL);
return false;
}
sptr<IPrintCallback> listener = iface_cast<IPrintCallback>(remote);
if (listener.GetRefPtr() == nullptr) {
PRINT_HILOGE("PrintServiceStub::OnEventOn listener is null");
reply.WriteInt32(ERROR_RPC_FAIL);
return false;
}
int32_t ret = On(type, listener);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnEventOn out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnEventOff(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnEventOff in");
std::string type = data.ReadString();
PRINT_HILOGD("PrintServiceStub::OnEventOff type=%{public}s ", type.c_str());
int32_t ret = Off(type);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnEventOff out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnRegisterExtCallback(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnRegisterExtCallback in");
std::string extensionCID = data.ReadString();
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
PRINT_HILOGD("PrintServiceStub::OnRegisterExtCallback remote is nullptr");
reply.WriteInt32(ERROR_RPC_FAIL);
return false;
}
sptr<IPrintExtensionCallback> listener = iface_cast<IPrintExtensionCallback>(remote);
if (listener.GetRefPtr() == nullptr) {
PRINT_HILOGD("PrintServiceStub::OnRegisterExtCallback listener is null");
reply.WriteInt32(ERROR_RPC_FAIL);
return false;
}
int32_t ret = RegisterExtCallback(extensionCID, listener);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnRegisterExtCallback out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnUnregisterAllExtCallback(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnRegisterExtCallback in");
std::string extensionId = data.ReadString();
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
PRINT_HILOGD("PrintServiceStub::OnUnregisterAllExtCallback remote is nullptr");
reply.WriteInt32(ERROR_RPC_FAIL);
return true;
}
sptr<IPrintExtensionCallback> listener = iface_cast<IPrintExtensionCallback>(remote);
if (listener.GetRefPtr() == nullptr) {
PRINT_HILOGD("PrintServiceStub::OnUnregisterAllExtCallback listener is null");
reply.WriteInt32(ERROR_RPC_FAIL);
return false;
}
int32_t ret = UnregisterAllExtCallback(extensionId);
reply.WriteInt32(ret);
PRINT_HILOGD("PrintServiceStub::OnUnregisterAllExtCallback out");
return ret == ERROR_NONE;
}
bool PrintServiceStub::OnRead(MessageParcel &data, MessageParcel &reply)
{
PRINT_HILOGD("PrintServiceStub::OnRead in");
std::string fileUrl = data.ReadString();
uint32_t offset = data.ReadUint32();
uint32_t max = data.ReadUint32();
FILE *file = fopen(fileUrl.c_str(), "rb");
if (file == nullptr) {
PRINT_HILOGD("PrintServiceStub::OnRead no permission");
if (!reply.WriteBool(false)) {
return false;
}
return true;
}
fseek(file, 0, SEEK_END);
uint32_t totalSize = static_cast<uint32_t>(ftell(file));
uint32_t size = totalSize - offset;
if (size > max) {
size = max;
}
std::vector<uint8_t> fileRead;
fileRead.resize(size);
fread(&fileRead[0], 1, size, file);
if (!reply.WriteBool(true)) {
PRINT_HILOGD("PrintServiceStub::OnRead failed to write response");
return false;
}
reply.WriteUInt8Vector(fileRead);
PRINT_HILOGD("PrintServiceStub::OnRead out");
return true;
}
} // namespace OHOS::Print

View File

@ -0,0 +1,93 @@
/*
* 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.
*/
#ifndef PRINT_CONSTANT_H
#define PRINT_CONSTANT_H
#include <string>
namespace OHOS::Print {
const std::string INVALID_PRINT_TASK = "invalid_print_task";
enum PrintErrorCode {
ERROR_NONE = 0,
ERROR_GENERIC_FAIL = -1,
ERROR_INVALID_PARAMETER = -2,
ERROR_NO_PERMISSION = -3,
ERROR_RPC_FAIL = -4,
ERROR_SERVER_FAIL = -5,
ERROR_INVALID_EXTENSION = -6,
ERROR_INVALID_PRINTER = -7,
ERROR_INVALID_PRINTJOB = -8,
ERROR_FILE_IO = -9,
ERROR_UNKNOWN = -255,
};
const std::string ErrorMessage[] = {
"ERROR_NONE",
"ERROR_GENERIC_FAIL",
"ERROR_INVALID_PARAMETER",
"ERROR_NO_PERMISSION",
"ERROR_RPC_FAIL",
"ERROR_SERVER_FAIL",
"ERROR_INVALID_EXTENSION",
"ERROR_INVALID_PRINTER",
"ERROR_INVALID_PRINTJOB",
"ERROR_FILE_IO",
"ERROR_UNKNOWN",
};
enum PrinterState {
PRINTER_ADDED = 0, // new printers arrival
PRINTER_REMOVED = 1, // printers lost
PRINTER_UPDATE_CAP = 2, // printers update
PRINTER_CONNECTED = 3, // printer has been connected
PRINTER_DISCONNECTED = 4, // printer has been disconnected
PRINTER_RUNNING = 5, // printer is working
PRINTER_UNKNOWN = 6, // unknown printer state
};
enum PrintJobState {
PRINT_JOB_PREPARED = 0, // initial state of print job
PRINT_JOB_QUEUED = 1, // deliver print job to the printer
PRINT_JOB_RUNNING = 2, // executing print job
PRINT_JOB_BLOCKED = 3, // print job has been blocked
PRINT_JOB_COMPLETED = 4, // print job ocmpleted
PRINT_JOB_UNKNOWN = 5, // unknown state of print job
};
enum PrintJobSubState {
PRINT_JOB_COMPLETED_SUCCESS = 0, // print job succeed
PRINT_JOB_COMPLETED_FAILED = 1, // print job fail
PRINT_JOB_COMPLETED_CANCELLED = 2, // print job has been cancelled
PRINT_JOB_COMPLETED_FILE_CORRUPT = 3, // print job has been corrupted
PRINT_JOB_BLOCKED_OFFLINE = 4, // printer is offline
PRINT_JOB_BLOCKED_BUSY = 5, // printer is occupied by other process
PRINT_JOB_BLOCKED_CANCELLED = 6, // print job has been canncelled
PRINT_JOB_BLOCKED_OUT_OF_PAPER = 7, // out of paper
PRINT_JOB_BLOCKED_OUT_OF_INK = 8, // out of ink
PRINT_JOB_BLOCKED_OUT_OF_TONER = 9, // out of toner
PRINT_JOB_BLOCKED_JAMMED = 10, // paper jam
PRINT_JOB_BLOCKED_DOOR_OPEN = 11, // cover open
PRINT_JOB_BLOCKED_SERVICE_REQUEST = 12, // service request
PRINT_JOB_BLOCKED_LOW_ON_INK = 13, // low on ink
PRINT_JOB_BLOCKED_LOW_ON_TONER = 14, // low on toner
PRINT_JOB_BLOCKED_REALLY_LOW_ON_INK = 15, // really low on ink
PRINT_JOB_BLOCKED_BAD_CERTIFICATE = 16, // bad certification
PRINT_JOB_BLOCKED_UNKNOWN = 17, // unknown issue
};
} // namespace OHOS::Print
#endif // PRINT_CONSTANT_H

View File

@ -0,0 +1,78 @@
/*
* 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.
*/
#ifndef PRINT_LOG
#define PRINT_LOG
#define CONFIG_PRINT_LOG
#ifdef CONFIG_PRINT_LOG
#include "hilog/log.h"
#ifdef PRINT_HILOGF
#undef PRINT_HILOGF
#endif
#ifdef PRINT_HILOGE
#undef PRINT_HILOGE
#endif
#ifdef PRINT_HILOGW
#undef PRINT_HILOGW
#endif
#ifdef PRINT_HILOGD
#undef PRINT_HILOGD
#endif
#ifdef PRINT_HILOGI
#undef PRINT_HILOGI
#endif
#define PRINT_LOG_TAG "printkit"
#define PRINT_LOG_DOMAIN 0xD001C00
static constexpr OHOS::HiviewDFX::HiLogLabel PRINT_LOG_LABEL = {LOG_CORE, PRINT_LOG_DOMAIN, PRINT_LOG_TAG};
#define MAKE_FILE_NAME (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)
#define PRINT_HILOGF(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Fatal(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \
MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define PRINT_HILOGE(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Error(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \
MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define PRINT_HILOGW(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Warn(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \
MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define PRINT_HILOGD(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Debug(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \
MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define PRINT_HILOGI(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Info(PRINT_LOG_LABEL, "[%{public}s %{public}s %{public}d] " fmt, \
MAKE_FILE_NAME, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define PRINT_HILOGF(fmt, ...)
#define PRINT_HILOGE(fmt, ...)
#define PRINT_HILOGW(fmt, ...)
#define PRINT_HILOGD(fmt, ...)
#define PRINT_HILOGI(fmt, ...)
#endif // CONFIG_PRINT_LOG
#endif /* PRINT_LOG */