回退 'Pull Request !3058 : del unused code'

This commit is contained in:
openharmony_ci 2022-11-24 06:23:33 +00:00 committed by Gitee
parent 83b8a436ec
commit ee5306074c
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
74 changed files with 6122 additions and 4 deletions

View File

@ -16,7 +16,12 @@ import("//foundation/graphic/graphic_2d/utils/wmlayout/wmlayout.gni")
import("graphic_config.gni") import("graphic_config.gni")
group("default") { group("default") {
public_deps = [ ":graphic.rc" ] public_deps = [
":graphic.rc",
"frameworks/dumper:gdumper",
"frameworks/dumper:gdumper.ini",
"frameworks/dumper:graphic_dumper_server",
]
if (graphic_standard_feature_bootanimation_enable) { if (graphic_standard_feature_bootanimation_enable) {
public_deps += [ "frameworks/bootanimation:bootanimation" ] public_deps += [ "frameworks/bootanimation:bootanimation" ]
@ -64,6 +69,10 @@ group("libgl") {
public_deps = libgl public_deps = libgl
} }
group("libgraphic_dumper_client") {
public_deps = [ "frameworks/dumper:libgraphic_dumper_client" ]
}
group("libnative_image") { group("libnative_image") {
public_deps = [ "frameworks/surfaceimage:libnative_image" ] public_deps = [ "frameworks/surfaceimage:libnative_image" ]
} }

View File

@ -0,0 +1,156 @@
/*
* 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 "animation_module.h"
#include <cerrno>
#include <gslogger.h>
#include <scoped_bytrace.h>
#include <securec.h>
namespace OHOS {
namespace {
DEFINE_HILOG_LABEL("AnimationModule");
} // namespace
GSError AnimationModule::Init()
{
handler = AppExecFwk::EventHandler::Current();
vhelper = VsyncHelper::Current();
auto wm = WindowManager::GetInstance();
auto option = WindowOption::Get();
option->SetWindowType(WINDOW_TYPE_ANIMATION);
auto wret = wm->CreateWindow(window, option);
if (wret != GSERROR_OK || window == nullptr) {
GSLOG2HI(ERROR) << "WindowManager::CreateWindow failed: " << GSErrorStr(wret);
return wret;
}
window->Hide();
auto producer = window->GetProducer();
return GSERROR_OK;
}
GSError AnimationModule::StartRotationAnimation(int32_t did, int32_t degree)
{
if (isAnimationRunning == false) {
struct Animation animation {
.degree = degree,
.retval = new Promise<GSError>(),
};
handler->PostTask(std::bind(&AnimationModule::StartAnimation, this, std::ref(animation)));
return animation.retval->Await();
}
return GSERROR_ANIMATION_RUNNING;
}
void AnimationModule::OnScreenShot(const struct WMImageInfo &info)
{
int32_t length = info.size;
struct AnimationScreenshotInfo ainfo = {
.wmimage = info,
.ptr = nullptr,
};
if (info.wret != GSERROR_OK) {
screenshotPromise->Resolve(ainfo);
return;
}
ainfo.ptr = std::make_shared<struct Array>();
ainfo.ptr->ptr = std::make_unique<uint8_t[]>(length);
ainfo.wmimage.data = ainfo.ptr.get();
if (memcpy_s(ainfo.ptr->ptr.get(), length, info.data, info.size) != EOK) {
GSLOG2HI(ERROR) << "memcpy_s failed: " << strerror(errno);
ainfo.wmimage.wret = static_cast<enum GSError>(GSERROR_INTERNAL);
screenshotPromise->Resolve(ainfo);
return;
}
screenshotPromise->Resolve(ainfo);
}
void AnimationModule::StartAnimation(struct Animation &animation)
{
if (isAnimationRunning) {
animation.retval->Resolve(GSERROR_ANIMATION_RUNNING);
return;
}
ScopedBytrace trace(__func__);
isAnimationRunning = true;
GSLOG2HI(INFO) << "Animation Start";
window->Hide();
auto wm = WindowManager::GetInstance();
screenshotPromise = new Promise<struct AnimationScreenshotInfo>();
wm->ListenNextScreenShot(0, this);
auto asinfo = screenshotPromise->Await();
if (asinfo.wmimage.wret) {
GSLOG2HI(ERROR) << "OnScreenShot failed: " << GSErrorStr(asinfo.wmimage.wret);
animation.retval->Resolve(static_cast<enum GSError>(asinfo.wmimage.wret));
isAnimationRunning = false;
return;
}
window->Show();
auto sret = eglSurface->InitContext();
if (sret != GSERROR_OK) {
GSLOG2HI(ERROR) << "EGLSurface InitContext failed: " << sret;
animation.retval->Resolve(static_cast<enum GSError>(sret));
isAnimationRunning = false;
return;
}
ranimation = std::make_unique<RotationAnimation>();
constexpr int32_t rotationAnimationDuration = 500;
auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
struct RotationAnimationParam param = {
.data = asinfo.ptr,
.width = window->GetWidth(),
.height = window->GetHeight(),
.startTime = now,
.duration = rotationAnimationDuration,
.degree = animation.degree,
};
auto gret = ranimation->Init(param);
if (gret != GSERROR_OK) {
GSLOG2HI(ERROR) << "RotationAnimation Init failed: " << GSErrorStr(gret);
animation.retval->Resolve(gret);
isAnimationRunning = false;
return;
}
struct FrameCallback cb = { .callback_ = std::bind(&AnimationModule::AnimationSync, this, SYNC_FUNC_ARG) };
animation.retval->Resolve(static_cast<enum GSError>(vhelper->RequestFrameCallback(cb)));
}
void AnimationModule::AnimationSync(int64_t time, void *data)
{
ScopedBytrace trace(__func__);
if (ranimation->Draw()) {
eglSurface->SwapBuffers();
struct FrameCallback cb = { .callback_ = std::bind(&AnimationModule::AnimationSync, this, SYNC_FUNC_ARG) };
vhelper->RequestFrameCallback(cb);
trace.End();
} else {
trace.End();
GSLOG2HI(INFO) << "Animation End";
window->Hide();
isAnimationRunning = false;
}
}
} // namespace OHOS

176
frameworks/dumper/BUILD.gn Executable file
View File

@ -0,0 +1,176 @@
# 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")
## Build libgraphic_dumper_client.so {{{
config("graphic_dumper_client_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("graphic_dumper_client_public_config") {
include_dirs = [ "common" ]
}
ohos_shared_library("libgraphic_dumper_client") {
sources = [
"src/graphic_dumper_helper.cpp",
"src/graphic_dumper_helper_impl.cpp",
"src/ipc/graphic_dumper_client_listener_stub.cpp",
"src/ipc/graphic_dumper_service_proxy.cpp",
]
configs = [ ":graphic_dumper_client_config" ]
public_configs = [ ":graphic_dumper_client_public_config" ]
deps = [ "//foundation/graphic/graphic_2d/utils:libgraphic_utils" ]
external_deps = [
"c_utils:utils",
"hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Build libgraphic_dumper_client.so }}}
## Build graphic_dumper_server {{{
config("graphic_dumper_server_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
ohos_executable("graphic_dumper_server") {
install_enable = true
sources = [
"src/graphic_dumper_server.cpp",
"src/graphic_dumper_server_main.cpp",
"src/graphic_dumper_tree.cpp",
"src/graphic_dumper_util.cpp",
"src/ipc/graphic_dumper_client_listener_death_recipient.cpp",
"src/ipc/graphic_dumper_client_listener_proxy.cpp",
"src/ipc/graphic_dumper_command_proxy.cpp",
"src/ipc/graphic_dumper_command_stub.cpp",
"src/ipc/graphic_dumper_info_listener_death_recipient.cpp",
"src/ipc/graphic_dumper_info_listener_proxy.cpp",
"src/ipc/graphic_dumper_service_proxy.cpp",
"src/ipc/graphic_dumper_service_stub.cpp",
]
configs = [
":graphic_dumper_server_config",
":graphic_dumper_client_public_config",
]
deps = [
"//foundation/graphic/graphic_2d/utils:libgraphic_utils",
"//third_party/zlib:libz",
]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Build graphic_dumper_server }}}
## Build gdumper {{{
config("gdumper_config") {
visibility = [ ":*" ]
include_dirs = [ "include" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
ohos_executable("gdumper") {
install_enable = true
sources = [
"src/graphic_dumper_command_line.cpp",
"src/graphic_dumper_command_line_main.cpp",
"src/graphic_dumper_server.cpp",
"src/graphic_dumper_tree.cpp",
"src/graphic_dumper_util.cpp",
"src/ipc/graphic_dumper_client_listener_death_recipient.cpp",
"src/ipc/graphic_dumper_command_proxy.cpp",
"src/ipc/graphic_dumper_command_stub.cpp",
"src/ipc/graphic_dumper_info_listener_death_recipient.cpp",
"src/ipc/graphic_dumper_info_listener_proxy.cpp",
"src/ipc/graphic_dumper_info_listener_stub.cpp",
"src/ipc/graphic_dumper_service_proxy.cpp",
"src/ipc/graphic_dumper_service_stub.cpp",
]
configs = [
":gdumper_config",
":graphic_dumper_client_public_config",
]
deps = [
"//foundation/graphic/graphic_2d/utils:libgraphic_utils",
"//third_party/zlib:libz",
]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Build gdumper }}}
## Install gdumper.ini to /system/etc/./gdumper.ini {{{
ohos_prebuilt_etc("gdumper.ini") {
source = "gdumper.ini"
relative_install_dir = "."
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Install gdumper.ini to /system/etc/./gdumper.ini }}}

View File

@ -0,0 +1,55 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_HELPER_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_HELPER_H
#include "graphic_common.h"
#ifdef __cplusplus
#include <refbase.h>
namespace OHOS {
using OnConfigChangeFunc = std::function<void(const std::string &, const std::string &)>;
using OnDumpFunc = std::function<void()>;
class GraphicDumperHelper : public RefBase {
public:
static sptr<GraphicDumperHelper> GetInstance();
virtual GSError SendInfo(const std::string &tag, const char *fmt, ...) = 0;
virtual int32_t AddConfigChangeListener(const std::string &tag, OnConfigChangeFunc func) = 0;
virtual GSError RemoveConfigChangeListener(const int32_t listenerId) = 0;
virtual int32_t AddDumpListener(const std::string &tag, OnDumpFunc func) = 0;
virtual GSError RemoveDumpListener(const int32_t listenerId) = 0;
};
} // namespace OHOS
extern "C" {
#endif
typedef void(*OnDumpFuncPtr)(void);
typedef void(*OnConfigChangeFuncPtr)(const char *, const char *);
int SendInfo(const char* tag, const char *fmt, ...);
int AddConfigChangeListener(const char* tag, OnConfigChangeFuncPtr func);
int RemoveConfigChangeListener(int listenerId);
int AddDumpListener(const char* tag, OnDumpFuncPtr func);
int RemoveDumpListener(int listenerId);
#ifdef __cplusplus
}
#endif
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_HELPER_H

View File

@ -0,0 +1,15 @@
# 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.
# [dumper]
# A.B=true

View File

@ -0,0 +1,63 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_LINE_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_LINE_H
#include <promise.h>
#include <string>
#include "ipc/graphic_dumper_info_listener_stub.h"
#include "ipc/igraphic_dumper_command.h"
namespace OHOS {
struct DumperArgs {
bool wait = false;
std::string dumpTag = {};
std::string logTag = {};
std::string getCfgKey = {};
std::string setCfgKey = {};
std::string setCfgValue = {};
};
class GraphicDumperCommandLine : public GraphicDumperInfoListenerStub {
public:
static sptr<GraphicDumperCommandLine> GetInstance();
virtual void OnInfoComing(const std::string &info) override;
GSError Main(int32_t argc, char *argv[]);
private:
GraphicDumperCommandLine() = default;
~GraphicDumperCommandLine() = default;
static inline sptr<GraphicDumperCommandLine> instance_;
void HandlerOfArgs();
GSError OptionParse(const char option);
GSError Parse(int32_t argc, char *argv[]);
GSError InitSA(int32_t systemAbilityId);
sptr<IGraphicDumperCommand> service_;
DumperArgs dumperArgs_ = {};
};
class GDumperCommandDeathRecipient : public IRemoteObject::DeathRecipient {
public:
GDumperCommandDeathRecipient() = default;
virtual ~GDumperCommandDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_LINE_H

View File

@ -0,0 +1,131 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_HELPER_IMPL_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_HELPER_IMPL_H
#include <atomic>
#include <mutex>
#include <string>
#include <map>
#include <memory>
#include "ipc/graphic_dumper_service_proxy.h"
#include "ipc/graphic_dumper_client_listener_stub.h"
#include "graphic_dumper_helper.h"
namespace OHOS {
namespace {
class GraphicDumperClientListener;
}
using ConfigFuncMapPtr = std::unique_ptr<std::map<int32_t, OnConfigChangeFunc>>;
using DumpFuncMapPtr = std::unique_ptr<std::map<int32_t, OnDumpFunc>>;
class GraphicDumperHelperImpl : public GraphicDumperHelper {
friend class GraphicDumperClientListener;
public:
static sptr<GraphicDumperHelper> GetInstance();
virtual GSError SendInfo(const std::string &tag, const char *fmt, ...) override;
virtual int32_t AddConfigChangeListener(const std::string &tag, OnConfigChangeFunc func) override;
virtual GSError RemoveConfigChangeListener(const int32_t listenerId) override;
virtual int32_t AddDumpListener(const std::string &tag, OnDumpFunc func) override;
virtual GSError RemoveDumpListener(const int32_t listenerId) override;
void SetConnectState(bool state);
private:
virtual ~GraphicDumperHelperImpl() = default;
static inline sptr<GraphicDumperHelper> currentHelper = nullptr;
static void SetNoopInstance();
GSError Init();
GSError InitSA(int32_t systemAbilityId);
GSError AddClientListener(const std::string &tag);
void DispenseOnConfigChange(const std::string &tag, const std::string &val);
void DispenseOnDump(const std::string &tag);
std::mutex initMutex_;
std::atomic_int64_t requestConnectTime = 0;
std::atomic_bool serverConnected = false;
sptr<IGraphicDumperService> service_ = nullptr;
std::mutex clientListenerMutex_;
sptr<IGraphicDumperClientListener> listener_ = nullptr;
int32_t onConfigChangeFuncId_ = 0;
std::mutex onConfigChangeMutex_;
std::map<std::string, ConfigFuncMapPtr> onConfigChangeMap_;
int32_t onDumperFuncId_ = 0;
std::mutex onDumperFuncsMutex_;
std::map<std::string, DumpFuncMapPtr> onDumpFuncsMap_;
struct InfoStruct {
std::string tag;
std::string info;
};
std::mutex cacheInfoMutex_;
std::vector<InfoStruct> cacheInfo_;
};
class GDumperServiceDeathRecipient : public IRemoteObject::DeathRecipient {
public:
GDumperServiceDeathRecipient() = default;
virtual ~GDumperServiceDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
};
class GraphicDumperHelperNoop : public GraphicDumperHelper {
public:
virtual GSError SendInfo(const std::string &tag, const char *fmt, ...)
{
return GSERROR_CONNOT_CONNECT_SERVER;
}
virtual int32_t AddConfigChangeListener(const std::string &tag, OnConfigChangeFunc func)
{
return 0;
}
virtual GSError RemoveConfigChangeListener(const int32_t listenerId)
{
return GSERROR_CONNOT_CONNECT_SERVER;
}
virtual int32_t AddDumpListener(const std::string &tag, OnDumpFunc func)
{
return 0;
}
virtual GSError RemoveDumpListener(const int32_t listenerId)
{
return GSERROR_CONNOT_CONNECT_SERVER;
}
};
namespace {
class GraphicDumperClientListener : public GraphicDumperClientListenerStub {
public:
GraphicDumperClientListener(sptr<GraphicDumperHelperImpl>& helper);
virtual ~GraphicDumperClientListener() = default;
void OnConfigChange(const std::string &tag, const std::string &val) override;
void OnDump(const std::string &tag) override;
private:
sptr<GraphicDumperHelperImpl> helperImpl_ = nullptr;
};
} // namespace
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_HELPER_IMPL_H

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.
*/
#ifndef FRAMEWORKS_DUMPER_INCLUDE_GRAPHIC_DUMPER_HILOG_H
#define FRAMEWORKS_DUMPER_INCLUDE_GRAPHIC_DUMPER_HILOG_H
#include "hilog/log.h"
namespace OHOS {
#define GD_CPRINTF(func, fmt, ...) func(LABEL, "<%{public}d>" fmt, __LINE__, ##__VA_ARGS__)
#define GDLOGD(fmt, ...) GD_CPRINTF(HiviewDFX::HiLog::Debug, fmt, ##__VA_ARGS__)
#define GDLOGI(fmt, ...) GD_CPRINTF(HiviewDFX::HiLog::Info, fmt, ##__VA_ARGS__)
#define GDLOGW(fmt, ...) GD_CPRINTF(HiviewDFX::HiLog::Warn, fmt, ##__VA_ARGS__)
#define GDLOGE(fmt, ...) GD_CPRINTF(HiviewDFX::HiLog::Error, fmt, ##__VA_ARGS__)
#define GDLOGFD(fmt, ...) GDLOGD("%{public}s: " fmt, __func__, ##__VA_ARGS__)
#define GDLOGFI(fmt, ...) GDLOGI("%{public}s: " fmt, __func__, ##__VA_ARGS__)
#define GDLOGFW(fmt, ...) GDLOGW("%{public}s: " fmt, __func__, ##__VA_ARGS__)
#define GDLOGFE(fmt, ...) GDLOGE("%{public}s: " fmt, __func__, ##__VA_ARGS__)
#define GDLOG_SUCCESS(fmt, ...) GDLOGI("Success, Way: " fmt, ##__VA_ARGS__)
#define GDLOG_FAILURE(fmt, ...) GDLOGE("Failure, Reason: " fmt, ##__VA_ARGS__)
#define GDLOG_FAILURE_NO(gs_error) GDLOG_FAILURE("%{public}s", GSErrorStr(gs_error).c_str())
#define GDLOG_FAILURE_RET(gs_error) \
do { \
GDLOG_FAILURE_NO(gs_error); \
return gs_error; \
} while (0)
#define GDLOG_FAILURE_API(api, ret) GDLOG_FAILURE(#api " failed with %{public}s", GSErrorStr(ret).c_str())
#define GDLOG_ERROR(errno, fmt, ...) \
GDLOGE(fmt ", means %{public}s", ##__VA_ARGS__, strerror(errno))
#define GDLOG_ERROR_API(ret, api) \
GDLOG_ERROR(ret, #api " failed with %{public}d", ret)
} // namespace OHOS
#endif // FRAMEWORKS_DUMPER_INCLUDE_GRAPHIC_DUMPER_HILOG_H

View File

@ -0,0 +1,116 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVER_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVER_H
#include <any>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
#include <string>
#include <thread>
#include <ipc_skeleton.h>
#include <refbase.h>
#include "graphic_dumper_tree.h"
#include "ipc/igraphic_dumper_client_listener.h"
#include "ipc/igraphic_dumper_command.h"
#include "ipc/igraphic_dumper_info_listener.h"
#include "ipc/igraphic_dumper_service.h"
namespace OHOS {
struct LogBuffer {
bool canSave = false;
bool needSave = false;
bool sync = false;
uint32_t index = 0;
uint32_t size[2] = {0};
std::mutex mutex[2];
std::vector<std::unique_ptr<std::vector<std::string>>> vec;
std::string mask = {};
};
struct LogBlock {
uint32_t size;
uint32_t length;
uint8_t data[0];
};
struct ConfigTags {
uint32_t id = 0;
sptr<IGraphicDumperClientListener> listener = nullptr;
std::vector<std::string> tags = {};
};
class GraphicDumperServer : public RefBase {
public:
static sptr<GraphicDumperServer> GetInstance();
int32_t Init();
GSError AddConfigListener(const std::string &tag, sptr<IGraphicDumperClientListener> &listener);
GSError RemoveConfigListener(sptr<IRemoteObject> object);
GSError GetConfig(const std::string &k, std::string &v);
GSError SetConfig(const std::string &k, const std::string &v);
GSError Dump(const std::string &tag);
GSError AddInfoListener(sptr<IGraphicDumperInfoListener> &listener);
GSError RemoveInfoListener(const wptr<IRemoteObject> &object);
GSError InfoHandle(const std::string &tag, const std::string &info);
GSError GetLog(const std::string &tag, const std::string &info);
private:
GraphicDumperServer() = default;
virtual ~GraphicDumperServer() = default;
static inline sptr<GraphicDumperServer> instance_;
int32_t StartServer(int32_t systemAbility, sptr<IRemoteObject> obj);
int32_t ReadDefaultConfig();
void AddConfigDeathRecipient(sptr<IRemoteObject> &object);
bool HaveConfigDeathRecipient(sptr<IRemoteObject> &object);
bool HaveObject(const sptr<IRemoteObject> &obj);
void VisitEach(const TreeNodePtr &node, std::function<void(const TreeNodePtr&)> func);
void RemoveNode(std::vector<std::string> &vec, TreeNodePtr &sub, uint32_t &listenerId);
void DispenseConfig(const TreeNodePtr &node, const std::string &k, const std::string &v);
void DispenseDump(const TreeNodePtr &node, const std::string &tag);
void AddInfoDeathRecipient(sptr<IRemoteObject> &object);
bool HaveInfoDeathRecipient(sptr<IRemoteObject> &object);
void SendToInfoListener(const std::string &info);
static void SaveLog(std::any server);
GSError LogHandle(const std::string &tag, const std::string &info);
private:
std::mutex infoListenersMutex_;
std::map<sptr<IRemoteObject>, sptr<IGraphicDumperInfoListener>> infoListeners_;
std::map<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>> infoListenerDeathRecipientMap_;
uint32_t objectId_ = 0;
std::map<uint32_t, ConfigTags> configTagsMap_;
std::map<sptr<IRemoteObject>, uint32_t> objectIdMap_;
std::mutex treeMutex_;
const TreeNodePtr root = std::make_shared<GraphicDumperTree>();
LogBuffer logBuf_;
uint32_t logBlockSize_ = 0;
std::mutex logBlockVectorMutex_;
std::vector<std::unique_ptr<uint8_t[]>> logBlockVector_;
std::unique_ptr<std::thread> thread_ = nullptr;
std::map<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>> configListenerDeathRecipientMap_;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVER_H

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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_TREE_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_TREE_H
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <refbase.h>
#include "ipc/igraphic_dumper_client_listener.h"
namespace OHOS {
class GraphicDumperTree;
using TreeNodePtr = std::shared_ptr<GraphicDumperTree>;
using TreeNodeVisitFunc = std::function<void(const TreeNodePtr &v)>;
using TreeNodeMap = std::map<const std::string, TreeNodePtr>;
class GraphicDumperTree {
public:
TreeNodePtr GetSetNode(const std::string str);
bool HasNode(const std::string str);
bool IsEmptyNode();
void EraseNode(const std::string &tag);
std::string GetTag();
void SetValue(const std::string str);
std::string GetValue();
void AddListenerId(uint32_t &listenerId);
void RemoveListenerId(uint32_t &listenerId);
std::vector<uint32_t> GetListenerIds() const;
void Foreach(TreeNodeVisitFunc func) const;
private:
std::string tag_ = "";
std::string value_ = "";
std::unique_ptr<TreeNodeMap> nodeMap_ = nullptr;
std::vector<uint32_t> listenerIds_ = {};
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_TREE_H

View File

@ -0,0 +1,28 @@
/*
* 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 FRAMEWORKS_DUMPER_INCLUDE_GRAPHIC_DUMPER_UTIL_H
#define FRAMEWORKS_DUMPER_INCLUDE_GRAPHIC_DUMPER_UTIL_H
#include <string>
#include <vector>
namespace OHOS {
constexpr int32_t CFGTERMSIZE = 2;
std::vector<std::string> Split(std::string src, const std::string &splitStr);
} // namespace OHOS
#endif // FRAMEWORKS_DUMPER_INCLUDE_GRAPHIC_DUMPER_UTIL_H

View File

@ -0,0 +1,37 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_DEATH_RECIPIENT_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_DEATH_RECIPIENT_H
#include <vector>
#include <iremote_stub.h>
#include <iremote_proxy.h>
#include <message_parcel.h>
#include <message_option.h>
#include "ipc/igraphic_dumper_service.h"
namespace OHOS {
class GraphicDumperClientListenerDeathRecipient : public IRemoteObject::DeathRecipient {
public:
GraphicDumperClientListenerDeathRecipient() = default;
virtual ~GraphicDumperClientListenerDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_H

View File

@ -0,0 +1,38 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_PROXY_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_PROXY_H
#include <iremote_object.h>
#include <iremote_proxy.h>
#include "ipc/igraphic_dumper_client_listener.h"
namespace OHOS {
class GraphicDumperClientListenerProxy : public IRemoteProxy<IGraphicDumperClientListener> {
public:
GraphicDumperClientListenerProxy(const sptr<IRemoteObject>& impl);
virtual ~GraphicDumperClientListenerProxy() = default;
void OnConfigChange(const std::string &tag, const std::string &val) override;
void OnDump(const std::string &tag) override;
private:
static inline BrokerDelegator<GraphicDumperClientListenerProxy> delegator_;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_STUB_H

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_STUB_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_STUB_H
#include <iremote_stub.h>
#include <message_parcel.h>
#include <message_option.h>
#include "ipc/igraphic_dumper_client_listener.h"
namespace OHOS {
class GraphicDumperClientListenerStub : public IRemoteStub<IGraphicDumperClientListener> {
public:
virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_CLIENT_LISTENER_STUB_H

View File

@ -0,0 +1,41 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_PROXY_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_PROXY_H
#include <iremote_object.h>
#include <iremote_proxy.h>
#include "ipc/igraphic_dumper_command.h"
namespace OHOS {
class GraphicDumperCommandProxy : public IRemoteProxy<IGraphicDumperCommand> {
public:
GraphicDumperCommandProxy(const sptr<IRemoteObject>& impl);
virtual ~GraphicDumperCommandProxy() = default;
GSError GetConfig(const std::string &k, std::string &v) override;
GSError SetConfig(const std::string &k, const std::string &v) override;
GSError Dump(const std::string &key) override;
GSError GetLog(const std::string &tag, std::string &log) override;
GSError AddInfoListener(const std::string &tag, sptr<IGraphicDumperInfoListener> &listener) override;
private:
static inline BrokerDelegator<GraphicDumperCommandProxy> delegator_;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_STUB_H

View File

@ -0,0 +1,40 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_STUB_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_STUB_H
#include <iremote_stub.h>
#include <message_parcel.h>
#include <message_option.h>
#include "ipc/igraphic_dumper_command.h"
namespace OHOS {
class GraphicDumperCommandStub : public IRemoteStub<IGraphicDumperCommand> {
public:
virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option) override;
virtual GSError GetConfig(const std::string &k, std::string &v) override;
virtual GSError SetConfig(const std::string &k, const std::string &v) override;
using IPCObjectStub::Dump;
virtual GSError Dump(const std::string &tag) override;
virtual GSError GetLog(const std::string &tag, std::string &log) override;
virtual GSError AddInfoListener(const std::string &tag, sptr<IGraphicDumperInfoListener> &listener) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_H

View File

@ -0,0 +1,34 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_DEATH_RECIPIENT_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_DEATH_RECIPIENT_H
#include <iremote_stub.h>
#include <message_parcel.h>
#include <message_option.h>
#include "ipc/igraphic_dumper_command.h"
namespace OHOS {
class GraphicDumperInfoListenerDeathRecipient : public IRemoteObject::DeathRecipient {
public:
GraphicDumperInfoListenerDeathRecipient() = default;
virtual ~GraphicDumperInfoListenerDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_COMMAND_H

View File

@ -0,0 +1,36 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_PROXY_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_PROXY_H
#include <iremote_object.h>
#include <iremote_proxy.h>
#include "ipc/igraphic_dumper_info_listener.h"
namespace OHOS {
class GraphicDumperInfoListenerProxy : public IRemoteProxy<IGraphicDumperInfoListener> {
public:
GraphicDumperInfoListenerProxy(const sptr<IRemoteObject>& impl);
virtual ~GraphicDumperInfoListenerProxy() = default;
void OnInfoComing(const std::string &info) override;
private:
static inline BrokerDelegator<GraphicDumperInfoListenerProxy> delegator_;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_STUB_H

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_STUB_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_STUB_H
#include <iremote_stub.h>
#include <message_parcel.h>
#include <message_option.h>
#include "ipc/igraphic_dumper_info_listener.h"
namespace OHOS {
class GraphicDumperInfoListenerStub : public IRemoteStub<IGraphicDumperInfoListener> {
public:
virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_INFO_LISTENER_STUB_H

View File

@ -0,0 +1,37 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_PROXY_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_PROXY_H
#include <iremote_object.h>
#include <iremote_proxy.h>
#include "ipc/igraphic_dumper_service.h"
namespace OHOS {
class GraphicDumperServiceProxy : public IRemoteProxy<IGraphicDumperService> {
public:
GraphicDumperServiceProxy(const sptr<IRemoteObject>& impl);
virtual ~GraphicDumperServiceProxy() = default;
GSError AddClientListener(const std::string &tag, sptr<IGraphicDumperClientListener> &listener) override;
GSError SendInfo(const std::string &tag, const std::string &info) override;
private:
static inline BrokerDelegator<GraphicDumperServiceProxy> delegator_;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_PROXY_H

View File

@ -0,0 +1,38 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_STUB_H
#define FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_STUB_H
#include <vector>
#include <iremote_stub.h>
#include <iremote_proxy.h>
#include <message_parcel.h>
#include <message_option.h>
#include "ipc/igraphic_dumper_service.h"
namespace OHOS {
class GraphicDumperServiceStub : public IRemoteStub<IGraphicDumperService> {
public:
virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option) override;
GSError AddClientListener(const std::string &tag, sptr<IGraphicDumperClientListener> &listener) override;
GSError SendInfo(const std::string &tag, const std::string &info) override;
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_GRAPHIC_DUMPER_SERVICE_H

View File

@ -0,0 +1,38 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_CLIENT_LISTENER_H
#define FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_CLIENT_LISTENER_H
#include <string>
#include <iremote_broker.h>
namespace OHOS {
class IGraphicDumperClientListener : public IRemoteBroker {
public:
virtual void OnConfigChange(const std::string &tag, const std::string &val) = 0;
virtual void OnDump(const std::string &key) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"IGraphicDumperClientListener");
protected:
enum {
IGRAPHIC_DUMPER_CLIENT_LISTENER_ON_CONFIG_CHANGE,
IGRAPHIC_DUMPER_CLIENT_LISTENER_ON_DUMP,
};
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_CLIENT_LISTENER_H

View File

@ -0,0 +1,48 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_COMMAND_H
#define FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_COMMAND_H
#include <string>
#include <iremote_broker.h>
#include "graphic_common.h"
#include "ipc/igraphic_dumper_info_listener.h"
namespace OHOS {
class IGraphicDumperCommand : public IRemoteBroker {
public:
virtual GSError GetConfig(const std::string &k, std::string &v) = 0;
virtual GSError SetConfig(const std::string &k, const std::string &v) = 0;
virtual GSError Dump(const std::string &tag) = 0;
virtual GSError GetLog(const std::string &tag, std::string &log) = 0;
virtual GSError AddInfoListener(const std::string &tag, sptr<IGraphicDumperInfoListener> &listener) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"IGraphicDumperCommand");
protected:
enum {
IGRAPHIC_DUMPER_COMMAND_GET_CONFIG,
IGRAPHIC_DUMPER_COMMAND_SET_CONFIG,
IGRAPHIC_DUMPER_COMMAND_DUMP,
IGRAPHIC_DUMPER_COMMAND_GET_LOG,
IGRAPHIC_DUMPER_COMMAND_ADD_INFO_LISTENER,
};
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_COMMAND_H

View File

@ -0,0 +1,36 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_INFO_LISTENER_H
#define FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_INFO_LISTENER_H
#include <string>
#include <iremote_broker.h>
namespace OHOS {
class IGraphicDumperInfoListener : public IRemoteBroker {
public:
virtual void OnInfoComing(const std::string &info) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"IGraphicDumperInfoListener");
protected:
enum {
IGRAPHIC_DUMPER_INFO_LISTENER_ON_INFO_COMING,
};
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_INFO_LISTENER_H

View File

@ -0,0 +1,41 @@
/*
* 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 FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_SERVICE_H
#define FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_SERVICE_H
#include <string>
#include <iremote_broker.h>
#include "graphic_common.h"
#include "ipc/igraphic_dumper_client_listener.h"
namespace OHOS {
class IGraphicDumperService : public IRemoteBroker {
public:
virtual GSError AddClientListener(const std::string &tag, sptr<IGraphicDumperClientListener> &listener) = 0;
virtual GSError SendInfo(const std::string &tag, const std::string &info) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"IGraphicDumperService");
protected:
enum {
IGRAPHIC_DUMPER_SERVICE_ADD_CLIENT_LISTENER,
IGRAPHIC_DUMPER_SERVICE_SEND_INFO,
};
};
} // namespace OHOS
#endif // FRAMEWORKS_DUMPRE_INCLUDE_IGRAPHIC_DUMPER_SERVICE_H

View File

@ -0,0 +1,266 @@
/*
* 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 "graphic_dumper_command_line.h"
#include <condition_variable>
#include <csignal>
#include <iostream>
#include <mutex>
#include <vector>
#include <getopt.h>
#include <ipc_skeleton.h>
#include <iservice_registry.h>
#include <system_ability_definition.h>
#include <unistd.h>
#include "graphic_dumper_hilog.h"
#include "graphic_dumper_util.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperCommandLine" };
constexpr int SLEEP_TIME = 5 * 1000;
Promise<int> signalPromise;
static void Helper()
{
std::cerr <<
"Usage: [options]\n"
"options include:\n"
" -h --help show this message.\n"
" -w --wait wait mode; listen for new prints.\n"
" -g <key>, --get <key>\n"
" get config with key.\n"
" -s <key>=<value>, --set <key>=<value>\n"
" set config of key is equal to value.\n"
" -l <tag> --log <tag>\n"
" read log with tag.\n"
" -d <tag> --dump <tag>\n"
" read dump info with tag.\n"
" read all dump info with --all.\n"
<< std::endl;
}
} // namespace
sptr<GraphicDumperCommandLine> GraphicDumperCommandLine::GetInstance()
{
if (instance_ == nullptr) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
if (instance_ == nullptr) {
instance_ = new GraphicDumperCommandLine();
}
}
return instance_;
}
void GraphicDumperCommandLine::OnInfoComing(const std::string &info)
{
std::cerr << info.c_str() << std::endl;
}
void Handler(int signal)
{
switch (signal) {
case SIGINT:
case SIGTERM:
case SIGTSTP:
case SIGQUIT:
case SIGHUP: {
signalPromise.Resolve(signal);
break;
}
default:
break;
}
}
void SignalInit()
{
std::signal(SIGINT, Handler);
std::signal(SIGKILL, Handler);
std::signal(SIGTERM, Handler);
std::signal(SIGTSTP, Handler);
std::signal(SIGQUIT, Handler);
std::signal(SIGHUP, Handler);
}
GSError GraphicDumperCommandLine::Main(int32_t argc, char *argv[])
{
GSError iRet = GSERROR_OK;
if (argc <= 1) {
Helper();
return iRet;
}
iRet = Parse(argc, argv);
if (iRet != GSERROR_OK) {
return iRet;
}
SignalInit();
iRet = InitSA(GRAPHIC_DUMPER_COMMAND_SA_ID);
if (iRet != GSERROR_OK) {
std::cerr << "Init SA failed: " << GSErrorStr(iRet) << std::endl;
return iRet;
}
sptr<IGraphicDumperInfoListener> listener = this;
iRet = service_->AddInfoListener("", listener);
if (iRet != GSERROR_OK) {
std::cerr << "Add info listener failed: " << GSErrorStr(iRet) << std::endl;
return iRet;
}
HandlerOfArgs();
usleep(SLEEP_TIME);
return GSERROR_OK;
}
void GraphicDumperCommandLine::HandlerOfArgs()
{
if (!dumperArgs_.dumpTag.empty()) {
service_->Dump("*#dp#*." + dumperArgs_.dumpTag);
std::cerr << "get dump with tag:" << dumperArgs_.dumpTag.c_str() << std::endl;
}
if (!dumperArgs_.logTag.empty()) {
std::string getLog = {};
std::cerr << "get log with tag:" << dumperArgs_.logTag.c_str() << std::endl;
service_->GetLog(dumperArgs_.logTag, getLog);
std::cerr << "log is" << getLog.c_str() << std::endl;
}
if (!dumperArgs_.getCfgKey.empty()) {
std::string getCfgValue = {};
service_->GetConfig(dumperArgs_.getCfgKey, getCfgValue);
std::cerr << "get cfg with key:" << dumperArgs_.getCfgKey.c_str() << "value is:"
<< getCfgValue.c_str() << std::endl;
}
if ((!dumperArgs_.setCfgKey.empty()) && (!dumperArgs_.setCfgKey.empty())) {
service_->SetConfig(dumperArgs_.setCfgKey, dumperArgs_.setCfgValue);
std::cerr << "set cfg with key:" << dumperArgs_.setCfgKey.c_str() << "value is:"
<< dumperArgs_.setCfgValue.c_str() << std::endl;
}
if (dumperArgs_.wait) {
signalPromise.Await();
}
}
GSError GraphicDumperCommandLine::OptionParse(const char option)
{
switch (option) {
case 'h': {
Helper();
return GSERROR_OK;
}
case 'w': {
dumperArgs_.wait = true;
break;
}
case 'g': {
dumperArgs_.getCfgKey = optarg;
break;
}
case 's': {
auto ret = Split(optarg, "=");
if (ret.size() != CFGTERMSIZE) {
std::cerr << "Parameter format error." << std::endl;
return GSERROR_INVALID_OPERATING;
}
dumperArgs_.setCfgKey = ret[0];
dumperArgs_.setCfgValue = ret[1];
break;
}
case 'l': {
dumperArgs_.logTag = optarg;
break;
}
case 'd': {
dumperArgs_.dumpTag = optarg;
break;
}
default: {
std::cerr << "Command not found." << std::endl;
return GSERROR_INVALID_OPERATING;
}
} // switch
return GSERROR_OK;
}
GSError GraphicDumperCommandLine::Parse(int32_t argc, char *argv[])
{
int optIndex = 0;
static const struct option longOptions[] = {
{ "help", no_argument, nullptr, 'h' },
{ "wait", no_argument, nullptr, 'w' },
{ "log", required_argument, nullptr, 'l' },
{ "dump", required_argument, nullptr, 'd' },
{ "get", required_argument, nullptr, 'g' },
{ "set", required_argument, nullptr, 's' },
{nullptr, 0, nullptr, 0}
};
while (true) {
int opt = getopt_long(argc, argv, "hwg:s:l:d:", longOptions, &optIndex);
if (opt == -1) {
break;
}
auto ret = OptionParse(opt);
if (ret != GSERROR_OK) {
return ret;
}
} // while
return GSERROR_OK;
}
GSError GraphicDumperCommandLine::InitSA(int32_t systemAbilityId)
{
if (service_ != nullptr) {
GDLOG_SUCCESS("_instance != nullptr");
return GSERROR_OK;
}
auto sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sm == nullptr) {
GDLOG_FAILURE_RET(GSERROR_CONNOT_CONNECT_SAMGR);
}
auto remoteObject = sm->GetSystemAbility(systemAbilityId);
if (remoteObject == nullptr) {
GDLOG_FAILURE_RET(GSERROR_CONNOT_CONNECT_SERVER);
}
sptr<IRemoteObject::DeathRecipient> deathRecipient = new GDumperCommandDeathRecipient();
if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient))) {
GDLOGFE("Failed to add death recipient");
}
service_ = iface_cast<IGraphicDumperCommand>(remoteObject);
if (service_ == nullptr) {
GDLOG_FAILURE_RET(GSERROR_PROXY_NOT_INCLUDE);
}
GDLOG_SUCCESS("service_ = iface_cast");
return GSERROR_OK;
}
void GDumperCommandDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
{
GDLOGFE("Command server Died!");
std::raise(SIGQUIT);
}
} // namespace OHOS

View File

@ -0,0 +1,23 @@
/*
* 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 "graphic_dumper_command_line.h"
using namespace OHOS;
int32_t main(int32_t argc, char *argv[])
{
return GraphicDumperCommandLine::GetInstance()->Main(argc, argv);
}

View File

@ -0,0 +1,67 @@
/*
* 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 "graphic_dumper_helper.h"
#include <cstdarg>
#include <securec.h>
#include "graphic_dumper_helper_impl.h"
namespace OHOS {
sptr<GraphicDumperHelper> GraphicDumperHelper::GetInstance()
{
return GraphicDumperHelperImpl::GetInstance();
}
} // namespace OHOS
int SendInfo(const char* tag, const char *fmt, ...)
{
constexpr int infoSize = 4096;
char info[infoSize];
va_list args;
va_start(args, fmt);
int ret = vsnprintf_s(info, sizeof(info), (sizeof(info) - 1), fmt, args);
if (ret < 0) {
va_end(args);
return 0;
}
va_end(args);
return OHOS::GraphicDumperHelperImpl::GetInstance()->SendInfo(std::string(tag), "%s", info);
}
int AddConfigChangeListener(const char* tag, OnConfigChangeFuncPtr func)
{
auto cfunc = [func](const std::string &a, const std::string &b) {
func(a.c_str(), b.c_str());
};
return OHOS::GraphicDumperHelperImpl::GetInstance()->AddConfigChangeListener(std::string(tag), cfunc);
}
int RemoveConfigChangeListener(int listenerId)
{
return OHOS::GraphicDumperHelperImpl::GetInstance()->RemoveConfigChangeListener(listenerId);
}
int AddDumpListener(const char* tag, OnDumpFuncPtr func)
{
return OHOS::GraphicDumperHelperImpl::GetInstance()->AddDumpListener(std::string(tag), func);
}
int RemoveDumpListener(int listenerId)
{
return OHOS::GraphicDumperHelperImpl::GetInstance()->RemoveDumpListener(listenerId);
}

View File

@ -0,0 +1,339 @@
/*
* 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 "graphic_dumper_helper_impl.h"
#include <chrono>
#include <cstdarg>
#include <vector>
#include <gslogger.h>
#include <iservice_registry.h>
#include <securec.h>
#include <system_ability_definition.h>
#include <unistd.h>
#include "graphic_dumper_hilog.h"
#include "ipc/igraphic_dumper_command.h"
namespace OHOS {
namespace {
DEFINE_HILOG_LABEL("GraphicDumperHelperImpl");
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperHelperImpl" };
constexpr int INFO_SIZE_MAX = 4096;
}
GraphicDumperClientListener::GraphicDumperClientListener(sptr<GraphicDumperHelperImpl>& helper)
: helperImpl_(helper)
{
}
void GraphicDumperClientListener::OnConfigChange(const std::string &tag, const std::string &val)
{
GDLOGI("%{public}s -> %{public}s", tag.c_str(), val.c_str());
if (helperImpl_) {
helperImpl_->DispenseOnConfigChange(tag, val);
}
}
void GraphicDumperClientListener::OnDump(const std::string &tag)
{
if (helperImpl_) {
std::string flag = "*#dp#*.";
if (tag.find(flag) == 0) {
std::string sTag = tag.substr(flag.length());
helperImpl_->DispenseOnDump(sTag);
}
}
}
sptr<GraphicDumperHelper> GraphicDumperHelperImpl::GetInstance()
{
if (currentHelper == nullptr) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
if (currentHelper == nullptr) {
currentHelper = new GraphicDumperHelperImpl();
}
}
return currentHelper;
}
void GraphicDumperHelperImpl::SetNoopInstance()
{
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
currentHelper = new GraphicDumperHelperNoop();
}
GSError GraphicDumperHelperImpl::Init()
{
if (serverConnected) {
return GSERROR_OK;
}
if (access("/data/gdumper_enable", F_OK) != 0) {
SetNoopInstance();
return GSERROR_NOT_SUPPORT;
}
auto now = std::chrono::steady_clock::now().time_since_epoch();
auto nowTime = (int64_t)std::chrono::duration_cast<std::chrono::milliseconds>(now).count();
constexpr int64_t reconnectTime = 1000;
if ((nowTime - requestConnectTime) < reconnectTime) {
return GSERROR_OUT_OF_RANGE;
}
requestConnectTime = nowTime;
GSError ret = InitSA(GRAPHIC_DUMPER_SERVICE_SA_ID);
if (ret != GSERROR_OK) {
GSLOG2HI(ERROR) << "InitSA failed with " << ret;
return ret;
}
{
std::lock_guard<std::mutex> guard(onConfigChangeMutex_);
for (const auto& iter : onConfigChangeMap_) {
ret = AddClientListener(iter.first);
if (ret != GSERROR_OK) {
return ret;
}
}
}
{
std::lock_guard<std::mutex> guard(onDumperFuncsMutex_);
for (const auto& iter : onDumpFuncsMap_) {
ret = AddClientListener(iter.first);
if (ret != GSERROR_OK) {
return ret;
}
}
}
{
std::lock_guard<std::mutex> guard(cacheInfoMutex_);
for (const auto& infoStruct : cacheInfo_) {
ret = service_->SendInfo(infoStruct.tag, infoStruct.info);
GDLOG_SUCCESS("SendInfo is %{public}d", ret);
}
cacheInfo_.clear();
cacheInfo_.shrink_to_fit();
}
return ret;
}
GSError GraphicDumperHelperImpl::InitSA(int32_t systemAbilityId)
{
if (serverConnected) {
return GSERROR_OK;
}
auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
GSLOG2HI(ERROR) << "failed with " << GSERROR_CONNOT_CONNECT_SAMGR;
return GSERROR_CONNOT_CONNECT_SAMGR;
}
auto remoteObject = sam->GetSystemAbility(systemAbilityId);
if (remoteObject == nullptr) {
GSLOG2HI(ERROR) << "failed with " << GSERROR_CONNOT_CONNECT_SERVER;
return GSERROR_CONNOT_CONNECT_SERVER;
}
sptr<IRemoteObject::DeathRecipient> deathRecipient = new GDumperServiceDeathRecipient();
if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient))) {
GSLOG2HI(WARN) << "failed to add death recipient";
}
service_ = iface_cast<IGraphicDumperService>(remoteObject);
if (service_ == nullptr) {
GSLOG2HI(ERROR) << "failed with " << GSERROR_PROXY_NOT_INCLUDE;
return GSERROR_PROXY_NOT_INCLUDE;
}
serverConnected = true;
GSLOG2HI(INFO) << "service_ = iface_cast";
return GSERROR_OK;
}
GSError GraphicDumperHelperImpl::AddClientListener(const std::string &tag)
{
if (Init() != GSERROR_OK) {
GSLOG2HI(ERROR) << "Init() failed";
return GSERROR_CONNOT_CONNECT_SERVER;
}
if (listener_ == nullptr) {
std::lock_guard<std::mutex> guard(clientListenerMutex_);
if (listener_ == nullptr) {
sptr<GraphicDumperHelperImpl> helper = this;
listener_ = new GraphicDumperClientListener(helper);
}
}
GSLOG2HI(INFO) << "AddClientListener Success";
return service_->AddClientListener(tag, listener_);
}
GSError GraphicDumperHelperImpl::SendInfo(const std::string &tag, const char *fmt, ...)
{
char info[INFO_SIZE_MAX]; // clear by vsnprintf
{
static std::mutex sprintfMutex_;
std::lock_guard<std::mutex> lock(sprintfMutex_);
va_list args;
va_start(args, fmt);
int ret = vsnprintf_s(info, sizeof(info), (sizeof(info) - 1), fmt, args);
if (ret < 0) {
va_end(args);
return GSERROR_INVALID_ARGUMENTS;
}
va_end(args);
}
GSError retInit = Init();
if (retInit == GSERROR_OK) {
return service_->SendInfo(tag, std::string(info));
} else if (retInit == GSERROR_NOT_SUPPORT) {
return retInit;
} else {
struct InfoStruct infoStruct = {
.tag = tag,
.info = info,
};
std::lock_guard<std::mutex> guard(cacheInfoMutex_);
cacheInfo_.push_back(infoStruct);
return GSERROR_OK;
}
}
int32_t GraphicDumperHelperImpl::AddConfigChangeListener(const std::string &tag, OnConfigChangeFunc func)
{
{
std::lock_guard<std::mutex> guard(onConfigChangeMutex_);
if (onConfigChangeMap_.find(tag) != onConfigChangeMap_.end()) {
(*onConfigChangeMap_[tag])[++onConfigChangeFuncId_] = func;
return onConfigChangeFuncId_;
}
}
int ret = AddClientListener(tag);
if (ret != GSERROR_OK) {
return 0;
}
auto onConfigChangeFuncs = std::make_unique<std::map<int32_t, OnConfigChangeFunc>>();
(*onConfigChangeFuncs)[++onConfigChangeFuncId_] = func;
onConfigChangeMap_[tag] = std::move(onConfigChangeFuncs);
return onConfigChangeFuncId_;
}
GSError GraphicDumperHelperImpl::RemoveConfigChangeListener(const int32_t listenerId)
{
std::lock_guard<std::mutex> guard(onConfigChangeMutex_);
for (auto& [k, v] : onConfigChangeMap_) {
if (v->find(listenerId) != v->end()) {
v->erase(listenerId);
return GSERROR_OK;
}
}
return GSERROR_INVALID_ARGUMENTS;
}
int32_t GraphicDumperHelperImpl::AddDumpListener(const std::string &tag, OnDumpFunc func)
{
{
std::lock_guard<std::mutex> guard(onDumperFuncsMutex_);
if (onDumpFuncsMap_.find(tag) != onDumpFuncsMap_.end()) {
(*onDumpFuncsMap_[tag])[++onDumperFuncId_] = func;
return onDumperFuncId_;
}
}
auto dumpTag = "*#dp#*." + tag;
int ret = AddClientListener(dumpTag);
if (ret != GSERROR_OK) {
GSLOG2HI(ERROR) << "AddClientListener failed with " << ret;
return 0;
}
auto onDumpFuncs = std::make_unique<std::map<int32_t, OnDumpFunc>>();
(*onDumpFuncs)[++onDumperFuncId_] = func;
onDumpFuncsMap_[tag] = std::move(onDumpFuncs);
return onDumperFuncId_;
}
GSError GraphicDumperHelperImpl::RemoveDumpListener(const int32_t listenerId)
{
std::lock_guard<std::mutex> guard(onDumperFuncsMutex_);
for (auto& [k, v] : onDumpFuncsMap_) {
if (v->find(listenerId) != v->end()) {
v->erase(listenerId);
return GSERROR_OK;
}
}
return GSERROR_INVALID_ARGUMENTS;
}
void GraphicDumperHelperImpl::SetConnectState(bool state)
{
GDLOGFI("");
serverConnected = state;
}
void GraphicDumperHelperImpl::DispenseOnConfigChange(const std::string &tag, const std::string &val)
{
GDLOGI("%{public}s -> %{public}s", tag.c_str(), val.c_str());
std::lock_guard<std::mutex> guard(onConfigChangeMutex_);
if (onConfigChangeMap_.empty()) {
return;
}
if (!onConfigChangeMap_[tag]->empty()) {
for (const auto &[id, func] : *onConfigChangeMap_[tag]) {
func(tag, val);
}
}
}
void GraphicDumperHelperImpl::DispenseOnDump(const std::string &tag)
{
std::lock_guard<std::mutex> guard(onDumperFuncsMutex_);
if (onDumpFuncsMap_.empty()) {
return;
}
if (tag == "--all") {
for (const auto& [t, mapPtr] : onDumpFuncsMap_) {
if (mapPtr != nullptr) {
for (const auto &[id, func] : *mapPtr) {
func();
}
}
}
return;
}
if (onDumpFuncsMap_.find(tag) != onDumpFuncsMap_.end()) {
if (onDumpFuncsMap_[tag] != nullptr) {
for (const auto &[id, func] : *onDumpFuncsMap_[tag]) {
func();
}
}
}
}
void GDumperServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
{
auto helper = GraphicDumperHelperImpl::GetInstance();
auto helperImpl = reinterpret_cast<GraphicDumperHelperImpl *>(helper.GetRefPtr());
helperImpl->SetConnectState(false);
}
} // namespace OHOS

View File

@ -0,0 +1,567 @@
/*
* 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 "graphic_dumper_server.h"
#include <fstream>
#include <iostream>
#include <regex>
#include <iremote_object.h>
#include <iservice_registry.h>
#include <securec.h>
#include <system_ability_definition.h>
#include <unistd.h>
#include <zlib.h>
#include "ipc/graphic_dumper_info_listener_death_recipient.h"
#include "ipc/graphic_dumper_client_listener_death_recipient.h"
#include "ipc/graphic_dumper_service_stub.h"
#include "ipc/graphic_dumper_command_stub.h"
#include "graphic_dumper_hilog.h"
#include "graphic_dumper_util.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperServer" };
constexpr int SLEEP_TIME = 500 * 1000;
constexpr uint32_t LOG_BUF_SIZE_MAX = 192 * 1024;
constexpr uint32_t LOG_BLOCK_SIZE_MAX = 4 * 1000 * 1024;
constexpr uint32_t LOG_VEC_SIZE = 2;
constexpr const char *GDUMPER_INI_PATH = "/system/etc/gdumper.ini";
std::string& Trim (std::string &s)
{
std::regex fmt("\\s");
s = std::regex_replace(s, fmt, "");
return s;
}
void StrLogRomveTag(bool getAll, const std::string &tag,
const std::string &strIn, std::string &strOut)
{
auto pos = strIn.find_first_of("| [");
constexpr int offset = 2;
if (pos == std::string::npos) {
pos = 0;
} else {
pos += offset;
}
if (getAll) {
strOut += strIn.substr(pos);
} else if (strIn.compare(0, tag.size(), tag) == 0) {
strOut += strIn.substr(pos);
}
}
} // namespace
sptr<GraphicDumperServer> GraphicDumperServer::GetInstance()
{
if (instance_ == nullptr) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
if (instance_ == nullptr) {
instance_ = new GraphicDumperServer();
}
}
return instance_;
}
int32_t GraphicDumperServer::Init()
{
int32_t ret = 0;
ret = ReadDefaultConfig();
if (ret) {
GDLOGI("Read default config error with %d.\n", ret);
}
for (auto& s : logBuf_.size) {
s = 0;
logBuf_.vec.push_back(std::make_unique<std::vector<std::string>>());
}
sptr<IRemoteObject> service = new GraphicDumperServiceStub();
ret = StartServer(GRAPHIC_DUMPER_SERVICE_SA_ID, service);
if (ret) {
GDLOGI("Start graphic dumper service failed: %d\n", ret);
return ret;
}
sptr<IRemoteObject> command = new GraphicDumperCommandStub();
ret = StartServer(GRAPHIC_DUMPER_COMMAND_SA_ID, command);
if (ret) {
GDLOGI("Start graphic dumper command failed: %d\n", ret);
return ret;
}
return ret;
}
GSError GraphicDumperServer::AddConfigListener(const std::string &tag,
sptr<IGraphicDumperClientListener> &listener)
{
if (listener == nullptr) {
return GSERROR_INVALID_ARGUMENTS;
}
GDLOGFE("%{public}s", tag.c_str());
auto object = listener->AsObject();
AddConfigDeathRecipient(object);
if (HaveObject(object) == false) {
objectIdMap_[object] = ++objectId_;
configTagsMap_[objectId_].id = objectId_;
configTagsMap_[objectId_].listener = listener;
}
auto &objectId = objectIdMap_[object];
auto &configTags = configTagsMap_[objectId];
for (const auto &iter : configTags.tags) {
if (iter == tag) {
return GSERROR_OK;
}
}
configTags.tags.push_back(tag);
for (auto &tag__ : configTags.tags) {
GDLOGFE("configTagsMap %{public}s", tag__.c_str());
}
std::lock_guard<std::mutex> lock(treeMutex_);
std::vector<std::string> nodes = Split(tag, ".");
TreeNodePtr sub = root;
for (const auto& iter : nodes) {
sub = sub->GetSetNode(iter);
}
sub->AddListenerId(configTags.id);
return GSERROR_OK;
}
GSError GraphicDumperServer::RemoveConfigListener(sptr<IRemoteObject> object)
{
if (object == nullptr) {
return GSERROR_INVALID_ARGUMENTS;
}
auto &deathRecipient = configListenerDeathRecipientMap_[object];
if (deathRecipient != nullptr) {
object->RemoveDeathRecipient(deathRecipient);
}
configListenerDeathRecipientMap_.erase(object);
auto &objectId = objectIdMap_[object];
auto &configTags = configTagsMap_[objectId];
for (auto &tag : configTags.tags) {
GDLOGFE("configTagsMap %{public}s", tag.c_str());
std::lock_guard<std::mutex> lock(treeMutex_);
std::vector<std::string> nodes = Split(tag, ".");
TreeNodePtr sub = root;
RemoveNode(nodes, sub, configTags.id);
}
object = nullptr;
return GSERROR_OK;
}
GSError GraphicDumperServer::GetConfig(const std::string &k, std::string &v)
{
GDLOGI("%{public}s -> %{public}s", k.c_str(), v.c_str());
std::lock_guard<std::mutex> lock(treeMutex_);
std::vector<std::string> nodes = Split(k, ".");
TreeNodePtr sub = root;
for (const auto& iter : nodes) {
if (sub->HasNode(iter)) {
sub = sub->GetSetNode(iter);
} else {
return GSERROR_INVALID_ARGUMENTS;
}
}
v = sub->GetValue();
GDLOGI("%{public}s -> %{public}s", k.c_str(), v.c_str());
return GSERROR_OK;
}
GSError GraphicDumperServer::SetConfig(const std::string &k, const std::string &v)
{
GDLOGI("%{public}s -> %{public}s", k.c_str(), v.c_str());
std::lock_guard<std::mutex> lock(treeMutex_);
std::vector<std::string> nodes = Split(k, ".");
TreeNodePtr sub = root;
for (const auto& iter : nodes) {
sub = sub->GetSetNode(iter);
}
if (sub->GetValue().compare(v)) {
sub->SetValue(v);
DispenseConfig(sub, k, v);
}
GDLOGI("%{public}s -> %{public}s", k.c_str(), v.c_str());
return GSERROR_OK;
}
GSError GraphicDumperServer::Dump(const std::string &tag)
{
std::lock_guard<std::mutex> lock(treeMutex_);
std::vector<std::string> nodes = Split(tag, ".");
TreeNodePtr sub = root;
for (const auto& iter : nodes) {
if (iter.compare("--all") == 0) {
break;
}
GDLOGFE("%{public}s", iter.c_str());
sub = sub->GetSetNode(iter);
}
DispenseDump(sub, tag);
GDLOGFE("%{public}s", tag.c_str());
return GSERROR_OK;
}
GSError GraphicDumperServer::AddInfoListener(sptr<IGraphicDumperInfoListener> &listener)
{
if (listener == nullptr) {
return GSERROR_INVALID_ARGUMENTS;
}
std::lock_guard<std::mutex> guard(infoListenersMutex_);
auto object = listener->AsObject();
AddInfoDeathRecipient(object);
infoListeners_[object] = listener;
return GSERROR_OK;
}
GSError GraphicDumperServer::RemoveInfoListener(const wptr<IRemoteObject> &object)
{
std::lock_guard<std::mutex> guard(infoListenersMutex_);
auto sObject = object.promote();
if (infoListeners_.find(sObject) != infoListeners_.end()) {
infoListeners_.erase(sObject);
}
if (infoListeners_.empty()) {
logBuf_.sync = false;
logBuf_.mask.clear();
}
return GSERROR_OK;
}
GSError GraphicDumperServer::InfoHandle(const std::string &tag, const std::string &info)
{
GDLOGFE("GraphicDumperServer::InfoHandle --start!!!!!!!!!");
std::string logFlag = {"log."};
GDLOGFE("%{public}s -> %{public}s", tag.c_str(), info.c_str());
if (tag.compare(0, logFlag.size(), logFlag) == 0) {
GDLOGFE("InfoHandle to LogHandle");
return LogHandle(tag.substr(logFlag.size()), info);
}
GDLOGFE("InfoHandle to SendToInfoListener");
SendToInfoListener(tag + " : " + info);
return GSERROR_OK;
}
GSError GraphicDumperServer::GetLog(const std::string &tag, const std::string &info)
{
GDLOGFE("%{public}s -> %{public}s", tag.c_str(), info.c_str());
bool getAll = false;
if (tag.compare("--all") == 0) {
getAll = true;
logBuf_.mask.clear();
} else {
logBuf_.mask = tag;
}
{
std::lock_guard<std::mutex> lock(logBlockVectorMutex_);
for (const auto& array : logBlockVector_) {
auto logBlock = reinterpret_cast<LogBlock *>(array.get());
std::string toSendStr = {};
uint32_t offset = 0;
GDLOGFE("logBlock->size = %{public}d", logBlock->size);
while (offset < logBlock->size) {
std::string str(reinterpret_cast<const char*>(logBlock->data + offset));
GDLOGFE("logBlock = %{public}s", str.c_str());
StrLogRomveTag(getAll, tag, str, toSendStr);
offset += (str.size() + 1);
}
SendToInfoListener(toSendStr);
}
}
std::string logStr = {};
if (logBuf_.canSave || logBuf_.needSave) {
uint32_t index = (logBuf_.index + 1) % LOG_VEC_SIZE;
std::lock_guard<std::mutex> guard(logBuf_.mutex[index]);
for (const auto& str : *logBuf_.vec[index]) {
GDLOGFE("logBuf_cansave = %{public}s", str.c_str());
StrLogRomveTag(getAll, tag, str, logStr);
}
}
SendToInfoListener(logStr);
logStr.clear();
{
uint32_t index = logBuf_.index;
std::lock_guard<std::mutex> guard(logBuf_.mutex[index]);
for (const auto& str : *logBuf_.vec[index]) {
GDLOGFE("logBuf_ = %{public}s", str.c_str());
StrLogRomveTag(getAll, tag, str, logStr);
}
}
SendToInfoListener(logStr);
logBuf_.sync = true;
return GSERROR_OK;
}
int32_t GraphicDumperServer::StartServer(int32_t systemAbility, sptr<IRemoteObject> obj)
{
if (systemAbility == 0 || obj == nullptr) {
GDLOGI("graphic dumper start_server parameter error");
return 1;
}
int result = 0;
while (1) {
auto sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sm != nullptr) {
result = sm->AddSystemAbility(systemAbility, obj);
break;
}
GDLOGI("graphic dumper start_server SystemAbilityManager is nullptr");
usleep(SLEEP_TIME);
}
return result;
}
int32_t GraphicDumperServer::ReadDefaultConfig()
{
int32_t successConst = 0;
int32_t failConst = 0;
std::string getLineStr = {};
std::vector<std::string> cfgStrs = {};
std::ifstream input(GDUMPER_INI_PATH);
if (!input.is_open()) {
GDLOGE("failed to open: %{public}s", GDUMPER_INI_PATH);
} else {
while (!input.eof()) {
getline(input, getLineStr);
Trim(getLineStr);
std::string first = getLineStr.substr(0, 1);
if (first != "#" && first != "") {
cfgStrs.push_back(getLineStr);
}
}
input.clear();
input.close();
}
std::lock_guard<std::mutex> lock(treeMutex_);
for (auto iter : cfgStrs) {
if (!iter.empty()) {
std::vector<std::string> cfg = Split(iter, "=");
if (cfg.size() != CFGTERMSIZE) {
failConst++;
GDLOGE("fail cfg(%{public}d): %{public}s", failConst, iter.c_str());
}
std::vector<std::string> nodes = Split(cfg[0], ".");
TreeNodePtr sub = root;
for (const auto& iter : nodes) {
sub = sub->GetSetNode(iter);
}
sub->SetValue(cfg[1]);
successConst++;
}
}
GDLOGI("There are %{public}d items successfully configured", successConst);
return failConst;
}
void GraphicDumperServer::AddConfigDeathRecipient(sptr<IRemoteObject> &object)
{
if (!HaveConfigDeathRecipient(object)) {
sptr<IRemoteObject::DeathRecipient> deathRecipient = new GraphicDumperClientListenerDeathRecipient();
if ((object->IsProxyObject()) && (!object->AddDeathRecipient(deathRecipient))) {
GDLOGFE("Failed to add death recipient");
}
configListenerDeathRecipientMap_[object] = deathRecipient;
}
}
bool GraphicDumperServer::HaveConfigDeathRecipient(sptr<IRemoteObject> &object)
{
auto &map = configListenerDeathRecipientMap_;
return map.find(object) != map.end();
}
bool GraphicDumperServer::HaveObject(const sptr<IRemoteObject> &obj)
{
return objectIdMap_.find(obj) != objectIdMap_.end();
}
void GraphicDumperServer::VisitEach(const TreeNodePtr &node, TreeNodeVisitFunc func)
{
GDLOGFI("");
TreeNodeVisitFunc getV = [&](const TreeNodePtr &v) {
GDLOGFI("");
func(v);
v->Foreach(getV);
};
node->Foreach(getV);
}
void GraphicDumperServer::RemoveNode(std::vector<std::string> &vec,
TreeNodePtr &sub,
uint32_t &listenerId)
{
GDLOGFE("listener: %{public}u", listenerId);
if (vec.empty() || sub == nullptr || listenerId == 0) {
return;
}
std::string tag = *vec.begin();
GDLOGFE("tag: %{public}s", tag.c_str());
vec.erase(vec.begin());
if (sub->HasNode(tag)) {
TreeNodePtr subNd = sub->GetSetNode(tag);
if (vec.empty()) {
subNd->RemoveListenerId(listenerId);
return;
}
RemoveNode(vec, subNd, listenerId);
if (subNd->IsEmptyNode()) {
sub->EraseNode(subNd->GetTag());
}
}
}
void GraphicDumperServer::DispenseConfig(const TreeNodePtr &node, const std::string &k, const std::string &v)
{
GDLOGFI("%{public}s -> %{public}s", k.c_str(), v.c_str());
auto dispenseConfig = [&](const TreeNodePtr &nd) {
GDLOGFI("%{public}s -> %{public}s", k.c_str(), v.c_str());
auto ls = nd->GetListenerIds();
for (const auto& id : ls) {
configTagsMap_[id].listener->OnConfigChange(k, v);
}
};
dispenseConfig(node);
VisitEach(node, dispenseConfig);
}
void GraphicDumperServer::DispenseDump(const TreeNodePtr &node, const std::string &tag)
{
GDLOGFI("%{public}s", tag.c_str());
auto dispenseDump = [&](const TreeNodePtr &nd) {
GDLOGFI("%{public}s", tag.c_str());
auto ls = nd->GetListenerIds();
for (const auto& id : ls) {
configTagsMap_[id].listener->OnDump(tag);
}
};
dispenseDump(node);
VisitEach(node, dispenseDump);
}
void GraphicDumperServer::AddInfoDeathRecipient(sptr<IRemoteObject> &object)
{
if (!HaveInfoDeathRecipient(object)) {
sptr<IRemoteObject::DeathRecipient> deathRecipient = new GraphicDumperInfoListenerDeathRecipient();
if ((object->IsProxyObject()) && (!object->AddDeathRecipient(deathRecipient))) {
GDLOGFE("Failed to add death recipient");
}
infoListenerDeathRecipientMap_[object] = deathRecipient;
}
}
bool GraphicDumperServer::HaveInfoDeathRecipient(sptr<IRemoteObject> &object)
{
auto &map = infoListenerDeathRecipientMap_;
return map.find(object) != map.end();
}
void GraphicDumperServer::SendToInfoListener(const std::string &info)
{
std::lock_guard<std::mutex> guard(infoListenersMutex_);
for (const auto& [k, v] : infoListeners_) {
v->OnInfoComing(info);
}
}
void GraphicDumperServer::SaveLog(std::any server)
{
auto serverPtr = std::any_cast<GraphicDumperServer *>(server);
uint32_t index = (serverPtr->logBuf_.index + 1) % LOG_VEC_SIZE;
std::lock_guard<std::mutex> guard(serverPtr->logBuf_.mutex[index]);
uint32_t size = sizeof(LogBlock) + serverPtr->logBuf_.size[index] + 1;
auto logArray = std::make_unique<uint8_t[]>(size);
auto logBlock = reinterpret_cast<LogBlock *>(logArray.get());
logBlock->size = serverPtr->logBuf_.size[index];
logBlock->length = serverPtr->logBuf_.size[index];
uint32_t offset = 0;
for (const auto& str : *serverPtr->logBuf_.vec[index]) {
int ret = memcpy_s(logBlock->data + offset,
serverPtr->logBuf_.size[index] - offset,
str.c_str(), str.size() + 1);
if (ret < 0) {
return;
}
offset += str.size() + 1;
}
std::lock_guard<std::mutex> lock(serverPtr->logBlockVectorMutex_);
if ((serverPtr->logBlockSize_ + serverPtr->logBuf_.size[index]) > LOG_BLOCK_SIZE_MAX) {
auto logFirstBlock = reinterpret_cast<LogBlock *>(serverPtr->logBlockVector_.begin()->get());
serverPtr->logBlockSize_ -= logFirstBlock->size;
serverPtr->logBlockVector_.erase(serverPtr->logBlockVector_.begin());
}
serverPtr->logBlockVector_.push_back(std::move(logArray));
serverPtr->logBlockSize_ += serverPtr->logBuf_.size[index];
serverPtr->logBuf_.vec[index]->clear();
serverPtr->logBuf_.size[index] = 0;
}
GSError GraphicDumperServer::LogHandle(const std::string &tag, const std::string &info)
{
std::string log = tag + " | " + info;
GDLOGFI("%{public}s -> %{public}s", tag.c_str(), info.c_str());
{
std::lock_guard<std::mutex> guard(logBuf_.mutex[logBuf_.index]);
logBuf_.size[logBuf_.index] += log.size() + 1;
logBuf_.vec[logBuf_.index]->push_back(log);
if (logBuf_.canSave && (logBuf_.size[logBuf_.index] > (LOG_BUF_SIZE_MAX / LOG_VEC_SIZE))) {
thread_ = std::make_unique<std::thread>(&GraphicDumperServer::SaveLog, this);
logBuf_.needSave = true;
logBuf_.canSave = false;
}
if (logBuf_.size[logBuf_.index] >= LOG_BUF_SIZE_MAX) {
logBuf_.vec[logBuf_.index]->shrink_to_fit();
if (logBuf_.needSave) {
thread_->join();
logBuf_.needSave = false;
}
logBuf_.index = (logBuf_.index + 1) % LOG_VEC_SIZE;
logBuf_.canSave = true;
}
}
if (logBuf_.sync) {
if ((!logBuf_.mask.empty()) && (log.compare(0, logBuf_.mask.size(), logBuf_.mask) != 0)) {
return GSERROR_OK;
}
auto pos = log.find_first_of("| [");
constexpr int offset = 2;
if (pos == std::string::npos) {
pos = 0;
} else {
pos += offset;
}
SendToInfoListener(log.substr(pos));
}
return GSERROR_OK;
}
} // namespace OHOS

View File

@ -0,0 +1,29 @@
/*
* 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 <ipc_skeleton.h>
#include "graphic_dumper_server.h"
using namespace OHOS;
int main()
{
int ret = GraphicDumperServer::GetInstance()->Init();
if (ret == 0) {
IPCSkeleton::JoinWorkThread();
}
return ret;
}

View File

@ -0,0 +1,106 @@
/*
* 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 "graphic_dumper_tree.h"
#include "graphic_dumper_hilog.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperTree" };
} // namespace
TreeNodePtr GraphicDumperTree::GetSetNode(const std::string s)
{
if (nodeMap_ == nullptr) {
nodeMap_ = std::make_unique<TreeNodeMap>();
}
if (!HasNode(s)) {
(*nodeMap_)[s] = std::make_shared<GraphicDumperTree>();
(*nodeMap_)[s]->tag_ = s;
}
return (*nodeMap_)[s];
}
bool GraphicDumperTree::HasNode(const std::string s)
{
return nodeMap_->find(s) != nodeMap_->end();
}
bool GraphicDumperTree::IsEmptyNode()
{
if (nodeMap_->empty() && listenerIds_.empty()) {
return true;
}
return false;
}
void GraphicDumperTree::EraseNode(const std::string &s)
{
(*nodeMap_)[s] = nullptr;
nodeMap_->erase(s);
}
std::string GraphicDumperTree::GetTag()
{
return tag_;
}
void GraphicDumperTree::SetValue(const std::string s)
{
value_ = s;
}
std::string GraphicDumperTree::GetValue()
{
return value_;
}
void GraphicDumperTree::AddListenerId(uint32_t &listenerId)
{
GDLOGFI("");
listenerIds_.push_back(listenerId);
}
void GraphicDumperTree::RemoveListenerId(uint32_t &listenerId)
{
GDLOGFI("%{public}u", listenerId);
for (auto iter = listenerIds_.begin(); iter != listenerIds_.end(); ++iter) {
GDLOGFI("%{public}u <==> %{public}u", (*iter), listenerId);
if (*iter == listenerId) {
GDLOGFI("");
listenerIds_.erase(iter--);
}
}
}
std::vector<uint32_t> GraphicDumperTree::GetListenerIds() const
{
GDLOGFI("");
return listenerIds_;
}
void GraphicDumperTree::Foreach(TreeNodeVisitFunc func) const
{
GDLOGFI("");
if (nodeMap_ == nullptr) {
return;
}
for (const auto& [k, v] : (*nodeMap_)) {
GDLOGFI("%{public}s", k.c_str());
func(v);
}
}
} // namespace OHOS

View File

@ -0,0 +1,38 @@
/*
* 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 "graphic_dumper_util.h"
namespace OHOS {
std::vector<std::string> Split(std::string src, const std::string &splitStr)
{
std::vector<std::string> ret;
std::string::size_type pos = 0;
while (pos != std::string::npos) {
pos = src.find(splitStr);
if (pos == std::string::npos) {
if (!src.empty()) {
ret.push_back(src);
}
} else {
if (!src.empty()) {
ret.push_back(src.substr(0, pos));
}
src = src.substr(pos + splitStr.size());
}
}
return ret;
}
} // namespace OHOS

View File

@ -0,0 +1,28 @@
/*
* 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 "ipc/graphic_dumper_client_listener_death_recipient.h"
#include "graphic_dumper_server.h"
namespace OHOS {
void GraphicDumperClientListenerDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
{
if (object == nullptr) {
return;
}
GraphicDumperServer::GetInstance()->RemoveConfigListener(object.promote());
}
} // namespace OHOS

View File

@ -0,0 +1,74 @@
/*
* 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 "ipc/graphic_dumper_client_listener_proxy.h"
#include <message_option.h>
#include <message_parcel.h>
#include "graphic_dumper_hilog.h"
#include "graphic_common.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperClientListenerProxy" };
}
GraphicDumperClientListenerProxy::GraphicDumperClientListenerProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IGraphicDumperClientListener>(impl)
{
}
void GraphicDumperClientListenerProxy::OnConfigChange(const std::string &tag, const std::string &val)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
GDLOGFI("%{public}s -> %{public}s", tag.c_str(), val.c_str());
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
arg.WriteString(val);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_CLIENT_LISTENER_ON_CONFIG_CHANGE, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return;
}
return;
}
void GraphicDumperClientListenerProxy::OnDump(const std::string &tag)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
GDLOGFI("%{public}s", tag.c_str());
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_CLIENT_LISTENER_ON_DUMP, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return;
}
return;
}
} // namespace OHOS

View File

@ -0,0 +1,55 @@
/*
* 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 "ipc/graphic_dumper_client_listener_stub.h"
#include "graphic_dumper_hilog.h"
#include "graphic_common.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperClientListenerStub" };
}
int32_t GraphicDumperClientListenerStub::OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option)
{
auto remoteDescriptor = data.ReadInterfaceToken();
if (GetDescriptor() != remoteDescriptor) {
return 1;
}
switch (code) {
case IGRAPHIC_DUMPER_CLIENT_LISTENER_ON_CONFIG_CHANGE: {
std::string tag = data.ReadString();
std::string val = data.ReadString();
GDLOGI("%{public}s -> %{public}s", tag.c_str(), val.c_str());
OnConfigChange(tag, val);
reply.WriteInt32(GSERROR_OK);
}
break;
case IGRAPHIC_DUMPER_CLIENT_LISTENER_ON_DUMP: {
std::string val = data.ReadString();
OnDump(val);
reply.WriteInt32(GSERROR_OK);
}
break;
default:
GDLOGFE("code %{public}d cannot process", code);
return 1;
}
return 0;
}
} // namespace OHOS

View File

@ -0,0 +1,148 @@
/*
* 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 "ipc/graphic_dumper_command_proxy.h"
#include <message_option.h>
#include <message_parcel.h>
#include "graphic_dumper_hilog.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperCommandProxy" };
}
GraphicDumperCommandProxy::GraphicDumperCommandProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IGraphicDumperCommand>(impl)
{
}
GSError GraphicDumperCommandProxy::GetConfig(const std::string &k, std::string &v)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
GDLOGFE("%{public}s -> %{public}s", k.c_str(), v.c_str());
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(k);
arg.WriteString(v);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_COMMAND_GET_CONFIG, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_API_FAILED;
}
GSError retCode = static_cast<GSError>(ret.ReadInt32());
if (retCode == GSERROR_OK) {
v = ret.ReadString();
GDLOGFE("%{public}s -> %{public}s", k.c_str(), v.c_str());
}
return retCode;
}
GSError GraphicDumperCommandProxy::SetConfig(const std::string &k, const std::string &v)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
GDLOGFE("%{public}s -> %{public}s", k.c_str(), v.c_str());
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(k);
arg.WriteString(v);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_COMMAND_SET_CONFIG, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_API_FAILED;
}
return GSERROR_OK;
}
GSError GraphicDumperCommandProxy::Dump(const std::string &tag)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
GDLOGFE("%{public}s", tag.c_str());
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_COMMAND_DUMP, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_API_FAILED;
}
return GSERROR_OK;
}
GSError GraphicDumperCommandProxy::GetLog(const std::string &tag, std::string &log)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
GDLOGFE("%{public}s -> %{public}s", tag.c_str(), log.c_str());
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_COMMAND_GET_LOG, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_API_FAILED;
}
return GSERROR_OK;
}
GSError GraphicDumperCommandProxy::AddInfoListener(const std::string &tag, sptr<IGraphicDumperInfoListener> &listener)
{
if (listener == nullptr) {
GDLOG_FAILURE_NO(GSERROR_INVALID_ARGUMENTS);
return GSERROR_INVALID_ARGUMENTS;
}
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
arg.WriteRemoteObject(listener->AsObject());
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_COMMAND_ADD_INFO_LISTENER, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_BINDER;
}
GSError err = (GSError)ret.ReadInt32();
if (err != GSERROR_OK) {
GDLOG_FAILURE_NO(err);
}
return err;
}
} // namespace OHOS

View File

@ -0,0 +1,127 @@
/*
* 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 "ipc/graphic_dumper_command_stub.h"
#include "graphic_dumper_hilog.h"
#include "graphic_dumper_server.h"
#include "ipc/igraphic_dumper_command.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperCommandStub" };
}
int32_t GraphicDumperCommandStub::OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option)
{
auto remoteDescriptor = data.ReadInterfaceToken();
if (GetDescriptor() != remoteDescriptor) {
return 1;
}
switch (code) {
case IGRAPHIC_DUMPER_COMMAND_GET_CONFIG: {
std::string k = data.ReadString();
std::string v = data.ReadString();
GSError ret = GetConfig(k, v);
reply.WriteInt32(ret);
reply.WriteString(v);
break;
}
case IGRAPHIC_DUMPER_COMMAND_SET_CONFIG: {
std::string k = data.ReadString();
std::string v = data.ReadString();
GSError ret = SetConfig(k, v);
reply.WriteInt32(ret);
break;
}
case IGRAPHIC_DUMPER_COMMAND_DUMP: {
std::string v = data.ReadString();
GSError ret = Dump(v);
reply.WriteInt32(ret);
break;
}
case IGRAPHIC_DUMPER_COMMAND_GET_LOG: {
std::string tag = data.ReadString();
std::string log = "";
GSError ret = GetLog(tag, log);
reply.WriteInt32(ret);
break;
}
case IGRAPHIC_DUMPER_COMMAND_ADD_INFO_LISTENER: {
auto tag = data.ReadString();
auto remoteObject = data.ReadRemoteObject();
if (remoteObject == nullptr) {
reply.WriteInt32(GSERROR_INVALID_ARGUMENTS);
GDLOG_FAILURE_NO(GSERROR_INVALID_ARGUMENTS);
break;
}
auto l = iface_cast<IGraphicDumperInfoListener>(remoteObject);
GSError ret = AddInfoListener(tag, l);
reply.WriteInt32(ret);
if (ret != GSERROR_OK) {
GDLOG_FAILURE_NO(ret);
}
break;
}
default: {
return 1;
}
}
return 0;
}
GSError GraphicDumperCommandStub::GetConfig(const std::string &k, std::string &v)
{
GDLOGFE("%{public}s -> %{public}s", k.c_str(), v.c_str());
GraphicDumperServer::GetInstance()->GetConfig(k, v);
GDLOGFE("%{public}s -> %{public}s", k.c_str(), v.c_str());
return GSERROR_OK;
}
GSError GraphicDumperCommandStub::SetConfig(const std::string &k, const std::string &v)
{
GDLOGFE("%{public}s -> %{public}s", k.c_str(), v.c_str());
GraphicDumperServer::GetInstance()->SetConfig(k, v);
return GSERROR_OK;
}
GSError GraphicDumperCommandStub::Dump(const std::string &tag)
{
GDLOGFE("%{public}s", tag.c_str());
GraphicDumperServer::GetInstance()->Dump(tag);
return GSERROR_OK;
}
GSError GraphicDumperCommandStub::GetLog(const std::string &tag, std::string &log)
{
GDLOGFE("%{public}s -> %{public}s", tag.c_str(), log.c_str());
GraphicDumperServer::GetInstance()->GetLog(tag, log);
return GSERROR_OK;
}
GSError GraphicDumperCommandStub::AddInfoListener(const std::string &tag, sptr<IGraphicDumperInfoListener> &listener)
{
GDLOGFE("");
if (listener == nullptr) {
return GSERROR_INVALID_ARGUMENTS;
}
return GraphicDumperServer::GetInstance()->AddInfoListener(listener);
}
} // namespace OHOS

View File

@ -0,0 +1,29 @@
/*
* 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 "ipc/graphic_dumper_info_listener_death_recipient.h"
#include "graphic_dumper_server.h"
#include "ipc/igraphic_dumper_command.h"
#include "graphic_common.h"
#include "graphic_dumper_hilog.h"
namespace OHOS {
void GraphicDumperInfoListenerDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
{
if (object == nullptr) {
return;
}
GraphicDumperServer::GetInstance()->RemoveInfoListener(object);
}
} // namespace OHOS

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.
*/
#include "ipc/graphic_dumper_info_listener_proxy.h"
#include <message_option.h>
#include <message_parcel.h>
#include "graphic_dumper_hilog.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperInfoListenerProxy" };
}
GraphicDumperInfoListenerProxy::GraphicDumperInfoListenerProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IGraphicDumperInfoListener>(impl)
{
}
void GraphicDumperInfoListenerProxy::OnInfoComing(const std::string &info)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(info);
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_INFO_LISTENER_ON_INFO_COMING, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return;
}
return;
}
} // namespace OHOS

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.
*/
#include "ipc/graphic_dumper_info_listener_stub.h"
#include "graphic_dumper_hilog.h"
#include "graphic_common.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperInfoListenerStub" };
}
int32_t GraphicDumperInfoListenerStub::OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option)
{
auto remoteDescriptor = data.ReadInterfaceToken();
if (GetDescriptor() != remoteDescriptor) {
return 1;
}
switch (code) {
case IGRAPHIC_DUMPER_INFO_LISTENER_ON_INFO_COMING: {
std::string info = data.ReadString();
OnInfoComing(info);
reply.WriteInt32(GSERROR_OK);
break;
}
default: {
GDLOGFE("code %{public}d cannot process", code);
return 1;
}
}
return 0;
}
} // namespace OHOS

View File

@ -0,0 +1,84 @@
/*
* 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 "ipc/graphic_dumper_service_proxy.h"
#include <message_option.h>
#include <message_parcel.h>
#include "graphic_dumper_hilog.h"
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperServiceProxy" };
}
GraphicDumperServiceProxy::GraphicDumperServiceProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IGraphicDumperService>(impl)
{
}
GSError GraphicDumperServiceProxy::AddClientListener(const std::string &tag,
sptr<IGraphicDumperClientListener> &listener)
{
if (listener == nullptr) {
GDLOG_FAILURE_NO(GSERROR_INVALID_ARGUMENTS);
return GSERROR_INVALID_ARGUMENTS;
}
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
arg.WriteRemoteObject(listener->AsObject());
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_SERVICE_ADD_CLIENT_LISTENER, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_BINDER;
}
GSError err = (GSError)ret.ReadInt32();
if (err != GSERROR_OK) {
GDLOG_FAILURE_NO(err);
}
return err;
}
GSError GraphicDumperServiceProxy::SendInfo(const std::string &tag, const std::string &info)
{
MessageOption opt;
MessageParcel arg;
MessageParcel ret;
if (!arg.WriteInterfaceToken(GetDescriptor())) {
GDLOGE("write interface token failed");
}
arg.WriteString(tag);
arg.WriteString(info);
GDLOGE("SendInfo SendRequest !!!!!");
int result = Remote()->SendRequest(IGRAPHIC_DUMPER_SERVICE_SEND_INFO, arg, ret, opt);
if (result) {
GDLOG_ERROR_API(result, SendRequest);
return GSERROR_BINDER;
}
return GSERROR_OK;
}
} // namespace OHOS

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 "ipc/graphic_dumper_service_stub.h"
#include "graphic_dumper_hilog.h"
#include "graphic_dumper_server.h"
#define REMOTE_RETURN(reply, gs_error) \
do { \
(reply).WriteInt32(gs_error); \
if ((gs_error) != GSERROR_OK) { \
GDLOG_FAILURE_NO(gs_error); \
} \
} while (0); \
break
namespace OHOS {
namespace {
constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "GraphicDumperServiceStub" };
}
int32_t GraphicDumperServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
auto remoteDescriptor = data.ReadInterfaceToken();
if (GetDescriptor() != remoteDescriptor) {
return 1;
}
switch (code) {
case IGRAPHIC_DUMPER_SERVICE_ADD_CLIENT_LISTENER: {
auto tag = data.ReadString();
GDLOGFE("%{public}s", tag.c_str());
auto remoteObject = data.ReadRemoteObject();
if (remoteObject == nullptr) {
reply.WriteInt32(GSERROR_INVALID_ARGUMENTS);
GDLOG_FAILURE_NO(GSERROR_INVALID_ARGUMENTS);
break;
}
auto l = iface_cast<IGraphicDumperClientListener>(remoteObject);
GSError ret = AddClientListener(tag, l);
reply.WriteInt32(ret);
if (ret != GSERROR_OK) {
GDLOG_FAILURE_NO(ret);
}
break;
}
case IGRAPHIC_DUMPER_SERVICE_SEND_INFO: {
std::string tag = data.ReadString();
std::string info = data.ReadString();
GSError ret = SendInfo(tag, info);
reply.WriteInt32(ret);
if (ret != GSERROR_OK) {
GDLOG_FAILURE_NO(ret);
}
break;
}
default: {
GDLOGFE("code %{public}d cannot process", code);
return 1;
}
}
return 0;
}
GSError GraphicDumperServiceStub::AddClientListener(const std::string &tag,
sptr<IGraphicDumperClientListener> &listener)
{
if (listener == nullptr) {
return GSERROR_INVALID_ARGUMENTS;
}
return GraphicDumperServer::GetInstance()->AddConfigListener(tag, listener);
}
GSError GraphicDumperServiceStub::SendInfo(const std::string &tag, const std::string &info)
{
return GraphicDumperServer::GetInstance()->InfoHandle(tag, info);
}
} // namespace OHOS

View File

@ -78,7 +78,10 @@ ohos_shared_library("surface") {
"//commonlibrary/c_utils/base:utils_config", "//commonlibrary/c_utils/base:utils_config",
] ]
deps = [ "//foundation/graphic/graphic_2d/utils/sync_fence:sync_fence" ] deps = [
"//foundation/graphic/graphic_2d/utils/gslogger:libgslogger",
"//foundation/graphic/graphic_2d/utils/sync_fence:sync_fence",
]
public_deps = [ public_deps = [
"//commonlibrary/c_utils/base:utils", "//commonlibrary/c_utils/base:utils",

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.
*/
#include "egl_consumer_surface.h"
#include <gslogger.h>
namespace OHOS {
namespace {
DEFINE_HILOG_LABEL("MockEglConsumerSurface");
} // namespace
EglConsumerSurface::EglConsumerSurface(const std::string &name, bool isShared)
: ConsumerSurface(name, isShared)
{
GSLOG2HI(DEBUG) << "ctor";
}
EglConsumerSurface::~EglConsumerSurface()
{
GSLOG2HI(DEBUG) << "dtor";
}
GSError EglConsumerSurface::Init()
{
return GSERROR_NOT_SUPPORT;
}
GSError EglConsumerSurface::AcquireBuffer(sptr<SurfaceBuffer>& buffer, int32_t &fence,
int64_t &timestamp, Rect &damage)
{
return GSERROR_NOT_SUPPORT;
}
} // namespace OHOS

View File

@ -226,8 +226,6 @@ ohos_static_library("surface_test_common") {
"//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc",
"//foundation/graphic/graphic_2d:libnative_image", "//foundation/graphic/graphic_2d:libnative_image",
"//foundation/graphic/graphic_2d:libsurface", "//foundation/graphic/graphic_2d:libsurface",
"//foundation/graphic/graphic_2d/frameworks/opengl_wrapper:EGL",
"//foundation/graphic/graphic_2d/frameworks/opengl_wrapper:GLESv3",
"//foundation/graphic/graphic_2d/utils:buffer_handle", "//foundation/graphic/graphic_2d/utils:buffer_handle",
"//foundation/graphic/graphic_2d/utils:libgraphic_utils", "//foundation/graphic/graphic_2d/utils:libgraphic_utils",
"//foundation/graphic/graphic_2d/utils:sync_fence", "//foundation/graphic/graphic_2d/utils:sync_fence",

26
graphic.rc Normal file
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.
service graphic_dumper_server /system/bin/graphic_dumper_server
class weston
disabled
seclabel u:r:wms_service:s0
service bootanimation /system/bin/bootanimation
class weston
disabled
oneshot
on weston_start
start graphic_dumper_server
start bootanimation

View File

@ -33,6 +33,10 @@ group("promise") {
public_deps = [ "promise:promise" ] public_deps = [ "promise:promise" ]
} }
group("semaphore") {
public_deps = [ "semaphore:semaphore" ]
}
group("socketpair") { group("socketpair") {
public_deps = [ "socketpair:socketpair" ] public_deps = [ "socketpair:socketpair" ]
} }
@ -41,10 +45,34 @@ group("test_header") {
public_deps = [ "test_header:test_header" ] public_deps = [ "test_header:test_header" ]
} }
group("option_parser") {
public_deps = [ "option_parser:option_parser" ]
}
group("libgslogger") {
public_deps = [ "gslogger:libgslogger" ]
}
group("matrix") { group("matrix") {
public_deps = [ "matrix:matrix" ] public_deps = [ "matrix:matrix" ]
} }
group("raw_parser") {
public_deps = [ "raw_parser:raw_parser" ]
}
group("cpudraw") {
public_deps = [ "cpudraw:cpudraw" ]
}
group("gl_utils") {
public_deps = [ "gl_utils:gl_utils" ]
}
group("raw_maker") {
public_deps = [ "raw_maker:raw_maker" ]
}
group("sync_fence") { group("sync_fence") {
public_deps = [ "sync_fence:sync_fence" ] public_deps = [ "sync_fence:sync_fence" ]
} }
@ -65,9 +93,17 @@ ohos_shared_library("libgraphic_utils") {
public_deps = [ public_deps = [
"buffer_handle:buffer_handle", "buffer_handle:buffer_handle",
"color_manager:color_manager", "color_manager:color_manager",
"cpudraw:cpudraw",
"gl_utils:gl_utils",
"gslogger:libgslogger",
"matrix:matrix", "matrix:matrix",
"option_parser:option_parser",
"promise:promise", "promise:promise",
"raw_maker:raw_maker",
"raw_parser:raw_parser",
"sandbox:sandbox_utils", "sandbox:sandbox_utils",
"scoped_bytrace:scoped_bytrace",
"semaphore:semaphore",
"test_header:test_header", "test_header:test_header",
] ]

42
utils/cpudraw/BUILD.gn Normal file
View File

@ -0,0 +1,42 @@
# 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")
## Build cpudraw.a {{{
config("cpudraw_config") {
visibility = [ ":*" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("cpudraw_public_config") {
include_dirs = [ "export" ]
}
ohos_static_library("cpudraw") {
sources = [ "src/cpudraw.cpp" ]
configs = [ ":cpudraw_config" ]
public_configs = [ ":cpudraw_public_config" ]
deps = [ "..:scoped_bytrace" ]
subsystem_name = "graphic"
part_name = "graphic_standard"
}
## Build cpudraw.a }}}

View File

@ -0,0 +1,54 @@
/*
* 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 UTILS_INCLUDE_CPUDRAW_EXPORT_CPUDRAW_H
#define UTILS_INCLUDE_CPUDRAW_EXPORT_CPUDRAW_H
#include <cstdint>
struct CpudrawRect {
double x;
double y;
double w;
double h;
bool Contain(int32_t x2, int32_t y2);
};
class Cpudraw {
public:
Cpudraw(uint32_t *vaddr, int32_t width, int32_t height);
void SetColor(const uint32_t &color);
void SetBorder(const int32_t &border);
void DrawBorder(const int32_t &x, const int32_t &y, const int32_t &w, const int32_t &h);
void DrawBorder(const struct CpudrawRect &rect);
void DrawRect(const int32_t &x, const int32_t &y, const int32_t &w, const int32_t &h);
void DrawRect(const struct CpudrawRect &rect);
private:
int32_t Min(const int32_t &a, const int32_t &b);
int32_t Max(const int32_t &a, const int32_t &b);
uint32_t *addr = nullptr;
int32_t width = 0;
int32_t height = 0;
uint32_t color = 0xffffffff;
int32_t border = 0;
};
#endif // UTILS_INCLUDE_CPUDRAW_EXPORT_CPUDRAW_H

View File

@ -0,0 +1,77 @@
/*
* 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 "cpudraw.h"
#include <scoped_bytrace.h>
bool CpudrawRect::Contain(int32_t x2, int32_t y2)
{
return x <= x2 && x2 <= x + w && y <= y2 && y2 <= y + h;
}
Cpudraw::Cpudraw(uint32_t *vaddr, int32_t width, int32_t height)
: addr(vaddr), width(width), height(height)
{
}
void Cpudraw::SetColor(const uint32_t &color)
{
this->color = color;
}
void Cpudraw::SetBorder(const int32_t &border)
{
this->border = border;
}
void Cpudraw::DrawBorder(const struct CpudrawRect &rect)
{
DrawBorder(rect.x, rect.y, rect.w, rect.h);
}
void Cpudraw::DrawBorder(const int32_t &x, const int32_t &y, const int32_t &w, const int32_t &h)
{
ScopedBytrace trace(__func__);
DrawRect(x, y, border, h);
DrawRect(x + w - border, y, border, h);
DrawRect(x, y, w, border);
DrawRect(x, y + h - border, w, border);
}
void Cpudraw::DrawRect(const struct CpudrawRect &rect)
{
DrawRect(rect.x, rect.y, rect.w, rect.h);
}
void Cpudraw::DrawRect(const int32_t &x, const int32_t &y, const int32_t &w, const int32_t &h)
{
ScopedBytrace trace(__func__);
for (int32_t j = Max(y, 0); j < Min(y + h, height); j++) {
for (int32_t i = Max(x, 0); i < Min(x + w, width); i++) {
addr[j * width + i] = color;
}
}
}
int32_t Cpudraw::Min(const int32_t &a, const int32_t &b)
{
return a < b ? a : b;
}
int32_t Cpudraw::Max(const int32_t &a, const int32_t &b)
{
return a > b ? a : b;
}

64
utils/gl_utils/BUILD.gn Normal file
View File

@ -0,0 +1,64 @@
# 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("//foundation/graphic/graphic_2d/graphic_config.gni")
## Build gl_utils.a {{{
config("gl_utils_config") {
visibility = [ ":*" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
if (!ace_enable_gpu) {
cflags += [ "-Wno-unused-private-field" ]
}
}
config("gl_utils_public_config") {
include_dirs = [ "export" ]
}
ohos_static_library("gl_utils") {
sources = []
if (ace_enable_gpu) {
sources += [
"src/shader.cpp",
"src/texture.cpp",
]
} else {
sources += [
"src/mock/shader.cpp",
"src/mock/texture.cpp",
]
}
configs = [ ":gl_utils_config" ]
public_configs = [ ":gl_utils_public_config" ]
public_deps = [
"..:libgslogger",
"..:matrix",
"//foundation/graphic/graphic_2d:libgl",
]
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Build gl_utils.a }}}

View File

@ -0,0 +1,51 @@
/*
* 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 FRAMEWORKS_ANIMATION_SERVER_SERVER_INCLUDE_SHADER_H
#define FRAMEWORKS_ANIMATION_SERVER_SERVER_INCLUDE_SHADER_H
#include <cstdint>
#include <unordered_map>
#include <string>
#include <matrix.h>
class Shader {
public:
Shader(const std::string& vertexSource, const std::string& fragmentSource);
~Shader();
bool Available();
void Bind() const;
void Unbind() const;
void SetUniform1i(const std::string& name, int32_t v);
void SetUniform1f(const std::string& name, float v);
void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3);
void SetUniformMat4f(const std::string& name, const Matrix<float>& matrix);
int32_t GetAttribLocation(const std::string& name);
private:
int32_t GetUniformLocation(const std::string& name);
uint32_t CompileShader(uint32_t type, const std::string& source);
uint32_t CreateShader(const std::string& vertexShader, const std::string& fragmentShader);
uint32_t rendererID_ = 0;
std::unordered_map<std::string, int32_t> uniformLocationCache_;
};
#endif // FRAMEWORKS_ANIMATION_SERVER_SERVER_INCLUDE_SHADER_H

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.
*/
#ifndef FRAMEWORKS_ANIMATION_SERVER_SERVER_INCLUDE_TEXTURE_H
#define FRAMEWORKS_ANIMATION_SERVER_SERVER_INCLUDE_TEXTURE_H
#include <cstdint>
class Texture {
public:
// from buffer
Texture(void *buffer, int32_t width, int32_t height);
// from texture
Texture(uint32_t texture);
~Texture();
void Bind(uint32_t slot = 0) const;
void Unbind();
inline int32_t GetWidth() const
{
return width_;
}
inline int32_t GetHeight() const
{
return height_;
}
private:
uint32_t rendererID_ = 0;
void *buffer_ = nullptr;
int32_t width_ = 0;
int32_t height_ = 0;
};
#endif // FRAMEWORKS_ANIMATION_SERVER_SERVER_INCLUDE_TEXTURE_H

View File

@ -0,0 +1,73 @@
/*
* 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 "shader.h"
Shader::Shader(const std::string& vertexSource, const std::string& fragmentSource)
{
}
Shader::~Shader()
{
}
bool Shader::Available()
{
return false;
}
void Shader::Bind() const
{
}
void Shader::Unbind() const
{
}
void Shader::SetUniform1i(const std::string& name, int32_t v)
{
}
void Shader::SetUniform1f(const std::string& name, float v)
{
}
void Shader::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3)
{
}
void Shader::SetUniformMat4f(const std::string& name, const Matrix<float>& matrix)
{
}
int32_t Shader::GetAttribLocation(const std::string& name)
{
return -1;
}
int32_t Shader::GetUniformLocation(const std::string& name)
{
return -1;
}
uint32_t Shader::CompileShader(uint32_t type, const std::string& source)
{
return -1;
}
uint32_t Shader::CreateShader(const std::string& vertexShader, const std::string& fragmentShader)
{
return -1;
}

View File

@ -0,0 +1,37 @@
/*
* 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 "texture.h"
Texture::Texture(void *buffer, int32_t width, int32_t height)
: buffer_(buffer), width_(width), height_(height)
{
}
Texture::Texture(uint32_t texture)
{
}
Texture::~Texture()
{
}
void Texture::Bind(uint32_t slot) const
{
}
void Texture::Unbind()
{
}

View File

@ -0,0 +1,159 @@
/*
* 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 "shader.h"
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <gslogger.h>
namespace {
DEFINE_HILOG_LABEL("Shader");
} // namespace
Shader::Shader(const std::string& vertexSource, const std::string& fragmentSource)
{
rendererID_ = CreateShader(vertexSource, fragmentSource);
}
Shader::~Shader()
{
if (rendererID_ != 0) {
glDeleteProgram(rendererID_);
}
}
bool Shader::Available()
{
return rendererID_ != 0;
}
void Shader::Bind() const
{
glUseProgram(rendererID_);
}
void Shader::Unbind() const
{
glUseProgram(0);
}
void Shader::SetUniform1i(const std::string& name, int32_t v)
{
glUniform1i(GetUniformLocation(name), v);
}
void Shader::SetUniform1f(const std::string& name, float v)
{
glUniform1f(GetUniformLocation(name), v);
}
void Shader::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3)
{
glUniform4f(GetUniformLocation(name), v0, v1, v2, v3);
}
void Shader::SetUniformMat4f(const std::string& name, const Matrix<float>& matrix)
{
glUniformMatrix4fv(GetUniformLocation(name), 1, GL_FALSE, matrix);
}
int32_t Shader::GetAttribLocation(const std::string& name)
{
return glGetAttribLocation(rendererID_, name.c_str());
}
int32_t Shader::GetUniformLocation(const std::string& name)
{
if (uniformLocationCache_.find(name) != uniformLocationCache_.end()) {
return uniformLocationCache_[name];
}
auto location = glGetUniformLocation(rendererID_, name.c_str());
if (location == -1) {
GSLOG2HI(WARN) << "Warning: uniform '" << name << "' doesn't exist!" << std::endl;
}
uniformLocationCache_[name] = location;
return location;
}
uint32_t Shader::CompileShader(uint32_t type, const std::string& source)
{
auto id = glCreateShader(type);
auto src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
auto result = GL_FALSE;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE) {
int32_t length = 0;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
if (length < 0) {
GSLOG2HI(ERROR) << "CompileShader Failed length is not right";
return 0;
}
char* message = static_cast<char*>(malloc(length));
if (message == nullptr) {
GSLOG2HI(ERROR) << "CompileShader Failed malloc failed";
return 0;
}
glGetShaderInfoLog(id, length, &length, message);
GSLOG2HI(ERROR) << "CompileShader[" << type << "] Failed: " << message;
glDeleteShader(id);
free(message);
message = nullptr;
return 0;
}
return id;
}
uint32_t Shader::CreateShader(const std::string& vertexShader, const std::string& fragmentShader)
{
auto program = glCreateProgram();
auto vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
auto fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glDeleteShader(vs);
glDeleteShader(fs);
auto result = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &result);
if (result == GL_FALSE) {
int32_t length = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
if (length < 0) {
GSLOG2HI(ERROR) << "CreateShader Failed length is not right";
return 0;
}
char* message = static_cast<char*>(malloc(length));
if (message == nullptr) {
GSLOG2HI(ERROR) << "CreateShader Failed malloc failed";
return 0;
}
glGetProgramInfoLog(program, length, nullptr, message);
GSLOG2HI(ERROR) << "program error[" << glGetError() << "]: " << message;
free(message);
message = nullptr;
return 0;
}
GSLOG2HI(INFO) << "Shader create success " << program;
return program;
}

View File

@ -0,0 +1,58 @@
/*
* 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 "texture.h"
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <gslogger.h>
Texture::Texture(void *buffer, int32_t width, int32_t height)
: buffer_(buffer), width_(width), height_(height)
{
glGenTextures(1, &rendererID_);
glBindTexture(GL_TEXTURE_2D, rendererID_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, width_, height_, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer_);
}
Texture::Texture(uint32_t texture)
{
rendererID_ = texture;
}
Texture::~Texture()
{
glDeleteTextures(1, &rendererID_);
}
void Texture::Bind(uint32_t slot) const
{
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, rendererID_);
}
void Texture::Unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}

44
utils/gslogger/BUILD.gn Normal file
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.
import("//build/ohos.gni")
## Build libgslogger.a {{{
config("libgslogger_config") {
visibility = [ ":*" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("libgslogger_public_config") {
include_dirs = [ "export" ]
}
ohos_static_library("libgslogger") {
sources = [ "src/gslogger.cpp" ]
configs = [ ":libgslogger_config" ]
public_configs = [ ":libgslogger_public_config" ]
public_deps =
[ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog" ]
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Build libgslogger.a }}}

View File

@ -0,0 +1,161 @@
/*
* 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 UTILS_INCLUDE_LOGGER_EXPORT_GSLOGGER_H
#define UTILS_INCLUDE_LOGGER_EXPORT_GSLOGGER_H
#include <any>
#include <cstdarg>
#include <sstream>
#include <vector>
class Gslogger : public std::stringstream {
public:
enum class LOG_LEVEL { DEBUG, INFO, WARN, ERROR, FATAL };
enum class LOG_PHASE { BEGIN, END };
using GsloggerWrapperFunc = void(*)(Gslogger &, enum LOG_PHASE phase);
// output GsloggerWrapperFunc
static void Stdout(Gslogger &logger, enum LOG_PHASE phase);
static void Stderr(Gslogger &logger, enum LOG_PHASE phase);
static void Hilog(Gslogger &logger, enum LOG_PHASE phase);
static void FileLog(Gslogger &logger, enum LOG_PHASE phase);
// wrapper GsloggerWrapperFunc
static void Func(Gslogger &logger, enum LOG_PHASE phase); // 1
static void FuncLine(Gslogger &logger, enum LOG_PHASE phase); // 2
static void FileLine(Gslogger &logger, enum LOG_PHASE phase); // 3
static void FileFuncLine(Gslogger &logger, enum LOG_PHASE phase); // 4
static void PidTid(Gslogger &logger, enum LOG_PHASE phase); // +5
Gslogger(const std::string &file, const std::string &func, int line, enum LOG_LEVEL level, ...);
virtual ~Gslogger() override;
const std::string &GetFile() const;
const std::string &GetFunc() const;
int GetLine() const;
enum LOG_LEVEL GetLevel() const;
va_list &GetVariousArgument();
template<class T>
std::shared_ptr<T> GetData()
{
using sptrT = std::shared_ptr<T>;
sptrT ret = nullptr;
auto pRet = std::any_cast<sptrT>(&data_);
if (pRet != nullptr) {
ret = *pRet;
} else {
ret = std::make_shared<T>();
data_ = ret;
}
return ret;
}
private:
std::string file_;
std::string func_;
int line_;
enum LOG_LEVEL level_;
va_list vl_;
std::any data_;
std::vector<GsloggerWrapperFunc> wrappers_;
};
#define LOGGER_ARG(level) __FILE__, __func__, __LINE__, (Gslogger::LOG_LEVEL::level)
// hilog
#define DEFINE_HILOG_LABEL(str) \
namespace { constexpr const char *HILOG_LABEL = str; }
#define GSLOG0HI(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Hilog, HILOG_LABEL, NULL)
#define GSLOG1HI(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Func, Gslogger::Hilog, HILOG_LABEL, NULL)
#define GSLOG2HI(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FuncLine, Gslogger::Hilog, HILOG_LABEL, NULL)
#define GSLOG3HI(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileLine, Gslogger::Hilog, HILOG_LABEL, NULL)
#define GSLOG4HI(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileFuncLine, Gslogger::Hilog, HILOG_LABEL, NULL)
// stdout
#define GSLOG0SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Stdout, NULL)
#define GSLOG1SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Func, Gslogger::Stdout, NULL)
#define GSLOG2SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FuncLine, Gslogger::Stdout, NULL)
#define GSLOG3SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileLine, Gslogger::Stdout, NULL)
#define GSLOG4SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileFuncLine, Gslogger::Stdout, NULL)
#define GSLOG5SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::Stdout, NULL)
#define GSLOG6SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::Func, Gslogger::Stdout, NULL)
#define GSLOG7SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FuncLine, Gslogger::Stdout, NULL)
#define GSLOG8SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileLine, Gslogger::Stdout, NULL)
#define GSLOG9SO(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileFuncLine, Gslogger::Stdout, NULL)
// stderr
#define GSLOG0SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Stderr, NULL)
#define GSLOG1SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Func, Gslogger::Stderr, NULL)
#define GSLOG2SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FuncLine, Gslogger::Stderr, NULL)
#define GSLOG3SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileLine, Gslogger::Stderr, NULL)
#define GSLOG4SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileFuncLine, Gslogger::Stderr, NULL)
#define GSLOG5SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::Stderr, NULL)
#define GSLOG6SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::Func, Gslogger::Stderr, NULL)
#define GSLOG7SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FuncLine, Gslogger::Stderr, NULL)
#define GSLOG8SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileLine, Gslogger::Stderr, NULL)
#define GSLOG9SE(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileFuncLine, Gslogger::Stderr, NULL)
// filelog
#define DEFINE_FILE_LABEL(str) \
namespace { constexpr const char *FILE_LABEL = str; }
#define GSLOG0F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG1F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::Func, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG2F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FuncLine, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG3F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileLine, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG4F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::FileFuncLine, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG5F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG6F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::Func, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG7F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FuncLine, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG8F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileLine, Gslogger::FileLog, FILE_LABEL, NULL)
#define GSLOG9F(level) Gslogger(LOGGER_ARG(level), \
Gslogger::PidTid, Gslogger::FileFuncLine, Gslogger::FileLog, FILE_LABEL, NULL)
#endif // UTILS_INCLUDE_LOGGER_EXPORT_GSLOGGER_H

View File

@ -0,0 +1,206 @@
/*
* 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 "gslogger.h"
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <hilog/log.h>
namespace {
const char *GetLevelStr(enum Gslogger::LOG_LEVEL level)
{
switch (level) {
case Gslogger::LOG_LEVEL::DEBUG: return "D";
case Gslogger::LOG_LEVEL::INFO: return "I";
case Gslogger::LOG_LEVEL::WARN: return "W";
case Gslogger::LOG_LEVEL::ERROR: return "E";
case Gslogger::LOG_LEVEL::FATAL: return "F";
}
return "?";
}
} // namespace
void Gslogger::Stdout(Gslogger& logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
return;
}
// LOG_PHASE::END
std::cout << "[" << GetLevelStr(logger.GetLevel()) << "] " << logger.str() << std::endl;
}
void Gslogger::Stderr(Gslogger& logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
return;
}
// LOG_PHASE::END
std::cerr << "[" << GetLevelStr(logger.GetLevel()) << "] " << logger.str() << std::endl;
}
void Gslogger::Hilog(Gslogger& logger, enum LOG_PHASE phase)
{
struct HilogData {
OHOS::HiviewDFX::HiLogLabel hiLogLabel;
};
auto data = logger.GetData<struct HilogData>();
if (phase == LOG_PHASE::BEGIN) {
auto label = va_arg(logger.GetVariousArgument(), const char *);
data->hiLogLabel = { LOG_CORE, 0, label };
return;
}
// LOG_PHASE::END
auto fn = OHOS::HiviewDFX::HiLog::Debug;
switch (logger.GetLevel()) {
case LOG_LEVEL::DEBUG:
fn = OHOS::HiviewDFX::HiLog::Debug;
break;
case LOG_LEVEL::INFO:
fn = OHOS::HiviewDFX::HiLog::Info;
break;
case LOG_LEVEL::WARN:
fn = OHOS::HiviewDFX::HiLog::Warn;
break;
case LOG_LEVEL::ERROR:
fn = OHOS::HiviewDFX::HiLog::Error;
break;
case LOG_LEVEL::FATAL:
fn = OHOS::HiviewDFX::HiLog::Fatal;
break;
}
fn(data->hiLogLabel, "%{public}s", logger.str().c_str());
}
void Gslogger::FileLog(Gslogger& logger, enum LOG_PHASE phase)
{
struct FileLogData {
const char *filename;
};
auto data = logger.GetData<struct FileLogData>();
if (phase == LOG_PHASE::BEGIN) {
auto filename = va_arg(logger.GetVariousArgument(), const char *);
data->filename = filename;
return;
}
char path[PATH_MAX + 1] = { 0x00 };
if (strlen(data->filename) > PATH_MAX || realpath(data->filename, path) == NULL) {
std::cerr << "File path error!" << std::endl;
return;
}
// LOG_PHASE::END
std::ofstream ofs(path, std::ofstream::out | std::ofstream::app);
if (!ofs) {
// open failed, errno
return;
}
if (ofs) {
ofs << "[" << GetLevelStr(logger.GetLevel()) << "] " << logger.str() << std::endl;
}
}
void Gslogger::Func(Gslogger& logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
logger << "[" << logger.GetFunc() << "] ";
}
}
void Gslogger::FuncLine(Gslogger& logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
logger << "[" << logger.GetFunc() << ":" << logger.GetLine() << "] ";
}
}
void Gslogger::FileLine(Gslogger& logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
logger << "[" << logger.GetFile() << " +" << logger.GetLine() << "] ";
}
}
void Gslogger::FileFuncLine(Gslogger& logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
logger << "[" << logger.GetFile() << " +" << logger.GetLine() << ":" << logger.GetFunc() << "] ";
}
}
void Gslogger::PidTid(Gslogger &logger, enum LOG_PHASE phase)
{
if (phase == LOG_PHASE::BEGIN) {
logger << "[" << getpid() << "][" << gettid() << "]";
}
}
Gslogger::Gslogger(const std::string &file, const std::string &func, int line, enum LOG_LEVEL level, ...)
{
file_ = file;
func_ = func;
line_ = line;
level_ = level;
va_start(vl_, level);
while (true) {
GsloggerWrapperFunc f = va_arg(vl_, GsloggerWrapperFunc);
if (f == nullptr) {
break;
}
f(*this, LOG_PHASE::BEGIN);
wrappers_.push_back(f);
}
}
Gslogger::~Gslogger()
{
for (const auto &wrapper : wrappers_) {
wrapper(*this, LOG_PHASE::END);
}
}
const std::string &Gslogger::GetFile() const
{
return file_;
}
const std::string &Gslogger::GetFunc() const
{
return func_;
}
int Gslogger::GetLine() const
{
return line_;
}
enum Gslogger::LOG_LEVEL Gslogger::GetLevel() const
{
return level_;
}
va_list &Gslogger::GetVariousArgument()
{
return vl_;
}

View File

@ -0,0 +1,41 @@
# 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")
## Build option_parser.a {{{
config("option_parser_config") {
visibility = [ ":*" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("option_parser_public_config") {
include_dirs = [ "export" ]
}
ohos_static_library("option_parser") {
sources = [ "src/option_parser.cpp" ]
configs = [ ":option_parser_config" ]
public_configs = [ ":option_parser_public_config" ]
subsystem_name = "graphic"
part_name = "graphic_standard"
}
## Build option_parser.a }}}

View File

@ -0,0 +1,166 @@
/*
* 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 UTILS_OPTION_PARSER_EXPORT_OPTION_PARSER_H
#define UTILS_OPTION_PARSER_EXPORT_OPTION_PARSER_H
#include <list>
#include <string>
#include <vector>
class OptionParser {
public:
int32_t Parse(int32_t argc, const char **argv);
std::string GetErrorString();
template<typename T>
int32_t AddOption(const std::string &shortOpt, const std::string &longOpt, T &result)
{
return 0;
}
template<>
int32_t AddOption<int32_t>(const std::string &shortOpt, const std::string &longOpt, int32_t &result)
{
return AddOption(shortOpt, longOpt, &result, Option::ValueType::i32);
}
template<>
int32_t AddOption<uint32_t>(const std::string &shortOpt, const std::string &longOpt, uint32_t &result)
{
return AddOption(shortOpt, longOpt, &result, Option::ValueType::u32);
}
template<>
int32_t AddOption<int64_t>(const std::string &shortOpt, const std::string &longOpt, int64_t &result)
{
return AddOption(shortOpt, longOpt, &result, Option::ValueType::i64);
}
template<>
int32_t AddOption<double>(const std::string &shortOpt, const std::string &longOpt, double &result)
{
return AddOption(shortOpt, longOpt, &result, Option::ValueType::f64);
}
template<>
int32_t AddOption<std::string>(const std::string &shortOpt, const std::string &longOpt, std::string &result)
{
return AddOption(shortOpt, longOpt, &result, Option::ValueType::str);
}
template<>
int32_t AddOption<bool>(const std::string &shortOpt, const std::string &longOpt, bool &result)
{
return AddOption(shortOpt, longOpt, &result, Option::ValueType::bol);
}
template<typename T>
int32_t AddArguments(T &result)
{
return 0;
}
template<>
int32_t AddArguments<int32_t>(int32_t &result)
{
return AddArguments(&result, Argument::ValueType::i32);
}
template<>
int32_t AddArguments<uint32_t>(uint32_t &result)
{
return AddArguments(&result, Argument::ValueType::u32);
}
template<>
int32_t AddArguments<int64_t>(int64_t &result)
{
return AddArguments(&result, Argument::ValueType::i64);
}
template<>
int32_t AddArguments<double>(double &result)
{
return AddArguments(&result, Argument::ValueType::f64);
}
template<>
int32_t AddArguments<std::string>(std::string &result)
{
return AddArguments(&result, Argument::ValueType::str);
}
int32_t GetSkippedArgc();
const char **GetSkippedArgv();
private:
int32_t ParseArgument(const char *arg, const char *arg2);
int32_t ParseArgc(const char *arg, const char *arg2);
int32_t ParseShortOption(const char *arg1, const char *arg2);
int32_t ParseLongEqualOption(const char *arg, const char *arg2);
int32_t ParseLongOption(const char *arg1, const char *arg2);
int32_t AddSkipped(const char *arg, const char *arg2);
struct Option {
const std::string so;
const std::string lo;
union Value {
int32_t i32;
uint32_t u32;
int64_t i64;
double f64;
std::string str;
bool bl;
} *result;
enum class ValueType {
i32,
u32,
i64,
f64,
str,
bol,
} type;
};
int32_t AddOption(const std::string &shortOpt,
const std::string &longOpt, void *result, Option::ValueType type);
struct Argument {
union Value {
int32_t i32;
uint32_t u32;
int64_t i64;
double f64;
std::string str;
} *result;
enum class ValueType {
i32,
u32,
i64,
f64,
str,
} type;
};
int32_t AddArguments(void *result, Argument::ValueType type);
std::list<struct Argument> arguments;
std::vector<struct Option> options;
std::vector<const char *> skipped;
std::string error = "";
};
#endif // UTILS_OPTION_PARSER_EXPORT_OPTION_PARSER_H

View File

@ -0,0 +1,282 @@
/*
* 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 <option_parser.h>
#include <iomanip>
#include <sstream>
enum {
PARSER_NEXT = 0,
PARSER_ERROR = 1,
PARSER_PARSED = 2,
PARSER_PARSED_MORE = 3,
};
int32_t OptionParser::ParseArgument(const char *arg, const char *arg2)
{
if (arguments.empty()) {
return PARSER_NEXT;
}
std::stringstream ss(arg);
switch (arguments.front().type) {
case Argument::ValueType::i32:
ss >> std::setbase(0) >> arguments.front().result->i32;
break;
case Argument::ValueType::u32:
ss >> std::setbase(0) >> arguments.front().result->u32;
break;
case Argument::ValueType::i64:
ss >> std::setbase(0) >> arguments.front().result->i64;
break;
case Argument::ValueType::f64:
ss >> arguments.front().result->f64;
break;
case Argument::ValueType::str:
ss >> arguments.front().result->str;
break;
}
if (!ss.eof() || !ss) {
error = "parse ";
error = error + arg + " error";
return PARSER_ERROR;
}
arguments.pop_front();
return PARSER_PARSED;
}
int32_t OptionParser::ParseArgc(const char *arg, const char *arg2)
{
if (arg[0] == 0) {
return PARSER_ERROR;
}
if (arg[0] != '-') {
skipped.push_back(arg);
return PARSER_PARSED;
}
if (arg[1] == 0) {
return PARSER_ERROR;
}
return PARSER_NEXT;
}
int32_t OptionParser::ParseShortOption(const char *arg1, const char *arg2)
{
if (arg1[1] == '-') {
// long option
return PARSER_NEXT;
}
for (const auto &option : options) {
if (option.so == &arg1[1]) {
if (option.type == Option::ValueType::bol) {
option.result->bl = !option.result->bl;
return PARSER_PARSED;
} else if (arg2 == nullptr) {
error = option.so + " need argument";
return PARSER_ERROR;
}
std::stringstream ss(arg2);
switch (option.type) {
case Option::ValueType::i32:
ss >> std::setbase(0) >> option.result->i32;
break;
case Option::ValueType::u32:
ss >> std::setbase(0) >> option.result->u32;
break;
case Option::ValueType::i64:
ss >> std::setbase(0) >> option.result->i64;
break;
case Option::ValueType::f64:
ss >> option.result->f64;
break;
case Option::ValueType::str:
ss >> option.result->str;
break;
default:
break;
}
if (!ss.eof() || !ss) {
error = "parse ";
error = error + arg1 + " error, " + arg2;
return PARSER_ERROR;
}
return PARSER_PARSED_MORE;
}
}
return PARSER_NEXT;
}
int32_t OptionParser::ParseLongEqualOption(const char *arg, const char *arg2)
{
if (arg[1] != '-') {
return PARSER_NEXT;
}
int32_t ret = 0;
bool parsed = false;
for (const char *c = arg; *c; c++) {
if (*c == '=') {
std::string arg1(arg, c - arg);
std::string arg2(c + 1);
ret = ParseLongOption(arg1.c_str(), arg2.c_str());
parsed = true;
break;
}
}
if (ret == PARSER_ERROR || ret == PARSER_NEXT) {
return ret;
}
if (parsed) {
return PARSER_PARSED;
}
return PARSER_NEXT;
}
int32_t OptionParser::ParseLongOption(const char *arg1, const char *arg2)
{
if (arg1[1] != '-') {
return PARSER_NEXT;
}
for (const auto &option : options) {
if (option.lo == &arg1[0x2]) {
if (option.type == Option::ValueType::bol) {
option.result->bl = !option.result->bl;
return PARSER_PARSED;
} else if (arg2 == nullptr) {
error = option.lo + " need argument";
return PARSER_ERROR;
}
std::stringstream ss(arg2);
switch (option.type) {
case Option::ValueType::i32:
ss >> std::setbase(0) >> option.result->i32;
break;
case Option::ValueType::u32:
ss >> std::setbase(0) >> option.result->u32;
break;
case Option::ValueType::i64:
ss >> std::setbase(0) >> option.result->i64;
break;
case Option::ValueType::f64:
ss >> option.result->f64;
break;
case Option::ValueType::str:
ss >> option.result->str;
break;
default:
break;
}
if (!ss.eof() || !ss) {
error = "parse ";
error = error + arg1 + " error, " + arg2;
return PARSER_ERROR;
}
return PARSER_PARSED_MORE;
}
}
return PARSER_NEXT;
}
int32_t OptionParser::AddSkipped(const char *arg, const char *arg2)
{
skipped.push_back(arg);
return PARSER_PARSED;
}
int32_t OptionParser::Parse(int32_t argc, const char **argv)
{
int32_t (OptionParser:: *parsers[])(const char *, const char *) = {
&OptionParser::ParseArgument,
&OptionParser::ParseArgc,
&OptionParser::ParseShortOption,
&OptionParser::ParseLongEqualOption,
&OptionParser::ParseLongOption,
&OptionParser::AddSkipped,
};
for (int32_t i = 0; i < argc; i++) {
for (auto &parser : parsers) {
auto ret = (this->*parser)(argv[i], argv[i + 1]);
if (ret == PARSER_ERROR) {
return ret;
} else if (ret == PARSER_PARSED_MORE) {
i++;
break;
} else if (ret == PARSER_PARSED) {
break;
}
}
}
if (!arguments.empty()) {
error = "need more arguments";
return 1;
} else {
skipped.push_back(nullptr);
}
return 0;
}
int32_t OptionParser::AddOption(const std::string &shortOpt,
const std::string &longOpt, void *result, Option::ValueType type)
{
struct Option option = {
.so = shortOpt,
.lo = longOpt,
.result = reinterpret_cast<union Option::Value *>(result),
.type = type,
};
options.emplace_back(std::move(option));
return 0;
}
int32_t OptionParser::AddArguments(void *result, Argument::ValueType type)
{
struct Argument argument = {
.result = reinterpret_cast<union Argument::Value *>(result),
.type = type,
};
arguments.emplace_back(std::move(argument));
return 0;
}
std::string OptionParser::GetErrorString()
{
return error;
}
int32_t OptionParser::GetSkippedArgc()
{
return skipped.size() - 1;
}
const char **OptionParser::GetSkippedArgv()
{
return skipped.data();
}

50
utils/raw_maker/BUILD.gn Normal file
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")
## Build raw_maker.a {{{
config("raw_maker_config") {
visibility = [ ":*" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("raw_maker_public_config") {
include_dirs = [
"export",
"../raw_parser/export",
]
}
ohos_static_library("raw_maker") {
sources = [ "src/raw_maker.cpp" ]
configs = [ ":raw_maker_config" ]
public_configs = [ ":raw_maker_public_config" ]
deps = [
"..:libgslogger",
"//third_party/zlib:libz",
]
subsystem_name = "graphic"
part_name = "graphic_standard"
external_deps = [ "c_utils:utils" ]
}
## Build raw_maker.a }}}

View File

@ -0,0 +1,64 @@
/*
* 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 FRAMEWORKS_BOOTANIMATION_INCLUDE_RAW_MAKER_H
#define FRAMEWORKS_BOOTANIMATION_INCLUDE_RAW_MAKER_H
#include <raw_parser.h>
#include <memory>
#include <fstream>
#include <string>
namespace OHOS {
class RawMaker {
public:
void SetFilename(const std::string &filename);
void SetWidth(uint32_t width);
void SetHeight(uint32_t height);
void SetHeaderType(RawHeaderType type);
int32_t WriteNextData(const uint8_t *addr);
private:
int32_t DoFirstFrame();
int32_t PrepareInNone();
int32_t PrepareInRaw(const uint8_t *addr);
int32_t PrepareInCompress(const uint8_t *addr);
int32_t UpdateLastFrame(const uint8_t *addr);
int32_t WriteData();
void WriteInt32(int32_t integer);
void CompareWithLastFrame(const uint8_t *addr);
std::string filename = "";
uint32_t width = 0;
uint32_t height = 0;
int32_t size = 0;
RawHeaderType type = RAW_HEADER_TYPE_NONE;
bool firstFrame = true;
std::ofstream ofs;
std::unique_ptr<uint8_t[]> lastFrame;
std::unique_ptr<uint8_t[]> compressed;
struct {
RawHeaderType type;
int32_t offset;
int32_t length;
int32_t compressedLength;
const uint8_t *data;
} writing;
};
} // namespace OHOS
#endif // FRAMEWORKS_BOOTANIMATION_INCLUDE_RAW_MAKER_H

View File

@ -0,0 +1,212 @@
/*
* 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 "raw_maker.h"
#include <cerrno>
#include <string>
#include <gslogger.h>
#include <securec.h>
#include <zlib.h>
namespace OHOS {
namespace {
DEFINE_HILOG_LABEL("RawMaker");
} // namespace
void RawMaker::SetFilename(const std::string &filename)
{
if (firstFrame) {
this->filename = filename;
}
if (this->filename != filename) {
GSLOG2HI(ERROR) << "RawMaker::SetFilename now filename is different to first frame filename";
}
}
void RawMaker::SetWidth(uint32_t width)
{
if (firstFrame) {
this->width = width;
}
if (this->width != width) {
GSLOG2HI(ERROR) << "RawMaker::SetWidth now width is different to first frame width";
}
size = static_cast<int32_t>(width * height * 0x4);
}
void RawMaker::SetHeight(uint32_t height)
{
if (firstFrame) {
this->height = height;
}
if (this->height != height) {
GSLOG2HI(ERROR) << "RawMaker::SetHeight now height is different to first frame height";
}
size = static_cast<int32_t>(width * height * 0x4);
}
void RawMaker::SetHeaderType(RawHeaderType type)
{
this->type = type;
if (type != RAW_HEADER_TYPE_NONE) {
GSLOG2HI(ERROR) << "RawMaker::SetHeaderType now type is not RAW_HEADER_TYPE_NONE";
}
}
int32_t RawMaker::WriteNextData(const uint8_t *addr)
{
int32_t ret = 0;
if (firstFrame) {
ret = DoFirstFrame();
writing.offset = 0;
writing.length = size;
} else {
CompareWithLastFrame(addr);
}
ofs.open(filename, std::ofstream::app | std::ofstream::binary | std::ofstream::out);
if (errno) {
GSLOG2HI(ERROR) << "open " << filename << ", because " << strerror(errno);
return errno;
}
if (writing.length == 0) {
ret = PrepareInNone();
} else if (type == RAW_HEADER_TYPE_RAW) {
ret = PrepareInRaw(addr);
} else if (type == RAW_HEADER_TYPE_COMPRESSED) {
ret = PrepareInCompress(addr);
}
if (ret) {
GSLOG2SO(ERROR) << "failed at prepare";
ofs.close();
return ret;
}
WriteData();
ofs.close();
return 0;
}
int32_t RawMaker::PrepareInNone()
{
writing.type = RAW_HEADER_TYPE_NONE;
writing.offset = 0;
writing.length = 0;
writing.compressedLength = 0;
writing.data = nullptr;
return 0;
}
int32_t RawMaker::PrepareInRaw(const uint8_t *addr)
{
writing.type = RAW_HEADER_TYPE_RAW;
writing.compressedLength = writing.length;
writing.data = addr + writing.offset;
return UpdateLastFrame(addr);
}
int32_t RawMaker::PrepareInCompress(const uint8_t *addr)
{
writing.type = RAW_HEADER_TYPE_COMPRESSED;
uLongf clen = compressBound(writing.length);
compressed = std::make_unique<uint8_t[]>(clen);
auto ret = compress(compressed.get(), &clen, addr + writing.offset, writing.length);
if (ret != Z_OK) {
GSLOG2HI(ERROR) << "compress failed with " << ret;
return ret;
}
writing.compressedLength = static_cast<int32_t>(clen);
writing.data = compressed.get();
return UpdateLastFrame(addr);
}
int32_t RawMaker::UpdateLastFrame(const uint8_t *addr)
{
auto dst = lastFrame.get() + writing.offset;
auto dstlen = size - writing.offset;
auto src = writing.data;
auto srclen = writing.length;
auto ret = memcpy_s(dst, dstlen, src, srclen);
if (ret) {
GSLOG2HI(ERROR) << "memcpy_s failed with <" << strerror(errno) << ">"
<< ", params: " << "dstlen(" << dstlen << "), srclen(" << srclen << ")";
return ret;
}
return 0;
}
int32_t RawMaker::WriteData()
{
WriteInt32(writing.type);
WriteInt32(writing.offset);
WriteInt32(writing.length);
WriteInt32(writing.compressedLength);
ofs.write(reinterpret_cast<const char *>(writing.data), writing.compressedLength);
int32_t align = writing.compressedLength % 0x4;
while (align) {
align = (align + 1) % 0x4;
ofs.write("\0", 1);
}
return 0;
}
void RawMaker::WriteInt32(int32_t integer)
{
ofs.write(reinterpret_cast<const char *>(&integer), sizeof(integer));
}
void RawMaker::CompareWithLastFrame(const uint8_t *addr)
{
writing.length = 0;
writing.offset = size;
for (int32_t i = 0; i < size; i++) {
if (addr[i] != lastFrame[i]) {
writing.offset = i;
break;
}
}
for (int32_t i = size - 1; i >= writing.offset; i++) {
if (addr[i] != lastFrame[i]) {
writing.length = i - writing.offset + 1;
break;
}
}
}
int32_t RawMaker::DoFirstFrame()
{
firstFrame = false;
ofs.open(filename, std::ofstream::trunc | std::ofstream::binary | std::ofstream::out);
if (errno) {
GSLOG2HI(ERROR) << "open " << filename << ", because " << strerror(errno);
return errno;
}
lastFrame = std::make_unique<uint8_t[]>(static_cast<uint32_t>(size));
ofs.write("RAW.dif2", 0x8);
WriteInt32(static_cast<int32_t>(width));
WriteInt32(height);
ofs.close();
return 0;
}
} // namespace OHOS

47
utils/raw_parser/BUILD.gn Normal file
View File

@ -0,0 +1,47 @@
# 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")
## Build raw_parser.a {{{
config("raw_parser_config") {
visibility = [ ":*" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("raw_parser_public_config") {
include_dirs = [ "export" ]
}
ohos_static_library("raw_parser") {
sources = [ "src/raw_parser.cpp" ]
configs = [ ":raw_parser_config" ]
public_configs = [ ":raw_parser_public_config" ]
deps = [
"..:libgslogger",
"//third_party/zlib:libz",
]
subsystem_name = "graphic"
part_name = "graphic_standard"
external_deps = [ "c_utils:utils" ]
}
## Build raw_parser.a }}}

View File

@ -0,0 +1,132 @@
#!/bin/bash
# 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.
set -e
GENERATE_RAW=raw.raw
# put jpg
# bash generate_raw.sh <width> <height>
declare -A HEADER_TYPE=(
[NONE]=0
[RAW]=1
[COMPRESSED]=2
)
echo_int32_t_to_bin()
{
local int32_t=$1
local big_endian=$(printf "%08x" $int32_t)
local little_endian=${big_endian:6:2}${big_endian:4:2}${big_endian:2:2}${big_endian:0:2}
echo "0: $little_endian" | xxd -r
}
get_file_size()
{
local filename=$1
du -b $filename | awk '{print $1}'
}
echo_file_part()
{
local filename=$1
local position=$2
local length=$3
xxd -l $length -s $position -o $((-$position)) $filename | xxd -r
}
main()
{
local width=$1
local height=$2
ls * | while read filename; do
# check mime type
file $filename | grep "image" >/dev/null 2>&1
if [ $? != 0 ]; then
continue
fi
# generate raw data
convert $filename $filename.rgba
xxd -c 1 $filename.rgba > $filename.xxd
ofilename=$filename.rgba
if [ "$last_filename" = "" ]; then
# first image
header_type=${HEADER_TYPE["RAW"]}
position=0
length="$(get_file_size $ofilename)"
else
# damage range
result="$(diff -y $filename.xxd $last_filename.xxd | grep " |$(echo -e "\x09")")"
if [ "$result" = "" ]; then
header_type=${HEADER_TYPE["NONE"]}
position=0
length=0
else
header_type=${HEADER_TYPE["RAW"]}
position="$(printf "%d\n" 0x$(echo "$result" | head -1 | awk '{print $1}' | cut -d: -f1))"
length="$(printf "%d\n" 0x$(echo "$result" | tail -1 | awk '{print $1}' | cut -d: -f1))"
((length -= ${position}))
((length = $length / 4 * 4))
fi
fi
# compress
clen=$length
if [ "$header_type" = "${HEADER_TYPE["RAW"]}" ]; then
header_type=${HEADER_TYPE["COMPRESSED"]}
ofilename=$filename.compress
echo_file_part $filename.rgba $position $length | zlib-flate -compress=9 > $ofilename
clen=$(get_file_size $ofilename)
else
if [ "$header_type" = "${HEADER_TYPE["NONE"]}" ]; then
clen=0
fi
fi
if [ "$last_filename" = "" ]; then
echo -en "RAW.dif2" > $GENERATE_RAW
echo_int32_t_to_bin $width >> $GENERATE_RAW
echo_int32_t_to_bin $height >> $GENERATE_RAW
fi
echo_int32_t_to_bin $header_type >> $GENERATE_RAW
echo_int32_t_to_bin $position >> $GENERATE_RAW
echo_int32_t_to_bin $length >> $GENERATE_RAW
echo_int32_t_to_bin $clen >> $GENERATE_RAW
echo_file_part $ofilename 0 $clen >> $GENERATE_RAW
# for BUS_ADRALN
(( align = $clen - $clen / 4 * 4 ))
[ "$align" != "0" ] && (( align = 4 - $align ))
[ "$align" != "0" ] && echo -en "\x00" >> $GENERATE_RAW && (( align-- ))
[ "$align" != "0" ] && echo -en "\x00" >> $GENERATE_RAW && (( align-- ))
[ "$align" != "0" ] && echo -en "\x00" >> $GENERATE_RAW && (( align-- ))
echo $filename $header_type $position $length $clen
last_filename=$filename
done
rm -f *.rgba
rm -f *.xxd
rm -f *.compress
return 0
}
main $*
exit $?

View File

@ -0,0 +1,103 @@
/*
* 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 FRAMEWORKS_BOOTANIMATION_INCLUDE_RAW_PARSER_H
#define FRAMEWORKS_BOOTANIMATION_INCLUDE_RAW_PARSER_H
#include <memory>
#include <string>
#include <vector>
namespace OHOS {
enum RawHeaderType {
RAW_HEADER_TYPE_NONE,
RAW_HEADER_TYPE_RAW,
RAW_HEADER_TYPE_COMPRESSED,
};
struct RawFrameInfoPtr {
enum RawHeaderType type;
uint32_t offset;
uint32_t length;
uint32_t clen;
uint8_t *mem;
};
struct RawHeaderInfo {
char magic[8];
uint32_t width;
uint32_t height;
};
struct RawFrameInfo {
enum RawHeaderType type;
uint32_t offset;
uint32_t length;
uint32_t clen;
uint8_t mem[0];
};
class RawParser {
public:
// 0 for success
int32_t Parse(const std::string &file);
uint32_t GetWidth() const
{
return width;
}
uint32_t GetHeight() const
{
return height;
}
uint32_t GetSize() const
{
return width * height * 0x4;
}
int32_t GetCount() const
{
return infos.size();
}
// 0 for success
int32_t GetNextData(uint32_t *addr);
int32_t GetNowData(uint32_t *addr);
private:
int32_t ReadFile(const std::string &file, std::unique_ptr<uint8_t[]> &ptr);
// 0 for success
int32_t Uncompress(std::unique_ptr<uint8_t[]> &dst, uint32_t dstlen, uint8_t *cmem, uint32_t clen);
std::unique_ptr<uint8_t[]> compressed = nullptr;
uint32_t clength = 0;
std::vector<struct RawFrameInfoPtr> infos;
std::unique_ptr<uint8_t[]> uncompressed = nullptr;
int32_t lastID = -1;
std::unique_ptr<uint8_t[]> lastData = nullptr;
uint32_t width = 0;
uint32_t height = 0;
static constexpr int32_t magicHeaderLength = 16;
};
} // namespace OHOS
#endif // FRAMEWORKS_BOOTANIMATION_INCLUDE_RAW_PARSER_H

View File

@ -0,0 +1,162 @@
/*
* 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 "raw_parser.h"
#include <cstdio>
#include <fstream>
#include <gslogger.h>
#include <mutex>
#include <securec.h>
#include <sstream>
#include <zlib.h>
namespace OHOS {
namespace {
DEFINE_HILOG_LABEL("RawParser");
} // namespace
int32_t RawParser::Parse(const std::string &file)
{
int32_t ret = ReadFile(file, compressed);
if (ret) {
GSLOG2HI(ERROR) << "ReadFile failed with" << ret;
return ret;
}
auto minfo = reinterpret_cast<struct RawHeaderInfo*>(&compressed[0]);
if (strncmp(minfo->magic, "RAW.dif2", 0x8) != 0) {
GSLOG2HI(ERROR) << "magic header mistake, is " << minfo->magic;
return -1;
}
width = minfo->width;
height = minfo->height;
lastData = std::make_unique<uint8_t[]>(GetSize());
struct RawFrameInfo *info = reinterpret_cast<struct RawFrameInfo *>(&compressed[magicHeaderLength]);
uint32_t ipos = reinterpret_cast<uint8_t *>(info) - reinterpret_cast<uint8_t *>(minfo);
while (ipos < clength) {
GSLOG2HI(DEBUG) << info->type << ", " << info->offset << ", " << info->length << ", " << info->clen;
if (info->clen < 0) {
GSLOG2HI(ERROR) << "clen < 0";
return -1;
}
struct RawFrameInfoPtr zi = { info->type, info->offset, info->length, info->clen, info->mem };
infos.push_back(zi);
// for BUS_ADRALN
constexpr uint32_t memalign = 4;
uint32_t align = info->clen - info->clen / memalign * memalign;
if (align) {
align = memalign - align;
}
info = reinterpret_cast<struct RawFrameInfo *>(info->mem + info->clen + align);
ipos = reinterpret_cast<uint8_t *>(info) - reinterpret_cast<uint8_t *>(minfo);
}
if (infos.empty()) {
GSLOG2HI(ERROR) << "infos is empty";
return -1;
}
return 0;
}
int32_t RawParser::GetNextData(uint32_t *addr)
{
const int32_t count = (lastID + 1) % static_cast<int32_t>(infos.size());
if (count < 0) {
GSLOG2HI(ERROR) << "current count < 0";
return -1;
}
auto type = infos[count].type;
if (type == RAW_HEADER_TYPE_NONE) {
lastID = count;
return GetNowData(addr);
}
auto offset = infos[count].offset;
auto length = infos[count].length;
auto clen = infos[count].clen;
if (type == RAW_HEADER_TYPE_COMPRESSED) {
if (length == 0) {
GSLOG2HI(INFO) << "length == 0";
lastID = count;
return GetNowData(addr);
}
uncompressed = std::make_unique<uint8_t[]>(length);
int32_t ret = Uncompress(uncompressed, length, infos[count].mem, clen);
if (ret) {
GSLOG2HI(ERROR) << "uncompress failed";
return -1;
}
} else if (type == RAW_HEADER_TYPE_RAW) {
uncompressed = std::make_unique<uint8_t[]>(length);
if (memcpy_s(uncompressed.get(), length, infos[count].mem, clen)) {
GSLOG2HI(ERROR) << "memcpy failed";
return -1;
}
}
lastID = count;
if (length > 0 && memcpy_s(lastData.get() + offset, GetSize() - offset,
uncompressed.get(), length) != EOK) {
GSLOG2HI(ERROR) << "memcpy failed";
return -1;
}
return GetNowData(addr);
}
int32_t RawParser::GetNowData(uint32_t *addr)
{
if (memcpy_s(addr, GetSize(), lastData.get(), GetSize()) != EOK) {
GSLOG2HI(ERROR) << "memcpy failed";
return -1;
}
return 0;
}
int32_t RawParser::ReadFile(const std::string &file, std::unique_ptr<uint8_t[]> &ptr)
{
std::ifstream ifs(file, std::ifstream::in | std::ifstream::binary);
if (!ifs.good()) {
GSLOG2HI(ERROR) << "read file failed";
return 1;
}
ifs.seekg(0, ifs.end);
clength = static_cast<uint32_t>(ifs.tellg());
ifs.seekg (0, ifs.beg);
ptr = std::make_unique<uint8_t[]>(static_cast<unsigned int>(clength));
ifs.read(reinterpret_cast<char *>(ptr.get()), clength);
return 0;
}
int32_t RawParser::Uncompress(std::unique_ptr<uint8_t[]> &dst, uint32_t dstlen, uint8_t *cmem, uint32_t clen)
{
unsigned long ulength = dstlen;
auto ret = uncompress(dst.get(), &ulength, cmem, clen);
if (ret) {
GSLOG2HI(ERROR) << "uncompress failed";
}
return ret;
}
} // namespace OHOS

41
utils/semaphore/BUILD.gn Normal file
View File

@ -0,0 +1,41 @@
# 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")
## Build semaphore.a {{{
config("semaphore_config") {
visibility = [ ":semaphore" ]
cflags = [
"-Wall",
"-Werror",
"-g3",
]
}
config("semaphore_public_config") {
include_dirs = [ "export" ]
}
ohos_static_library("semaphore") {
sources = [ "src/local_semaphore.cpp" ]
configs = [ ":semaphore_config" ]
public_configs = [ ":semaphore_public_config" ]
part_name = "graphic_standard"
subsystem_name = "graphic"
}
## Build semaphore.a }}}

View File

@ -0,0 +1,35 @@
/*
* 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 UTILS_INCLUDE_LOCAL_SEMAPHORE_H
#define UTILS_INCLUDE_LOCAL_SEMAPHORE_H
#include <semaphore.h>
namespace OHOS {
class LocalSemaphore {
public:
LocalSemaphore(int count = 0);
~LocalSemaphore();
void Inc();
void Dec();
private:
sem_t sem;
};
} // namespace OHOS
#endif // UTILS_INCLUDE_LOCAL_SEMAPHORE_H

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 "local_semaphore.h"
#include <cerrno>
#include <cstdint>
namespace OHOS {
LocalSemaphore::LocalSemaphore(int count)
{
sem_init(&sem, false, static_cast<unsigned int>(count));
}
LocalSemaphore::~LocalSemaphore()
{
sem_destroy(&sem);
}
void LocalSemaphore::Inc()
{
sem_post(&sem);
}
void LocalSemaphore::Dec()
{
int32_t ret = 0;
do {
ret = sem_wait(&sem);
} while (ret == -1 && errno == EINTR);
}
} // namespace OHOS