• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 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 { common } from '@kit.AbilityKit';
17import CounterLock from './CounterLock';
18import { HiLog } from './HiLog';
19import Singleton from './Singleton';
20import { UIContext } from '@kit.ArkUI';
21
22const TAG: string = 'UIContextUtil';
23
24export default class UIContextUtil {
25  private static singletonInstance: Singleton<UIContextUtil> = new Singleton<UIContextUtil>(() => new UIContextUtil());
26  private static uiContext: UIContext | undefined = undefined;
27  private static locker: CounterLock = new CounterLock();
28
29  public static getInstance(): UIContextUtil {
30    return UIContextUtil.singletonInstance.getInstance();
31  }
32
33  public getUIContext(
34    context: common.UIAbilityContext | common.UIExtensionContext | common.ServiceExtensionContext
35  ): UIContext | undefined {
36    HiLog.info(TAG, 'Getting UIContext.');
37    if (!UIContextUtil.uiContext) {
38      UIContextUtil.locker.acquire();
39      try {
40        if (!UIContextUtil.uiContext) {
41          HiLog.info(TAG, 'UIContext is undefined. Creating UIContext without window.');
42          UIContextUtil.uiContext = UIContext.createUIContextWithoutWindow(context) as UIContext;
43        }
44      } catch(error) {
45        HiLog.wrapError(TAG, error, 'Failed to create UIContext without window');
46      } finally {
47        UIContextUtil.locker.release();
48      }
49    }
50    return UIContextUtil.uiContext;
51  }
52}