summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/gpu_internals/browser_bridge.js
blob: 1b1a97c9d67b5922cb02b47071e65710feebf753 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('gpu', function() {
  /**
   * This class provides a 'bridge' for communicating between javascript and
   * the browser.
   * @constructor
   */
  function BrowserBridge() {
    // If we are not running inside WebUI, output chrome.send messages
    // to the console to help with quick-iteration debugging.
    if (chrome.send === undefined && console.log) {
      this.debugMode_ = true;
      chrome.send = function(messageHandler, args) {
        console.log('chrome.send', messageHandler, args);
      };
    } else {
      this.debugMode_ = false;
    }

    this.nextRequestId_ = 0;
    this.pendingCallbacks_ = [];

    // Tell c++ code that we are ready to receive GPU Info.
    chrome.send('browserBridgeInitialized');
  }

  BrowserBridge.prototype = {
    __proto__: cr.EventTarget.prototype,

    /**
     * Returns true if the page is hosted inside Chrome WebUI
     * Helps have behavior conditional to emulate_webui.py
     */
    get debugMode() {
      return this.debugMode_;
    },

    /**
     * Sends a message to the browser with specified args. The
     * browser will reply asynchronously via the provided callback.
     */
    callAsync: function(submessage, args, callback) {
      var requestId = this.nextRequestId_;
      this.nextRequestId_ += 1;
      this.pendingCallbacks_[requestId] = callback;
      if (!args) {
        chrome.send('callAsync', [requestId.toString(), submessage]);
      } else {
        var allArgs = [requestId.toString(), submessage].concat(args);
        chrome.send('callAsync', allArgs);
      }
    },

    /**
     * Called by gpu c++ code when client info is ready.
     */
    onCallAsyncReply: function(requestId, args) {
      if (this.pendingCallbacks_[requestId] === undefined) {
        throw new Error('requestId ' + requestId + ' is not pending');
      }
      var callback = this.pendingCallbacks_[requestId];
      callback(args);
      delete this.pendingCallbacks_[requestId];
    },

    /**
     * Get gpuInfo data.
     */
    get gpuInfo() {
      return this.gpuInfo_;
    },

    /**
     * Called from gpu c++ code when GPU Info is updated.
     */
    onGpuInfoUpdate: function(gpuInfo) {
      this.gpuInfo_ = gpuInfo;
      cr.dispatchSimpleEvent(this, 'gpuInfoUpdate');
    }
  };

  return {
    BrowserBridge: BrowserBridge
  };
});