aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/demos/xpc/xpcdemo.js
blob: db3204aa4b32e9ef07b18576f55ffa6bc62c89ce (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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Contains application code for the XPC demo.
 * This script is used in both the container page and the iframe.
 *
 */

goog.require('goog.Uri');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.json');
goog.require('goog.net.xpc.CrossPageChannel');


/**
 * Namespace for the demo. We don't use goog.provide here because it's not a
 * real module (cannot be required).
 */
var xpcdemo = {};


/**
 * Global function to kick off initialization in the containing document.
 */
goog.global.initOuter = function() {
  goog.events.listen(window, 'load', function() { xpcdemo.initOuter(); });
};


/**
 * Global function to kick off initialization in the iframe.
 */
goog.global.initInner = function() {
  goog.events.listen(window, 'load', function() { xpcdemo.initInner(); });
};


/**
 * Initializes XPC in the containing page.
 */
xpcdemo.initOuter = function() {
  // Build the configuration object.
  var cfg = {};

  var ownUri = new goog.Uri(window.location.href);
  var relayUri = ownUri.resolve(new goog.Uri('relay.html'));
  var pollUri = ownUri.resolve(new goog.Uri('blank.html'));

  // Determine the peer domain. Uses the value of the URI-parameter
  // 'peerdomain'. If that parameter is not present, it falls back to
  // the own domain so that the demo will work out of the box (but
  // communication will of course not cross domain-boundaries).  For
  // real cross-domain communication, the easiest way is to point two
  // different host-names to the same webserver and then hit the
  // following URI:
  // http://host1.com/path/to/closure/demos/xpc/index.html?peerdomain=host2.com
  var peerDomain = ownUri.getParameterValue('peerdomain') || ownUri.getDomain();

  cfg[goog.net.xpc.CfgFields.LOCAL_RELAY_URI] = relayUri.toString();
  cfg[goog.net.xpc.CfgFields.PEER_RELAY_URI] =
      relayUri.setDomain(peerDomain).toString();

  cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = pollUri.toString();
  cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] =
      pollUri.setDomain(peerDomain).toString();


  // Force transport to be used if tp-parameter is set.
  var tp = ownUri.getParameterValue('tp');
  if (tp) {
    cfg[goog.net.xpc.CfgFields.TRANSPORT] = parseInt(tp, 10);
  }


  // Construct the URI of the peer page.

  var peerUri = ownUri.resolve(
      new goog.Uri('inner.html')).setDomain(peerDomain);
  // Passthrough of verbose and compiled flags.
  if (goog.isDef(ownUri.getParameterValue('verbose'))) {
    peerUri.setParameterValue('verbose', '');
  }
  if (goog.isDef(ownUri.getParameterValue('compiled'))) {
    peerUri.setParameterValue('compiled', '');
  }

  cfg[goog.net.xpc.CfgFields.PEER_URI] = peerUri;

  // Instantiate the channel.
  xpcdemo.channel = new goog.net.xpc.CrossPageChannel(cfg);

  // Create the peer iframe.
  xpcdemo.peerIframe = xpcdemo.channel.createPeerIframe(
      goog.dom.getElement('iframeContainer'));

  xpcdemo.initCommon_();

  goog.dom.getElement('inactive').style.display = 'none';
  goog.dom.getElement('active').style.display = '';
};


/**
 * Initialization in the iframe.
 */
xpcdemo.initInner = function() {
  // Get the channel configuration passed by the containing document.
  var cfg = goog.json.parse(
      (new goog.Uri(window.location.href)).getParameterValue('xpc'));

  xpcdemo.channel = new goog.net.xpc.CrossPageChannel(cfg);

  xpcdemo.initCommon_();
};


/**
 * Initializes the demo.
 * Registers service-handlers and connects the channel.
 * @private
 */
xpcdemo.initCommon_ = function() {
  var xpcLogger = goog.debug.Logger.getLogger('goog.net.xpc');
  xpcLogger.addHandler(function(logRecord) {
    xpcdemo.log('[XPC] ' + logRecord.getMessage());
  });
  xpcLogger.setLevel(window.location.href.match(/verbose/) ?
      goog.debug.Logger.Level.ALL : goog.debug.Logger.Level.INFO);

  // Register services.
  xpcdemo.channel.registerService('log', xpcdemo.log);
  xpcdemo.channel.registerService('ping', xpcdemo.pingHandler_);
  xpcdemo.channel.registerService('events', xpcdemo.eventsMsgHandler_);

  // Connect the channel.
  xpcdemo.channel.connect(function() {
    xpcdemo.channel.send('log', 'Hi from ' + window.location.host);
    goog.events.listen(goog.dom.getElement('clickfwd'),
                       'click', xpcdemo.mouseEventHandler_);
  });
};


