1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "wallpaper_service.h"
16
17 #include <display_type.h>
18 #include <fcntl.h>
19 #include <rs_surface_node.h>
20 #include <sys/sendfile.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include <window_manager.h>
25
26 #include <cerrno>
27 #include <cstdio>
28 #include <cstdlib>
29 #include <cstring>
30 #include <iostream>
31 #include <thread>
32
33 #include "ability_manager_client.h"
34 #include "accesstoken_adapter.h"
35 #include "bundle_mgr_proxy.h"
36 #include "canvas.h"
37 #include "color_picker.h"
38 #include "command.h"
39 #include "directory_ex.h"
40 #include "dump_helper.h"
41 #include "effect_errors.h"
42 #include "export/color.h"
43 #include "file_deal.h"
44 #include "file_ex.h"
45 #include "hilog_wrapper.h"
46 #include "hitrace_meter.h"
47 #include "image/bitmap.h"
48 #include "image_packer.h"
49 #include "image_source.h"
50 #include "image_type.h"
51 #include "image_utils.h"
52 #include "iservice_registry.h"
53 #include "pen.h"
54 #include "pixel_map.h"
55 #include "surface.h"
56 #include "system_ability_definition.h"
57 #include "wallpaper_common.h"
58 #include "wallpaper_common_event.h"
59 #include "wallpaper_service_cb_proxy.h"
60 #include "wallpaper_extension_ability_death_recipient.h"
61 #include "window.h"
62 #include "memory_guard.h"
63
64 namespace OHOS {
65 namespace WallpaperMgrService {
66 REGISTER_SYSTEM_ABILITY_BY_ID(WallpaperService, WALLPAPER_MANAGER_SERVICE_ID, true);
67
68 using namespace OHOS::Media;
69 using namespace OHOS::MiscServices;
70
71 const std::string WallpaperService::WALLPAPER = "wallpaper_orig";
72 const std::string WallpaperService::WALLPAPER_CROP = "wallpaper";
73 const std::string WallpaperService::WALLPAPER_LOCK_ORIG = "wallpaper_lock_orig";
74 const std::string WallpaperService::WALLPAPER_LOCK_CROP = "wallpaper_lock";
75 const std::string WallpaperService::WALLPAPER_BUNDLE_NAME = "com.ohos.launcher";
76
77 const std::int64_t INIT_INTERVAL = 10000L;
78 const std::int64_t DELAY_TIME = 1000L;
79 constexpr int HALF = 2;
80 constexpr int32_t CONNECT_EXTENSION_INTERVAL = 500000;
81 constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 360;
82 constexpr int HUNDRED = 100;
83 constexpr int FOO_MAX_LEN = 52428800;
84 constexpr int MAX_RETRY_TIMES = 20;
85 constexpr int32_t DEFAULT_WALLPAPER_ID = -1;
86 constexpr int32_t FILE_PERMISSION = 0440;
87 std::mutex WallpaperService::instanceLock_;
88
89 sptr<WallpaperService> WallpaperService::instance_;
90
91 std::shared_ptr<AppExecFwk::EventHandler> WallpaperService::serviceHandler_;
92
WallpaperService(int32_t systemAbilityId,bool runOnCreate)93 WallpaperService::WallpaperService(int32_t systemAbilityId, bool runOnCreate)
94 : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
95 {
96 }
97
WallpaperService()98 WallpaperService::WallpaperService() : state_(ServiceRunningState::STATE_NOT_START)
99 {
100 }
101
~WallpaperService()102 WallpaperService::~WallpaperService()
103 {
104 }
105
GetInstance()106 sptr<WallpaperService> WallpaperService::GetInstance()
107 {
108 if (instance_ == nullptr) {
109 std::lock_guard<std::mutex> autoLock(instanceLock_);
110 if (instance_ == nullptr) {
111 instance_ = new WallpaperService();
112 }
113 }
114 return instance_;
115 }
116
Init()117 int32_t WallpaperService::Init()
118 {
119 bool ret = Publish(this);
120 if (!ret) {
121 HILOG_ERROR("Publish failed.");
122 ReporterFault(FaultType::SERVICE_FAULT, FaultCode::SF_SERVICE_UNAVAIABLE);
123 return -1;
124 }
125 HILOG_INFO("Publish success.");
126 state_ = ServiceRunningState::STATE_RUNNING;
127 return E_OK;
128 }
129
OnStart()130 void WallpaperService::OnStart()
131 {
132 HILOG_INFO("Enter OnStart.");
133 MemoryGuard cacheGuard;
134 if (state_ == ServiceRunningState::STATE_RUNNING) {
135 HILOG_ERROR("WallpaperService is already running.");
136 return;
137 }
138 InitData();
139 InitServiceHandler();
140 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
141 std::thread(&WallpaperService::StartWallpaperExtension, this).detach();
142 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
143 auto cmd = std::make_shared<Command>(std::vector<std::string>({ "-all" }), "Show all",
144 [this, uid](const std::vector<std::string> &input, std::string &output) -> bool {
145 int32_t height = 0;
146 int32_t width = 0;
147 GetWallpaperMinHeight(height);
148 GetWallpaperMinWidth(width);
149 std::string bundleName(WALLPAPER_BUNDLE_NAME);
150 WPGetBundleNameByUid(uid, bundleName);
151 output.append("height\t\t\t: " + std::to_string(height) + "\n")
152 .append("width\t\t\t: " + std::to_string(width) + "\n")
153 .append("WallpaperExtension\t: ExtensionInfo{" + bundleName + "}\n");
154 return true;
155 });
156 DumpHelper::GetInstance().RegisterCommand(cmd);
157 StatisticReporter::StartTimerThread();
158 if (Init() != 0) {
159 auto callback = [=]() { Init(); };
160 serviceHandler_->PostTask(callback, INIT_INTERVAL);
161 HILOG_ERROR("Init failed. Try again 10s later");
162 return;
163 }
164 return;
165 }
166
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)167 void WallpaperService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
168 {
169 HILOG_INFO("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
170 if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
171 int times = 0;
172 RegisterSubscriber(times);
173 }
174 }
175
RegisterSubscriber(int times)176 void WallpaperService::RegisterSubscriber(int times)
177 {
178 MemoryGuard cacheGuard;
179 times++;
180 bool subRes = WallpaperCommonEvent::RegisterSubscriber();
181 if (subRes == false && times <= MAX_RETRY_TIMES) {
182 HILOG_INFO("RegisterSubscriber failed");
183 auto callback = [this, times]() { RegisterSubscriber(times); };
184 serviceHandler_->PostTask(callback, DELAY_TIME);
185 }
186 }
187
InitServiceHandler()188 void WallpaperService::InitServiceHandler()
189 {
190 HILOG_INFO("InitServiceHandler started.");
191 if (serviceHandler_ != nullptr) {
192 HILOG_ERROR("InitServiceHandler already init.");
193 return;
194 }
195 std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("WallpaperService");
196 serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
197
198 HILOG_INFO("InitServiceHandler succeeded.");
199 }
200
OnStop()201 void WallpaperService::OnStop()
202 {
203 HILOG_INFO("OnStop started.");
204 if (state_ != ServiceRunningState::STATE_RUNNING) {
205 return;
206 }
207 serviceHandler_ = nullptr;
208 recipient_ = nullptr;
209 state_ = ServiceRunningState::STATE_NOT_START;
210 HILOG_INFO("OnStop end.");
211 }
212
InitData()213 void WallpaperService::InitData()
214 {
215 HILOG_INFO("WallpaperService::initData --> start ");
216 userId_ = 0;
217 wallpaperId_ = DEFAULT_WALLPAPER_ID;
218 wallpaperMap_.Clear();
219 lockWallpaperMap_.Clear();
220 userId_ = GetUserId();
221 std::string userIdPath = GetWallpaperDir();
222 this->wallpaperLockScreenFilePath_ = userIdPath + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
223 this->wallpaperSystemFilePath_ = userIdPath + "/" + WALLPAPER_SYSTEM_DIRNAME;
224 wallpaperLockScreenFileFullPath_ = wallpaperLockScreenFilePath_ + "/" + WALLPAPER_LOCK_ORIG;
225 wallpaperLockScreenCropFileFullPath_ = wallpaperLockScreenFilePath_ + "/" + WALLPAPER_LOCK_CROP;
226 wallpaperSystemCropFileFullPath_ = wallpaperSystemFilePath_ + "/" + WALLPAPER_CROP;
227 wallpaperSystemFileFullPath_ = wallpaperSystemFilePath_ + "/" + WALLPAPER;
228 wallpaperTmpFullPath_ = wallpaperSystemFilePath_ + "/" + WALLPAPER_TMP_DIRNAME;
229 wallpaperCropPath = wallpaperSystemFilePath_ + "/" + WALLPAPER_CROP_PICTURE;
230 LoadSettingsLocked(userId_, true);
231 SaveColor(WALLPAPER_SYSTEM);
232 SaveColor(WALLPAPER_LOCKSCREEN);
233 systemWallpaperColor_ = 0;
234 lockWallpaperColor_ = 0;
235 colorChangeListenerMap_.clear();
236 HILOG_INFO("WallpaperService::initData --> end ");
237 }
238
AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> & remoteObject)239 void WallpaperService::AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> &remoteObject)
240 {
241 if (remoteObject != nullptr) {
242 IPCObjectProxy *proxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
243 if (recipient_ == nullptr) {
244 recipient_ = sptr<IRemoteObject::DeathRecipient>(new WallpaperExtensionAbilityDeathRecipient(*this));
245 }
246 if (proxy != nullptr && !proxy->IsObjectDead()) {
247 HILOG_INFO("get remoteObject succeed");
248 proxy->AddDeathRecipient(recipient_);
249 }
250 }
251 }
252
StartWallpaperExtension()253 void WallpaperService::StartWallpaperExtension()
254 {
255 MemoryGuard cacheGuard;
256 HILOG_INFO("WallpaperService StartWallpaperExtension");
257 int time = 0;
258 ErrCode ret = 0;
259 AAFwk::Want want;
260 want.SetElementName(WALLPAPER_BUNDLE_NAME, "WallpaperExtAbility");
261 AAFwk::AbilityManagerClient::GetInstance()->Connect();
262 HILOG_INFO("WallpaperService::Startwhile");
263 while (1) {
264 HILOG_INFO("WallpaperService::StartAbility");
265 time++;
266 ret = ConnectExtensionAbility(want);
267 if (ret == 0 || time == CONNECT_EXTENSION_MAX_RETRY_TIMES) {
268 break;
269 }
270 usleep(CONNECT_EXTENSION_INTERVAL);
271 HILOG_INFO("WallpaperService::StartAbility %{public}d", time);
272 }
273 if (ret != 0) {
274 HILOG_ERROR("WallpaperService::StartAbility --> failed ");
275 ReporterFault(FaultType::SERVICE_FAULT, FaultCode::SF_STARTABILITY_FAILED);
276 }
277 }
OnBootPhase()278 void WallpaperService::OnBootPhase()
279 {
280 HILOG_INFO("WallpaperService OnBootPhase");
281 AAFwk::Want want;
282 want.SetElementName(WALLPAPER_BUNDLE_NAME, "WallpaperExtAbility");
283 AAFwk::AbilityManagerClient::GetInstance()->Connect();
284 AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want);
285 }
286
GetUserId()287 int WallpaperService::GetUserId()
288 {
289 userId_ = 0;
290 return userId_;
291 }
292
GetDisplayId()293 int WallpaperService::GetDisplayId()
294 {
295 int displayid = 0;
296 return displayid;
297 }
298
GetWallpaperDir()299 std::string WallpaperService::GetWallpaperDir()
300 {
301 std::string sWallpaperPath = WALLPAPER_USERID_PATH + std::to_string(userId_);
302 return sWallpaperPath;
303 }
304
MakeWallpaperIdLocked()305 int WallpaperService::MakeWallpaperIdLocked()
306 {
307 HILOG_INFO("MakeWallpaperIdLocked start");
308 if (wallpaperId_ == INT32_MAX) {
309 wallpaperId_ = DEFAULT_WALLPAPER_ID;
310 }
311 return ++wallpaperId_;
312 }
313
LoadSettingsLocked(int userId,bool keepDimensionHints)314 void WallpaperService::LoadSettingsLocked(int userId, bool keepDimensionHints)
315 {
316 HILOG_INFO("load Setting locked start.");
317 if (!wallpaperMap_.Contains(userId)) {
318 HILOG_INFO("wallpaperMap_ does not contains userId");
319 MigrateFromOld();
320 WallpaperData wallpaper(userId, wallpaperSystemFileFullPath_, wallpaperSystemCropFileFullPath_);
321 wallpaper.allowBackup = true;
322 wallpaper.wallpaperId_ = DEFAULT_WALLPAPER_ID;
323 wallpaperMap_.InsertOrAssign(userId, wallpaper);
324 }
325
326 if (!lockWallpaperMap_.Contains(userId)) {
327 HILOG_INFO("lockWallpaperMap_ does not Contains userId");
328 WallpaperData wallpaperLock(userId, wallpaperLockScreenFileFullPath_, wallpaperLockScreenCropFileFullPath_);
329 wallpaperLock.allowBackup = true;
330 wallpaperLock.wallpaperId_ = DEFAULT_WALLPAPER_ID;
331 lockWallpaperMap_.InsertOrAssign(userId, wallpaperLock);
332 }
333 HILOG_INFO("load Setting locked end.");
334 }
335
MigrateFromOld()336 void WallpaperService::MigrateFromOld()
337 {
338 if (!OHOS::FileExists(wallpaperLockScreenFilePath_)) {
339 if (!OHOS::ForceCreateDirectory(wallpaperLockScreenFilePath_)) {
340 return;
341 }
342 }
343 if (!OHOS::FileExists(wallpaperSystemFilePath_)) {
344 if (!OHOS::ForceCreateDirectory(wallpaperSystemFilePath_)) {
345 return;
346 }
347 }
348 if (OHOS::FileExists(wallpaperSystemCropFileFullPath_)) {
349 if (!OHOS::FileExists(wallpaperSystemFileFullPath_)) {
350 int ret = FileDeal::CopyFile(wallpaperSystemCropFileFullPath_, wallpaperSystemFileFullPath_);
351 if (ret < 0) {
352 return;
353 }
354 }
355 } else if (OHOS::FileExists(WALLPAPER_DEFAULT_FILEFULLPATH)) {
356 int ret = FileDeal::CopyFile(WALLPAPER_DEFAULT_FILEFULLPATH, wallpaperSystemCropFileFullPath_);
357 if (ret < 0) {
358 return;
359 }
360 ret = FileDeal::CopyFile(WALLPAPER_DEFAULT_FILEFULLPATH, wallpaperSystemFileFullPath_);
361 if (ret < 0) {
362 return;
363 }
364 }
365 if (OHOS::FileExists(wallpaperLockScreenCropFileFullPath_)) {
366 if (!OHOS::FileExists(wallpaperLockScreenFileFullPath_)) {
367 int ret = FileDeal::CopyFile(wallpaperLockScreenCropFileFullPath_, wallpaperLockScreenFileFullPath_);
368 if (ret < 0) {
369 return;
370 }
371 }
372 } else if (OHOS::FileExists(WALLPAPER_DEFAULT_LOCK_FILEFULLPATH)) {
373 int ret = FileDeal::CopyFile(WALLPAPER_DEFAULT_LOCK_FILEFULLPATH, wallpaperLockScreenCropFileFullPath_);
374 if (ret < 0) {
375 return;
376 }
377 ret = FileDeal::CopyFile(WALLPAPER_DEFAULT_LOCK_FILEFULLPATH, wallpaperLockScreenFileFullPath_);
378 if (ret < 0) {
379 return;
380 }
381 }
382 }
383
GetColors(int32_t wallpaperType,std::vector<uint64_t> & colors)384 int32_t WallpaperService::GetColors(int32_t wallpaperType, std::vector<uint64_t> &colors)
385 {
386 if (wallpaperType == WALLPAPER_SYSTEM) {
387 colors.emplace_back(systemWallpaperColor_);
388 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
389 colors.emplace_back(lockWallpaperColor_);
390 }
391 HILOG_INFO(" Service End!");
392 return E_OK;
393 }
394
GetColorsV9(int32_t wallpaperType,std::vector<uint64_t> & colors)395 int32_t WallpaperService::GetColorsV9(int32_t wallpaperType, std::vector<uint64_t> &colors)
396 {
397 if (!IsSystemApp()) {
398 HILOG_INFO("CallingApp is not SystemApp");
399 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
400 }
401 return GetColors(wallpaperType, colors);
402 }
403
GetFile(int32_t wallpaperType,int32_t & wallpaperFd)404 int32_t WallpaperService::GetFile(int32_t wallpaperType, int32_t &wallpaperFd)
405 {
406 if (!WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
407 HILOG_INFO("GetFile no get permission!");
408 return static_cast<int32_t>(E_NO_PERMISSION);
409 }
410 int32_t ret = GetImageFd(wallpaperType, wallpaperFd);
411 HILOG_INFO("Get image fd ret is : %{public}d", ret);
412 return ret;
413 }
414
WritePixelMapToFile(const std::string & filePath,std::unique_ptr<PixelMap> pixelMap)415 int64_t WallpaperService::WritePixelMapToFile(const std::string &filePath, std::unique_ptr<PixelMap> pixelMap)
416 {
417 ImagePacker imagePacker;
418 PackOption option;
419 option.format = "image/jpeg";
420 option.quality = HUNDRED;
421 option.numberHint = 1;
422 std::set<std::string> formats;
423 uint32_t ret = imagePacker.GetSupportedFormats(formats);
424 if (ret != 0) {
425 return 0;
426 }
427 imagePacker.StartPacking(filePath, option);
428 HILOG_INFO("AddImage start");
429 imagePacker.AddImage(*pixelMap);
430 int64_t packedSize = 0;
431 HILOG_INFO("FinalizePacking start");
432 imagePacker.FinalizePacking(packedSize);
433 return packedSize;
434 }
435
CompareColor(const uint64_t & localColor,const ColorManager::Color & color)436 bool WallpaperService::CompareColor(const uint64_t &localColor, const ColorManager::Color &color)
437 {
438 return localColor == color.PackValue();
439 }
440
SaveColor(int wallpaperType)441 bool WallpaperService::SaveColor(int wallpaperType)
442 {
443 uint32_t errorCode = 0;
444 OHOS::Media::SourceOptions opts;
445 opts.formatHint = "image/jpeg";
446 std::unique_ptr<OHOS::Media::ImageSource> imageSource =
447 OHOS::Media::ImageSource::CreateImageSource((wallpaperType == WALLPAPER_SYSTEM ?
448 wallpaperSystemCropFileFullPath_: wallpaperLockScreenCropFileFullPath_), opts, errorCode);
449 if (errorCode != 0) {
450 HILOG_ERROR("CreateImageSource failed");
451 return false;
452 }
453 OHOS::Media::DecodeOptions decodeOpts;
454 std::unique_ptr<PixelMap> wallpaperPixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
455 if (errorCode != 0) {
456 HILOG_ERROR("CreatePixelMap failed");
457 return false;
458 }
459
460 auto colorPicker = Rosen::ColorPicker::CreateColorPicker(std::move(wallpaperPixelMap), errorCode);
461 if (errorCode != 0) {
462 HILOG_ERROR("CreateColorPicker failed");
463 return false;
464 }
465 auto color = ColorManager::Color();
466 uint32_t ret = colorPicker->GetMainColor(color);
467 if (ret != Rosen::SUCCESS) {
468 HILOG_ERROR("GetMainColor failed ret is : %{public}d", ret);
469 return false;
470 }
471 std::vector<uint64_t> colors;
472 if (wallpaperType == WALLPAPER_SYSTEM && !CompareColor(systemWallpaperColor_, color)) {
473 systemWallpaperColor_ = color.PackValue();
474 colors.emplace_back(systemWallpaperColor_);
475 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
476 for (const auto listener : colorChangeListenerMap_) {
477 listener.second->OnColorsChange(colors, WALLPAPER_SYSTEM);
478 }
479 } else if (wallpaperType == WALLPAPER_LOCKSCREEN && !CompareColor(lockWallpaperColor_, color)) {
480 lockWallpaperColor_ = color.PackValue();
481 colors.emplace_back(lockWallpaperColor_);
482 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
483 for (const auto listener : colorChangeListenerMap_) {
484 listener.second->OnColorsChange(colors, WALLPAPER_LOCKSCREEN);
485 }
486 }
487 return true;
488 }
489
MakeCropWallpaper(int wallpaperType)490 bool WallpaperService::MakeCropWallpaper(int wallpaperType)
491 {
492 uint32_t errorCode = 0;
493 bool ret = false;
494 OHOS::Media::SourceOptions opts;
495 opts.formatHint = "image/jpeg";
496 std::unique_ptr<OHOS::Media::ImageSource> imageSource = OHOS::Media::ImageSource::CreateImageSource(
497 (wallpaperType == WALLPAPER_SYSTEM ? wallpaperSystemFileFullPath_ : wallpaperLockScreenFileFullPath_), opts,
498 errorCode);
499 if (imageSource == nullptr || errorCode != 0) {
500 return ret;
501 }
502 OHOS::Media::DecodeOptions decodeOpts;
503 std::unique_ptr<PixelMap> wallpaperPixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
504 if (wallpaperPixelMap == nullptr || errorCode != 0) {
505 return ret;
506 }
507 SetPixelMapCropParameters(std::move(wallpaperPixelMap), decodeOpts);
508 wallpaperPixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
509 if (errorCode != 0) {
510 return false;
511 }
512 std::string tmpPath = wallpaperCropPath;
513 int64_t packedSize = WritePixelMapToFile(tmpPath, std::move(wallpaperPixelMap));
514 if (packedSize != 0) {
515 ret = FileDeal::CopyFile(tmpPath, (wallpaperType == WALLPAPER_SYSTEM ? wallpaperSystemCropFileFullPath_
516 : wallpaperLockScreenCropFileFullPath_));
517 if (remove(tmpPath.c_str()) < 0) {
518 return false;
519 }
520 }
521 HILOG_INFO("End Crop wallpaper: ret= %{public}d", ret);
522 return ret;
523 }
524
SetPixelMapCropParameters(std::unique_ptr<PixelMap> wallpaperPixelMap,DecodeOptions & decodeOpts)525 void WallpaperService::SetPixelMapCropParameters(std::unique_ptr<PixelMap> wallpaperPixelMap, DecodeOptions &decodeOpts)
526 {
527 int32_t pictureHeight = wallpaperPixelMap->GetHeight();
528 int32_t pictureWidth = wallpaperPixelMap->GetWidth();
529 int32_t pyScrWidth = 0;
530 int32_t pyScrHeight = 0;
531 GetWallpaperMinWidth(pyScrWidth);
532 GetWallpaperMinHeight(pyScrHeight);
533 bool bHeightFlag = false;
534 bool bWidthFlag = false;
535 if (pictureHeight > pyScrHeight) {
536 decodeOpts.CropRect.top = (pictureHeight - pyScrHeight) / HALF;
537 bHeightFlag = true;
538 }
539 if (pictureWidth > pyScrWidth) {
540 decodeOpts.CropRect.left = (pictureWidth - pyScrWidth) / HALF;
541 bWidthFlag = true;
542 }
543 decodeOpts.CropRect.height = bHeightFlag ? pyScrHeight : pictureHeight;
544 decodeOpts.desiredSize.height = decodeOpts.CropRect.height;
545 decodeOpts.CropRect.width = bWidthFlag ? pyScrWidth : pictureWidth;
546 decodeOpts.desiredSize.width = decodeOpts.CropRect.width;
547 }
548
SetWallpaperByMapV9(int32_t fd,int32_t wallpaperType,int32_t length)549 int32_t WallpaperService::SetWallpaperByMapV9(int32_t fd, int32_t wallpaperType, int32_t length)
550 {
551 if (!IsSystemApp()) {
552 HILOG_INFO("CallingApp is not SystemApp");
553 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
554 }
555 return SetWallpaperByMap(fd, wallpaperType, length);
556 }
557
SetWallpaperByMap(int fd,int wallpaperType,int length)558 int32_t WallpaperService::SetWallpaperByMap(int fd, int wallpaperType, int length)
559 {
560 StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaperByMap", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER_BY_MAP));
561 HILOG_INFO("SetWallpaperByMap");
562 if (!WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
563 HILOG_INFO("SetWallpaperByMap no set permission!");
564 return static_cast<int32_t>(E_NO_PERMISSION);
565 }
566 if (length <= 0 || length > FOO_MAX_LEN) {
567 return static_cast<int32_t>(E_PARAMETERS_INVALID);
568 }
569 std::string url = wallpaperTmpFullPath_;
570 char *paperBuf = new (std::nothrow) char[length]();
571 if (paperBuf == nullptr) {
572 return static_cast<int32_t>(E_NO_MEMORY);
573 }
574 mtx.lock();
575 int32_t bufsize = read(fd, paperBuf, length);
576 if (bufsize <= 0) {
577 HILOG_ERROR("read fd failed");
578 delete[] paperBuf;
579 mtx.unlock();
580 return static_cast<int32_t>(E_DEAL_FAILED);
581 }
582 int fdw = open(url.c_str(), O_WRONLY | O_CREAT, 0660);
583 if (fdw < 0) {
584 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
585 delete[] paperBuf;
586 mtx.unlock();
587 return static_cast<int32_t>(E_DEAL_FAILED);
588 }
589 int writeSize = write(fdw, paperBuf, length);
590 mtx.unlock();
591 if (writeSize <= 0) {
592 HILOG_ERROR("WritefdToFile failed");
593 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
594 delete[] paperBuf;
595 close(fdw);
596 return static_cast<int32_t>(E_DEAL_FAILED);
597 }
598 delete[] paperBuf;
599 close(fdw);
600 int32_t wallpaperErrorCode = SetWallpaperBackupData(url, wallpaperType);
601 SaveColor(wallpaperType);
602 FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaperByMap", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER_BY_MAP));
603 return wallpaperErrorCode;
604 }
605
SetWallpaperByFDV9(int32_t fd,int32_t wallpaperType,int32_t length)606 int32_t WallpaperService::SetWallpaperByFDV9(int32_t fd, int32_t wallpaperType, int32_t length)
607 {
608 if (!IsSystemApp()) {
609 HILOG_INFO("CallingApp is not SystemApp");
610 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
611 }
612 return SetWallpaperByFD(fd, wallpaperType, length);
613 }
614
SetWallpaperByFD(int fd,int wallpaperType,int length)615 int32_t WallpaperService::SetWallpaperByFD(int fd, int wallpaperType, int length)
616 {
617 StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaperByFD", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER_BY_FD));
618 HILOG_INFO("SetWallpaperByFD");
619 if (!WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
620 return static_cast<int32_t>(E_NO_PERMISSION);
621 }
622 std::string url = wallpaperTmpFullPath_;
623 if (length <= 0 || length > FOO_MAX_LEN) {
624 return static_cast<int32_t>(E_PARAMETERS_INVALID);
625 }
626 char *paperBuf = new (std::nothrow) char[length];
627 if (paperBuf == nullptr) {
628 return E_NO_MEMORY;
629 }
630 mtx.lock();
631 int readSize = read(fd, paperBuf, length);
632 if (readSize <= 0) {
633 HILOG_ERROR("read from fd fail");
634 delete[] paperBuf;
635 mtx.unlock();
636 return static_cast<int32_t>(E_DEAL_FAILED);
637 }
638 int fdw = open(url.c_str(), O_WRONLY | O_CREAT, 0660);
639 if (fdw < 0) {
640 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
641 delete[] paperBuf;
642 mtx.unlock();
643 return static_cast<int32_t>(E_DEAL_FAILED);
644 }
645 int writeSize = write(fdw, paperBuf, length);
646 mtx.unlock();
647 if (writeSize <= 0) {
648 HILOG_ERROR("Write to fdw fail, errno %{public}d", errno);
649 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
650 close(fdw);
651 delete[] paperBuf;
652 return static_cast<int32_t>(E_DEAL_FAILED);
653 }
654 close(fdw);
655 delete[] paperBuf;
656 int32_t wallpaperErrorCode = SetWallpaperBackupData(url, wallpaperType);
657 SaveColor(wallpaperType);
658 FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaperByFD", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER_BY_FD));
659 return wallpaperErrorCode;
660 }
661
SetWallpaperBackupData(std::string uriOrPixelMap,int wallpaperType)662 int32_t WallpaperService::SetWallpaperBackupData(std::string uriOrPixelMap, int wallpaperType)
663 {
664 HILOG_INFO("set wallpaper and backup data Start.");
665 if (wallpaperType != WALLPAPER_LOCKSCREEN && wallpaperType != WALLPAPER_SYSTEM) {
666 return static_cast<int32_t>(E_PARAMETERS_INVALID);
667 }
668
669 if (!OHOS::FileExists(uriOrPixelMap)) {
670 return static_cast<int32_t>(E_DEAL_FAILED);
671 }
672 WallpaperData wallpaperData(userId_,
673 (wallpaperType == WALLPAPER_SYSTEM ? wallpaperSystemFileFullPath_ : wallpaperLockScreenFileFullPath_),
674 (wallpaperType == WALLPAPER_SYSTEM ? wallpaperSystemCropFileFullPath_ : wallpaperLockScreenCropFileFullPath_));
675
676 mtx.lock();
677 bool ret = GetWallpaperSafeLocked(userId_, wallpaperType, wallpaperData);
678 if (!ret) {
679 HILOG_ERROR("GetWallpaperSafeLocked failed !");
680 mtx.unlock();
681 return static_cast<int32_t>(E_DEAL_FAILED);
682 }
683
684 wallpaperData.wallpaperId_ = MakeWallpaperIdLocked();
685 bool retFileCp = FileDeal::CopyFile(uriOrPixelMap,
686 (wallpaperType == WALLPAPER_SYSTEM ? wallpaperSystemFileFullPath_ : wallpaperLockScreenFileFullPath_));
687 bool retCropFileCp = MakeCropWallpaper(wallpaperType);
688 mtx.unlock();
689
690 if (wallpaperType == WALLPAPER_SYSTEM) {
691 wallpaperMap_.InsertOrAssign(userId_, wallpaperData);
692 WallpaperCommonEvent::SendWallpaperSystemSettingMessage();
693 ReporterUsageTimeStatisic();
694 HILOG_INFO(" SetWallpaperBackupData callbackProxy->OnCall start");
695 if (callbackProxy != nullptr) {
696 callbackProxy->OnCall(wallpaperType);
697 }
698 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
699 lockWallpaperMap_.InsertOrAssign(userId_, wallpaperData);
700 WallpaperCommonEvent::SendWallpaperLockSettingMessage();
701 ReporterUsageTimeStatisic();
702 HILOG_INFO(" SetWallpaperBackupData callbackProxy->OnCall start");
703 if (callbackProxy != nullptr) {
704 callbackProxy->OnCall(wallpaperType);
705 }
706 }
707 if (remove(uriOrPixelMap.c_str()) < 0) {
708 return static_cast<int32_t>(E_DEAL_FAILED);
709 }
710 return (retFileCp && retCropFileCp) ? static_cast<int32_t>(E_OK) : static_cast<int32_t>(E_DEAL_FAILED);
711 }
712
ReporterUsageTimeStatisic()713 void WallpaperService::ReporterUsageTimeStatisic()
714 {
715 int userId = static_cast<int>(IPCSkeleton::GetCallingUid());
716 std::string bundleName;
717 bool bRet = WPGetBundleNameByUid(userId, bundleName);
718 if (!bRet) {
719 bundleName = WALLPAPER_BUNDLE_NAME;
720 }
721 UsageTimeStat timeStat;
722 timeStat.packagesName = bundleName;
723 timeStat.startTime = time(nullptr);
724 StatisticReporter::ReportUsageTimeStatistic(userId, timeStat);
725 }
726
GetPixelMapV9(int32_t wallpaperType,IWallpaperService::FdInfo & fdInfo)727 int32_t WallpaperService::GetPixelMapV9(int32_t wallpaperType, IWallpaperService::FdInfo &fdInfo)
728 {
729 return GetPixelMap(wallpaperType, fdInfo);
730 }
731
GetPixelMap(int wallpaperType,IWallpaperService::FdInfo & fdInfo)732 int32_t WallpaperService::GetPixelMap(int wallpaperType, IWallpaperService::FdInfo &fdInfo)
733 {
734 HILOG_INFO("WallpaperService::getPixelMap start ");
735 if (!IsSystemApp()) {
736 HILOG_INFO("CallingApp is not SystemApp");
737 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
738 }
739 if (!WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
740 HILOG_INFO("GetPixelMap no get permission!");
741 return static_cast<int32_t>(E_NO_PERMISSION);
742 }
743 int32_t ret = GetImageSize(wallpaperType, fdInfo.size);
744 if (ret != static_cast<int32_t>(E_OK)) {
745 HILOG_ERROR("GetImageSize failed");
746 return ret;
747 }
748 ret = GetImageFd(wallpaperType, fdInfo.fd);
749 if (ret != static_cast<int32_t>(E_OK)) {
750 HILOG_ERROR("GetImageFd failed");
751 return ret;
752 }
753 return static_cast<int32_t>(E_OK);
754 }
755
GetWallpaperId(int32_t wallpaperType)756 int WallpaperService::GetWallpaperId(int32_t wallpaperType)
757 {
758 HILOG_INFO("WallpaperService::GetWallpaperId --> start ");
759 int iWallpaperId = 1;
760 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
761 auto wallpaperData = lockWallpaperMap_.Find(userId_);
762 if (wallpaperData.first) {
763 iWallpaperId = wallpaperData.second.wallpaperId_;
764 }
765 } else if (wallpaperType == WALLPAPER_SYSTEM) {
766 auto wallpaperData = wallpaperMap_.Find(userId_);
767 if (wallpaperData.first) {
768 iWallpaperId = wallpaperData.second.wallpaperId_;
769 }
770 }
771 HILOG_INFO("WallpaperService::GetWallpaperId --> end ID[%{public}d]", iWallpaperId);
772 return iWallpaperId;
773 }
774
GetWallpaperMinHeightV9(int32_t & minHeight)775 int32_t WallpaperService::GetWallpaperMinHeightV9(int32_t &minHeight)
776 {
777 if (!IsSystemApp()) {
778 HILOG_INFO("CallingApp is not SystemApp");
779 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
780 }
781 return GetWallpaperMinHeight(minHeight);
782 }
783
GetWallpaperMinHeight(int32_t & minHeight)784 int32_t WallpaperService::GetWallpaperMinHeight(int32_t &minHeight)
785 {
786 HILOG_INFO("WallpaperService::GetWallpaperMinHeight --> start ");
787 auto display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
788 if (display == nullptr) {
789 HILOG_ERROR("GetDefaultDisplay is nullptr");
790 return static_cast<int32_t>(E_DEAL_FAILED);
791 }
792 minHeight = display->GetHeight();
793 return static_cast<int32_t>(E_OK);
794 }
795
GetWallpaperMinWidthV9(int32_t & minWidth)796 int32_t WallpaperService::GetWallpaperMinWidthV9(int32_t &minWidth)
797 {
798 if (!IsSystemApp()) {
799 HILOG_INFO("CallingApp is not SystemApp");
800 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
801 }
802 return GetWallpaperMinWidth(minWidth);
803 }
804
GetWallpaperMinWidth(int32_t & minWidth)805 int32_t WallpaperService::GetWallpaperMinWidth(int32_t &minWidth)
806 {
807 HILOG_INFO("WallpaperService::GetWallpaperMinWidth --> start ");
808 auto display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
809 if (display == nullptr) {
810 HILOG_ERROR("GetDefaultDisplay is nullptr");
811 return static_cast<int32_t>(E_DEAL_FAILED);
812 }
813 minWidth = display->GetWidth();
814 return static_cast<int32_t>(E_OK);
815 }
816
IsChangePermitted()817 bool WallpaperService::IsChangePermitted()
818 {
819 HILOG_INFO("IsChangePermitted wallpaper Start!");
820 bool bFlag = WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
821 return bFlag;
822 }
823
IsOperationAllowed()824 bool WallpaperService::IsOperationAllowed()
825 {
826 HILOG_INFO("IsOperationAllowed wallpaper Start!");
827 bool bFlag = WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
828 return bFlag;
829 }
830
ResetWallpaperV9(int32_t wallpaperType)831 int32_t WallpaperService::ResetWallpaperV9(int32_t wallpaperType)
832 {
833 if (!IsSystemApp()) {
834 HILOG_INFO("CallingApp is not SystemApp");
835 return static_cast<int32_t>(E_NOT_SYSTEM_APP);
836 }
837 return ResetWallpaper(wallpaperType);
838 }
839
ResetWallpaper(int wallpaperType)840 int32_t WallpaperService::ResetWallpaper(int wallpaperType)
841 {
842 HILOG_INFO("reset wallpaper Start!");
843 bool permissionSet = WPCheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
844 if (!permissionSet) {
845 HILOG_INFO("reset wallpaper no set permission!");
846 return static_cast<int32_t>(E_NO_PERMISSION);
847 }
848
849 if (wallpaperType != WALLPAPER_LOCKSCREEN && wallpaperType != WALLPAPER_SYSTEM) {
850 HILOG_INFO("wallpaperType = %{public}d type not support ", wallpaperType);
851 return static_cast<int32_t>(E_PARAMETERS_INVALID);
852 }
853 int32_t wallpaperErrorCode;
854 ClearWallpaperLocked(userId_, wallpaperType);
855 wallpaperErrorCode = SetDefaultDateForWallpaper(userId_, wallpaperType);
856 HILOG_INFO(" Set default data result[%{public}d]", wallpaperErrorCode);
857
858 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
859 if (lockWallpaperMap_.Contains(userId_)) {
860 wallpaperErrorCode = static_cast<int32_t>(E_OK);
861 }
862 } else {
863 if (wallpaperMap_.Contains(userId_)) {
864 wallpaperErrorCode = static_cast<int32_t>(E_OK);
865 }
866 }
867 HILOG_INFO("reset wallpaper End!");
868 return wallpaperErrorCode;
869 }
870
CopySystemWallpaper()871 bool WallpaperService::CopySystemWallpaper()
872 {
873 if (!OHOS::FileExists(wallpaperSystemFilePath_)) {
874 if (!OHOS::ForceCreateDirectory(wallpaperSystemFilePath_)) {
875 HILOG_ERROR("CopySystemWallpaper ForceCreateDirectory error");
876 return false;
877 }
878 }
879 if (OHOS::FileExists(WALLPAPER_DEFAULT_FILEFULLPATH)) {
880 if (!FileDeal::CopyFile(WALLPAPER_DEFAULT_FILEFULLPATH, wallpaperSystemCropFileFullPath_)) {
881 HILOG_ERROR("CopyScreenLockWallpaper copy Crop file error");
882 return false;
883 }
884 if (!FileDeal::CopyFile(WALLPAPER_DEFAULT_FILEFULLPATH, wallpaperSystemFileFullPath_)) {
885 HILOG_ERROR("CopyScreenLockWallpaper copy Original file error");
886 return false;
887 }
888 WallpaperCommonEvent::SendWallpaperSystemSettingMessage();
889 if (callbackProxy != nullptr) {
890 HILOG_INFO("CopySystemWallpaper callbackProxy OnCall start");
891 callbackProxy->OnCall(WALLPAPER_SYSTEM);
892 }
893 SaveColor(WALLPAPER_SYSTEM);
894 } else {
895 HILOG_ERROR("FileExists error");
896 return false;
897 }
898 return true;
899 }
CopyScreenLockWallpaper()900 bool WallpaperService::CopyScreenLockWallpaper()
901 {
902 if (!OHOS::FileExists(wallpaperLockScreenFilePath_)) {
903 if (!OHOS::ForceCreateDirectory(wallpaperLockScreenFilePath_)) {
904 HILOG_ERROR("CopyScreenLockWallpaper ForceCreateDirectory error");
905 return false;
906 }
907 }
908 if (OHOS::FileExists(WALLPAPER_DEFAULT_LOCK_FILEFULLPATH)) {
909 if (!FileDeal::CopyFile(WALLPAPER_DEFAULT_LOCK_FILEFULLPATH, wallpaperLockScreenCropFileFullPath_)) {
910 HILOG_ERROR("CopyScreenLockWallpaper copy Crop file error");
911 return false;
912 }
913 if (!FileDeal::CopyFile(WALLPAPER_DEFAULT_LOCK_FILEFULLPATH, wallpaperLockScreenFileFullPath_)) {
914 HILOG_ERROR("CopyScreenLockWallpaper copy Original file error");
915 return false;
916 }
917 WallpaperCommonEvent::SendWallpaperLockSettingMessage();
918 if (callbackProxy != nullptr) {
919 HILOG_INFO("CopyScreenLockWallpaper callbackProxy OnCall start");
920 callbackProxy->OnCall(WALLPAPER_LOCKSCREEN);
921 }
922 SaveColor(WALLPAPER_LOCKSCREEN);
923 } else {
924 HILOG_ERROR("FileExists error");
925 return false;
926 }
927 return true;
928 }
929
SetDefaultDateForWallpaper(int32_t userId,int32_t wpType)930 int32_t WallpaperService::SetDefaultDateForWallpaper(int32_t userId, int32_t wpType)
931 {
932 std::string tmpPath = "";
933 std::string tmpCropPath = "";
934 if (wpType == WALLPAPER_LOCKSCREEN) {
935 if (!CopyScreenLockWallpaper()) {
936 HILOG_ERROR("CopyScreenLockWallpaper error");
937 return static_cast<int32_t>(E_DEAL_FAILED);
938 }
939 tmpPath = wallpaperLockScreenFileFullPath_;
940 tmpCropPath = wallpaperLockScreenCropFileFullPath_;
941 } else {
942 if (!CopySystemWallpaper()) {
943 HILOG_ERROR("CopySystemWallpaper error");
944 return static_cast<int32_t>(E_DEAL_FAILED);
945 }
946 tmpPath = wallpaperSystemFileFullPath_;
947 tmpCropPath = wallpaperSystemCropFileFullPath_;
948 }
949 WallpaperData wallpaperData(userId, tmpPath, tmpCropPath);
950 wallpaperData.wallpaperId_ = DEFAULT_WALLPAPER_ID;
951 wallpaperData.allowBackup = true;
952 if (wpType == WALLPAPER_LOCKSCREEN) {
953 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
954 } else {
955 wallpaperMap_.InsertOrAssign(userId, wallpaperData);
956 }
957 return static_cast<int32_t>(E_OK);
958 }
959
On(sptr<IWallpaperColorChangeListener> listener)960 bool WallpaperService::On(sptr<IWallpaperColorChangeListener> listener)
961 {
962 HILOG_DEBUG("WallpaperService::On in");
963 if (listener == nullptr) {
964 HILOG_ERROR("WallpaperService::On listener is null");
965 return false;
966 }
967 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
968 colorChangeListenerMap_.insert_or_assign(IPCSkeleton::GetCallingTokenID(), listener);
969 HILOG_DEBUG("WallpaperService::On out");
970 return true;
971 }
972
Off(sptr<IWallpaperColorChangeListener> listener)973 bool WallpaperService::Off(sptr<IWallpaperColorChangeListener> listener)
974 {
975 HILOG_DEBUG("WallpaperService::Off in");
976 (void)listener;
977 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
978 auto iter = colorChangeListenerMap_.find(IPCSkeleton::GetCallingTokenID());
979 if (iter != colorChangeListenerMap_.end()) {
980 iter->second = nullptr;
981 colorChangeListenerMap_.erase(iter);
982 }
983 HILOG_DEBUG("WallpaperService::Off out");
984 return true;
985 }
986
RegisterWallpaperCallback(const sptr<IWallpaperCallback> callback)987 bool WallpaperService::RegisterWallpaperCallback(const sptr<IWallpaperCallback> callback)
988 {
989 HILOG_INFO(" WallpaperService::RegisterWallpaperCallback");
990 callbackProxy = callback;
991 return true;
992 }
993
GetWallpaperSafeLocked(int userId,int wpType,WallpaperData paperdata)994 bool WallpaperService::GetWallpaperSafeLocked(int userId, int wpType, WallpaperData paperdata)
995 {
996 HILOG_INFO("function start.");
997 bool ret = true;
998 if (wpType == WALLPAPER_LOCKSCREEN) {
999 auto wallpaperData = lockWallpaperMap_.Find(userId);
1000 if (!wallpaperData.first) {
1001 HILOG_INFO(" No Lock wallpaper? Not tracking for lock-only ");
1002 LoadSettingsLocked(userId, true);
1003 wallpaperData = lockWallpaperMap_.Find(userId);
1004 if (!wallpaperData.first) {
1005 ret = false;
1006 HILOG_INFO("default data is saved into mLockWallpaperMap failed.");
1007 }
1008 }
1009 if (ret) {
1010 paperdata.wallpaperId_ = wallpaperData.second.wallpaperId_;
1011 paperdata.allowBackup = wallpaperData.second.allowBackup;
1012 }
1013 } else {
1014 auto wallpaperData = wallpaperMap_.Find(userId);
1015 if (!wallpaperData.first) {
1016 HILOG_INFO(" No system wallpaper? Not tracking for lock-only ");
1017 LoadSettingsLocked(userId, true);
1018 wallpaperData = wallpaperMap_.Find(userId);
1019 if (!wallpaperData.first) {
1020 ret = false;
1021 HILOG_INFO("default data is saved into mWallpaperMap failed.");
1022 }
1023 }
1024 if (ret) {
1025 paperdata.wallpaperId_ = wallpaperData.second.wallpaperId_;
1026 paperdata.allowBackup = wallpaperData.second.allowBackup;
1027 }
1028 }
1029 return ret;
1030 }
1031
ClearWallpaperLocked(int userId,int wpType)1032 void WallpaperService::ClearWallpaperLocked(int userId, int wpType)
1033 {
1034 HILOG_INFO("Clear wallpaper Start!");
1035 if (wpType == WALLPAPER_LOCKSCREEN) {
1036 auto wallpaperData = lockWallpaperMap_.Find(userId);
1037 if (!wallpaperData.first) {
1038 HILOG_INFO("Lock wallpaper already cleared");
1039 return;
1040 }
1041 if (!wallpaperData.second.wallpaperFile_.empty()) {
1042 lockWallpaperMap_.Erase(userId);
1043 }
1044 } else {
1045 auto wallpaperData = wallpaperMap_.Find(userId);
1046 if (!wallpaperData.first) {
1047 HILOG_INFO("system wallpaper already cleared");
1048 LoadSettingsLocked(userId, true);
1049 wallpaperData = wallpaperMap_.Find(userId);
1050 if (!wallpaperData.first) {
1051 HILOG_INFO("system wallpaper already cleared too");
1052 return;
1053 }
1054 }
1055 if (!wallpaperData.second.wallpaperFile_.empty()) {
1056 wallpaperMap_.Erase(userId);
1057 }
1058 }
1059 HILOG_INFO("Clear wallpaper End!");
1060 }
1061
WPCheckCallingPermission(const std::string & permissionName)1062 bool WallpaperService::WPCheckCallingPermission(const std::string &permissionName)
1063 {
1064 bool bflag = false;
1065 int result;
1066 Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1067 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
1068 if (tokenType == Security::AccessToken::TOKEN_NATIVE || tokenType == Security::AccessToken::TOKEN_SHELL
1069 || tokenType == Security::AccessToken::TOKEN_HAP) {
1070 result = AccessTokenProxy::VerifyAccessToken(callerToken, permissionName);
1071 } else {
1072 HILOG_INFO("Check permission tokenId ilegal");
1073 return false;
1074 }
1075 if (result == Security::AccessToken::TypePermissionState::PERMISSION_GRANTED) {
1076 bflag = true;
1077 } else {
1078 bflag = false;
1079 }
1080 HILOG_INFO("Check permission result %{public}d", result);
1081 return bflag;
1082 }
1083
WPGetBundleNameByUid(std::int32_t uid,std::string & bname)1084 bool WallpaperService::WPGetBundleNameByUid(std::int32_t uid, std::string &bname)
1085 {
1086 sptr<ISystemAbilityManager> systemMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1087 if (systemMgr == nullptr) {
1088 HILOG_ERROR("Fail to get system ability mgr");
1089 return false;
1090 }
1091
1092 sptr<IRemoteObject> remoteObject = systemMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1093 if (remoteObject == nullptr) {
1094 HILOG_ERROR("Fail to get bundle manager proxy");
1095 return false;
1096 }
1097
1098 sptr<OHOS::AppExecFwk::IBundleMgr> bundleMgrProxy = iface_cast<OHOS::AppExecFwk::IBundleMgr>(remoteObject);
1099 if (bundleMgrProxy == nullptr) {
1100 HILOG_ERROR("Bundle mgr proxy is nullptr");
1101 return false;
1102 }
1103
1104 if (!bundleMgrProxy->GetBundleNameForUid(uid, bname)) {
1105 HILOG_ERROR("Get bundle name failed");
1106 return false;
1107 }
1108 HILOG_INFO("Get bundle name is %{public}s", bname.c_str());
1109 return true;
1110 }
1111
ReporterFault(FaultType faultType,FaultCode faultCode)1112 void WallpaperService::ReporterFault(FaultType faultType, FaultCode faultCode)
1113 {
1114 FaultMsg msg;
1115 msg.faultType = faultType;
1116 msg.errorCode = faultCode;
1117 ReportStatus nRet;
1118 if (faultType == FaultType::SERVICE_FAULT) {
1119 msg.moduleName = "WallpaperService";
1120 nRet = FaultReporter::ReportServiceFault(msg);
1121 } else {
1122 nRet = FaultReporter::ReportRuntimeFault(msg);
1123 }
1124
1125 if (nRet == ReportStatus::SUCCESS) {
1126 HILOG_INFO("ReporterFault success");
1127 } else {
1128 HILOG_ERROR("ReporterFault failed");
1129 }
1130 }
1131
Dump(int fd,const std::vector<std::u16string> & args)1132 int WallpaperService::Dump(int fd, const std::vector<std::u16string> &args)
1133 {
1134 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
1135 const int maxUid = 10000;
1136 if (uid > maxUid) {
1137 Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1138 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
1139 if (tokenType != Security::AccessToken::TOKEN_NATIVE && tokenType != Security::AccessToken::TOKEN_SHELL) {
1140 return 1;
1141 }
1142 }
1143
1144 std::vector<std::string> argsStr;
1145 for (auto item : args) {
1146 argsStr.emplace_back(Str16ToStr8(item));
1147 }
1148
1149 if (DumpHelper::GetInstance().Dispatch(fd, argsStr)) {
1150 HILOG_ERROR("DumpHelper Dispatch failed");
1151 return 0;
1152 }
1153 return 1;
1154 }
1155
ConnectExtensionAbility(const AAFwk::Want & want)1156 int32_t WallpaperService::ConnectExtensionAbility(const AAFwk::Want &want)
1157 {
1158 HILOG_DEBUG("ConnectAdapter");
1159 ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
1160 if (errCode != ERR_OK) {
1161 HILOG_ERROR("connect ability server failed errCode=%{public}d", errCode);
1162 return errCode;
1163 }
1164 std::vector<int> ids;
1165 ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
1166 if (ret != ERR_OK || ids.empty()) {
1167 HILOG_ERROR("query active user failed errCode=%{public}d", ret);
1168 return AAFwk::INVALID_PARAMETERS_ERR;
1169 }
1170 const sptr<AAFwk::IAbilityConnection> connection = new WallpaperExtensionAbilityConnection();
1171 ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectExtensionAbility(want, connection, ids[0]);
1172 HILOG_INFO("ConnectExtensionAbility errCode=%{public}d", ret);
1173 return ret;
1174 }
1175
GetFilePath(int wallpaperType,std::string & filePath)1176 int32_t WallpaperService::GetFilePath(int wallpaperType, std::string &filePath)
1177 {
1178 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1179 auto wallpaperData = lockWallpaperMap_.Find(userId_);
1180 if (wallpaperData.first) {
1181 filePath = wallpaperData.second.cropFile_;
1182 return static_cast<int32_t>(E_OK);
1183 }
1184 } else if (wallpaperType == WALLPAPER_SYSTEM) {
1185 auto wallpaperData = wallpaperMap_.Find(userId_);
1186 if (wallpaperData.first) {
1187 filePath = wallpaperData.second.cropFile_;
1188 return static_cast<int32_t>(E_OK);
1189 }
1190 }
1191 return static_cast<int32_t>(E_PARAMETERS_INVALID);
1192 }
1193
IsSystemApp()1194 bool WallpaperService::IsSystemApp()
1195 {
1196 int32_t uid = IPCSkeleton::GetCallingUid();
1197 auto bundleMgr = GetBundleMgr();
1198 bool isSystemApplication = false;
1199 if (bundleMgr != nullptr) {
1200 isSystemApplication = bundleMgr->CheckIsSystemAppByUid(uid);
1201 }
1202 return isSystemApplication;
1203 }
1204
GetImageFd(int32_t wallpaperType,int32_t & fd)1205 int32_t WallpaperService::GetImageFd(int32_t wallpaperType, int32_t &fd)
1206 {
1207 HILOG_INFO("WallpaperService::GetImageFd start ");
1208 std::string filePath = "";
1209 if (GetFilePath(wallpaperType, filePath) != static_cast<int32_t>(E_OK)) {
1210 return static_cast<int32_t>(E_PARAMETERS_INVALID);
1211 }
1212 mtx.lock();
1213 fd = open(filePath.c_str(), O_RDONLY, FILE_PERMISSION);
1214 if (fd < 0) {
1215 HILOG_ERROR("Open file Path failed, errno %{public}d.", errno);
1216 ReporterFault(FaultType::LOAD_WALLPAPER_FAULT, FaultCode::RF_FD_INPUT_FAILED);
1217 mtx.unlock();
1218 return static_cast<int32_t>(E_DEAL_FAILED);
1219 }
1220 mtx.unlock();
1221 return static_cast<int32_t>(E_OK);
1222 }
1223
GetImageSize(int32_t wallpaperType,int32_t & size)1224 int32_t WallpaperService::GetImageSize(int32_t wallpaperType, int32_t &size)
1225 {
1226 HILOG_INFO("WallpaperService::GetImageSize start ");
1227 std::string filePath = "";
1228 if (GetFilePath(wallpaperType, filePath) != static_cast<int32_t>(E_OK)) {
1229 return static_cast<int32_t>(E_PARAMETERS_INVALID);
1230 }
1231
1232 if (!OHOS::FileExists(filePath)) {
1233 HILOG_ERROR("file is not exist!");
1234 return static_cast<int32_t>(E_NOT_FOUND);
1235 }
1236 mtx.lock();
1237 FILE *fd = fopen(filePath.c_str(), "rb");
1238 if (fd == nullptr) {
1239 HILOG_ERROR("fopen file Path failed, errno %{public}d.", errno);
1240 mtx.unlock();
1241 return static_cast<int32_t>(E_FILE_ERROR);
1242 }
1243 int32_t fend = fseek(fd, 0, SEEK_END);
1244 size = ftell(fd);
1245 int32_t fset = fseek(fd, 0, SEEK_SET);
1246 if (size <= 0 || fend != 0 || fset != 0) {
1247 HILOG_ERROR("ftell file failed or fseek file failed, errno %{public}d", errno);
1248 fclose(fd);
1249 mtx.unlock();
1250 return static_cast<int32_t>(E_FILE_ERROR);
1251 }
1252 fclose(fd);
1253 mtx.unlock();
1254 return static_cast<int32_t>(E_OK);
1255 }
1256
GetBundleMgr()1257 OHOS::sptr<OHOS::AppExecFwk::IBundleMgr> WallpaperService::GetBundleMgr()
1258 {
1259 auto systemAbilityManager = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1260 if (systemAbilityManager == nullptr) {
1261 return nullptr;
1262 }
1263 auto bundleMgrSa = systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1264 if (bundleMgrSa == nullptr) {
1265 return nullptr;
1266 }
1267 auto bundleMgr = OHOS::iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
1268 if (bundleMgr == nullptr) {
1269 HILOG_INFO("GetBundleMgr is null");
1270 }
1271 return bundleMgr;
1272 }
1273 } // namespace WallpaperMgrService
1274 } // namespace OHOS