• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 */
15import deviceManager from '@ohos.distributedDeviceManager';
16import Logger from '../model/Logger'
17import { DeviceDialog } from '../common/DeviceDialog'
18import { RemoteDeviceModel, BUNDLE_NAME } from '../model/RemoteDeviceModel'
19import common from '@ohos.app.ability.common'
20import Want from '@ohos.app.ability.Want';
21
22const TAG: string = 'TitleBar'
23const DATA_CHANGE: string = 'dataChange'
24const EXIT: string = 'exit'
25const DEVICE_DISCOVERY_RANGE: number = 1000
26
27@Component
28export struct TitleBarComponent {
29  @Prop isLand: boolean | null = null
30  @State selectedIndex: number | undefined = 0
31  @StorageLink('deviceList') deviceList: Array<deviceManager.DeviceBasicInfo> = []
32  @Link isDistributed: boolean
33  private isShow: boolean = false
34  private startAbilityCallBack: (key: string) => void = () => {
35  }
36  private dialogController: CustomDialogController | null = null
37  private remoteDeviceModel: RemoteDeviceModel = new RemoteDeviceModel()
38  onSelectedIndexChange = async (index: number | undefined) => {
39    Logger.info(TAG, `selectedIndexChange`)
40    this.selectedIndex = index
41    if (this.selectedIndex === 0) {
42      Logger.info(TAG, `stop ability`)
43      await this.startAbilityCallBack(EXIT)
44      this.isDistributed = false
45      this.deviceList = []
46      if (this.dialogController !== null) {
47        this.dialogController.close()
48      }
49      return
50    }
51    this.selectDevice()
52  }
53
54  aboutToAppear() {
55    AppStorage.setOrCreate('deviceList', this.deviceList)
56  }
57
58  clearSelectState() {
59    this.deviceList = []
60    if (this.dialogController !== null) {
61      this.dialogController.close()
62    }
63    Logger.info(TAG, `cancelDialog`)
64    if (this.remoteDeviceModel === undefined) {
65      return
66    }
67    this.remoteDeviceModel.unregisterDeviceListCallback()
68  }
69
70  selectDevice() {
71    Logger.info(TAG, `start ability ......`)
72    this.isDistributed = true
73    if (this.selectedIndex !== undefined && (this.remoteDeviceModel === null || this.remoteDeviceModel.discoverList.length <= 0)) {
74      Logger.info(TAG, `continue unauthed device: ${JSON.stringify(this.deviceList)}`)
75      this.startAbility(this.deviceList[this.selectedIndex].networkId)
76      this.clearSelectState()
77      return
78    }
79    Logger.info(TAG, `start ability1, needAuth:`)
80    if (this.selectedIndex !== undefined) {
81      this.remoteDeviceModel.authenticateDevice(this.deviceList[this.selectedIndex], () => {
82        Logger.info(TAG, `auth and online finished`);
83        if (this.remoteDeviceModel !== null && this.remoteDeviceModel.deviceList !== null && this.selectedIndex !== undefined) {
84          for (let i = 0; i < this.remoteDeviceModel.deviceList!.length; i++) {
85            if (this.remoteDeviceModel.deviceList![i].deviceName === this.deviceList[this.selectedIndex].deviceName) {
86              this.startAbility(this.remoteDeviceModel.deviceList![i].networkId);
87            }
88          }
89        }
90      })
91    }
92    Logger.info(TAG, `start ability2 ......`)
93    this.clearSelectState()
94  }
95
96  async startAbility(deviceId: string | undefined) {
97    Logger.debug(TAG, `startAbility deviceId: ${deviceId}`)
98    let context = getContext(this) as common.UIAbilityContext
99    let want: Want = {
100      bundleName: BUNDLE_NAME,
101      abilityName: 'MainAbility',
102      deviceId: deviceId,
103      parameters: {
104        isRemote: 'isRemote'
105      }
106    }
107    context.startAbility(want).then((data) => {
108      Logger.info(TAG, `start ability finished: ${JSON.stringify(data)}`)
109      this.startAbilityCallBack(DATA_CHANGE)
110    })
111  }
112
113  showDiainfo() {
114    this.deviceList = []
115    // 注册监听回调,发现设备或查找到已认证设备会弹窗显示
116    this.remoteDeviceModel.registerDeviceListCallback(() => {
117      this.deviceList = []
118      Logger.info(TAG, `registerDeviceListCallback, callback entered`)
119      this.deviceList.push({
120        deviceId: '0',
121        deviceName: getContext(this).resourceManager.getStringSync($r('app.string.localhost').id),
122        deviceType: '0',
123        networkId: ''
124      })
125      let deviceTempList = this.remoteDeviceModel.discoverList.length > 0 ? this.remoteDeviceModel.discoverList : this.remoteDeviceModel.deviceList;
126      if (deviceTempList !== null) {
127        for (let i = 0; i < deviceTempList!.length; i++) {
128          Logger.debug(TAG, `device ${i}/${deviceTempList!.length} deviceId= ${deviceTempList![i].deviceId},
129        deviceName= ${deviceTempList![i].deviceName}, deviceType= ${deviceTempList![i].deviceType}`);
130          if (deviceTempList !== null) {
131            this.deviceList.push({
132              deviceId: deviceTempList![i].deviceId,
133              deviceName: deviceTempList![i].deviceName,
134              deviceType: deviceTempList![i].deviceType,
135              networkId: deviceTempList![i].networkId,
136            })
137            AppStorage.set('deviceList', this.deviceList)
138          }
139        }
140      }
141    })
142    if (this.dialogController === null) {
143      this.dialogController = new CustomDialogController({
144        builder: DeviceDialog({
145          selectedIndex: this.selectedIndex,
146          onSelectedIndexChange: this.onSelectedIndexChange
147        }),
148        cancel: () => {
149          this.clearSelectState()
150        },
151        autoCancel: true,
152        alignment: this.isLand ? DialogAlignment.Center : DialogAlignment.Bottom,
153        customStyle: true
154      })
155    }
156    if (this.dialogController !== null) {
157      this.dialogController.open()
158    }
159  }
160
161  build() {
162    Row() {
163      Image($r('app.media.ic_back'))
164        .height('60%')
165        .margin({ left: '5%' })
166        .width('50px')
167        .objectFit(ImageFit.Contain)
168        .onClick(async () => {
169          let context = getContext(this) as common.UIAbilityContext
170          context.terminateSelf()
171        })
172      Text($r('app.string.distributed_calculator'))
173        .height('60%')
174        .fontSize('28px')
175        .margin({ left: 12 })
176      Blank().layoutWeight(1)
177      if (!this.isShow) {
178        Image($r("app.media.ic_hop_normal1"))
179          .id('selectDevice')
180          .margin({ right: 32 })
181          .width('9%')
182          .margin({ right: '12%' })
183          .objectFit(ImageFit.Contain)
184          .onClick(() => {
185            this.showDiainfo()
186          })
187      }
188    }
189    .width('100%')
190    .height(this.isLand ? '10%' : '6%')
191    .constraintSize({ minHeight: 50 })
192    .alignItems(VerticalAlign.Center)
193  }
194}