提交 5f159aea 编写于 作者: O openharmony_ci 提交者: Gitee

!5 相机、图库、setting 应用代码

Merge pull request !5 from guyuanzhang/zhangguyuan_20201113150636
# Copyright (c) 2020 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/lite/config/component/lite_component.gni")
import("//build/lite/config/hap_pack.gni")
shared_library("cameraApp") {
sources = [
"cameraApp/src/main/cpp/camera_ability.cpp",
"cameraApp/src/main/cpp/camera_ability_slice.cpp",
"cameraApp/src/main/cpp/camera_manager.cpp"
]
deps = [
"//foundation/aafwk/frameworks/ability_lite:aafwk_abilitykit_lite",
"//foundation/appexecfwk/frameworks/bundle_lite:bundle",
"//foundation/communication/frameworks/ipc_lite:liteipc_adapter",
"//foundation/distributedschedule/services/samgr_lite/samgr:samgr",
"//utils/native/lite/kv_store:kv_store",
"//foundation/graphic/lite/frameworks/ui:ui",
"//foundation/graphic/lite/utils:graphic_utils",
"//foundation/graphic/lite/frameworks/surface",
"//foundation/multimedia/frameworks/camera_lite:camera",
"//foundation/multimedia/frameworks/recorder_lite:recorder",
]
include_dirs = [
"cameraApp/src/main/cpp",
"//foundation/aafwk/interfaces/kits/ability_lite",
"//foundation/graphic/lite/interfaces/kits/ui/components",
"//foundation/graphic/lite/interfaces/kits/ui",
"//foundation/graphic/lite/interfaces/kits/utils",
"//foundation/graphic/lite/interfaces/kits/config",
"//foundation/appexecfwk/interfaces/kits/bundle_lite",
"//foundation/aafwk/interfaces/kits/want_lite",
"//base/startup/interfaces/kits/syspara_lite",
"//foundation/multimedia/interfaces/kits/camera_lite",
"//foundation/multimedia/interfaces/kits/camera_lite"
]
ldflags = [
"-L$ohos_root_path/sysroot/usr/lib",
"-Wl,-rpath-link=$ohos_root_path/sysroot/usr/lib",
"-lstdc++", "-lcamera", "-lsurface", "-lrecorder"
]
defines = [
"ENABLE_WINDOW=1",
"ABILITY_WINDOW_SUPPORT"
]
}
lite_component("cameraApp_component") {
features = [
":cameraApp",
]
}
hap_pack("cameraApp_hap")
{
deps = [":cameraApp"]
mode = "hap"
json_path = "cameraApp/src/main/config.json"
ability_so_path = "$root_out_dir/libcameraApp.so"
force = "true"
cert_profile = "cert/camera_HarmonyAppProvision_Release.p7b"
resources_path = "cameraApp/src/main/resources"
hap_name = "cameraApp"
}
{
"app": {
"bundleName": "com.huawei.camera",
"vendor": "huawei",
"version": {
"code": 2,
"name": "2"
},
"apiVersion": {
"compatible": 3,
"target": 4
}
},
"deviceConfig": {
"default": {
}
},
"module": {
"package": "com.huawei.camera",
"name": ".MyHarmonyAbilityPackage",
"deviceType": [
"phone",
"tv",
"tablet",
"pc",
"car",
"smartWatch",
"sportsWatch",
"smartVision"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "cameraApp",
"moduleType": "entry"
},
"abilities": [
{
"name": "CameraAbility",
"icon": "assets/cameraApp/resources/base/media/camera.png",
"label": "test app 1",
"launchType": "standard",
"type": "page",
"visible": true
}
],
"reqPermissions": [
{
"name": "ohos.permission.CAMERA",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.MODIFY_AUDIO_SETTINGS",
"reason": "SYSTEM_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_MEDIA",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.MICROPHONE",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.WRITE_MEDIA",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
}
]
}
}
/*
* Copyright (c) 2020 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 "camera_ability.h"
namespace OHOS {
REGISTER_AA(CameraAbility)
void CameraAbility::OnStart(const Want &want)
{
printf("CameraAbility::OnStart\n");
SetMainRoute("CameraAbilitySlice");
Ability::OnStart(want);
}
void CameraAbility::OnInactive()
{
printf("CameraAbility::OnInactive\n");
Ability::OnInactive();
}
void CameraAbility::OnActive(const Want &want)
{
printf("CameraAbility::OnActive\n");
Ability::OnActive(want);
}
void CameraAbility::OnBackground()
{
printf("CameraAbility::OnBackground\n");
Ability::OnBackground();
}
void CameraAbility::OnStop()
{
printf("CameraAbility::OnStop\n");
Ability::OnStop();
}
}
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_MAIN_ABILITY_H
#define OHOS_MAIN_ABILITY_H
#include <ability_loader.h>
namespace OHOS {
class CameraAbility : public Ability {
protected:
void OnStart(const Want &want) override;
void OnInactive() override;
void OnActive(const Want &want) override;
void OnBackground() override;
void OnStop() override;
};
}
#endif // OHOS_MAIN_ABILITY_H
/*
* Copyright (c) 2020 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 OHOS_MAIN_ABILITY_SLICE_H
#define OHOS_MAIN_ABILITY_SLICE_H
#include <ability_loader.h>
#include <functional>
#include <utility>
#include <securec.h>
#include <common/task.h>
#include <stdio.h>
#include <components/ui_label_button.h>
#include <components/ui_label.h>
#include <components/ui_checkbox.h>
#include <components/ui_image_view.h>
#include <components/ui_scroll_view.h>
#include <components/ui_surface_view.h>
#include <components/ui_slider.h>
#include <animator/animator.h>
#include "event_listener.h"
#include "camera_manager.h"
namespace OHOS {
class TaskView : public Task {
public:
TaskView() = delete;
TaskView(UILabel* tmLabel):timeLabel_(tmLabel)
{
runEnable_ = false;
gTimeCount_ = 0;
Task::Init();
}
virtual ~TaskView(){}
void TaskStart(void)
{
Task::SetPeriod(1000); /* 1000=1s */
Task::TaskExecute();
}
void SetStart(void)
{
runEnable_ = true;
gTimeCount_ = 0;
}
void SetPause(void)
{
runEnable_ = false;
}
void SetResume(void)
{
runEnable_ = true;
}
void SetStop(void)
{
gTimeCount_ = 0;
runEnable_ = false;
UpdateTimeLabel(gTimeCount_);
}
void Callback() override
{
if (runEnable_)
UpdateTimeLabel(gTimeCount_++);
}
private:
UILabel* timeLabel_;
bool runEnable_;
uint32_t gTimeCount_;
void UpdateTimeLabel(int ss)
{
char buff[20] = { 0 };
if (timeLabel_ == nullptr) return;
sprintf_s(buff, sizeof(buff), "%02d : %02d", ss / 60, ss % 60); /* 60=1s */
timeLabel_->SetText(buff);
}
};
class CameraAbilitySlice : public AbilitySlice {
public:
CameraAbilitySlice() = default;
~CameraAbilitySlice() override;
protected:
void OnStart(const Want &want) override;
void OnInactive() override;
void OnActive(const Want &want) override;
void OnBackground() override;
void OnStop() override;
private:
static constexpr int BUTTON_NUMS = 4;
static constexpr int FONT_SIZE = 28;
EventListener *buttonListener_ { nullptr };
SampleCameraManager *cam_manager;
UIImageView *background_;
UISurfaceView* surfaceView;
UIImageView *backBttn;
UIImageView *backIcon;
UILabel *txtMsgLabel;
UIImageView *recordImage;
UILabel *tmLabel;
UIImageView* bttnLeft;
UIImageView* bttnMidle;
UIImageView* bttnRight;
UIImageView* bttnRecord;
UIScrollView* scroll;
UISlider *slider;
Animator *animator_;
TaskView *gTaskView_;
UIView::OnClickListener *bttnImageClick[BUTTON_NUMS];
void SetHead();
void SetBottom();
};
}
#endif // OHOS_MAIN_ABILITY_SLICE_H
/*
* Copyright (c) 2020 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 <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include "camera_manager.h"
#include "securec.h"
#include "ui_config.h"
using namespace std;
using namespace OHOS;
using namespace OHOS::Media;
static constexpr int TEMP_BUF_LEN = 8;
static constexpr int MAX_THM_SIZE = (64 * PAGE_SIZE);
static constexpr int FILE_NAME_LEN = 128;
static constexpr int MILLI_SECONDS = 1000;
char* g_dstBuf = nullptr;
static int32_t SampleDealThumb(char* psrc, uint32_t srcSize, uint32_t* dstSize, uint16_t u16THMLen)
{
int32_t endpos = 0;
int32_t s32I = 0;
int32_t startpos = 0;
char tempbuf[TEMP_BUF_LEN] = { 0 };
int32_t bufpos = 0;
char startflag[2] = { 0xff, 0xd8 };
char endflag[2] = { 0xff, 0xd9 };
while (s32I < srcSize) {
tempbuf[bufpos] = psrc[s32I++];
if (bufpos > 0) {
if (0 == memcmp(tempbuf + bufpos - 1, startflag, sizeof(startflag))) {
startpos = s32I - 2; /* 2 thumb head offset */
if (startpos < 0) {
startpos = 0;
}
}
if (0 == memcmp(tempbuf + bufpos - 1, endflag, sizeof(endflag))) {
if (u16THMLen == s32I) {
endpos = s32I;
break;
} else {
endpos = s32I;
break;
}
}
}
bufpos++;
if (bufpos == (TEMP_BUF_LEN - 1)) {
if (tempbuf[bufpos - 1] != 0xFF) {
bufpos = 0;
}
} else if (bufpos > (TEMP_BUF_LEN - 1)) {
bufpos = 0;
}
}
if ((endpos - startpos <= 0) || (endpos - startpos >= srcSize)) {
return -1;
}
char* temp = psrc + startpos;
if (MAX_THM_SIZE < (endpos - startpos)) {
return -1;
}
char* cDstBuf = (char*)malloc(endpos - startpos);
if (cDstBuf == nullptr) {
return -1;
}
(void)memcpy_s(cDstBuf, endpos - startpos, temp, endpos - startpos);
g_dstBuf = cDstBuf;
*dstSize = endpos - startpos;
return 0;
}
static int32_t SampleGetThmFromJpg(char* jpegPath, uint32_t* dstSize)
{
int32_t s32RtnVal = 0;
FILE* fpJpg = nullptr;
fpJpg = fopen(jpegPath, "rb");
char* pszFile = nullptr;
int32_t fd = 0;
struct stat stStat;
(void)memset_s(&stStat, sizeof(struct stat), 0, sizeof(struct stat));
if (fpJpg == nullptr) {
printf("file %s not exist!\n", jpegPath);
return -1;
}
fd = fileno(fpJpg);
fstat(fd, &stStat);
pszFile = (char*)malloc(stStat.st_size);
if ((pszFile == nullptr) || (stStat.st_size < 6)) { /* 6 min size of thumb head */
fclose(fpJpg);
printf("memory malloc fail!\n");
return -1;
}
if (fread(pszFile, stStat.st_size, 1, fpJpg) <= 0) {
fclose(fpJpg);
free(pszFile);
printf("fread jpeg src fail!\n");
return -1;
}
fclose(fpJpg);
// The fourth byte is shifted to the left by eight bits then the fifth byte is added.
uint16_t u16THMLen = (pszFile[4] << 8) + pszFile[5];
if (SampleDealThumb(pszFile, stStat.st_size, dstSize, u16THMLen) < 0) {
printf("get jpg thumb failed! \n");
free(pszFile);
return -1;
}
free(pszFile);
return 0;
}
int32_t SampleGetdcfinfo(const char* srcJpgPath, const char* dstThmPath)
{
int32_t s32RtnVal = 0;
char jpegSrcPath[FILE_NAME_LEN] = { 0 };
char jpegDesPath[FILE_NAME_LEN] = { 0 };
uint32_t dstSize = 0;
if (sprintf_s(jpegSrcPath, sizeof(jpegSrcPath), "%s", srcJpgPath) < 0) {
return -1;
}
if (sprintf_s(jpegDesPath, sizeof(jpegDesPath), "%s", dstThmPath) < 0) {
return -1;
}
s32RtnVal = SampleGetThmFromJpg(jpegSrcPath, &dstSize);
if ((s32RtnVal != 0) || (dstSize == 0)) {
printf("fail to get thm\n");
return -1;
}
FILE* fpTHM = fopen(jpegDesPath, "w");
if (fpTHM == 0) {
printf("file to create file %s\n", jpegDesPath);
return -1;
}
int32_t u32WritenSize = 0;
while (u32WritenSize < dstSize) {
s32RtnVal = fwrite(g_dstBuf + u32WritenSize, 1, dstSize, fpTHM);
if (s32RtnVal <= 0) {
printf("fail to wirte file, rtn=%d\n", s32RtnVal);
break;
}
u32WritenSize += s32RtnVal;
}
if (fpTHM != nullptr) {
fclose(fpTHM);
fpTHM = 0;
}
if (g_dstBuf != nullptr) {
free(g_dstBuf);
g_dstBuf = nullptr;
}
return 0;
}
static void SampleSaveCapture(const char* p, uint32_t size, int type, char *timeStamp, int length)
{
char acFileDcf[FILE_NAME_LEN] = {0};
FILE *fp = nullptr;
char acFile[FILE_NAME_LEN] = { 0 };
int ws = 0;
if (type == 0) {
char tmpFile[FILE_NAME_LEN] = {0};
if (sprintf_s(tmpFile, sizeof(tmpFile), "%s/photo%s.jpg", PHOTO_PATH, timeStamp) < 0) {
return;
}
fp = fopen(tmpFile, "w+");
if (fp) {
ws = fwrite(p, 1, size, fp);
fclose(fp);
}
}
if (sprintf_s(acFile, sizeof(acFile), "%s/tmp.jpg", PHOTO_PATH) < 0) {
return;
}
remove(acFile);
fp = fopen(acFile, "w+");
if (fp == NULL) {
return;
}
ws = fwrite(p, 1, size, fp);
fclose(fp);
if (type == 0) {
if (sprintf_s(acFileDcf, sizeof(acFileDcf), "%s/photo%s.jpg", THUMB_PATH, timeStamp) < 0) {
return;
}
} else if (type == 1) {
if (sprintf_s(acFileDcf, sizeof(acFileDcf), "%s/video%s.jpg", THUMB_PATH, timeStamp) < 0) {
return;
}
} else {
return;
}
SampleGetdcfinfo(static_cast<char *>(acFile), static_cast<char *>(acFileDcf));
}
static int CameraGetRecordFd(char* p)
{
int fd = -1;
char pname[128] = {0};
char *pe = strrchr(p, '.');
char *ps = strrchr(p, '/');
if (strcpy_s(static_cast<char *>(pname), sizeof(pname), VIDEO_PATH) != 0) {
return -1;
}
if (strncat_s(pname, sizeof(pname), ps, pe - ps) != 0) {
return -1;
}
if (strcat_s(pname, sizeof(pname), ".mp4") < 0) {
return -1;
}
fd = open(pname, O_RDWR | O_CREAT | O_CLOEXEC | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd <= 0) {
return -1;
}
return fd;
}
Recorder *SampleCreateRecorder(int w, int h)
{
int ret = 0;
AudioCodecFormat audioFormat = AAC_LC;
AudioSourceType inputSource = AUDIO_MIC;
VideoSourceType source = VIDEO_SOURCE_SURFACE_ES;
int32_t sourceId = 0;
int32_t audioSourceId = 0;
VideoCodecFormat encoder = HEVC;
Recorder *recorder = new Recorder();
if ((ret = recorder->SetVideoSource(source, sourceId)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetVideoEncoder(sourceId, encoder)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetVideoSize(sourceId, w, h)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetVideoFrameRate(sourceId, FRAME_RATE)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetVideoEncodingBitRate(sourceId, BIT_RATE)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetCaptureRate(sourceId, FRAME_RATE)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetAudioSource(inputSource, audioSourceId)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetAudioEncoder(audioSourceId, audioFormat)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetAudioSampleRate(audioSourceId, SAMPLE_RATE)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetAudioChannels(audioSourceId, CHANNEL_COUNT)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetAudioEncodingBitRate(audioSourceId, AUDIO_ENCODING_BITRATE)) != SUCCESS) {
goto EXIT_;
}
if ((ret = recorder->SetMaxDuration(36000)) != SUCCESS) { // 36000=10h
goto EXIT_;
}
EXIT_:
if (ret != SUCCESS) {
delete recorder;
recorder = nullptr;
}
return recorder;
}
// TestFrameStateCallback
void TestFrameStateCallback::OnFrameFinished(Camera &camera, FrameConfig &fc, FrameResult &result)
{
if (fc.GetFrameConfigType() == FRAME_CONFIG_CAPTURE) {
cout << "Capture frame received." << endl;
list<Surface *> surfaceList = fc.GetSurfaces();
for (Surface *surface : surfaceList) {
SurfaceBuffer *buffer = surface->AcquireBuffer();
if (buffer != nullptr) {
char *virtAddr = static_cast<char *>(buffer->GetVirAddr());
if (virtAddr != nullptr) {
SampleSaveCapture(virtAddr, buffer->GetSize(), gPhotoType_, timeStamp_, sizeof(timeStamp_));
}
surface->ReleaseBuffer(buffer);
} else {
printf("ERROR:surface buffer is NULL!! \n");
}
delete surface;
gIsFinished_ = true;
}
delete &fc;
} else if (fc.GetFrameConfigType() == FRAME_CONFIG_RECORD || fc.GetFrameConfigType() == FRAME_CONFIG_PREVIEW) {
delete &fc;
}
}
void TestFrameStateCallback::SetPhotoType(int type)
{
gPhotoType_ = type;
gIsFinished_ = false;
}
bool TestFrameStateCallback::IsFinish(void)
{
return gIsFinished_;
}
void TestFrameStateCallback::GetVideoName(char *pName, int length)
{
if (strlen(videoName_) <= 0)
return;
if (pName == nullptr || length < strlen(videoName_))
return;
if (strcpy_s(pName, length, videoName_) != 0) {
return;
}
}
void TestFrameStateCallback::InitTimeStamp()
{
struct timeval tv;
struct tm *ltm = nullptr;
gettimeofday(&tv, nullptr);
ltm = localtime(&tv.tv_sec);
if (ltm != nullptr) {
if (sprintf_s(timeStamp_, sizeof(timeStamp_), "%02d-%02d-%02d-%lld",
ltm->tm_hour, ltm->tm_min, ltm->tm_sec, tv.tv_usec / MILLI_SECONDS) < 0) {
return;
}
}
}
void TestFrameStateCallback::InitVideoName()
{
if (sprintf_s(videoName_, sizeof(videoName_), "%s/video%s.jpg", THUMB_PATH, timeStamp_) < 0) {
return;
}
}
// SampleCameraStateMng class
SampleCameraStateMng::~SampleCameraStateMng()
{
if (recorder_ != nullptr) {
if (gRecordSta_ != MEDIA_STATE_IDLE) {
recorder_->Stop(false);
}
recorder_->Release();
delete recorder_;
}
if (gRecFd_ >= 0)
close (gRecFd_);
if (fc_) {
delete fc_;
fc_ = nullptr;
}
}
void SampleCameraStateMng::OnCreated(Camera &c)
{
cout << "Sample recv OnCreate camera." << endl;
auto config = CameraConfig::CreateCameraConfig();
if (config == nullptr) {
cout << "New object failed." << endl;
return;
}
config->SetFrameStateCallback(&fsCb_, &eventHdlr_);
c.Configure(*config);
cam_ = &c;
}
void SampleCameraStateMng::StartRecord(Surface *mSurface)
{
int ret = 0;
if (gRecordSta_ == MEDIA_STATE_START) {
return;
}
if (recorder_ == nullptr) {
recorder_ = SampleCreateRecorder(IMAGE_WIDTH, IMAGE_HEIGHT);
}
if (recorder_ == nullptr) {
return;
}
if (gRecFd_ > 0) {
close(gRecFd_);
gRecFd_ = -1;
}
char vName[MAX_NAME_LEN] = {0};
fsCb_.GetVideoName(vName, sizeof(vName));
gRecFd_ = CameraGetRecordFd(static_cast<char *>(vName));
if (gRecFd_ < 0) {
return;
}
if (gRecordSta_ == MEDIA_STATE_PAUSE) {
recorder_->SetNextOutputFile(gRecFd_);
recorder_->Resume();
} else {
ret = recorder_->SetOutputFile(gRecFd_);
if (ret != SUCCESS) {
return;
}
if (recorder_->Prepare() != SUCCESS || recorder_->Start() != SUCCESS) {
return;
}
}
Surface *surface = (recorder_->GetSurface(0)).get();
if (surface == nullptr) {
return;
}
surface->SetWidthAndHeight(IMAGE_WIDTH, IMAGE_HEIGHT);
surface->SetQueueSize(3); /* queueSize is 3 */
surface->SetSize(PAGE_SIZE * PAGE_SIZE);
FrameConfig *fc = new FrameConfig(FRAME_CONFIG_RECORD);
fc->AddSurface(*surface);
ret = cam_->TriggerLoopingCapture(*fc);
if (ret != 0) {
delete fc;
return;
}
gRecordSta_ = MEDIA_STATE_START;
}
void SampleCameraStateMng::StartPreview(Surface *surface)
{
printf("enter StartPreview ##################################### \n");
if (cam_ == nullptr) {
cout << "Camera is not ready." << endl;
return;
}
if (gPreviewSta_ == MEDIA_STATE_START) {
cout << "Camera is already previewing." << endl;
return;
}
if (surface == nullptr) {
cout << "surface is NULL." << endl;
return;
}
FrameConfig *fc = new FrameConfig(FRAME_CONFIG_PREVIEW);
fc->AddSurface(*surface);
int32_t ret = cam_->TriggerLoopingCapture(*fc);
if (ret != 0) {
delete fc;
cout << "camera start preview failed. ret=" << ret << endl;
return;
}
gPreviewSta_ = MEDIA_STATE_START;
cout << "camera start preview succeed." << endl;
}
void SampleCameraStateMng::Capture(int type)
{
printf("camera start Capture ##################################### \n");
if (cam_ == nullptr) {
cout << "Camera is not ready." << endl;
return;
}
fsCb_.SetPhotoType(type);
fsCb_.InitTimeStamp();
fsCb_.InitVideoName();
FrameConfig *fc = new FrameConfig(FRAME_CONFIG_CAPTURE);
Surface *surface = Surface::CreateSurface();
if (surface == nullptr) {
delete fc;
return;
}
surface->SetWidthAndHeight(IMAGE_WIDTH, IMAGE_HEIGHT);
fc->AddSurface(*surface);
printf("Capture before TriggerSingleCapture. ##################################### \n");
cam_->TriggerSingleCapture(*fc);
printf("camera start Capture over. ##################################### \n");
}
bool SampleCameraStateMng::IsCaptureOver(void)
{
return fsCb_.IsFinish();
}
void SampleCameraStateMng::SetPause()
{
}
void SampleCameraStateMng::SetResume(Surface *mSurface)
{
}
void SampleCameraStateMng::SetStop(int s)
{
if (cam_ == nullptr) {
cout << "Camera is not ready." << endl;
return;
}
cam_->StopLoopingCapture();
if (gRecordSta_ == MEDIA_STATE_START) {
if (s) {
recorder_->Stop(false);
gRecordSta_ = MEDIA_STATE_IDLE;
} else {
recorder_->Pause();
gRecordSta_ = MEDIA_STATE_PAUSE;
}
}
gPreviewSta_ = MEDIA_STATE_IDLE;
}
bool SampleCameraStateMng::RecordState()
{
return (gRecordSta_ == MEDIA_STATE_START);
}
bool SampleCameraStateMng::CameraIsReady()
{
return (cam_ == nullptr) ? false : true;
}
// SampleCameraManager class
SampleCameraManager::~SampleCameraManager()
{
if (CamStateMng) {
CamStateMng->SetStop(1);
delete CamStateMng;
CamStateMng = NULL;
}
}
int SampleCameraManager::SampleCameraCreate(int picMode)
{
int retval = 0;
int timeout = 0;
printf("camera start init!!! \n");
camKit = CameraKit::GetInstance();
if (camKit == nullptr) {
cout << "Can not get CameraKit instance" << endl;
return -1;
}
list<string> camList = camKit->GetCameraIds();
for (auto &cam : camList) {
cout << "camera name:" << cam << endl;
const CameraAbility *ability = camKit->GetCameraAbility(cam);
/* find camera which fits user's ability */
list<CameraPicSize> sizeList = ability->GetSupportedSizes(0);
if (find(sizeList.begin(), sizeList.end(), CAM_PIC_1080P) != sizeList.end()) {
camId = cam;
break;
}
}
if (camId.empty()) {
cout << "No available camera.(1080p wanted)" << endl;
printf("No available camera.(1080p wanted)####################### \n");
return -1;
}
CamStateMng = new SampleCameraStateMng(eventHdlr_);
if (CamStateMng == NULL) {
printf("create SampleCameraStateMng failed! \n");
return -1;
}
printf("before CreateCamera \n");
camKit->CreateCamera(camId, *CamStateMng, eventHdlr_);
printf("after CreateCamera \n");
if (!access("/userdata/", F_OK | R_OK | W_OK)) {
if (access(PHOTO_PATH, F_OK)) {
mkdir(PHOTO_PATH, FILE_MODE);
}
if (access(THUMB_PATH, F_OK)) {
mkdir(THUMB_PATH, FILE_MODE);
}
if (access(VIDEO_PATH, F_OK)) {
mkdir(VIDEO_PATH, FILE_MODE);
}
}
printf("camera init ok! \n");
return retval;
}
bool SampleCameraManager::SampleCameraExist(void)
{
return camId.empty() ? false : true;
}
int SampleCameraManager::SampleCameraStart(Surface *surface)
{
if (CamStateMng == NULL)
return -1;
CamStateMng->StartPreview(surface);
return 0;
}
int SampleCameraManager::SampleCameraStop(void)
{
if (CamStateMng == nullptr)
return -1;
CamStateMng->SetStop(1);
return 0;
}
int SampleCameraManager::SampleCameraCaptrue(int type)
{
if (CamStateMng == NULL)
return -1;
CamStateMng->Capture(type);
return 0;
}
int SampleCameraManager::SampleCameraStartRecord(Surface *surface)
{
if (CamStateMng == NULL)
return -1;
CamStateMng->StartRecord(surface);
return 0;
}
int SampleCameraManager::SampleCameraPauseRecord(void)
{
if (CamStateMng == NULL)
return -1;
CamStateMng->SetPause();
return 0;
}
int SampleCameraManager::SampleCameraResumeRecord(Surface *mSurface)
{
if (CamStateMng == NULL)
return -1;
CamStateMng->SetResume(mSurface);
return 0;
}
int SampleCameraManager::SampleCameraStopRecord(void)
{
if (CamStateMng == NULL)
return -1;
CamStateMng->SetStop(0);
return 0;
}
bool SampleCameraManager::SampleCameraGetRecord(void)
{
if (CamStateMng == NULL)
return false;
return CamStateMng->RecordState();
}
bool SampleCameraManager::SampleCameraCaptrueIsFinish(void)
{
return CamStateMng->IsCaptureOver();
}
bool SampleCameraManager::SampleCameraIsReady(void)
{
return CamStateMng->CameraIsReady();
}
/*
* Copyright (c) 2020 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 __CAMERA_MANAGER_H__
#define __CAMERA_MANAGER_H__
#include <stdio.h>
#include <sys/time.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <errno.h>
#include "camera_kit.h"
#include "recorder.h"
using namespace std;
using namespace OHOS;
using namespace OHOS::Media;
typedef enum {
PHOTO_TYPE_NORMAL,
PHOTO_TYPE_VIDEO,
PHOTO_TYPE_TMP,
PHOTO_TYPE_NBR
}PHOTO_TYPE;
typedef enum {
MEDIA_STATE_IDLE = 0,
MEDIA_STATE_START,
MEDIA_STATE_PAUSE,
MEDIA_STATE_STOP
} CAMERA_MEDIA_STATUS;
class TestFrameStateCallback : public FrameStateCallback {
public:
TestFrameStateCallback(){}
~TestFrameStateCallback(){}
void OnFrameFinished(Camera &camera, FrameConfig &fc, FrameResult &result) override;
void SetPhotoType(int type);
bool IsFinish(void);
void GetVideoName(char *pName, int length);
void InitVideoName();
void InitTimeStamp();
private:
int gPhotoType_;
bool gIsFinished_;
char videoName_[256];
char timeStamp_[256];
};
class SampleCameraStateMng : public CameraStateCallback {
public:
SampleCameraStateMng() = delete;
SampleCameraStateMng(EventHandler &eventHdlr) : eventHdlr_(eventHdlr) {}
~SampleCameraStateMng();
void OnCreated(Camera &c) override;
void OnCreateFailed(const std::string cameraId, int32_t errorCode) override {}
void OnReleased(Camera &c) override {}
void StartRecord(Surface *mSurface);
void StartPreview(Surface *surface);
void Capture(int type);
void SetPause();
void SetResume(Surface *mSurface);
void SetStop(int s);
bool RecordState();
bool CameraIsReady();
bool IsCaptureOver(void);
private:
int gRecordSta_ = 0;
int gPreviewSta_ = 0;
int gRecFd_ = -1;
EventHandler &eventHdlr_;
Camera *cam_ = nullptr;
Recorder *recorder_ = nullptr;
TestFrameStateCallback fsCb_;
FrameConfig *fc_ = nullptr;
};
class SampleCameraManager {
public:
SampleCameraManager() = delete;
SampleCameraManager(int mode) : picMode(mode) {}
~SampleCameraManager();
int SampleCameraCreate(int picMode);
bool SampleCameraExist(void);
int SampleCameraStart(Surface *surface);
int SampleCameraStop(void);
int SampleCameraCaptrue(int type);
int SampleCameraStartRecord(Surface *surface);
int SampleCameraPauseRecord(void);
int SampleCameraResumeRecord(Surface *mSurface);
int SampleCameraStopRecord(void);
bool SampleCameraGetRecord(void);
bool SampleCameraIsReady(void);
bool SampleCameraCaptrueIsFinish(void);
private:
CameraKit *camKit;
string camId;
SampleCameraStateMng *CamStateMng;
int picMode = 0;
EventHandler eventHdlr_;
};
#endif /* __CAMERA_MANAGER_H__ */
/*
* Copyright (c) 2020 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 OHOS_EVENT_LISTENER_H
#define OHOS_EVENT_LISTENER_H
#include <components/ui_view.h>
#include <functional>
#include <utility>
namespace OHOS {
using OnEventFunc = std::function<bool(UIView &view, const Event &event)>;
class EventListener :
public UIView::OnClickListener,
public UIView::OnLongPressListener {
public:
EventListener() = delete;
~EventListener() override = default;
EventListener(OnEventFunc onClick, OnEventFunc onLongPress)
{
onClick_ = std::move(onClick);
onLongPress_ = std::move(onLongPress);
}
bool OnClick(UIView &view, const ClickEvent &event) override
{
if (!onClick_) {
return false;
}
return onClick_(view, event);
}
bool OnLongPress(UIView &view, const LongPressEvent &event) override
{
if (!onLongPress_) {
return false;
}
return onLongPress_(view, event);
}
private:
OnEventFunc onClick_ {};
OnEventFunc onLongPress_ {};
};
}
#endif // OHOS_EVENT_LISTENER_H
/*
* Copyright (c) 2020 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 __UI_CONFIG_H__
#define __UI_CONFIG_H__
#ifdef __cplusplus
extern "C" {
#endif
#define LCD_CH_55 0
#define LCD_CH_70 1
#define LCD_CH_SEL LCD_CH_55
#define LCD_MODE_HORIZONTAL 0
#define LCD_MODE_VERTICAL 1
#define LCD_MODE_SELECT LCD_MODE_HORIZONTAL
#if (LCD_CH_SEL==LCD_CH_55)
#if (LCD_MODE_SELECT==LCD_MODE_HORIZONTAL)
#define SCREEN_WIDTH 960
#define SCREEN_HEIGHT 480
#else
#define SCREEN_WIDTH 480
#define SCREEN_HEIGHT 960
#endif
#elif (LCD_CH_SEL==LCD_CH_70)
#if (LCD_MODE_SELECT==LCD_MODE_HORIZONTAL)
#define SCREEN_WIDTH 1024
#define SCREEN_HEIGHT 600
#else
#define SCREEN_WIDTH 600
#define SCREEN_HEIGHT 1024
#endif
#else
#error "no such type LCD SIZE select!!!"
// exit (1)
#endif
#define START_X 0
#define START_Y 0
#define BUTTON_ICON_SW 60
#define BUTTON_ICON_SH 60
#define BUTTON_ICON_BW 114
#define BUTTON_ICON_BH 114
#define TITLE_HEIGHT 80
#define ICON_B_WIDTH 50
#define ICON_B_HEIGHT 50
#define ICON_M_WIDTH 36
#define ICON_M_HEIGHT 36
#define ICON_S_WIDTH 12
#define ICON_S_HEIGHT 12
// coord define
#define V_GROUP_X START_X
#define V_GROUP_Y START_Y
#define V_GROUP_W SCREEN_WIDTH
#define V_GROUP_H SCREEN_HEIGHT
#if (LCD_MODE_SELECT==LCD_MODE_HORIZONTAL)
#define BACK_LABEL_X (START_X + 30)
#define BACK_LABEL_Y ((TITLE_HEIGHT - ICON_M_HEIGHT) / 2)
#define BACK_LABEL_W ICON_M_WIDTH
#define BACK_LABEL_H ICON_M_HEIGHT
#define TXT_LABEL_X (BACK_LABEL_X + BUTTON_ICON_SW)
#define TXT_LABEL_Y (START_Y + (TITLE_HEIGHT - ICON_B_HEIGHT) / 2)
#define TXT_LABEL_W (ICON_B_WIDTH * 3)
#define TXT_LABEL_H ICON_B_HEIGHT
#define RECORD_IMAGE_X (SCREEN_WIDTH / 2 - BUTTON_ICON_SW)
#define RECORD_IMAGE_Y (START_Y + (TITLE_HEIGHT - ICON_S_HEIGHT) / 2)
#define RECORD_IMAGE_W ICON_S_WIDTH
#define RECORD_IMAGE_H ICON_S_HEIGHT
#define TIME_LABEL_X (RECORD_IMAGE_X + RECORD_IMAGE_W + 14)
#define TIME_LABEL_Y (START_Y + (TITLE_HEIGHT - ICON_B_HEIGHT) / 2)
#define TIME_LABEL_W (SCREEN_WIDTH-(RECORD_IMAGE_X + RECORD_IMAGE_W + 14))
#define TIME_LABEL_H ICON_B_HEIGHT
#define SCROLL_VIEW_X START_X
#define SCROLL_VIEW_Y ((SCREEN_HEIGHT - BUTTON_ICON_BH) - 30)
#define SCROLL_VIEW_W SCREEN_WIDTH
#define SCROLL_VIEW_H (BUTTON_ICON_BH + 6)
#define LEFT_BUTTON_X (SCREEN_WIDTH / 3)
#define LEFT_BUTTON_Y ((SCROLL_VIEW_H - BUTTON_ICON_SH) / 2)
#define LEFT_BUTTON_W BUTTON_ICON_SW
#define LEFT_BUTTON_H BUTTON_ICON_SH
#define MID_BUTTON_X (((SCREEN_WIDTH / 3) - BUTTON_ICON_BW) / 2 + 1 * (SCREEN_WIDTH / 3))
#define MID_BUTTON_Y ((SCROLL_VIEW_H - BUTTON_ICON_BH) / 2)
#define MID_BUTTON_W BUTTON_ICON_BW
#define MID_BUTTON_H BUTTON_ICON_BH
#define RIGHT_BUTTON_X (2 * (SCREEN_WIDTH / 3) - BUTTON_ICON_SW)
#define RIGHT_BUTTON_Y ((SCROLL_VIEW_H - BUTTON_ICON_SH) / 2)
#define RIGHT_BUTTON_W BUTTON_ICON_SW
#define RIGHT_BUTTON_H BUTTON_ICON_SH
#else
#define BACK_LABEL_X (START_X + 30)
#define BACK_LABEL_Y ((BUTTON_ICON_SH - ICON_M_HEIGHT) / 2)
#define BACK_LABEL_W ICON_M_WIDTH
#define BACK_LABEL_H ICON_M_HEIGHT
#define TXT_LABEL_X (BACK_LABEL_X + BUTTON_ICON_SW)
#define TXT_LABEL_Y (START_Y + (BUTTON_ICON_SH - ICON_B_HEIGHT) / 2)
#define TXT_LABEL_W (ICON_B_WIDTH * 3)
#define TXT_LABEL_H ICON_B_HEIGHT
#define RECORD_IMAGE_X (SCREEN_WIDTH / 2 - BUTTON_ICON_SW)
#define RECORD_IMAGE_Y (START_Y + (BUTTON_ICON_SH - ICON_S_HEIGHT) / 2)
#define RECORD_IMAGE_W ICON_S_WIDTH
#define RECORD_IMAGE_H ICON_S_HEIGHT
#define TIME_LABEL_X (RECORD_IMAGE_X + RECORD_IMAGE_W + 14)
#define TIME_LABEL_Y (START_Y + (BUTTON_ICON_SH - ICON_B_HEIGHT) / 2)
#define TIME_LABEL_W (BUTTON_ICON_SW * 2)
#define TIME_LABEL_H ICON_B_HEIGHT
#define SCROLL_VIEW_X START_X
#define SCROLL_VIEW_Y ((SCREEN_HEIGHT - BUTTON_ICON_BH) - 10)
#define SCROLL_VIEW_W SCREEN_WIDTH
#define SCROLL_VIEW_H (BUTTON_ICON_BH + 6)
#define LEFT_BUTTON_X (SCREEN_WIDTH / 3)
#define LEFT_BUTTON_Y ((SCROLL_VIEW_H - BUTTON_ICON_SH) / 2)
#define LEFT_BUTTON_W BUTTON_ICON_SW
#define LEFT_BUTTON_H BUTTON_ICON_SH
#define MID_BUTTON_X (((SCREEN_WIDTH / 3) - BUTTON_ICON_BW) / 2 + 1 * (SCREEN_WIDTH / 3))
#define MID_BUTTON_Y ((SCROLL_VIEW_H - BUTTON_ICON_SH) / 2)
#define MID_BUTTON_W BUTTON_ICON_SW
#define MID_BUTTON_H BUTTON_ICON_SH
#define RIGHT_BUTTON_X (2 * (SCREEN_WIDTH / 3) - BUTTON_ICON_SW)
#define RIGHT_BUTTON_Y ((SCROLL_VIEW_H - BUTTON_ICON_SH) / 2)
#define RIGHT_BUTTON_W BUTTON_ICON_SW
#define RIGHT_BUTTON_H BUTTON_ICON_SH
#endif
#define UI_IMAGE_PATH \
"/storage/app/run/com.huawei.camera/cameraApp/assets/cameraApp/resources/base/media/"
#define TTF_PATH "SourceHanSansSC-Regular.otf"
#define PHOTO_PATH "/userdata/photo/"
#define VIDEO_PATH "/userdata/video/"
#define THUMB_PATH "/userdata/thumb/"
#define MAX_NAME_LEN 256
#define PAGE_SIZE 1024
#define IMAGE_WIDTH 1920
#define IMAGE_HEIGHT 1080
#define SAMPLE_RATE 48000
#define CHANNEL_COUNT 1
#define AUDIO_ENCODING_BITRATE SAMPLE_RATE
#define FRAME_RATE 30
#define BIT_RATE 4096
#define FILE_MODE 777
#ifdef __cplusplus
}
#endif
#endif
# Copyright (c) 2020 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/lite/config/component/lite_component.gni")
import("//build/lite/config/hap_pack.gni")
shared_library("gallery") {
sources = [
"src/gallery_ability.cpp",
"src/gallery_ability_slice.cpp",
"src/picture_ability_slice.cpp",
"src/player_ability_slice.cpp",
]
include_dirs = [
"include",
"//foundation/aafwk/interfaces/kits/ability_lite",
"//foundation/graphic/lite/interfaces/kits/ui/components",
"//foundation/graphic/lite/interfaces/kits/ui",
"//foundation/graphic/lite/interfaces/kits/utils",
"//foundation/graphic/lite/interfaces/kits/config",
"//foundation/appexecfwk/interfaces/kits/bundle_lite",
"//foundation/aafwk/interfaces/kits/want_lite",
"//foundation/multimedia/interfaces/kits/player_lite",
"//base/startup/interfaces/kits/syspara_lite"
]
deps = [
"//foundation/aafwk/frameworks/ability_lite:aafwk_abilitykit_lite",
"//foundation/appexecfwk/frameworks/bundle_lite:bundle",
"//foundation/communication/frameworks/ipc_lite:liteipc_adapter",
"//foundation/distributedschedule/services/samgr_lite/samgr:samgr",
"//utils/native/lite/kv_store:kv_store",
"//foundation/graphic/lite/frameworks/ui:ui",
"//foundation/graphic/lite/frameworks/surface",
"//foundation/graphic/lite/utils:graphic_utils",
"//foundation/multimedia/frameworks/recorder_lite:recorder",
"//foundation/multimedia/frameworks/player_lite:player"
]
ldflags = [
"-shared",
]
ldflags += ["-lstdc++"]
ldflags += ["-lpthread"]
ldflags += ["-L$ohos_root_path/sysroot/usr/lib"]
ldflags += ["-Wl,-rpath-link=$ohos_root_path/sysroot/usr/lib"]
ldflags += ["-lui",
"-lsurface",
"-lplayer",
"-lability"
]
defines = [
"OHOS_APPEXECFWK_BMS_BUNDLEMANAGER",
"ENABLE_WINDOW=1",
"ABILITY_WINDOW_SUPPORT"
]
}
lite_component("gallery_component") {
features = [
":gallery",
]
}
hap_pack("gallery_hap")
{
deps = [":gallery"]
mode = "hap"
json_path = "config.json"
ability_so_path = "$root_out_dir/libgallery.so"
force = "true"
cert_profile = "cert/gallery_HarmonyAppProvision_Release.p7b"
resources_path = "resources"
hap_name = "gallery"
}
{
"app": {
"bundleName": "com.huawei.gallery",
"vendor": "huawei",
"version": {
"code": 1,
"name": "1.0"
},
"apiVersion": {
"compatible": 3,
"target": 4
}
},
"deviceConfig": {
"default": {
}
},
"module": {
"package": "com.huawei.gallery",
"name": ".MyHarmonyAbilityPackage",
"deviceType": [
"phone",
"tv",
"tablet",
"pc",
"car",
"smartWatch",
"sportsWatch",
"smartVision"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "gallery",
"moduleType": "entry"
},
"abilities": [
{
"name": "GalleryAbility",
"icon": "assets/gallery/resources/drawable/com.huawei.photos.png",
"label": "test app 1",
"launchType": "standard",
"type": "page",
"visible": true
}
],
"reqPermissions": [
{
"name": "ohos.permission.MODIFY_AUDIO_SETTINGS",
"reason": "SYSTEM_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_MEDIA",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_MEDIA_AUDIO",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_MEDIA_IMAGES",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_MEDIA_VIDEO",
"reason": "USER_GRANT",
"usedScene": {
"ability": [
".FormAbility"
],
"when": "inuse"
}
}
]
}
}
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_EVENT_LISTENER_H
#define OHOS_EVENT_LISTENER_H
#include <components/ui_view.h>
#include <functional>
#include <utility>
namespace OHOS {
using OnEventFunc = std::function<bool(UIView &view, const Event &event)>;
class EventListener :
public UIView::OnClickListener,
public UIView::OnLongPressListener {
public:
EventListener() = delete;
~EventListener() override = default;
EventListener(OnEventFunc onClick, OnEventFunc onLongPress)
{
onClick_ = std::move(onClick);
onLongPress_ = std::move(onLongPress);
}
bool OnClick(UIView &view, const ClickEvent &event) override
{
if (!onClick_) {
return false;
}
return onClick_(view, event);
}
bool OnLongPress(UIView &view, const LongPressEvent &event) override
{
if (!onLongPress_) {
return false;
}
return onLongPress_(view, event);
}
private:
OnEventFunc onClick_ {};
OnEventFunc onLongPress_ {};
};
}
#endif // OHOS_EVENT_LISTENER_H
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_GALLERY_ABILITY_H
#define OHOS_GALLERY_ABILITY_H
#include <ability_loader.h>
namespace OHOS {
class GalleryAbility : public Ability {
protected:
void OnStart(const Want &want) override;
void OnInactive() override;
void OnActive(const Want &want) override;
void OnBackground() override;
void OnStop() override;
};
}
#endif // OHOS_GALLERY_ABILITY_H
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_GALLERY_ABILITY_SLICE_H
#define OHOS_GALLERY_ABILITY_SLICE_H
#include <ability_loader.h>
#include <components/ui_image_view.h>
#include <components/ui_label.h>
#include <components/ui_scroll_view.h>
#include "event_listener.h"
#include "gallery_config.h"
namespace OHOS {
class GalleryAbilitySlice : public AbilitySlice {
public:
GalleryAbilitySlice() = default;
~GalleryAbilitySlice() override;
protected:
void OnStart(const Want &want) override;
void OnInactive() override;
void OnActive(const Want &want) override;
void OnBackground() override;
void OnStop() override;
private:
void Clear();
void ClearThumb();
void ClearPictureList(const UIView* view);
void InitTitle();
void InitPictureList();
void AddAllPictures(const Point& pos, int16_t numInLine);
UIView* CreateImageItem(const Point& pos, const char* imageName, const char* imagePath);
EventListener* GetImageClickListener(const char* path);
void DeleteAllData();
void DeleteAllFilesInDir(const char* path);
RootView* rootView_ { nullptr };
uint16_t pictureCount_ { 0 };
UIViewGroup* backArea_ { nullptr };
UIImageView* backIcon_ { nullptr };
EventListener* backIconListener_ { nullptr };
EventListener* deleteClickListener_ { nullptr };
UILabel* titleLabel_ { nullptr };
UILabel* deleteLabel_ { nullptr };
UIScrollView* picContainer_ { nullptr };
UIViewGroup* picList_ { nullptr };
char* pictureName_[MAX_PICTURE_COUNT] = { nullptr };
uint16_t pictureOnClickListenerCount_ { 0 };
EventListener* pictureOnClickListener_[MAX_PICTURE_COUNT] = { nullptr };
};
}
#endif // OHOS_GALLERY_ABILITY_SLICE_H
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_GALLERY_CONFIG_H
#define OHOS_GALLERY_CONFIG_H
namespace OHOS {
/** icon resource file path */
static const char* const BACK_ICON_PATH = "/gallery/assets/gallery/resources/drawable/ic_back.png";
static const char* const VIDEO_TAG_ICON_PATH = "/gallery/assets/gallery/resources/drawable/ic_gallery_video_tag.png";
static const char* const VIDEO_PALY_PATH = "/gallery/assets/gallery/resources/drawable/ic_gallery_play.png";
static const char* const VIDEO_PAUSE_PATH = "/gallery/assets/gallery/resources/drawable/ic_gallery_pause.png";
static constexpr int16_t MAX_PICTURE_COUNT = 256;
static constexpr uint16_t MAX_PATH_LENGTH = 512;
static char g_backIconAbsolutePath[MAX_PATH_LENGTH] = {0};
static char g_videoTagIconAbsolutePath[MAX_PATH_LENGTH] = {0};
/** thumb, photo, and video folder path */
static const char* const THUMBNAIL_DIRECTORY = "/userdata/thumb";
static const char* const PHOTO_DIRECTORY = "/userdata/photo";
static const char* const VIDEO_SOURCE_DIRECTORY = "/userdata/video";
/** general page configuration */
static constexpr int ROOT_VIEW_POSITION_X = 0;
static constexpr int ROOT_VIEW_POSITION_Y = 0;
static constexpr int ROOT_VIEW_WIDTH = 960;
static constexpr int ROOT_VIEW_HEIGHT = 480;
static constexpr uint16_t ROOT_VIEW_OPACITY = 255;
static const char* const FONT_NAME = "SourceHanSansSC-Regular.otf";
/** back icon 36 x 36 */
static constexpr int16_t BACK_ICON_POSITION_X = 38;
static constexpr int16_t BACK_ICON_POSITION_Y = 17;
/** THUMBNAIL */
static constexpr int16_t THUMBNAIL_RESOLUTION_X = 120;
static constexpr int16_t THUMBNAIL_RESOLUTION_Y = 120;
static constexpr int16_t THUMBNAIL_SPACE = 4;
static constexpr int16_t THUMBNAIL_COLUMN = 3;
static constexpr int16_t VIDEO_TAG_POSITION_X = 10;
static constexpr int16_t VIDEO_TAG_POSITION_Y = THUMBNAIL_RESOLUTION_Y - 37;
/** title */
static constexpr int16_t LABEL_POSITION_X = BACK_ICON_POSITION_X + 60;
static constexpr int16_t LABEL_POSITION_Y = 0;
static constexpr int16_t LABEL_WIDTH = 100;
static constexpr int16_t LABEL_HEIGHT = 70;
static constexpr uint16_t GALLERY_FONT_SIZE = 25;
static constexpr uint16_t GALLERY_DELETE_FONT_SIZE = 22;
static constexpr int16_t DELETE_LABEL_WIDTH = 150;
/** prefix and File Type */
static const char* const PHOTO_PREFIX = "photo";
static const char* const AVAILABEL_SOURCE_TYPE = ".mp4";
static const char* const AVAILABEL_SOURCE_TYPE_MP4 = ".MP4";
/** player */
static char g_videoPlayAbsolutePath[MAX_PATH_LENGTH] = {0};
static char g_videoPauseAbsolutePath[MAX_PATH_LENGTH] = {0};
/** playback status bar */
static constexpr uint16_t STATUS_BAR_GROUP_HEIGHT = 96;
static constexpr uint16_t TOGGLE_BUTTON_OFFSET_X = 36;
static constexpr uint16_t TOGGLE_BUTTON_OFFSET_Y = 18;
static constexpr uint16_t TOGGLE_BUTTON_WIDTH = 60;
static constexpr uint16_t TOGGLE_BUTTON_HEIGHT = 60;
static constexpr uint16_t CURRENT_TIME_LABEL_X = TOGGLE_BUTTON_OFFSET_X + TOGGLE_BUTTON_WIDTH + TOGGLE_BUTTON_OFFSET_Y;
static constexpr uint16_t CURRENT_TIME_LABEL_Y = 0;
static constexpr uint16_t CURRENT_TIME_LABEL_WIDTH = 60;
static constexpr uint16_t CURRENT_TIME_LABEL_HEIGHT = STATUS_BAR_GROUP_HEIGHT;
static constexpr uint16_t TOTAL_TIME_LABEL_WIDTH = 90;
static constexpr uint16_t TOTAL_TIME_LABEL_HEIGHT = STATUS_BAR_GROUP_HEIGHT;
static constexpr uint16_t TOTAL_TIME_LABEL_X = ROOT_VIEW_WIDTH - TOTAL_TIME_LABEL_WIDTH;
static constexpr uint16_t TOTAL_TIME_LABEL_Y = 0;
static constexpr uint16_t SLIDER_X = CURRENT_TIME_LABEL_X + CURRENT_TIME_LABEL_WIDTH;
static constexpr uint16_t SLIDER_Y = 2;
static constexpr uint16_t SLIDER_HEIGHT = 3;
static constexpr uint16_t SLIDER_WIDTH = ROOT_VIEW_WIDTH - SLIDER_X - TOTAL_TIME_LABEL_WIDTH - 20;
static constexpr uint16_t KNOB_WIDTH = 25;
static constexpr uint16_t PLAYER_FONT_SIZE = 18;
} // namespace OHOS
#endif // OHOS_GALLERY_CONFIG_H
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_PICTURE_ABILITY_SLICE_H
#define OHOS_PICTURE_ABILITY_SLICE_H
#include <ability_loader.h>
#include "components/ui_image_view.h"
#include "components/ui_view_group.h"
#include "event_listener.h"
namespace OHOS {
class PictureAbilitySlice : public AbilitySlice {
public:
~PictureAbilitySlice() override;
protected:
void OnStart(const Want &want) override;
void OnInactive() override;
void OnActive(const Want &want) override;
void OnBackground() override;
void OnStop() override;
private:
void Clear();
void InitTitle();
void InitPicture(const char* path);
RootView* rootView_ { nullptr };
UIViewGroup* backArea_ { nullptr };
UIImageView* backIcon_ { nullptr };
EventListener* backIconListener_ { nullptr };
UIImageView* picture_ { nullptr };
};
}
#endif // OHOS_PICTURE_ABILITY_SLICE_H
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_PLAYER_ABILITY_SLICE_H
#define OHOS_PLAYER_ABILITY_SLICE_H
#include "ability_loader.h"
#include "animator/animator.h"
#include "animator/easing_equation.h"
#include "components/root_view.h"
#include "components/ui_label.h"
#include "components/ui_slider.h"
#include "components/ui_surface_view.h"
#include "components/ui_toggle_button.h"
#include "event_listener.h"
#include "gallery_config.h"
#include "player.h"
#include "securec.h"
#include "source.h"
namespace OHOS {
using OHOS::Media::Player;
using OHOS::Media::Source;
using namespace OHOS::Media;
struct PlayerAdapter {
std::shared_ptr<Player> adapter;
int32_t sourceType;
char filePath[MAX_PATH_LENGTH];
};
class ToggleBtnListener : public UIView::OnClickListener {
public:
explicit ToggleBtnListener(UIToggleButton* btn,
PlayerAdapter* sample,
Animator* animator,
UISurfaceView* surfaceView)
: button_(btn),
videoPlayer_(sample),
animator_(animator) {}
virtual ~ToggleBtnListener() {}
bool OnClick(UIView& view, const ClickEvent& event) override;
void SetCompleteFlag(bool state)
{
completeFlag_ = state;
}
private:
UIToggleButton* button_;
PlayerAdapter* videoPlayer_;
Animator* animator_;
bool completeFlag_ { false };
};
class SliderAnimator : public Animator, public AnimatorCallback {
public:
explicit SliderAnimator(PlayerAdapter *sample,
UISlider *slider,
UILabel *label,
int64_t duration,
UISurfaceView* surfaceView)
: Animator(this, slider, duration, true),
videoPlayer_(sample),
slider_(slider),
timeLabel_(label),
duration_(duration),
surfaceView_(surfaceView),
needRefreshPlayer_(false) {}
virtual ~SliderAnimator() {}
void Callback(UIView* view) override;
void SetToggleButton(UIToggleButton* toggleButton)
{
toggleButton_ = toggleButton;
}
void SetToggleBtnListener(ToggleBtnListener* listener)
{
listener_ = listener;
}
private:
PlayerAdapter* videoPlayer_;
UISlider* slider_;
UILabel* timeLabel_;
int64_t duration_;
UISurfaceView* surfaceView_;
UIToggleButton* toggleButton_ { nullptr };
ToggleBtnListener* listener_ { nullptr };
bool needRefreshPlayer_;
};
class PlayerAbilitySlice : public AbilitySlice {
public:
PlayerAbilitySlice() = default;
~PlayerAbilitySlice() override;
protected:
void OnStart(const Want &want) override;
void OnInactive() override;
void OnActive(const Want &want) override;
void OnBackground() override;
void OnStop() override;
private:
void Clear();
void ShowErrorTips();
void SetUpRootView();
void SetUpBackArea(const char* pathHeader);
void SetUpVideoPlayer(const Want &want);
bool SetUpSurfaceView();
void SetUpProgress(int64_t duration);
void SetUpAnimatorGroup(const char* pathHeader);
void SetUpToggleButton(const char* pathHeader);
PlayerAdapter* videoPlayer_ { nullptr };
SliderAnimator* animator_ { nullptr };
EventListener* backIconListener_ { nullptr };
ToggleBtnListener* onClickListener_ { nullptr };
RootView* rootView_ { nullptr };
UIViewGroup* backArea_ { nullptr };
UIImageView* backIcon_ { nullptr };
UISurfaceView* surfaceView_ { nullptr };
UIViewGroup* animatorGroup_ { nullptr };
UIToggleButton* toggleButton_ { nullptr };
UIViewGroup* toggleButtonArea_ { nullptr };
UILabel* currentTimeLabel_ { nullptr };
UISlider* slider_ { nullptr };
UILabel* totalTimeLabel_ { nullptr };
UILabel* errorTips_ { nullptr };
};
} // namespace OHOS
#endif // OHOS_PLAYER_ABILITY_SLICE_H
\ No newline at end of file
/*
* Copyright (c) 2020 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 "gallery_ability.h"
namespace OHOS {
REGISTER_AA(GalleryAbility)
void GalleryAbility::OnStart(const Want &want)
{
printf("GalleryAbility::OnStart\n");
SetMainRoute("GalleryAbilitySlice");
Ability::OnStart(want);
}
void GalleryAbility::OnInactive()
{
printf("GalleryAbility::OnInactive\n");
Ability::OnInactive();
}
void GalleryAbility::OnActive(const Want &want)
{
printf("GalleryAbility::OnActive\n");
Ability::OnActive(want);
}
void GalleryAbility::OnBackground()
{
printf("GalleryAbility::OnBackground\n");
Ability::OnBackground();
}
void GalleryAbility::OnStop()
{
printf("GalleryAbility::OnStop\n");
Ability::OnStop();
}
}
\ No newline at end of file
/*
* Copyright (c) 2020 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 "gallery_ability_slice.h"
#include "ability_env.h"
#include "ability_manager.h"
#include "picture_ability_slice.h"
#include "file.h"
#include "securec.h"
namespace OHOS {
REGISTER_AS(GalleryAbilitySlice)
GalleryAbilitySlice::~GalleryAbilitySlice()
{
printf("~GalleryAbilitySlice() | start \n");
Clear();
printf("~GalleryAbilitySlice() | end \n");
}
void GalleryAbilitySlice::Clear()
{
printf("GalleryAbilitySlice::Clear() | start \n");
if (backIcon_ != nullptr) {
delete backIcon_;
backIcon_ = nullptr;
}
if (backIconListener_ != nullptr) {
delete backIconListener_;
backIconListener_ = nullptr;
}
if (deleteClickListener_ != nullptr) {
delete deleteClickListener_;
deleteClickListener_ = nullptr;
}
if (backArea_ != nullptr) {
delete backArea_;
backArea_ = nullptr;
}
if (titleLabel_ != nullptr) {
delete titleLabel_;
titleLabel_ = nullptr;
}
if (deleteLabel_ != nullptr) {
delete deleteLabel_;
deleteLabel_ = nullptr;
}
ClearThumb();
if (rootView_ != nullptr) {
RootView::DestoryWindowRootView(rootView_);
rootView_ = nullptr;
}
printf("GalleryAbilitySlice::Clear() | end \n");
}
void GalleryAbilitySlice::ClearThumb()
{
printf("GalleryAbilitySlice::ClearThumb() | start \n");
if (picContainer_ != nullptr) {
delete picContainer_;
picContainer_ = nullptr;
}
if (picList_ != nullptr) {
ClearPictureList(picList_);
delete picList_;
picList_ = nullptr;
}
for (uint16_t i = 0; i < pictureCount_; i++) {
if (pictureName_[i] != nullptr) {
delete[] pictureName_[i];
pictureName_[i] = nullptr;
}
}
for (uint16_t i = 0; i < pictureOnClickListenerCount_; i++) {
if (pictureOnClickListener_[i] != nullptr) {
delete pictureOnClickListener_[i];
pictureOnClickListener_[i] = nullptr;
}
}
pictureCount_ = 0;
pictureOnClickListenerCount_ = 0;
printf("GalleryAbilitySlice::ClearThumb() | end \n");
}
void GalleryAbilitySlice::ClearPictureList(const UIView* view)
{
printf("GalleryAbilitySlice::ClearPictureList() | start \n");
if (view == nullptr || !(view->IsViewGroup())) {
return;
}
UIView* child = static_cast<const UIViewGroup*>(view)->GetChildrenHead();
UIView* childNext = nullptr;
while (child != nullptr) {
childNext = child->GetNextSibling();
if (child->IsViewGroup()) {
ClearPictureList(child);
}
delete child;
child = childNext;
}
printf("GalleryAbilitySlice::ClearPictureList() | end \n");
}
void GalleryAbilitySlice::InitTitle()
{
printf("GalleryAbilitySlice::InitTitle | start \n");
backIcon_ = new UIImageView();
backIcon_->SetPosition(BACK_ICON_POSITION_X, BACK_ICON_POSITION_Y);
backIcon_->SetSrc(g_backIconAbsolutePath);
backIcon_->SetTouchable(true);
backArea_ = new UIViewGroup();
backArea_->SetPosition(0, 0, LABEL_POSITION_X, LABEL_HEIGHT);
backArea_->SetStyle(STYLE_BACKGROUND_OPA, 0);
backArea_->SetTouchable(true);
auto onClick = [this] (UIView& view, const Event& event) -> bool {
printf("############ Next AS enter #############\n");
TerminateAbility();
printf("############ Next AS exit #############\n");
return true;
};
backIconListener_ = new EventListener(onClick, nullptr);
backIcon_->SetOnClickListener(backIconListener_);
backArea_->SetOnClickListener(backIconListener_);
titleLabel_ = new UILabel();
titleLabel_->SetPosition(LABEL_POSITION_X, LABEL_POSITION_Y, LABEL_WIDTH, LABEL_HEIGHT);
titleLabel_->SetAlign(UITextLanguageAlignment::TEXT_ALIGNMENT_LEFT, UITextLanguageAlignment::TEXT_ALIGNMENT_CENTER);
titleLabel_->SetFont(FONT_NAME, GALLERY_FONT_SIZE);
titleLabel_->SetText("照片");
deleteLabel_ = new UILabel();
deleteLabel_->SetPosition(ROOT_VIEW_WIDTH - DELETE_LABEL_WIDTH, LABEL_POSITION_Y,
DELETE_LABEL_WIDTH, LABEL_HEIGHT);
deleteLabel_->SetAlign(UITextLanguageAlignment::TEXT_ALIGNMENT_LEFT,
UITextLanguageAlignment::TEXT_ALIGNMENT_CENTER);
deleteLabel_->SetFont(FONT_NAME, GALLERY_DELETE_FONT_SIZE);
deleteLabel_->SetText("全部删除");
deleteLabel_->SetTouchable(true);
auto deleteClick = [this] (UIView& view, const Event& event) -> bool {
printf("############ DeleteAllData click enter #############\n");
DeleteAllData();
printf("############ DeleteAllData click exit #############\n");
return true;
};
deleteClickListener_ = new EventListener(deleteClick, nullptr);
deleteLabel_->SetOnClickListener(deleteClickListener_);
backArea_->Add(backIcon_);
rootView_->Add(backArea_);
rootView_->Add(titleLabel_);
rootView_->Add(deleteLabel_);
}
void GalleryAbilitySlice::InitPictureList()
{
printf("GalleryAbilitySlice::InitPictureList | start \n");
picContainer_ = new UIScrollView();
picContainer_->SetPosition(0, LABEL_POSITION_Y + LABEL_HEIGHT);
picContainer_->Resize(ROOT_VIEW_WIDTH, (THUMBNAIL_RESOLUTION_Y + THUMBNAIL_SPACE) * THUMBNAIL_COLUMN);
picContainer_->SetStyle(STYLE_BACKGROUND_OPA, 0);
rootView_->Add(picContainer_);
picList_ = new UIViewGroup();
picList_->SetPosition(0, 0, ROOT_VIEW_WIDTH, ROOT_VIEW_HEIGHT);
picList_->SetStyle(STYLE_BACKGROUND_OPA, 0);
int16_t numInLine = (ROOT_VIEW_WIDTH + THUMBNAIL_SPACE) / (THUMBNAIL_RESOLUTION_X + THUMBNAIL_SPACE);
int16_t offset = ((ROOT_VIEW_WIDTH + THUMBNAIL_SPACE) % (THUMBNAIL_RESOLUTION_X + THUMBNAIL_SPACE)) / 2; // 2: half
AddAllPictures(Point { offset, 0 }, numInLine);
int16_t totalHeight = (pictureCount_ / numInLine) * (THUMBNAIL_RESOLUTION_Y + THUMBNAIL_SPACE);
if ((pictureCount_ % numInLine) != 0) {
totalHeight += THUMBNAIL_RESOLUTION_Y + THUMBNAIL_SPACE;
}
picList_->Resize(ROOT_VIEW_WIDTH, totalHeight);
printf("------------ totalHeight : %d ------------", totalHeight);
picContainer_->Add(picList_);
}
void GalleryAbilitySlice::AddAllPictures(const Point& pos, int16_t numInLine)
{
printf("GalleryAbilitySlice::AddAllPictures | start | %d\n", numInLine);
Point imagePos = pos;
void* drip = FileOpenDir(THUMBNAIL_DIRECTORY);
if (drip == nullptr) {
return;
}
FileDirentInfo* info = new FileDirentInfo();
while (FileReadDir(drip, info) >= 0 && pictureCount_ < MAX_PICTURE_COUNT) {
uint16_t imageNameLen = static_cast<uint16_t>(strlen(info->name));
if (imageNameLen > MAX_PATH_LENGTH) {
printf("GalleryAbilitySlice::AddAllPictures | imageNameLen > MAX_PATH_LENGTH | %d\n", imageNameLen);
continue;
}
char* imageName = new char[imageNameLen + 1]();
memcpy_s(imageName, imageNameLen + 1, info->name, imageNameLen + 1);
pictureName_[pictureCount_] = imageName;
pictureCount_++;
uint16_t pathLen = static_cast<uint16_t>(strlen(THUMBNAIL_DIRECTORY)) + imageNameLen + 1;
if (pathLen > MAX_PATH_LENGTH) {
printf("GalleryAbilitySlice::AddAllPictures | pathLen > MAX_PATH_LENGTH | %d\n", pathLen);
continue;
}
char* imagePath = new char[pathLen + 1]();
if (sprintf_s(imagePath, pathLen + 1, "%s/%s", THUMBNAIL_DIRECTORY, info->name) < 0) {
printf("GalleryAbilitySlice::AddAllPictures | sprintf_s error\n");
delete[] imagePath;
continue;
}
picList_->Add(CreateImageItem(imagePos, imageName, imagePath));
delete[] imagePath;
if ((pictureCount_ % numInLine) == 0) {
imagePos.x = pos.x;
imagePos.y += THUMBNAIL_RESOLUTION_Y + THUMBNAIL_SPACE;
} else {
imagePos.x += THUMBNAIL_RESOLUTION_X + THUMBNAIL_SPACE;
}
}
delete info;
FileCloseDir(drip);
}
UIView* GalleryAbilitySlice::CreateImageItem(const Point& pos, const char* imageName, const char* imagePath)
{
UIImageView* imageView = new UIImageView();
imageView->SetAutoEnable(false);
imageView->Resize(THUMBNAIL_RESOLUTION_X, THUMBNAIL_RESOLUTION_Y);
imageView->SetSrc(imagePath);
pictureOnClickListener_[pictureOnClickListenerCount_] = GetImageClickListener(imageName);
imageView->SetOnClickListener(pictureOnClickListener_[pictureOnClickListenerCount_++]);
imageView->SetTouchable(true);
if (strncmp(imageName, PHOTO_PREFIX, strlen(PHOTO_PREFIX)) == 0) {
imageView->SetPosition(pos.x, pos.y);
return imageView;
}
imageView->SetPosition(0, 0);
UIViewGroup* imageItem = new UIViewGroup();
imageItem->SetStyle(STYLE_BACKGROUND_OPA, 0);
imageItem->SetPosition(pos.x, pos.y, THUMBNAIL_RESOLUTION_X, THUMBNAIL_RESOLUTION_Y);
imageItem->SetTouchable(true);
imageItem->SetOnClickListener(imageView->GetOnClickListener());
UIImageView* videoTag = new UIImageView();
videoTag->SetPosition(VIDEO_TAG_POSITION_X, VIDEO_TAG_POSITION_Y);
videoTag->SetSrc(g_videoTagIconAbsolutePath);
videoTag->SetTouchable(true);
videoTag->SetOnClickListener(imageView->GetOnClickListener());
imageItem->Add(imageView);
imageItem->Add(videoTag);
return imageItem;
}
EventListener* GalleryAbilitySlice::GetImageClickListener(const char* path)
{
auto onClick = [this, path] (UIView& view, const Event& event) -> bool {
printf("############ Next AS enter #############\n");
Want wantData = { nullptr };
printf("------- imagePath: %s \n", path);
bool ret = SetWantData(&wantData, path, strlen(path) + 1);
if (!ret) {
printf("############ SetWantData error #############\n");
return ret;
}
AbilitySlice* nextSlice = nullptr;
if (strncmp(path, PHOTO_PREFIX, strlen(PHOTO_PREFIX)) == 0) {
printf("--------- enter PictureAbilitySlice \n");
nextSlice = AbilityLoader::GetInstance().GetAbilitySliceByName("PictureAbilitySlice");
} else {
printf("--------- enter PlayerAbilitySlice \n");
nextSlice = AbilityLoader::GetInstance().GetAbilitySliceByName("PlayerAbilitySlice");
}
if (nextSlice == nullptr) {
printf("undefined nextSlice\n");
} else {
Present(*nextSlice, wantData);
}
printf("############ Next AS exit #############\n");
return true;
};
return new EventListener(onClick, nullptr);
}
void GalleryAbilitySlice::DeleteAllData()
{
picContainer_->Invalidate();
rootView_->Remove(picContainer_);
ClearThumb();
DeleteAllFilesInDir(THUMBNAIL_DIRECTORY);
DeleteAllFilesInDir(PHOTO_DIRECTORY);
DeleteAllFilesInDir(VIDEO_SOURCE_DIRECTORY);
InitPictureList();
}
void GalleryAbilitySlice::DeleteAllFilesInDir(const char* path)
{
void* drip = FileOpenDir(path);
if (drip == nullptr) {
return;
}
FileDirentInfo* info = new FileDirentInfo();
while (FileReadDir(drip, info) >= 0) {
uint16_t fileNameLen = static_cast<uint16_t>(strlen(info->name));
uint16_t pathLen = static_cast<uint16_t>(strlen(path)) + fileNameLen + 1;
if (pathLen > MAX_PATH_LENGTH) {
printf("GalleryAbilitySlice::AddAllPictures | pathLen > MAX_PATH_LENGTH | %d\n", pathLen);
continue;
}
char* filePath = new char[pathLen + 1]();
if (sprintf_s(filePath, pathLen + 1, "%s/%s", path, info->name) < 0) {
printf("GalleryAbilitySlice::AddAllPictures | sprintf_s error\n");
delete[] filePath;
continue;
}
if (FileUnlink(filePath) != 0) {
printf("unlink file error | %s\n", filePath);
}
delete[] filePath;
}
delete info;
FileCloseDir(drip);
printf("GalleryAbilitySlice::DeleteAllFilesInDir() | success | %s\n", path);
}
void GalleryAbilitySlice::OnStart(const Want &want)
{
AbilitySlice::OnStart(want);
rootView_ = RootView::GetWindowRootView();
rootView_->SetPosition(ROOT_VIEW_POSITION_X, ROOT_VIEW_POSITION_Y);
rootView_->Resize(ROOT_VIEW_WIDTH, ROOT_VIEW_HEIGHT);
rootView_->SetStyle(STYLE_BACKGROUND_COLOR, Color::Black().full);
const char* pathHeader = GetSrcPath();
if (sprintf_s(g_backIconAbsolutePath, MAX_PATH_LENGTH, "%s%s", pathHeader, BACK_ICON_PATH) < 0) {
printf("GalleryAbilitySlice::OnStart | g_backIconAbsolutePath error");
return;
}
if (sprintf_s(g_videoTagIconAbsolutePath, MAX_PATH_LENGTH, "%s%s", pathHeader, VIDEO_TAG_ICON_PATH) < 0) {
printf("GalleryAbilitySlice::OnStart | g_videoTagIconAbsolutePath error");
return;
}
InitTitle();
InitPictureList();
SetUIContent(rootView_);
}
void GalleryAbilitySlice::OnInactive()
{
printf("GalleryAbilitySlice::OnInactive\n");
AbilitySlice::OnInactive();
}
void GalleryAbilitySlice::OnActive(const Want &want)
{
printf("GalleryAbilitySlice::OnActive\n");
AbilitySlice::OnActive(want);
}
void GalleryAbilitySlice::OnBackground()
{
printf("GalleryAbilitySlice::OnBackground\n");
AbilitySlice::OnBackground();
}
void GalleryAbilitySlice::OnStop()
{
printf("GalleryAbilitySlice::OnStop\n");
AbilitySlice::OnStop();
Clear();
}
}
\ No newline at end of file
/*
* Copyright (c) 2020 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 "picture_ability_slice.h"
#include "ability_env.h"
#include "file.h"
#include "gallery_config.h"
#include "securec.h"
namespace OHOS {
REGISTER_AS(PictureAbilitySlice)
PictureAbilitySlice::~PictureAbilitySlice()
{
Clear();
}
void PictureAbilitySlice::Clear()
{
printf("PictureAbilitySlice::Clear() | start \n");
if (backIcon_ != nullptr) {
delete backIcon_;
backIcon_ = nullptr;
}
if (backIconListener_ != nullptr) {
delete backIconListener_;
backIconListener_ = nullptr;
}
if (backArea_ != nullptr) {
delete backArea_;
backArea_ = nullptr;
}
if (picture_ != nullptr) {
delete picture_;
picture_ = nullptr;
}
if (rootView_ != nullptr) {
RootView::DestoryWindowRootView(rootView_);
rootView_ = nullptr;
}
printf("PictureAbilitySlice::Clear() | end \n");
}
void PictureAbilitySlice::InitTitle()
{
printf("PictureAbilitySlice::InitTitle | start \n");
backIcon_ = new UIImageView();
backIcon_->SetPosition(BACK_ICON_POSITION_X, BACK_ICON_POSITION_Y);
backIcon_->SetSrc(g_backIconAbsolutePath);
backIcon_->SetTouchable(true);
backArea_ = new UIViewGroup();
backArea_->SetPosition(0, 0, LABEL_POSITION_X, LABEL_HEIGHT);
backArea_->SetStyle(STYLE_BACKGROUND_OPA, 0);
backArea_->SetTouchable(true);
auto onClick = [this] (UIView &view, const Event &event) -> bool {
printf("############ terminate AS enter #############\n");
Terminate();
printf("############ terminate AS exit #############\n");
return true;
};
backIconListener_ = new EventListener(onClick, nullptr);
backIcon_->SetOnClickListener(backIconListener_);
backArea_->SetOnClickListener(backIconListener_);
backArea_->Add(backIcon_);
rootView_->Add(backArea_);
}
void PictureAbilitySlice::InitPicture(const char* path)
{
printf("PictureAbilitySlice::InitPicture | start | %s\n", path);
picture_ = new UIImageView();
picture_->SetSrc(path);
int16_t imageWidth = picture_->GetWidth();
int16_t imageHeight = picture_->GetHeight();
if (imageWidth > ROOT_VIEW_WIDTH || imageHeight > ROOT_VIEW_HEIGHT) {
TransformMap transMap(picture_->GetOrigRect());
float scaleWidth = 1.0;
float scaleHeight = 1.0;
if (imageWidth > ROOT_VIEW_WIDTH) {
scaleWidth = static_cast<float>(ROOT_VIEW_WIDTH) / imageWidth;
printf("########## scaleWidth: %f \n", scaleWidth);
}
if (imageHeight > ROOT_VIEW_HEIGHT) {
scaleHeight = static_cast<float>(ROOT_VIEW_HEIGHT) / imageHeight;
printf("########## scaleHeight: %f \n", scaleHeight);
}
float scale = (scaleWidth < scaleHeight) ? scaleWidth : scaleHeight;
printf("########## scale: %f \n", scale);
transMap.Scale(Vector2<float>(scale, scale), Vector2<int16_t>(0, 0));
picture_->SetTransformMap(transMap);
picture_->SetTransformAlgorithm(TransformAlgorithm::NEAREST_NEIGHBOR);
imageWidth = imageWidth * scale;
imageHeight = imageHeight * scale;
}
int16_t imagePosX = (ROOT_VIEW_WIDTH - imageWidth) / 2; // 2: half
int16_t imagePosY = (ROOT_VIEW_HEIGHT - imageHeight) / 2; // 2: half
printf("########## image pos x: %d | y: %d \n", imagePosX, imagePosY);
picture_->SetPosition(imagePosX, imagePosY);
rootView_->Add(picture_);
}
void PictureAbilitySlice::OnStart(const Want &want)
{
printf("######### PictureAbilitySlice::OnStart\n");
printf("receive the data -> %s\n", reinterpret_cast<char*>(want.data));
AbilitySlice::OnStart(want);
rootView_ = RootView::GetWindowRootView();
rootView_->SetPosition(ROOT_VIEW_POSITION_X, ROOT_VIEW_POSITION_Y);
rootView_->Resize(ROOT_VIEW_WIDTH, ROOT_VIEW_HEIGHT);
rootView_->SetStyle(STYLE_BACKGROUND_COLOR, Color::Black().full);
uint16_t imagePathLen = strlen(PHOTO_DIRECTORY) + strlen(reinterpret_cast<char*>(want.data)) + 1;
if (imagePathLen > MAX_PATH_LENGTH) {
printf("---- imagePathLen > MAX_PATH_LENGTH | %d", imagePathLen);
return;
}
char* imagePath = new char[imagePathLen + 1]();
if (sprintf_s(imagePath, imagePathLen + 1, "%s/%s", PHOTO_DIRECTORY, reinterpret_cast<char*>(want.data)) < 0) {
printf("PictureAbilitySlice::OnStart | imagePath\n");
return;
}
const char* pathHeader = GetSrcPath();
if (sprintf_s(g_backIconAbsolutePath, MAX_PATH_LENGTH, "%s%s", pathHeader, BACK_ICON_PATH) < 0) {
printf("PictureAbilitySlice::OnStart | g_backIconAbsolutePath\n");
return;
}
InitPicture(imagePath);
InitTitle();
delete[] imagePath;
SetUIContent(rootView_);
}
void PictureAbilitySlice::OnInactive()
{
printf("PictureAbilitySlice::OnInactive\n");
AbilitySlice::OnInactive();
}
void PictureAbilitySlice::OnActive(const Want &want)
{
printf("PictureAbilitySlice::OnActive\n");
AbilitySlice::OnActive(want);
}
void PictureAbilitySlice::OnBackground()
{
printf("PictureAbilitySlice::OnBackground\n");
AbilitySlice::OnBackground();
}
void PictureAbilitySlice::OnStop()
{
printf("PictureAbilitySlice::OnStop\n");
AbilitySlice::OnStop();
Clear();
}
}
\ No newline at end of file
/*
* Copyright (c) 2020 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 "player_ability_slice.h"
#include <algorithm>
#include <vector>
#include "ability_env.h"
#include "ability_manager.h"
#include "components/ui_image_view.h"
#include "file.h"
using OHOS::Media::Player;
using OHOS::Media::Source;
using namespace OHOS::Media;
namespace OHOS {
REGISTER_AS(PlayerAbilitySlice)
PlayerAbilitySlice::~PlayerAbilitySlice()
{
printf("################ ~PlayerAbilitySlice enter\n");
/** released in DestoryPlayer(). */
printf("################ ~PlayerAbilitySlice exit\n");
}
void PlayerAbilitySlice::Clear()
{
printf("PlayerAbilitySlice::Clear | enter\n");
if (backIconListener_ != nullptr) {
delete backIconListener_;
backIconListener_ = nullptr;
}
if (onClickListener_ != nullptr) {
delete onClickListener_;
onClickListener_ = nullptr;
}
if (surfaceView_ != nullptr) {
delete surfaceView_;
surfaceView_ = nullptr;
}
if (animatorGroup_ != nullptr) {
delete animatorGroup_;
animatorGroup_ = nullptr;
}
if (backIcon_ != nullptr) {
delete backIcon_;
backIcon_ = nullptr;
}
if (backArea_ != nullptr) {
delete backArea_;
backArea_ = nullptr;
}
if (errorTips_ != nullptr) {
delete errorTips_;
errorTips_ = nullptr;
}
if (totalTimeLabel_ != nullptr) {
delete totalTimeLabel_;
totalTimeLabel_ = nullptr;
}
if (currentTimeLabel_ != nullptr) {
delete currentTimeLabel_;
currentTimeLabel_ = nullptr;
}
if (slider_ != nullptr) {
delete slider_;
slider_ = nullptr;
}
if (toggleButton_ != nullptr) {
delete toggleButton_;
toggleButton_ = nullptr;
}
if (toggleButtonArea_ != nullptr) {
delete toggleButtonArea_;
toggleButtonArea_ = nullptr;
}
if (rootView_ != nullptr) {
RootView::DestoryWindowRootView(rootView_);
rootView_ = nullptr;
}
printf("PlayerAbilitySlice::Clear() | end\n");
}
void PlayerAbilitySlice::ShowErrorTips()
{
errorTips_ = new UILabel();
errorTips_->SetPosition(ROOT_VIEW_POSITION_X, ROOT_VIEW_POSITION_Y, ROOT_VIEW_WIDTH, ROOT_VIEW_HEIGHT);
errorTips_->SetAlign(UITextLanguageAlignment::TEXT_ALIGNMENT_CENTER,
UITextLanguageAlignment::TEXT_ALIGNMENT_CENTER);
errorTips_->SetFont(FONT_NAME, GALLERY_FONT_SIZE);
errorTips_->SetText("视频播放错误");
rootView_->Add(backArea_);
rootView_->Add(errorTips_);
rootView_->Add(backIcon_);
SetUIContent(rootView_);
}
void PlayerAbilitySlice::SetUpRootView()
{
if (rootView_ != nullptr) {
return;
}
rootView_ = RootView::GetWindowRootView();
rootView_->SetPosition(ROOT_VIEW_POSITION_X, ROOT_VIEW_POSITION_Y);
rootView_->Resize(ROOT_VIEW_WIDTH, ROOT_VIEW_HEIGHT);
rootView_->SetStyle(STYLE_BACKGROUND_COLOR, Color::Black().full);
}
void PlayerAbilitySlice::SetUpBackArea(const char* pathHeader)
{
auto onClick = [this] (UIView &view, const Event &event) -> bool {
printf("############ PlayerAbilitySlice terminate AS enter #############\n");
Terminate();
printf("############ PlayerAbilitySlice terminate AS exit #############\n");
return true;
};
backIcon_ = new UIImageView();
backIcon_->SetPosition(BACK_ICON_POSITION_X, BACK_ICON_POSITION_Y);
if (sprintf_s(g_backIconAbsolutePath, MAX_PATH_LENGTH, "%s%s", pathHeader, BACK_ICON_PATH) < 0) {
printf("PlayerAbilitySlice::OnStart | g_backIconAbsolutePath | %s\n", pathHeader);
return;
}
backIcon_->SetSrc(g_backIconAbsolutePath);
backIcon_->SetTouchable(true);
backIconListener_ = new EventListener(onClick, nullptr);
backIcon_->SetOnClickListener(backIconListener_);
backArea_ = new UIViewGroup();
backArea_->SetPosition(0, 0, LABEL_POSITION_X, LABEL_HEIGHT);
backArea_->SetStyle(STYLE_BACKGROUND_OPA, 0);
backArea_->SetTouchable(true);
backArea_->SetOnClickListener(backIconListener_);
rootView_->Add(backArea_);
rootView_->Add(backIcon_);
}
void PlayerAbilitySlice::SetUpVideoPlayer(const Want &want)
{
if (videoPlayer_ == nullptr) {
videoPlayer_ = new PlayerAdapter();
}
videoPlayer_->sourceType = 1;
uint16_t videoPathLen = strlen(VIDEO_SOURCE_DIRECTORY) + strlen(reinterpret_cast<char*>(want.data)) + 1;
int8_t ret = sprintf_s(videoPlayer_->filePath, videoPathLen + 1, "%s/%s", VIDEO_SOURCE_DIRECTORY,
reinterpret_cast<char*>(want.data));
if (ret < 0) {
printf("PlayerAbilitySlice::OnStart | videoPlayer_->filePath | %s\n", reinterpret_cast<char*>(want.data));
return;
}
ret = sprintf_s(&videoPlayer_->filePath[videoPathLen - strlen(AVAILABEL_SOURCE_TYPE)],
strlen(AVAILABEL_SOURCE_TYPE) + 1, "%s", AVAILABEL_SOURCE_TYPE);
if (ret < 0) {
printf("PlayerAbilitySlice::OnStart | videoPlayer_->filePath \n");
return;
}
printf("------########### mp4 file path | %s\n", videoPlayer_->filePath);
videoPlayer_->adapter = std::make_shared<Player>();
std::string uri(videoPlayer_->filePath);
std::map<std::string, std::string> header;
Source source(uri, header);
videoPlayer_->adapter->SetSource(source);
}
bool PlayerAbilitySlice::SetUpSurfaceView()
{
if (surfaceView_ != nullptr) {
return true;
}
int32_t width = 0;
int32_t height = 0;
videoPlayer_->adapter->GetVideoWidth(width);
printf("[%s,%d] width:%d\n", __func__, __LINE__, width);
videoPlayer_->adapter->GetVideoHeight(height);
printf("[%s,%d] height:%d\n", __func__, __LINE__, height);
if (width <= 0 || height <= 0) {
videoPlayer_->adapter->Release();
delete videoPlayer_;
videoPlayer_ = nullptr;
printf("******** width <= 0 || height <= 0 | return \n");
ShowErrorTips();
return false;
}
float ratio_x = static_cast<float>(width) / ROOT_VIEW_WIDTH;
float ratio_y = static_cast<float>(height) / ROOT_VIEW_HEIGHT;
uint16_t surfaceViewWidth;
uint16_t surfaceViewHeight;
uint16_t surfaceViewPositionX = 0;
uint16_t surfaceViewPositionY = 0;
if (ratio_x > ratio_y) {
surfaceViewWidth = ROOT_VIEW_WIDTH;
surfaceViewHeight = height / ratio_x;
surfaceViewPositionY = (ROOT_VIEW_HEIGHT - surfaceViewHeight) / 2; // 2: half
} else {
surfaceViewWidth = width / ratio_y;
surfaceViewHeight = ROOT_VIEW_HEIGHT;
surfaceViewPositionX = (ROOT_VIEW_WIDTH - surfaceViewWidth) / 2; // 2: half
}
surfaceView_ = new UISurfaceView();
surfaceView_->SetPosition(surfaceViewPositionX, surfaceViewPositionY);
surfaceView_->SetWidth(surfaceViewWidth - 1);
surfaceView_->SetHeight(surfaceViewHeight);
videoPlayer_->adapter->SetVideoSurface(surfaceView_->GetSurface());
rootView_->Add(surfaceView_);
return true;
}
void PlayerAbilitySlice::SetUpProgress(int64_t duration)
{
slider_ = new UISlider();
slider_->SetPosition(SLIDER_X, SLIDER_Y, SLIDER_WIDTH, STATUS_BAR_GROUP_HEIGHT);
slider_->SetValidHeight(SLIDER_HEIGHT);
slider_->SetValidWidth(SLIDER_WIDTH - KNOB_WIDTH);
slider_->SetRange(SLIDER_WIDTH, 0);
slider_->SetValue(0);
slider_->SetKnobWidth(KNOB_WIDTH);
slider_->SetSliderRadius(SLIDER_HEIGHT, SLIDER_HEIGHT, KNOB_WIDTH / 2); // 2: half
slider_->SetKnobStyle(STYLE_BACKGROUND_COLOR, Color::White().full);
slider_->SetBackgroundStyle(STYLE_BACKGROUND_COLOR, 0x1A888888);
slider_->SetBackgroundStyle(STYLE_BACKGROUND_OPA, 90); // 90: opacity is 90
slider_->SetDirection(UISlider::Direction::DIR_LEFT_TO_RIGHT);
slider_->SetTouchable(false);
animatorGroup_->Add(slider_);
animator_ = new SliderAnimator(videoPlayer_, slider_, currentTimeLabel_, duration, surfaceView_);
AnimatorManager::GetInstance()->Add(animator_);
}
void PlayerAbilitySlice::SetUpAnimatorGroup(const char* pathHeader)
{
int64_t duration = 0;
videoPlayer_->adapter->GetDuration(duration);
printf("[%s,%d] GetDuration:%lld\n", __func__, __LINE__, duration);
animatorGroup_ = new UIViewGroup();
animatorGroup_->SetPosition(0, ROOT_VIEW_HEIGHT - STATUS_BAR_GROUP_HEIGHT,
ROOT_VIEW_WIDTH, STATUS_BAR_GROUP_HEIGHT);
animatorGroup_->SetStyle(STYLE_BACKGROUND_OPA, 0);
totalTimeLabel_ = new UILabel();
totalTimeLabel_->SetPosition(TOTAL_TIME_LABEL_X, TOTAL_TIME_LABEL_Y,
TOTAL_TIME_LABEL_WIDTH, TOTAL_TIME_LABEL_HEIGHT);
totalTimeLabel_->SetAlign(UITextLanguageAlignment::TEXT_ALIGNMENT_LEFT,
UITextLanguageAlignment::TEXT_ALIGNMENT_CENTER);
totalTimeLabel_->SetFont(FONT_NAME, PLAYER_FONT_SIZE);
int64_t second = duration / 1000; // 1000: 1s = 1000ms
char timer[6]; // 6: length of time label
if (sprintf_s(timer, sizeof(timer), "%02lld:%02lld", second / 60, second % 60) < 0) { // 60: 1minute = 60s
return;
}
totalTimeLabel_->SetText(timer);
totalTimeLabel_->SetTextColor(Color::White());
animatorGroup_->Add(totalTimeLabel_);
currentTimeLabel_ = new UILabel();
currentTimeLabel_->SetPosition(CURRENT_TIME_LABEL_X, CURRENT_TIME_LABEL_Y,
CURRENT_TIME_LABEL_WIDTH, CURRENT_TIME_LABEL_HEIGHT);
currentTimeLabel_->SetStyle(STYLE_BACKGROUND_COLOR, Color::Red().full);
currentTimeLabel_->SetFont(FONT_NAME, PLAYER_FONT_SIZE);
currentTimeLabel_->SetText("00:00");
currentTimeLabel_->SetTextColor(Color::White());
currentTimeLabel_->SetAlign(UITextLanguageAlignment::TEXT_ALIGNMENT_LEFT,
UITextLanguageAlignment::TEXT_ALIGNMENT_CENTER);
animatorGroup_->Add(currentTimeLabel_);
SetUpProgress(duration);
SetUpToggleButton(pathHeader);
rootView_->Add(animatorGroup_);
}
void PlayerAbilitySlice::SetUpToggleButton(const char* pathHeader)
{
toggleButton_ = new UIToggleButton();
toggleButton_->SetTouchable(false);
toggleButton_->SetPosition(TOGGLE_BUTTON_OFFSET_X, TOGGLE_BUTTON_OFFSET_Y,
TOGGLE_BUTTON_WIDTH, TOGGLE_BUTTON_HEIGHT);
toggleButton_->SetState(true);
if (sprintf_s(g_videoPlayAbsolutePath, MAX_PATH_LENGTH, "%s%s", pathHeader, VIDEO_PALY_PATH) < 0) {
printf("PlayerAbilitySlice::OnStart | g_videoPlayAbsolutePath\n");
return;
}
if (sprintf_s(g_videoPauseAbsolutePath, MAX_PATH_LENGTH, "%s%s", pathHeader, VIDEO_PAUSE_PATH) < 0) {
printf("PlayerAbilitySlice::OnStart | g_videoPauseAbsolutePath\n");
return;
}
toggleButton_->SetImages(g_videoPauseAbsolutePath, g_videoPlayAbsolutePath);
onClickListener_ = new ToggleBtnListener(toggleButton_, videoPlayer_, animator_, surfaceView_);
toggleButtonArea_ = new UIViewGroup();
toggleButtonArea_->SetStyle(STYLE_BACKGROUND_OPA, 0);
toggleButtonArea_->SetPosition(0, 0, TOGGLE_BUTTON_OFFSET_X + TOGGLE_BUTTON_WIDTH, STATUS_BAR_GROUP_HEIGHT);
toggleButtonArea_->SetTouchable(true);
toggleButtonArea_->SetOnClickListener(onClickListener_);
toggleButtonArea_->Add(toggleButton_);
animatorGroup_->Add(toggleButtonArea_);
}
void PlayerAbilitySlice::OnStart(const Want &want)
{
printf("@@@@@ PlayerAbilitySlice::OnStart\n");
AbilitySlice::OnStart(want);
SetUpRootView();
const char* pathHeader = GetSrcPath();
SetUpVideoPlayer(want);
videoPlayer_->adapter->Prepare();
if (!SetUpSurfaceView()) {
return;
}
SetUpBackArea(pathHeader);
SetUpAnimatorGroup(pathHeader);
SetUIContent(rootView_);
videoPlayer_->adapter->Play();
animator_->SetToggleButton(toggleButton_);
animator_->SetToggleBtnListener(onClickListener_);
animator_->Start();
printf("## @@@@@ PlayerAbilitySlice::OnStart | end \n");
}
void PlayerAbilitySlice::OnInactive()
{
printf("PlayerAbilitySlice::OnInactive\n");
AbilitySlice::OnInactive();
}
void PlayerAbilitySlice::OnActive(const Want &want)
{
printf("PlayerAbilitySlice::OnActive\n");
AbilitySlice::OnActive(want);
}
void PlayerAbilitySlice::OnBackground()
{
printf("PlayerAbilitySlice::OnBackground\n");
AbilitySlice::OnBackground();
}
void PlayerAbilitySlice::OnStop()
{
if (animator_ != nullptr) {
animator_->Stop();
AnimatorManager::GetInstance()->Remove(animator_);
delete animator_;
animator_ = nullptr;
}
if (videoPlayer_ != nullptr && videoPlayer_->adapter.get() != nullptr) {
videoPlayer_->adapter->Stop();
videoPlayer_->adapter->Release();
delete videoPlayer_;
videoPlayer_ = nullptr;
}
Clear();
printf("PlayerAbilitySlice::OnStop\n");
AbilitySlice::OnStop();
}
void SliderAnimator::Callback(UIView* view)
{
if (needRefreshPlayer_) {
videoPlayer_->adapter->Stop();
videoPlayer_->adapter->Release();
videoPlayer_->adapter = std::make_shared<Player>();
std::string uri(videoPlayer_->filePath);
std::map<std::string, std::string> header;
Source source(uri, header);
videoPlayer_->adapter->SetSource(source);
videoPlayer_->adapter->Prepare();
videoPlayer_->adapter->SetVideoSurface(surfaceView_->GetSurface());
videoPlayer_->adapter->Play();
needRefreshPlayer_ = false;
}
int64_t currentTime = 0;
videoPlayer_->adapter->GetCurrentTime(currentTime);
int64_t currentSecond = currentTime / 1000; // 1000: 1s = 1000ms
char time[6]; // 6: length of time label
sprintf_s(time, sizeof(time), "%02lld:%02lld", currentSecond / 60, currentSecond % 60); // 60: 1minute = 60s
timeLabel_->SetText(time);
timeLabel_->Invalidate();
int64_t curPosition = currentTime * slider_->GetRangeMax() / duration_;
slider_->SetValue(curPosition);
slider_->Invalidate();
if (currentTime >= duration_) {
listener_->SetCompleteFlag(true);
toggleButton_->SetState(false);
needRefreshPlayer_ = true;
Stop();
}
}
bool ToggleBtnListener::OnClick(UIView& view, const ClickEvent& event)
{
button_->OnClickEvent(event);
if (completeFlag_) {
animator_->Start();
button_->Invalidate();
completeFlag_ = false;
return true;
}
if (button_->GetState()) {
videoPlayer_->adapter->Play();
animator_->Resume();
printf("ToggleBtnListener::OnClick | play\n");
} else {
videoPlayer_->adapter->Pause();
animator_->Pause();
printf("ToggleBtnListener::OnClick | pause\n");
}
button_->Invalidate();
return true;
}
}
\ No newline at end of file
# Copyright (c) 2020 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.
copy("copy_hap") {
sources = [
"//applications/sample/camera/hap/launcher.hap",
"//applications/sample/camera/hap/setting.hap",
"//applications/sample/camera/hap/camera.hap",
"//applications/sample/camera/hap/gallery.hap",
]
outputs = [
"$root_out_dir/system/internal/{{source_file_part}}",
]
}
# Copyright (c) 2020 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/lite/config/component/lite_component.gni")
import("//build/lite/config/hap_pack.gni")
shared_library("launcher") {
sources = [
"launcher/src/main/cpp/main_ability.cpp",
"launcher/src/main/cpp/main_ability_slice.cpp",
"launcher/src/main/cpp/swipe_view.cpp",
"launcher/src/main/cpp/app_info.cpp",
"launcher/src/main/cpp/long_press_view.cpp",
"launcher/src/main/cpp/app_manage.cpp",
"launcher/src/main/cpp/view_group_page.cpp",
"launcher/src/main/cpp/time_weather_view.cpp"
]
deps = [
"//foundation/aafwk/frameworks/ability_lite:aafwk_abilitykit_lite",
"//foundation/appexecfwk/frameworks/bundle_lite:bundle",
"//foundation/communication/frameworks/ipc_lite:liteipc_adapter",
"//foundation/distributedschedule/services/samgr_lite/samgr:samgr",
"//utils/native/lite/kv_store:kv_store",
"//foundation/graphic/lite/frameworks/ui:ui",
"//foundation/graphic/lite/utils:graphic_utils",
"//foundation/graphic/lite/frameworks/surface",
]
include_dirs = [
"launcher/src/main/cpp",
"//foundation/aafwk/interfaces/kits/ability_lite",
"//foundation/graphic/lite/interfaces/kits/ui/components",
"//foundation/graphic/lite/interfaces/kits/ui",
"//foundation/graphic/lite/interfaces/kits/utils",
"//foundation/graphic/lite/interfaces/kits/config",
"//foundation/appexecfwk/interfaces/kits/bundle_lite",
"//foundation/aafwk/interfaces/kits/want_lite",
"//base/startup/interfaces/kits/syspara_lite",
]
defines = [
"ENABLE_WINDOW=1",
"ABILITY_WINDOW_SUPPORT",
"OHOS_APPEXECFWK_BMS_BUNDLEMANAGER"
]
}
lite_component("launcher_component") {
features = [
":launcher",
]
}
hap_pack("launcher_hap")
{
deps = [":launcher"]
mode = "hap"
json_path = "launcher/src/main/config.json"
ability_so_path = "$root_out_dir/liblauncher.so"
force = "true"
cert_profile = "cert/com.huawei.launcher_HarmonyAppProvision_release.p7b"
resources_path = "launcher/src/main/resources"
hap_name = "launcher"
}
{
"app": {
"bundleName": "com.huawei.launcher",
"vendor": "huawei",
"version": {
"code": 1,
"name": "1.0"
},
"apiVersion": {
"compatible": 3,
"target": 4
}
},
"deviceConfig": {
"default": {
"keepAlive": true
},
"smartCamera": {
"keepAlive": true
}
},
"module": {
"package": "com.huawei.launcher",
"name": ".MyHarmonyAbilityPackage",
"deviceType": [
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartVision"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "launcher",
"moduleType": "entry"
},
"abilities": [{
"name": "MainAbility",
"icon": "assets/launcher/resources/base/media/background.png",
"label": "launcher",
"launchType": "standard",
"type": "page",
"visible":true
}
]
}
}
/*
* Copyright (c) 2020 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 "app_info.h"
#include "ui_config.h"
namespace OHOS {
AppInfo::AppInfo()
{
ReSet();
}
void AppInfo::Release()
{
if (button_) {
delete button_;
button_ = nullptr;
}
if (lable_) {
delete lable_;
lable_ = nullptr;
}
if (appClickListener_) {
delete appClickListener_;
appClickListener_ = nullptr;
}
if (appLpListener_) {
delete appLpListener_;
appLpListener_ = nullptr;
}
if (appDListener_) {
delete appDListener_;
appDListener_ = nullptr;
}
}
AppInfo::~AppInfo()
{
Release();
}
void AppInfo::ReSet()
{
button_ = nullptr;
lable_ = nullptr;
appClickListener_ = nullptr;
appLpListener_ = nullptr;
appDListener_ = nullptr;
}
void AppInfo::SetButton(UILabelButton* button)
{
button->SetPosition(buttonXY_.x, buttonXY_.y, buttonHV_.x, buttonHV_.y);
button->SetFont(FOND_PATH, LAUNCHER_FOND_ID);
button->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_RADIUS, UIButton::PRESSED);
button->SetStyleForState(STYLE_BACKGROUND_OPA, TOTAL_OPACITY, UIButton::PRESSED);
button->SetStyleForState(STYLE_BORDER_OPA, TOTAL_OPACITY, UIButton::PRESSED);
button->SetStyle(STYLE_BORDER_RADIUS, BUTTON_RADIUS);
button->SetStyle(STYLE_BACKGROUND_OPA, TOTAL_OPACITY);
button->SetStyle(STYLE_BORDER_OPA, TOTAL_OPACITY);
button->SetStyle(STYLE_TEXT_COLOR, Color::ColorTo32(Color::White()));
button->SetImageSrc(appIconDir_, appIconDir_);
button_ = button;
}
void AppInfo::SetLable(UILabel* lable)
{
lable->SetPosition(lableXY_.x, lableXY_.y, lableHV_.x, lableHV_.y);
char* p = strrchr(appName_, static_cast<int>('.'));
if (p != nullptr) {
lable->SetText(p + 1);
} else {
lable->SetText(appName_);
}
lable->SetAlign(TEXT_ALIGNMENT_CENTER, TEXT_ALIGNMENT_TOP);
lable->SetFont(FOND_PATH, APP_FOND_ID);
lable->SetStyle(STYLE_BORDER_RADIUS, LABLE_RADIUS);
lable->SetStyle(STYLE_BACKGROUND_OPA, TOTAL_OPACITY);
lable_ = lable;
}
void AppInfo::SetListener(AppInfo* app)
{
AppClickListener* appClickListener = new AppClickListener(app->funcclick_, this);
button_->SetOnClickListener(appClickListener);
appClickListener_ = static_cast<UIView::OnClickListener*>(appClickListener);
AppLongPressListener* appLpListener = new AppLongPressListener(app->funclPress_, this);
button_->SetOnLongPressListener(appLpListener);
appLpListener_ = static_cast<UIView::OnLongPressListener*>(appLpListener);
AppDragListener* appDListener = new AppDragListener(this);
button_->SetDraggable(true);
button_->SetOnDragListener(appDListener);
appDListener_ = static_cast<UIView::OnDragListener*>(appDListener);
}
void AppInfo::SetLocation(int16_t r, int16_t c)
{
row_col_.x = r;
row_col_.y = c;
}
} // namespace OHOS
/*
* Copyright (c) 2020 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 OHOS_APP_INFO_H
#define OHOS_APP_INFO_H
#include <components/ui_label_button.h>
#include <components/ui_label.h>
#include <components/ui_view_group.h>
#include "native_base.h"
#include "ui_config.h"
namespace OHOS {
class AppInfo;
typedef bool (*funcLongPress)(AppInfo *app);
typedef bool (*funcClick)(AppInfo *app);
typedef bool (*UninstallApp)(AppInfo *app);
typedef bool (*AddApp)(AppInfo *app);
struct MyPoint {
int16_t x; // the x coordinate of the point
int16_t y; // the y coordinate of the point
};
class AppInfo {
public:
AppInfo();
virtual ~AppInfo();
void Release();
void ReSet();
void SetButton(UILabelButton *button);
void SetLable(UILabel *lable);
void SetListener(AppInfo *app);
void SetLocation(int16_t r, int16_t c);
UILabelButton* button_ { nullptr };
UILabel* lable_ { nullptr };
UIView::OnLongPressListener* appLpListener_ { nullptr };
UIView::OnDragListener* appDListener_ { nullptr };
UIView::OnClickListener* appClickListener_ { nullptr };
funcClick funcclick_ { nullptr };
funcLongPress funclPress_ { nullptr };
MyPoint lableXY_ { 0 };
MyPoint lableHV_ { 0 };
MyPoint buttonXY_ { 0 };
MyPoint buttonHV_ { 0 };
MyPoint row_col_ { 0 };
char appName_[TMP_BUF_SIZE];
char abilityName_[TMP_BUF_SIZE];
char appIconDir_[TMP_BUF_SIZE];
};
class AppDragListener : public UIView::OnDragListener {
public:
AppDragListener(AppInfo* app) : appInfo_(app) {}
virtual ~AppDragListener() {}
bool OnDrag(UIView &view, const DragEvent &event) override
{
return true;
}
bool OnDragEnd(UIView& view, const DragEvent& event) override
{
return true;
}
bool OnDragStart(UIView& view, const DragEvent& event) override
{
return true;
}
private:
AppInfo* appInfo_ { nullptr };
};
class AppClickListener : public UIView::OnClickListener {
public:
AppClickListener(funcClick func, AppInfo* app) : funcClick_(func), appInfo_(app) {}
virtual ~AppClickListener() {}
bool OnClick(UIView& view, const ClickEvent& event) override
{
funcClick_(appInfo_);
return true;
}
private:
funcClick funcClick_ { nullptr };
AppInfo *appInfo_ { nullptr };
};
class AppLongPressListener : public UIView::OnLongPressListener {
public:
AppLongPressListener(funcClick func, AppInfo* app) : appInfo_(app), funcLongPress_(func) {}
virtual ~AppLongPressListener() {}
bool OnLongPress(UIView& view, const LongPressEvent& event) override
{
funcLongPress_(appInfo_);
return true;
}
private:
AppInfo* appInfo_ { nullptr };
funcLongPress funcLongPress_ { nullptr };
};
} // namespace OHOS
#endif
/*
* Copyright (c) 2020 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 <stdio.h>
#include <securec.h>
#include "app_manage.h"
namespace OHOS {
ViewGroupPage* AppManage::viewPage_[MAX_VIEWGROUP] = { nullptr };
funcClick AppManage::installFuncclick_ = { nullptr };
funcLongPress AppManage::installFunclPress_ = { nullptr };
int AppManage::size_ = 0;
AppManage::~AppManage()
{
UnregisterCallback();
}
bool AppManage::GetAailityInfosByBundleName(const char* bundleName, AppInfo* pApp)
{
if (bundleName == nullptr || pApp == nullptr) {
return false;
}
uint8_t ret = -1;
BundleInfo* pBundleInfos = nullptr;
int count = 0;
ret = GetBundleInfos(1, &pBundleInfos, &count);
if (ret == 0) {
BundleInfo* pBundleInfo = pBundleInfos;
for (int i = 0; i < count; i++, pBundleInfo++) {
if (memcmp(bundleName, pBundleInfo->bundleName, strlen(pBundleInfo->bundleName)) == 0) {
memcpy_s(
pApp->appName_, sizeof(pApp->appName_), pBundleInfo->bundleName, strlen(pBundleInfo->bundleName));
pApp->appName_[strlen(pBundleInfo->bundleName)] = 0;
if (pBundleInfo->abilityInfos[0].name) {
memcpy_s(pApp->abilityName_, sizeof(pApp->abilityName_), pBundleInfo->abilityInfos[0].name,
strlen(pBundleInfo->abilityInfos[0].name));
pApp->abilityName_[strlen(pBundleInfo->abilityInfos[0].name)] = 0;
}
if (pBundleInfo->bigIconPath) {
memcpy_s(pApp->appIconDir_, sizeof(pApp->appIconDir_), pBundleInfo->bigIconPath,
strlen(pBundleInfo->bigIconPath));
pApp->appIconDir_[strlen(pBundleInfo->bigIconPath)] = 0;
}
return true;
}
}
}
return false;
}
bool AppManage::GetAppInstallInfo(const char* bundleName)
{
if (bundleName == nullptr) {
return false;
}
AppInfo* pApp = new AppInfo();
pApp->funcclick_ = installFuncclick_;
pApp->funclPress_ = installFunclPress_;
if (GetAailityInfosByBundleName(bundleName, pApp) == true) {
int i = 0;
for (; i < size_; i++) {
if (viewPage_[i]->FindApp(pApp)) {
break;
}
}
if (i == size_) {
for (i = 0; i < size_; i++) {
if (viewPage_[i]->AddApp(pApp)) {
return true;
}
}
}
}
delete pApp;
pApp = nullptr;
return false;
}
void AppManage::MyBundleStateCallback(
const uint8_t installType, const uint8_t resultCode, const void* resultMessage, const char* bundleName, void* data)
{
if (installType == 0) { // install update
if (resultCode == 0 && bundleName != nullptr) {
char tmpName[TMP_BUF_SIZE] = {0};
memcpy_s(tmpName, sizeof(tmpName), bundleName, strlen(bundleName));
tmpName[strlen(bundleName)] = 0;
GetAppInstallInfo(tmpName);
}
}
}
void AppManage::MyBundleOwnCallback(const uint8_t resultCode, const void* resultMessage)
{
// todo uninstall callback
}
bool AppManage::LauncherApp(BundleInfo** info, int& count)
{
callBackParam_.bundleName = nullptr;
callBackParam_.data = nullptr;
callBackParam_.callBack = MyBundleStateCallback;
RegisterCallback(&callBackParam_);
BundleInfo* pBundleInfos = nullptr;
uint8_t ret = GetBundleInfos(1, &pBundleInfos, &count);
if (ret == 0) {
*info = pBundleInfos;
return true;
} else {
*info = nullptr;
return false;
}
}
bool AppManage::InstallApp(AppInfo* app)
{
return true;
}
bool AppManage::UnInstallApp(AppInfo* app)
{
return Uninstall(app->appName_, nullptr, MyBundleOwnCallback);
}
bool AppManage::StartApp(AppInfo* app)
{
Want want1 = { nullptr };
ElementName element = { nullptr };
SetElementBundleName(&element, app->appName_);
SetElementAbilityName(&element, app->abilityName_);
SetWantElement(&want1, element);
SetWantData(&want1, "WantData", strlen("WantData") + 1);
StartAbility(&want1);
ClearElement(&element);
ClearWant(&want1);
return true;
}
void AppManage::SetViewGroup(funcClick click, funcLongPress press, ViewGroupPage* viewPage[MAX_VIEWGROUP], int size)
{
if (click == nullptr || press == nullptr || viewPage == nullptr) {
return;
}
for (int i = 0; i < size; i++) {
viewPage_[i] = viewPage[i];
}
size_ = size;
installFuncclick_ = click;
installFunclPress_ = press;
}
} // namespace OHOS
/*
* Copyright (c) 2020 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 OHOS_APP_MANAGE_H
#define OHOS_APP_MANAGE_H
#include <ability_info.h>
#include <ability_slice.h>
#include <bundle_manager.h>
#include <element_name.h>
#include <module_info.h>
#include <want.h>
#include "app_info.h"
#include "ui_config.h"
#include "view_group_page.h"
namespace OHOS {
class AppManage {
public:
AppManage() = default;
~AppManage();
// start all app ,get all app info
bool LauncherApp(BundleInfo** info, int& count);
bool InstallApp(AppInfo* app);
bool UnInstallApp(AppInfo* app);
bool StartApp(AppInfo* app);
static void SetViewGroup(funcClick click, funcLongPress press, ViewGroupPage* arrPage[MAX_VIEWGROUP], int size);
private:
static void MyBundleStateCallback(const uint8_t installType, const uint8_t resultCode, const void* resultMessage,
const char* bundleName, void* data);
static void MyBundleOwnCallback(const uint8_t resultCode, const void* resultMessage);
static bool GetAailityInfosByBundleName(const char* bundleName, AppInfo* pApp);
static bool GetAppInstallInfo(const char* bundleName);
private:
BundleStatusCallback callBackParam_ { nullptr };
static ViewGroupPage* viewPage_[MAX_VIEWGROUP];
static int size_;
static funcClick installFuncclick_;
static funcLongPress installFunclPress_;
};
} // namespace OHOS
#endif
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_EVENT_LISTENER_H
#define OHOS_EVENT_LISTENER_H
#include <components/ui_view.h>
#include <functional>
#include <utility>
namespace OHOS {
using OnEventFunc = std::function<bool(UIView& view, const Event& event)>;
class EventListener : public UIView::OnClickListener, public UIView::OnLongPressListener {
public:
EventListener() = delete;
~EventListener() override = default;
EventListener(OnEventFunc onClick, OnEventFunc onLongPress)
{
onClick_ = std::move(onClick);
onLongPress_ = std::move(onLongPress);
}
bool OnClick(UIView& view, const ClickEvent& event) override
{
if (!onClick_) {
return false;
}
return onClick_(view, event);
}
bool OnLongPress(UIView& view, const LongPressEvent& event) override
{
if (!onLongPress_) {
return false;
}
return onLongPress_(view, event);
}
private:
OnEventFunc onClick_ { nullptr };
OnEventFunc onLongPress_ { nullptr };
};
} // namespace OHOS
#endif
/*
* Copyright (c) 2020 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 "long_press_view.h"
#include "ui_config.h"
namespace OHOS {
LongPressView::LongPressView(UninstallApp uninstall)
{
bStatus_ = false;
uninstall_ = uninstall;
viewGroup_ = new UIViewGroup();
viewGroup_->SetStyle(STYLE_BACKGROUND_COLOR, Color::ColorTo32(Color::Black()));
viewGroup_->SetStyle(STYLE_BORDER_RADIUS, GROUP_VIEW_RADIUS);
viewGroup_->SetStyle(STYLE_BACKGROUND_OPA, UN_OPACITY);
buttUninstall_ = new UILabelButton();
buttUninstall_->SetStyle(STYLE_BACKGROUND_COLOR, Color::ColorTo32(Color::Gray()));
buttUninstall_->SetStyle(STYLE_BORDER_RADIUS, BUTTON_RADIUS);
buttUninstall_->SetStyle(STYLE_TEXT_COLOR, Color::ColorTo32(Color::White()));
buttUninstall_->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_RADIUS, UIButton::PRESSED);
buttUninstall_->SetStyleForState(STYLE_BACKGROUND_OPA, HALF_OPACITY, UIButton::PRESSED);
buttUninstall_->SetText("卸载");
buttUninstall_->SetFont(FOND_PATH, LAUNCHER_FOND_ID);
buttUninstall_->SetOnClickListener(this);
buttCancle_ = new UILabelButton();
buttCancle_->SetStyle(STYLE_BACKGROUND_COLOR, Color::ColorTo32(Color::Gray()));
buttCancle_->SetStyle(STYLE_BORDER_RADIUS, BUTTON_RADIUS);
buttCancle_->SetStyle(STYLE_TEXT_COLOR, Color::ColorTo32(Color::White()));
buttCancle_->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_RADIUS, UIButton::PRESSED);
buttCancle_->SetStyleForState(STYLE_BACKGROUND_OPA, HALF_OPACITY, UIButton::PRESSED);
buttCancle_->SetText("取消");
buttCancle_->SetFont(FOND_PATH, LAUNCHER_FOND_ID);
buttCancle_->SetOnClickListener(this);
viewGroup_->Add(buttUninstall_);
viewGroup_->Add(buttCancle_);
viewGroup_->SetVisible(false);
}
LongPressView::~LongPressView()
{
DeleteChildren(viewGroup_);
}
void LongPressView::RemoveLview()
{
if (bStatus_ == false) {
return;
}
viewParent_->Remove(viewGroup_);
viewGroup_->SetVisible(false);
viewParent_->Invalidate();
bStatus_ = false;
}
void LongPressView::Show(UIViewGroup* viewParent, AppInfo* pApp)
{
const int16_t HEIGHT_DISCOUNT = 3;
const int16_t WIDTH_DISCOUNT = 2;
bStatus_ = true;
viewParent_ = viewParent;
app_ = pApp;
viewGroup_->SetPosition(pApp->buttonXY_.x / WIDTH_DISCOUNT + pApp->button_->GetWidth(),
pApp->buttonXY_.y / WIDTH_DISCOUNT + pApp->button_->GetHeight(), pApp->button_->GetWidth(),
(pApp->button_->GetHeight() * WIDTH_DISCOUNT) / HEIGHT_DISCOUNT + pApp->button_->GetHeight() / WIDTH_DISCOUNT);
buttUninstall_->SetPosition(0, 0,
pApp->button_->GetWidth(), pApp->button_->GetHeight() / WIDTH_DISCOUNT);
buttCancle_->SetPosition(0, (pApp->button_->GetHeight() * WIDTH_DISCOUNT) / HEIGHT_DISCOUNT,
pApp->button_->GetWidth(), pApp->button_->GetHeight() / WIDTH_DISCOUNT);
viewGroup_->SetVisible(true);
viewParent_->Add(viewGroup_);
viewParent_->Invalidate();
}
bool LongPressView::OnClick(UIView& view, const ClickEvent& event)
{
UILabelButton* lbutt = nullptr;
lbutt = static_cast<UILabelButton*>(&view);
RemoveLview();
if (&view == buttUninstall_) {
uninstall_(app_);
}
return true;
}
} // namespace OHOS
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_LISTENTER_H
#define OHOS_LISTENTER_H
#include "app_info.h"
#include "view_group_page.h"
#include "app_manage.h"
namespace OHOS {
class LongPressView : public UIView::OnClickListener, public NativeBase {
public:
LongPressView(UninstallApp uninstall);
virtual ~LongPressView();
bool OnClick(UIView &view, const ClickEvent& event) override;
void RemoveLview();
void Show(UIViewGroup* viewParent, AppInfo* pApp);
void SetStatus(bool status)
{
bStatus_ = status;
}
bool GetStatus()
{
return bStatus_;
}
private:
UIViewGroup* viewParent_ { nullptr };
UIViewGroup* viewGroup_ { nullptr };
UILabelButton* buttUninstall_ { nullptr };
UILabelButton* buttCancle_ { nullptr };
UninstallApp uninstall_ { nullptr };
AppInfo* app_ { nullptr };
bool bStatus_ { false };
};
} // namespace OHOS
#endif
\ No newline at end of file
/*
* Copyright (c) 2020 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 "main_ability.h"
namespace OHOS {
REGISTER_AA(MainAbility)
void MainAbility::OnStart(const Want& want)
{
SetMainRoute("MainAbilitySlice");
Ability::OnStart(want);
}
void MainAbility::OnInactive()
{
Ability::OnInactive();
}
void MainAbility::OnActive(const Want& want)
{
Ability::OnActive(want);
}
void MainAbility::OnBackground()
{
Ability::OnBackground();
}
void MainAbility::OnStop()
{
Ability::OnStop();
}
} // namespace OHOS
\ No newline at end of file
/*
* Copyright (c) 2020 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 OHOS_MAIN_ABILITY_H
#define OHOS_MAIN_ABILITY_H
#include <ability_loader.h>
namespace OHOS {
class MainAbility : public Ability {
protected:
void OnStart(const Want& want) override;
void OnInactive() override;
void OnActive(const Want& want) override;
void OnBackground() override;
void OnStop() override;
};
} // namespace OHOS
#endif
/*
* Copyright (c) 2020 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 <stdio.h>
#include <common/screen.h>
#include <components/ui_label.h>
#include <components/ui_label_button.h>
#include "main_ability_slice.h"
#include "ability_manager.h"
namespace OHOS {
REGISTER_AS(MainAbilitySlice)
MainAbilitySlice::~MainAbilitySlice()
{
ReleaseView();
}
void MainAbilitySlice::ReleaseView()
{
if (swipeView_) {
delete swipeView_;
swipeView_ = nullptr;
}
if (uiImageView_) {
delete uiImageView_;
uiImageView_ = nullptr;
}
if (lableHead_) {
delete lableHead_;
lableHead_ = nullptr;
}
if (lableTail_) {
delete lableTail_;
lableTail_ = nullptr;
}
}
void MainAbilitySlice::SetHead()
{
char tmp[TMP_BUF_SIZE] = { 0 };
time_t t = time(nullptr);
struct tm* st = nullptr;
st = localtime(&t);
sprintf_s(tmp, sizeof(tmp), "%02d : %02d", st->tm_hour, st->tm_min);
UILabel* label = new UILabel();
rootview_->Add(label);
label->SetPosition(0, 0, LA_HORIZONTAL_RESOLUTION, LABLE_TITLE_HEIGHT);
label->SetText(tmp);
label->SetAlign(TEXT_ALIGNMENT_RIGHT, TEXT_ALIGNMENT_TOP);
label->SetFont(FOND_PATH, LAUNCHER_FOND_ID);
label->SetStyle(STYLE_TEXT_COLOR, Color::ColorTo32(Color::White()));
label->SetStyle(STYLE_BACKGROUND_OPA, TOTAL_OPACITY);
lableHead_ = label;
}
void MainAbilitySlice::SetTail()
{
UILabel* label = new UILabel();
rootview_->Add(label);
label->SetPosition(0, LA_VERTICAL_RESOLUTION - LABLE_TAIL_HEIGHT, LA_HORIZONTAL_RESOLUTION, LABLE_TAIL_HEIGHT);
char buf[TMP_BUF_SIZE] = { 0 };
sprintf_s(buf, sizeof(buf), ".%d.", 1);
label->SetText(buf);
label->SetAlign(TEXT_ALIGNMENT_CENTER, TEXT_ALIGNMENT_CENTER);
label->SetFont(FOND_PATH, LAUNCHER_FOND_ID);
label->SetStyle(STYLE_TEXT_COLOR, Color::ColorTo32(Color::White()));
label->SetStyle(STYLE_BACKGROUND_OPA, TOTAL_OPACITY);
lableTail_ = label;
}
void MainAbilitySlice::SetImageView()
{
uiImageView_ = new UIImageView();
// modify image view height
uiImageView_->SetPosition(0, 0, LA_HORIZONTAL_RESOLUTION, LA_VERTICAL_RESOLUTION);
uiImageView_->SetStyle(STYLE_BACKGROUND_COLOR, Color::ColorTo32(Color::White()));
uiImageView_->SetSrc(TABLE_BACKGROUND);
uiImageView_->SetStyle(STYLE_BACKGROUND_OPA, UN_OPACITY);
rootview_->Add(uiImageView_);
}
void MainAbilitySlice::SetSwipe()
{
swipeView_ = new SwipeView(lableHead_, lableTail_);
swipeView_->OnSetUpView();
rootview_->Add(swipeView_->GetSwipeView());
}
void MainAbilitySlice::OnStart(const Want& want)
{
AbilitySlice::OnStart(want);
LA_HORIZONTAL_RESOLUTION = Screen::GetInstance().GetWidth();
LA_VERTICAL_RESOLUTION = Screen::GetInstance().GetHeight();
rootview_ = RootView::GetWindowRootView();
rootview_->SetPosition(0, 0);
rootview_->Resize(LA_HORIZONTAL_RESOLUTION, LA_VERTICAL_RESOLUTION);
rootview_->SetStyle(STYLE_BACKGROUND_OPA, UN_OPACITY);
rootview_->SetStyle(STYLE_BACKGROUND_COLOR, Color::ColorTo32(Color::GetColorFromRGB(0x30, 0x30, 0x30)));
SetHead();
SetTail();
SetSwipe();
SetUIContent(rootview_);
rootview_->Invalidate();
}
void MainAbilitySlice::OnInactive()
{
AbilitySlice::OnInactive();
}
void MainAbilitySlice::OnActive(const Want& want)
{
AbilitySlice::OnActive(want);
}
void MainAbilitySlice::OnBackground()
{
AbilitySlice::OnBackground();
}
void MainAbilitySlice::OnStop()
{
AbilitySlice::OnStop();
}
} // namespace OHOS
/*
* Copyright (c) 2020 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 OHOS_MAIN_ABILITY_SLICE_H
#define OHOS_MAIN_ABILITY_SLICE_H
#include <ability_info.h>
#include <ability_loader.h>
#include <bundle_info.h>
#include <components/root_view.h>
#include <components/ui_image_view.h>
#include <components/ui_label.h>
#include <components/ui_label_button.h>
#include <components/ui_swipe_view.h>
#include <list.h>
#include "event_listener.h"
#include "swipe_view.h"
#include "ui_config.h"
namespace OHOS {
class MainAbilitySlice : public AbilitySlice {
public:
MainAbilitySlice() = default;
~MainAbilitySlice() override;
protected:
void OnStart(const Want& want) override;
void OnInactive() override;
void OnActive(const Want& want) override;
void OnBackground() override;
void OnStop() override;
void SetHead();
void SetTail();
void SetSwipe();
void ReleaseView();
void SetImageView();
private:
SwipeView* swipeView_ { nullptr };
UIImageView* uiImageView_ { nullptr };
UILabel* lableHead_ { nullptr };
UILabel* lableTail_ { nullptr };
RootView *rootview_ { nullptr };
};
} // namespace OHOS
#endif
/*
* Copyright (c) 2020 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 OHOS_NATIVE_BASE_H
#define OHOS_NATIVE_BASE_H
#include <components/ui_view_group.h>
namespace OHOS {
class NativeBase : public HeapBase {
public:
void DeleteChildren(UIView *view)
{
if (view == nullptr) {
return;
}
while (view) {
UIView *tempView = view;
view = view->GetNextSibling();
if (tempView->IsViewGroup()) {
DeleteChildren(static_cast<UIViewGroup *>(tempView)->GetChildrenHead());
}
if (tempView->GetParent()) {
static_cast<UIViewGroup *>(tempView->GetParent())->Remove(tempView);
}
delete tempView;
}
}
};
} // namespace OHOS
#endif
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
{
"app": {
"bundleName": "com.huawei.setting",
"vendor": "huawei",
"version": {
"code": 1,
"name": "1.0"
},
"apiVersion": {
"compatible": 3,
"target": 4
}
},
"deviceConfig": {
"default": {
}
},
"module": {
"package": "com.huawei.setting",
"name": ".MyHarmonyAbilityPackage",
"deviceType": [
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartVision"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "setting",
"moduleType": "entry"
},
"abilities": [{
"name": "SettingMainAbility",
"icon": "assets/setting/resources/base/media/setting.png",
"label": "test testapp2 1",
"launchType": "standard",
"type": "page",
"visible":true
}
]
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册