Update appexecfwk code.

Signed-off-by: dy_study <dingyao5@huawei.com>
This commit is contained in:
dy_study 2021-12-31 17:05:50 +08:00
parent 04291e1748
commit 687e8fd71a
246 changed files with 5178 additions and 622 deletions

View File

@ -61,7 +61,7 @@ Note:If the text contains special characters, please escape them according to th
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
<filteritem type="filename" name="*.hap|*.rpk|*.ha" desc="valid and invalid bundle files for tests"/>
<filteritem type="filename" name="*.ha|*.hap|*.rpk" desc="valid and invalid bundle files for tests"/>
<filteritem type="filepath" name="figures/.*" desc="Self-developed image"/>
</filefilter>
</filefilterlist>

View File

@ -746,4 +746,4 @@ HWTEST_F(CommonPerfProfileTest, PerfProfileEnable_001, TestSize.Level0)
PerfProfile::GetInstance().Reset();
profileFlag = PerfProfile::GetInstance().GetPerfProfileEnabled();
ASSERT_TRUE(profileFlag);
}
}

View File

@ -94,7 +94,7 @@ namespace Constants {
const std::string PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY = "form_manager_service_bundlename";
// PROVIDER_FLAG false:ProviderFormInfo is null;true: ProviderFormInfo not null
const std::string PROVIDER_FLAG = "provider_flag";
const std::string PROVIDER_FLAG = "provider_flag";
const std::string FORM_CONNECT_ID = "form_connect_id";
const std::string FORM_SUPPLY_INFO = "form_supply_info";

View File

@ -41,7 +41,7 @@ struct FormJsInfo : public Parcelable {
std::string cssPath;
std::string jsPath;
std::string fileReousePath;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static FormJsInfo *Unmarshalling(Parcel &parcel);

View File

@ -30,10 +30,10 @@ bool FormJsInfo::ReadFromParcel(Parcel &parcel)
formData = Str16ToStr8(parcel.ReadString16());
auto bindingData = parcel.ReadParcelable<FormProviderData>();
formProviderData = *bindingData;
if (nullptr == bindingData) {
if (nullptr == bindingData){
return false;
}
formProviderData = *bindingData;
return true;
}

View File

@ -266,7 +266,7 @@ bool FormProviderData::Marshalling(Parcel &parcel) const
* @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object.
* @param parcel Indicates the {@code Parcel} object for unmarshalling.
* @return FormProviderData.
*/
*/
FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel)
{
std::unique_ptr<FormProviderData> formProviderData = std::make_unique<FormProviderData>();
@ -278,7 +278,7 @@ FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel)
/**
* @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_.
*/
*/
void FormProviderData::ClearData()
{
jsonFormProviderData_.clear();

View File

@ -39,7 +39,6 @@ bool FormProviderInfo::Marshalling(Parcel &parcel) const
if (!parcel.WriteParcelable(&jsBindingData_)) {
return false;
}
return true;
}
void FormProviderInfo::SetFormDataString(std::string &dataString)
@ -49,7 +48,7 @@ void FormProviderInfo::SetFormDataString(std::string &dataString)
/**
* @brief Merge new data to FormProviderData.
* @param addJsonData data to merge to FormProviderData
*/
*/
void FormProviderInfo::MergeData(nlohmann::json &addJsonData)
{
jsBindingData_.MergeData(addJsonData);

View File

@ -119,6 +119,7 @@ ohos_shared_library("appexecfwk_core") {
"hiviewdfx_hilog_native:libhilog",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"bytrace_standard:bytrace_core",
]
subsystem_name = "appexecfwk"

View File

@ -20,6 +20,7 @@ namespace OHOS {
namespace AppExecFwk {
namespace Constants {
const std::string APP_MGR_SERVICE_NAME = "AppMgrService";
const std::string USER_ID = "UserId";
} // namespace Constants
enum class ApplicationState {

View File

@ -394,7 +394,7 @@ public:
* @param userId Indicates the user id.
* @return Returns true if the data cleared successfully; returns false otherwise.
*/
virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) = 0;
virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) = 0;
/**
* @brief Register the specific bundle status callback.
* @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result.

View File

@ -360,7 +360,7 @@ public:
* @param userId Indicates the user id.
* @return Returns true if the data cleared successfully; returns false otherwise.
*/
virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override;
virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override;
/**
* @brief Register the specific bundle status callback through the proxy object.
* @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result.

View File

@ -14,12 +14,12 @@
*/
#include "ams_mgr_proxy.h"
#include "string_ex.h"
#include "ipc_types.h"
#include "iremote_object.h"
#include "string_ex.h"
#include "appexecfwk_errors.h"
#include "app_log_wrapper.h"
#include "appexecfwk_errors.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -20,10 +20,11 @@
#include "iremote_object.h"
#include "ability_info.h"
#include "appexecfwk_errors.h"
#include "app_log_wrapper.h"
#include "app_mgr_proxy.h"
#include "app_scheduler_interface.h"
#include "appexecfwk_errors.h"
#include "bytrace.h"
#include "iapp_state_callback.h"
namespace OHOS {
@ -80,6 +81,7 @@ int AmsMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParce
ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
sptr<IRemoteObject> preToke = data.ReadParcelable<IRemoteObject>();
std::shared_ptr<AbilityInfo> abilityInfo(data.ReadParcelable<AbilityInfo>());
@ -100,6 +102,7 @@ ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply)
ErrCode AmsMgrStub::HandleTerminateAbility(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
TerminateAbility(token);
return NO_ERROR;
@ -107,6 +110,7 @@ ErrCode AmsMgrStub::HandleTerminateAbility(MessageParcel &data, MessageParcel &r
ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
int32_t state = data.ReadInt32();
UpdateAbilityState(token, static_cast<AbilityState>(state));
@ -115,6 +119,7 @@ ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel
ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> obj = data.ReadParcelable<IRemoteObject>();
sptr<IAppStateCallback> callback = iface_cast<IAppStateCallback>(obj);
RegisterAppStateCallback(callback);
@ -123,12 +128,14 @@ ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageP
ErrCode AmsMgrStub::HandleReset(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
Reset();
return NO_ERROR;
}
ErrCode AmsMgrStub::HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
sptr<IRemoteObject> preToke = data.ReadParcelable<IRemoteObject>();
int32_t visibility = data.ReadInt32();
@ -141,6 +148,7 @@ ErrCode AmsMgrStub::HandleAbilityBehaviorAnalysis(MessageParcel &data, MessagePa
ErrCode AmsMgrStub::HandleKillProcessByAbilityToken(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
KillProcessByAbilityToken(token);
@ -149,6 +157,7 @@ ErrCode AmsMgrStub::HandleKillProcessByAbilityToken(MessageParcel &data, Message
ErrCode AmsMgrStub::HandleKillApplication(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::string bundleName = data.ReadString();
int32_t result = KillApplication(bundleName);
reply.WriteInt32(result);
@ -157,6 +166,7 @@ ErrCode AmsMgrStub::HandleKillApplication(MessageParcel &data, MessageParcel &re
ErrCode AmsMgrStub::HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::string bundleName = data.ReadString();
int uid = data.ReadInt32();
int32_t result = KillApplicationByUid(bundleName, uid);
@ -166,6 +176,7 @@ ErrCode AmsMgrStub::HandleKillApplicationByUid(MessageParcel &data, MessageParce
int32_t AmsMgrStub::HandleAbilityAttachTimeOut(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
AbilityAttachTimeOut(token);
return NO_ERROR;
@ -173,6 +184,7 @@ int32_t AmsMgrStub::HandleAbilityAttachTimeOut(MessageParcel &data, MessageParce
int32_t AmsMgrStub::HandleCompelVerifyPermission(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
auto permission = Str16ToStr8(data.ReadString16());
auto pid = data.ReadInt32();
auto uid = data.ReadInt32();

View File

@ -22,9 +22,9 @@
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "app_log_wrapper.h"
#include "app_mgr_interface.h"
#include "app_service_manager.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -20,10 +20,11 @@
#include "iremote_object.h"
#include "ability_info.h"
#include "appexecfwk_errors.h"
#include "app_log_wrapper.h"
#include "app_mgr_proxy.h"
#include "app_scheduler_interface.h"
#include "appexecfwk_errors.h"
#include "bytrace.h"
#include "iapp_state_callback.h"
namespace OHOS {
@ -88,6 +89,7 @@ int AppMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParce
int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> client = data.ReadParcelable<IRemoteObject>();
AttachApplication(client);
return NO_ERROR;
@ -95,24 +97,28 @@ int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &
int32_t AppMgrStub::HandleApplicationForegrounded(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ApplicationForegrounded(data.ReadInt32());
return NO_ERROR;
}
int32_t AppMgrStub::HandleApplicationBackgrounded(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ApplicationBackgrounded(data.ReadInt32());
return NO_ERROR;
}
int32_t AppMgrStub::HandleApplicationTerminated(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ApplicationTerminated(data.ReadInt32());
return NO_ERROR;
}
int32_t AppMgrStub::HandleCheckPermission(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
int32_t recordId = data.ReadInt32();
std::string permission = data.ReadString();
int32_t result = CheckPermission(recordId, permission);
@ -122,6 +128,7 @@ int32_t AppMgrStub::HandleCheckPermission(MessageParcel &data, MessageParcel &re
int32_t AppMgrStub::HandleAbilityCleaned(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
AbilityCleaned(token);
return NO_ERROR;
@ -129,6 +136,7 @@ int32_t AppMgrStub::HandleAbilityCleaned(MessageParcel &data, MessageParcel &rep
int32_t AppMgrStub::HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
int32_t result = NO_ERROR;
sptr<IAmsMgr> amsMgr = GetAmsMgr();
if (!amsMgr) {
@ -146,6 +154,7 @@ int32_t AppMgrStub::HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply)
int32_t AppMgrStub::HandleClearUpApplicationData(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::string bundleName = data.ReadString();
int32_t result = ClearUpApplicationData(bundleName);
reply.WriteInt32(result);
@ -154,6 +163,7 @@ int32_t AppMgrStub::HandleClearUpApplicationData(MessageParcel &data, MessagePar
int32_t AppMgrStub::HandleIsBackgroundRunningRestricted(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::string bundleName = data.ReadString();
int32_t result = IsBackgroundRunningRestricted(bundleName);
reply.WriteInt32(result);
@ -162,6 +172,7 @@ int32_t AppMgrStub::HandleIsBackgroundRunningRestricted(MessageParcel &data, Mes
int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::vector<RunningProcessInfo> info;
auto result = GetAllRunningProcesses(info);
reply.WriteInt32(info.size());
@ -178,12 +189,14 @@ int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessagePar
int32_t AppMgrStub::HandleSetAppFreezingTime(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
SetAppFreezingTime(data.ReadInt32());
return NO_ERROR;
}
int32_t AppMgrStub::HandleGetAppFreezingTime(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
int time = 0;
GetAppFreezingTime(time);
reply.WriteInt32(time);
@ -192,6 +205,7 @@ int32_t AppMgrStub::HandleGetAppFreezingTime(MessageParcel &data, MessageParcel
int32_t AppMgrStub::HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
SystemMemoryAttr memoryInfo;
std::string strConfig;
data.ReadString(strConfig);
@ -205,6 +219,7 @@ int32_t AppMgrStub::HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel
int32_t AppMgrStub::HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
int32_t recordId = data.ReadInt32();
AddAbilityStageDone(recordId);
return NO_ERROR;
@ -212,6 +227,7 @@ int32_t AppMgrStub::HandleAddAbilityStageDone(MessageParcel &data, MessageParcel
int32_t AppMgrStub::HandleStartupResidentProcess(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
StartupResidentProcess();
return NO_ERROR;
}

View File

@ -14,10 +14,11 @@
*/
#include "app_scheduler_host.h"
#include "ipc_types.h"
#include "ability_info.h"
#include "appexecfwk_errors.h"
#include "app_log_wrapper.h"
#include "appexecfwk_errors.h"
#include "bytrace.h"
#include "ipc_types.h"
namespace OHOS {
namespace AppExecFwk {
@ -76,36 +77,42 @@ int AppSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag
int32_t AppSchedulerHost::HandleScheduleForegroundApplication(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ScheduleForegroundApplication();
return NO_ERROR;
}
int32_t AppSchedulerHost::HandleScheduleBackgroundApplication(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ScheduleBackgroundApplication();
return NO_ERROR;
}
int32_t AppSchedulerHost::HandleScheduleTerminateApplication(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ScheduleTerminateApplication();
return NO_ERROR;
}
int32_t AppSchedulerHost::HandleScheduleLowMemory(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ScheduleLowMemory();
return NO_ERROR;
}
int32_t AppSchedulerHost::HandleScheduleShrinkMemory(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ScheduleShrinkMemory(data.ReadInt32());
return NO_ERROR;
}
int32_t AppSchedulerHost::HandleScheduleLaunchAbility(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::unique_ptr<AbilityInfo> abilityInfo(data.ReadParcelable<AbilityInfo>());
if (!abilityInfo) {
APP_LOGE("ReadParcelable<AbilityInfo> failed");
@ -119,6 +126,7 @@ int32_t AppSchedulerHost::HandleScheduleLaunchAbility(MessageParcel &data, Messa
int32_t AppSchedulerHost::HandleScheduleCleanAbility(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> token = data.ReadParcelable<IRemoteObject>();
ScheduleCleanAbility(token);
return NO_ERROR;
@ -126,6 +134,7 @@ int32_t AppSchedulerHost::HandleScheduleCleanAbility(MessageParcel &data, Messag
int32_t AppSchedulerHost::HandleScheduleLaunchApplication(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::unique_ptr<AppLaunchData> launchData(data.ReadParcelable<AppLaunchData>());
if (!launchData) {
@ -139,6 +148,7 @@ int32_t AppSchedulerHost::HandleScheduleLaunchApplication(MessageParcel &data, M
int32_t AppSchedulerHost::HandleScheduleAbilityStageInfo(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::unique_ptr<AppResidentProcessInfo> appResidentProcessInfo(data.ReadParcelable<AppResidentProcessInfo>());
if (!appResidentProcessInfo) {
APP_LOGE("ReadParcelable<launchData> failed");
@ -151,6 +161,7 @@ int32_t AppSchedulerHost::HandleScheduleAbilityStageInfo(MessageParcel &data, Me
int32_t AppSchedulerHost::HandleScheduleProfileChanged(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::unique_ptr<Profile> profile(data.ReadParcelable<Profile>());
if (!profile) {
APP_LOGE("ReadParcelable<Profile> failed");
@ -163,6 +174,7 @@ int32_t AppSchedulerHost::HandleScheduleProfileChanged(MessageParcel &data, Mess
int32_t AppSchedulerHost::HandleScheduleConfigurationUpdated(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::unique_ptr<Configuration> configuration(data.ReadParcelable<Configuration>());
if (!configuration) {
APP_LOGE("ReadParcelable<Configuration> failed");
@ -175,6 +187,7 @@ int32_t AppSchedulerHost::HandleScheduleConfigurationUpdated(MessageParcel &data
int32_t AppSchedulerHost::HandleScheduleProcessSecurityExit(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
ScheduleProcessSecurityExit();
return NO_ERROR;
}

View File

@ -15,10 +15,9 @@
#include "app_scheduler_proxy.h"
#include "iremote_object.h"
#include "ipc_types.h"
#include "app_log_wrapper.h"
#include "ipc_types.h"
#include "iremote_object.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -15,12 +15,12 @@
#include "app_service_manager.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "system_ability_definition.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "app_mgr_constants.h"
#include "iservice_registry.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -15,9 +15,9 @@
#include "app_state_callback_host.h"
#include "appexecfwk_errors.h"
#include "app_log_wrapper.h"
#include "appexecfwk_errors.h"
#include "bytrace.h"
#include "ipc_types.h"
#include "iremote_object.h"
@ -71,6 +71,7 @@ void AppStateCallbackHost::OnAppStateChanged(const AppProcessData &)
int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
std::unique_ptr<AppProcessData> processData(data.ReadParcelable<AppProcessData>());
if (!processData) {
APP_LOGE("ReadParcelable<AppProcessData> failed");
@ -83,6 +84,7 @@ int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, Messa
int32_t AppStateCallbackHost::HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply)
{
BYTRACE(BYTRACE_TAG_APP);
sptr<IRemoteObject> obj = data.ReadParcelable<IRemoteObject>();
int32_t state = data.ReadInt32();
OnAbilityRequestDone(obj, static_cast<AbilityState>(state));

View File

@ -13,10 +13,12 @@
* limitations under the License.
*/
#include <nlohmann/json.hpp>
#include "string_ex.h"
#include "app_log_wrapper.h"
#include "configuration.h"
#include <nlohmann/json.hpp>
#include "app_log_wrapper.h"
#include "string_ex.h"
namespace ConfigurationInner {
const std::string CONNECTION_SYMBOL {"#"};
const std::string EMPTY_STRING {""};
@ -138,7 +140,7 @@ std::string Configuration::GetValue(const std::string &key) const
void Configuration::CompareDifferent(std::vector<std::string> &diffKeyV, const Configuration &other)
{
if (other.GetItemSize() == 0) {
return ;
return;
}
diffKeyV.clear();

View File

@ -14,8 +14,9 @@
*/
#include "process_info.h"
#include "string_ex.h"
#include "app_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -379,10 +379,10 @@ int FormMgrProxy::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &
MessageOption option;
int error = Remote()->SendRequest(
static_cast<uint32_t>(
IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM),
data,
reply,
option);
IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM),
data,
reply,
option);
if (error != ERR_OK) {
APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error);
return ERR_APPEXECFWK_FORM_SEND_FMS_MSG;
@ -455,7 +455,7 @@ int FormMgrProxy::DumpFormInfoByFormId(const std::int64_t formId, std::string &f
int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo);
if (error != ERR_OK) {
APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error);
APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error);
}
return error;
@ -480,7 +480,7 @@ int FormMgrProxy::DumpFormTimerByFormId(const std::int64_t formId, std::string &
int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_TIMER_INFO_BY_ID, data, isTimingService);
if (error != ERR_OK) {
APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error);
APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error);
}
return error;
@ -512,13 +512,13 @@ int FormMgrProxy::MessageEvent(const int64_t formId, const Want &want, const spt
APP_LOGE("%{public}s, failed to write callerToken", __func__);
return ERR_APPEXECFWK_PARCEL_ERROR;
}
MessageParcel reply;
MessageOption option;
int error = Remote()->SendRequest(
static_cast<uint32_t>(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT),
data,
reply,
static_cast<uint32_t>(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT),
data,
reply,
option);
if (error != ERR_OK) {
APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error);
@ -636,7 +636,7 @@ int FormMgrProxy::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, M
int32_t result = remote->SendRequest(static_cast<uint32_t>(code), data, reply, option);
if (result != ERR_OK) {
APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code);
return ERR_APPEXECFWK_FORM_SEND_FMS_MSG;
return ERR_APPEXECFWK_FORM_SEND_FMS_MSG;
}
return ERR_OK;
}

View File

@ -409,7 +409,7 @@ int32_t FormMgrStub::HandleMessageEvent(MessageParcel &data, MessageParcel &repl
APP_LOGE("%{public}s, failed to ReadParcelable<IRemoteObject>", __func__);
return ERR_APPEXECFWK_PARCEL_ERROR;
}
int32_t result = MessageEvent(formId, *want, client);
reply.WriteInt32(result);
return result;

View File

@ -47,7 +47,7 @@ void ProviderConnectProxy::OnAbilityConnectDone(
return;
}
if (!data.WriteParcelable(remoteObject)) {
if (!data.WriteRemoteObject(remoteObject)) {
APP_LOGE("%{public}s, failed to write remote object ", __func__);
return;
}

View File

@ -46,7 +46,7 @@ int ProviderConnectStub::OnRemoteRequest(
APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__);
return ERR_APPEXECFWK_PARCEL_ERROR;
}
auto remoteObject = data.ReadParcelable<IRemoteObject>();
auto remoteObject = data.ReadRemoteObject();
auto resultCode = data.ReadInt32();
OnAbilityConnectDone(*element, remoteObject, resultCode);
delete element;

View File

@ -14,8 +14,9 @@
*/
#include "native_interface_eventhandler.h"
#include "native_implement_eventhandler.h"
#include "hilog/log.h"
#include "native_implement_eventhandler.h"
#include <cstdint>
using OHOS::ErrCode;

View File

@ -42,7 +42,6 @@ class FormMgr final : public DelayedRefSingleton<FormMgr> {
DECLARE_DELAYED_REF_SINGLETON(FormMgr)
public:
DISALLOW_COPY_AND_MOVE(FormMgr);
/**
* @brief Add form with want, send want to form manager service.
* @param formId The Id of the forms to add.
@ -61,7 +60,7 @@ public:
* @return Returns ERR_OK on success, others on failure.
*/
int DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken);
/**
* @brief Release forms with formIds, send formIds to form manager service.
* @param formId The Id of the forms to release.
@ -162,7 +161,7 @@ public:
/**
* @brief UnRegister death callback.
*
*
* @param formDeathCallback The death callback.
*/
void UnRegisterDeathCallback(const std::shared_ptr<FormCallbackInterface> &formDeathCallback);
@ -183,8 +182,8 @@ public:
* @param updateType Next refresh time.
* @return Returns ERR_OK on success, others on failure.
*/
int LifecycleUpdate(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken,
const int32_t updateType);
int LifecycleUpdate(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken,
const int32_t updateType);
/**
* @brief Set fms recoverStatus.
@ -213,7 +212,7 @@ public:
/**
* @brief Get the error message content.
*
*
* @param errCode Error code.
* @return Message content.
*/

View File

@ -13,11 +13,13 @@
* limitations under the License.
*/
#include <thread>
#include "appexecfwk_errors.h"
#include "app_log_wrapper.h"
#include "form_errors.h"
#include "form_mgr.h"
#include <thread>
#include "app_log_wrapper.h"
#include "appexecfwk_errors.h"
#include "form_errors.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
@ -218,7 +220,7 @@ int FormMgr::DumpFormInfoByFormId(const std::int64_t formId, std::string &formIn
if (errCode != ERR_OK) {
return errCode;
}
return remoteProxy_->DumpFormInfoByFormId(formId, formInfo);
}
/**
@ -233,7 +235,7 @@ int FormMgr::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTim
if (errCode != ERR_OK) {
return errCode;
}
return remoteProxy_->DumpFormTimerByFormId(formId, isTimingService);
}
/**
@ -249,7 +251,7 @@ int FormMgr::MessageEvent(const int64_t formId, const Want &want, const sptr<IRe
if (errCode != ERR_OK) {
return errCode;
}
return remoteProxy_->MessageEvent(formId, want, callerToken);
}
@ -265,7 +267,7 @@ int FormMgr::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
if (errCode != ERR_OK) {
return errCode;
}
return remoteProxy_->SetNextRefreshTime(formId, nextTime);
}
@ -526,7 +528,7 @@ void FormMgr::SetFormMgrService(sptr<IFormMgr> formMgrService)
int FormMgr::DistributedDataAddForm(const Want &want)
{
APP_LOGI("%{public}s called.", __func__);
int errCode = Connect();
if (errCode != ERR_OK) {
return errCode;
@ -543,7 +545,7 @@ int FormMgr::DistributedDataAddForm(const Want &want)
int FormMgr::DistributedDataDeleteForm(const std::string &formId)
{
APP_LOGI("%{public}s called.", __func__);
int errCode = Connect();
if (errCode != ERR_OK) {
return errCode;

View File

@ -32,7 +32,10 @@ ohos_shared_library("libeventhandler") {
public_configs = [ ":public_libeventhandler_config" ]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"hitrace_native:libhitrace",
]
subsystem_name = "appexecfwk"
part_name = "eventhandler"
}

View File

@ -26,7 +26,13 @@
#include "nocopyable.h"
namespace OHOS {
namespace HiviewDFX {
class HiTraceId;
}
namespace AppExecFwk {
using HiTraceId = OHOS::HiviewDFX::HiTraceId;
class EventHandler;
const std::string LINE_SEPARATOR = "\n";
@ -425,6 +431,21 @@ private:
smartPtrTypeId_ = CalculateSmartPtrTypeId(object);
}
/**
* if event has trace id ,return trace id, else create span id,
* store it in event and return.
*
* @return return hiTrace Id.
*/
const std::shared_ptr<HiTraceId> GetOrCreateTraceId();
/**
* return trace id.
*
* @return return hiTrace Id.
*/
const std::shared_ptr<HiTraceId> GetTraceId();
/*
* Calculate the type id for different smart pointers.
*/
@ -499,6 +520,9 @@ private:
// Used for synchronized event.
std::shared_ptr<Waiter> waiter_;
// use to store hitrace Id
std::shared_ptr<HiTraceId> hiTraceId_;
};
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -0,0 +1,20 @@
# 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.
import("//build/ohos.gni")
group("napi_packages") {
deps = [
"${innerkits_path}/napi/eventhandler:emitter",
]
}

View File

@ -0,0 +1,50 @@
# 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.
import("//build/ohos.gni")
import("//build/ohos/ace/ace.gni")
import("//foundation/appexecfwk/standard/appexecfwk.gni")
config("native_module_config") {
include_dirs = [ "include" ]
}
ohos_shared_library("emitter") {
include_dirs = [
"${innerkits_path}/libeventhandler/include",
"//third_party/node/src",
"//third_party/libuv/include",
]
configs = [ ":native_module_config" ]
sources = [
"src/events_emitter.cpp",
"src/init.cpp",
]
deps = [
"${innerkits_path}/libeventhandler:libeventhandler",
"//third_party/libuv:uv_static",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
]
relative_install_dir = "module"
subsystem_name = "appexecfwk"
part_name = "appexecfwk_standard"
}

View File

@ -0,0 +1,89 @@
/*
* 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_NAPI_EVENTHANDLER_JS_EMITTER_H
#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_NAPI_EVENTHANDLER_JS_EMITTER_H
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "event_handler.h"
#include "event_runner.h"
#include "event_queue.h"
#include "inner_event.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace AppExecFwk {
using Priority = EventQueue::Priority;
static const int32_t ARGC_NUM = 2;
static const int32_t NAPI_VALUE_STRING_LEN = 10240;
class EventHandlerInstance : public EventHandler {
public:
EventHandlerInstance(const std::shared_ptr<EventRunner>& runner);
static std::shared_ptr<EventHandlerInstance> GetInstance();
~EventHandlerInstance();
void ProcessEvent(const InnerEvent::Pointer& event) override;
};
enum class DataType: uint32_t {
BOOL = 0,
INT,
STRING,
};
struct Val {
DataType type;
union {
bool bValue;
int32_t nValue;
char cValue[NAPI_VALUE_STRING_LEN] = {0};
} value;
};
struct EventData {
std::map<std::string, Val> data;
};
struct AsyncCallbackInfo {
napi_env env;
bool once = false;
bool isDeleted = false;
napi_ref callback = 0;
};
struct CallbackInfos {
std::vector<AsyncCallbackInfo *> asyncCallbackInfo;
};
struct EventDataWorker {
EventData data;
AsyncCallbackInfo* callbackInfo;
};
napi_value EmitterInit(napi_env env, napi_value exports);
napi_value JS_On(napi_env env, napi_callback_info cbinfo);
napi_value JS_Off(napi_env env, napi_callback_info cbinfo);
napi_value JS_Once(napi_env env, napi_callback_info cbinfo);
napi_value JS_Emit(napi_env env, napi_callback_info cbinfo);
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_NAPI_EVENTHANDLER_JS_EMITTER_H

View File

@ -0,0 +1,474 @@
/*
* 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 "hilog/log.h"
#include "events_emitter.h"
#include <uv.h>
#define DEFINE_HILOG_LABEL(name) \
static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_DOMAIN, name }
#define HILOGE(...) OHOS::HiviewDFX::HiLog::Error(LOG_LABEL, ##__VA_ARGS__)
#define HILOGW(...) OHOS::HiviewDFX::HiLog::Warn(LOG_LABEL, ##__VA_ARGS__)
#define HILOGI(...) OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, ##__VA_ARGS__)
#define HILOGD(...) OHOS::HiviewDFX::HiLog::Debug(LOG_LABEL, ##__VA_ARGS__)
DEFINE_HILOG_LABEL("events_emitter");
using namespace std;
namespace OHOS {
namespace AppExecFwk {
static map<uint32_t, CallbackInfos> emitterInstances;
std::shared_ptr<EventHandlerInstance> eventHandler;
EventHandlerInstance::EventHandlerInstance(const std::shared_ptr<EventRunner>& runner): EventHandler(runner)
{
HILOGI("EventHandlerInstance::EventHandlerInstance constructed");
}
EventHandlerInstance::~EventHandlerInstance()
{
HILOGI("EventHandlerInstance::EventHandlerInstance de-constructed");
}
std::shared_ptr<EventHandlerInstance> EventHandlerInstance::GetInstance()
{
static auto runner = EventRunner::Create("events_emitter");
if (runner.get() == nullptr) {
HILOGE("failed to create EventRunner events_emitter");
return nullptr;
}
static auto instance = std::make_shared<EventHandlerInstance>(runner);
return instance;
}
void TransToEventData(napi_env env, EventData eventData, napi_value resultData)
{
napi_value data = nullptr;
napi_create_object(env, &data);
for (map<string, Val>::iterator it = eventData.data.begin(); it != eventData.data.end(); it++) {
string key = it->first;
Val val = it->second;
napi_value napiValue = nullptr;
switch (val.type) {
case DataType::BOOL:
HILOGD("ProcessEvent key:%{public}s value:%{public}d", key.c_str(), val.value.bValue);
napi_get_boolean(env, val.value.bValue, &napiValue);
break;
case DataType::INT:
HILOGD("ProcessEvent key:%{public}s value:%{public}d", key.c_str(), val.value.nValue);
napi_create_int32(env, val.value.nValue, &napiValue);
break;
case DataType::STRING:
HILOGD("ProcessEvent key:%{public}s value:%{public}s", key.c_str(), val.value.cValue);
napi_create_string_utf8(env, val.value.cValue, NAPI_AUTO_LENGTH, &napiValue);
break;
default:
HILOGE("ProcessEvent unsupport type data");
break;
}
napi_set_named_property(env, data, key.c_str(), napiValue);
}
napi_set_named_property(env, resultData, "data", data);
}
void ProcessCallback(const EventDataWorker* eventDataInner)
{
if (eventDataInner == nullptr) {
HILOGW("EventDataWorkder instance(uv_work_t) is nullptr");
return;
}
AsyncCallbackInfo* callbackInner = eventDataInner->callbackInfo;
if (callbackInner->isDeleted) {
HILOGI("ProcessEvent isDeleted callbackInfo = %{public}p", callbackInner);
napi_delete_reference(callbackInner->env, callbackInner->callback);
} else {
napi_value resultData = nullptr;
napi_create_object(callbackInner->env, &resultData);
TransToEventData(callbackInner->env, eventDataInner->data, resultData);
napi_value callback = nullptr;
napi_value returnVal = nullptr;
napi_get_reference_value(callbackInner->env, callbackInner->callback, &callback);
napi_call_function(callbackInner->env, nullptr, callback, 1, &resultData, &returnVal);
if (callbackInner->once) {
HILOGI("ProcessEvent delete once callback callbackInfo = %{public}p", callbackInner);
napi_delete_reference(callbackInner->env, callbackInner->callback);
}
}
}
void EventHandlerInstance::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer& event)
{
uint32_t eventId = event->GetInnerEventId();
HILOGI("ProcessEvent, eventId = %d", eventId);
auto subscribe = emitterInstances.find(eventId);
if (subscribe == emitterInstances.end()) {
HILOGW("ProcessEvent has no callback");
return;
}
CallbackInfos callbackInfos = subscribe->second;
HILOGI("ProcessEvent, size = %zu", callbackInfos.asyncCallbackInfo.size());
EventData eventData = *(event->GetUniqueObject<EventData>());
for (auto iter = callbackInfos.asyncCallbackInfo.begin(); iter != callbackInfos.asyncCallbackInfo.end();) {
AsyncCallbackInfo* callbackInfo = *iter;
EventDataWorker* eventDataWorker = new EventDataWorker();
eventDataWorker->data = eventData;
eventDataWorker->callbackInfo = callbackInfo;
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(callbackInfo->env, &loop);
uv_work_t *work = new uv_work_t;
if (work == nullptr) {
HILOGI("uv_work_t instance is nullptr");
return;
}
work->data = (void *)eventDataWorker;
uv_queue_work(loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int status) {
EventDataWorker* eventDataInner = (EventDataWorker*)work->data;
ProcessCallback(eventDataInner);
delete eventDataInner;
eventDataInner = nullptr;
delete work;
work = nullptr;
});
if (callbackInfo->once || callbackInfo->isDeleted) {
HILOGI("ProcessEvent once callback or isDeleted callback");
iter = callbackInfos.asyncCallbackInfo.erase(iter);
if (callbackInfos.asyncCallbackInfo.begin() == callbackInfos.asyncCallbackInfo.end()) {
emitterInstances.erase(eventId);
HILOGI("ProcessEvent delete the last callback");
break;
}
} else {
++iter;
}
}
HILOGI("ProcessEvent end");
}
bool IsExistSameCallback(napi_env env, uint32_t eventIdValue, napi_value argv, bool once)
{
auto subscribe = emitterInstances.find(eventIdValue);
if (subscribe == emitterInstances.end()) {
return false;
}
vector<AsyncCallbackInfo *> callbackInfo = subscribe->second.asyncCallbackInfo;
size_t callbackSize = callbackInfo.size();
napi_value callback = nullptr;
for (size_t i = 0; i < callbackSize; i++) {
if (callbackInfo[i]->isDeleted) {
continue;
}
if (callbackInfo[i]->env != env) {
continue;
}
napi_get_reference_value(callbackInfo[i]->env, callbackInfo[i]->callback, &callback);
bool isEq = false;
napi_strict_equals(env, argv, callback, &isEq);
if (!isEq) {
continue;
}
if (!once) {
if (callbackInfo[i]->once) {
HILOGI("JS_On change once to on");
callbackInfo[i]->once = false;
} else {
HILOGI("JS_On already on");
}
} else {
if (callbackInfo[i]->once) {
HILOGI("JS_Once already once");
} else {
HILOGI("JS_Once change on to once");
callbackInfo[i]->once = true;
}
}
return true;
}
return false;
}
napi_value OnOrOnce(napi_env env, napi_callback_info cbinfo, bool once)
{
size_t argc = ARGC_NUM;
napi_value argv[ARGC_NUM] = {0};
NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, NULL, NULL));
NAPI_ASSERT(env, argc >= ARGC_NUM, "requires 2 parameter");
napi_valuetype eventValueType;
napi_typeof(env, argv[0], &eventValueType);
NAPI_ASSERT(env, eventValueType == napi_object, "type mismatch for parameter 1");
napi_valuetype eventHandleType;
napi_typeof(env, argv[1], &eventHandleType);
NAPI_ASSERT(env, eventHandleType == napi_function, "type mismatch for parameter 2");
bool hasEventId = false;
napi_value eventId;
napi_has_named_property(env, argv[0], "eventId", &hasEventId);
NAPI_ASSERT(env, hasEventId, "Wrong argument 1");
napi_get_named_property(env, argv[0], "eventId", &eventId);
uint32_t eventIdValue;
napi_get_value_uint32(env, eventId, &eventIdValue);
HILOGI("OnOrOnce eventIdValue:%{public}d", eventIdValue);
if (!IsExistSameCallback(env, eventIdValue, argv[1], once)) {
AsyncCallbackInfo* callbackInfo = new AsyncCallbackInfo();
callbackInfo->env = env;
callbackInfo->once = once;
napi_create_reference(env, argv[1], 1, &callbackInfo->callback);
emitterInstances[eventIdValue].asyncCallbackInfo.push_back(callbackInfo);
HILOGI("OnOrOnce callbackInfo = %{public}p", callbackInfo);
}
return nullptr;
}
napi_value JS_On(napi_env env, napi_callback_info cbinfo)
{
HILOGI("JS_On start");
OnOrOnce(env, cbinfo, false);
return nullptr;
}
napi_value JS_Off(napi_env env, napi_callback_info cbinfo)
{
HILOGI("JS_Off start");
size_t argc = 1;
napi_value argv[1] = {0};
NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, NULL, NULL));
NAPI_ASSERT(env, argc >= 1, "requires 1 parameter");
napi_valuetype eventValueType;
napi_typeof(env, argv[0], &eventValueType);
NAPI_ASSERT(env, eventValueType == napi_number, "type mismatch for parameter 1");
uint32_t eventId;
napi_get_value_uint32(env, argv[0], &eventId);
auto subscribe = emitterInstances.find(eventId);
if (subscribe != emitterInstances.end()) {
for (auto callbackInfo : subscribe->second.asyncCallbackInfo) {
HILOGI("JS_Off callbackInfo = %{public}p", callbackInfo);
callbackInfo->isDeleted = true;
}
}
return nullptr;
}
napi_value JS_Once(napi_env env, napi_callback_info cbinfo)
{
HILOGI("JS_Once start");
OnOrOnce(env, cbinfo, true);
return nullptr;
}
bool ParseEventData(napi_env env, napi_value key, napi_value data, Val* &val, char keyChars[NAPI_VALUE_STRING_LEN])
{
napi_valuetype valueType;
napi_typeof(env, key, &valueType);
if (valueType != napi_valuetype::napi_string) {
HILOGI("param is discarded because the key type of the event params must be String.");
return false;
}
size_t keyLength = 0;
napi_get_value_string_utf8(env, key, keyChars, NAPI_VALUE_STRING_LEN, &keyLength);
napi_value value = nullptr;
napi_get_named_property(env, data, keyChars, &value);
napi_typeof(env, value, &valueType);
if (valueType == napi_valuetype::napi_boolean) {
val->type = DataType::BOOL;
napi_get_value_bool(env, value, &(val->value.bValue));
HILOGD("key:%{public}s value=%{public}d.", keyChars, val->value.bValue);
} else if (valueType == napi_valuetype::napi_number) {
val->type = DataType::INT;
napi_get_value_int32(env, value, &(val->value.nValue));
HILOGD("key:%{public}s value=%{public}d.", keyChars, val->value.nValue);
} else if (valueType == napi_valuetype::napi_string) {
napi_get_value_string_utf8(env, value, val->value.cValue, NAPI_VALUE_STRING_LEN, &keyLength);
val->type = DataType::STRING;
HILOGD("key:%{public}s value=%{public}s.", keyChars, val->value.cValue);
} else {
HILOGI("param=%{public}s is discarded because the value type is invalid.", keyChars);
return false;
}
return true;
}
bool EmitWithEventData(napi_env env, napi_value argv, uint32_t eventId, Priority priority)
{
napi_valuetype dataType;
napi_typeof(env, argv, &dataType);
NAPI_ASSERT(env, dataType == napi_object, "type mismatch for parameter 2");
bool hasData = false;
napi_has_named_property(env, argv, "data", &hasData);
if (hasData) {
napi_value data = nullptr;
napi_get_named_property(env, argv, "data", &data);
napi_value keyArr = nullptr;
napi_status status = napi_get_property_names(env, data, &keyArr);
uint32_t len = 0;
status = napi_get_array_length(env, keyArr, &len);
EventData eventData;
bool hasEventData = false;
for (uint32_t i = 0; i < len; i++) {
napi_value key = nullptr;
napi_get_element(env, keyArr, i, &key);
char keyChars[NAPI_VALUE_STRING_LEN] = {0};
Val* val = new Val();
if (!ParseEventData(env, key, data, val, keyChars)) {
delete val;
continue;
}
eventData.data.insert(make_pair(keyChars, *val));
hasEventData = true;
delete val;
}
if (hasEventData) {
HILOGI("sendevent with eventData id:%{public}d", eventId);
auto event = InnerEvent::Get(eventId, make_unique<EventData>(eventData));
eventHandler->SendEvent(event, 0, priority);
return true;
}
}
return false;
}
bool IsExistValidCallback(napi_env env, uint32_t eventId)
{
auto subscribe = emitterInstances.find(eventId);
if (subscribe == emitterInstances.end()) {
HILOGW("JS_Emit has no callback");
return false;
}
vector<AsyncCallbackInfo *> callbackInfo = subscribe->second.asyncCallbackInfo;
size_t callbackSize = callbackInfo.size();
for (size_t i = 0; i < callbackSize; i++) {
if (!callbackInfo[i]->isDeleted) {
return true;
}
}
return false;
}
napi_value JS_Emit(napi_env env, napi_callback_info cbinfo)
{
HILOGI("JS_Emit start");
size_t argc = ARGC_NUM;
napi_value argv[ARGC_NUM] = {0};
NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, NULL, NULL));
NAPI_ASSERT(env, argc >= 1, "requires more than 1 parameter");
HILOGI("JS_Emit argc:%{public}zu", argc);
napi_valuetype eventValueType;
napi_typeof(env, argv[0], &eventValueType);
NAPI_ASSERT(env, eventValueType == napi_object, "type mismatch for parameter 1");
bool hasEventId = false;
napi_value value;
napi_has_named_property(env, argv[0], "eventId", &hasEventId);
NAPI_ASSERT(env, hasEventId == true, "Wrong argument 1");
napi_get_named_property(env, argv[0], "eventId", &value);
uint32_t eventId;
napi_get_value_uint32(env, value, &eventId);
HILOGI("JS_Emit eventIdValue:%{public}d", eventId);
if (!IsExistValidCallback(env, eventId)) {
HILOGW("JS_Emit has no valid callback");
return nullptr;
}
bool hasPriority = false;
napi_has_named_property(env, argv[0], "priority", &hasPriority);
Priority priority = Priority::LOW;
if (hasPriority) {
napi_get_named_property(env, argv[0], "priority", &value);
uint32_t priorityValue;
napi_get_value_uint32(env, value, &priorityValue);
HILOGI("JS_Emit priority:%{public}d", priorityValue);
priority = static_cast<Priority>(priorityValue);
}
if (argc == ARGC_NUM && EmitWithEventData(env, argv[1], eventId, priority)) {
HILOGI("EmitWithEventData sucess");
return nullptr;
} else {
HILOGI("JS_Emit sendevent without id:%{public}d", eventId);
auto event = InnerEvent::Get(eventId, make_unique<EventData>());
eventHandler->SendEvent(event, 0, priority);
return nullptr;
}
}
napi_value EnumEventClassConstructor(napi_env env, napi_callback_info info)
{
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
return thisArg;
}
napi_value CreateEnumEventPriority(napi_env env, napi_value exports)
{
napi_value immediate = nullptr;
napi_value high = nullptr;
napi_value low = nullptr;
napi_value idle = nullptr;
napi_create_uint32(env, (uint32_t)Priority::IMMEDIATE, &immediate);
napi_create_uint32(env, (uint32_t)Priority::HIGH, &high);
napi_create_uint32(env, (uint32_t)Priority::LOW, &low);
napi_create_uint32(env, (uint32_t)Priority::IDLE, &idle);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("IMMEDIATE", immediate),
DECLARE_NAPI_STATIC_PROPERTY("HIGH", high),
DECLARE_NAPI_STATIC_PROPERTY("LOW", low),
DECLARE_NAPI_STATIC_PROPERTY("IDLE", idle),
};
napi_value result = nullptr;
napi_define_class(env, "EventPriority", NAPI_AUTO_LENGTH, EnumEventClassConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "EventPriority", result);
return exports;
}
napi_value EmitterInit(napi_env env, napi_value exports)
{
HILOGE("enter");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("on", JS_On),
DECLARE_NAPI_FUNCTION("once", JS_Once),
DECLARE_NAPI_FUNCTION("off", JS_Off),
DECLARE_NAPI_FUNCTION("emit", JS_Emit),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
CreateEnumEventPriority(env, exports);
eventHandler = EventHandlerInstance::GetInstance();
return exports;
}
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -0,0 +1,44 @@
/*
* 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 "events_emitter.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace AppExecFwk {
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
EmitterInit(env, exports);
return exports;
}
EXTERN_C_END
static napi_module _module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "emitter",
.nm_priv = ((void *)0),
.reserved = {0}
};
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&_module);
}
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -122,7 +122,8 @@ std::shared_ptr<Revocable> ParallelTaskDispatcherBase::DelayDispatch(
return nullptr;
}
TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG);
std::function<void()> callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask);
std::function<void()> callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(),
innerTask);
bool executeFlag = executor_->DelayExecute(callback, delayMs);
if (!executeFlag) {
APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch execute failed");

View File

@ -94,7 +94,7 @@ std::shared_ptr<Task> TaskExecutor::GetTask(const std::shared_ptr<WorkerThread>
std::shared_ptr<Task> nullRunnable = nullptr;
std::shared_ptr<Task> next = nullptr;
for(;;){
for (;;) {
if (terminated_.load() && pendingTasks_->Empty()) {
APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is terminated",
workerThread->GetThreadName().c_str());
@ -203,7 +203,7 @@ bool TaskExecutor::EnsureConsumeStarted()
void TaskExecutor::Consume()
{
for(;;){
for (;;) {
if (terminated_.load() && delayTasks_->Empty()) {
APP_LOGI("TaskExecutor::Consume delay task is empty");
break;

View File

@ -71,6 +71,7 @@ bool WorkerPool::CheckConfigParams(const std::shared_ptr<WorkerPoolConfig> &conf
int maxThreadCount = config->GetMaxThreadCount();
int coreThreadCount = config->GetCoreThreadCount();
if (!CheckThreadCount(maxThreadCount, coreThreadCount)) {
APP_LOGE("WorkerPool::CheckConfigParams parameters are illegal, maxThreadCount %{public}d is less than "
"coreThreadCount %{public}d",
@ -238,7 +239,7 @@ bool WorkerPool::AddWorker(const std::shared_ptr<Delegate> &delegate, const std:
std::unique_lock<std::mutex> mLock(poolLock_);
std::shared_ptr<WorkerThread> newThread = nullptr;
for(;;){
for (;;) {
unsigned int value = control_.load();
int num = GetWorkingThreadNum(value);
if (num >= thread_limit_) {
@ -326,7 +327,7 @@ int WorkerPool::GetStateFromControl(unsigned int ctl)
void WorkerPool::AdvanceStateTo(unsigned int target)
{
APP_LOGI("WorkerPool::AdvanceStateTo begin");
for(;;){
for (;;) {
unsigned int current = control_.load();
if ((current >= target) ||
CompareAndSet(control_, current, CombineToControl(target, GetWorkingThreadNum(current)))) {

View File

@ -16,14 +16,15 @@
#define private public
#undef private
#include "base_task_dispatcher.h"
#include "runnable.h"
#include "serial_task_dispatcher.h"
#include "task_dispatcher.h"
#include "task_dispatcher_context.h"
#include <gtest/gtest.h>
#include <string>
#include <thread>
#include <unistd.h>
#include "task_dispatcher_context.h"
#include "task_dispatcher.h"
#include "serial_task_dispatcher.h"
#include "runnable.h"
using namespace testing;
using namespace testing::ext;

View File

@ -19,10 +19,10 @@
#undef private
#include "app_log_wrapper.h"
#include "appexecfwk_errors.h"
#include "task_priority.h"
#include "task_executor.h"
#include "task.h"
#include "default_worker_pool_config.h"
#include "task.h"
#include "task_executor.h"
#include "task_priority.h"
using namespace testing;
using namespace testing::ext;

View File

@ -16,15 +16,17 @@
#define private public
#undef private
#include "spec_task_dispatcher.h"
#include "event_runner.h"
#include "runnable.h"
#include "serial_task_dispatcher.h"
#include "task_dispatcher.h"
#include "task_dispatcher_context.h"
#include <gtest/gtest.h>
#include <string>
#include <thread>
#include <unistd.h>
#include <string>
#include <gtest/gtest.h>
#include "task_dispatcher_context.h"
#include "task_dispatcher.h"
#include "serial_task_dispatcher.h"
#include "runnable.h"
#include "event_runner.h"
using namespace testing;
using namespace testing::ext;

View File

@ -17,11 +17,11 @@
#define private public
#include "sync_task.h"
#undef private
#include "app_log_wrapper.h"
#include "default_worker_pool_config.h"
#include "task.h"
#include "task_priority.h"
#include "task_executor.h"
#include "task.h"
#include "default_worker_pool_config.h"
#include "app_log_wrapper.h"
using namespace testing;
using namespace testing::ext;

View File

@ -17,10 +17,10 @@
#define private public
#include "task_dispatcher_context.h"
#undef private
#include "default_worker_pool_config.h"
#include "task.h"
#include "task_priority.h"
#include "task_executor.h"
#include "task.h"
#include "default_worker_pool_config.h"
using namespace testing;
using namespace testing::ext;

View File

@ -17,12 +17,12 @@
#define private public
#include "work_thread.h"
#undef private
#include "app_log_wrapper.h"
#include "default_thread_factory.h"
#include "default_worker_pool_config.h"
#include "task_priority.h"
#include "task_executor.h"
#include "task.h"
#include "default_worker_pool_config.h"
#include "default_thread_factory.h"
#include "app_log_wrapper.h"
using namespace testing;
using namespace testing::ext;

View File

@ -35,6 +35,7 @@ config("appkit_public_config") {
visibility = [ ":*" ]
include_dirs = [
"//base/global/resmgr_standard/interfaces/innerkits/include",
"//base/global/i18n_standard/frameworks/intl/include",
"//third_party/icu/icu4c/source/common",
]
}
@ -50,6 +51,8 @@ ohos_executable("appexec") {
"//foundation/aafwk/standard/interfaces/innerkits/base/include",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/aafwk/standard/services/abilitymgr/include",
"//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/app",
"//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core/include",
"//utils/native/base/include",
@ -85,6 +88,9 @@ ohos_shared_library("appkit_native") {
"$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core/include/appmgr",
"$SUBSYSTEM_DIR/interfaces/innerkits/libeventhandler/include",
"$SUBSYSTEM_DIR/kits/appkit/native/app/include",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/app",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context",
"$SUBSYSTEM_DIR/kits/appkit/native",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/aafwk/standard/services/abilitymgr/include",
@ -117,6 +123,66 @@ ohos_shared_library("appkit_native") {
"$SUBSYSTEM_DIR/kits/appkit/native/app/src/main_thread.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/app/src/ohos_application.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/app/src/sys_mgr_client.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/app/ability_stage.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"$SUBSYSTEM_DIR/kits:app_context",
"$SUBSYSTEM_DIR/common:libappexecfwk_common",
"$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/frameworks/proxy:libmmi-client",
"//utils/native/base:utils",
"//third_party/icu/icu4c:shared_icuuc",
]
public_deps = [
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//base/global/i18n_standard/frameworks/intl:intl_util",
]
external_deps = [
"aafwk_standard:runtime",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
"bytrace_standard:bytrace_core",
]
part_name = "appexecfwk_standard"
}
# build so
ohos_shared_library("app_context") {
include_dirs = [
"$SUBSYSTEM_DIR/kits/appkit/native/app/include",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context",
"$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core/include",
"//utils/system/safwk/native/include",
]
configs = [ ":appkit_config" ]
public_configs = [ ":appkit_public_config" ]
sources = [
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/context_impl.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/js_context_utils.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp",
"$SUBSYSTEM_DIR/kits/appkit/native/app/src/sys_mgr_client.cpp",
]
cflags = []
if (target_cpu == "arm") {
@ -126,7 +192,7 @@ ohos_shared_library("appkit_native") {
"$SUBSYSTEM_DIR/common:libappexecfwk_common",
"$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
# "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
@ -134,13 +200,19 @@ ohos_shared_library("appkit_native") {
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/frameworks/proxy:libmmi-client",
"//utils/native/base:utils",
"//third_party/icu/icu4c:shared_icuuc",
]
public_deps = [
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//base/global/i18n_standard/frameworks/intl:intl_util",
]
public_deps =
[ "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr" ]
external_deps = [
"aafwk_standard:runtime",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
]
part_name = "appexecfwk_standard"

View File

@ -15,8 +15,11 @@ import("//build/ohos.gni")
group("napi_packages") {
deps = [
"//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage:abilitystage_napi",
"//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage_context:abilitystagecontext_napi",
"//foundation/appexecfwk/standard/kits/appkit/napi/appMgr:napi_app_mgr",
"//foundation/appexecfwk/standard/kits/appkit/napi/bundlemgr:bundle",
"//foundation/appexecfwk/standard/kits/appkit/napi/context:context_napi",
"//foundation/appexecfwk/standard/kits/appkit/napi/launchermgr:innerbundlemanager",
]
}

View File

@ -0,0 +1,49 @@
# 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.
import("//ark/ts2abc/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_ability_stage_abc") {
src_js = rebase_path("ability_stage.js")
dst_file = rebase_path(target_out_dir + "/ability_stage.abc")
in_puts = [ "ability_stage.js" ]
out_puts = [ target_out_dir + "/ability_stage.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("ability_stage_js") {
input = "ability_stage.js"
output = target_out_dir + "/ability_stage.o"
}
gen_js_obj("ability_stage_abc") {
input = get_label_info(":gen_ability_stage_abc", "target_out_dir") + "/ability_stage.abc"
output = target_out_dir + "/ability_stage_abc.o"
dep = ":gen_ability_stage_abc"
}
ohos_shared_library("abilitystage_napi") {
sources = [ "ability_stage_module.cpp" ]
deps = [
":ability_stage_abc",
":ability_stage_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "appexecfwk"
part_name = "appexecfwk_standard"
}

View File

@ -0,0 +1,21 @@
/*
* 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.
*/
class AbilityStage {
constructor() {}
onCreate() {}
}
export default AbilityStage

View File

@ -0,0 +1,57 @@
/*
* 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 "native_engine/native_engine.h"
extern const char _binary_ability_stage_js_start[];
extern const char _binary_ability_stage_js_end[];
extern const char _binary_ability_stage_abc_start[];
extern const char _binary_ability_stage_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_AbilityStage_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.AbilityStage",
.fileName = "application/libabilitystage_napi.so/ability_stage.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_AbilityStage_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_ability_stage_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_ability_stage_js_end - _binary_ability_stage_js_start;
}
}
// ability_stage JS register
extern "C" __attribute__((visibility("default")))
void NAPI_application_AbilityStage_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_ability_stage_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_ability_stage_abc_end - _binary_ability_stage_abc_start;
}
}

View File

@ -0,0 +1,49 @@
# 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.
import("//ark/ts2abc/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_ability_stage_context_abc") {
src_js = rebase_path("ability_stage_context.js")
dst_file = rebase_path(target_out_dir + "/ability_stage_context.abc")
in_puts = [ "ability_stage_context.js" ]
out_puts = [ target_out_dir + "/ability_stage_context.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("ability_stage_context_js") {
input = "ability_stage_context.js"
output = target_out_dir + "/ability_stage_context.o"
}
gen_js_obj("ability_stage_context_abc") {
input = get_label_info(":gen_ability_stage_context_abc", "target_out_dir") + "/ability_stage_context.abc"
output = target_out_dir + "/ability_stage_context_abc.o"
dep = ":gen_ability_stage_context_abc"
}
ohos_shared_library("abilitystagecontext_napi") {
sources = [ "ability_stage_context_module.cpp" ]
deps = [
":ability_stage_context_abc",
":ability_stage_context_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "appexecfwk"
part_name = "appexecfwk_standard"
}

View File

@ -0,0 +1,26 @@
/*
* 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.
*/
var Context = requireNapi("application.Context")
class AbilityStageContext extends Context {
constructor(obj) {
super(obj)
this.currentHapModuleInfo = obj.currentHapModuleInfo
}
}
export default AbilityStageContext

View File

@ -0,0 +1,57 @@
/*
* 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 "native_engine/native_engine.h"
extern const char _binary_ability_stage_context_js_start[];
extern const char _binary_ability_stage_context_js_end[];
extern const char _binary_ability_stage_context_abc_start[];
extern const char _binary_ability_stage_context_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_AbilityStageContext_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.AbilityStageContext",
.fileName = "application/libabilitystagecontext_napi.so/ability_stage_context.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_AbilityStageContext_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_ability_stage_context_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_ability_stage_context_js_end - _binary_ability_stage_context_js_start;
}
}
// ability_stage_context JS register
extern "C" __attribute__((visibility("default")))
void NAPI_application_AbilityStageContext_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_ability_stage_context_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_ability_stage_context_abc_end - _binary_ability_stage_context_abc_start;
}
}

View File

@ -15,15 +15,15 @@
#include "app_mgr.h"
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "ipc_skeleton.h"
#include "system_ability_definition.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
using namespace OHOS;
using namespace OHOS::AAFwk;

View File

@ -16,12 +16,12 @@
#ifndef APP_MGR_H
#define APP_MGR_H
#include "napi/native_common.h"
#include <js_native_api.h>
#include "napi/native_node_api.h"
#include "hilog_wrapper.h"
#include "ability_manager_interface.h"
#include "hilog_wrapper.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
struct AsyncCallbackInfo {
napi_env env;

View File

@ -0,0 +1,49 @@
# 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.
import("//ark/ts2abc/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_context_abc") {
src_js = rebase_path("context.js")
dst_file = rebase_path(target_out_dir + "/context.abc")
in_puts = [ "context.js" ]
out_puts = [ target_out_dir + "/context.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("context_js") {
input = "context.js"
output = target_out_dir + "/context.o"
}
gen_js_obj("context_abc") {
input = get_label_info(":gen_context_abc", "target_out_dir") + "/context.abc"
output = target_out_dir + "/context_abc.o"
dep = ":gen_context_abc"
}
ohos_shared_library("context_napi") {
sources = [ "context_module.cpp" ]
deps = [
":context_abc",
":context_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "appexecfwk"
part_name = "appexecfwk_standard"
}

View File

@ -0,0 +1,39 @@
/*
* 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.
*/
class Context {
constructor(obj) {
this.__context_impl__ = obj
this.resourceManager = obj.resourceManager
this.applicationInfo = obj.applicationInfo
this.cacheDir = obj.cacheDir
this.tempDir = obj.tempDir
this.filesDir = obj.filesDir
this.distributedFilesDir = obj.distributedFilesDir
this.databaseDir = obj.databaseDir
this.storageDir = obj.storageDir
this.bundleCodeDir = obj.bundleCodeDir
}
createBundleContext(bundleName) {
return this.__context_impl__.createBundleContext(bundleName)
}
getApplicationContext() {
return this.__context_impl__.getApplicationContext()
}
}
export default Context

View File

@ -0,0 +1,57 @@
/*
* 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 "native_engine/native_engine.h"
extern const char _binary_context_js_start[];
extern const char _binary_context_js_end[];
extern const char _binary_context_abc_start[];
extern const char _binary_context_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_Context_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.Context",
.fileName = "application/libcontext_napi.so/context.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_Context_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_context_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_context_js_end - _binary_context_js_start;
}
}
// context JS register
extern "C" __attribute__((visibility("default")))
void NAPI_application_Context_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_context_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_context_abc_end - _binary_context_abc_start;
}
}

View File

@ -0,0 +1,90 @@
/*
* 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 "ability_stage.h"
#include "hilog_wrapper.h"
#include "js_ability_stage.h"
#include "runtime.h"
namespace OHOS {
namespace AbilityRuntime {
std::shared_ptr<AbilityStage> AbilityStage::Create(
const std::unique_ptr<Runtime>& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo)
{
if (!runtime) {
return std::make_shared<AbilityStage>();
}
switch (runtime->GetLanguage()) {
case Runtime::Language::JS:
return JsAbilityStage::Create(runtime, hapModuleInfo);
default:
return std::make_shared<AbilityStage>();
}
}
void AbilityStage::OnCreate() const
{
HILOG_INFO("AbilityStage::OnCreate come");
}
void AbilityStage::OnDestory() const
{
HILOG_INFO("AbilityStage::OnDestory come");
}
std::shared_ptr<Context> AbilityStage::GetContext() const
{
return context_;
}
void AbilityStage::Init(std::shared_ptr<Context> context)
{
this->context_ = context;
}
void AbilityStage::AddAbility(const sptr<IRemoteObject> &token,
std::shared_ptr<AppExecFwk::AbilityLocalRecord> abilityRecord)
{
if (token == nullptr) {
HILOG_ERROR("AbilityStage::AddAbility failed, token is nullptr");
return;
}
if (abilityRecord == nullptr) {
HILOG_ERROR("AbilityStage::AddAbility failed, abilityRecord is nullptr");
return;
}
abilityRecords_[token] = abilityRecord;
}
void AbilityStage::RemoveAbility(const sptr<IRemoteObject> &token)
{
if (token == nullptr) {
HILOG_ERROR("AbilityStage::RemoveAbility failed, token is nullptr");
return;
}
abilityRecords_.erase(token);
}
bool AbilityStage::ContainsAbility()
{
return abilityRecords_.size() > 0;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,56 @@
/*
* 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 ABILITY_RUNTIME_ABILITY_STAGE_H
#define ABILITY_RUNTIME_ABILITY_STAGE_H
#include <map>
#include <memory>
#include <string>
#include "ability_local_record.h"
#include "ability_runtime/context/context.h"
namespace OHOS {
namespace AbilityRuntime {
class Runtime;
/**
* @brief the hap level entity
*
* To share the data amony the abilities of a hap,
* and supply lifecycle func for the developers.
*
*/
class AbilityStage {
public:
static std::shared_ptr<AbilityStage> Create(
const std::unique_ptr<Runtime>& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo);
AbilityStage() = default;
virtual ~AbilityStage() = default;
virtual void OnCreate() const;
virtual void OnDestory() const;
virtual void Init(std::shared_ptr<Context> context);
std::shared_ptr<Context> GetContext() const;
void AddAbility(const sptr<IRemoteObject> &token, std::shared_ptr<AppExecFwk::AbilityLocalRecord> abilityRecord);
void RemoveAbility(const sptr<IRemoteObject> &token);
bool ContainsAbility();
private:
std::shared_ptr<Context> context_;
std::map<sptr<IRemoteObject>, std::shared_ptr<AppExecFwk::AbilityLocalRecord>> abilityRecords_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_ABILITY_STAGE_H

View File

@ -0,0 +1,111 @@
/*
* 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_ability_stage.h"
#include "hilog_wrapper.h"
#include "js_context_utils.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
namespace OHOS {
namespace AbilityRuntime {
std::shared_ptr<AbilityStage> JsAbilityStage::Create(
const std::unique_ptr<Runtime>& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo)
{
auto& jsRuntime = static_cast<JsRuntime&>(*runtime);
std::string srcPath(hapModuleInfo.name);
srcPath.append("/assets/js/");
if (hapModuleInfo.srcPath.empty()) {
srcPath.append("AbilityStage.abc");
} else {
srcPath.append(hapModuleInfo.srcPath);
srcPath.append("/AbilityStage.abc");
}
std::string moduleName(hapModuleInfo.moduleName);
moduleName.append("::").append("AbilityStage");
auto moduleObj = jsRuntime.LoadModule(moduleName, srcPath);
return std::make_shared<JsAbilityStage>(jsRuntime, std::move(moduleObj));
}
JsAbilityStage::JsAbilityStage(JsRuntime& jsRuntime, std::unique_ptr<NativeReference>&& jsAbilityStageObj)
: jsRuntime_(jsRuntime), jsAbilityStageObj_(std::move(jsAbilityStageObj))
{}
JsAbilityStage::~JsAbilityStage() = default;
void JsAbilityStage::Init(std::shared_ptr<Context> context)
{
AbilityStage::Init(context);
if (!context) {
HILOG_ERROR("context is nullptr");
return;
}
if (!jsAbilityStageObj_) {
return;
}
HandleScope handleScope(jsRuntime_);
auto& engine = jsRuntime_.GetNativeEngine();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(jsAbilityStageObj_->Get());
if (obj == nullptr) {
HILOG_ERROR("Failed to get AbilityStage object");
return;
}
NativeValue* contextObj = CreateJsBaseContext(engine, context);
auto shellContextRef = jsRuntime_.LoadSystemModule("application.AbilityStageContext", &contextObj, 1);
contextObj = shellContextRef->Get();
context->Bind(jsRuntime_, shellContextRef.release());
obj->SetProperty("context", contextObj);
}
void JsAbilityStage::OnCreate() const
{
HILOG_INFO("JsAbilityStage::OnCreate come");
AbilityStage::OnCreate();
if (!jsAbilityStageObj_) {
HILOG_WARN("Not found AbilityStage.js");
return;
}
HandleScope handleScope(jsRuntime_);
auto& nativeEngine = jsRuntime_.GetNativeEngine();
NativeValue* value = jsAbilityStageObj_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
HILOG_ERROR("Failed to get AbilityStage object");
return;
}
NativeValue* methodOnCreate = obj->GetProperty("onCreate");
if (methodOnCreate == nullptr) {
HILOG_ERROR("Failed to get 'onCreate' from AbilityStage object");
return;
}
nativeEngine.CallFunction(value, methodOnCreate, nullptr, 0);
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,44 @@
/*
* 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 ABILITY_RUNTIME_JS_ABILITY_STAGE_H
#define ABILITY_RUNTIME_JS_ABILITY_STAGE_H
#include "ability_stage.h"
class NativeReference;
namespace OHOS {
namespace AbilityRuntime {
class JsRuntime;
class JsAbilityStage : public AbilityStage {
public:
static std::shared_ptr<AbilityStage> Create(
const std::unique_ptr<Runtime>& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo);
JsAbilityStage(JsRuntime& jsRuntime, std::unique_ptr<NativeReference>&& jsAbilityStageObj);
~JsAbilityStage() override;
void Init(std::shared_ptr<Context> context) override;
void OnCreate() const override;
private:
JsRuntime& jsRuntime_;
std::unique_ptr<NativeReference> jsAbilityStageObj_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_JS_ABILITY_STAGE_H

View File

@ -0,0 +1,86 @@
/*
* 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 ABILITY_RUNTIME_BINDABLE_H
#define ABILITY_RUNTIME_BINDABLE_H
#include <memory>
namespace OHOS {
namespace AbilityRuntime {
class Runtime;
class BindingObject final {
public:
template<class T>
BindingObject(Runtime& runtime, T* ptr) : runtime_(runtime), object_(ptr, SimpleRelease<T>) {}
~BindingObject() = default;
template<class T>
T* Get()
{
return static_cast<T*>(object_.get());
}
void Reset()
{
object_.reset();
}
Runtime& GetRuntime()
{
return runtime_;
}
BindingObject(const BindingObject&) = delete;
BindingObject& operator=(const BindingObject&) = delete;
BindingObject(BindingObject&&) = delete;
BindingObject& operator=(BindingObject&&) = delete;
private:
template<class T>
static void SimpleRelease(void* ptr)
{
delete static_cast<T*>(ptr);
}
Runtime& runtime_;
std::unique_ptr<void, void(*)(void*)> object_;
};
class Bindable {
public:
virtual ~Bindable() = default;
template<class T>
void Bind(Runtime& runtime, T* object)
{
object_ = std::make_unique<BindingObject>(runtime, object);
}
const std::unique_ptr<BindingObject>& GetBindingObject() const
{
return object_;
}
protected:
Bindable() = default;
private:
std::unique_ptr<BindingObject> object_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_BINDABLE_H

View File

@ -0,0 +1,146 @@
/*
* 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 ABILITY_RUNTIME_CONTEXT_H
#define ABILITY_RUNTIME_CONTEXT_H
#include <memory>
#include <mutex>
#include "application_info.h"
#include "bindable.h"
#include "hap_module_info.h"
#include "resource_manager.h"
namespace OHOS {
namespace AbilityRuntime {
class Context : public Bindable {
public:
Context() = default;
~Context() override = default;
/**
* @brief Obtains the Context object of the application.
*
* @return Returns the Context object of the application.
*/
static std::shared_ptr<Context> GetApplicationContext();
/**
* @brief Obtains the bundle name of the current ability.
*
* @return Returns the bundle name of the current ability.
*/
virtual std::string GetBundleName() const = 0;
/**
* @brief Creates a Context object for an application with the given bundle name.
*
* @param bundleName Indicates the bundle name of the application.
*
* @return Returns a Context object created for the specified application.
*/
virtual std::shared_ptr<Context> CreateBundleContext(const std::string &bundleName) = 0;
/**
* @brief Obtains information about the current application. The returned application information includes basic
* information such as the application name and application permissions.
*
* @return Returns the ApplicationInfo for the current application.
*/
virtual std::shared_ptr<AppExecFwk::ApplicationInfo> GetApplicationInfo() const = 0;
/**
* @brief Obtains a resource manager.
*
* @return Returns a ResourceManager object.
*/
virtual std::shared_ptr<Global::Resource::ResourceManager> GetResourceManager() const = 0;
/**
* @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
* source code, and configuration files of a module.
*
* @return Returns the path of the package file.
*/
virtual std::string GetBundleCodePath() const = 0;
/**
* @brief Obtains the HapModuleInfo object of the application.
*
* @return Returns the HapModuleInfo object of the application.
*/
virtual std::shared_ptr<AppExecFwk::HapModuleInfo> GetHapModuleInfo() const = 0;
/**
* @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
* source code, and configuration files of a module.
*
* @return Returns the path of the package file.
*/
virtual std::string GetBundleCodeDir() = 0;
/**
* @brief Obtains the application-specific cache directory on the device's internal storage. The system
* automatically deletes files from the cache directory if disk space is required elsewhere on the device.
* Older files are always deleted first.
*
* @return Returns the application-specific cache directory.
*/
virtual std::string GetCacheDir() = 0;
/**
* @brief Obtains the temporary directory.
*
* @return Returns the application temporary directory.
*/
virtual std::string GetTempDir() = 0;
/**
* @brief Obtains the directory for storing files for the application on the device's internal storage.
*
* @return Returns the application file directory.
*/
virtual std::string GetFilesDir() = 0;
/**
* @brief Obtains the local database path.
* If the local database path does not exist, the system creates one and returns the created path.
*
* @return Returns the local database file.
*/
virtual std::string GetDatabaseDir() = 0;
/**
* @brief Obtains the path storing the storage file of the application.
*
* @return Returns the local storage file.
*/
virtual std::string GetStorageDir() = 0;
/**
* @brief Obtains the path distributed file of the application
*
* @return Returns the distributed file.
*/
virtual std::string GetDistributedFilesDir() = 0;
protected:
static std::shared_ptr<Context> appContext_;
static std::mutex contextMutex_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_CONTEXT_H

View File

@ -0,0 +1,322 @@
/*
* 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 "context_impl.h"
#include "hilog_wrapper.h"
#include "ipc_singleton.h"
#include "locale_config.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace AbilityRuntime {
const int64_t ContextImpl::CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001);
const std::string ContextImpl::CONTEXT_BUNDLECODE_BASE("/data/app/base/");
const std::string ContextImpl::CONTEXT_BUNDLECODE("/data/storage/app/base");
const std::string ContextImpl::CONTEXT_BUNDLE("/bundle/");
const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE("/mnt/hmdfs/");
const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE("/device_view/local/data/");
const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES("distributedfiles");
const std::string ContextImpl::CONTEXT_FILE_SEPARATOR("/");
const std::string ContextImpl::CONTEXT_DATA("/data/");
const std::string ContextImpl::CONTEXT_BASE("/data/storage/");
const std::string ContextImpl::CONTEXT_PRIVATE("/private/");
const std::string ContextImpl::CONTEXT_CACHES("caches");
const std::string ContextImpl::CONTEXT_STORAGE("storage");
const std::string ContextImpl::CONTEXT_DATABASE("database");
const std::string ContextImpl::CONTEXT_TEMP("/temp");
const std::string ContextImpl::CONTEXT_FILES("/files");
const std::string ContextImpl::CONTEXT_CE("ce");
std::string ContextImpl::GetBundleName() const
{
if (parentContext_ != nullptr) {
return parentContext_->GetBundleName();
}
return (applicationInfo_ != nullptr) ? applicationInfo_->bundleName : "";
}
std::string ContextImpl::GetBundleCodeDir()
{
std::string dir;
if (IsCreateBySystemApp()) {
dir = CONTEXT_BUNDLECODE_BASE + GetBundleName();
} else {
dir = CONTEXT_BUNDLECODE;
}
HILOG_DEBUG("ContextImpl::GetBundleCodeDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetCacheDir()
{
std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_CACHES;
HILOG_DEBUG("ContextImpl::GetCacheDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetDatabaseDir()
{
std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_DATABASE;
HILOG_DEBUG("ContextImpl::GetDatabaseDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetStorageDir()
{
std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_STORAGE;
HILOG_DEBUG("ContextImpl::GetStorageDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetTempDir()
{
std::string dir = GetBaseDir() + CONTEXT_TEMP;
HILOG_DEBUG("ContextImpl::GetTempDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetFilesDir()
{
std::string dir = GetBaseDir() + CONTEXT_FILES;
HILOG_DEBUG("ContextImpl::GetFilesDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetDistributedFilesDir()
{
HILOG_DEBUG("ContextImpl::GetDistributedFilesDir");
std::string dir;
if (IsCreateBySystemApp()) {
dir = CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE + GetCurrentAccount() +
CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE + GetBundleName();
} else {
dir = CONTEXT_BASE + CONTEXT_DISTRIBUTEDFILES;
}
HILOG_DEBUG("ContextImpl::GetDistributedFilesDir:%{public}s", dir.c_str());
return dir;
}
std::string ContextImpl::GetBaseDir() const
{
std::string baseDir;
if (IsCreateBySystemApp()) {
baseDir = CONTEXT_DATA + currArea_ + CONTEXT_FILE_SEPARATOR + GetCurrentAccount() +
CONTEXT_BUNDLE + GetBundleName();
} else {
baseDir = CONTEXT_BASE + currArea_;
}
if (parentContext_ != nullptr) {
baseDir = baseDir + CONTEXT_FILE_SEPARATOR + GetHapModuleInfo()->moduleName;
}
HILOG_DEBUG("ContextImpl::GetBaseDir:%{public}s", baseDir.c_str());
return baseDir;
}
std::string ContextImpl::GetCurrentAccount() const
{
return "0";
}
std::shared_ptr<Context> ContextImpl::CreateBundleContext(const std::string &bundleName)
{
if (parentContext_ != nullptr) {
return parentContext_->CreateBundleContext(bundleName);
}
if (bundleName.empty()) {
HILOG_ERROR("ContextImpl::CreateBundleContext bundleName is empty");
return nullptr;
}
sptr<AppExecFwk::IBundleMgr> bundleMgr = GetBundleManager();
if (bundleMgr == nullptr) {
HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleManager is nullptr");
return nullptr;
}
AppExecFwk::BundleInfo bundleInfo;
HILOG_DEBUG("ContextImpl::CreateBundleContext length: %{public}zu, bundleName: %{public}s",
(size_t)bundleName.length(),
bundleName.c_str());
bundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo);
if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) {
HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleInfo is error");
return nullptr;
}
std::shared_ptr<ContextImpl> appContext = std::make_shared<ContextImpl>();
appContext->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
// init resourceManager.
InitResourceManager(bundleInfo, appContext);
appContext->SetApplicationInfo(std::make_shared<AppExecFwk::ApplicationInfo>(bundleInfo.applicationInfo));
return appContext;
}
void ContextImpl::InitResourceManager(
const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr<ContextImpl> &appContext) const
{
std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
if (appContext == nullptr || resourceManager == nullptr) {
HILOG_ERROR("ContextImpl::InitResourceManager create resourceManager failed");
return;
}
HILOG_DEBUG(
"ContextImpl::InitResourceManager moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size());
for (auto moduleResPath : bundleInfo.moduleResPaths) {
if (!moduleResPath.empty()) {
HILOG_ERROR("ContextImpl::InitResourceManager length: %{public}zu, moduleResPath: %{public}s",
moduleResPath.length(),
moduleResPath.c_str());
if (!resourceManager->AddResource(moduleResPath.c_str())) {
HILOG_ERROR("ContextImpl::InitResourceManager AddResource failed");
}
}
}
std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
UErrorCode status = U_ZERO_ERROR;
icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
resConfig->SetLocaleInfo(locale);
if (resConfig->GetLocaleInfo() != nullptr) {
HILOG_DEBUG("ContextImpl::InitResourceManager language: %{public}s, script: %{public}s, region: %{public}s,",
resConfig->GetLocaleInfo()->getLanguage(),
resConfig->GetLocaleInfo()->getScript(),
resConfig->GetLocaleInfo()->getCountry());
} else {
HILOG_ERROR("ContextImpl::InitResourceManager language: GetLocaleInfo is null.");
}
resourceManager->UpdateResConfig(*resConfig);
appContext->SetResourceManager(resourceManager);
}
sptr<AppExecFwk::IBundleMgr> ContextImpl::GetBundleManager() const
{
HILOG_DEBUG("ContextImpl::GetBundleManager begin");
auto bundleObj =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(
BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
if (bundleObj == nullptr) {
HILOG_ERROR("failed to get bundle manager service");
return nullptr;
}
HILOG_DEBUG("ContextImpl::GetBundleManager before iface_cast<bundleObj>");
sptr<AppExecFwk::IBundleMgr> bms = iface_cast<AppExecFwk::IBundleMgr>(bundleObj);
HILOG_DEBUG("ContextImpl::GetBundleManager after iface_cast<bundleObj>");
HILOG_DEBUG("ContextImpl::GetBundleManager end");
return bms;
}
void ContextImpl::SetApplicationInfo(const std::shared_ptr<AppExecFwk::ApplicationInfo> &info)
{
if (info == nullptr) {
HILOG_ERROR("ContextImpl::SetApplicationInfo failed, info is empty");
return;
}
applicationInfo_ = info;
}
void ContextImpl::SetResourceManager(const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
{
HILOG_DEBUG("ContextImpl::initResourceManager. Start.");
resourceManager_ = resourceManager;
HILOG_DEBUG("ContextImpl::initResourceManager. End.");
}
std::shared_ptr<Global::Resource::ResourceManager> ContextImpl::GetResourceManager() const
{
if (parentContext_ != nullptr) {
return parentContext_->GetResourceManager();
}
return resourceManager_;
}
std::shared_ptr<AppExecFwk::ApplicationInfo> ContextImpl::GetApplicationInfo() const
{
if (parentContext_ != nullptr) {
return parentContext_->GetApplicationInfo();
}
return applicationInfo_;
}
void ContextImpl::SetParentContext(const std::shared_ptr<Context> &context)
{
parentContext_ = context;
}
std::string ContextImpl::GetBundleCodePath() const
{
if (parentContext_ != nullptr) {
return parentContext_->GetBundleCodePath();
}
return (applicationInfo_ != nullptr) ? applicationInfo_->codePath : "";
}
void ContextImpl::InitHapModuleInfo(const std::shared_ptr<AppExecFwk::AbilityInfo> &abilityInfo)
{
if (hapModuleInfo_ != nullptr || abilityInfo == nullptr) {
return;
}
sptr<AppExecFwk::IBundleMgr> ptr = GetBundleManager();
if (ptr == nullptr) {
HILOG_ERROR("InitHapModuleInfo: failed to get bundle manager service");
return;
}
hapModuleInfo_ = std::make_shared<AppExecFwk::HapModuleInfo>();
if (!ptr->GetHapModuleInfo(*abilityInfo.get(), *hapModuleInfo_)) {
HILOG_ERROR("InitHapModuleInfo: GetHapModuleInfo failed, will retval false value");
}
}
std::shared_ptr<AppExecFwk::HapModuleInfo> ContextImpl::GetHapModuleInfo() const
{
return hapModuleInfo_;
}
void ContextImpl::SetFlags(int64_t flags)
{
flags_ = static_cast<uint64_t>(flags_) | CONTEXT_CREATE_BY_SYSTEM_APP;
}
bool ContextImpl::IsCreateBySystemApp() const
{
return (static_cast<uint64_t>(flags_) & CONTEXT_CREATE_BY_SYSTEM_APP) == 1;
}
std::shared_ptr<Context> Context::appContext_ = nullptr;
std::mutex Context::contextMutex_;
std::shared_ptr<Context> Context::GetApplicationContext()
{
std::lock_guard<std::mutex> lock(contextMutex_);
return appContext_;
}
void ContextImpl::InitAppContext()
{
std::lock_guard<std::mutex> lock(Context::contextMutex_);
Context::appContext_ = shared_from_this();
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,205 @@
/*
* 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 ABILITY_RUNTIME_CONTEXT_IMPL_H
#define ABILITY_RUNTIME_CONTEXT_IMPL_H
#include "context.h"
#include "bundle_mgr_interface.h"
namespace OHOS {
namespace AbilityRuntime {
class ContextImpl : public Context, public std::enable_shared_from_this<ContextImpl> {
public:
ContextImpl() = default;
virtual ~ContextImpl() = default;
/**
* @brief Obtains the bundle name of the current ability.
*
* @return Returns the bundle name of the current ability.
*/
std::string GetBundleName() const override;
/**
* @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
* source code, and configuration files of a module.
*
* @return Returns the path of the package file.
*/
std::string GetBundleCodeDir() override;
/**
* @brief Obtains the application-specific cache directory on the device's internal storage. The system
* automatically deletes files from the cache directory if disk space is required elsewhere on the device.
* Older files are always deleted first.
*
* @return Returns the application-specific cache directory.
*/
std::string GetCacheDir() override;
/**
* @brief Obtains the temporary directory.
*
* @return Returns the application temporary directory.
*/
std::string GetTempDir() override;
/**
* @brief Obtains the directory for storing files for the application on the device's internal storage.
*
* @return Returns the application file directory.
*/
std::string GetFilesDir() override;
/**
* @brief Obtains the local database path.
* If the local database path does not exist, the system creates one and returns the created path.
*
* @return Returns the local database file.
*/
std::string GetDatabaseDir() override;
/**
* @brief Obtains the path storing the storage file of the application.
*
* @return Returns the local storage file.
*/
std::string GetStorageDir() override;
/**
* @brief Obtains the path distributed file of the application
*
* @return Returns the distributed file.
*/
std::string GetDistributedFilesDir() override;
/**
* @brief set the ResourceManager.
*
* @param the ResourceManager has been inited.
*
*/
void SetResourceManager(const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager);
/**
* @brief Obtains a resource manager.
*
* @return Returns a ResourceManager object.
*/
std::shared_ptr<Global::Resource::ResourceManager> GetResourceManager() const override;
/**
* @brief Creates a Context object for an application with the given bundle name.
*
* @param bundleName Indicates the bundle name of the application.
*
* @return Returns a Context object created for the specified application.
*/
std::shared_ptr<Context> CreateBundleContext(const std::string &bundleName) override;
/**
* @brief Obtains an IBundleMgr instance.
* You can use this instance to obtain information about the application bundle.
*
* @return Returns an IBundleMgr instance.
*/
sptr<AppExecFwk::IBundleMgr> GetBundleManager() const;
/**
* @brief Set ApplicationInfo
*
* @param info ApplicationInfo instance.
*/
void SetApplicationInfo(const std::shared_ptr<AppExecFwk::ApplicationInfo> &info);
/**
* @brief Obtains information about the current application. The returned application information includes basic
* information such as the application name and application permissions.
*
* @return Returns the ApplicationInfo for the current application.
*/
std::shared_ptr<AppExecFwk::ApplicationInfo> GetApplicationInfo() const override;
/**
* @brief Set ApplicationInfo
*
* @param info ApplicationInfo instance.
*/
void SetParentContext(const std::shared_ptr<Context> &context);
/**
* @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
* source code, and configuration files of a module.
*
* @return Returns the path of the package file.
*/
std::string GetBundleCodePath() const override;
/**
* @brief Obtains the HapModuleInfo object of the application.
*
* @return Returns the HapModuleInfo object of the application.
*/
std::shared_ptr<AppExecFwk::HapModuleInfo> GetHapModuleInfo() const override;
/**
* @brief Set HapModuleInfo
*
* @param hapModuleInfo HapModuleInfo instance.
*/
void InitHapModuleInfo(const std::shared_ptr<AppExecFwk::AbilityInfo> &abilityInfo);
/**
* @brief Set application context
*/
void InitAppContext();
private:
static const std::string CONTEXT_BUNDLECODE_BASE;
static const std::string CONTEXT_BUNDLECODE;
static const std::string CONTEXT_BUNDLE;
static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE;
static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE;
static const std::string CONTEXT_DISTRIBUTEDFILES;
static const std::string CONTEXT_FILE_SEPARATOR;
static const std::string CONTEXT_DATA;
static const std::string CONTEXT_BASE;
static const std::string CONTEXT_PRIVATE;
static const std::string CONTEXT_CACHES;
static const std::string CONTEXT_STORAGE;
static const std::string CONTEXT_DATABASE;
static const std::string CONTEXT_TEMP;
static const std::string CONTEXT_FILES;
static const std::string CONTEXT_CE;
static const int64_t CONTEXT_CREATE_BY_SYSTEM_APP;
int flags_ = 0x00000000;
void InitResourceManager(
const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr<ContextImpl> &appContext) const;
bool IsCreateBySystemApp() const;
std::string GetBaseDir() const;
std::string GetCurrentAccount() const;
void SetFlags(int64_t flags);
std::shared_ptr<AppExecFwk::ApplicationInfo> applicationInfo_ = nullptr;
std::shared_ptr<Context> parentContext_ = nullptr;
std::shared_ptr<Global::Resource::ResourceManager> resourceManager_ = nullptr;
std::shared_ptr<AppExecFwk::HapModuleInfo> hapModuleInfo_ = nullptr;
std::string currArea_ = CONTEXT_CE;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_CONTEXT_IMPL_H

View File

@ -0,0 +1,158 @@
/*
* 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_context_utils.h"
#include "hilog_wrapper.h"
#include "js_data_struct_converter.h"
#include "js_hap_module_info_utils.h"
#include "js_resource_manager_utils.h"
#include "js_runtime_utils.h"
namespace OHOS {
namespace AbilityRuntime {
namespace {
constexpr char BASE_CONTEXT_NAME[] = "__base_context_ptr__";
class JsBaseContext {
public:
explicit JsBaseContext(std::weak_ptr<Context>&& context) : context_(std::move(context)) {}
virtual ~JsBaseContext() = default;
static void Finalizer(NativeEngine* engine, void* data, void* hint);
static NativeValue* CreateBundleContext(NativeEngine* engine, NativeCallbackInfo* info);
static NativeValue* GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info);
void KeepContext(std::shared_ptr<Context> context)
{
keepContext_ = context;
}
private:
NativeValue* OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info);
NativeValue* OnGetApplicationContext(NativeEngine& engine, NativeCallbackInfo& info);
std::shared_ptr<Context> keepContext_;
protected:
std::weak_ptr<Context> context_;
};
void JsBaseContext::Finalizer(NativeEngine* engine, void* data, void* hint)
{
HILOG_INFO("JsBaseContext::Finalizer is called");
std::unique_ptr<JsBaseContext>(static_cast<JsBaseContext*>(data));
}
NativeValue* JsBaseContext::CreateBundleContext(NativeEngine* engine, NativeCallbackInfo* info)
{
JsBaseContext* me = CheckParamsAndGetThis<JsBaseContext>(engine, info, BASE_CONTEXT_NAME);
return me != nullptr ? me->OnCreateBundleContext(*engine, *info) : nullptr;
}
NativeValue* JsBaseContext::GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info)
{
JsBaseContext* me = CheckParamsAndGetThis<JsBaseContext>(engine, info, BASE_CONTEXT_NAME);
return me != nullptr ? me->OnGetApplicationContext(*engine, *info) : nullptr;
}
NativeValue* JsBaseContext::OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info)
{
if (info.argc == 0) {
HILOG_ERROR("Not enough params");
return engine.CreateUndefined();
}
auto context = context_.lock();
if (!context) {
HILOG_WARN("context is already released");
return engine.CreateUndefined();
}
std::string bundleName;
if (!ConvertFormJsValue(engine, info.argv[0], bundleName)) {
HILOG_ERROR("Parse bundleName failed");
return engine.CreateUndefined();
}
auto bundleContext = context->CreateBundleContext(bundleName);
if (!bundleContext) {
HILOG_ERROR("bundleContext is nullptr");
return engine.CreateUndefined();
}
JsRuntime& jsRuntime = *static_cast<JsRuntime*>(engine.GetJsEngine());
NativeValue* value = CreateJsBaseContext(engine, bundleContext, true);
return jsRuntime.LoadSystemModule("application.AbilityStageContext", &value, 1)->Get();
}
NativeValue* JsBaseContext::OnGetApplicationContext(NativeEngine& engine, NativeCallbackInfo& info)
{
auto context = context_.lock();
if (!context) {
HILOG_WARN("context is already released");
return engine.CreateUndefined();
}
auto appContext = context->GetApplicationContext();
if (!appContext) {
HILOG_ERROR("appContext is nullptr");
return engine.CreateUndefined();
}
JsRuntime& jsRuntime = *static_cast<JsRuntime*>(engine.GetJsEngine());
NativeValue* value = CreateJsBaseContext(engine, appContext, true);
return jsRuntime.LoadSystemModule("application.Context", &value, 1)->Get();
}
} // namespace
NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr<Context> context, bool keepContext)
{
NativeValue* objValue = engine.CreateObject();
NativeObject* object = ConvertNativeValueTo<NativeObject>(objValue);
auto jsContext = std::make_unique<JsBaseContext>(context);
if (keepContext) {
jsContext->KeepContext(context);
}
SetNamedNativePointer(engine, *object, BASE_CONTEXT_NAME, jsContext.release(), JsBaseContext::Finalizer);
auto appInfo = context->GetApplicationInfo();
if (appInfo != nullptr) {
object->SetProperty("applicationInfo", CreateJsApplicationInfo(engine, *appInfo));
}
auto hapModuleInfo = context->GetHapModuleInfo();
if (hapModuleInfo != nullptr) {
object->SetProperty("currentHapModuleInfo", CreateJsHapModuleInfo(engine, *hapModuleInfo));
}
auto resourceManager = context->GetResourceManager();
if (resourceManager != nullptr) {
object->SetProperty("resourceManager", CreateJsResourceManager(engine, resourceManager));
}
object->SetProperty("cacheDir", CreateJsValue(engine, context->GetCacheDir()));
object->SetProperty("tempDir", CreateJsValue(engine, context->GetTempDir()));
object->SetProperty("filesDir", CreateJsValue(engine, context->GetFilesDir()));
object->SetProperty("distributedFilesDir", CreateJsValue(engine, context->GetDistributedFilesDir()));
object->SetProperty("databaseDir", CreateJsValue(engine, context->GetDatabaseDir()));
object->SetProperty("storageDir", CreateJsValue(engine, context->GetStorageDir()));
object->SetProperty("bundleCodeDir", CreateJsValue(engine, context->GetBundleCodeDir()));
BindNativeFunction(engine, *object, "createBundleContext", JsBaseContext::CreateBundleContext);
BindNativeFunction(engine, *object, "getApplicationContext", JsBaseContext::GetApplicationContext);
return objValue;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,32 @@
/*
* 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 ABILITY_RUNTIME_JS_CONTEXT_UTILS_H
#define ABILITY_RUNTIME_JS_CONTEXT_UTILS_H
#include <memory>
#include "context.h"
class NativeEngine;
class NativeValue;
struct NativeCallbackInfo;
namespace OHOS {
namespace AbilityRuntime {
NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr<Context> context, bool keepContext = false);
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_JS_CONTEXT_UTILS_H

View File

@ -0,0 +1,71 @@
/*
* 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_hap_module_info_utils.h"
#include "js_data_struct_converter.h"
#include "js_runtime_utils.h"
namespace OHOS {
namespace AbilityRuntime {
NativeValue* CreateJsHapModuleInfo(NativeEngine& engine, AppExecFwk::HapModuleInfo& hapModuleInfo)
{
NativeValue* objValue = engine.CreateObject();
NativeObject* object = ConvertNativeValueTo<NativeObject>(objValue);
object->SetProperty("name", CreateJsValue(engine, hapModuleInfo.name));
object->SetProperty("moduleName", CreateJsValue(engine, hapModuleInfo.moduleName));
object->SetProperty("description", CreateJsValue(engine, hapModuleInfo.description));
object->SetProperty("iconPath", CreateJsValue(engine, hapModuleInfo.iconPath));
object->SetProperty("label", CreateJsValue(engine, hapModuleInfo.label));
object->SetProperty("backgroundImg", CreateJsValue(engine, hapModuleInfo.backgroundImg));
object->SetProperty("mainAbility", CreateJsValue(engine, hapModuleInfo.mainAbility));
object->SetProperty("srcPath", CreateJsValue(engine, hapModuleInfo.srcPath));
object->SetProperty("supportedModes", CreateJsValue(engine, hapModuleInfo.supportedModes));
NativeValue *capArrayValue = engine.CreateArray(hapModuleInfo.reqCapabilities.size());
NativeArray *capArray = ConvertNativeValueTo<NativeArray>(capArrayValue);
if (capArray != nullptr) {
int index = 0;
for (auto cap : hapModuleInfo.reqCapabilities) {
capArray->SetElement(index++, CreateJsValue(engine, cap));
}
}
object->SetProperty("reqCapabilities", capArrayValue);
NativeValue *deviceArrayValue = engine.CreateArray(hapModuleInfo.deviceTypes.size());
NativeArray *deviceArray = ConvertNativeValueTo<NativeArray>(deviceArrayValue);
if (deviceArray != nullptr) {
int index = 0;
for (auto device : hapModuleInfo.deviceTypes) {
deviceArray->SetElement(index++, CreateJsValue(engine, device));
}
}
object->SetProperty("deviceTypes", deviceArrayValue);
NativeValue *abilityArrayValue = engine.CreateArray(hapModuleInfo.abilityInfos.size());
NativeArray *abilityArray = ConvertNativeValueTo<NativeArray>(abilityArrayValue);
if (abilityArray != nullptr) {
int index = 0;
for (auto abilityInfo : hapModuleInfo.abilityInfos) {
abilityArray->SetElement(index++, CreateJsAbilityInfo(engine, abilityInfo));
}
}
object->SetProperty("abilityInfos", abilityArrayValue);
return objValue;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,31 @@
/*
* 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 ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H
#define ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H
#include "hap_module_info.h"
class NativeEngine;
class NativeValue;
namespace OHOS {
namespace AbilityRuntime {
class JsRuntime;
NativeValue* CreateJsHapModuleInfo(NativeEngine& engine, AppExecFwk::HapModuleInfo& hapModuleInfo);
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H

View File

@ -0,0 +1,100 @@
/*
* 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_resource_manager_utils.h"
#include "hilog_wrapper.h"
#include "js_runtime_utils.h"
#include "rstate.h"
namespace OHOS {
namespace AbilityRuntime {
namespace {
const int32_t GETSTRING_PARAM_SIZE = 1;
class JsResourceManager final {
public:
JsResourceManager(const std::shared_ptr<Global::Resource::ResourceManager>& resourceManager)
: resourceManager_(resourceManager) {}
~JsResourceManager() = default;
static void Finalizer(NativeEngine* engine, void* data, void* hint)
{
HILOG_INFO("JsResourceManager::Finalizer is called");
std::unique_ptr<JsResourceManager>(static_cast<JsResourceManager*>(data));
}
static NativeValue* GetString(NativeEngine* engine, NativeCallbackInfo* info)
{
JsResourceManager* me = CheckParamsAndGetThis<JsResourceManager>(engine, info);
return me != nullptr ? me->GetString(*engine, *info) : nullptr;
}
private:
NativeValue* GetString(NativeEngine& engine, NativeCallbackInfo& info)
{
HILOG_INFO("JsResourceManager GetString is called");
if (info.argc == 0) {
HILOG_ERROR("Not enough params");
return engine.CreateUndefined();
}
NativeNumber* number = ConvertNativeValueTo<NativeNumber>(info.argv[0]);
uint32_t param = number ? *(number) : 0;
AsyncTask::CompleteCallback complete =
[weak = resourceManager_, resId = param](NativeEngine& engine, AsyncTask& task, int32_t status) {
auto resourceManager = weak.lock();
if (!resourceManager) {
HILOG_INFO("JsResourceManager is released");
task.Reject(engine, CreateJsError(engine, 1, "resourceManager is released"));
return;
}
std::string retValue;
OHOS::Global::Resource::RState errval = resourceManager->GetStringById(resId, retValue);
if (errval == OHOS::Global::Resource::RState::SUCCESS) {
HILOG_DEBUG("resourceManager GetStringById:%{public}s", retValue.c_str());
task.Resolve(engine, engine.CreateString(retValue.c_str(), retValue.length()));
} else {
HILOG_DEBUG("resourceManager GetStringById failed");
task.Reject(engine, CreateJsError(engine, errval, "getString failed"));
}
};
NativeValue* lastParam = info.argc > GETSTRING_PARAM_SIZE ? info.argv[GETSTRING_PARAM_SIZE] : nullptr;
NativeValue* result = nullptr;
AsyncTask::Schedule(
engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result));
return result;
}
std::weak_ptr<Global::Resource::ResourceManager> resourceManager_;
};
} // namespace
NativeValue* CreateJsResourceManager(
NativeEngine& engine, std::shared_ptr<Global::Resource::ResourceManager> resourceManager)
{
NativeValue* objValue = engine.CreateObject();
NativeObject* object = ConvertNativeValueTo<NativeObject>(objValue);
std::unique_ptr<JsResourceManager> jsResourceManager = std::make_unique<JsResourceManager>(resourceManager);
object->SetNativePointer(jsResourceManager.release(), JsResourceManager::Finalizer, nullptr);
BindNativeFunction(engine, *object, "getString", JsResourceManager::GetString);
return objValue;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,32 @@
/*
* 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 ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H
#define ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H
#include "resource_manager.h"
class NativeEngine;
class NativeValue;
namespace OHOS {
namespace AbilityRuntime {
class JsRuntime;
NativeValue* CreateJsResourceManager(NativeEngine& engine,
std::shared_ptr<Global::Resource::ResourceManager> resourceManager);
} // namespace AbilityRuntime
} // namespace OHOS
#endif // ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H

View File

@ -0,0 +1,31 @@
/*
* 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 "extension_context.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace AbilityRuntime {
void ExtensionContext::SetToken(const sptr<IRemoteObject> &token)
{
if (token == nullptr) {
HILOG_DEBUG("ExtensionContext::SetToken failed, application is nullptr");
return;
}
token_ = token;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,46 @@
/*
* 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 EXTENSION_CONTEXT_H
#define EXTENSION_CONTEXT_H
#include "context_impl.h"
#include "iremote_object.h"
namespace OHOS {
namespace AbilityRuntime {
/**
* @brief context supply for extension
*
*/
class ExtensionContext : public ContextImpl {
public:
ExtensionContext() = default;
virtual ~ExtensionContext() = default;
/**
* @brief Set the token witch the app launched.
*
* @param token The token which the is launched by app.
*/
void SetToken(const sptr<IRemoteObject> &token);
protected:
sptr<IRemoteObject> token_;
private:
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // EXTENSION_CONTEXT_H

View File

@ -0,0 +1,95 @@
/*
* 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 "service_extension_context.h"
#include "ability_manager_client.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace AbilityRuntime {
int ServiceExtensionContext::ILLEGAL_REQUEST_CODE(-1);
void ServiceExtensionContext::StartAbility(const AAFwk::Want &want) const
{
HILOG_DEBUG("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE);
HILOG_DEBUG("%{public}s. End calling ams->StartAbility. ret=%{public}d", __func__, err);
if (err != ERR_OK) {
HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err);
}
}
bool ServiceExtensionContext::ConnectAbility(const AAFwk::Want &want, const sptr<AAFwk::IAbilityConnection> &conn)
{
HILOG_INFO("%{public}s begin.", __func__);
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_);
HILOG_INFO("%{public}s end ConnectAbility, ret=%{public}d", __func__, ret);
bool value = ((ret == ERR_OK) ? true : false);
if (!value) {
HILOG_ERROR("ServiceContext::ConnectAbility ErrorCode = %{public}d", ret);
}
HILOG_INFO("%{public}s end.", __func__);
return value;
}
void ServiceExtensionContext::DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn)
{
HILOG_INFO("%{public}s begin.", __func__);
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn);
HILOG_INFO("%{public}s end ams->DisconnectAbility, ret=%{public}d", __func__, ret);
if (ret != ERR_OK) {
HILOG_ERROR("ServiceContext::DisconnectAbility error");
}
HILOG_INFO("ServiceContext::DisconnectAbility end");
}
void ServiceExtensionContext::TerminateAbility()
{
HILOG_INFO("%{public}s begin.", __func__);
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr);
if (err != ERR_OK) {
HILOG_ERROR("ServiceExtensionContext::TerminateAbility is failed %{public}d", err);
}
HILOG_INFO("%{public}s end.", __func__);
}
AppExecFwk::AbilityType ServiceExtensionContext::GetAbilityInfoType() const
{
std::shared_ptr<AppExecFwk::AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr");
return AppExecFwk::AbilityType::UNKNOWN;
}
return info->type;
}
std::shared_ptr<AppExecFwk::AbilityInfo> ServiceExtensionContext::GetAbilityInfo() const
{
return abilityInfo_;
}
void ServiceExtensionContext::SetAbilityInfo(const std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> &abilityInfo)
{
if (abilityInfo == nullptr) {
HILOG_ERROR("ServiceExtensionContext::SetAbilityInfo Info == nullptr");
return;
}
abilityInfo_ = abilityInfo;
}
} // namespace AbilityRuntime
} // namespace OHOS

View File

@ -0,0 +1,100 @@
/*
* 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 SERVICE_EXTENSION_CONTEXT_H
#define SERVICE_EXTENSION_CONTEXT_H
#include "extension_context.h"
#include "ability_connect_callback_interface.h"
#include "ability_info.h"
#include "want.h"
namespace OHOS {
namespace AbilityRuntime {
/**
* @brief context supply for service
*
*/
class ServiceExtensionContext : public ExtensionContext {
public:
ServiceExtensionContext() = default;
virtual ~ServiceExtensionContext() = default;
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.SERVICE 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.
*
*/
void StartAbility(const AAFwk::Want &want) const;
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE 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<AAFwk::IAbilityConnection> &conn);
/**
* @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.
*/
void DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn);
/**
* @brief Destroys the current ability.
*
*/
void TerminateAbility();
/**
* @brief Obtains information about the current ability.
* The returned information includes the class name, bundle name, and other information about the current ability.
*
* @return Returns the AbilityInfo object for the current ability.
*/
std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> GetAbilityInfo() const;
/**
* @brief Set AbilityInfo when init.
*
*/
void SetAbilityInfo(const std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> &abilityInfo);
private:
static int ILLEGAL_REQUEST_CODE;
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const;
std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> abilityInfo_;
};
} // namespace AbilityRuntime
} // namespace OHOS
#endif // SERVICE_EXTENSION_CONTEXT_H

View File

@ -705,7 +705,7 @@ public:
/**
* set lock screen white list
*
* @param isAllow Whether to allow lock screen.
* @param isAllow Whether to allow lock screen.
*
*/
virtual void SetShowOnLockScreen(bool isAllow) = 0;

View File

@ -32,6 +32,7 @@ namespace OHOS {
namespace AppExecFwk {
using namespace OHOS::Global;
enum class MainThreadState { INIT, ATTACH, READY, RUNNING };
struct BundleInfo;
class ContextDeal;
// class Global::Resource::ResourceManager;
class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient {
@ -453,7 +454,7 @@ private:
Profile &appProfile);
bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData);
bool InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo);
std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo);
std::vector<std::string> fileEntries_;
std::vector<void *> handleAbilityLib_; // the handler of ACE Library.
#endif // ABILITY_LIBRARY_LOADER

View File

@ -18,11 +18,18 @@
#include <string>
#include <list>
#include <memory>
#include "application_context.h"
#include "ability_lifecycle_callbacks.h"
#include "ability_runtime/context/context.h"
#include "ability_stage.h"
#include "element_callback.h"
namespace OHOS {
namespace AbilityRuntime {
class Runtime;
} // namespace AbilityRuntime
namespace AppExecFwk {
class ElementsCallback;
class ApplicationImpl;
@ -33,7 +40,7 @@ class OHOSApplication : public ApplicationContext,
public std::enable_shared_from_this<OHOSApplication> {
public:
OHOSApplication();
virtual ~OHOSApplication() = default;
virtual ~OHOSApplication();
/**
* @brief dump OHOSApplication info
@ -42,6 +49,20 @@ public:
*/
void DumpApplication();
/**
* @brief Set Runtime
*
* @param runtime Runtime instance.
*/
void SetRuntime(std::unique_ptr<AbilityRuntime::Runtime>&& runtime);
/**
* @brief Set ApplicationContext
*
* @param context ApplicationContext instance.
*/
void SetApplicationContext(const std::shared_ptr<AbilityRuntime::Context> &abilityRuntimeContext);
/**
*
* @brief Set the abilityRecordMgr to the OHOSApplication.
@ -194,10 +215,43 @@ public:
*/
virtual void OnTerminate();
/**
* @brief add the ability stage when a hap first load
*
* @param abilityRecord
* @return abilityStage context
*/
std::shared_ptr<AbilityRuntime::Context> AddAbilityStage(
const std::shared_ptr<AbilityLocalRecord> &abilityRecord);
/**
* @brief remove the ability stage when all of the abilities in the hap have been removed
*
* @param abilityInfo
*/
void CleanAbilityStage(const sptr<IRemoteObject> &token, const std::shared_ptr<AbilityInfo> &abilityInfo);
/**
* @brief return the application context
*
* @param context
*/
std::shared_ptr<AbilityRuntime::Context> GetAppContext() const;
/**
* @brief return the application runtime
*
* @param runtime
*/
const std::unique_ptr<AbilityRuntime::Runtime>& GetRuntime();
private:
std::list<std::shared_ptr<AbilityLifecycleCallbacks>> abilityLifecycleCallbacks_;
std::list<std::shared_ptr<ElementsCallback>> elementsCallbacks_;
std::shared_ptr<AbilityRecordMgr> abilityRecordMgr_ = nullptr;
std::shared_ptr<AbilityRuntime::Context> abilityRuntimeContext_ = nullptr;
std::unordered_map<std::string, std::shared_ptr<AbilityRuntime::AbilityStage>> abilityStages_;
std::unique_ptr<AbilityRuntime::Runtime> runtime_;
};
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -16,8 +16,8 @@
#include "ability_manager.h"
#include "app_log_wrapper.h"
#include "singleton.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -14,8 +14,9 @@
*/
#include "application_impl.h"
#include "ohos_application.h"
#include "app_log_wrapper.h"
#include "ohos_application.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -13,11 +13,12 @@
* limitations under the License.
*/
#include "context_container.h"
#include "app_log_wrapper.h"
#include "ability_manager_client.h"
#include "ability_manager_errors.h"
#include "app_log_wrapper.h"
#include "application_context.h"
#include "bundle_constants.h"
#include "ability_manager_client.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -14,16 +14,16 @@
*/
#include "context_deal.h"
#include "file_ex.h"
#include "directory_ex.h"
#include "iservice_registry.h"
#include "app_log_wrapper.h"
#include "ability_manager_interface.h"
#include "ability_manager_client.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
#include "spec_task_dispatcher.h"
#include "ability_manager_interface.h"
#include "app_log_wrapper.h"
#include "application_context.h"
#include "directory_ex.h"
#include "file_ex.h"
#include "iservice_registry.h"
#include "spec_task_dispatcher.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
#include "task_dispatcher_context.h"
#define MODE 0771

View File

@ -14,19 +14,28 @@
*/
#include "main_thread.h"
#include <new>
#include "ohos_application.h"
#include "app_loader.h"
#include "application_env_impl.h"
#include "ability_loader.h"
#include "ability_thread.h"
#include "task_handler_client.h"
#include "app_loader.h"
#include "app_log_wrapper.h"
#include "application_env_impl.h"
#include "bytrace.h"
#include "context_deal.h"
#include "context_impl.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "js_runtime.h"
#include "locale_config.h"
#include "ohos_application.h"
#include "resource_manager.h"
#include "runtime.h"
#include "service_extension.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
#include "app_log_wrapper.h"
#include "task_handler_client.h"
#if defined(ABILITY_LIBRARY_LOADER) || defined(APPLICATION_LIBRARY_LOADER)
#include <dirent.h>
@ -35,6 +44,10 @@
namespace OHOS {
namespace AppExecFwk {
namespace {
constexpr int TARGET_VERSION_THRESHOLDS = 8;
}
#define ACEABILITY_LIBRARY_LOADER
#ifdef ABILITY_LIBRARY_LOADER
#endif
@ -371,6 +384,17 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemo
sptr<IRemoteObject> abilityToken = token;
std::shared_ptr<AbilityLocalRecord> abilityRecord = std::make_shared<AbilityLocalRecord>(abilityInfo, abilityToken);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
sptr<IBundleMgr> bundleMgr = contextDeal->GetBundleManager();
if (bundleMgr == nullptr) {
APP_LOGE("MainThread::ScheduleLaunchAbility GetBundleManager is nullptr");
} else {
BundleInfo bundleInfo;
bundleMgr->GetBundleInfo(abilityInfo->bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo);
abilityRecord->SetTargetVersion(bundleInfo.targetVersion);
APP_LOGI("MainThread::ScheduleLaunchAbility targetVersion:%{public}d", bundleInfo.targetVersion);
}
auto task = [appThread = this, abilityRecord]() { appThread->HandleLaunchAbility(abilityRecord); };
if (!mainHandler_->PostTask(task)) {
APP_LOGE("MainThread::ScheduleLaunchAbility PostTask task failed");
@ -536,6 +560,7 @@ void MainThread::HandleTerminateApplicationLocal()
*/
void MainThread::HandleProcessSecurityExit()
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::HandleProcessSecurityExit called start.");
if (abilityRecordMgr_ == nullptr) {
APP_LOGE("MainThread::HandleProcessSecurityExit abilityRecordMgr_ is null");
@ -614,22 +639,8 @@ bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchD
}
bool MainThread::InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo)
std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo)
{
APP_LOGI("MainThread::InitResourceManager. Start calling GetBundleManager.");
sptr<IBundleMgr> bundleMgr = contextDeal->GetBundleManager();
if (bundleMgr == nullptr) {
APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr");
return false;
}
APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager.");
BundleInfo bundleInfo;
APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s",
appInfo.bundleName.length(),
appInfo.bundleName.c_str());
bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo);
APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start",
bundleInfo.moduleResPaths.size());
for (auto moduleResPath : bundleInfo.moduleResPaths) {
@ -648,7 +659,9 @@ bool MainThread::InitResourceManager(std::shared_ptr<Global::Resource::ResourceM
APP_LOGI("MainThread::handleLaunchApplication before Resource::CreateResConfig.");
std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
APP_LOGI("MainThread::handleLaunchApplication after Resource::CreateResConfig.");
resConfig->SetLocaleInfo("zh", "Hans", "CN");
UErrorCode status = U_ZERO_ERROR;
icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
resConfig->SetLocaleInfo(locale);
const icu::Locale *localeInfo = resConfig->GetLocaleInfo();
if (localeInfo != nullptr) {
APP_LOGI("MainThread::handleLaunchApplication language: %{public}s, script: %{public}s, region: %{public}s,",
@ -673,6 +686,7 @@ bool MainThread::InitResourceManager(std::shared_ptr<Global::Resource::ResourceM
*/
void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData)
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::handleLaunchApplication called start.");
if (!CheckForHandleLaunchApplication(appLaunchData)) {
APP_LOGE("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed");
@ -705,16 +719,64 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData)
return;
}
if (!InitResourceManager(resourceManager, contextDeal, appInfo)) {
APP_LOGI("MainThread::handleLaunchApplication. Start calling GetBundleManager.");
sptr<IBundleMgr> bundleMgr = contextDeal->GetBundleManager();
if (bundleMgr == nullptr) {
APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr");
return;
}
APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager.");
BundleInfo bundleInfo;
APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s",
appInfo.bundleName.length(), appInfo.bundleName.c_str());
bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo);
if (!InitResourceManager(resourceManager, contextDeal, appInfo, bundleInfo)) {
APP_LOGE("MainThread::handleLaunchApplication InitResourceManager failed");
return;
}
if (bundleInfo.compatibleVersion >= TARGET_VERSION_THRESHOLDS) {
// Create runtime
AbilityRuntime::Runtime::Options options;
options.codePath = appInfo.codePath;
auto runtime = AbilityRuntime::Runtime::Create(options);
if (!runtime) {
APP_LOGE("OHOSApplication::OHOSApplication: Failed to create runtime");
return;
}
if (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS) {
std::unique_ptr<std::function<void()>> idleTask = std::make_unique<std::function<void()>>();
*idleTask = [&jsRuntime = static_cast<AbilityRuntime::JsRuntime&>(*runtime), &idleTask = *idleTask]() {
jsRuntime.GetNativeEngine().Loop(LOOP_NOWAIT);
EventHandler::Current()->PostIdleTask(idleTask);
};
mainHandler_->PostIdleTask(*idleTask.release());
}
application_->SetRuntime(std::move(runtime));
AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() {
return Ability::Create(application->GetRuntime());
});
AbilityLoader::GetInstance().RegisterExtension("ServiceExtension", [application = application_]() {
return AbilityRuntime::ServiceExtension::Create(application->GetRuntime());
});
}
contextDeal->initResourceManager(resourceManager);
contextDeal->SetApplicationContext(application_);
application_->AttachBaseContext(contextDeal);
application_->SetAbilityRecordMgr(abilityRecordMgr_);
// create contextImpl
std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
contextImpl->SetResourceManager(resourceManager);
contextImpl->SetApplicationInfo(std::make_shared<ApplicationInfo>(appInfo));
contextImpl->InitAppContext();
application_->SetApplicationContext(contextImpl);
applicationImpl_->SetRecordId(appLaunchData.GetRecordId());
applicationImpl_->SetApplication(application_);
mainThreadState_ = MainThreadState::READY;
@ -748,6 +810,7 @@ void MainThread::HandleAbilityStageInfo(const AppResidentProcessInfo &residentPr
*/
void MainThread::HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::handleLaunchAbility called start.");
if (applicationImpl_ == nullptr) {
@ -785,13 +848,14 @@ void MainThread::HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> &
}
mainThreadState_ = MainThreadState::RUNNING;
std::shared_ptr<AbilityRuntime::Context> stageContext = application_->AddAbilityStage(abilityRecord);
#ifdef APP_ABILITY_USE_TWO_RUNNER
APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain start.");
AbilityThread::AbilityThreadMain(application_, abilityRecord);
AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext);
APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain end.");
#else
APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain start.");
AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner());
AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner(), stageContext);
APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain end.");
#endif
APP_LOGI("MainThread::handleLaunchAbility called end.");
@ -830,7 +894,6 @@ void MainThread::HandleCleanAbilityLocal(const sptr<IRemoteObject> &token)
APP_LOGI("MainThread::HandleCleanAbilityLocal ability name: %{public}s", abilityInfo->name.c_str());
abilityRecordMgr_->RemoveAbilityRecord(token);
#ifdef APP_ABILITY_USE_TWO_RUNNER
std::shared_ptr<EventRunner> runner = record->GetEventRunner();
@ -856,6 +919,7 @@ void MainThread::HandleCleanAbilityLocal(const sptr<IRemoteObject> &token)
*/
void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token)
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::handleCleanAbility called start.");
if (!IsApplicationReady()) {
APP_LOGE("MainThread::handleCleanAbility not init OHOSApplication, should launch application first");
@ -880,7 +944,6 @@ void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token)
APP_LOGI("MainThread::handleCleanAbility ability name: %{public}s", abilityInfo->name.c_str());
abilityRecordMgr_->RemoveAbilityRecord(token);
#ifdef APP_ABILITY_USE_TWO_RUNNER
std::shared_ptr<EventRunner> runner = record->GetEventRunner();
@ -907,6 +970,7 @@ void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token)
*/
void MainThread::HandleForegroundApplication()
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::handleForegroundApplication called start.");
if ((application_ == nullptr) || (appMgr_ == nullptr)) {
APP_LOGE("MainThread::handleForegroundApplication error!");
@ -931,6 +995,7 @@ void MainThread::HandleForegroundApplication()
*/
void MainThread::HandleBackgroundApplication()
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::handleBackgroundApplication called start.");
if ((application_ == nullptr) || (appMgr_ == nullptr)) {
@ -956,6 +1021,7 @@ void MainThread::HandleBackgroundApplication()
*/
void MainThread::HandleTerminateApplication()
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::handleTerminateApplication called start.");
if ((application_ == nullptr) || (appMgr_ == nullptr)) {
APP_LOGE("MainThread::handleTerminateApplication error!");
@ -1009,6 +1075,7 @@ void MainThread::HandleTerminateApplication()
*/
void MainThread::HandleShrinkMemory(const int level)
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::HandleShrinkMemory called start.");
if (applicationImpl_ == nullptr) {
@ -1029,6 +1096,7 @@ void MainThread::HandleShrinkMemory(const int level)
*/
void MainThread::HandleConfigurationUpdated(const Configuration &config)
{
BYTRACE(BYTRACE_TAG_APP);
APP_LOGI("MainThread::HandleConfigurationUpdated called start.");
if (applicationImpl_ == nullptr) {

View File

@ -14,11 +14,14 @@
*/
#include "ohos_application.h"
#include "application_impl.h"
#include "ability_record_mgr.h"
#include "app_loader.h"
#include "app_log_wrapper.h"
#include "application_impl.h"
#include "context_impl.h"
#include "iservice_registry.h"
#include "runtime.h"
#include "system_ability_definition.h"
namespace OHOS {
@ -31,6 +34,8 @@ OHOSApplication::OHOSApplication()
elementsCallbacks_.clear();
}
OHOSApplication::~OHOSApplication() = default;
/**
*
* @brief Called when Ability#onSaveAbilityState(PacMap) was called on an ability.
@ -109,6 +114,38 @@ void OHOSApplication::DumpApplication()
}
}
/**
* @brief Set Runtime
*
* @param runtime Runtime instance.
*/
void OHOSApplication::SetRuntime(std::unique_ptr<AbilityRuntime::Runtime>&& runtime)
{
APP_LOGI("OHOSApplication::SetRuntime begin");
if (runtime == nullptr) {
APP_LOGE("OHOSApplication::SetRuntime failed, runtime is empty");
return;
}
runtime_ = std::move(runtime);
APP_LOGI("OHOSApplication::SetRuntime end");
}
/**
* @brief Set ApplicationContext
*
* @param abilityRuntimeContext ApplicationContext instance.
*/
void OHOSApplication::SetApplicationContext(const std::shared_ptr<AbilityRuntime::Context> &abilityRuntimeContext)
{
APP_LOGI("OHOSApplication::SetApplicationContext begin");
if (abilityRuntimeContext == nullptr) {
APP_LOGE("OHOSApplication::SetApplicationContext failed, context is empty");
return;
}
abilityRuntimeContext_ = abilityRuntimeContext;
APP_LOGI("OHOSApplication::SetApplicationContext end");
}
/**
*
* @brief Set the abilityRecordMgr to the OHOSApplication.
@ -125,7 +162,7 @@ void OHOSApplication::SetAbilityRecordMgr(const std::shared_ptr<AbilityRecordMgr
abilityRecordMgr_ = abilityRecordMgr;
APP_LOGI("OHOSApplication::SetAbilityRecordMgr. End");
}
/**
*
* Register AbilityLifecycleCallbacks with OHOSApplication
@ -389,5 +426,78 @@ void OHOSApplication::OnAbilitySaveState(const PacMap &outState)
{
DispatchAbilitySavedState(outState);
}
std::shared_ptr<AbilityRuntime::Context> OHOSApplication::AddAbilityStage(
const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
{
if (abilityRecord == nullptr) {
APP_LOGE("AddAbilityStage:abilityRecord is nullptr");
return nullptr;
}
const std::shared_ptr<AbilityInfo> &abilityInfo = abilityRecord->GetAbilityInfo();
if (abilityInfo == nullptr) {
APP_LOGE("AddAbilityStage:abilityInfo is nullptr");
return nullptr;
}
std::string moduleName = abilityInfo->moduleName;
std::shared_ptr<AbilityRuntime::AbilityStage> abilityStage;
auto iterator = abilityStages_.find(moduleName);
if (iterator == abilityStages_.end()) {
std::shared_ptr<AbilityRuntime::ContextImpl> stageContext = std::make_shared<AbilityRuntime::ContextImpl>();
stageContext->SetParentContext(abilityRuntimeContext_);
stageContext->InitHapModuleInfo(abilityInfo);
std::shared_ptr<AppExecFwk::HapModuleInfo> hapModuleInfo = stageContext->GetHapModuleInfo();
if (hapModuleInfo == nullptr) {
APP_LOGE("AddAbilityStage:hapModuleInfo is nullptr");
return nullptr;
}
abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *hapModuleInfo);
abilityStage->Init(stageContext);
abilityStage->OnCreate();
abilityStages_[moduleName] = abilityStage;
} else {
abilityStage = iterator->second;
}
const sptr<IRemoteObject> &token = abilityRecord->GetToken();
if (token == nullptr) {
APP_LOGE("AddAbilityStage:token is null");
return nullptr;
}
abilityStage->AddAbility(token, abilityRecord);
return abilityStage->GetContext();
}
void OHOSApplication::CleanAbilityStage(const sptr<IRemoteObject> &token,
const std::shared_ptr<AbilityInfo> &abilityInfo)
{
if (abilityInfo == nullptr) {
APP_LOGE("CleanAbilityStage:abilityInfo is nullptr");
return;
}
if (token == nullptr) {
APP_LOGE("CleanAbilityStage:token is nullptr");
return;
}
std::string moduleName = abilityInfo->moduleName;
auto iterator = abilityStages_.find(moduleName);
if (iterator != abilityStages_.end()) {
auto abilityStage = iterator->second;
abilityStage->RemoveAbility(token);
if (!abilityStage->ContainsAbility()) {
abilityStage->OnDestory();
abilityStages_.erase(moduleName);
}
}
}
std::shared_ptr<AbilityRuntime::Context> OHOSApplication::GetAppContext() const
{
return abilityRuntimeContext_;
}
const std::unique_ptr<AbilityRuntime::Runtime>& OHOSApplication::GetRuntime()
{
return runtime_;
}
} // namespace AppExecFwk
} // namespace OHOS

View File

@ -17,8 +17,8 @@
#include "app_log_wrapper.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "string_ex.h"
namespace OHOS {

View File

@ -22,6 +22,7 @@ ABILITY_INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content",
@ -109,6 +110,8 @@ ohos_unittest("application_test") {
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"unittest/application_test.cpp",
"unittest/ability_stage_test.cpp",
"unittest/context_impl_test.cpp",
]
configs = [ ":module_private_config" ]
@ -119,6 +122,8 @@ ohos_unittest("application_test") {
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/kits:app_context",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
@ -132,6 +137,7 @@ ohos_unittest("application_test") {
]
external_deps = [
"aafwk_standard:runtime",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
@ -164,6 +170,7 @@ ohos_unittest("context_container_test") {
]
external_deps = [
"aafwk_standard:runtime",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
@ -250,6 +257,7 @@ ohos_unittest("context_deal_test") {
]
external_deps = [
"aafwk_standard:runtime",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
@ -285,6 +293,7 @@ ohos_unittest("application_impl_test") {
]
external_deps = [
"aafwk_standard:runtime",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]

View File

@ -18,14 +18,14 @@
#include <mutex>
#include "ability_connect_callback_interface.h"
#include "ability_context.h"
#include "ability_manager_client.h"
#include "ability_manager_errors.h"
#include "ability_manager_interface.h"
#include "ability_scheduler_interface.h"
#include "iremote_object.h"
#include "iremote_stub.h"
#include "ability_connect_callback_interface.h"
#include "ability_manager_errors.h"
#include "ability_scheduler_interface.h"
#include "ability_manager_interface.h"
#include "ability_manager_client.h"
#include "ability_context.h"
#include "want.h"
namespace OHOS {
@ -199,7 +199,7 @@ public:
{
return true;
};
virtual bool CleanBundleDataFiles(const std::string &bundleName)
virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0)
{
return true;
};

View File

@ -0,0 +1,211 @@
/*
* 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 <gtest/gtest.h>
#include <singleton.h>
#include "ability_local_record.h"
#include "ability_stage.h"
#include "context.h"
#include "context_impl.h"
#include "iremote_object.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class AbilityStageTest : public testing::Test {
public:
AbilityStageTest() : abilityStage_(nullptr)
{}
~AbilityStageTest()
{}
std::shared_ptr<AbilityRuntime::AbilityStage> abilityStage_ = nullptr;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class MockToken : public OHOS::IRemoteObject {
public:
int32_t GetObjectRefCount() override
{
return 0;
}
int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override
{
return 0;
}
bool AddDeathRecipient(const sptr<DeathRecipient> &recipient) override
{
return true;
}
bool RemoveDeathRecipient(const sptr<DeathRecipient> &recipient) override
{
return true;
}
int Dump(int fd, const std::vector<std::u16string> &args) override
{
return 0;
}
};
void AbilityStageTest::SetUpTestCase(void)
{}
void AbilityStageTest::TearDownTestCase(void)
{}
void AbilityStageTest::SetUp(void)
{
abilityStage_ = std::make_shared<AbilityRuntime::AbilityStage>();
}
void AbilityStageTest::TearDown(void)
{}
/**
* @tc.number: AppExecFwk_AbilityStage_GetContext_001
* @tc.name: GetContext
* @tc.desc: Test whether getContext is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_GetContext_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_001 start";
std::shared_ptr<AbilityRuntime::Context> context = abilityStage_->GetContext();
EXPECT_EQ(context, nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_001 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_GetContext_002
* @tc.name: GetContext
* @tc.desc: Test whether getContext is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ71I
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_GetContext_002, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_002 start";
std::shared_ptr<AbilityRuntime::Context> context = std::make_shared<AbilityRuntime::ContextImpl>();
abilityStage_->Init(context);
EXPECT_NE(abilityStage_->GetContext(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_002 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_AddAbility_001
* @tc.name: AddAbility
* @tc.desc: Test whether AddAbility is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ719
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_001, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_001 start";
EXPECT_FALSE(abilityStage_->ContainsAbility());
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_001 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_AddAbility_002
* @tc.name: AddAbility
* @tc.desc: Test whether AddAbility is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ719
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_002, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 start";
sptr<IRemoteObject> token = new MockToken();
abilityStage_->AddAbility(token, std::make_shared<AppExecFwk::AbilityLocalRecord>(nullptr, nullptr));
EXPECT_TRUE(abilityStage_->ContainsAbility());
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_RemoveAbility_001
* @tc.name: RemoveAbility
* @tc.desc: Test whether RemoveAbility is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ719
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RemoveAbility_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_001 start";
EXPECT_FALSE(abilityStage_->ContainsAbility());
abilityStage_->RemoveAbility(nullptr);
EXPECT_FALSE(abilityStage_->ContainsAbility());
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_001 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_RemoveAbility_002
* @tc.name: RemoveAbility
* @tc.desc: Test whether RemoveAbility is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ719
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RemoveAbility_002, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_002 start";
sptr<IRemoteObject> token = new MockToken();
abilityStage_->AddAbility(token, std::make_shared<AppExecFwk::AbilityLocalRecord>(nullptr, nullptr));
EXPECT_TRUE(abilityStage_->ContainsAbility());
abilityStage_->RemoveAbility(token);
EXPECT_FALSE(abilityStage_->ContainsAbility());
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_002 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_ContainsAbility_001
* @tc.name: ContainsAbility
* @tc.desc: Test whether ContainsAbility is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ719
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_ContainsAbility_001, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_001 start";
EXPECT_FALSE(abilityStage_->ContainsAbility());
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_001 end";
}
/**
* @tc.number: AppExecFwk_AbilityStage_ContainsAbility_002
* @tc.name: ContainsAbility
* @tc.desc: Test whether ContainsAbility is called normally.
* @tc.type: FUNC
* @tc.require: AR000GJ719
*/
HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_ContainsAbility_002, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_002 start";
sptr<IRemoteObject> token = new MockToken();
abilityStage_->AddAbility(token, std::make_shared<AppExecFwk::AbilityLocalRecord>(nullptr, nullptr));
EXPECT_TRUE(abilityStage_->ContainsAbility());
GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_002 end";
}
} // namespace AppExecFwk
}

View File

@ -17,8 +17,8 @@
#include <singleton.h>
#include "application_context.h"
#include "event_runner.h"
#include "context_deal.h"
#include "event_runner.h"
namespace OHOS {

View File

@ -13,15 +13,15 @@
* limitations under the License.
*/
#include <singleton.h>
#include <gtest/gtest.h>
#include "gmock/gmock.h"
#include <gtest/gtest.h>
#include <singleton.h>
#include "context_deal.h"
#include "ohos_application.h"
#include "ability_handler.h"
#include "ability_info.h"
#include "ability.h"
#include "context_deal.h"
#include "ohos_application.h"
#include "mock_ability_manager_client_interface1.h"
#include "mock_resourceManager_interface1.h"

View File

@ -0,0 +1,164 @@
/*
* 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 <gtest/gtest.h>
#include <singleton.h>
#include "ability_local_record.h"
#include "context_impl.h"
#include "context.h"
#include "iremote_object.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class ContextImplTest : public testing::Test {
public:
ContextImplTest() : contextImpl_(nullptr)
{}
~ContextImplTest()
{}
std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl_ = nullptr;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void ContextImplTest::SetUpTestCase(void)
{}
void ContextImplTest::TearDownTestCase(void)
{}
void ContextImplTest::SetUp(void)
{
contextImpl_ = std::make_shared<AbilityRuntime::ContextImpl>();
}
void ContextImplTest::TearDown(void)
{}
/**
* @tc.number: AppExecFwk_ContextImpl_GetBundleName_001
* @tc.name: GetBundleName
* @tc.desc: Test whether GetBundleName is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_001 start";
std::string bundleName = contextImpl_->GetBundleName();
EXPECT_STREQ(bundleName.c_str(), "");
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_001 end";
}
/**
* @tc.number: AppExecFwk_ContextImpl_GetBundleName_002
* @tc.name: GetBundleName
* @tc.desc: Test whether GetBundleName is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_002, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 start";
std::shared_ptr<AppExecFwk::ApplicationInfo> applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
applicationInfo->bundleName = "com.test";
contextImpl_->SetApplicationInfo(applicationInfo);
std::string bundleName = contextImpl_->GetBundleName();
EXPECT_STREQ(bundleName.c_str(), "com.test");
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 end";
}
/**
* @tc.number: AppExecFwk_ContextImpl_SetApplicationInfo_001
* @tc.name: SetApplicationInfo
* @tc.desc: Test whether SetApplicationInfo is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetApplicationInfo_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 start";
std::shared_ptr<AppExecFwk::ApplicationInfo> applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
contextImpl_->SetApplicationInfo(applicationInfo);
EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 end";
}
/**
* @tc.number: AppExecFwk_ContextImpl_GetApplicationInfo_001
* @tc.name: GetApplicationInfo
* @tc.desc: Test whether GetApplicationInfo is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationInfo_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 start";
EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 end";
}
/**
* @tc.number: AppExecFwk_ContextImpl_GetApplicationContext_001
* @tc.name: GetApplicationContext
* @tc.desc: Test whether GetApplicationContext is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationContext_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 start";
EXPECT_EQ(contextImpl_->GetApplicationContext(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 end";
}
/**
* @tc.number: AppExecFwk_ContextImpl_SetParentContext_001
* @tc.name: SetParentContext
* @tc.desc: Test whether SetParentContext is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetParentContext_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 start";
std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl_ = std::make_shared<AbilityRuntime::ContextImpl>();
contextImpl_->SetParentContext(contextImpl_);
EXPECT_NE(contextImpl_->GetApplicationContext(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 end";
}
/**
* @tc.number: AppExecFwk_ContextImpl_GetHapModuleInfo_001
* @tc.name: GetHapModuleInfo
* @tc.desc: Test whether GetHapModuleInfo is called normally.
* @tc.type: FUNC
* @tc.require: SR000GH1HL
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetHapModuleInfo_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetHapModuleInfo_001 start";
EXPECT_EQ(contextImpl_->GetHapModuleInfo(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetHapModuleInfo_001 end";
}
} // namespace AppExecFwk
}

View File

@ -78,6 +78,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_first") {
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"bytrace_standard:bytrace_core",
]
}
@ -117,6 +118,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_second") {
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"bytrace_standard:bytrace_core",
]
}
@ -156,6 +158,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_third") {
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"bytrace_standard:bytrace_core",
]
}
@ -195,6 +198,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_fourth") {
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"bytrace_standard:bytrace_core",
]
}

View File

@ -63,6 +63,7 @@ public:
}
MOCK_METHOD2(GetBundleInfosByMetaData, bool(const std::string &metaData, std::vector<BundleInfo> &bundleInfos));
MOCK_METHOD2(QueryAbilityInfo, bool(const Want &want, AbilityInfo &abilityInfo));
MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector<AbilityInfo> &abilityInfos));
MOCK_METHOD2(QueryAbilityInfoByUri, bool(const std::string &abilityUri, AbilityInfo &abilityInfo));
MOCK_METHOD1(QueryKeepAliveBundleInfos, bool(std::vector<BundleInfo> &bundleInfos));
MOCK_METHOD2(GetAbilityLabel, std::string(const std::string &bundleName, const std::string &className));

View File

@ -15,13 +15,13 @@
#include <gtest/gtest.h>
#include "main_thread.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
#include "mock_ability_mgr_service.h"
#include "mock_ability_token.h"
#include "mock_app_mgr_service.h"
#include "mock_app_thread.h"
#include "mock_ability_token.h"
#include "mock_ability_mgr_service.h"
#include "mock_bundle_mgr_service.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -15,13 +15,13 @@
#include <gtest/gtest.h>
#include "main_thread.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
#include "mock_ability_mgr_service.h"
#include "mock_ability_token.h"
#include "mock_app_mgr_service.h"
#include "mock_app_thread.h"
#include "mock_ability_token.h"
#include "mock_ability_mgr_service.h"
#include "mock_bundle_mgr_service.h"
#include "sys_mgr_client.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -20,6 +20,7 @@ config("libeventhandler_config") {
"//utils/native/base/include",
"src",
"//base/hiviewdfx/interfaces/innerkits/libhilog/include",
"//base/hiviewdfx/interfaces/innerkits/libhitrace/include",
]
}

View File

@ -19,8 +19,8 @@
#include <atomic>
#include <mutex>
#include "nocopyable.h"
#include "io_waiter.h"
#include "nocopyable.h"
namespace OHOS {
namespace AppExecFwk {

View File

@ -69,6 +69,13 @@ bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Prio
}
event->SetOwner(shared_from_this());
// get traceId from event, if HiTrace::begin has been called, would get a valid trace id.
auto traceId = event->GetOrCreateTraceId();
// if traceId is valid, out put trace information
if (AllowHiTraceOutPut(traceId, event->HasWaiter())) {
HiTracePointerOutPut(traceId, event, "Send", HiTraceTracepointType::HITRACE_TP_CS);
}
eventRunner_->GetEventQueue()->Insert(event, priority);
return true;
}
@ -104,6 +111,10 @@ bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority)
DistributeEvent(event);
return true;
}
// get traceId from event, if HiTrace::begin has been called, would get a valid trace id.
auto spanId = event->GetOrCreateTraceId();
// Create waiter, used to block.
auto waiter = event->CreateWaiter();
// Send this event as normal one.
@ -113,6 +124,10 @@ bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority)
// Wait until event is processed(recycled).
waiter->Wait();
if ((spanId) && (spanId->IsValid())) {
HiTrace::Tracepoint(HiTraceTracepointType::HITRACE_TP_CR, *spanId, "event is processed");
}
return true;
}
@ -231,6 +246,15 @@ void EventHandler::DistributeEvent(const InnerEvent::Pointer &event)
std::weak_ptr<EventHandler> oldHandler = currentEventHandler;
// Save current event handler into thread local data.
currentEventHandler = shared_from_this();
auto spanId = event->GetTraceId();
auto traceId = HiTrace::GetId();
bool allowTraceOutPut = AllowHiTraceOutPut(spanId, event->HasWaiter());
if (allowTraceOutPut) {
HiTrace::SetId(*spanId);
HiTracePointerOutPut(spanId, event, "Receive", HiTraceTracepointType::HITRACE_TP_SR);
}
if (event->HasTask()) {
// Call task callback directly if contains a task.
(event->GetTaskCallback())();
@ -238,6 +262,15 @@ void EventHandler::DistributeEvent(const InnerEvent::Pointer &event)
// Otherwise let developers to handle it.
ProcessEvent(event);
}
if (allowTraceOutPut) {
HiTrace::Tracepoint(HiTraceTracepointType::HITRACE_TP_SS, *spanId, "Event Distribute over");
HiTrace::ClearId();
if (traceId.IsValid()) {
HiTrace::SetId(traceId);
}
}
// Restore current event handler.
if (oldHandler.expired()) {
currentEventHandler = nullptr;

View File

@ -22,6 +22,7 @@
#include <string>
#include "hilog/log.h"
#include "hitrace/trace.h"
#include "inner_event.h"
#define DEFINE_HILOG_LABEL(name) static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = {LOG_CORE, LOG_DOMAIN, name}
@ -63,6 +64,31 @@ static inline int32_t NanosecondsToTimeout(int64_t nanoseconds)
return (milliseconds > INT32_MAX) ? INT32_MAX : static_cast<int32_t>(milliseconds);
}
using HiTrace = OHOS::HiviewDFX::HiTrace;
static inline bool AllowHiTraceOutPut(const std::shared_ptr<HiTraceId>& traceId, bool isSyncEvent)
{
if ((!traceId) || (!traceId->IsValid())) {
return false;
}
if ((!isSyncEvent) && (!traceId->IsFlagEnabled(HITRACE_FLAG_INCLUDE_ASYNC))) {
return false;
}
return true;
}
static inline void HiTracePointerOutPut(const std::shared_ptr<HiTraceId>& spanId,
const InnerEvent::Pointer& event, const char* action, HiTraceTracepointType type)
{
if (!event->HasTask()) {
HiTrace::Tracepoint(type, *spanId, "%s event, event id: %d", action, event->GetInnerEventId());
} else if (!event->GetTaskName().empty()) {
HiTrace::Tracepoint(type, *spanId, "%s task with name, name: %s", action, event->GetTaskName().c_str());
} else {
HiTrace::Tracepoint(type, *spanId, "%s UnNamed Task", action);
}
}
static inline char *GetLastErr()
{
return strerror(errno);

View File

@ -27,8 +27,8 @@
#include "event_handler.h"
#include "event_handler_utils.h"
#include "event_inner_runner.h"
#include "thread_local_data.h"
#include "singleton.h"
#include "thread_local_data.h"
DEFINE_HILOG_LABEL("EventRunner");

Some files were not shown because too many files have changed in this diff Show More