• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022-2023 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
16import router from '@ohos.router';
17import {
18  AlbumDefine,
19  BigDataConstants,
20  BroadCast,
21  BroadCastConstants,
22  BroadCastManager,
23  Constants as Cons,
24  DataStoreUtil,
25  Log,
26  ReportToBigDataUtil,
27  ScreenManager,
28  UiUtil,
29  UserFileManagerAccess,
30} from '@ohos/common';
31import { Constants, FormControllerManager } from '@ohos/formAbility';
32import formBindingData from '@ohos.application.formBindingData';
33import formProvider from '@ohos.application.formProvider';
34import userFileManager from '@ohos.filemanagement.userFileManager';
35
36
37const TAG: string = 'FormEditorPage';
38
39@Entry
40@Component
41struct FormEditorPage {
42  @StorageLink('FASetting_FormId') formId: string = '0';
43  @StorageLink('isHorizontal') isHorizontal: boolean = ScreenManager.getInstance().isHorizontal();
44  @StorageLink('isSidebar') isSidebar: boolean = ScreenManager.getInstance().isSidebar();
45  @StorageLink('leftBlank') leftBlank: [number, number, number, number]
46    = [0, ScreenManager.getInstance().getStatusBarHeight(), 0, ScreenManager.getInstance().getNaviBarHeight()];
47  currentIndex: number = 0;
48  @State isShowName: boolean = true;
49  isShowAlbums: boolean = true;
50  fd: number = Constants.FA_FD_NULL;
51  fileAsset: userFileManager.FileAsset = null;
52  displayName: string = '';
53  albumUri: string = '';
54  uri: string = '';
55  @State time: number = 30;
56  private appBroadCast: BroadCast = BroadCastManager.getInstance().getBroadCast();
57  private saveDataFunc = this.saveData.bind(this);
58  private indexValue: number = 0;
59  @State private selectAlbumsStr: string = '';
60
61  async getItems(albumUri?: string, startIndex?: number, count?: number, filterMediaType?: string):
62    Promise<Array<userFileManager.FileAsset>> {
63    let result: Array<userFileManager.FileAsset> = null;
64
65    // Get from target album if albumUri is not undefined, otherwise getAllObject
66    if (albumUri) {
67      let album: userFileManager.Album = await UserFileManagerAccess.getInstance().getAlbumByUri(albumUri);
68      let fetchOpt = AlbumDefine.getFileFetchOpt(startIndex, count, filterMediaType);
69      let fetchResult = await album.getPhotoAssets(fetchOpt);
70      result = await fetchResult.getAllObject();
71      fetchResult.close();
72    } else {
73      let fetchOpt = AlbumDefine.getFileFetchOpt(startIndex, count, filterMediaType);
74      Log.debug(TAG, `getMediaItem start ${JSON.stringify(fetchOpt)}`);
75      result = await UserFileManagerAccess.getInstance().getAllObject(fetchOpt);
76    }
77    return result;
78  }
79
80  async GetMediaData(albumUri: string, uri: string) {
81    Log.debug(TAG, `GetMediaData start uri: ${uri} albumUri: ${albumUri}`)
82    let dataList = await this.getItems(albumUri);
83    if (uri != '') {
84      for (let i = 0; i < dataList.length; i++) {
85        let temUri = dataList[i].uri;
86        if (temUri === uri) {
87          this.currentIndex = i;
88          break;
89        }
90      }
91    } else {
92      this.currentIndex = 0;
93    }
94    this.fileAsset = dataList[this.currentIndex];
95    Log.debug(TAG, 'GetMediaData fileAsset: ' + JSON.stringify(this.fileAsset));
96  }
97
98  async openCurrentfd() {
99    this.fd = (this.fileAsset != null) ? await UserFileManagerAccess.getInstance().openAsset('R', this.fileAsset)
100                                       : Constants.FA_FD_NULL;
101  }
102
103  bindFormData(): formBindingData.FormBindingData {
104    Log.debug(TAG, `bindFormData start formId: ${this.formId}`)
105    let image: string = 'image_' + this.fd + '_formId_' + this.formId;
106    let dataObj1: object = {
107      "fd": this.fd == Constants.FA_FD_NULL ? false : true,
108      "image0": "memory://" + image,
109      "image1": "memory://" + image,
110      "indexValue": this.indexValue,
111      "albumName": this.displayName,
112      "currentIndex": this.currentIndex,
113      "isShow": Boolean(this.isShowName) && Boolean(this.isShowAlbums),
114      "formImages": JSON.parse(`{ "${image}": ${this.fd} }`),
115      "uri": (this.uri != '') ? Cons.ACTION_URI_FORM_ABILITY : Cons.ACTION_URI_FORM_ABILITY_NONE,
116      "albumUri": `${this.albumUri}`,
117      "currentUri": this.uri
118    };
119    Log.debug(TAG, `bindFormData, createFormBindingData dataObj2.data: ${JSON.stringify(dataObj1)}`);
120    let obj = formBindingData.createFormBindingData(JSON.stringify(dataObj1));
121    Log.debug(TAG, `bindFormData, createFormBindingData obj2.data: ${JSON.stringify(obj.data)}`);
122    return obj;
123  }
124
125  terminate() {
126    globalThis.photosAbilityContext.terminateSelf((result) => {
127      Log.info(TAG, `terminateSelf result: ${JSON.stringify(result)}`);
128    })
129  }
130
131  async updateFormData() {
132    Log.debug(TAG, `updateFormData formId: ${JSON.stringify(this.formId)}`);
133    let dataStore = DataStoreUtil.getInstance();
134    await dataStore.init();
135    let temp = await dataStore.getData(Constants.FA_INDEX_VALUE, 0);
136    this.indexValue = (temp + Constants.NUMBER_1) % Constants.NUMBER_2;
137    await dataStore.putData(Constants.FA_INDEX_VALUE, this.indexValue);
138    await dataStore.flush();
139    await this.GetMediaData(this.albumUri, this.uri);
140    await this.openCurrentfd();
141    let obj3 = this.bindFormData();
142    Log.debug(TAG, `updateFormData obj: ${JSON.stringify(obj3)}`);
143    Log.debug(TAG, `indexValueindexValueindexValue: ${this.indexValue}`);
144    formProvider.updateForm(this.formId, obj3)
145      .then(() => {
146        Log.debug(TAG, `updateFormData, success`);
147        this.terminate();
148      }).catch((error) => {
149      Log.error(TAG, `updateForm failed. Cause: ${JSON.stringify(error)}`);
150      let msg = {
151        'err': JSON.stringify(error)
152      }
153      ReportToBigDataUtil.errEventReport(BigDataConstants.CHANGE_FA_CARD_IMAGE_ERROR, msg);
154      this.terminate();
155    });
156  }
157
158  async saveData(albumName: string, albumUri: string, displayName, uri: string, isShowAlbums: boolean) {
159    Log.debug(TAG, `saveData start! ${albumUri} ${displayName}  ${uri}`)
160    ReportToBigDataUtil.report(BigDataConstants.CHANGE_FA_CARD_IMAGE_ID, null);
161    let msgDisplayName: string = '';
162    if (displayName instanceof Object) {
163      Log.debug(TAG, `saveData object ${displayName}`);
164      msgDisplayName = await UiUtil.getResourceString(displayName);
165    } else {
166      msgDisplayName = displayName;
167    }
168    this.isShowAlbums = isShowAlbums;
169    this.displayName = msgDisplayName;
170    this.albumUri = albumUri;
171    this.uri = uri;
172    Log.debug(TAG, `saveData msgDisplayName ${msgDisplayName}`);
173    await DataStoreUtil.getInstance().init();
174    let formIdKey = 'formId_' + this.formId;
175    let hasFormId = await DataStoreUtil.getInstance().hasData(formIdKey);
176    Log.debug(TAG, `The value of hasFormId is ${hasFormId}`);
177    if (hasFormId) {
178      let displayNameKey = 'displayName_' + this.formId;
179      await DataStoreUtil.getInstance().putData(displayNameKey, msgDisplayName);
180      let albumNameKey = 'albumName_' + this.formId;
181      await DataStoreUtil.getInstance().putData(albumNameKey, albumName);
182      let albumUriKey = 'albumUri_' + this.formId;
183      await DataStoreUtil.getInstance().putData(albumUriKey, albumUri);
184      let currentUriKey = 'currentUri_' + this.formId;
185      await DataStoreUtil.getInstance().putData(currentUriKey, uri);
186      let intervalTimeKey = 'intervalTime_' + this.formId;
187      await DataStoreUtil.getInstance().putData(intervalTimeKey, this.time);
188      let currentIndexKey = 'currentIndex_' + this.formId;
189      await DataStoreUtil.getInstance().putData(currentIndexKey, this.currentIndex);
190      let isShowKey = 'isShowAlbums_' + this.formId;
191      await DataStoreUtil.getInstance().putData(isShowKey, this.isShowAlbums ? 1 : 0);
192      await DataStoreUtil.getInstance().flush();
193      this.updateFormData();
194    } else {
195      globalThis.photosAbilityContext.terminateSelf((result) => {
196        Log.info(TAG, `terminateSelf result: ${JSON.stringify(result)}`);
197      })
198    }
199    Log.debug(TAG, 'meow saveData end!');
200  }
201
202  routerPhotos(isSelectPhoto: boolean) {
203    let options = {
204      url: 'pages/ThirdSelectPhotoGridPage',
205      params: {
206        itemCoverUri: '',
207        uri: "",
208        itemCount: 1,
209        bundleName: '',
210        isMultiPick: false,
211        filterMediaType: AlbumDefine.FILTER_MEDIA_TYPE_IMAGE,
212        maxSelectCount: Cons.NUMBER_1,
213        itemDisplayName: $r('app.string.album_all'),
214        isFromFa: isSelectPhoto,
215        isFromFaPhoto: isSelectPhoto,
216        isFirstEnter: true
217      }
218    }
219    router.pushUrl(options);
220  }
221
222  selectPhoto() {
223    this.routerPhotos(true);
224  }
225
226  aboutToAppear(): void {
227    Log.debug(TAG, 'aboutToAppear start!')
228    ScreenManager.getInstance().setSystemUi(false);
229    this.appBroadCast.on(BroadCastConstants.SAVE_FORM_EDITOR_DATA, this.saveDataFunc);
230    DataStoreUtil.getInstance().init().then(() => {
231      let intervalTimeKey = 'intervalTime_' + this.formId;
232      DataStoreUtil.getInstance().getData(intervalTimeKey, this.time).then((intervalTime) => {
233        this.time = intervalTime;
234        AppStorage.SetOrCreate(Constants.FROM_PLAYBACK_INTERVAL, this.time);
235      })
236      let isShowKey = Constants.FROM_PLAYBACK_ISSHOWNAME;
237      DataStoreUtil.getInstance().getData(isShowKey, this.isShowName).then((isShowName) => {
238        Log.debug(TAG, `aboutToAppear  isShowKey:` + JSON.stringify(isShowKey) + JSON.stringify(Boolean(isShowName)))
239        this.isShowName = isShowName;
240      })
241    })
242    UiUtil.getResourceString($r('app.string.fa_select_album_text')).then((stringResource) => {
243      Log.debug(TAG, `getResourceString ${stringResource}}`)
244      this.selectAlbumsStr = stringResource;
245    })
246  }
247
248  aboutToDisappear() {
249    this.appBroadCast.off(BroadCastConstants.SAVE_FORM_EDITOR_DATA, this.saveDataFunc);
250  }
251
252  onPageShow() {
253    BroadCastManager.getInstance().getBroadCast().emit(BroadCastConstants.THIRD_ROUTE_PAGE, []);
254  }
255
256  onBackPress() {
257    this.terminate();
258  }
259
260  build() {
261    Column() {
262      Row() {
263        Row() {
264          Image($r('app.media.ic_gallery_public_cancel'))
265            .fillColor($r('app.color.white'))
266            .width($r('app.float.ic_size_default'))
267            .height($r('app.float.ic_size_default'))
268            .margin({ left: $r('app.float.FA_back_margin_left') })
269        }
270        .alignItems(VerticalAlign.Center)
271        .height($r('app.float.tab_bar_vertical_height'))
272      }
273      .padding({
274        top: $r('app.float.album_set_page_action_bar_padding_top')
275      })
276      .width('100%')
277      .onClick(() => {
278        this.onBackPress();
279      })
280
281      Column() {
282        Text($r('app.string.fa_title_text'))
283          .fontSize($r('sys.float.ohos_id_text_size_headline8'))
284          .fontColor($r('app.color.FA_title_text_color'))
285          .fontWeight(FontWeight.Medium)
286
287        Text($r('app.string.fa_subTitle_text'))
288          .fontSize($r('sys.float.ohos_id_text_size_body1'))
289          .margin({ top: $r('app.float.tab_bar_padding_top') })
290          .fontColor($r('app.color.FA_subTitle_text_color'))
291      }
292      .margin({ top: $r('app.float.FA_subTitle_margin_top'), bottom: $r('app.float.FA_title_margin_bottom') })
293
294      Row() {
295        Row() {
296          Text($r('app.string.fa_select_image_text'))
297            .fontWeight(FontWeight.Medium)
298            .fontSize($r('sys.float.ohos_id_text_size_body1'))
299            .fontColor($r('app.color.black'))
300            .flexGrow(Constants.FLEX_GROW)
301          Row() {
302            Image($r('app.media.ic_gallery_form_arrow'))
303              .width($r('app.float.form_list_card_more_arrow_w'))
304              .height($r('app.float.form_list_card_more_arrow_h'))
305              .fillColor($r('sys.color.ohos_id_color_fourth'))
306          }
307        }
308        .height($r('app.float.title_default'))
309        .width('100%')
310        .key('FASelectPhoto')
311        .padding({
312          left: $r('app.float.FA_ListCard_padding_left'), right: $r('app.float.FA_ListCard_padding_left'),
313        })
314        .backgroundColor($r('app.color.white'))
315        .borderRadius($r('app.float.FA_ListCard_radius'))
316        .onClick(() => {
317          this.selectPhoto();
318        })
319      }
320      .padding({ left: $r('app.float.FA_select_album_padding'), right: $r('app.float.FA_select_album_padding') })
321    }
322    .backgroundColor($r('app.color.FA_background_color'))
323    .width('100%')
324    .height('100%')
325  }
326}