• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2019 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 {binaryDecode} from '../base/string_utils';
16import {ChromeTracingController} from './chrome_tracing_controller';
17
18let chromeTraceController: ChromeTracingController|undefined = undefined;
19
20enableOnlyOnPerfettoHost();
21
22// Listen for messages from the perfetto ui.
23if (window.chrome) {
24  chrome.runtime.onConnectExternal.addListener(port => {
25    chromeTraceController = new ChromeTracingController(port);
26    port.onMessage.addListener(onUIMessage);
27  });
28}
29
30function onUIMessage(
31    message: {method: string, requestData: string}, port: chrome.runtime.Port) {
32  if (message.method === 'ExtensionVersion') {
33    port.postMessage({version: chrome.runtime.getManifest().version});
34    return;
35  }
36  console.assert(chromeTraceController !== undefined);
37  if (!chromeTraceController) return;
38  // ChromeExtensionConsumerPort sends the request data as string because
39  // chrome.runtime.port doesn't support ArrayBuffers.
40  const requestDataArray: Uint8Array = message.requestData ?
41      binaryDecode(message.requestData) :
42      new Uint8Array();
43  chromeTraceController.handleCommand(message.method, requestDataArray);
44}
45
46function enableOnlyOnPerfettoHost() {
47  function enableOnHostWithSuffix(suffix: string) {
48    return {
49      conditions: [new chrome.declarativeContent.PageStateMatcher({
50        pageUrl: {hostSuffix: suffix},
51      })],
52      actions: [new chrome.declarativeContent.ShowPageAction()]
53    };
54  }
55  chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {
56    chrome.declarativeContent.onPageChanged.addRules([
57      enableOnHostWithSuffix('localhost'),
58      enableOnHostWithSuffix('.perfetto.dev'),
59    ]);
60  });
61}
62