• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1//@ts-nocheck
2/*
3 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import Log from '../../../../../../../common/src/main/ets/default/Log';
18import WindowManager, { WindowType } from '../../../../../../../common/src/main/ets/default/WindowManager';
19import getSingleInstance from '../../../../../../../common/src/main/ets/default/SingleInstanceHelper';
20import TintStateManager, { TintState, TintStateListener
21} from '../../../../../../../common/src/main/ets/default/TintStateManager';
22import { NavigationBarComponentData, NAVIGATIONBAR_HIDE_EVENT } from '../common/constants';
23import dataShare from '@ohos.data.dataShare';
24import settings from '@ohos.settings';
25import commonEvent from '@ohos.commonEvent';
26import AbilityManager from '../../../../../../../common/src/main/ets/default/abilitymanager/abilityManager';
27import Constants from '../../../../../../../common/src/main/ets/default/Constants';
28
29const TAG = 'NavigationBarViewModel';
30
31const NAVIGATION_BAE_VIEW_MODEL_KEY = 'AppStorage_NavigationBarViewModel';
32
33const NAVIGATION_BAR_COMPONENT_DATA_KEY = 'AppStorage_NavigationBarComponentData';
34
35const RETRY_INTERVAL_MS = 1500;
36
37const MAX_RETRY_TIME = 5;
38
39export default class NavigationBarViewModel {
40  private readonly settingDataKey = 'settings.display.navigationbar_status';
41  private readonly urivar: string;
42  private readonly helper: dataShare.DataShareHelper;
43  private readonly navigationBarStatusDefaultValue = '1';
44  private isDisplay = true;
45  mNavigationBarComponentData: NavigationBarComponentData  = {
46    ...new NavigationBarComponentData()
47  };
48  mUseCount = 0;
49
50  static getInstance(): NavigationBarViewModel {
51    return getSingleInstance(NavigationBarViewModel, NAVIGATION_BAE_VIEW_MODEL_KEY);
52  }
53
54  constructor() {
55    Log.showInfo(TAG, 'constructor');
56    this.mNavigationBarComponentData =
57    AppStorage.SetAndLink(NAVIGATION_BAR_COMPONENT_DATA_KEY, this.mNavigationBarComponentData).get()
58    if (AbilityManager.getContext(AbilityManager.ABILITY_NAME_NAVIGATION_BAR) == null) {
59      Log.showError(TAG, 'AbilityManager.getContext() is null');
60    } else {
61      Log.showInfo(TAG, 'context: ' + AbilityManager.getContext(AbilityManager.ABILITY_NAME_NAVIGATION_BAR));
62    }
63    this.initNavigationBarStatus();
64    this.initHelper(this.dataChangesCallback.bind(this), MAX_RETRY_TIME);
65  }
66
67  private async initHelper(callback: () => void, retryTimes: number): Promise<void> {
68    if (retryTimes < 1) {
69      Log.showInfo(TAG, 'initHelper, retry too many times');
70      return;
71    }
72    Log.showInfo(TAG, 'initHelper in, retry times: %{public}d', MAX_RETRY_TIME - retryTimes + 1);
73    this.urivar = Constants.getUriSync(Constants.KEY_NAVIGATIONBAR_STATUS);
74    try {
75      this.helper = await dataShare.createDataShareHelper(AbilityManager.getContext(AbilityManager.ABILITY_NAME_NAVIGATION_BAR), this.urivar);
76      Log.showInfo(TAG, 'initHelper, helper: ' + this.helper + ', uri: ' + this.urivar);
77      this.helper.on('dataChange', this.urivar, () => {
78        Log.showInfo(TAG, 'onDataChange.');
79        callback();
80      });
81    } catch (err) {
82      Log.showError(TAG, 'initHelper error, code: ' + err?.code + ', message: ' + err?.message);
83      await this.sleep(RETRY_INTERVAL_MS);
84      this.initHelper(this.dataChangesCallback.bind(this), retryTimes - 1);
85    }
86  }
87
88  private sleep (time: number) {
89    return new Promise(resolve => {
90      setTimeout(resolve, time);
91    })
92  }
93
94  install(): void {
95    Log.showDebug(TAG, `install, useCount: ${this.mUseCount}`);
96    if (!this.mUseCount) {
97      TintStateManager.getInstance().registerListener('navigation', this as TintStateListener);
98    }
99    this.mUseCount++;
100  }
101
102  uninstall(): void {
103    Log.showDebug(TAG, `uninstall, useCount: ${this.mUseCount}`);
104    this.mUseCount--;
105    if (this.mUseCount) {
106      TintStateManager.getInstance().unregisterListener('navigation');
107    }
108  }
109
110  getNavigationBarComponentData(): NavigationBarComponentData {
111    Log.showDebug(TAG, 'getNavigationBarComponentData');
112    return this.mNavigationBarComponentData;
113  }
114
115  onTintStateChange(tintState: TintState): void {
116    Log.showDebug(TAG, `onTintStateChange, tintState: ${JSON.stringify(tintState)}`);
117    if (typeof (tintState.isEnable) == 'boolean') {
118      this.setWindowEnable(tintState.isEnable);
119    }
120    if (tintState.backgroundColor) {
121      this.mNavigationBarComponentData.backgroundColor = tintState.backgroundColor;
122    }
123    if (tintState.contentColor) {
124      this.mNavigationBarComponentData.contentColor = tintState.contentColor;
125    }
126    Log.showDebug(TAG, `onTintStateChange, backgroundColor ${this.mNavigationBarComponentData.backgroundColor},
127      contentColor ${this.mNavigationBarComponentData.contentColor}`);
128  }
129
130  setWindowEnable(isEnable: boolean): void {
131    Log.showDebug(TAG, `setWindowEnable, isEnable ${String(isEnable)}`);
132    if (this.mNavigationBarComponentData.isEnable == isEnable) {
133      return;
134    }
135    this.mNavigationBarComponentData.isEnable = isEnable;
136    if (isEnable && this.isDisplay) {
137      WindowManager.showWindow(WindowType.NAVIGATION_BAR).then(() => {
138      }).catch((err) => {
139      });
140    } else {
141      WindowManager.hideWindow(WindowType.NAVIGATION_BAR).then(() => {
142      }).catch((err) => {
143      });
144    }
145  }
146
147  private setValue(value: string): void {
148    let context = AbilityManager.getContext(AbilityManager.ABILITY_NAME_NAVIGATION_BAR);
149    if (context == undefined || context == null) {
150      Log.showInfo(TAG, `setValue: ${context}`);
151      return;
152    }
153    try {
154      settings.setValueSync(context, this.settingDataKey, value);
155    } catch (err) {
156      Log.showError(TAG, `setValue: ${context}, ${JSON.stringify(err)}`);
157    }
158  }
159
160  private getValue(defaultValue?: string): string {
161    let context = AbilityManager.getContext(AbilityManager.ABILITY_NAME_NAVIGATION_BAR);
162    if (context == undefined || context == null) {
163      Log.showInfo(TAG, `getValue: ${context}`);
164      return defaultValue ? defaultValue : this.navigationBarStatusDefaultValue;
165    }
166    try {
167      return settings.getValueSync(
168        context, this.settingDataKey, defaultValue ? defaultValue : this.navigationBarStatusDefaultValue
169      );
170    } catch (err) {
171      Log.showError(TAG, `getValue: ${context}, ${JSON.stringify(err)}`);
172      return defaultValue ? defaultValue : this.navigationBarStatusDefaultValue;
173    }
174  }
175
176  /**
177   * Initialize the NavigationBar status.
178   */
179  initNavigationBarStatus(): void {
180    try {
181      let initValue = this.getValue();
182      Log.showInfo(TAG, `initNavigationBarStatus initValue ${initValue}`);
183      this.windowSwitches(initValue);
184    } catch (e) {
185      Log.showError(TAG, `initNavigationBarStatus error:  ${e.toString()}`);
186    }
187  }
188
189  /**
190   * Get NavigationBar status data.
191   * @return
192   */
193  dataChangesCallback(): void {
194    let getRetValue = this.getValue();
195    Log.showInfo(TAG, `dataChangesCallback initValue ${getRetValue}`);
196    this.windowSwitches(getRetValue);
197  }
198
199  private windowSwitches(navigationBarStatusValue: string): void {
200    this.isDisplay = navigationBarStatusValue == '1' ? true : false;
201    if (!this.isDisplay || !this.mNavigationBarComponentData.isEnable) {
202      //For gesture navigation scenarios
203      //Systemui hides the navigation bar,and then notifies the launcher that it can start moving down the dock bar.
204      WindowManager.hideWindow(WindowType.NAVIGATION_BAR).then(() => {
205        if(!this.isDisplay){
206          commonEvent.publish(NAVIGATIONBAR_HIDE_EVENT, (err) => {
207            if (err.code) {
208              Log.showError(TAG, `${NAVIGATIONBAR_HIDE_EVENT} PublishCallBack err: ${JSON.stringify(err)}`);
209            } else {
210              Log.showInfo(TAG, `${NAVIGATIONBAR_HIDE_EVENT} Publish sucess`);
211            }
212          })
213        }
214      }).catch((err) => {
215        Log.showError(TAG, `${NAVIGATIONBAR_HIDE_EVENT} Publish catch err: ${JSON.stringify(err)}`);
216      });
217    } else {
218      WindowManager.showWindow(WindowType.NAVIGATION_BAR).then(() => {
219      }).catch((err) => {
220      });
221    }
222  }
223}