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 <fcntl.h>
18 #include <sys/prctl.h>
19 #include <sys/sendfile.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <cerrno>
25 #include <cstdio>
26 #include <cstdlib>
27 #include <cstring>
28 #include <iostream>
29 #include <thread>
30 #include <sstream>
31
32 #include "bundle_mgr_interface.h"
33 #include "bundle_mgr_proxy.h"
34 #include "color_picker.h"
35 #include "command.h"
36 #include "directory_ex.h"
37 #include "dump_helper.h"
38 #include "effect_errors.h"
39 #include "export/color.h"
40 #include "file_deal.h"
41 #include "file_ex.h"
42 #include "hilog_wrapper.h"
43 #include "hitrace_meter.h"
44 #include "image_packer.h"
45 #include "image_source.h"
46 #include "image_type.h"
47 #include "image_utils.h"
48 #include "iservice_registry.h"
49 #include "memory_guard.h"
50 #include "nlohmann/json.hpp"
51 #include "parameter.h"
52 #include "pixel_map.h"
53 #include "scene_board_judgement.h"
54 #include "system_ability_definition.h"
55 #include "tokenid_kit.h"
56 #include "uri.h"
57 #include "wallpaper_common.h"
58 #include "wallpaper_common_event_manager.h"
59 #include "wallpaper_manager_common_info.h"
60 #include "wallpaper_service_cb_proxy.h"
61 #include "want.h"
62 #include "window.h"
63
64 #ifndef THEME_SERVICE
65 #include "ability_manager_client.h"
66 #include "wallpaper_extension_ability_death_recipient.h"
67 #endif
68
69 namespace OHOS {
70 namespace WallpaperMgrService {
71 REGISTER_SYSTEM_ABILITY_BY_ID(WallpaperService, WALLPAPER_MANAGER_SERVICE_ID, true);
72
73 using namespace OHOS::Media;
74 using namespace OHOS::MiscServices;
75 using namespace OHOS::Security::AccessToken;
76 using namespace OHOS::AccountSA;
77
78 constexpr const char *WALLPAPER_SYSTEM_ORIG = "wallpaper_system_orig";
79 constexpr const char *WALLPAPER_LOCK_ORIG = "wallpaper_lock_orig";
80 constexpr const char *LIVE_WALLPAPER_SYSTEM_ORIG = "live_wallpaper_system_orig";
81 constexpr const char *LIVE_WALLPAPER_LOCK_ORIG = "live_wallpaper_lock_orig";
82 constexpr const char *CUSTOM_WALLPAPER_LOCK = "custom_lock.zip";
83 constexpr const char *CUSTOM_WALLPAPER_SYSTEM = "custom_system.zip";
84 constexpr const char *OHOS_WALLPAPER_BUNDLE_NAME = "com.ohos.launcher";
85 constexpr const char *SHOW_SYSTEM_SCREEN = "SHOW_SYSTEMSCREEN";
86 constexpr const char *SHOW_LOCK_SCREEN = "SHOW_LOCKSCREEN";
87 constexpr const char *SYSTEM_RES_TYPE = "SystemResType";
88 constexpr const char *LOCKSCREEN_RES_TYPE = "LockScreenResType";
89 constexpr const char *WALLPAPER_CHANGE = "wallpaperChange";
90 constexpr const char *COLOR_CHANGE = "colorChange";
91 constexpr const char *BUNDLE_NAME_KEY = "persist.wallpaper_mgr.bundleName";
92 constexpr const char *SCENEBOARD_BUNDLE_NAME = "com.ohos.sceneboard";
93
94 constexpr const char *WALLPAPER_USERID_PATH = "/data/service/el1/public/wallpaper/";
95 constexpr const char *WALLPAPER_SYSTEM_DIRNAME = "system";
96 constexpr const char *WALLPAPER_TMP_DIRNAME = "fwsettmp";
97 constexpr const char *WALLPAPER_LOCKSCREEN_DIRNAME = "lockscreen";
98 constexpr const char *WALLPAPER_DEFAULT_FILEFULLPATH = "/system/etc/wallpaperdefault.jpeg";
99 constexpr const char *WALLPAPER_DEFAULT_LOCK_FILEFULLPATH = "/system/etc/wallpaperlockdefault.jpeg";
100 constexpr const char *WALLPAPER_PREFABRICATE_FILEFULLPATH = "/sys_prod/media/themes/wallpaperdefault.jpeg";
101 constexpr const char *WALLPAPER_PREFABRICATE_LOCK_FILEFULLPATH = "/sys_prod/media/themes/wallpaperlockdefault.jpeg";
102 constexpr const char *WALLPAPER_CROP_PICTURE = "crop_file";
103
104 constexpr int64_t INIT_INTERVAL = 10000L;
105 constexpr int64_t DELAY_TIME = 1000L;
106 constexpr int64_t QUERY_USER_ID_INTERVAL = 300L;
107 constexpr int32_t FOO_MAX_LEN = 52428800;
108 constexpr int32_t MAX_RETRY_TIMES = 20;
109 constexpr int32_t QUERY_USER_MAX_RETRY_TIMES = 100;
110 constexpr int32_t DEFAULT_WALLPAPER_ID = -1;
111 constexpr int32_t DEFAULT_USER_ID = 0;
112 constexpr int32_t MAX_VIDEO_SIZE = 104857600;
113 constexpr int32_t OPTION_QUALITY = 100;
114 const int CONFIG_LEN = 30;
115
116 #ifndef THEME_SERVICE
117 constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100;
118 constexpr int32_t DEFAULT_VALUE = -1;
119 constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 50;
120 #endif
121
122 std::mutex WallpaperService::instanceLock_;
123
124 sptr<WallpaperService> WallpaperService::instance_;
125
126 std::shared_ptr<AppExecFwk::EventHandler> WallpaperService::serviceHandler_;
127
WallpaperService(int32_t systemAbilityId,bool runOnCreate)128 WallpaperService::WallpaperService(int32_t systemAbilityId, bool runOnCreate)
129 : SystemAbility(systemAbilityId, runOnCreate), WallpaperServiceStub(true),
130 state_(ServiceRunningState::STATE_NOT_START)
131 {
132 }
133
WallpaperService()134 WallpaperService::WallpaperService() : WallpaperServiceStub(true), state_(ServiceRunningState::STATE_NOT_START)
135 {
136 }
137
~WallpaperService()138 WallpaperService::~WallpaperService()
139 {
140 }
141
Init()142 int32_t WallpaperService::Init()
143 {
144 InitQueryUserId(QUERY_USER_MAX_RETRY_TIMES);
145 bool ret = Publish(this);
146 if (!ret) {
147 HILOG_ERROR("Publish failed.");
148 ReporterFault(FaultType::SERVICE_FAULT, FaultCode::SF_SERVICE_UNAVAILABLE);
149 return -1;
150 }
151 HILOG_INFO("Publish success.");
152 state_ = ServiceRunningState::STATE_RUNNING;
153 #ifndef THEME_SERVICE
154 StartExtensionAbility(CONNECT_EXTENSION_MAX_RETRY_TIMES);
155 #endif
156 return E_OK;
157 }
158
OnStart()159 void WallpaperService::OnStart()
160 {
161 HILOG_INFO("Enter OnStart.");
162 MemoryGuard cacheGuard;
163 if (state_ == ServiceRunningState::STATE_RUNNING) {
164 HILOG_ERROR("WallpaperService is already running.");
165 return;
166 }
167 InitData();
168 InitServiceHandler();
169 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
170 auto cmd = std::make_shared<Command>(std::vector<std::string>({ "-all" }), "Show all",
171 [this](const std::vector<std::string> &input, std::string &output) -> bool {
172 output.append(
173 "WallpaperExtensionAbility\t: ExtensionInfo{" + std::string(OHOS_WALLPAPER_BUNDLE_NAME) + "}\n");
174 return true;
175 });
176 DumpHelper::GetInstance().RegisterCommand(cmd);
177 if (Init() != E_OK) {
178 auto callback = [=]() { Init(); };
179 serviceHandler_->PostTask(callback, INIT_INTERVAL);
180 HILOG_ERROR("Init failed. Try again 10s later");
181 }
182 return;
183 }
184
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)185 void WallpaperService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
186 {
187 HILOG_INFO("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
188 if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
189 int32_t times = 0;
190 RegisterSubscriber(times);
191 }
192 }
193
RegisterSubscriber(int32_t times)194 void WallpaperService::RegisterSubscriber(int32_t times)
195 {
196 MemoryGuard cacheGuard;
197 times++;
198 subscriber_ = std::make_shared<WallpaperCommonEventSubscriber>(*this);
199 bool subRes = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
200 if (!subRes && times <= MAX_RETRY_TIMES) {
201 HILOG_INFO("RegisterSubscriber failed");
202 auto callback = [this, times]() { RegisterSubscriber(times); };
203 serviceHandler_->PostTask(callback, DELAY_TIME);
204 }
205 }
206
InitServiceHandler()207 void WallpaperService::InitServiceHandler()
208 {
209 HILOG_INFO("InitServiceHandler started.");
210 if (serviceHandler_ != nullptr) {
211 HILOG_ERROR("InitServiceHandler already init.");
212 return;
213 }
214 std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("WallpaperService");
215 serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
216 }
217
OnStop()218 void WallpaperService::OnStop()
219 {
220 HILOG_INFO("OnStop started.");
221 if (state_ != ServiceRunningState::STATE_RUNNING) {
222 return;
223 }
224 serviceHandler_ = nullptr;
225 #ifndef THEME_SERVICE
226 connection_ = nullptr;
227 #endif
228 recipient_ = nullptr;
229 extensionRemoteObject_ = nullptr;
230 if (subscriber_ != nullptr) {
231 bool unSubscribeResult = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_);
232 subscriber_ = nullptr;
233 HILOG_INFO("UnregisterSubscriber end, unSubscribeResult = %{public}d", unSubscribeResult);
234 }
235 state_ = ServiceRunningState::STATE_NOT_START;
236 }
237
InitData()238 void WallpaperService::InitData()
239 {
240 HILOG_INFO("WallpaperService::initData --> start ");
241 wallpaperId_ = DEFAULT_WALLPAPER_ID;
242 int32_t userId = DEFAULT_USER_ID;
243 systemWallpaperMap_.Clear();
244 lockWallpaperMap_.Clear();
245 wallpaperTmpFullPath_ = std::string(WALLPAPER_USERID_PATH) + std::string(WALLPAPER_TMP_DIRNAME);
246 wallpaperCropPath_ = std::string(WALLPAPER_USERID_PATH) + std::string(WALLPAPER_CROP_PICTURE);
247 systemWallpaperColor_ = 0;
248 lockWallpaperColor_ = 0;
249 currentUserId_ = userId;
250 wallpaperEventMap_.clear();
251 appBundleName_ = SCENEBOARD_BUNDLE_NAME;
252 InitBundleNameParameter();
253 InitUserDir(userId);
254 LoadSettingsLocked(userId);
255 InitResources(userId, WALLPAPER_SYSTEM);
256 InitResources(userId, WALLPAPER_LOCKSCREEN);
257 LoadWallpaperState();
258 }
259
InitBundleNameParameter()260 void WallpaperService::InitBundleNameParameter()
261 {
262 char value[CONFIG_LEN] = "";
263 if (GetParameter(BUNDLE_NAME_KEY, "", value, CONFIG_LEN) < 0 || strlen(value) == 0) {
264 HILOG_ERROR("No found bundle name from system parameter.");
265 return;
266 }
267 appBundleName_ = value;
268 HILOG_INFO("get appBundleName_ :%{public}s", appBundleName_.c_str());
269 }
270
271 #ifndef THEME_SERVICE
AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> & remoteObject)272 void WallpaperService::AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> &remoteObject)
273 {
274 if (remoteObject != nullptr) {
275 std::lock_guard<std::mutex> lock(remoteObjectMutex_);
276 IPCObjectProxy *proxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
277 if (recipient_ == nullptr) {
278 recipient_ = sptr<IRemoteObject::DeathRecipient>(new WallpaperExtensionAbilityDeathRecipient(*this));
279 }
280 if (proxy != nullptr && !proxy->IsObjectDead()) {
281 HILOG_INFO("get remoteObject succeed");
282 proxy->AddDeathRecipient(recipient_);
283 extensionRemoteObject_ = remoteObject;
284 }
285 }
286 }
287 #endif
288
RemoveExtensionDeathRecipient()289 void WallpaperService::RemoveExtensionDeathRecipient()
290 {
291 if (extensionRemoteObject_ != nullptr && recipient_ != nullptr) {
292 HILOG_INFO("Remove Extension DeathRecipient");
293 std::lock_guard<std::mutex> lock(remoteObjectMutex_);
294 extensionRemoteObject_->RemoveDeathRecipient(recipient_);
295 recipient_ = nullptr;
296 extensionRemoteObject_ = nullptr;
297 }
298 }
299
InitQueryUserId(int32_t times)300 void WallpaperService::InitQueryUserId(int32_t times)
301 {
302 times--;
303 bool ret = InitUsersOnBoot();
304 if (!ret && times > 0) {
305 HILOG_INFO("InitQueryUserId failed");
306 auto callback = [this, times]() { InitQueryUserId(times); };
307 serviceHandler_->PostTask(callback, QUERY_USER_ID_INTERVAL);
308 }
309 }
310
311 #ifndef THEME_SERVICE
StartExtensionAbility(int32_t times)312 void WallpaperService::StartExtensionAbility(int32_t times)
313 {
314 times--;
315 bool ret = ConnectExtensionAbility();
316 if (!ret && times > 0 && serviceHandler_ != nullptr) {
317 HILOG_ERROR("StartExtensionAbilty failed, remainder of the times: %{public}d", times);
318 auto callback = [this, times]() { StartExtensionAbility(times); };
319 serviceHandler_->PostTask(callback, CONNECT_EXTENSION_INTERVAL);
320 }
321 }
322 #endif
323
InitUsersOnBoot()324 bool WallpaperService::InitUsersOnBoot()
325 {
326 std::vector<int32_t> userIds;
327 if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(userIds) != ERR_OK || userIds.empty()) {
328 HILOG_DEBUG("WallpaperService: failed to get current userIds");
329 return false;
330 }
331 HILOG_INFO("WallpaperService::get current userIds success, Current userId: %{public}d", userIds[0]);
332 for (auto userId : userIds) {
333 InitUserDir(userId);
334 LoadSettingsLocked(userId);
335 InitResources(userId, WALLPAPER_SYSTEM);
336 InitResources(userId, WALLPAPER_LOCKSCREEN);
337 }
338 return true;
339 }
340
OnInitUser(int32_t userId)341 void WallpaperService::OnInitUser(int32_t userId)
342 {
343 if (userId < 0) {
344 HILOG_ERROR("userId error, userId = %{public}d", userId);
345 return;
346 }
347 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
348 if (FileDeal::IsFileExist(userDir)) {
349 std::lock_guard<std::mutex> lock(mtx_);
350 if (!OHOS::ForceRemoveDirectory(userDir)) {
351 HILOG_ERROR("Force remove user directory path failed, errno %{public}d, userId:%{public}d", errno, userId);
352 return;
353 }
354 }
355 if (!InitUserDir(userId)) {
356 return;
357 }
358 LoadSettingsLocked(userId);
359 InitResources(userId, WALLPAPER_SYSTEM);
360 InitResources(userId, WALLPAPER_LOCKSCREEN);
361 HILOG_INFO("OnInitUser success, userId = %{public}d", userId);
362 }
363
InitResources(int32_t userId,WallpaperType wallpaperType)364 void WallpaperService::InitResources(int32_t userId, WallpaperType wallpaperType)
365 {
366 std::string pathName;
367 if (!GetFileNameFromMap(userId, wallpaperType, pathName)) {
368 HILOG_ERROR("Get user file name from map failed, userId = %{public}d", userId);
369 return;
370 }
371 if (!FileDeal::IsFileExist(pathName)) {
372 WallpaperData wallpaperData;
373 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
374 HILOG_ERROR("Get wallpaper data failed, userId = %{public}d", userId);
375 return;
376 }
377 if (!RestoreUserResources(wallpaperData, wallpaperType)) {
378 HILOG_ERROR("RestoreUserResources error");
379 return;
380 }
381 }
382 }
383
InitUserDir(int32_t userId)384 bool WallpaperService::InitUserDir(int32_t userId)
385 {
386 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
387 if (!FileDeal::Mkdir(userDir)) {
388 HILOG_ERROR("Failed to create destination path, userId:%{public}d ", userId);
389 return false;
390 }
391 std::string wallpaperSystemFilePath = userDir + "/" + WALLPAPER_SYSTEM_DIRNAME;
392 if (!FileDeal::Mkdir(wallpaperSystemFilePath)) {
393 HILOG_ERROR("Failed to create destination wallpaper system path, userId:%{public}d, type:%{public}s", userId,
394 WALLPAPER_SYSTEM_DIRNAME);
395 return false;
396 }
397 std::string wallpaperLockScreenFilePath = userDir + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
398 if (!FileDeal::Mkdir(wallpaperLockScreenFilePath)) {
399 HILOG_ERROR("Failed to create destination wallpaper lockscreen path, userId:%{public}d, type:%{public}s",
400 userId, WALLPAPER_LOCKSCREEN_DIRNAME);
401 return false;
402 }
403 return true;
404 }
405
RestoreUserResources(const WallpaperData & wallpaperData,WallpaperType wallpaperType)406 bool WallpaperService::RestoreUserResources(const WallpaperData &wallpaperData, WallpaperType wallpaperType)
407 {
408 std::string wallpaperDefaultPath = wallpaperType == WallpaperType::WALLPAPER_SYSTEM
409 ? WALLPAPER_DEFAULT_FILEFULLPATH
410 : WALLPAPER_DEFAULT_LOCK_FILEFULLPATH;
411 if (wallpaperType == WallpaperType::WALLPAPER_SYSTEM) {
412 if (FileDeal::IsFileExist(WALLPAPER_PREFABRICATE_FILEFULLPATH)) {
413 wallpaperDefaultPath = WALLPAPER_PREFABRICATE_FILEFULLPATH;
414 }
415 } else {
416 if (FileDeal::IsFileExist(WALLPAPER_PREFABRICATE_LOCK_FILEFULLPATH)) {
417 wallpaperDefaultPath = WALLPAPER_PREFABRICATE_LOCK_FILEFULLPATH;
418 }
419 }
420 if (!FileDeal::IsFileExist(wallpaperDefaultPath)
421 || !FileDeal::IsFileExist(GetWallpaperDir(wallpaperData.userId, wallpaperType))) {
422 HILOG_ERROR("Copy file path is not exist");
423 return false;
424 }
425 std::lock_guard<std::mutex> lock(mtx_);
426 if (!FileDeal::CopyFile(wallpaperDefaultPath, wallpaperData.wallpaperFile)) {
427 HILOG_ERROR("CopyFile WALLPAPER_DEFAULT_FILEFULLPATH failed");
428 return false;
429 }
430 HILOG_INFO("Restore user resources end ");
431 return true;
432 }
433
OnRemovedUser(int32_t userId)434 void WallpaperService::OnRemovedUser(int32_t userId)
435 {
436 if (userId < 0) {
437 HILOG_ERROR("userId error, userId = %{public}d", userId);
438 return;
439 }
440 ClearWallpaperLocked(userId, WALLPAPER_SYSTEM);
441 ClearWallpaperLocked(userId, WALLPAPER_LOCKSCREEN);
442 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
443 std::lock_guard<std::mutex> lock(mtx_);
444 if (!OHOS::ForceRemoveDirectory(userDir)) {
445 HILOG_ERROR("Force remove user directory path failed, errno %{public}d.", errno);
446 }
447 HILOG_INFO("OnRemovedUser end, userId = %{public}d", userId);
448 }
449
OnSwitchedUser(int32_t userId)450 void WallpaperService::OnSwitchedUser(int32_t userId)
451 {
452 if (userId < 0) {
453 HILOG_ERROR("userId error, userId = %{public}d", userId);
454 return;
455 }
456 if (userId == currentUserId_) {
457 HILOG_ERROR("userId not switch, userId = %{public}d", userId);
458 return;
459 }
460 currentUserId_ = userId;
461 RemoveExtensionDeathRecipient();
462 #ifndef THEME_SERVICE
463 ConnectExtensionAbility();
464 #endif
465 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
466 std::string systemFile =
467 WALLPAPER_USERID_PATH + std::to_string(userId) + "/" + WALLPAPER_SYSTEM_DIRNAME + "/" + WALLPAPER_SYSTEM_ORIG;
468 std::string lockFile = WALLPAPER_USERID_PATH + std::to_string(userId) + "/" + WALLPAPER_LOCKSCREEN_DIRNAME + "/"
469 + WALLPAPER_LOCK_ORIG;
470 LoadSettingsLocked(userId);
471 if (!FileDeal::IsFileExist(userDir)) {
472 HILOG_INFO("User file is not exist, userId = %{public}d", userId);
473 InitUserDir(userId);
474 InitResources(userId, WALLPAPER_SYSTEM);
475 InitResources(userId, WALLPAPER_LOCKSCREEN);
476 } else {
477 if (!FileDeal::IsFileExist(systemFile)) {
478 HILOG_INFO("systemFile is not exist, userId = %{public}d", userId);
479 InitResources(userId, WALLPAPER_SYSTEM);
480 }
481 if (!FileDeal::IsFileExist(lockFile)) {
482 HILOG_INFO("lockFile is not exist, userId = %{public}d", userId);
483 InitResources(userId, WALLPAPER_LOCKSCREEN);
484 }
485 }
486 LoadWallpaperState();
487 SendWallpaperChangeEvent(userId, WALLPAPER_SYSTEM);
488 SendWallpaperChangeEvent(userId, WALLPAPER_LOCKSCREEN);
489 SaveColor(userId, WALLPAPER_SYSTEM);
490 SaveColor(userId, WALLPAPER_LOCKSCREEN);
491 HILOG_INFO("OnSwitchedUser end, newUserId = %{public}d", userId);
492 }
493
OnBootPhase()494 void WallpaperService::OnBootPhase()
495 {
496 HILOG_INFO("WallpaperService OnBootPhase");
497 }
498
GetWallpaperDir(int32_t userId,WallpaperType wallpaperType)499 std::string WallpaperService::GetWallpaperDir(int32_t userId, WallpaperType wallpaperType)
500 {
501 std::string userIdPath = WALLPAPER_USERID_PATH + std::to_string(userId);
502 std::string wallpaperFilePath;
503 if (wallpaperType == WALLPAPER_SYSTEM) {
504 wallpaperFilePath = userIdPath + "/" + WALLPAPER_SYSTEM_DIRNAME;
505 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
506 wallpaperFilePath = userIdPath + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
507 }
508 return wallpaperFilePath;
509 }
510
GetFileNameFromMap(int32_t userId,WallpaperType wallpaperType,std::string & filePathName)511 bool WallpaperService::GetFileNameFromMap(int32_t userId, WallpaperType wallpaperType, std::string &filePathName)
512 {
513 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
514 : lockWallpaperMap_.Find(userId);
515 if (!iterator.first) {
516 HILOG_ERROR("system wallpaper already cleared");
517 return false;
518 }
519 HILOG_DEBUG("GetFileNameFromMap resourceType : %{public}d", static_cast<int32_t>(iterator.second.resourceType));
520 switch (iterator.second.resourceType) {
521 case PICTURE:
522 filePathName = iterator.second.wallpaperFile;
523 break;
524 case VIDEO:
525 filePathName = iterator.second.liveWallpaperFile;
526 break;
527 case DEFAULT:
528 filePathName = iterator.second.wallpaperFile;
529 break;
530 case PACKAGE:
531 filePathName = iterator.second.customPackageUri;
532 break;
533 default:
534 filePathName = "";
535 break;
536 }
537 return filePathName != "";
538 }
539
GetPictureFileName(int32_t userId,WallpaperType wallpaperType,std::string & filePathName)540 bool WallpaperService::GetPictureFileName(int32_t userId, WallpaperType wallpaperType, std::string &filePathName)
541 {
542 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
543 : lockWallpaperMap_.Find(userId);
544 if (!iterator.first) {
545 HILOG_INFO("WallpaperType:%{public}d ,WallpaperMap not found userId: %{public}d", wallpaperType, userId);
546 OnInitUser(userId);
547 iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
548 : lockWallpaperMap_.Find(userId);
549 }
550 filePathName = iterator.second.wallpaperFile;
551 HILOG_INFO("GetPictureFileName filePathName : %{public}s", filePathName.c_str());
552 return filePathName != "";
553 }
554
MakeWallpaperIdLocked()555 int32_t WallpaperService::MakeWallpaperIdLocked()
556 {
557 HILOG_INFO("MakeWallpaperIdLocked start");
558 if (wallpaperId_ == INT32_MAX) {
559 wallpaperId_ = DEFAULT_WALLPAPER_ID;
560 }
561 return ++wallpaperId_;
562 }
563
LoadSettingsLocked(int32_t userId)564 void WallpaperService::LoadSettingsLocked(int32_t userId)
565 {
566 HILOG_INFO("load Setting locked start.");
567 if (!systemWallpaperMap_.Contains(userId)) {
568 HILOG_INFO("systemWallpaperMap_ does not contains userId");
569 std::string wallpaperSystemFilePath = GetWallpaperDir(userId, WALLPAPER_SYSTEM);
570 WallpaperData wallpaperSystem(userId, wallpaperSystemFilePath + "/" + WALLPAPER_SYSTEM_ORIG);
571 wallpaperSystem.liveWallpaperFile = wallpaperSystemFilePath + "/" + LIVE_WALLPAPER_SYSTEM_ORIG;
572 wallpaperSystem.customPackageUri = wallpaperSystemFilePath + "/" + CUSTOM_WALLPAPER_SYSTEM;
573 wallpaperSystem.allowBackup = true;
574 wallpaperSystem.resourceType = PICTURE;
575 wallpaperSystem.wallpaperId = DEFAULT_WALLPAPER_ID;
576 systemWallpaperMap_.InsertOrAssign(userId, wallpaperSystem);
577 }
578 if (!lockWallpaperMap_.Contains(userId)) {
579 HILOG_INFO("lockWallpaperMap_ does not Contains userId");
580 std::string wallpaperLockScreenFilePath = GetWallpaperDir(userId, WALLPAPER_LOCKSCREEN);
581 WallpaperData wallpaperLock(userId, wallpaperLockScreenFilePath + "/" + WALLPAPER_LOCK_ORIG);
582 wallpaperLock.liveWallpaperFile = wallpaperLockScreenFilePath + "/" + LIVE_WALLPAPER_LOCK_ORIG;
583 wallpaperLock.customPackageUri = wallpaperLockScreenFilePath + "/" + CUSTOM_WALLPAPER_LOCK;
584 wallpaperLock.allowBackup = true;
585 wallpaperLock.resourceType = PICTURE;
586 wallpaperLock.wallpaperId = DEFAULT_WALLPAPER_ID;
587 lockWallpaperMap_.InsertOrAssign(userId, wallpaperLock);
588 }
589 }
590
GetColors(int32_t wallpaperType,std::vector<uint64_t> & colors)591 ErrorCode WallpaperService::GetColors(int32_t wallpaperType, std::vector<uint64_t> &colors)
592 {
593 if (wallpaperType == WALLPAPER_SYSTEM) {
594 colors.emplace_back(systemWallpaperColor_);
595 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
596 colors.emplace_back(lockWallpaperColor_);
597 }
598 HILOG_INFO("GetColors Service End!");
599 return E_OK;
600 }
601
GetColorsV9(int32_t wallpaperType,std::vector<uint64_t> & colors)602 ErrorCode WallpaperService::GetColorsV9(int32_t wallpaperType, std::vector<uint64_t> &colors)
603 {
604 if (!IsSystemApp()) {
605 HILOG_ERROR("CallingApp is not SystemApp");
606 return E_NOT_SYSTEM_APP;
607 }
608 return GetColors(wallpaperType, colors);
609 }
610
GetFile(int32_t wallpaperType,int32_t & wallpaperFd)611 ErrorCode WallpaperService::GetFile(int32_t wallpaperType, int32_t &wallpaperFd)
612 {
613 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
614 HILOG_ERROR("GetPixelMap no get permission!");
615 return E_NO_PERMISSION;
616 }
617 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
618 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
619 return E_PARAMETERS_INVALID;
620 }
621 auto type = static_cast<WallpaperType>(wallpaperType);
622 int32_t userId = QueryActiveUserId();
623 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
624 ErrorCode ret = GetImageFd(userId, type, wallpaperFd);
625 HILOG_INFO("GetImageFd fd:%{public}d, ret:%{public}d", wallpaperFd, ret);
626 return ret;
627 }
628
CompareColor(const uint64_t & localColor,const ColorManager::Color & color)629 bool WallpaperService::CompareColor(const uint64_t &localColor, const ColorManager::Color &color)
630 {
631 return localColor == color.PackValue();
632 }
633
SaveColor(int32_t userId,WallpaperType wallpaperType)634 bool WallpaperService::SaveColor(int32_t userId, WallpaperType wallpaperType)
635 {
636 uint32_t errorCode = 0;
637 OHOS::Media::SourceOptions opts;
638 opts.formatHint = "image/jpeg";
639 std::string pathName;
640 if (!GetPictureFileName(userId, wallpaperType, pathName)) {
641 return false;
642 }
643 std::unique_ptr<OHOS::Media::ImageSource> imageSource =
644 OHOS::Media::ImageSource::CreateImageSource(pathName, opts, errorCode);
645 if (errorCode != 0) {
646 HILOG_ERROR("CreateImageSource failed");
647 return false;
648 }
649 OHOS::Media::DecodeOptions decodeOpts;
650 std::unique_ptr<PixelMap> wallpaperPixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
651 if (errorCode != 0) {
652 HILOG_ERROR("CreatePixelMap failed");
653 return false;
654 }
655
656 pictureHeight_ = wallpaperPixelMap->GetHeight();
657 pictureWidth_ = wallpaperPixelMap->GetWidth();
658
659 auto colorPicker = Rosen::ColorPicker::CreateColorPicker(std::move(wallpaperPixelMap), errorCode);
660 if (errorCode != 0) {
661 HILOG_ERROR("CreateColorPicker failed");
662 return false;
663 }
664 auto color = ColorManager::Color();
665 uint32_t ret = colorPicker->GetMainColor(color);
666 if (ret != Rosen::SUCCESS) {
667 HILOG_ERROR("GetMainColor failed ret is : %{public}d", ret);
668 return false;
669 }
670 OnColorsChange(wallpaperType, color);
671 return true;
672 }
673
SetWallpaper(int32_t fd,int32_t wallpaperType,int32_t length)674 ErrorCode WallpaperService::SetWallpaper(int32_t fd, int32_t wallpaperType, int32_t length)
675 {
676 StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
677 ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, PICTURE);
678 FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
679 return wallpaperErrorCode;
680 }
681
SetWallpaperByPixelMap(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,int32_t wallpaperType)682 ErrorCode WallpaperService::SetWallpaperByPixelMap(
683 std::shared_ptr<OHOS::Media::PixelMap> pixelMap, int32_t wallpaperType)
684 {
685 StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
686 ErrorCode wallpaperErrorCode = SetWallpaperByPixelMap(pixelMap, wallpaperType, PICTURE);
687 FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
688 return wallpaperErrorCode;
689 }
690
SetWallpaperV9(int32_t fd,int32_t wallpaperType,int32_t length)691 ErrorCode WallpaperService::SetWallpaperV9(int32_t fd, int32_t wallpaperType, int32_t length)
692 {
693 if (!IsSystemApp()) {
694 HILOG_ERROR("CallingApp is not SystemApp");
695 return E_NOT_SYSTEM_APP;
696 }
697 return SetWallpaper(fd, wallpaperType, length);
698 }
699
SetWallpaperV9ByPixelMap(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,int32_t wallpaperType)700 ErrorCode WallpaperService::SetWallpaperV9ByPixelMap(
701 std::shared_ptr<OHOS::Media::PixelMap> pixelMap, int32_t wallpaperType)
702 {
703 if (!IsSystemApp()) {
704 HILOG_INFO("CallingApp is not SystemApp");
705 return E_NOT_SYSTEM_APP;
706 }
707 return SetWallpaperByPixelMap(pixelMap, wallpaperType);
708 }
709
SetWallpaperBackupData(int32_t userId,WallpaperResourceType resourceType,const std::string & uriOrPixelMap,WallpaperType wallpaperType)710 ErrorCode WallpaperService::SetWallpaperBackupData(
711 int32_t userId, WallpaperResourceType resourceType, const std::string &uriOrPixelMap, WallpaperType wallpaperType)
712 {
713 HILOG_INFO("set wallpaper and backup data Start.");
714 if (!OHOS::FileExists(uriOrPixelMap)) {
715 return E_DEAL_FAILED;
716 }
717 WallpaperData wallpaperData;
718 bool ret = GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData);
719 if (!ret) {
720 HILOG_ERROR("GetWallpaperSafeLocked failed !");
721 return E_DEAL_FAILED;
722 }
723 wallpaperData.resourceType = resourceType;
724 wallpaperData.wallpaperId = MakeWallpaperIdLocked();
725 std::string wallpaperFile;
726 WallpaperService::GetWallpaperFile(resourceType, wallpaperData, wallpaperFile);
727 {
728 std::lock_guard<std::mutex> lock(mtx_);
729 if (!FileDeal::CopyFile(uriOrPixelMap, wallpaperFile)) {
730 HILOG_ERROR("CopyFile failed !");
731 return E_DEAL_FAILED;
732 }
733 if (!FileDeal::DeleteFile(uriOrPixelMap)) {
734 return E_DEAL_FAILED;
735 }
736 }
737 if (!SaveWallpaperState(userId, wallpaperType, resourceType)) {
738 HILOG_ERROR("Save wallpaper state failed!");
739 return E_DEAL_FAILED;
740 }
741 if (wallpaperType == WALLPAPER_SYSTEM) {
742 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
743 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
744 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
745 }
746 if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
747 HILOG_ERROR("Send wallpaper state failed!");
748 return E_DEAL_FAILED;
749 }
750 return E_OK;
751 }
752
GetWallpaperFile(WallpaperResourceType resourceType,const WallpaperData & wallpaperData,std::string & wallpaperFile)753 void WallpaperService::GetWallpaperFile(
754 WallpaperResourceType resourceType, const WallpaperData &wallpaperData, std::string &wallpaperFile)
755 {
756 switch (resourceType) {
757 case PICTURE:
758 wallpaperFile = wallpaperData.wallpaperFile;
759 break;
760 case DEFAULT:
761 wallpaperFile = wallpaperData.wallpaperFile;
762 break;
763 case VIDEO:
764 wallpaperFile = wallpaperData.liveWallpaperFile;
765 break;
766 case PACKAGE:
767 wallpaperFile = wallpaperData.customPackageUri;
768 break;
769 default:
770 HILOG_ERROR("Non-existent error type!");
771 break;
772 }
773 }
774
GetResType(int32_t userId,WallpaperType wallpaperType)775 WallpaperResourceType WallpaperService::GetResType(int32_t userId, WallpaperType wallpaperType)
776 {
777 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
778 auto iterator = lockWallpaperMap_.Find(userId);
779 if (iterator.first) {
780 return iterator.second.resourceType;
781 }
782 } else if (wallpaperType == WALLPAPER_SYSTEM) {
783 auto iterator = systemWallpaperMap_.Find(userId);
784 if (iterator.first) {
785 return iterator.second.resourceType;
786 }
787 }
788 return WallpaperResourceType::DEFAULT;
789 }
790
SendEvent(const std::string & eventType)791 ErrorCode WallpaperService::SendEvent(const std::string &eventType)
792 {
793 HILOG_INFO("Send event start.");
794 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
795 HILOG_ERROR("Send event not set permission!");
796 return E_NO_PERMISSION;
797 }
798
799 int32_t userId = QueryActiveUserId();
800 WallpaperType wallpaperType;
801 WallpaperData data;
802 if (eventType == SHOW_SYSTEM_SCREEN) {
803 wallpaperType = WALLPAPER_SYSTEM;
804 } else if (eventType == SHOW_LOCK_SCREEN) {
805 wallpaperType = WALLPAPER_LOCKSCREEN;
806 } else {
807 HILOG_ERROR("Event type error!");
808 return E_PARAMETERS_INVALID;
809 }
810
811 if (!GetWallpaperSafeLocked(userId, wallpaperType, data)) {
812 HILOG_ERROR("Get wallpaper safe locked failed!");
813 return E_PARAMETERS_INVALID;
814 }
815 std::string uri;
816 GetFileNameFromMap(userId, WALLPAPER_SYSTEM, uri);
817 WallpaperChanged(wallpaperType, data.resourceType, uri);
818 return E_OK;
819 }
820
SendWallpaperChangeEvent(int32_t userId,WallpaperType wallpaperType)821 bool WallpaperService::SendWallpaperChangeEvent(int32_t userId, WallpaperType wallpaperType)
822 {
823 WallpaperData wallpaperData;
824 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
825 HILOG_ERROR("GetWallpaperSafeLocked failed !");
826 return false;
827 }
828 shared_ptr<WallpaperCommonEventManager> wallpaperCommonEventManager = make_shared<WallpaperCommonEventManager>();
829 if (wallpaperType == WALLPAPER_SYSTEM) {
830 HILOG_INFO("Send wallpaper system setting message");
831 wallpaperCommonEventManager->SendWallpaperSystemSettingMessage(wallpaperData.resourceType);
832 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
833 HILOG_INFO("Send wallpaper lock setting message");
834 wallpaperCommonEventManager->SendWallpaperLockSettingMessage(wallpaperData.resourceType);
835 }
836 HILOG_INFO("SetWallpaperBackupData callbackProxy_->OnCall start");
837 if (callbackProxy_ != nullptr && (wallpaperData.resourceType == PICTURE || wallpaperData.resourceType == DEFAULT)) {
838 callbackProxy_->OnCall(wallpaperType);
839 }
840 std::string uri;
841 WallpaperChanged(wallpaperType, wallpaperData.resourceType, uri);
842 return true;
843 }
844
SetVideo(int32_t fd,int32_t wallpaperType,int32_t length)845 ErrorCode WallpaperService::SetVideo(int32_t fd, int32_t wallpaperType, int32_t length)
846 {
847 if (!IsSystemApp()) {
848 HILOG_ERROR("current app is not SystemApp");
849 return E_NOT_SYSTEM_APP;
850 }
851 StartAsyncTrace(HITRACE_TAG_MISC, "SetVideo", static_cast<int32_t>(TraceTaskId::SET_VIDEO));
852 ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, VIDEO);
853 FinishAsyncTrace(HITRACE_TAG_MISC, "SetVideo", static_cast<int32_t>(TraceTaskId::SET_VIDEO));
854 return wallpaperErrorCode;
855 }
856
SetCustomWallpaper(int32_t fd,int32_t type,int32_t length)857 ErrorCode WallpaperService::SetCustomWallpaper(int32_t fd, int32_t type, int32_t length)
858 {
859 if (!IsSystemApp()) {
860 HILOG_ERROR("current app is not SystemApp");
861 return E_NOT_SYSTEM_APP;
862 }
863 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
864 HILOG_ERROR("SetWallpaper no set permission!");
865 return E_NO_PERMISSION;
866 }
867 if (type != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) && type != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
868 return E_PARAMETERS_INVALID;
869 }
870 StartAsyncTrace(HITRACE_TAG_MISC, "SetCustomWallpaper", static_cast<int32_t>(TraceTaskId::SET_CUSTOM_WALLPAPER));
871 int32_t userId = QueryActiveUserId();
872 WallpaperType wallpaperType = static_cast<WallpaperType>(type);
873 WallpaperData wallpaperData;
874 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
875 HILOG_ERROR("GetWallpaper data failed!");
876 return E_DEAL_FAILED;
877 }
878 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
879 HILOG_ERROR("SceneBoard is not Enabled");
880 return E_NO_PERMISSION;
881 }
882 if (!SaveWallpaperState(userId, wallpaperType, PACKAGE)) {
883 HILOG_ERROR("Save wallpaper state failed!");
884 return E_DEAL_FAILED;
885 }
886 ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, PACKAGE);
887 wallpaperData.resourceType = PACKAGE;
888 wallpaperData.wallpaperId = MakeWallpaperIdLocked();
889 if (wallpaperType == WALLPAPER_SYSTEM) {
890 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
891 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
892 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
893 }
894 if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
895 HILOG_ERROR("Send wallpaper state failed!");
896 return E_DEAL_FAILED;
897 }
898 FinishAsyncTrace(HITRACE_TAG_MISC, "SetCustomWallpaper", static_cast<int32_t>(TraceTaskId::SET_CUSTOM_WALLPAPER));
899 return wallpaperErrorCode;
900 }
901
GetPixelMap(int32_t wallpaperType,IWallpaperService::FdInfo & fdInfo)902 ErrorCode WallpaperService::GetPixelMap(int32_t wallpaperType, IWallpaperService::FdInfo &fdInfo)
903 {
904 HILOG_INFO("WallpaperService::getPixelMap start ");
905 if (!IsSystemApp()) {
906 HILOG_ERROR("CallingApp is not SystemApp");
907 return E_NOT_SYSTEM_APP;
908 }
909 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
910 HILOG_ERROR("GetPixelMap no get permission!");
911 return E_NO_PERMISSION;
912 }
913 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
914 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
915 return E_PARAMETERS_INVALID;
916 }
917 auto type = static_cast<WallpaperType>(wallpaperType);
918 int32_t userId = QueryActiveUserId();
919 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
920 // current user's wallpaper is live video, not image
921 WallpaperResourceType resType = GetResType(userId, type);
922 if (resType != PICTURE && resType != DEFAULT) {
923 HILOG_ERROR("Current user's wallpaper is live video, not image");
924 fdInfo.size = 0; // 0: empty file size
925 fdInfo.fd = -1; // -1: invalid file description
926 return E_OK;
927 }
928 ErrorCode ret = GetImageSize(userId, type, fdInfo.size);
929 if (ret != E_OK) {
930 HILOG_ERROR("GetImageSize failed");
931 return ret;
932 }
933 ret = GetImageFd(userId, type, fdInfo.fd);
934 if (ret != E_OK) {
935 HILOG_ERROR("GetImageFd failed");
936 return ret;
937 }
938 return E_OK;
939 }
940
GetPixelMapV9(int32_t wallpaperType,IWallpaperService::FdInfo & fdInfo)941 ErrorCode WallpaperService::GetPixelMapV9(int32_t wallpaperType, IWallpaperService::FdInfo &fdInfo)
942 {
943 return GetPixelMap(wallpaperType, fdInfo);
944 }
945
GetWallpaperId(int32_t wallpaperType)946 int32_t WallpaperService::GetWallpaperId(int32_t wallpaperType)
947 {
948 HILOG_INFO("WallpaperService::GetWallpaperId --> start ");
949 int32_t iWallpaperId = -1;
950 int32_t userId = QueryActiveUserId();
951 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
952 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
953 auto iterator = lockWallpaperMap_.Find(userId);
954 if (iterator.first) {
955 iWallpaperId = iterator.second.wallpaperId;
956 }
957 } else if (wallpaperType == WALLPAPER_SYSTEM) {
958 auto iterator = systemWallpaperMap_.Find(userId);
959 if (iterator.first) {
960 iWallpaperId = iterator.second.wallpaperId;
961 }
962 }
963 HILOG_INFO("WallpaperService::GetWallpaperId --> end ID[%{public}d]", iWallpaperId);
964 return iWallpaperId;
965 }
966
IsChangePermitted()967 bool WallpaperService::IsChangePermitted()
968 {
969 HILOG_INFO("IsChangePermitted wallpaper Start!");
970 bool bFlag = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
971 return bFlag;
972 }
973
IsOperationAllowed()974 bool WallpaperService::IsOperationAllowed()
975 {
976 HILOG_INFO("IsOperationAllowed wallpaper Start!");
977 bool bFlag = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
978 return bFlag;
979 }
980
ResetWallpaper(int32_t wallpaperType)981 ErrorCode WallpaperService::ResetWallpaper(int32_t wallpaperType)
982 {
983 HILOG_INFO("reset wallpaper Start!");
984 bool permissionSet = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
985 if (!permissionSet) {
986 HILOG_ERROR("reset wallpaper no set permission!");
987 return E_NO_PERMISSION;
988 }
989 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
990 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
991 HILOG_ERROR("wallpaperType = %{public}d type not support ", wallpaperType);
992 return E_PARAMETERS_INVALID;
993 }
994 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
995 int32_t userId = QueryActiveUserId();
996 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
997 if (!CheckUserPermissionById(userId)) {
998 return E_USER_IDENTITY_ERROR;
999 }
1000 ErrorCode wallpaperErrorCode = SetDefaultDataForWallpaper(userId, type);
1001 HILOG_INFO(" Set default data result[%{public}d]", wallpaperErrorCode);
1002 return wallpaperErrorCode;
1003 }
1004
ResetWallpaperV9(int32_t wallpaperType)1005 ErrorCode WallpaperService::ResetWallpaperV9(int32_t wallpaperType)
1006 {
1007 if (!IsSystemApp()) {
1008 HILOG_ERROR("CallingApp is not SystemApp");
1009 return E_NOT_SYSTEM_APP;
1010 }
1011 return ResetWallpaper(wallpaperType);
1012 }
1013
SetDefaultDataForWallpaper(int32_t userId,WallpaperType wallpaperType)1014 ErrorCode WallpaperService::SetDefaultDataForWallpaper(int32_t userId, WallpaperType wallpaperType)
1015 {
1016 WallpaperData wallpaperData;
1017 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
1018 return E_DEAL_FAILED;
1019 }
1020 if (!RestoreUserResources(wallpaperData, wallpaperType)) {
1021 HILOG_ERROR("RestoreUserResources error");
1022 return E_DEAL_FAILED;
1023 }
1024 if (!SaveWallpaperState(userId, wallpaperType, DEFAULT)) {
1025 HILOG_ERROR("Save wallpaper state failed!");
1026 return E_DEAL_FAILED;
1027 }
1028 wallpaperData.wallpaperId = DEFAULT_WALLPAPER_ID;
1029 wallpaperData.resourceType = DEFAULT;
1030 wallpaperData.allowBackup = true;
1031 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1032 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
1033 } else if (wallpaperType == WALLPAPER_SYSTEM) {
1034 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
1035 }
1036 if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
1037 HILOG_ERROR("Send wallpaper state failed!");
1038 return E_DEAL_FAILED;
1039 }
1040 SaveColor(userId, wallpaperType);
1041 return E_OK;
1042 }
1043
On(const std::string & type,sptr<IWallpaperEventListener> listener)1044 ErrorCode WallpaperService::On(const std::string &type, sptr<IWallpaperEventListener> listener)
1045 {
1046 HILOG_DEBUG("WallpaperService::On in");
1047 if (listener == nullptr) {
1048 HILOG_ERROR("WallpaperService::On listener is null");
1049 return E_DEAL_FAILED;
1050 }
1051 if (type == WALLPAPER_CHANGE && !IsSystemApp()) {
1052 HILOG_ERROR("current app is not SystemApp");
1053 return E_NOT_SYSTEM_APP;
1054 }
1055 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1056 wallpaperEventMap_[type].insert_or_assign(IPCSkeleton::GetCallingTokenID(), listener);
1057 return E_OK;
1058 }
1059
Off(const std::string & type,sptr<IWallpaperEventListener> listener)1060 ErrorCode WallpaperService::Off(const std::string &type, sptr<IWallpaperEventListener> listener)
1061 {
1062 HILOG_DEBUG("WallpaperService::Off in");
1063 (void)listener;
1064 if (type == WALLPAPER_CHANGE && !IsSystemApp()) {
1065 HILOG_ERROR("current app is not SystemApp");
1066 return E_NOT_SYSTEM_APP;
1067 }
1068 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1069 auto iter = wallpaperEventMap_.find(type);
1070 if (iter != wallpaperEventMap_.end()) {
1071 auto it = iter->second.find(IPCSkeleton::GetCallingTokenID());
1072 if (it != iter->second.end()) {
1073 it->second = nullptr;
1074 iter->second.erase(it);
1075 }
1076 }
1077 return E_OK;
1078 }
1079
RegisterWallpaperCallback(const sptr<IWallpaperCallback> callback)1080 bool WallpaperService::RegisterWallpaperCallback(const sptr<IWallpaperCallback> callback)
1081 {
1082 HILOG_INFO(" WallpaperService::RegisterWallpaperCallback");
1083 callbackProxy_ = callback;
1084 return true;
1085 }
1086
GetWallpaperSafeLocked(int32_t userId,WallpaperType wallpaperType,WallpaperData & wallpaperData)1087 bool WallpaperService::GetWallpaperSafeLocked(int32_t userId, WallpaperType wallpaperType, WallpaperData &wallpaperData)
1088 {
1089 HILOG_DEBUG("GetWallpaperSafeLocked start.");
1090 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1091 : lockWallpaperMap_.Find(userId);
1092 if (!iterator.first) {
1093 HILOG_INFO(" No Lock wallpaper? Not tracking for lock-only ");
1094 LoadSettingsLocked(userId);
1095 iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1096 : lockWallpaperMap_.Find(userId);
1097 if (!iterator.first) {
1098 HILOG_ERROR("Fail to get wallpaper data");
1099 return false;
1100 }
1101 }
1102 wallpaperData = iterator.second;
1103 return true;
1104 }
1105
ClearWallpaperLocked(int32_t userId,WallpaperType wallpaperType)1106 void WallpaperService::ClearWallpaperLocked(int32_t userId, WallpaperType wallpaperType)
1107 {
1108 HILOG_INFO("Clear wallpaper Start!");
1109 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1110 : lockWallpaperMap_.Find(userId);
1111 if (!iterator.first) {
1112 HILOG_ERROR("Lock wallpaper already cleared");
1113 return;
1114 }
1115 if (!iterator.second.wallpaperFile.empty() || !iterator.second.liveWallpaperFile.empty()) {
1116 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1117 lockWallpaperMap_.Erase(userId);
1118 } else if (wallpaperType == WALLPAPER_SYSTEM) {
1119 systemWallpaperMap_.Erase(userId);
1120 }
1121 }
1122 }
1123
CheckCallingPermission(const std::string & permissionName)1124 bool WallpaperService::CheckCallingPermission(const std::string &permissionName)
1125 {
1126 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1127 int32_t result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
1128 if (result != TypePermissionState::PERMISSION_GRANTED) {
1129 HILOG_ERROR("Check permission failed.");
1130 return false;
1131 }
1132 return true;
1133 }
1134
GetBundleNameByUid(std::int32_t uid,std::string & bname)1135 bool WallpaperService::GetBundleNameByUid(std::int32_t uid, std::string &bname)
1136 {
1137 sptr<ISystemAbilityManager> systemMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1138 if (systemMgr == nullptr) {
1139 HILOG_ERROR("Fail to get system ability mgr");
1140 return false;
1141 }
1142
1143 sptr<IRemoteObject> remoteObject = systemMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1144 if (remoteObject == nullptr) {
1145 HILOG_ERROR("Fail to get bundle manager proxy");
1146 return false;
1147 }
1148
1149 sptr<OHOS::AppExecFwk::IBundleMgr> bundleMgrProxy = iface_cast<OHOS::AppExecFwk::IBundleMgr>(remoteObject);
1150 if (bundleMgrProxy == nullptr) {
1151 HILOG_ERROR("Bundle mgr proxy is nullptr");
1152 return false;
1153 }
1154
1155 ErrCode errCode = bundleMgrProxy->GetNameForUid(uid, bname);
1156 if (errCode != ERR_OK) {
1157 HILOG_ERROR("Get bundle name failed errcode:%{public}d", errCode);
1158 return false;
1159 }
1160 HILOG_INFO("Get bundle name is %{public}s", bname.c_str());
1161 return true;
1162 }
1163
ReporterFault(FaultType faultType,FaultCode faultCode)1164 void WallpaperService::ReporterFault(FaultType faultType, FaultCode faultCode)
1165 {
1166 FaultMsg msg;
1167 msg.faultType = faultType;
1168 msg.errorCode = faultCode;
1169 ReportStatus nRet;
1170 if (faultType == FaultType::SERVICE_FAULT) {
1171 msg.moduleName = "WallpaperService";
1172 nRet = FaultReporter::ReportServiceFault(msg);
1173 } else {
1174 nRet = FaultReporter::ReportRuntimeFault(msg);
1175 }
1176
1177 if (nRet == ReportStatus::SUCCESS) {
1178 HILOG_INFO("ReporterFault success");
1179 } else {
1180 HILOG_ERROR("ReporterFault failed");
1181 }
1182 }
1183
Dump(int32_t fd,const std::vector<std::u16string> & args)1184 int32_t WallpaperService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1185 {
1186 std::vector<std::string> argsStr;
1187 for (auto item : args) {
1188 argsStr.emplace_back(Str16ToStr8(item));
1189 }
1190
1191 if (DumpHelper::GetInstance().Dispatch(fd, argsStr)) {
1192 HILOG_ERROR("DumpHelper Dispatch failed");
1193 return 0;
1194 }
1195 return 1;
1196 }
1197
1198 #ifndef THEME_SERVICE
ConnectExtensionAbility()1199 bool WallpaperService::ConnectExtensionAbility()
1200 {
1201 HILOG_DEBUG("ConnectAdapter");
1202 MemoryGuard cacheGuard;
1203 AAFwk::Want want;
1204 want.SetElementName(OHOS_WALLPAPER_BUNDLE_NAME, "WallpaperExtAbility");
1205 ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
1206 if (errCode != ERR_OK) {
1207 HILOG_ERROR("connect ability server failed errCode=%{public}d", errCode);
1208 return false;
1209 }
1210 if (connection_ == nullptr) {
1211 connection_ = new WallpaperExtensionAbilityConnection(*this);
1212 }
1213 auto ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectExtensionAbility(want, connection_, DEFAULT_VALUE);
1214 HILOG_INFO("ConnectExtensionAbility errCode=%{public}d", ret);
1215 return ret;
1216 }
1217 #endif
1218
IsSystemApp()1219 bool WallpaperService::IsSystemApp()
1220 {
1221 HILOG_INFO("IsSystemApp start");
1222 uint64_t tokenId = IPCSkeleton::GetCallingFullTokenID();
1223 return TokenIdKit::IsSystemAppByFullTokenID(tokenId);
1224 }
1225
GetImageFd(int32_t userId,WallpaperType wallpaperType,int32_t & fd)1226 ErrorCode WallpaperService::GetImageFd(int32_t userId, WallpaperType wallpaperType, int32_t &fd)
1227 {
1228 HILOG_INFO("WallpaperService::GetImageFd start ");
1229 std::string filePathName;
1230 if (!GetFileNameFromMap(userId, wallpaperType, filePathName)) {
1231 return E_DEAL_FAILED;
1232 }
1233 if (GetResType(userId, wallpaperType) == WallpaperResourceType::PACKAGE) {
1234 HILOG_INFO("The current wallpaper is a custom wallpaper");
1235 return E_OK;
1236 }
1237 {
1238 std::lock_guard<std::mutex> lock(mtx_);
1239 fd = open(filePathName.c_str(), O_RDONLY, S_IREAD);
1240 }
1241 if (fd < 0) {
1242 HILOG_ERROR("Open file failed, errno %{public}d", errno);
1243 ReporterFault(FaultType::LOAD_WALLPAPER_FAULT, FaultCode::RF_FD_INPUT_FAILED);
1244 return E_DEAL_FAILED;
1245 }
1246 HILOG_INFO("fd = %{public}d", fd);
1247 return E_OK;
1248 }
1249
GetImageSize(int32_t userId,WallpaperType wallpaperType,int32_t & size)1250 ErrorCode WallpaperService::GetImageSize(int32_t userId, WallpaperType wallpaperType, int32_t &size)
1251 {
1252 HILOG_INFO("WallpaperService::GetImageSize start ");
1253 std::string filePathName;
1254 HILOG_INFO("userId = %{public}d", userId);
1255 if (!GetPictureFileName(userId, wallpaperType, filePathName)) {
1256 return E_DEAL_FAILED;
1257 }
1258
1259 if (!OHOS::FileExists(filePathName)) {
1260 HILOG_ERROR("file is not exist!");
1261 return E_NOT_FOUND;
1262 }
1263 std::lock_guard<std::mutex> lock(mtx_);
1264 FILE *fd = fopen(filePathName.c_str(), "rb");
1265 if (fd == nullptr) {
1266 HILOG_ERROR("fopen file failed, errno %{public}d", errno);
1267 return E_FILE_ERROR;
1268 }
1269 int32_t fend = fseek(fd, 0, SEEK_END);
1270 size = ftell(fd);
1271 int32_t fset = fseek(fd, 0, SEEK_SET);
1272 if (size <= 0 || fend != 0 || fset != 0) {
1273 HILOG_ERROR("ftell file failed or fseek file failed, errno %{public}d", errno);
1274 fclose(fd);
1275 return E_FILE_ERROR;
1276 }
1277 fclose(fd);
1278 return E_OK;
1279 }
1280
BlockRetry(int64_t interval,uint32_t maxRetryTimes,std::function<bool ()> function)1281 bool WallpaperService::BlockRetry(int64_t interval, uint32_t maxRetryTimes, std::function<bool()> function)
1282 {
1283 uint32_t times = 0;
1284 bool ret = false;
1285 do {
1286 times++;
1287 ret = function();
1288 if (ret) {
1289 break;
1290 }
1291 std::this_thread::sleep_for(std::chrono::milliseconds(interval));
1292 HILOG_INFO("function() is: %d", ret);
1293 } while (times < maxRetryTimes);
1294 HILOG_INFO("retry times: %d", times);
1295 return ret;
1296 }
1297
QueryActiveUserId()1298 int32_t WallpaperService::QueryActiveUserId()
1299 {
1300 std::vector<int32_t> ids;
1301 ErrCode errCode = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
1302 if (errCode != ERR_OK || ids.empty()) {
1303 HILOG_ERROR("Query active userid failed, errCode: %{public}d, ", errCode);
1304 return DEFAULT_USER_ID;
1305 }
1306 return ids[0];
1307 }
1308
CheckUserPermissionById(int32_t userId)1309 bool WallpaperService::CheckUserPermissionById(int32_t userId)
1310 {
1311 OsAccountInfo osAccountInfo;
1312 ErrCode errCode = OsAccountManager::QueryOsAccountById(userId, osAccountInfo);
1313 if (errCode != ERR_OK) {
1314 HILOG_ERROR("Query os account info failed, errCode: %{public}d, ", errCode);
1315 return false;
1316 }
1317 HILOG_INFO("osAccountInfo GetType: %{public}d", static_cast<int32_t>(osAccountInfo.GetType()));
1318 if (osAccountInfo.GetType() == OsAccountType::GUEST) {
1319 HILOG_ERROR("The guest does not have permissions");
1320 return false;
1321 }
1322 return true;
1323 }
1324
SetWallpaper(int32_t fd,int32_t wallpaperType,int32_t length,WallpaperResourceType resourceType)1325 ErrorCode WallpaperService::SetWallpaper(
1326 int32_t fd, int32_t wallpaperType, int32_t length, WallpaperResourceType resourceType)
1327 {
1328 int32_t userId = QueryActiveUserId();
1329 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1330 if (!CheckUserPermissionById(userId)) {
1331 return E_USER_IDENTITY_ERROR;
1332 }
1333 ErrorCode errCode = CheckValid(wallpaperType, length, resourceType);
1334 if (errCode != E_OK) {
1335 return errCode;
1336 }
1337 std::string uri = wallpaperTmpFullPath_;
1338 char *paperBuf = new (std::nothrow) char[length]();
1339 if (paperBuf == nullptr) {
1340 return E_NO_MEMORY;
1341 }
1342 {
1343 std::lock_guard<std::mutex> lock(mtx_);
1344 if (read(fd, paperBuf, length) <= 0) {
1345 HILOG_ERROR("read fd failed");
1346 delete[] paperBuf;
1347 return E_DEAL_FAILED;
1348 }
1349 mode_t mode = S_IRUSR | S_IWUSR;
1350 int32_t fdw = open(uri.c_str(), O_WRONLY | O_CREAT, mode);
1351 if (fdw < 0) {
1352 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
1353 delete[] paperBuf;
1354 return E_DEAL_FAILED;
1355 }
1356 if (write(fdw, paperBuf, length) <= 0) {
1357 HILOG_ERROR("Write to fdw failed, errno %{public}d", errno);
1358 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
1359 delete[] paperBuf;
1360 close(fdw);
1361 return E_DEAL_FAILED;
1362 }
1363 delete[] paperBuf;
1364 close(fdw);
1365 }
1366 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1367 ErrorCode wallpaperErrorCode = SetWallpaperBackupData(userId, resourceType, uri, type);
1368 if (resourceType == PICTURE) {
1369 SaveColor(userId, type);
1370 }
1371 return wallpaperErrorCode;
1372 }
1373
SetWallpaperByPixelMap(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,int32_t wallpaperType,WallpaperResourceType resourceType)1374 ErrorCode WallpaperService::SetWallpaperByPixelMap(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,
1375 int32_t wallpaperType, WallpaperResourceType resourceType)
1376 {
1377 int32_t userId = QueryActiveUserId();
1378 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1379 if (!CheckUserPermissionById(userId)) {
1380 return E_USER_IDENTITY_ERROR;
1381 }
1382 std::string uri = wallpaperTmpFullPath_;
1383 ErrorCode errCode = WritePixelMapToFile(pixelMap, uri, wallpaperType, resourceType);
1384 if (errCode != E_OK) {
1385 HILOG_ERROR("WritePixelMapToFile failed!");
1386 return errCode;
1387 }
1388 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1389 ErrorCode wallpaperErrorCode = SetWallpaperBackupData(userId, resourceType, uri, type);
1390 if (resourceType == PICTURE) {
1391 SaveColor(userId, type);
1392 }
1393 return wallpaperErrorCode;
1394 }
1395
WritePixelMapToFile(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,std::string wallpaperTmpFullPath,int32_t wallpaperType,WallpaperResourceType resourceType)1396 ErrorCode WallpaperService::WritePixelMapToFile(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,
1397 std::string wallpaperTmpFullPath, int32_t wallpaperType, WallpaperResourceType resourceType)
1398 {
1399 std::stringbuf stringBuf;
1400 std::ostream ostream(&stringBuf);
1401 int32_t mapSize = WritePixelMapToStream(pixelMap, ostream);
1402 if (mapSize <= 0) {
1403 HILOG_ERROR("WritePixelMapToStream failed");
1404 return E_WRITE_PARCEL_ERROR;
1405 }
1406 ErrorCode errCode = CheckValid(wallpaperType, mapSize, resourceType);
1407 if (errCode != E_OK) {
1408 HILOG_ERROR("CheckValid failed");
1409 return errCode;
1410 }
1411 char *buffer = new (std::nothrow) char[mapSize]();
1412 if (buffer == nullptr) {
1413 HILOG_ERROR("buffer failed");
1414 return E_NO_MEMORY;
1415 }
1416 stringBuf.sgetn(buffer, mapSize);
1417 {
1418 std::lock_guard<std::mutex> lock(mtx_);
1419 mode_t mode = S_IRUSR | S_IWUSR;
1420 int32_t fdw = open(wallpaperTmpFullPath.c_str(), O_WRONLY | O_CREAT, mode);
1421 if (fdw < 0) {
1422 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
1423 delete[] buffer;
1424 return E_DEAL_FAILED;
1425 }
1426 if (write(fdw, buffer, mapSize) <= 0) {
1427 HILOG_ERROR("Write to fdw failed, errno %{public}d", errno);
1428 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
1429 delete[] buffer;
1430 close(fdw);
1431 return E_DEAL_FAILED;
1432 }
1433 delete[] buffer;
1434 close(fdw);
1435 }
1436 return E_OK;
1437 }
1438
WritePixelMapToStream(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,std::ostream & outputStream)1439 int64_t WallpaperService::WritePixelMapToStream(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,
1440 std::ostream &outputStream)
1441 {
1442 OHOS::Media::ImagePacker imagePacker;
1443 OHOS::Media::PackOption option;
1444 option.format = "image/jpeg";
1445 option.quality = OPTION_QUALITY;
1446 option.numberHint = 1;
1447 std::set<std::string> formats;
1448 uint32_t ret = imagePacker.GetSupportedFormats(formats);
1449 if (ret != 0) {
1450 HILOG_ERROR("image packer get supported format failed, ret=%{public}u.", ret);
1451 }
1452
1453 imagePacker.StartPacking(outputStream, option);
1454 imagePacker.AddImage(*pixelMap);
1455 int64_t packedSize = 0;
1456 imagePacker.FinalizePacking(packedSize);
1457 HILOG_INFO("FrameWork WritePixelMapToStream End! packedSize=%{public}lld.", static_cast<long long>(packedSize));
1458 return packedSize;
1459 }
1460
OnColorsChange(WallpaperType wallpaperType,const ColorManager::Color & color)1461 void WallpaperService::OnColorsChange(WallpaperType wallpaperType, const ColorManager::Color &color)
1462 {
1463 std::vector<uint64_t> colors;
1464 if (wallpaperType == WALLPAPER_SYSTEM && !CompareColor(systemWallpaperColor_, color)) {
1465 systemWallpaperColor_ = color.PackValue();
1466 colors.emplace_back(systemWallpaperColor_);
1467 NotifyColorChange(colors, WALLPAPER_SYSTEM);
1468 } else if (wallpaperType == WALLPAPER_LOCKSCREEN && !CompareColor(lockWallpaperColor_, color)) {
1469 lockWallpaperColor_ = color.PackValue();
1470 colors.emplace_back(lockWallpaperColor_);
1471 NotifyColorChange(colors, WALLPAPER_LOCKSCREEN);
1472 }
1473 }
1474
CheckValid(int32_t wallpaperType,int32_t length,WallpaperResourceType resourceType)1475 ErrorCode WallpaperService::CheckValid(int32_t wallpaperType, int32_t length, WallpaperResourceType resourceType)
1476 {
1477 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
1478 HILOG_ERROR("SetWallpaper no set permission!");
1479 return E_NO_PERMISSION;
1480 }
1481 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
1482 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
1483 return E_PARAMETERS_INVALID;
1484 }
1485
1486 int maxLength = resourceType == VIDEO ? MAX_VIDEO_SIZE : FOO_MAX_LEN;
1487 if (length <= 0 || length > maxLength) {
1488 return E_PARAMETERS_INVALID;
1489 }
1490 return E_OK;
1491 }
1492
WallpaperChanged(WallpaperType wallpaperType,WallpaperResourceType resType,const std::string & uri)1493 bool WallpaperService::WallpaperChanged(
1494 WallpaperType wallpaperType, WallpaperResourceType resType, const std::string &uri)
1495 {
1496 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1497 auto it = wallpaperEventMap_.find(WALLPAPER_CHANGE);
1498 if (it != wallpaperEventMap_.end()) {
1499 for (auto iter = it->second.begin(); iter != it->second.end(); iter++) {
1500 if (iter->second == nullptr) {
1501 continue;
1502 }
1503 iter->second->OnWallpaperChange(wallpaperType, resType, uri);
1504 }
1505 return true;
1506 }
1507 return false;
1508 }
1509
NotifyColorChange(const std::vector<uint64_t> & colors,const WallpaperType & wallpaperType)1510 void WallpaperService::NotifyColorChange(const std::vector<uint64_t> &colors, const WallpaperType &wallpaperType)
1511 {
1512 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1513 auto it = wallpaperEventMap_.find(COLOR_CHANGE);
1514 if (it != wallpaperEventMap_.end()) {
1515 for (auto iter = it->second.begin(); iter != it->second.end(); iter++) {
1516 if (iter->second == nullptr) {
1517 continue;
1518 }
1519 iter->second->OnColorsChange(colors, wallpaperType);
1520 }
1521 }
1522 }
1523
SaveWallpaperState(int32_t userId,WallpaperType wallpaperType,WallpaperResourceType resourceType)1524 bool WallpaperService::SaveWallpaperState(
1525 int32_t userId, WallpaperType wallpaperType, WallpaperResourceType resourceType)
1526 {
1527 WallpaperData systemData;
1528 WallpaperData lockScreenData;
1529 if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData)
1530 || !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
1531 return false;
1532 }
1533 nlohmann::json root;
1534 if (wallpaperType == WALLPAPER_SYSTEM) {
1535 root[SYSTEM_RES_TYPE] = static_cast<int32_t>(resourceType);
1536 root[LOCKSCREEN_RES_TYPE] = static_cast<int32_t>(lockScreenData.resourceType);
1537 } else {
1538 root[LOCKSCREEN_RES_TYPE] = static_cast<int32_t>(resourceType);
1539 root[SYSTEM_RES_TYPE] = static_cast<int32_t>(systemData.resourceType);
1540 }
1541 std::string json = root.dump();
1542 if (json.empty()) {
1543 HILOG_ERROR("write user config file failed. because json content is empty.");
1544 return false;
1545 }
1546
1547 std::string userPath = WALLPAPER_USERID_PATH + std::to_string(userId) + "/wallpapercfg";
1548 mode_t mode = S_IRUSR | S_IWUSR;
1549 int fd = open(userPath.c_str(), O_CREAT | O_WRONLY | O_SYNC, mode);
1550 if (fd <= 0) {
1551 HILOG_ERROR("open user config file failed.");
1552 return false;
1553 }
1554 ssize_t size = write(fd, json.c_str(), json.size());
1555 if (size <= 0) {
1556 HILOG_ERROR("write user config file failed.");
1557 close(fd);
1558 return false;
1559 }
1560 close(fd);
1561 return true;
1562 }
1563
LoadWallpaperState()1564 void WallpaperService::LoadWallpaperState()
1565 {
1566 int32_t userId = QueryActiveUserId();
1567 std::string userPath = WALLPAPER_USERID_PATH + std::to_string(userId) + "/wallpapercfg";
1568 int fd = open(userPath.c_str(), O_RDONLY, S_IREAD);
1569 if (fd <= 0) {
1570 HILOG_ERROR("open user config file failed.");
1571 return;
1572 }
1573 const size_t len = 255;
1574 char buf[len] = { 0 };
1575 ssize_t size = read(fd, buf, len);
1576 if (size <= 0) {
1577 HILOG_ERROR("read user config file failed.");
1578 close(fd);
1579 return;
1580 }
1581 close(fd);
1582
1583 if (buf[0] == '\0') {
1584 return;
1585 }
1586 WallpaperData systemData;
1587 WallpaperData lockScreenData;
1588 if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData)
1589 || !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
1590 return;
1591 }
1592 if (Json::accept(buf)) {
1593 auto root = nlohmann::json::parse(buf);
1594 if (root.contains(SYSTEM_RES_TYPE) && root[SYSTEM_RES_TYPE].is_number()) {
1595 systemData.resourceType = static_cast<WallpaperResourceType>(root[SYSTEM_RES_TYPE].get<int>());
1596 }
1597 if (root.contains(LOCKSCREEN_RES_TYPE) && root[SYSTEM_RES_TYPE].is_number()) {
1598 lockScreenData.resourceType = static_cast<WallpaperResourceType>(root[LOCKSCREEN_RES_TYPE].get<int>());
1599 }
1600 }
1601 }
1602 } // namespace WallpaperMgrService
1603 } // namespace OHOS
1604