Debian Codegraph @

closure-library/closure/goog/demos/xpc/xpcdemo.js

raw
1 // Copyright 2007 The Closure Library Authors. All Rights Reserved.
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
15 /**
16 * @fileoverview Contains application code for the XPC demo.
17 * This script is used in both the container page and the iframe.
18 *
19 */
20 goog.provide('xpcdemo');
21
22 goog.require('goog.Uri');
23 goog.require('goog.asserts');
24 goog.require('goog.dom');
25 goog.require('goog.dom.TagName');
26 goog.require('goog.events');
27 goog.require('goog.events.EventType');
28 goog.require('goog.html.SafeHtml');
29 goog.require('goog.log');
30 goog.require('goog.log.Level');
31 goog.require('goog.net.xpc.CfgFields');
32 goog.require('goog.net.xpc.CrossPageChannel');
33
34
35 /**
36 * Global function to kick off initialization in the containing document.
37 */
38 goog.global.initOuter = function() {
39 goog.events.listen(window, 'load', function() { xpcdemo.initOuter(); });
40 };
41
42
43 /**
44 * Global function to kick off initialization in the iframe.
45 */
46 goog.global.initInner = function() {
47 goog.events.listen(window, 'load', function() { xpcdemo.initInner(); });
48 };
49
50
51 /**
52 * Initializes XPC in the containing page.
53 */
54 xpcdemo.initOuter = function() {
55 // Build the configuration object.
56 var cfg = {};
57
58 var ownUri = new goog.Uri(window.location.href);
59 var relayUri = ownUri.resolve(new goog.Uri('relay.html'));
60 var pollUri = ownUri.resolve(new goog.Uri('blank.html'));
61
62 // Determine the peer domain. Uses the value of the URI-parameter
63 // 'peerdomain'. If that parameter is not present, it falls back to
64 // the own domain so that the demo will work out of the box (but
65 // communication will of course not cross domain-boundaries). For
66 // real cross-domain communication, the easiest way is to point two
67 // different host-names to the same webserver and then hit the
68 // following URI:
69 // http://host1.com/path/to/closure/demos/xpc/index.html?peerdomain=host2.com
70 var peerDomain = ownUri.getParameterValue('peerdomain') || ownUri.getDomain();
71
72 cfg[goog.net.xpc.CfgFields.LOCAL_RELAY_URI] = relayUri.toString();
73 cfg[goog.net.xpc.CfgFields.PEER_RELAY_URI] =
74 relayUri.setDomain(peerDomain).toString();
75
76 cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = pollUri.toString();
77 cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] =
78 pollUri.setDomain(peerDomain).toString();
79
80
81 // Force transport to be used if tp-parameter is set.
82 var tp = ownUri.getParameterValue('tp');
83 if (tp) {
84 cfg[goog.net.xpc.CfgFields.TRANSPORT] = parseInt(tp, 10);
85 }
86
87
88 // Construct the URI of the peer page.
89
90 var peerUri =
91 ownUri.resolve(new goog.Uri('inner.html')).setDomain(peerDomain);
92 // Passthrough of verbose and compiled flags.
93 if (goog.isDef(ownUri.getParameterValue('verbose'))) {
94 peerUri.setParameterValue('verbose', '');
95 }
96 if (goog.isDef(ownUri.getParameterValue('compiled'))) {
97 peerUri.setParameterValue('compiled', '');
98 }
99
100 cfg[goog.net.xpc.CfgFields.PEER_URI] = peerUri;
101
102 // Instantiate the channel.
103 xpcdemo.channel = new goog.net.xpc.CrossPageChannel(cfg);
104
105 // Create the peer iframe.
106 xpcdemo.peerIframe = xpcdemo.channel.createPeerIframe(
107 goog.asserts.assert(goog.dom.getElement('iframeContainer')));
108
109 xpcdemo.initCommon_();
110
111 goog.dom.getElement('inactive').style.display = 'none';
112 goog.dom.getElement('active').style.display = '';
113 };
114
115
116 /**
117 * Initialization in the iframe.
118 */
119 xpcdemo.initInner = function() {
120 // Get the channel configuration passed by the containing document.
121 var cfg = JSON.parse(
122 (new goog.Uri(window.location.href)).getParameterValue('xpc') || '');
123
124 xpcdemo.channel = new goog.net.xpc.CrossPageChannel(
125 /** @type {Object} */ (cfg));
126
127 xpcdemo.initCommon_();
128 };
129
130
131 /**
132 * Initializes the demo.
133 * Registers service-handlers and connects the channel.
134 * @private
135 */
136 xpcdemo.initCommon_ = function() {
137 var xpcLogger = goog.log.getLogger(
138 'goog.net.xpc', window.location.href.match(/verbose/) ?
139 goog.log.Level.ALL :
140 goog.log.Level.INFO);
141 goog.log.addHandler(xpcLogger, function(logRecord) {
142 xpcdemo.log('[XPC] ' + logRecord.getMessage());
143 });
144
145 // Register services.
146 // The functions will only receive strings but takes an optional third
147 // parameter that causes the function to receive an Object to cast to the
148 // expected type, but it would be better to change the API or add
149 // overload support to the compiler.
150 xpcdemo.channel.registerService(
151 'log',
152 /** @type {function((!Object|string)): ?} */ (xpcdemo.log));
153 xpcdemo.channel.registerService(
154 'ping',
155 /** @type {function((!Object|string)): ?} */ (xpcdemo.pingHandler_));
156 xpcdemo.channel.registerService(
157 'events',
158 /** @type {function((!Object|string)): ?} */ (xpcdemo.eventsMsgHandler_));
159
160 // Connect the channel.
161 xpcdemo.channel.connect(function() {
162 xpcdemo.channel.send('log', 'Hi from ' + window.location.host);
163 goog.events.listen(
164 goog.dom.getElement('clickfwd'), 'click', xpcdemo.mouseEventHandler_);
165 });
166 };
167
168
169 /**
170 * Kills the peer iframe and the disposes the channel.
171 */
172 xpcdemo.teardown = function() {
173 goog.events.unlisten(
174 goog.dom.getElement('clickfwd'), goog.events.EventType.CLICK,
175 xpcdemo.mouseEventHandler_);
176
177 xpcdemo.channel.dispose();
178 delete xpcdemo.channel;
179
180 goog.dom.removeNode(xpcdemo.peerIframe);
181 xpcdemo.peerIframe = null;
182
183 goog.dom.getElement('inactive').style.display = '';
184 goog.dom.getElement('active').style.display = 'none';
185 };
186
187
188 /**
189 * Logging function. Inserts log-message into element with it id 'console'.
190 * @param {string} msgString The log-message.
191 */
192 xpcdemo.log = function(msgString) {
193 xpcdemo.consoleElm || (xpcdemo.consoleElm = goog.dom.getElement('console'));
194 var msgElm = goog.html.SafeHtml.create(
195 goog.dom.TagName.DIV, {}, goog.html.SafeHtml.htmlEscape(msgString));
196 xpcdemo.consoleElm.insertBefore(msgElm, xpcdemo.consoleElm.firstChild);
197 };
198
199
200 /**
201 * Sends a ping request to the peer.
202 */
203 xpcdemo.ping = function() {
204 // send current time
205 xpcdemo.channel.send('ping', goog.now() + '');
206 };
207
208
209 /**
210 * The handler function for incoming pings (messages sent to the service
211 * called 'ping');
212 * @param {string} payload The message payload.
213 * @private
214 */
215 xpcdemo.pingHandler_ = function(payload) {
216 // is the incoming message a response to a ping we sent?
217 if (payload.charAt(0) == '#') {
218 // calculate roundtrip time and log
219 var dt = goog.now() - parseInt(payload.substring(1), 10);
220 xpcdemo.log('roundtrip: ' + dt + 'ms');
221 } else {
222 // incoming message is a ping initiated from peer
223 // -> prepend with '#' and send back
224 xpcdemo.channel.send('ping', '#' + payload);
225 xpcdemo.log('ping reply sent');
226 }
227 };
228
229
230 /**
231 * Counter for mousemove events.
232 * @type {number}
233 * @private
234 */
235 xpcdemo.mmCount_ = 0;
236
237
238 /**
239 * Holds timestamp when the last mousemove rate has been logged.
240 * @type {number}
241 * @private
242 */
243 xpcdemo.mmLastRateOutput_ = 0;
244
245
246 /**
247 * Start mousemove event forwarding. Registers a listener on the document which
248 * sends them over the channel.
249 */
250 xpcdemo.startMousemoveForwarding = function() {
251 goog.events.listen(
252 document, goog.events.EventType.MOUSEMOVE, xpcdemo.mouseEventHandler_);
253 xpcdemo.mmLastRateOutput_ = goog.now();
254 };
255
256
257 /**
258 * Stop mousemove event forwarding.
259 */
260 xpcdemo.stopMousemoveForwarding = function() {
261 goog.events.unlisten(
262 document, goog.events.EventType.MOUSEMOVE, xpcdemo.mouseEventHandler_);
263 };
264
265
266 /**
267 * Function to be used as handler for mouse-events.
268 * @param {goog.events.BrowserEvent} e The mouse event.
269 * @private
270 */
271 xpcdemo.mouseEventHandler_ = function(e) {
272 xpcdemo.channel.send(
273 'events', [e.type, e.clientX, e.clientY, goog.now()].join(','));
274 };
275
276
277 /**
278 * Handler for the 'events' service.
279 * @param {string} payload The string returned from the xpcdemo.
280 * @private
281 */
282 xpcdemo.eventsMsgHandler_ = function(payload) {
283 var now = goog.now();
284 var args = payload.split(',');
285 var type = args[0];
286 var pageX = args[1];
287 var pageY = args[2];
288 var time = parseInt(args[3], 10);
289
290 var msg = type + ': (' + pageX + ',' + pageY + '), latency: ' + (now - time);
291 xpcdemo.log(msg);
292
293 if (type == goog.events.EventType.MOUSEMOVE) {
294 xpcdemo.mmCount_++;
295 var dt = now - xpcdemo.mmLastRateOutput_;
296 if (dt > 1000) {
297 msg = 'RATE (mousemove/s): ' + (1000 * xpcdemo.mmCount_ / dt);
298 xpcdemo.log(msg);
299 xpcdemo.mmLastRateOutput_ = now;
300 xpcdemo.mmCount_ = 0;
301 }
302 }
303 };
304
305
306 /**
307 * Send multiple messages.
308 * @param {number} n The number of messages to send.
309 */
310 xpcdemo.sendN = function(n) {
311 xpcdemo.count_ || (xpcdemo.count_ = 1);
312
313 for (var i = 0; i < n; i++) {
314 xpcdemo.channel.send('log', '' + xpcdemo.count_++);
315 }
316 };