• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2022 The Android Open Source Project
2//
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 {RecordingError} from '../recording_error_handling';
16import {
17  OnTargetChangeCallback,
18  RecordingTargetV2,
19  TargetFactory,
20} from '../recording_interfaces_v2';
21import {isLinux, isMacOs} from '../recording_utils';
22import {targetFactoryRegistry} from '../target_factory_registry';
23import {HostOsTarget} from '../targets/host_os_target';
24
25export const HOST_OS_TARGET_FACTORY = 'HostOsTargetFactory';
26
27export class HostOsTargetFactory implements TargetFactory {
28  readonly kind = HOST_OS_TARGET_FACTORY;
29  private target?: HostOsTarget;
30  private onTargetChange: OnTargetChangeCallback = () => {};
31
32  connectNewTarget(): Promise<RecordingTargetV2> {
33    throw new RecordingError(
34        'Can not create a new Host OS target.' +
35        'The Host OS target is created at factory initialisation.');
36  }
37
38  getName(): string {
39    return 'HostOs';
40  }
41
42  listRecordingProblems(): string[] {
43    return [];
44  }
45
46  listTargets(): RecordingTargetV2[] {
47    if (this.target) {
48      return [this.target];
49    }
50    return [];
51  }
52
53  tryEstablishWebsocket(websocketUrl: string) {
54    if (this.target) {
55      if (this.target.getUrl() === websocketUrl) {
56        return;
57      } else {
58        this.target.disconnect();
59      }
60    }
61    this.target = new HostOsTarget(
62        websocketUrl, this.maybeClearTarget.bind(this), this.onTargetChange);
63    this.onTargetChange();
64  }
65
66  maybeClearTarget(target: HostOsTarget): void {
67    if (this.target === target) {
68      this.target = undefined;
69      this.onTargetChange();
70    }
71  }
72
73  setOnTargetChange(onTargetChange: OnTargetChangeCallback): void {
74    this.onTargetChange = onTargetChange;
75  }
76}
77
78// We instantiate the host target factory only on Mac and Linux.
79if (isMacOs(navigator.userAgent) || isLinux(navigator.userAgent)) {
80  targetFactoryRegistry.register(new HostOsTargetFactory());
81}
82