-
Notifications
You must be signed in to change notification settings - Fork 95
/
jade.js
1853 lines (1553 loc) · 67.4 KB
/
jade.js
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) 2011-2017 Massachusetts Institute of Technology
// Chris Terman
// pollute the global namespace with a single variable
var jade_defs = {};
var jade_dump_json; // function for grabbing JSON dumps of modules
var jade_load_json; // function for loading JSON dumps of modules
var jade_load_edx; // function for loading student edX submissions into editor
// "new jade_defs.jade()" will build a self-contained jade object so we can
// have multiple instances on the same webpage that don't share any
// state stored in shared variables.
jade_defs.jade = function() {
var j = this;
$.extend(j,jade_defs.top_level(j));
j.model = jade_defs.model(j);
jade_defs.netlist(j);
jade_defs.icons(j);
j.schematic_view = jade_defs.schematic_view(j);
j.icon_view = jade_defs.icon_view(j);
j.property_view = jade_defs.property_view(j);
j.test_view = jade_defs.test_view(j);
j.utils = jade_defs.utils(j);
j.plot = jade_defs.plot(j);
j.device_level = jade_defs.device_level(j);
j.cktsim = jade_defs.cktsim(j);
j.gate_level = jade_defs.gate_level(j);
j.gatesim = jade_defs.gatesim(j);
jade_defs.analog(j);
jade_defs.gates(j);
};
jade_defs.top_level = function(jade) {
var version = "Jade 2.3.17 (2020 \u00A9 MIT EECS)";
var about_msg = version +
"<p>Chris Terman wrote the schematic entry, testing and gate-level simulation tools." +
"<p>Jacob White wrote the simulation engine for the device-level simulation tools."+
"<p>We are grateful to Quanta Computer Incorporated for their support of the development of the Jade schematic entry and simulation tool as part of a research project on educational technologies with the MIT Computer Science and Artificial Intelligence Laboratory.";
//////////////////////////////////////////////////////////////////////
//
// Editor framework
//
//////////////////////////////////////////////////////////////////////
var editors = []; // list of supported aspects
var clipboards = {}; // clipboards for each editor type
function Jade(owner) {
owner.jade = this;
this.jade = jade;
this.parent = owner;
this.module = undefined;
this.configuration = {};
// insert framework into DOM
this.top_level = $('<div class="jade-top-level">' +
' <div id="module-tools" class="jade-toolbar"></div>' +
' <div class="jade-tabs-div"></div>' +
' <div class="jade-resize-icon"></div>' +
' <div class="jade-version"><a href="#">'+version+'</a></div>' +
' <div class="jade-status"><span id="message"></span></div>' +
'</div>');
$('.jade-resize-icon',this.top_level).append(jade.icons.resize_icon);
$(owner).append(this.top_level);
$('.jade-version a',this.top_level).on('click',function (event) {
jade_window('About Jade',$('<div class="jade-about"></div>').html(about_msg),$(owner).offset());
event.preventDefault();
return false;
});
this.status = this.top_level.find('#message');
// set up module tools at the very top
this.module_tools = this.top_level.find('#module-tools');
this.module_tools.append('<span>Module:</span><select id="module-select"></select>');
this.module_tools.append(this.module_tool(jade.icons.edit_module_icon,'edit-module','Edit/create module',edit_module,'hierarchy-tool'));
this.module_tools.append(this.module_tool(jade.icons.copy_module_icon,'copy-module','Copy current module',copy_module,'hierarchy-tool'));
this.module_tools.append(this.module_tool(jade.icons.delete_module_icon,'delete-module','Delete current module',delete_module,'hierarchy-tool'));
this.module_tools.append(this.module_tool(jade.icons.download_icon,'download-modules','Save modules to module clipboard',download_modules));
this.module_tools.append(this.module_tool(jade.icons.upload_icon,'upload-modules','Select modules to load from module clipboard',upload_modules));
// too dangerous!
// this.module_tools.append(this.module_tool(jade.icons.recycle_icon,'start-over','Discard all work on this problem and start over',start_over));
if (jade.cloud_upload) {
this.module_tools.append(this.module_tool(jade.icons.cloud_upload_icon,'cloud-upload','Upload designs to the cloud',jade.cloud_upload));
}
if (jade.cloud_download) {
this.module_tools.append(this.module_tool(jade.icons.cloud_download_icon,'cloud-download','Dowload designs from the cloud',jade.cloud_download));
}
/*
var mailto = $('<a href="#"><span class="fa fa-lg fa-envelope-o"></span>"');
mailto.on('click',function (event) {
window.location = "mailto:[email protected]?Subject=&body=bar";
return false;
});
this.module_tools.append(mailto);
*/
$('#module-select',this.module_tools).on('change',function () {
owner.jade.edit($(this).val());
});
// now add a display tab for each registered editor
this.tabs_div = this.top_level.find('.jade-tabs-div');
this.tabs = {};
this.selected_tab = undefined;
// add status line at the bottom
this.status.text('Copyright \u00A9 MIT EECS 2011, 2020');
// set up handler to resize jade
var me = this;
if ($(owner).hasClass('jade-resize')) {
$('.jade-resize-icon',this.top_level)
.css('display','inline')
.on('mousedown',function (event) {
var doc = $(document).get(0);
var div = $(owner);
var rx = event.pageX;
var ry = event.pageY;
function move(event) {
var w = div.width() + event.pageX - rx;
var h = div.height() + event.pageY - ry;
div.width(w);
div.height(h);
// requery size in case it's been constrained by css
me.resize(div.width(),div.height());
rx = event.pageX;
ry = event.pageY;
return false;
};
function up(event) {
doc.removeEventListener('mousemove',move,true);
doc.removeEventListener('mouseup',move,true);
return false;
}
// add handlers to document so we capture them no matter what
doc.addEventListener('mousemove',move,true);
doc.addEventListener('mouseup',up,true);
return false;
});
} else {
// we're full screen, so resize when window resizes
$(window).on('resize',function() {
var body = $('body');
body.css('overflow','hidden'); // avoid scrollbars
var win_w = $(window).width() - (body.outerWidth(true) - body.width());
var win_h = $(window).height() - (body.outerHeight(true) - body.height());
me.resize(win_w,win_h);
});
$(window).trigger('resize'); // initial sizing
}
}
Jade.prototype.module_tool = function (icon,id,tip,action,extra_classes) {
var tool = $('<span></span>').append(icon).addClass('jade-module-tool jade-tool-enabled').attr('id',id);
if (extra_classes) tool.addClass(extra_classes);
var j = this; // for closure
tool.on('click',function (event) {
if (action) action(j,event);
event.preventDefault();
return false;
});
tool.on('mouseenter',function () {
j.status.html(tip);
});
tool.on('mouseleave',function () {
j.status.html('');
});
return tool;
};
// helper function for dumping json for modules -- make accessible at top level
jade_dump_json = function (mname,dirty_only) {
var p = new RegExp(mname);
var result = {};
$.each(jade.model.get_modules(),function (mname,module) {
if (p.test(mname)) {
result[mname] = module.json(dirty_only);
}
});
return JSON.stringify(result);
};
// helper function for loading json -- make accessible at top level
jade_load_json = function (json) {
jade.model.load_json(JSON.parse(json));
};
jade_load_edx = function(s) {
var edx_state = JSON.parse(s).state;
var design = JSON.parse(edx_state).state;
jade.model.load_json(design);
var modules = Object.keys(design);
$('.jade')[0].jade.edit(modules[0]);
return modules;
};
// initialize editor from configuration object
Jade.prototype.initialize = function (config) {
var me = this;
$.extend(this.configuration,config);
$('#start-over',this.module_tools).toggle(this.configuration.state && this.configuration.initial_state);
$('#cloud-upload',this.module_tools).toggle(this.configuration.cloud_url !== undefined);
$('#cloud-download',this.module_tools).toggle(this.configuration.cloud_url !== undefined);
// initialize object for recording test results
if (this.configuration.tests === undefined) this.configuration.tests = {};
$('.hierarchy-tool',this.top_level).toggle(this.configuration.hierarchical == 'true');
// setup editor panes
var elist;
if (this.configuration.editors) {
elist = [];
$.each(this.configuration.editors,function(index,value) {
// look through list of defined editors to see if we have a match
$.each(editors,function(eindex,evalue) {
if (evalue.prototype.editor_name == value) elist.push(evalue);
});
});
} else elist = editors;
// clear out existing tabs
me.tabs_div.empty();
$('.jade-tab-body',me.top_level).remove();
// add tabs for specified editors
$.each(elist,function(i,editor) {
var ename = editor.prototype.editor_name;
clipboards[ename] = []; // initialize editor's clipboard
// add tab selector
var tab = $('<div class="jade-tab">'+ename+'</div>');
me.tabs_div.append(tab);
tab.click(function(event) {
jade.model.save_modules();
me.show(ename);
event.preventDefault();
return false;
});
// add body for each tab (only one will have display != none)
var body = $('<div class="jade-tab-body"></div>');
body[0].tab = tab[0]; // make it easy to find our tab later
me.top_level.find('.jade-tabs-div').after(body);
// make a new editor for this aspect
body[0].editor = new editor(body[0], me);
me.tabs[ename] = [tab[0], body[0]];
// save changes to server if we're leaving this particular editor
body.on('mouseleave',function () { jade.model.save_modules(); });
});
// select first aspect as the one to be displayed
if (elist.length > 0) {
this.show(elist[0].prototype.editor_name);
}
if ($(this.parent).hasClass('jade-resize'))
this.resize($(this.parent).width(),$(this.parent).height());
else $(window).trigger('resize'); // let editors know their size
// start by loading shared modules from the server
if (this.configuration.shared_modules) {
$.each(this.configuration.shared_modules, function (index,filename) {
console.log('sync loading '+filename);
$.ajax(filename,{
dataType: 'json',
async: false,
error: function(jqXHR,textStatus,errorThrown) {
console.log('oops, error loading '+filename);
},
success: function(data,jqXHR,textStatus,errorThrown) {
jade.model.load_json(data,true);
console.log('finished sync loading '+filename);
}
});
});
}
// load state (dictionary of module_name:json). Start with initial_state
// then overwrite with user's state
if (this.configuration.initial_state) {
jade.model.load_json(this.configuration.initial_state,true);
}
if (this.configuration.state) {
jade.model.load_json(this.configuration.state,false);
}
// starting module?
var edit = this.configuration.edit || '/user/untitled';
if (edit[0] != '/') edit = '/user/'+edit;
var mname = edit.split('.'); // module.aspect
this.edit(mname[0]); // select module
if (mname.length > 1) this.show(mname[1]);
};
Jade.prototype.get_state = function() {
// save updated test results and any aspects that
// differ from initial state
var state = {
tests: this.configuration.tests,
'required-tests': this.configuration['required-tests'],
state: jade.model.json_modules(true).json,
last_saved: Date.now()
};
if (this.configuration.help_url)
state.help_url = this.configuration.help_url;
if (this.configuration.student_id)
state.help_url = this.configuration.student_id;
// request for state means user library is being saved
jade.model.clear_modified();
return state;
};
Jade.prototype.get_grade = function() {
return {'required-tests': this.configuration['required-tests'] || [],
'tests': this.configuration.tests || {}
};
};
// remember module and aspect for next visit
Jade.prototype.bookmark = function() {
if (this.module !== undefined) {
var mark = this.module.get_name();
if (this.selected_tab !== undefined) mark += '.' + this.selected_tab;
}
};
Jade.prototype.edit = function(module) {
if (typeof module == 'string') module = jade.model.find_module(module);
this.module = module;
// update list of available modules
var pattern_list = (this.configuration.parts || ['.*']).map(function (p) { return new RegExp(p); });
var mlist = [];
jade.model.map_modules(pattern_list,function (m) {
if (m.confidential()) return; // can't view confidential models
var name = m.get_name();
// only include each module once!
if (mlist.indexOf(name) == -1) mlist.push(name);
});
build_select(mlist.sort(),module.get_name(),$('#module-select',this.module_tools));
if (module.shared) {
$('#delete-module',this.module_tools).removeClass('jade-tool-enabled');
$('#delete-module',this.module_tools).addClass('jade-tool-disabled');
} else {
$('#delete-module',this.module_tools).removeClass('jade-tool-disabled');
$('#delete-module',this.module_tools).addClass('jade-tool-enabled');
}
this.bookmark(); // remember current module for next visit
this.refresh(); // tell each tab which module we're editing
// save any changes to the server when we change what we're editing
jade.model.save_modules();
};
// if underlying library/module is reloaded, refresh each tab
Jade.prototype.refresh = function() {
if (this.module === undefined) return;
// tell each tab which module we're editing
for (var e in this.tabs) {
this.tabs[e][1].editor.set_aspect(this.module);
}
};
// make a particular tab visible -- DOM class name does the heavy lifting
Jade.prototype.show = function(tab_name) {
this.selected_tab = tab_name;
this.bookmark();
for (var tab in this.tabs) {
var e = this.tabs[tab]; // [tab div, body div]
var selected = (tab == tab_name);
//e[0].className = 'jade-tab';
$(e[0]).toggleClass('jade-tab-active', selected);
$(e[1]).toggleClass('jade-tab-body-active', selected);
if (selected) e[1].editor.show();
}
};
Jade.prototype.resize = function(w, h) {
var e = $(this.top_level);
// adjust target w,h to reflect postion and sizes of padding, borders, margins
var w_extra = e.outerWidth(true) - e.width();
var h_extra = e.outerHeight(true) - e.height();
w -= w_extra;
h -= h_extra + $('#module-tools').outerHeight(true) +
$('.jade-tabs-div',e).outerHeight(true) +
$('.jade-status',e).outerHeight(true);
// adjust size of all the tab bodies
for (var tab in this.tabs) {
var ediv = this.tabs[tab][1]; // [tab div, body div]
e = $(ediv);
w_extra = e.outerWidth(true) - e.width();
h_extra = e.outerHeight(true) - e.height();
var tw = w - w_extra;
var th = h - h_extra;
e.width(tw);
e.height(th);
// inform associated editor about its new size
ediv.editor.resize(tw, th, tab == this.selected_tab);
}
};
//////////////////////////////////////////////////////////////////////
//
// Module tools
//
//////////////////////////////////////////////////////////////////////
function edit_module(j) {
var offset = $('.jade-tabs-div',j.top_level).offset();
var content = $('<div style="margin:10px;"><div id="msg" style="display:none;color:red;margin-bottom:10px;"></div></div>');
content.append('Module name:');
var input = build_input('text',10,'');
$(input).css('vertical-align','middle');
content.append(input);
function edit() {
var name = $(input).val();
// force module names to be a pathname, in /user by default
if (name[0] != '/') name = '/user/'+name;
function try_again(msg) {
$('#msg',content).text(msg);
$('#msg',content).show();
dialog('Edit Module',content,edit,offset);
}
// make sure name is legit
var valid = true;
$.each(name.split('/'),function (index,n) {
if (!jade.utils.validate_name(n)) valid = false;
});
if (!valid) {
try_again('Invalid module name: '+name);
return;
}
var module = jade.model.find_module(name);
jade.model.save_modules(true);
j.edit(module.get_name());
}
dialog('Edit Module',content,edit,offset);
}
function delete_module(j) {
var offset = $('.jade-tabs-div',j.top_level).offset();
var content = $('<div style="margin:10px;width:300px;">Click OK to confirm the deletion of module <span id="mname"></span>. Note that this action cannot be undone.</div>');
$('#mname',content).text(j.module.get_name());
function del() {
var module = j.module;
jade.model.remove_module(module.name);
jade.model.save_modules(true);
// choose something else to edit
j.edit(jade.model.find_module('/user/untitled'));
}
dialog('Delete Module',content,del,offset);
}
function copy_module(j) {
var offset = $('.jade-tabs-div',j.top_level).offset();
var content = $('<div style="margin:10px;"><div id="msg" style="display:none;color:red;margin-bottom:10px;"></div></div>');
content.append('New module name:');
var input = build_input('text',10,'');
$(input).css('vertical-align','middle');
content.append(input);
function copy() {
var name = $(input).val();
// force module names to be a pathname, in /user by default
if (name[0] != '/') name = '/user/'+name;
function try_again(msg) {
$('#msg',content).text(msg);
$('#msg',content).show();
dialog('Copy Module',content,copy,offset);
}
// make sure name is legit
var valid = true;
$.each(name.split('/'),function (index,n) {
if (!jade.utils.validate_name(n)) valid = false;
});
if (!valid) {
try_again('Invalid module name: '+name);
return;
}
if (name in jade.model.get_modules()) {
try_again('Module already exists: '+name);
return;
}
// make a new module and initialize it using the original
var module = jade.model.find_module(name,j.module.json());
// in case we're copying a shared module
module.shared = false;
module.remove_property('readonly');
module.set_modified(); // since it hasn't been saved yet
jade.model.save_modules(true);
// select new module for editing
j.edit(module);
}
dialog('Copy Module',content,copy,offset);
}
// add our non-shared modules to localStorage
function download_modules(j) {
var saved_modules = JSON.parse(localStorage.getItem('jade_saved_modules') || "{}");
$.extend(saved_modules,jade.model.json_modules().json);
localStorage.setItem('jade_saved_modules',JSON.stringify(saved_modules));
};
function upload_modules(j,event) {
if (event && event.shiftKey) {
var content = $('<div style="margin:10px;"><textarea rows="5" cols="80"/></div>');
var offset = $('.jade-tabs-div',j.top_level).offset();
function load_answer() {
var s = eval($('textarea',content).val());
var edx_state = JSON.parse(s).state;
var design = JSON.parse(edx_state).state;
jade.model.load_json(design);
var modules = Object.keys(design);
j.edit(modules[0]);
console.log(modules);
}
dialog('Load student answer',content,load_answer,offset);
return;
}
// get modules from localStorage
var modules = JSON.parse(localStorage.getItem('jade_saved_modules') || '{}');
var mnames = Object.keys(modules).sort();
// build checkbox selector for each available module
var select = [];
$.each(mnames,function (index,mname) {
var cbox = $('<input type="checkbox" value=""></input>').attr('name',mname);
select.push($('<div class="jade-module-select"></div>').append(cbox,mname));
});
// build a dialog using up to 3 columns to list modules
var row = $('<tr valign="top"></tr>');
var ncols = Math.max(3,Math.ceil(select.length/10));
var select_all = $('<td><a href="">Select all</a></td>');
select_all.attr('colspan',ncols.toString());
var nitems = Math.ceil(select.length/ncols);
var col,index=0,i;
while (ncols--) {
col = $('<td></td>');
for (i = 0; i < nitems; i += 1)
col.append(select[index++]);
row.append(col);
}
var contents = $('<table></table>').append(row,$('<tr align="center"></tr>').append(select_all));
// implement select all functionality
$('a',select_all).on('click',function (event) {
$('input',row).prop('checked',true);
event.preventDefault();
return false;
});
// find checked items and load them
function upload () {
$.each(select,function (index,item) {
var input = $('input',item);
var mname = input.attr('name');
if (input[0].checked) {
//console.log(mname + ' is checked');
jade.model.find_module(mname,modules[mname]);
}
});
jade.model.save_modules(true);
j.edit(j.module); // trigger rebuild of module list
}
// let user choose
var offset = $('.jade-tabs-div',j.top_level).offset();
dialog('Select modules to load',contents,upload,offset);
};
function start_over(j) {
function restart() {
delete j.configuration.state;
delete j.configuration.tests;
j.initialize(j.configuration);
jade.model.save_modules(true);
}
var offset = $('.jade-tabs-div',j.top_level).offset();
dialog('Start over?',
$('<span>Click OK to discard all work on this problem and start over again.</span>'),
restart,offset);
}
//////////////////////////////////////////////////////////////////////
//
// Diagram editor base class
//
//////////////////////////////////////////////////////////////////////
function Diagram(editor, class_name) {
this.editor = editor;
this.aspect = undefined;
// setup canas
this.canvas = $('<div><svg></svg></div>').addClass(class_name)[0]
;
this.canvas.diagram = this;
this.svg = this.canvas.children.item(0);
// ethanschoonover.com
this.background_style = 'rgb(250,250,250)'; // backgrund color for diagram [base3]
this.grid_style = 'rgb(230,230,230)'; // grid on background
this.control_style = 'rgb(0,0,0)'; // grid on background [base1]
this.normal_style = 'rgb(88,110,117)'; // default drawing color [base01]
this.component_style = 'rgb(38,139,210)'; // color for unselected components [blue]
this.selected_style = 'rgb(211,54,130)'; // highlight color for selected components [magenta]
this.annotation_style = 'rgb(220,50,47)'; // color for diagram annotations [red]
this.property_font = '5pt sans-serif'; // point size for Component property text
this.annotation_font = '6pt sans-serif'; // point size for diagram annotations
// grid in the background
this.svg_grid = jade.utils.make_svg('g',{
id: 'grid',
stroke: this.grid_style,
'stroke-width': 0.2,
fill: 'none'
});
this.svg.appendChild(this.svg_grid);
// then static content
this.svg_content = jade.utils.make_svg('g',{
id: 'content',
stroke: this.normal_style,
'stroke-width': 1,
'stroke-linecap': 'round',
fill: 'none'
});
this.svg.appendChild(this.svg_content);
// then selected content
this.svg_selected = jade.utils.make_svg('g',{
id: 'selected',
stroke: this.selected_style,
'stroke-width': 1,
'stroke-linecap': 'round',
fill: 'none'
});
this.svg.appendChild(this.svg_selected);
// scrolling controls on top
this.svg.appendChild(this.svg_controls(24,24));
// module name
this.svg_module_name = jade.utils.svg_text('',4,4,'left','bottom',{
style: 'font: 12pt sans-serif',
fill: this.normal_style,
stroke: 'none'
});
this.svg.appendChild(this.svg_module_name);
this.canvas.tabIndex = 1; // so we get keystrokes
// initial state
this.dragging = false;
this.select_rect = undefined;
this.annotations = [];
this.show_grid = true;
this.origin_x = 0;
this.origin_y = 0;
this.scale = 1;
this.cursor_x = 0;
this.cursor_y = 0;
this.unsel_bbox = [Infinity, Infinity, - Infinity, - Infinity];
this.bbox = [0, 0, 0, 0];
}
// fetch attributes from the tag that created us
Diagram.prototype.getAttribute = function(attr) {
return undefined;
};
Diagram.prototype.set_aspect = function(aspect) {
this.aspect = aspect;
this.show_grid = true;
this.redraw_background(); // compute bounding box
this.zoomall(); // let's see the whole diagram
};
Diagram.prototype.unselect_all = function(which) {
this.annotations = []; // remove all annotations
this.aspect.map_over_components(function(c, i) {
if (i != which) c.set_select(false);
});
};
Diagram.prototype.remove_annotations = function() {
this.unselect_all();
this.redraw_background();
};
Diagram.prototype.add_annotation = function(callback) {
this.annotations.push(callback);
this.redraw();
};
Diagram.prototype.drag_begin = function() {
// let components know they're about to move
var cursor_grid = 1;
this.aspect.map_over_components(function(c) {
if (c.selected) {
c.move_begin();
cursor_grid = Math.max(cursor_grid, c.required_grid);
}
});
this.set_cursor_grid(cursor_grid);
// remember where drag started
this.drag_x = this.cursor_x;
this.drag_y = this.cursor_y;
this.dragging = true;
};
Diagram.prototype.drag_end = function() {
// let components know they're done moving
this.aspect.map_over_components(function(c) {
if (c.selected) c.move_end();
});
this.dragging = false;
this.aspect.end_action();
this.editor.diagram_changed(this);
this.redraw_background();
};
Diagram.prototype.zoomin = function() {
var nscale = this.scale * this.zoom_factor;
if (nscale < this.zoom_max) {
// keep center of view unchanged
this.origin_x += ($(this.canvas).width() / 2) * (1.0 / this.scale - 1.0 / nscale);
this.origin_y += ($(this.canvas).height() / 2) * (1.0 / this.scale - 1.0 / nscale);
this.scale = nscale;
this.redraw_background();
}
};
Diagram.prototype.zoomout = function() {
var nscale = this.scale / this.zoom_factor;
if (nscale > this.zoom_min) {
// keep center of view unchanged
this.origin_x += ($(this.canvas).width() / 2) * (1.0 / this.scale - 1.0 / nscale);
this.origin_y += ($(this.canvas).height() / 2) * (1.0 / this.scale - 1.0 / nscale);
this.scale = nscale;
this.redraw_background();
}
};
Diagram.prototype.zoomall = function() {
// w,h for diagram including a margin on all sides
var diagram_w = 1.5 * (this.bbox[2] - this.bbox[0]);
var diagram_h = 1.5 * (this.bbox[3] - this.bbox[1]);
if (diagram_w === 0) this.scale = 1;
else {
// compute scales that would make diagram fit, choose smallest
var scale_x = $(this.canvas).width() / diagram_w;
var scale_y = $(this.canvas).height() / diagram_h;
this.scale = Math.pow(this.zoom_factor,
Math.ceil(Math.log(Math.min(scale_x, scale_y)) / Math.log(this.zoom_factor)));
if (this.scale < this.zoom_min) this.scale = this.zoom_min;
else if (this.scale > this.zoom_max) this.scale = this.zoom_max;
}
// center the diagram
this.origin_x = (this.bbox[2] + this.bbox[0]) / 2 - $(this.canvas).width() / (2 * this.scale);
this.origin_y = (this.bbox[3] + this.bbox[1]) / 2 - $(this.canvas).height() / (2 * this.scale);
this.redraw_background();
};
function diagram_toggle_grid(diagram) {
diagram.show_grid = !diagram.show_grid;
$(diagram.canvas).css('background-color',diagram.show_grid ? diagram.background_style : 'white');
diagram.redraw_background();
}
function diagram_undo(diagram) {
diagram.aspect.undo();
diagram.unselect_all(-1);
diagram.redraw_background();
}
function diagram_redo(diagram) {
diagram.aspect.redo();
diagram.unselect_all(-1);
diagram.redraw_background();
}
function diagram_cut(diagram) {
// clear previous contents
clipboards[diagram.editor.editor_name] = [];
// look for selected components, move them to clipboard.
diagram.aspect.start_action();
diagram.aspect.map_over_components(function(c) {
if (c.selected) {
c.remove();
clipboards[diagram.editor.editor_name].push(c);
}
});
diagram.aspect.end_action();
diagram.editor.diagram_changed(diagram);
// update diagram view
diagram.redraw();
}
function diagram_copy(diagram) {
// clear previous contents
clipboards[diagram.editor.editor_name] = [];
// look for selected components, copy them to clipboard.
diagram.aspect.map_over_components(function(c) {
if (c.selected) clipboards[diagram.editor.editor_name].push(c.clone(c.coords[0], c.coords[1]));
});
diagram.redraw(); // digram didn't change, but toolbar status may have
}
function diagram_paste(diagram,keystroke) {
var clipboard = clipboards[diagram.editor.editor_name];
var i, c;
// compute left,top of bounding box for origins of
// components in the clipboard
var left;
var top;
var cursor_grid = 1;
for (i = clipboard.length - 1; i >= 0; i -= 1) {
c = clipboard[i];
left = left ? Math.min(left, c.coords[0]) : c.coords[0];
top = top ? Math.min(top, c.coords[1]) : c.coords[1];
cursor_grid = Math.max(cursor_grid, c.required_grid);
}
diagram.set_cursor_grid(cursor_grid);
left = diagram.on_grid(left);
top = diagram.on_grid(top);
// clear current selections
diagram.unselect_all(-1);
diagram.redraw_background(); // so we see any components that got unselected
// for keystroke, position relative to cursor
// for toolbar button, position relative to original location
var px = keystroke ? diagram.cursor_x : left + 16;
var py = keystroke ? diagram.cursor_y : top + 16;
// make clones of components on the clipboard, positioning
// them relative to the cursor
diagram.aspect.start_action();
for (i = clipboard.length - 1; i >= 0; i -= 1) {
c = clipboard[i];
var new_c = c.clone(px + (c.coords[0] - left), py + (c.coords[1] - top));
new_c.set_select(true);
new_c.add(diagram.aspect);
}
diagram.aspect.end_action();
diagram.editor.diagram_changed(diagram);
// see what we've wrought
diagram.redraw();
}
Diagram.prototype.set_cursor_grid = function(g) {
this.cursor_grid = g;
this.cursor_x = this.on_grid(this.aspect_x);
this.cursor_y = this.on_grid(this.aspect_y);
};
// determine nearest grid point
Diagram.prototype.on_grid = function(v, grid) {
if (grid === undefined) grid = this.cursor_grid;
if (v < 0) return Math.floor((-v + (grid >> 1)) / grid) * -grid;
else return Math.floor((v + (grid >> 1)) / grid) * grid;
};
// rotate selection about center of its bounding box
Diagram.prototype.rotate = function(rotation) {
var bbox = this.aspect.selected_bbox();
var grid = this.aspect.selected_grid();
// compute center of bounding box, ensure it's on grid
var cx = this.on_grid((bbox[0] + bbox[2]) >> 1, grid);
var cy = this.on_grid((bbox[1] + bbox[3]) >> 1, grid);
this.aspect.start_action();
// rotate each selected component relative center of bbox
this.aspect.map_over_components(function(c) {
if (c.selected) {
c.move_begin();
c.rotate(rotation, cx, cy);
}
});
// to prevent creep, recompute bounding box and move
// to old center
bbox = this.aspect.selected_bbox();
var dx = cx - this.on_grid((bbox[0] + bbox[2]) >> 1, grid);
var dy = cy - this.on_grid((bbox[1] + bbox[3]) >> 1, grid);
this.aspect.map_over_components(function(c) {
if (c.selected) {
if (dx !== 0 || dy !== 0) c.move(dx, dy);
c.move_end();
}
});
this.aspect.end_action();
this.editor.diagram_changed(this);
this.redraw();
};
// flip selection horizontally
function diagram_fliph(diagram) {
diagram.rotate(4);
}
// flip selection vertically
function diagram_flipv(diagram) {
diagram.rotate(6);
}
// rotate selection clockwise
function diagram_rotcw(diagram) {
diagram.rotate(1);
}
// rotate selection counterclockwise
function diagram_rotccw(diagram) {
diagram.rotate(3);
}
Diagram.prototype.resize = function(tw,th) {
if (tw === undefined) {
var c = $(this.canvas);
tw = c.width();
th = c.height();
}
this.svg.setAttribute('viewbox','0 0 '+ tw + ' ' + th);
$(this.svg).width(tw);
$(this.svg).height(th);
this.zoomall();
};