-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathactivity.js
More file actions
1847 lines (1597 loc) · 72.2 KB
/
activity.js
File metadata and controls
1847 lines (1597 loc) · 72.2 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014,2015 Walter Bender
// Modified by Yash Khandelwal, GSoC'15
//
// 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 3 of the License, or
// (at your option) any later version.
//
// You should have received a copy of the GNU General Public License
// along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
//
// Note: This code is inspired by the Python Turtle Blocks project
// (https://github.com/walterbender/turtleart), but implemented from
// scratch. -- Walter Bender, October 2014.
var lang = document.webL10n.getLanguage();
if (lang.indexOf("-") != -1) {
lang = lang.slice(0, lang.indexOf("-"));
document.webL10n.setLanguage(lang);
}
define(function(require) {
require('activity/platformstyle');
require('easeljs');
require('tweenjs');
require('preloadjs');
require('howler');
require('mespeak');
require('Chart');
require('activity/utils');
require('activity/artwork');
require('activity/munsell');
require('activity/trash');
require('activity/turtle');
require('activity/palette');
require('activity/protoblocks');
require('activity/blocks');
require('activity/block');
require('activity/logo');
require('activity/clearbox');
require('activity/utilitybox');
require('activity/samplesviewer');
require('activity/basicblocks');
require('activity/blockfactory');
require('activity/analytics');
require('prefixfree.min');
require('activity/matrix');
require('activity/assemble');
require('activity/musicnotation');
// Manipulate the DOM only when it is ready.
require(['domReady!'], function(doc) {
window.scroll(0, 0);
//document.getElementById("solfamenu").style.visibility = "hidden";
try {
meSpeak.loadConfig('lib/mespeak_config.json');
meSpeak.loadVoice('lib/voices/en/en.json');
} catch (e) {
console.log(e);
}
var canvas = docById('myCanvas');
var queue = new createjs.LoadQueue(false);
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = true;
} else {
alert('The File APIs are not fully supported in this browser.');
var files = false;
}
// Set up a file chooser for the doOpen function.
var fileChooser = docById('myOpenFile');
// Set up a file chooser for the doOpenPlugin function.
var pluginChooser = docById('myOpenPlugin');
// The file chooser for all files.
var allFilesChooser = docById('myOpenAll')
// Are we running off of a server?
var server = true;
var scale = 1;
var stage;
var turtles;
var palettes;
var blocks;
var logo;
var clearBox;
var utilityBox;
var thumbnails;
var buttonsVisible = true;
var headerContainer = null;
var toolbarButtonsVisible = true;
var menuButtonsVisible = false;
var menuContainer = null;
var workspaceContainer = null;
var currentKey = '';
var currentKeyCode = 0;
var lastKeyCode = 0;
var pasteContainer = null;
var chartBitmap = null;
var workspace = false;
// Calculate the palette colors.
for (var p in PALETTECOLORS) {
PALETTEFILLCOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1], PALETTECOLORS[p][2]);
PALETTESTROKECOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1] - 30, PALETTECOLORS[p][2]);
PALETTEHIGHLIGHTCOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1] + 10, PALETTECOLORS[p][2]);
HIGHLIGHTSTROKECOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1] - 50, PALETTECOLORS[p][2]);
// console.log(p + ' ' + PALETTEFILLCOLORS[p] + ' ' + PALETTESTROKECOLORS[p] + ' ' + PALETTEHIGHLIGHTCOLORS[p] + ' ' + HIGHLIGHTSTROKECOLORS[p]);
}
pluginObjs = {
'PALETTEPLUGINS': {},
'PALETTEFILLCOLORS': {},
'PALETTESTROKECOLORS': {},
'PALETTEHIGHLIGHTCOLORS': {},
'FLOWPLUGINS': {},
'ARGPLUGINS': {},
'BLOCKPLUGINS': {}
};
//Matrix
window.savedMatricesNotes = [];
window.savedMatricesCount = 0;
// Stacks of blocks saved in local storage
var macroDict = {};
var stopTurtleContainer = null;
var stopTurtleContainerX = 0;
var stopTurtleContainerY = 0;
var cameraID = null;
var toLang = null;
var fromLang = null;
// initial scroll position
var scrollX = 0;
var scrollY = 0;
// default values
var CAMERAVALUE = '##__CAMERA__##';
var VIDEOVALUE = '##__VIDEO__##';
var DEFAULTDELAY = 500; // milleseconds
var TURTLESTEP = -1; // Run in step-by-step mode
var blockscale = 2;
var blockscales = [1, 1.5, 2, 3, 4];
// Time when we hit run
var time = 0;
// Used by pause block
var waitTime = {};
// Used to track mouse state for mouse button block
var stageMouseDown = false;
var stageX = 0;
var stageY = 0;
var onXO = (screen.width == 1200 && screen.height == 900) || (screen.width == 900 && screen.height == 1200);
console.log('on XO? ' + onXO);
var cellSize = 55;
if (onXO) {
cellSize = 75;
};
var onscreenButtons = [];
var onscreenMenu = [];
var helpContainer = null;
var helpIdx = 0;
var HELPCONTENT = [[_('Welcome to Music Blocks'), _('Music Blocks is a collection of manipulative tools for exploring fundamental musical concepts in an integrative and fun way.'), 'activity/activity-icon-mouse-color.svg'],
[_('Meet "Mr. Mouse!"'), _('Mr. Mouse is our Music Blocks conductor. Mr. Mouse encourages you to explore the Musical Blocks, the Matrix, and the Performance/Notation possibilities of Music Blocks. "Let\'s start our tour!" '), 'activity/activity-icon-mouse-color.svg'],
[_('<<< Palette buttons'), _('The toolbar to the left contains the palette buttons: click the button to reveal the respective palettes of blocks (Matrix, Chunk, Perform, Tone, (Turtle), Number, Flow, Actions, Media, and more). Tip: You can drag blocks from the palettes onto the canvas to use them.'), 'images/icons.svg'], //<==Let's update the image. I could not find your originals.
[_('Clean'), _('Clears the user-generated Matrix and user-generated Music Notations.'), 'icons/clear-button.svg'],
[_('Show/hide palettes'), _('Toggle between Hiding and showing the block palette toolbar (i.e. the menu to the left).'), 'icons/palette-button.svg'], //<==I have always found this a little confusing. This should be an improvement.
[_('Show/hide blocks'), _('Hide or show the blocks.'), 'icons/hide-blocks-button.svg'], //this does not seem to be hiding the palettes so I changed wording to be consistent.
[_('Expand/collapse collapsable blocks'), _('Expand or collapse stacks of blocks, (e.g, "start", "action", and "matrix" stacks.)'), 'icons/collapse-blocks-button.svg'],
[_('Save Notations'), _('Click to Download the Music Notations in png (image) format'), 'icons/download-button.svg'],
[_('Help'), _('Show these help messages.'), 'icons/help-button.svg'],
[_('Play'), _('FUTURE FEATURE: Plays the Music which is inside the start block. ("Runs" the functions strung together in start block.)'), 'icons/play-button.svg'], //<==Perhaps a little confusing that we have a play button and a start block. Devin will need to think about better design for this. 2015-08-24
[_('Stop'), _('Stop the Music.'), 'icons/stop-turtle-button.svg'],
[_('Matrix'), _('The Matrix, once generated using Pitch and Rhythm blocks, becomes a workspace for designing musical patterns--like melodies and chords.'), 'icons/stop-turtle-button.svg'], //<==Let's make an icon for the Matrix and put here.
[_('Chunk'), _('Once you have created a musical pattern that you like using the matrix, you can save the matrix as a chunk. Chunks will appear at the bottom of the "chunk" palette with a numberic label. You can then string chunks together to create more complex musical patterns.'), 'icons/stop-turtle-button.svg'], //<==Let's make an icon for the Chunk HERE.
[_('Expand/collapse option toolbar'), _('Click this button to expand or collapse the auxillary toolbar. Here you will find options like copy, paste, stave stack, settings, and global (to connect with others using Music Blocks--FUTURE FEATURE).'), 'icons/menu-button.svg'],
[_('Copy'), _('The copy button copies a stack to the clipboard. It appears after a "long press" on a stack.'), 'icons/copy-button.svg'],
[_('Paste'), _('The paste button is enabled when there are blocks copied onto the clipboard.'), 'icons/paste-disabled-button.svg'],
[_('Save stack'), _('The save-stack button saves a stack onto a custom palette. It appears after a "long press" on a stack.'), 'icons/save-blocks-button.svg'],
[_('Settings'), _('Open a panel for configuring settings of Music Blocks.'), 'icons/utility-button.svg'],
[_('Decrease block size'), _('Decrease the display size of the blocks.'), 'icons/smaller-button.svg'],
[_('Increase block size'), _('Increase the display size of the blocks.'), 'icons/bigger-button.svg'],
[_('Delete all'), _('Remove all content on the canvas, including all of the blocks and the matrix.'), 'icons/empty-trash-button.svg'],
[_('Undo'), _('Restore blocks from the trash.'), 'icons/restore-trash-button.svg'],
[_('Code!'), _('Take a peak at the Code. Latest development can be found at https://github.com/khandelwalYash/Music-Blocks. Once you download the code, you are free to share it, study it, modify it, and share your modifications. More SugarLabs projects may be found at http://www.sugarlabs.org/'), 'activity/activity-icon-mouse-color.svg'],
[_('Congratulations.'), _('You have finished the tour. Please enjoy Music Blocks!'), 'activity/activity-icon-mouse-color.svg']]
pluginsImages = {};
function allClear() {
logo.boxes = {};
logo.time = 0;
hideMsgs();
logo.setBackgroundColor(-1);
for (var turtle = 0; turtle < turtles.turtleList.length; turtle++) {
turtles.turtleList[turtle].doClear();
}
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
var table = document.getElementById("myTable");
if(table != null)
{
table.remove();
}
var canvas = document.getElementById("music");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('musicNotation').innerHTML = "";
document.getElementById('musicNotation').style.display = 'none';
if(musicnotation != null && musicnotation.musicContainer)
{
musicnotation.musicContainer.removeAllChildren();
musicnotation.notationIndex = 0;
}
blocksContainer.x = 0;
blocksContainer.y = 0;
matrix.clearTurtles();
var i = 1;
while(logo.blocks.protoBlockDict['namedsavematrix' + i])
{
var cont = logo.blocks.blockList[blk].container;
delete logo.blocks.protoBlockDict['namedsavematrix' + i];
delete ProtoBlock('namedsavematrix' + i);
cont.updateCache();
window.savedMatricesCount -= 1;
i += 1;
}
}
function doAnalytics() {
document.body.style.cursor = 'wait';
var myChart = docById('myChart');
var ctx = myChart.getContext('2d');
var myRadarChart = null;
var scores = analyzeProject(blocks);
console.log(scores);
var data = scoreToChartData(scores);
var callback = function() {
var imageData = myRadarChart.toBase64Image();
var img = new Image();
img.onload = function () {
chartBitmap = new createjs.Bitmap(img);
stage.addChild(chartBitmap);
chartBitmap.x = (canvas.width / (2 * scale)) - (300);
chartBitmap.y = 0;
chartBitmap.scaleX = chartBitmap.scaleY = chartBitmap.scale = 600 / chartBitmap.image.width;
logo.hideBlocks();
update = true;
document.body.style.cursor = 'default';
};
img.src = imageData;
}
var options = getChartOptions(callback);
console.log('creating new chart');
myRadarChart = new Chart(ctx).Radar(data, options);
}
function doBiggerFont() {
if (blockscale < blockscales.length - 1) {
blockscale += 1;
blocks.setBlockScale(blockscales[blockscale]);
}
}
function doSmallerFont() {
if (blockscale > 0) {
blockscale -= 1;
blocks.setBlockScale(blockscales[blockscale]);
}
}
// Do we need to update the stage?
var update = true;
// The dictionary of action name: block
var actions = {};
// The dictionary of box name: value
var boxes = {};
// Coordinate grid
var cartesianBitmap = null;
// Polar grid
var polarBitmap = null;
// Msg block
var msgText = null;
// ErrorMsg block
var errorMsgText = null;
var errorMsgArrow = null;
var errorArtwork = {};
var ERRORARTWORK = ['emptybox', 'emptyheap', 'negroot', 'noinput', 'zerodivide', 'notanumber', 'nostack', 'notastring', 'nomicrophone'];
var assemble = null;
// Get things started
init();
function init() {
docById('loader').className = 'loader';
stage = new createjs.Stage(canvas);
createjs.Touch.enable(stage);
createjs.Ticker.timingMode = createjs.Ticker.RAF_SYNCHED;
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick', stage);
createjs.Ticker.addEventListener('tick', tick);
createMsgContainer('#ffffff', '#7a7a7a', function(text) {
msgText = text;
}, 55);
createMsgContainer('#ffcbc4', '#ff0031', function(text) {
errorMsgText = text;
}, 110);
createErrorContainers();
/* Z-Order (top to bottom):
* menus
* palettes
* blocks
* trash
* turtles
* logo (drawing)
*/
palettesContainer = new createjs.Container();
blocksContainer = new createjs.Container();
trashContainer = new createjs.Container();
turtleContainer = new createjs.Container();
stage.addChild(turtleContainer, trashContainer, blocksContainer,
palettesContainer);
setupBlocksContainerEvents();
trashcan = new Trashcan(canvas, trashContainer, cellSize, refreshCanvas);
turtles = new Turtles(canvas, turtleContainer, refreshCanvas);
blocks = new Blocks(canvas, blocksContainer, refreshCanvas, trashcan, stage.update);
palettes = initPalettes(canvas, refreshCanvas, palettesContainer, cellSize, refreshCanvas, trashcan, blocks);
musicnotation = new MusicNotation(turtles, stage);
matrix = new Matrix(turtles, musicnotation);
//palettes.buttons['assemble'].visible = false;
//setting bgcolor of canvas that will be download as image for music notation
var can = document.getElementById('canvasToSave');
var ctx = can.getContext('2d');
ctx.fillStyle = "#ffffff";
ctx.fillRect(0,0,700,800);
palettes.setBlocks(blocks);
turtles.setBlocks(blocks);
blocks.setTurtles(turtles);
blocks.setErrorMsg(errorMsg);
blocks.makeCopyPasteButtons(makeButton, updatePasteButton);
// TODO: clean up this mess.
logo = new Logo(matrix, canvas, blocks, turtles, turtleContainer,
refreshCanvas,
textMsg, errorMsg, hideMsgs, onStopTurtle,
onRunTurtle, prepareExport, getStageX, getStageY,
getStageMouseDown, getCurrentKeyCode,
clearCurrentKeyCode, meSpeak, saveLocally);
blocks.setLogo(logo);
// Set the default background color...
logo.setBackgroundColor(-1);
clearBox = new ClearBox(canvas, stage, refreshCanvas, sendAllToTrash);
utilityBox = new UtilityBox(canvas, stage, refreshCanvas, doBiggerFont, doSmallerFont, doOpenPlugin, doAnalytics);
thumbnails = new SamplesViewer(canvas, stage, refreshCanvas, loadProject, loadRawProject, sendAllToTrash);
initBasicProtoBlocks(palettes, blocks);
// Load any macros saved in local storage.
var macroData = localStorage.getItem('macros');
if (macroData != null) {
processMacroData(macroData, palettes, blocks, macroDict);
}
// Blocks and palettes need access to the macros dictionary.
blocks.setMacroDictionary(macroDict);
palettes.setMacroDictionary(macroDict);
// Load any plugins saved in local storage.
var pluginData = localStorage.getItem('plugins');
if (pluginData != null) {
var obj = processPluginData(pluginData, palettes, blocks, logo.evalFlowDict, logo.evalArgDict, logo.evalParameterDict, logo.evalSetterDict);
updatePluginObj(obj);
}
fileChooser.addEventListener('click', function(event) { this.value = null; });
fileChooser.addEventListener('change', function(event) {
// Read file here.
var reader = new FileReader();
reader.onload = (function(theFile) {
// Show busy cursor.
document.body.style.cursor = 'wait';
setTimeout(function() {
var rawData = reader.result;
var cleanData = rawData.replace('\n', ' ');
console.log(cleanData);
var obj = JSON.parse(cleanData);
console.log(obj)
blocks.loadNewBlocks(obj);
// Restore default cursor.
document.body.style.cursor = 'default';
}, 200);
});
reader.readAsText(fileChooser.files[0]);
}, false);
allFilesChooser.addEventListener('click', function(event) { this.value = null; });
pluginChooser.addEventListener('click', function(event) {
window.scroll(0, 0);
this.value = null;
});
pluginChooser.addEventListener('change', function(event) {
window.scroll(0, 0)
// Read file here.
var reader = new FileReader();
reader.onload = (function(theFile) {
// Show busy cursor.
document.body.style.cursor = 'wait';
setTimeout(function() {
obj = processRawPluginData(reader.result, palettes, blocks, errorMsg, logo.evalFlowDict, logo.evalArgDict, logo.evalParameterDict, logo.evalSetterDict);
// Save plugins to local storage.
if (obj != null) {
var foo = preparePluginExports(obj);
console.log(foo);
localStorage.setItem('plugins', foo); // preparePluginExports(obj));
}
// Refresh the palettes.
setTimeout(function() {
if (palettes.visible) {
palettes.hide();
}
palettes.show();
palettes.bringToTop();
}, 1000);
// Restore default cursor.
document.body.style.cursor = 'default';
}, 200);
});
reader.readAsText(pluginChooser.files[0]);
}, false);
// Workaround to chrome security issues
// createjs.LoadQueue(true, null, true);
// Enable touch interactions if supported on the current device.
// FIXME: voodoo
// createjs.Touch.enable(stage, false, true);
// Keep tracking the mouse even when it leaves the canvas.
stage.mouseMoveOutside = true;
// Enabled mouse over and mouse out events.
stage.enableMouseOver(10); // default is 20
cartesianBitmap = createGrid('images/Cartesian.svg');
polarBitmap = createGrid('images/polar.svg');
var URL = window.location.href;
var projectName = null;
try {
httpGet(null);
console.log('running from server or the user can access to examples.');
server = true;
} catch (e) {
console.log('running from filesystem or the connection isnt secure');
server = false;
}
setupAndroidToolbar();
// Scale the canvas relative to the screen size.
onResize();
if (URL.indexOf('?') > 0) {
var urlParts = URL.split('?');
if (urlParts[1].indexOf('=') > 0) {
var projectName = urlParts[1].split('=')[1];
}
}
if (projectName != null) {
setTimeout(function () { console.log('load ' + projectName); loadProject(projectName); }, 2000);
} else {
setTimeout(function () { loadStart(); }, 2000);
}
document.addEventListener('mousewheel', scrollEvent, false);
document.addEventListener('DOMMouseScroll', scrollEvent, false);
this.document.onkeydown = keyPressed;
}
function setupBlocksContainerEvents() {
var moving = false;
stage.on('stagemousemove', function (event) {
stageX = event.stageX;
stageY = event.stageY;
});
stage.on('stagemousedown', function (event) {
stageMouseDown = true;
if (stage.getObjectUnderPoint() !== null | turtles.running()) {
stage.on('stagemouseup', function (event) {
stageMouseDown = false;
});
return;
}
moving = true;
lastCords = {x: event.stageX, y: event.stageY};
stage.on('stagemousemove', function (event) {
if (!moving) {
return;
}
blocksContainer.x += event.stageX - lastCords.x;
blocksContainer.y += event.stageY - lastCords.y;
lastCords = {x: event.stageX, y: event.stageY};
refreshCanvas();
});
stage.on('stagemouseup', function (event) {
stageMouseDown = false;
moving = false;
}, null, true); // once = true
});
}
function scrollEvent(event) {
var data = event.wheelDelta || -event.detail;
var delta = Math.max(-1, Math.min(1, (data)));
var scrollSpeed = 3;
if (event.clientX < cellSize) {
palettes.menuScrollEvent(delta, scrollSpeed);
} else {
palette = palettes.findPalette(event.clientX/scale, event.clientY/scale);
if (palette) {
palette.scrollEvent(delta, scrollSpeed);
}
}
}
function getStageX() {
return turtles.screenX2turtleX(stageX / blocks.scale);
}
function getStageY() {
return turtles.screenY2turtleY(stageY / blocks.scale);
}
function getStageMouseDown() {
return stageMouseDown;
}
function setCameraID(id) {
cameraID = id;
}
function createGrid(imagePath) {
var img = new Image();
img.src = imagePath;
var container = new createjs.Container();
stage.addChild(container);
bitmap = new createjs.Bitmap(img);
container.addChild(bitmap);
bitmap.cache(0, 0, 1200, 900);
bitmap.x = (canvas.width - 1200) / 2;
bitmap.y = (canvas.height - 900) / 2;
bitmap.scaleX = bitmap.scaleY = bitmap.scale = 1;
bitmap.visible = false;
bitmap.updateCache();
return bitmap;
};
function createMsgContainer(fillColor, strokeColor, callback, y) {
var container = new createjs.Container();
stage.addChild(container);
container.x = (canvas.width - 1000) / 2;
container.y = y;
container.visible = false;
var img = new Image();
var svgData = MSGBLOCK.replace('fill_color', fillColor).replace(
'stroke_color', strokeColor);
img.onload = function() {
var msgBlock = new createjs.Bitmap(img);
container.addChild(msgBlock);
text = new createjs.Text('your message here',
'20px Arial', '#000000');
container.addChild(text);
text.textAlign = 'center';
text.textBaseline = 'alphabetic';
text.x = 500;
text.y = 30;
var bounds = container.getBounds();
container.cache(bounds.x, bounds.y, bounds.width, bounds.height);
var hitArea = new createjs.Shape();
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, 1000, 42);
hitArea.x = 0;
hitArea.y = 0;
container.hitArea = hitArea;
container.on('click', function(event) {
container.visible = false;
// On the possibility that there was an error
// arrow associated with this container
if (errorMsgArrow !== null) {
errorMsgArrow.removeAllChildren(); // Hide the error arrow.
}
update = true;
});
callback(text);
blocks.setMsgText(text);
}
img.src = 'data:image/svg+xml;base64,' + window.btoa(
unescape(encodeURIComponent(svgData)));
};
function createErrorContainers() {
// Some error messages have special artwork.
for (var i = 0; i < ERRORARTWORK.length; i++) {
var name = ERRORARTWORK[i];
makeErrorArtwork(name);
}
}
function makeErrorArtwork(name) {
var container = new createjs.Container();
stage.addChild(container);
container.x = (canvas.width - 1000) / 2;
container.y = 110;
errorArtwork[name] = container;
errorArtwork[name].name = name;
errorArtwork[name].visible = false;
var img = new Image();
img.onload = function() {
console.log('creating error message artwork for ' + img.src);
var artwork = new createjs.Bitmap(img);
container.addChild(artwork);
var text = new createjs.Text('', '20px Sans', '#000000');
container.addChild(text);
text.x = 70;
text.y = 10;
var bounds = container.getBounds();
container.cache(bounds.x, bounds.y, bounds.width, bounds.height);
var hitArea = new createjs.Shape();
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, bounds.width, bounds.height);
hitArea.x = 0;
hitArea.y = 0;
container.hitArea = hitArea;
container.on('click', function(event) {
container.visible = false;
// On the possibility that there was an error
// arrow associated with this container
if (errorMsgArrow !== null) {
errorMsgArrow.removeAllChildren(); // Hide the error arrow.
}
update = true;
});
}
img.src = 'images/' + name + '.svg';
}
function keyPressed(event) {
if (docById('labelDiv').classList.contains('hasKeyboard')) {
return;
}
var ESC = 27;
var ALT = 18;
var CTRL = 17;
var SHIFT = 16;
var RETURN = 13;
var SPACE = 32;
// Captured by browser
var PAGE_UP = 33;
var PAGE_DOWN = 34;
var KEYCODE_LEFT = 37;
var KEYCODE_RIGHT = 39;
var KEYCODE_UP = 38;
var KEYCODE_DOWN = 40;
if (event.altKey) {
switch (event.keyCode) {
case 69: // 'E'
allClear();
break;
case 82: // 'R'
doFastButton();
break;
case 83: // 'S'
logo.doStopTurtle();
break;
}
} else if (event.ctrlKey) {} else {
switch (event.keyCode) {
case ESC:
// toggle full screen
toggleToolbar();
break
case RETURN:
// toggle run
logo.runLogoCommands();
break
default:
currentKey = String.fromCharCode(event.keyCode);
currentKeyCode = event.keyCode;
break;
}
}
}
function getCurrentKeyCode() {
return currentKeyCode;
}
function clearCurrentKeyCode() {
currentKey = '';
currentKeyCode = 0;
}
function onResize() {
if (docById('labelDiv').classList.contains('hasKeyboard')) {
return;
}
if (!platform.androidWebkit) {
var w = window.innerWidth;
var h = window.innerHeight;
} else {
var w = window.outerWidth;
var h = window.outerHeight;
}
var smallSide = Math.min(w, h);
if (smallSide < cellSize * 11) {
var mobileSize = true;
if (w < cellSize * 10) {
scale = smallSide / (cellSize * 11);
} else {
scale = Math.max(smallSide / (cellSize * 11), 0.75);
}
} else {
var mobileSize = false;
if (w > h) {
scale = w / 1200;
} else {
scale = w / 900;
}
}
stage.scaleX = scale;
stage.scaleY = scale;
stage.canvas.width = w;
stage.canvas.height = h;
console.log('Resize: scale ' + scale +
', windowW ' + w + ', windowH ' + h +
', canvasW ' + canvas.width + ', canvasH ' + canvas.height +
', screenW ' + screen.width + ', screenH ' + screen.height);
turtles.setScale(scale);
blocks.setScale(scale);
palettes.setScale(scale);
trashcan.resizeEvent(scale);
setupAndroidToolbar(mobileSize);
// Reposition coordinate grids.
cartesianBitmap.x = (canvas.width / (2 * scale)) - (600);
cartesianBitmap.y = (canvas.height / (2 * scale)) - (450);
polarBitmap.x = (canvas.width / (2 * scale)) - (600);
polarBitmap.y = (canvas.height / (2 * scale)) - (450);
update = true;
// Setup help now that we have calculated scale.
showHelp(true);
// Hide palette icons on mobile
if (mobileSize) {
palettes.hide();
} else {
palettes.show();
palettes.bringToTop();
}
if(matrix.isMatrix == 1)
{
matrixTable = document.getElementById("myTable");
matrixTable.setAttribute("width", w/2 + 'px');
}
if(workspace)
{
console.log("clearing canvas");
assemble.clearAll();
clearMenus();
}
}
window.onresize = function() {
onResize();
}
function restoreTrash() {
var dx = 0;
var dy = -cellSize * 3; // Reposition blocks about trash area.
for (var blk in blocks.blockList) {
if (blocks.blockList[blk].trash) {
blocks.blockList[blk].trash = false;
blocks.moveBlockRelative(blk, dx, dy);
blocks.blockList[blk].show();
if (blocks.blockList[blk].name == 'start') {
turtle = blocks.blockList[blk].value;
turtles.turtleList[turtle].trash = false;
turtles.turtleList[turtle].container.visible = true;
}
}
}
update = true;
}
function deleteBlocksBox() {
clearBox.show(scale);
}
function doUtilityBox() {
utilityBox.show(scale);
}
// FIXME: confirm???
function sendAllToTrash(addStartBlock, doNotSave) {
var dx = 2000;
var dy = cellSize;
for (var blk in blocks.blockList) {
blocks.blockList[blk].trash = true;
blocks.moveBlockRelative(blk, dx, dy);
blocks.blockList[blk].hide();
if (blocks.blockList[blk].name == 'start') {
console.log('start blk ' + blk + ' value is ' + blocks.blockList[blk].value)
turtle = blocks.blockList[blk].value;
if (turtle != null) {
console.log('sending turtle ' + turtle + ' to trash');
turtles.turtleList[turtle].trash = true;
turtles.turtleList[turtle].container.visible = false;
}
}
}
if (addStartBlock) {
function postprocess() {
last(blocks.blockList).x = 250;
last(blocks.blockList).y = 250;
last(blocks.blockList).connections = [null, null, null];
turtles.add(last(blocks.blockList));
last(blocks.blockList).value = turtles.turtleList.length - 1;
blocks.updateBlockPositions();
if (!doNotSave) {
console.log('save locally');
saveLocally();
}
}
blocks.makeNewBlock('start', postprocess);
}
if (!doNotSave) {
// Overwrite session data too.
console.log('save locally');
saveLocally();
}
update = true;
}
function changePaletteVisibility() {
if (palettes.visible) {
palettes.hide();
} else {
palettes.show();
palettes.bringToTop();
}
}
function changeBlockVisibility() {
if (blocks.visible) {
logo.hideBlocks();
} else {
if (chartBitmap != null) {
stage.removeChild(chartBitmap);
chartBitmap = null;
}
logo.showBlocks();
}
}
function saveMusicNotations() {
var canvas = document.getElementById("canvasToSave");
var img = canvas.toDataURL("image/png");
//document.write('<img src="'+img+'"/>');*/
var link = document.createElement('a');
link.href = img;
link.download = 'Download.png';
document.body.appendChild(link);
link.click();
}
function toggleCollapsibleStacks() {
if (blocks.visible) {
console.log('calling toggleCollapsibles');
blocks.toggleCollapsibles();
}
}
function stop() {
// FIXME: who calls this???
createjs.Ticker.removeEventListener('tick', tick);
}
function onStopTurtle() {
// TODO: plugin support
if (!buttonsVisible) {
hideStopButton();
}
}
function onRunTurtle() {
// TODO: plugin support
// If the stop button is hidden, show it.
if (!buttonsVisible) {
showStopButton();
}
}
function refreshCanvas() {
update = true;
}
function tick(event) {
// This set makes it so the stage only re-renders when an
// event handler indicates a change has happened.
if (update) {
update = false; // Only update once
stage.update(event);