summaryrefslogtreecommitdiffstats
path: root/remoting/webapp/app_remoting/js/app_connected_view.js
blob: 0ba7b577d202e99441d286204370caae2ccd1fd2 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright 2015 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.

/**
 * @fileoverview
 * Implements a basic UX control for a connected app remoting session.
 */

/** @suppress {duplicate} */
var remoting = remoting || {};

(function() {

'use strict';

/**
 * Interval to test the connection speed.
 * @const {number}
 */
var CONNECTION_SPEED_PING_INTERVAL_MS = 10 * 1000;

/**
 * Interval to refresh the google drive access token.
 * @const {number}
 */
var DRIVE_ACCESS_TOKEN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;

/**
 * @param {HTMLElement} containerElement
 * @param {remoting.ConnectionInfo} connectionInfo
 *
 * @constructor
 * @implements {base.Disposable}
 * @implements {remoting.ProtocolExtension}
 */
remoting.AppConnectedView = function(containerElement, connectionInfo) {
  /** @private */
  this.plugin_ = connectionInfo.plugin();

  /** @private */
  this.host_ = connectionInfo.host();

  /** @private {remoting.ContextMenuAdapter} */
  var menuAdapter = new remoting.ContextMenuChrome();

  // Initialize the context menus.
  if (!remoting.platformIsChromeOS()) {
    menuAdapter =
        new remoting.ContextMenuDom(document.getElementById('context-menu'));
  }

  this.contextMenu_ =
      new remoting.ApplicationContextMenu(menuAdapter, this.plugin_);
  this.contextMenu_.setHostId(connectionInfo.host().hostId);

  /** @private */
  this.keyboardLayoutsMenu_ = new remoting.KeyboardLayoutsMenu(menuAdapter);

  /** @private */
  this.windowActivationMenu_ = new remoting.WindowActivationMenu(menuAdapter);

  var baseView = new remoting.ConnectedView(
      this.plugin_, containerElement,
      containerElement.querySelector('.mouse-cursor-overlay'));

  var windowShapeHook = new base.EventHook(
      this.plugin_.hostDesktop(),
      remoting.HostDesktop.Events.shapeChanged,
      remoting.windowShape.setDesktopRects.bind(remoting.windowShape));

  var desktopSizeHook = new base.EventHook(
      this.plugin_.hostDesktop(),
      remoting.HostDesktop.Events.sizeChanged,
      this.onDesktopSizeChanged_.bind(this));

  /** @private */
  this.disposables_ = new base.Disposables(
      baseView, windowShapeHook, desktopSizeHook, this.contextMenu_);

  /** @private */
  this.supportsGoogleDrive_ = this.plugin_.hasCapability(
      remoting.ClientSession.Capability.GOOGLE_DRIVE);

  this.resizeHostToClientArea_();
  this.plugin_.extensions().register(this);
};

/**
 * @return {void} Nothing.
 */
remoting.AppConnectedView.prototype.dispose = function() {
  this.windowActivationMenu_.setExtensionMessageSender(base.doNothing);
  this.keyboardLayoutsMenu_.setExtensionMessageSender(base.doNothing);
  base.dispose(this.disposables_);
};

/**
 * Resize the host to the dimensions of the current window.
 * @private
 */
remoting.AppConnectedView.prototype.resizeHostToClientArea_ = function() {
  var hostDesktop = this.plugin_.hostDesktop();
  var desktopScale = this.host_.options.desktopScale;
  hostDesktop.resize(window.innerWidth * desktopScale,
                     window.innerHeight * desktopScale,
                     window.devicePixelRatio);
};

/**
 * Adjust the size of the plugin according to the dimensions of the hostDesktop.
 *
 * @param {{width:number, height:number, xDpi:number, yDpi:number}} hostDesktop
 * @private
 */
remoting.AppConnectedView.prototype.onDesktopSizeChanged_ =
    function(hostDesktop) {
  // The first desktop size change indicates that we can close the loading
  // window.
  remoting.LoadingWindow.close();

  var hostSize = { width: hostDesktop.width, height: hostDesktop.height };
  var hostDpi = { x: hostDesktop.xDpi, y: hostDesktop.yDpi };
  var clientArea = { width: window.innerWidth, height: window.innerHeight };
  var newSize = remoting.Viewport.choosePluginSize(
      clientArea, window.devicePixelRatio,
      hostSize, hostDpi, this.host_.options.desktopScale,
      true /* fullscreen */ , true /* shrinkToFit */ );

  this.plugin_.element().style.width = newSize.width + 'px';
  this.plugin_.element().style.height = newSize.height + 'px';
};

/**
 * @return {Array<string>}
 * @override {remoting.ProtocolExtension}
 */
remoting.AppConnectedView.prototype.getExtensionTypes = function() {
  return ['openURL', 'onWindowRemoved', 'onWindowAdded',
          'onAllWindowsMinimized', 'setKeyboardLayouts', 'pingResponse'];
};

/**
 * @param {function(string,string)} sendMessageToHost Callback to send a message
 *     to the host.
 * @override {remoting.ProtocolExtension}
 */
remoting.AppConnectedView.prototype.startExtension = function(
    sendMessageToHost) {
  this.windowActivationMenu_.setExtensionMessageSender(sendMessageToHost);
  this.keyboardLayoutsMenu_.setExtensionMessageSender(sendMessageToHost);

  remoting.identity.getUserInfo().then(function(userInfo) {
    sendMessageToHost('setUserDisplayInfo',
                      JSON.stringify({fullName: userInfo.name}));
  });

  var onRestoreHook = new base.ChromeEventHook(
      chrome.app.window.current().onRestored, function() {
        sendMessageToHost('restoreAllWindows', '');
      });

  var pingTimer = new base.RepeatingTimer(function() {
    var message = {timestamp: new Date().getTime()};
    sendMessageToHost('pingRequest', JSON.stringify(message));
  }, CONNECTION_SPEED_PING_INTERVAL_MS);

  this.disposables_.add(onRestoreHook, pingTimer);

  if (this.supportsGoogleDrive_) {
    this.disposables_.add(new base.RepeatingTimer(
        this.sendGoogleDriveAccessToken_.bind(this, sendMessageToHost),
        DRIVE_ACCESS_TOKEN_REFRESH_INTERVAL_MS, true));
  }
};

/**
 * @param {string} type The message type.
 * @param {Object} message The parsed extension message data.
 * @override {remoting.ProtocolExtension}
 */
remoting.AppConnectedView.prototype.onExtensionMessage =
    function(type, message) {
  switch (type) {
    case 'openURL':
      // URL requests from the hosted app are untrusted, so disallow anything
      // other than HTTP or HTTPS.
      var url = base.getStringAttr(message, 'url');
      if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
        console.error('Bad URL: ' + url);
      } else {
        window.open(url);
      }
      return true;

    case 'onWindowRemoved':
      var id = base.getNumberAttr(message, 'id');
      this.windowActivationMenu_.remove(id);
      return true;

    case 'onWindowAdded':
      var id = base.getNumberAttr(message, 'id');
      var title = base.getStringAttr(message, 'title');
      this.windowActivationMenu_.add(id, title);
      return true;

    case 'onAllWindowsMinimized':
      chrome.app.window.current().minimize();
      return true;

    case 'setKeyboardLayouts':
      var supportedLayouts = base.getArrayAttr(message, 'supportedLayouts');
      var currentLayout = base.getStringAttr(message, 'currentLayout');
      console.log('Current host keyboard layout: ' + currentLayout);
      console.log('Supported host keyboard layouts: ' + supportedLayouts);
      this.keyboardLayoutsMenu_.setLayouts(supportedLayouts, currentLayout);
      return true;

    case 'pingResponse':
      var then = base.getNumberAttr(message, 'timestamp');
      var now = new Date().getTime();
      this.contextMenu_.updateConnectionRTT(now - then);
      return true;
  }

  return false;
};

/**
 * Timer callback to send the access token to the host.
 * @param {function(string, string)} sendExtensionMessage
 * @private
 */
remoting.AppConnectedView.prototype.sendGoogleDriveAccessToken_ =
    function(sendExtensionMessage) {
  var googleDriveScopes = [
    'https://docs.google.com/feeds/',
    'https://www.googleapis.com/auth/drive'
  ];
  remoting.identity.getNewToken(googleDriveScopes).then(
    function(/** string */ token){
      base.debug.assert(token !== previousToken_);
      previousToken_ = token;
      sendExtensionMessage('accessToken', token);
  }).catch(remoting.Error.handler(function(/** remoting.Error */ error) {
    console.log('Failed to refresh access token: ' + error.toString());
  }));
};

// The access token last received from getNewToken. Saved to ensure that we
// get a fresh token each time.
var previousToken_ = '';

})();