/**
 * Kills the peer iframe and the disposes the channel.
 */
xpcdemo.teardown = function() {
  goog.events.unlisten(goog.dom.getElement('clickfwd'),
                       goog.events.EventType.CLICK, xpcdemo.mouseEventHandler_);

  xpcdemo.channel.dispose();
  delete xpcdemo.channel;

  goog.dom.removeNode(xpcdemo.peerIframe);
  xpcdemo.peerIframe = null;

  goog.dom.getElement('inactive').style.display = '';
  goog.dom.getElement('active').style.display = 'none';
};


/**
 * Logging function. Inserts log-message into element with it id 'console'.
 * @param {string} msgString The log-message.
 */
xpcdemo.log = function(msgString) {
  xpcdemo.consoleElm || (xpcdemo.consoleElm = goog.dom.getElement('console'));
  var msgElm = goog.dom.createDom('div');
  msgElm.innerHTML = msgString;
  xpcdemo.consoleElm.insertBefore(msgElm, xpcdemo.consoleElm.firstChild);
};


/**
 * Sends a ping request to the peer.
 */
xpcdemo.ping = function() {
  // send current time
  xpcdemo.channel.send('ping', goog.now() + '');
};

/**
 * The handler function for incoming pings (messages sent to the service
 * called 'ping');
 * @param {string} payload The message payload.
 * @private
 */
xpcdemo.pingHandler_ = function(payload) {
  // is the incoming message a response to a ping we sent?
  if (payload.charAt(0) == '#') {
    // calculate roundtrip time and log
    var dt = goog.now() - parseInt(payload.substring(1), 10);
    xpcdemo.log('roundtrip: ' + dt + 'ms');
  } else {
    // incoming message is a ping initiated from peer
    // -> prepend with '#' and send back
    xpcdemo.channel.send('ping', '#' + payload);
    xpcdemo.log('ping reply sent');
  }
};


/**
 * Counter for mousemove events.
 * @type {number}
 * @private
 */
xpcdemo.mmCount_ = 0;


/**
 * Holds timestamp when the last mousemove rate has been logged.
 * @type {number}
 * @private
 */
xpcdemo.mmLastRateOutput_ = 0;


/**
 * Start mousemove event forwarding. Registers a listener on the document which
 * sends them over the channel.
 */
xpcdemo.startMousemoveForwarding = function() {
  goog.events.listen(document, goog.events.EventType.MOUSEMOVE,
                     xpcdemo.mouseEventHandler_);
  xpcdemo.mmLastRateOutput_ = goog.now();
};


/**
 * Stop mousemove event forwarding.
 */
xpcdemo.stopMousemoveForwarding = function() {
  goog.events.unlisten(document, goog.events.EventType.MOUSEMOVE,
                       xpcdemo.mouseEventHandler_);
};


/**
 * Function to be used as handler for mouse-events.
 * @param {goog.events.BrowserEvent} e The mouse event.
 * @private
 */
xpcdemo.mouseEventHandler_ = function(e) {
  xpcdemo.channel.send('events',
                   [e.type, e.clientX, e.clientY, goog.now()].join(','));
};


/**
 * Handler for the 'events' service.
 * @param {string} payload The string returned from the xpcdemo.
 * @private
 */
xpcdemo.eventsMsgHandler_ = function(payload) {
  var now = goog.now();
  var args = payload.split(',');
  var type = args[0];
  var pageX = args[1];
  var pageY = args[2];
  var time = parseInt(args[3], 10);

  var msg = type + ': (' + pageX + ',' + pageY + '), latency: ' + (now - time);
  xpcdemo.log(msg);

  if (type == goog.events.EventType.MOUSEMOVE) {
    xpcdemo.mmCount_++;
    var dt = now - xpcdemo.mmLastRateOutput_;
    if (dt > 1000) {
      msg = 'RATE (mousemove/s): ' + (1000 * xpcdemo.mmCount_ / dt);
      xpcdemo.log(msg);
      xpcdemo.mmLastRateOutput_ = now;
      xpcdemo.mmCount_ = 0;
    }
  }
};


/**
 * Send multiple messages.
 * @param {number} n The number of messages to send.
 */
xpcdemo.sendN = function(n) {
  xpcdemo.count_ || (xpcdemo.count_ = 1);

  for (var i = 0; i < n; i++) {
    xpcdemo.channel.send('log', '' + xpcdemo.count_++);
  }
};