forked from scratchfoundation/scratch-flash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExtensionManager.as
More file actions
543 lines (480 loc) · 17.7 KB
/
ExtensionManager.as
File metadata and controls
543 lines (480 loc) · 17.7 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/*
* Scratch Project Editor and Player
* Copyright (C) 2014 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// ExtensionManager.as
// John Maloney, September 2011
//
// Scratch extension manager. Maintains a dictionary of all extensions in use and manages
// socket-based communications with local and server-based extension helper applications.
package extensions {
import blocks.BlockArg;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.net.*;
import flash.utils.getTimer;
import blocks.Block;
import interpreter.*;
import uiwidgets.DialogBox;
import uiwidgets.IndicatorLight;
import util.*;
public class ExtensionManager {
private var app:Scratch;
private var extensionDict:Object = new Object(); // extension name -> extension record
private var justStartedWait:Boolean;
static public const wedoExt:String = 'LEGO WeDo';
public function ExtensionManager(app:Scratch) {
this.app = app;
clearImportedExtensions();
}
public function extensionActive(extName:String):Boolean {
return extensionDict.hasOwnProperty(extName);
}
public function isInternal(extName:String):Boolean {
return (extensionDict.hasOwnProperty(extName) && extensionDict[extName].isInternal);
}
public function clearImportedExtensions():void {
// Clear imported extensions before loading a new project.
extensionDict = {};
//extensionDict['PicoBoard'] = ScratchExtension.PicoBoard();
extensionDict[wedoExt] = ScratchExtension.WeDo();
}
// -----------------------------
// Block Specifications
//------------------------------
public function specForCmd(op:String):Array {
// Return a command spec array for the given operation or null.
for each (var ext:ScratchExtension in extensionDict) {
var prefix:String = ext.useScratchPrimitives ? '' : (ext.name + '.');
for each (var spec:Array in ext.blockSpecs) {
if ((spec.length > 2) && ((prefix + spec[2]) == op)) {
return [spec[1], spec[0], Specs.extensionsCategory, op, spec.slice(3)];
}
}
}
return null;
}
// -----------------------------
// Enable/disable/reset
//------------------------------
public function setEnabled(extName:String, flag:Boolean):void {
var ext:ScratchExtension = extensionDict[extName];
if (ext && ext.showBlocks != flag) {
ext.showBlocks = flag;
if(app.jsEnabled) {
if(flag && ext.javascriptURL) {
ExternalInterface.call('ScratchExtensions.loadExternalJS', ext.javascriptURL);
ext.showBlocks = false; // Wait for it to load
}
else if(!flag) {
ExternalInterface.call('ScratchExtensions.unregister', extName);
}
}
}
}
public function isEnabled(extName:String):Boolean {
var ext:ScratchExtension = extensionDict[extName];
return ext ? ext.showBlocks : false;
}
public function enabledExtensions():Array {
// Answer an array of enabled extensions, sorted alphabetically.
var result:Array = [];
for each (var ext:ScratchExtension in extensionDict) {
if (ext.showBlocks) result.push(ext);
}
result.sortOn('name');
return result;
}
public function stopButtonPressed():* {
// Send a reset_all command to all active extensions.
for each (var ext:ScratchExtension in enabledExtensions()) {
call(ext.name, 'reset_all', []);
}
}
// -----------------------------
// Importing
//------------------------------
public function importExtension():void {
function fileSelected(event:Event):void {
if (fileList.fileList.length == 0) return;
var file:FileReference = FileReference(fileList.fileList[0]);
file.addEventListener(Event.COMPLETE, fileLoaded);
file.load();
}
function fileLoaded(event:Event):void {
var extObj:Object;
try {
extObj = util.JSON.parse(FileReference(event.target).data.toString());
} catch(e:*) {}
if (!extObj || !('extensionName' in extObj) || !('extensionPort' in extObj)) return;
if (!extObj.blockSpecs) extObj.blockSpecs = [];
loadRawExtension(extObj);
}
var fileList:FileReferenceList = new FileReferenceList();
fileList.addEventListener(Event.SELECT, fileSelected);
try {
// Ignore the exception that happens when you call browse() with the file browser open
fileList.browse();
} catch(e:*) {}
}
public function extensionsToSave():Array {
// Answer an array of extension descriptor objects for imported extensions to be saved with the project.
var result:Array = [];
for each (var ext:ScratchExtension in extensionDict) {
if(!ext.showBlocks) continue;
var descriptor:Object = {};
descriptor.extensionName = ext.name;
descriptor.blockSpecs = ext.blockSpecs;
descriptor.menus = ext.menus;
if(ext.port) descriptor.extensionPort = ext.port;
else if(ext.javascriptURL) descriptor.javascriptURL = ext.javascriptURL;
result.push(descriptor);
}
return result;
}
public function callCompleted(extensionName:String, id:Number):void {
var ext:ScratchExtension = extensionDict[extensionName];
if (ext == null) return; // unknown extension
var index:int = ext.busy.indexOf(id);
if(index > -1) ext.busy.splice(index, 1);
}
public function reporterCompleted(extensionName:String, id:Number, retval:*):void {
var ext:ScratchExtension = extensionDict[extensionName];
if (ext == null) return; // unknown extension
var index:int = ext.busy.indexOf(id);
if(index > -1) {
ext.busy.splice(index, 1);
for(var b:Object in ext.waiting) {
if(ext.waiting[b] == id) {
delete ext.waiting[b];
(b as Block).response = retval;
(b as Block).requestState = 2;
}
}
}
}
public function loadRawExtension(extObj:Object):void {
var ext:ScratchExtension = extensionDict[extObj.extensionName];
if(!ext || (ext.blockSpecs && ext.blockSpecs.length))
ext = new ScratchExtension(extObj.extensionName, extObj.extensionPort);
ext.blockSpecs = extObj.blockSpecs;
if(extObj.url) ext.url = extObj.url;
ext.showBlocks = true;
ext.menus = extObj.menus;
ext.javascriptURL = extObj.javascriptURL;
if (extObj.host) ext.host = extObj.host; // non-local host allowed but not saved in project
extensionDict[extObj.extensionName] = ext;
Scratch.app.translationChanged();
Scratch.app.updatePalette();
// Update the indicator
for (var i:int = 0; i < app.palette.numChildren; i++) {
var indicator:IndicatorLight = app.palette.getChildAt(i) as IndicatorLight;
if (indicator && indicator.target === ext) {
updateIndicator(indicator, indicator.target, true);
break;
}
}
}
public function loadSavedExtensions(savedExtensions:Array):void {
// Reset the system extensions and load the given array of saved extensions.
if (!savedExtensions) return; // no saved extensions
for each (var extObj:Object in savedExtensions) {
if (!('extensionName' in extObj) ||
(!('extensionPort' in extObj) && !('javascriptURL' in extObj)) ||
!('blockSpecs' in extObj)) {
continue;
}
if (extensionDict[extObj.extensionName] &&
extensionDict[extObj.extensionName].isInternal) {
setEnabled(extObj.extensionName, true);
continue; // internal extension overrides one saved in project
}
var ext:ScratchExtension = new ScratchExtension(extObj.extensionName, extObj.extensionPort || 0);
ext.blockSpecs = extObj.blockSpecs;
ext.showBlocks = true;
ext.menus = extObj.menus;
if(extObj.javascriptURL) ext.javascriptURL = extObj.javascriptURL;
extensionDict[extObj.extensionName] = ext;
}
Scratch.app.updatePalette();
}
// -----------------------------
// Menu Support
//------------------------------
public function menuItemsFor(op:String, menuName:String):Array {
// Return a list of menu items for the given menu of the extension associated with op or null.
var i:int = op.indexOf('.');
if (i < 0) return null;
var ext:ScratchExtension = extensionDict[op.slice(0, i)];
if (ext == null) return null; // unknown extension
return ext.menus[menuName];
}
// -----------------------------
// Status Indicator
//------------------------------
public function updateIndicator(indicator:IndicatorLight, ext:ScratchExtension, firstTime:Boolean = false):void {
if(ext.port > 0) {
var msecsSinceLastResponse:uint = getTimer() - ext.lastPollResponseTime;
if (msecsSinceLastResponse > 500) indicator.setColorAndMsg(0xE00000, 'Cannot find helper app');
else if (ext.problem != '') indicator.setColorAndMsg(0xE0E000, ext.problem);
else indicator.setColorAndMsg(0x00C000, 'Okay');
}
else if(app.jsEnabled) {
var retval:Object = ExternalInterface.call('ScratchExtensions.getStatus', ext.name);
if(!retval) retval = {status: 0, msg: 'Cannot communicate with extension.'};
var color:uint;
if(retval.status == 2) color = 0x00C000;
else if(retval.status == 1) color = 0xE0E000;
else {
color = 0xE00000;
if(firstTime) {
Scratch.app.showTip('extensions');
// DialogBox.notify('Extension Problem', 'It looks like the '+ext.name+' is not working properly.' +
// 'Please read the extensions help in the tips window.', Scratch.app.stage);
DialogBox.notify('Extension Problem', 'See the Tips window (on the right) to install the plug-in and get the extension working.', Scratch.app.stage);
}
}
indicator.setColorAndMsg(color, retval.msg);
}
}
// -----------------------------
// Execution
//------------------------------
public function primExtensionOp(b:Block):* {
var i:int = b.op.indexOf('.');
var extName:String = b.op.slice(0, i);
var ext:ScratchExtension = extensionDict[extName];
if (ext == null) return 0; // unknown extension
var primOrVarName:String = b.op.slice(i + 1);
var args:Array = [];
for (i = 0; i < b.args.length; i++) {
args.push(app.interp.arg(b, i));
}
var value:*;
if (b.isReporter) {
if(b.isRequester) {
if(b.requestState == 2) {
b.requestState = 0;
return b.response;
}
else if(b.requestState == 0) {
request(extName, primOrVarName, args, b);
}
// Returns null if we just made a request or we're still waiting
return null;
}
else {
var sensorName:String = primOrVarName;
if(ext.port > 0) { // we were checking ext.isInternal before, should we?
for each (var a:* in args) sensorName += '/' + a; // append menu args
value = ext.stateVars[sensorName];
}
else if(Scratch.app.jsEnabled) {
// Javascript
value = ExternalInterface.call('ScratchExtensions.getReporter', ext.name, sensorName, args);
}
if (value == undefined) value = 0; // default to zero if missing
if ('b' == b.type) value = ('true' == value); // coerce value to a boolean
return value;
}
} else {
if ('w' == b.type) {
var activeThread:Thread = app.interp.activeThread;
if (activeThread.firstTime) {
var id:int = ++ext.nextID; // assign a unique ID for this call
ext.busy.push(id);
activeThread.tmp = id;
activeThread.firstTime = false;
app.interp.doYield();
justStartedWait = true;
if(ext.port == 0) {
if(app.jsEnabled)
ExternalInterface.call('ScratchExtensions.runAsync', ext.name, primOrVarName, args, id);
else
ext.busy.pop();
return;
}
args.unshift(id); // pass the ID as the first argument
} else {
if (ext.busy.indexOf(activeThread.tmp) > -1) {
app.interp.doYield();
} else {
activeThread.tmp = 0;
activeThread.firstTime = true;
}
return;
}
}
call(extName, primOrVarName, args);
}
}
public function call(extensionName:String, op:String, args:Array):void {
var ext:ScratchExtension = extensionDict[extensionName];
if (ext == null) return; // unknown extension
if (ext.port > 0) {
var activeThread:Thread = app.interp.activeThread;
if(activeThread && op != 'reset_all') {
if(activeThread.firstTime) {
httpCall(ext, op, args);
activeThread.firstTime = false;
app.interp.doYield();
}
else {
activeThread.firstTime = true;
}
}
else
httpCall(ext, op, args);
} else {
if(op == 'reset_all') op = 'resetAll';
// call a JavaScript extension function with the given arguments
if(Scratch.app.jsEnabled) ExternalInterface.call('ScratchExtensions.runCommand', ext.name, op, args);
app.interp.redraw(); // make sure interpreter doesn't do too many extension calls in one cycle
}
}
public function request(extensionName:String, op:String, args:Array, b:Block):void {
var ext:ScratchExtension = extensionDict[extensionName];
if (ext == null) {
// unknown extension, skip the block
b.requestState = 2;
return;
}
if (ext.port > 0) {
httpRequest(ext, op, args, b);
} else if(Scratch.app.jsEnabled) {
// call a JavaScript extension function with the given arguments
b.requestState = 1;
++ext.nextID;
ext.busy.push(ext.nextID);
ext.waiting[b] = ext.nextID;
ExternalInterface.call('ScratchExtensions.getReporterAsync', ext.name, op, args, ext.nextID);
}
}
private function httpRequest(ext:ScratchExtension, op:String, args:Array, b:Block):void {
function responseHandler(e:Event):void {
if(e.type == Event.COMPLETE)
b.response = loader.data;
else
b.response = '';
b.requestState = 2;
b.requestLoader = null;
}
var loader:URLLoader = new URLLoader();
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, responseHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, responseHandler);
loader.addEventListener(Event.COMPLETE, responseHandler);
b.requestState = 1;
b.requestLoader = loader;
var url:String = 'http://' + ext.host + ':' + ext.port + '/' + op;
for each (var arg:* in args) {
url += '/' + ((arg is String) ? escape(arg) : arg);
}
loader.load(new URLRequest(url));
}
private function httpCall(ext:ScratchExtension, op:String, args:Array):void {
function errorHandler(e:Event):void { } // ignore errors
var url:String = 'http://' + ext.host + ':' + ext.port + '/' + op;
for each (var arg:* in args) {
url += '/' + ((arg is String) ? escape(arg) : arg);
}
var loader:URLLoader = new URLLoader();
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.load(new URLRequest(url));
}
public function getStateVar(extensionName:String, varName:String, defaultValue:*):* {
var ext:ScratchExtension = extensionDict[extensionName];
if (ext == null) return defaultValue; // unknown extension
var value:* = ext.stateVars[varName];
return (value == undefined) ? defaultValue : value;
}
// -----------------------------
// Polling
//------------------------------
public function step():void {
// Poll all extensions.
for each (var ext:ScratchExtension in extensionDict) {
if (ext.showBlocks) {
if (!ext.isInternal && ext.port > 0) {
if (ext.blockSpecs.length == 0) httpGetSpecs(ext);
httpPoll(ext);
}
}
}
}
private function httpGetSpecs(ext:ScratchExtension):void {
// Fetch the block specs (and optional menu specs) from the helper app.
function completeHandler(e:Event):void {
var specsObj:Object;
try {
specsObj = util.JSON.parse(loader.data);
} catch(e:*) {}
if (!specsObj) return;
// use the block specs and (optionally) menu returned by the helper app
if (specsObj.blockSpecs) ext.blockSpecs = specsObj.blockSpecs;
if (specsObj.menus) ext.menus = specsObj.menus;
}
function errorHandler(e:Event):void { } // ignore errors
var url:String = 'http://' + ext.host + ':' + ext.port + '/get_specs';
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.load(new URLRequest(url));
}
private function httpPoll(ext:ScratchExtension):void {
// Poll via HTTP.
function completeHandler(e:Event):void {
processPollResponse(ext, loader.data);
}
function errorHandler(e:Event):void { } // ignore errors
var url:String = 'http://' + ext.host + ':' + ext.port + '/poll';
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.load(new URLRequest(url));
}
private function processPollResponse(ext:ScratchExtension, response:String):void {
if (response == null) return;
ext.lastPollResponseTime = getTimer();
ext.problem = '';
// clear the busy list unless we just started a command that waits
if (justStartedWait) justStartedWait = false;
else ext.busy = [];
var lines:Array = response.split('\n');
for each (var line:String in lines) {
var tokens:Array = ReadStream.tokenize(line);
if (tokens.length > 1) {
var key:String = tokens[0];
if (key.indexOf('_') == 0) { // internal status update or response
if ('_busy' == key) {
for (var i:int = 1; i < tokens.length; i++) {
var id:int = parseInt(tokens[i]);
if (ext.busy.indexOf(id) == -1) ext.busy.push(id);
}
}
if ('_problem' == key) ext.problem = line.slice(9);
} else { // sensor value
var val:String = tokens[1];
var n:Number = Number(val);
ext.stateVars[key] = isNaN(n) ? val : n;
}
}
}
}
}}