forked from JustusE20/SimpleLogicEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2309 lines (2131 loc) · 79.8 KB
/
Copy pathscript.js
File metadata and controls
2309 lines (2131 loc) · 79.8 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
/* v1.0.5 by Konstantin Fuchs
* v2.0.6 by Wiebke Albers
* v3.0.6 by Justus Epperlein
*/
var globalDeleteActive = false;
var colorActive = "rgb(90, 185, 90)";
var colorStandard = "rgb(250, 90, 71)";
var colorSelected = "lightgrey";
var colorConnectionPoints = "#38393d";
var viewZoom = 0;
var realZoom = 1000;
var inputCount = 0;
var outputCount = 0;
var modulID = 0;
var statusNavigationBar = true;
var widthNavBar = document.getElementById("navigationBar").clientHeight;
var width = 100;
var height = 90;
var select = document.getElementById("select");
const gridSize = 15;
//#region prototype additional functions
/* W.A.
* hide dropdown menus when loading the web page
*/
document.getElementById("myDropdownLogic").style.display = "none";
document.getElementById("myDropdownSave").style.display = "none";
/* K.F.
* changes the textbox color to orange when an error appears
*/
const textBox = document.getElementById("term");
textBox.addEventListener('showError', e => { showError(d3.select(e.target)); });
/* W.A.
* rightclick in simulation area: show most important buttons of navigation bar as dropdown list
*/
const logicBox = document.getElementById("simulationBox");
logicBox.addEventListener('contextmenu', function (event) {
event.preventDefault();
var top = event.clientY - logicBox.clientHeight - widthNavBar - 30;
var left = event.clientX - 10;
dropdownMenu(3, top, left);
});
/** K.F.
* moves an svg element to the lowest z-level
*/
d3.selection.prototype.moveToBack = function () {
return this.each(function () {
var firstChild = this.parentNode.firstChild;
if (firstChild) {
this.parentNode.insertBefore(this, firstChild);
}
});
};
/** K.F.
* swaps the two elements in the array
*
* @param {number} x the index of one of the elements to be exchanged
* @param {number} y the index of the other of the elements to be exchanged
*/
Array.prototype.swap = function (x, y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
};
/** W.A.
* Closes the dropdown menu if the user clicks outside of it
*/
window.onclick = function(event) {
if (!event.target.matches('.dropdownButton') && !event.target.matches('.dropdown-content a')){
var clickLogic = document.getElementById("myDropdownLogic");
var clickSave = document.getElementById("myDropdownSave");
var clickMenu = document.getElementById("myDropdownMenu");
clickLogic.style.display ="none";
clickSave.style.display ="none";
clickMenu.style.display ="none";
}
}
//#endregion
//#region functions
/** W.A.
* Shows developer information
*/
function about(){
alert("v1.0.5 by Konstantin Fuchs \nv2.0.6 by Wiebke Albers \nv3.0.6 by Justus Epperlein \nUnder the supervision of Prof. Dr. Rüdiger Heintz");
}
/** K.F./W.A.
* adds an SVG element to the DOM and reads the equation that may have been added to the URL
*/
function onLoad(){
try {
setWinParam();
var initVal = (decodeURI(window.location.hash.slice(1)));
d3.select(".frame").append("svg").attr("id", "svg").attr("viewBox", "0 0 " + realZoom + " 100").attr("preserveAspectRatio", "xMinYMin meet");
}
catch { }
if (typeof initVal != "undefined" || initVal != "") {
document.getElementById("term").value = initVal;
firstCharacter = initVal.slice(0,1);
if(firstCharacter == "[" || firstCharacter == "{"){
deserializeLogic();
}
else{
if (initVal) {
draw(initVal);
}
}
}
else term = "";
}
///////// Begin implementation of URL window-informtion
/** W.A.
* Set parameters of window-size, view, appearance
*/
function setWinParam(){
var urlParam = new URLSearchParams(document.location.search);
width = JSON.parse(urlParam.get('width'));
height = JSON.parse(urlParam.get('height'));
viewZoom = JSON.parse(urlParam.get('viewZoom'));
statusNavigationBar = JSON.parse(urlParam.get('statusNavigationBar'));
if(width != null && height != null){
document.getElementById("navigationBar").style.width = width + 'px';
document.getElementById("simulationBox").style.width = width + 'px';
document.getElementById("simulationBox").style.height = height + 'vh';
}
if(statusNavigationBar == false && height == null){
height = 85;
}
calcZoom();
toggleNavigationBar();
}
/** W.A.
* calculates Zoom out of window size
*/
function calcZoom(){
var absoluteWidth = document.body.offsetWidth;
var zoomRatio = absoluteWidth / 1000;
realZoom = (realZoom - viewZoom) *zoomRatio;
}
/** W.A.
* hide/show dropdown menu depending on which dropdown menu has been activated
*/
function dropdownMenu(number, x, y){
if(number == 1){
var click = document.getElementById("myDropdownLogic");
}
else if(number == 2){
var click = document.getElementById("myDropdownSave");
}
else if(number == 3){
var click = document.getElementById("myDropdownMenu");
click.style.top = x + "px";
click.style.left = y + "px";
}
if(click.style.display ==="none") {
click.style.display ="block";
}
else {
click.style.display ="none";
}
}
/** W.A.
* Show/hide of the navigation bar
*/
function toggleNavigationBar(toggle){
if(toggle == true){
statusNavigationBar = !statusNavigationBar;
}
if(statusNavigationBar == false){
height = height + 8;
document.getElementById("navigationBar").style.display = 'none';
}
else if(statusNavigationBar == true){
if(toggle == true){height = height - 8;}
document.getElementById("navigationBar").style.display = '';
}
}
///////// End implementation of URL window-informtion
/** K.F.
* lets the element light up in the highlight color
* @param {Object} element the d3 selection of the element to be highlighted
*/
function showError(element) {
element.transition().duration(500).style("background-color", colorActive);
element.transition().duration(500).delay(500).style("background-color", "white");
}
/** K.F.
* toggles the state of the global variable globalDeleteActivate
*/
function toggleDelete() {
if (globalDeleteActive) {
globalDeleteActive = false;
}
else {
globalDeleteActive = true;
}
}
/** K.F.
* reduces the view of the svg canvas
*/
function zoomIn() {
viewZoom += 50;
realZoom -= 50;
d3.select("#svg").attr("viewBox", "0 0 " + realZoom + " 100");
}
/** K.F.
* enlarges the view of the svg canvas
*/
function zoomOut() {
viewZoom -= 50;
realZoom += 50;
d3.select("#svg").attr("viewBox", "0 0 " + realZoom + " 100");
}
/** J.E.
* selection of an area on the canvas
*/
var selectionArea = {
x1: 0,
y1: 0,
x2: 0,
y2: 0,
drawSelection: function() { //Draws selection box and marks the modules inside the area
var x3 = Math.min(this.x1, this.x2);
var x4 = Math.max(this.x1, this.x2);
var y3 = Math.min(this.y1, this.y2);
var y4 = Math.max(this.y1, this.y2);
select.style.left = x3 + 'px';
select.style.top = y3 + 'px';
select.style.width = x4 - x3 + 'px';
select.style.height = y4 - y3 + 'px';
x3 = x3*realZoom/(realZoom + viewZoom);
x4 = x4*realZoom/(realZoom + viewZoom);
y3 = y3*realZoom/(realZoom + viewZoom);
y4 = y4*realZoom/(realZoom + viewZoom);
var moduleList = new ModuleManager().getModuleList();
for(var i=0; i < moduleList.length; i++) {
var element = moduleList[i];
if(x3 < element.getX() && element.getX() < x4 && y3 < element.getY() && element.getY() < y4) {
element.group.select("rect").attr("fill", colorSelected);
element.selected = true;
} else {
element.group.select("rect").attr("fill", "transparent");
element.selected = false;
}
}
},
setSelection: function(x1, y1, x2, y2) { //Sets all coordinates of selection area
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
},
};
onmousedown = function(e) {
if(e.clientY > (widthNavBar + 10) && !e.target.matches('.dropdown-content a') && !e.target.matches('.d3-context-menu ul li') && e.button === 0) {
select.hidden = 0;
selectionArea.setSelection(e.clientX - 10, e.clientY - 65, e.clientX - 10, e.clientY - 65);
selectionArea.drawSelection();
}
};
onmousemove = function(e) {
if(select.hidden == 0) {
selectionArea.x2 = e.clientX - 10;
if(e.clientY > (widthNavBar + 10)) {
selectionArea.y2 = e.clientY - 65;
} else {
selectionArea.y2 = widthNavBar - 50;
}
selectionArea.drawSelection();
}
};
onmouseup = function(e) {
select.hidden = 1;
selectionArea.setSelection(0, 0, 0, 0);
};
/** J.E.
* return Array of single selected module or all marked modules
* @param {Module} module the selected module
*/
function getSelection(module) {
var selectionList = new Array();
if(module.selected) {
var moduleList = new ModuleManager().getModuleList();
for(var i=0; i < moduleList.length; i++) {
if(moduleList[i].selected) {
selectionList.push(moduleList[i]);
}
}
} else {
selectionList.push(module);
}
return selectionList;
}
///////// Begin save logic with button
/** W.A.
* Converts logic objects to JSON-string and write it in URL
*/
function pushToURL(){
var urlParam = new URLSearchParams(document.location.search);
var textLogic = serializeLogic();
urlParam.set('statusNavigationBar', statusNavigationBar);
urlParam.set('viewZoom', viewZoom);
urlParam.set('width', width);
urlParam.set('height', height);
history.pushState(null, null, "?"+urlParam);
textLogic = textLogic[2] + "delimiter" + textLogic[3];
var encodedLogic = encodeURI(textLogic);
history.pushState(null, null, "#"+encodedLogic);
navigator.clipboard.writeText("?" + urlParam + "#" + encodedLogic);
alert("?" + urlParam + "#" + encodedLogic);
}
/** W.A.
* copies serialized logic into clipboard
*/
function copyText() {
var textLogic = serializeLogic();
var copy = textLogic[2] + "delimiter" + textLogic[3];
if ((textLogic[0].length < 1) && (textLogic[1].length < 1)) {
alert("No objects to copy!");
}
else {
document.getElementById("term").value = copy;
navigator.clipboard.writeText(copy);
alert("Module count: " + textLogic[0].length + "\nConnection count: " + textLogic[1].length + "\n\nSaved:\n" + textLogic[2] + "delimiter" + textLogic[3]);
}
}
/** W.A.
* saves text as .txt-file
*/
function saveTxt() {
var textLogic = serializeLogic();
var date = new Date();
if ((textLogic[0].length < 1) && (textLogic[1].length < 1)) {
alert("No ojects to save!");
}
else {
var text = document.createElement("a");
text.href = window.URL.createObjectURL(new Blob([textLogic[2] + "delimiter" + textLogic[3]], { type: "text/plain" }));
text.download = "LogicToText_" + date + ".txt";
text.click();
}
}
/** W.A.
* Serialization of drawn object-assembly
* Converts generated logic into JSON-text
* Possibility to save logic for later use
*/
function serializeLogic()
{
var listModules = new ModuleManager().getModuleList();
var listConnections = new ConnectionManager().getConnectionList();
var jsonModules = [];
var jsonConnections = [];
// Serialize only specific properties to aviod circular loops because of connections
jsonModules.push(JSON.stringify(listModules,['classname','text','id','value',
'x','y','width','height',
'maxInputCount','maxOutputCount',
'outputOffset','inputOffset']));
jsonConnections.push(JSON.stringify(listConnections,['classname','inputID','outputID',
'gridPointsX','gridPointsY', 'parent']));
var textLogic = [listModules, listConnections, jsonModules, jsonConnections];
return textLogic;
}
///////// End save logic with button
///////// Begin draw logic from JSON
/** W.A.
* Converts gernerated text back into objects
*/
function deserializeLogic()
{
var text = document.getElementById("term").value;
var firstCharacter = text.slice(0,1);
if(firstCharacter == "[" || firstCharacter == "{"){
var JSONarray = text.split('delimiter');
var listModulesOld = JSON.parse(JSONarray[0]);
var listConnectionsOld = JSON.parse(JSONarray[1]);
changeModuleID(listModulesOld);
listModulesOld.forEach(function(module){
if(module.classname == "INPUT" || module.classname == "OUTPUT"){
module.value = !module.value;
eval("Object.assign(new " + module.classname + "(module.x, module.y, module.text), module);")
}
else{
eval("Object.assign(new " + module.classname + "(module.x, module.y, module.maxInputCount), module);")
}
});
var listModulesNew = new ModuleManager().getModuleList();
var listConnectedModules = [];
listConnectionsOld.forEach(function(connection){
listConnectedModules.push(connection.outputID);
var inputIndex = listConnectedModules.filter(outID => outID == connection.outputID)
createConnection(connection, listModulesNew, inputIndex.length-1);
})
var listConnectionsNew = new ConnectionManager().getConnectionList();//J.E.
listConnectionsNew.forEach(function(connection){
connection.latch();
})
}
else{
draw(text);
}
}
/** W.A.
* Creates connection between reloaded modules based on their moduleID
* @param {CONNECTION} connection the connection to be drawn
* @param {Array} listModulesNew list of modules which can be connected
* @param {number} inputIndex number of input (relevant for modules with several inputs)
*/
function createConnection(connection, listModulesNew, inputIndex)
{
var startObject = listModulesNew.find(obj => obj.id == connection.inputID);
var endObject = listModulesNew.find(obj => obj.id == connection.outputID);
var newConnection = new CONNECTION(connection.gridPointsX, connection.gridPointsY);
if(connection.parent != null) { //J.E.
var listConnectionsNew = new ConnectionManager().getConnectionList();
for(var i = 0; i < listConnectionsNew.length; i++) {
var newParent = listConnectionsNew[i];
var oldParent = connection.parent;
var foundParent = true;
for(var j = 0; j < newParent.gridPointsX.length; j++) {
if(newParent.gridPointsX[j] != oldParent.gridPointsX[j] || newParent.gridPointsY[j] != oldParent.gridPointsY[j]) {
foundParent = false;
break;
}
}
if(foundParent) {
newParent.branches.push(newConnection);
newConnection.parent = newParent;
break;
}
}
}
try{
connect(startObject, newConnection, endObject, inputIndex);
startObject.checkActivated();
}
catch{
alert("Connection did not work!");
}
}
/** W.A.
* Changes id of currently plotted modules to avoid doublings when deserialize logic with 'old' ids
* Identify highest id in module-list (all lower ids are reserved for deserialization)
* @param {Array} listOldModules
*/
function changeModuleID(listModulesOld){
var listIDs = [];
listModulesOld.forEach(function(module){listIDs.push(module.id);});
var maxID = Math.max.apply(null, listIDs);
var listModulesNow = new ModuleManager().getModuleList();
if(listModulesNow.length != 0){
listModulesNow.forEach(function(module){
module.id = maxID + 1;
maxID++;
});
}
}
///////// End draw logic from JSON
///////// Begin draw logic from equation
/** K.F.
* initiates the process of drawing the equation
* @param {String} text the raw text that was entered and is to be drawn
*/
function draw(text) {draw
var parser = new Parser(text);
var variables = parser.getVariables()
var inputList = new Array(variables.length);
var buffer = new Array();
var lastElement = null;
try {
//drawing all necessary inputs
for (var i = 0; i < variables.length; i++) {
var input = new INPUT(15, 15, variables[i]);
buffer.push(input);
inputList[i] = place(input);
}
//drawing all modules
lastElement = buildEquation(variables, parser.getEquation(), inputList, buffer);
//drawing the output
if (lastElement != null) {
var output = place(new OUTPUT(210, 30, parser.getResult()));
buffer.push(output);
connect(lastElement, new CONNECTION([0, 0, 0, 0], [0, 0, 0, 0]), output, 0);
lastElement.checkActivated();
}
}
catch
{
//in the case of an exception, the elements drawn so far are deleted and the event showError is dispatched
for (var i = buffer.length; i >= 0; i--) {
if (buffer[i] != null) buffer.pop().delete();
}
var event = new CustomEvent('showError');
textBox.dispatchEvent(event);
}
}
/** K.F.
* draws the given equation
* @param {String[]} variables list of variables
* @param {String[]} equation the equation to be drawn
* @param {INPUT[]} inputList list of the inputs generated from the variables
* @param {Module[]} buffer the buffer in which every automatically generated module is cached so that it can be deleted in the event of an error
*/
function buildEquation(variables, equation, inputList, buffer) {
var innerBrackets = new Array();
var openBrackets = 0;
var searchBracketsLevel = 0;
var inBrackets = false;
var equationMerge = new Array();
//find brackets and save them in InnerBrackets
for (var i = 0; i < equation.length; i++) {
if (inBrackets) {
innerBrackets[innerBrackets.length - 1].push(equation[i]);
}
else if (equation[i] != "(") {
equationMerge.push(equation[i]);
}
if (equation[i] == "(") {
openBrackets++;
if (!inBrackets) {
innerBrackets.push(new Array());
searchBracketsLevel = openBrackets;
inBrackets = true;
}
}
else if (equation[i] == ")") {
if (inBrackets && searchBracketsLevel == openBrackets) {
searchBracketsLevel = openBrackets;
inBrackets = false;
innerBrackets[innerBrackets.length - 1].pop();
equationMerge.push(innerBrackets.length - 1);
}
openBrackets--;
}
}
//first build brackets with buildEquation (recursion)
var outputList = new Array(innerBrackets.length);
for (var i = 0; i < innerBrackets.length; i++) {
outputList[i] = buildEquation(variables, innerBrackets[i], inputList, buffer);
}
//draw the module and connect the inputs
var module = null;
var input;
switch (equationMerge[1]) {
case "ᴧ":
module = place(new AND(120, 15, 2));
break;
case "↑":
module = place(new NAND(120, 15, 2));
break;
case "ᴠ":
module = place(new OR(120, 15, 2));
break;
case "↓":
module = place(new NOR(120, 15, 2));
break;
case "¬":
module = place(new NOT(120, 15, 2));
break;
case "⊕":
module = place(new XOR(120, 15, 2));
break;
case "⊙":
module = place(new XNOR(120, 15, 2));
break;
}
if (module != null) {
buffer.push(module);
if (isNaN(equationMerge[0])) {
input = inputList[variables.indexOf(equationMerge[0])];
}
else {
input = outputList[equationMerge[0]];
}
connect(input, new CONNECTION([0, 0, 0, 0], [0, 0, 0, 0]), module, 0);
input.checkActivated();
if (equationMerge.length > 2) {
if (isNaN(equationMerge[2])) {
input = inputList[variables.indexOf(equationMerge[2])];
}
else {
input = outputList[equationMerge[2]];
}
connect(input, new CONNECTION([0, 0, 0, 0], [0, 0, 0, 0]), module, 1);
input.checkActivated();
}
}
else {
if (outputList) {
module = outputList[0];
}
}
return module;
}
///////// End draw logic from equation
/** K.F.
* takes the given element and moves it in y direction until it no longer touches any other module
* @param {Module} element the element to be placed
*/
function place(element) {
while (isTouching(element)) {
element.dMove(0, gridSize);
}
return element;
}
/** K.F.
* determines whether the specified element touches another module
* @param {Module} element the element which should be checked
*/
function isTouching(element) {
var elementLeft = element.getX();
var elementRight = element.getX() + element.width;
var elementTop = element.getY();
var elementBottom = element.getY() + element.height;
var moduleList = new ModuleManager().getModuleList();
var elementsList = new Array();
//adds the elements which lead to collisions in the x direction to the "elementsList" list
for (var i = 0; i < moduleList.length; i++) {
var moduleLeft = moduleList[i].getX();
var moduleRight = moduleList[i].getX() + moduleList[i].width;
if ((elementLeft <= moduleRight && elementRight >= moduleLeft) || (moduleLeft <= elementRight && moduleRight >= elementLeft)) {
elementsList.push(moduleList[i]);
}
}
//returns true if an element in the "elementsList" list leads to collisions in the y direction
for (var i = 0; i < elementsList.length; i++) {
var moduleTop = elementsList[i].getY();
var moduleBottom = elementsList[i].getY() + elementsList[i].height;
if ((element != elementsList[i]) && ((elementTop <= moduleBottom && elementBottom >= moduleTop) || (moduleTop <= elementBottom && moduleBottom >= elementTop))) {
return true;
}
}
return false;
}
/** K.F./J.E.
* lets the given module and its connections follow the movement of the mouse
* @param {Array} modules selection of modules to be moved
* @param {boolean} dragMode chooses drag or latch mode
*/
function dragMove(modules, dragMode) {
for(var h = 0; h < modules.length; h++) {
var module = modules[h];
if(dragMode) {
var dx = d3.event.dx;
var dy = d3.event.dy;
} else {
var dx = nextGridPoint(module.x) - module.x;
var dy = nextGridPoint(module.y) - module.y;
}
module.dMove(dx, dy);
if (module.output.length > 0) {
for (var i = 0; i < module.output.length; i++) {
module.output[i].dMoveStart(dx, dy);
}
}
if (module.input.length > 0) {
for (var i = 0; i < module.input.length; i++) {
for (var j = 0; j < module.input[i].length; j++) {
module.input[i][j].dMoveEnd(dx, dy);
for(var k = 0; k < module.input[i][j].branches.length; k++) {//J.E.
module.input[i][j].branches[k].dMoveStart(dx, dy);
}
}
}
}
}
}
/** K.F.
* lets the end of the given connection follow the movement of the mouse
* @param {CONNECTION} connection the connection to be moved
*/
function dragConnection(connection) {
var dx = d3.event.dx;
var dy = d3.event.dy;
connection.dMoveEnd(dx, dy);
}
/** J.E.
* calculates nearest grid point of current coordinate
* @param {number} coordinate the coordinate to be used
*/
function nextGridPoint(coordinate) {
var res = Math.round(coordinate/gridSize)*gridSize;
return res;
}
/** J.E.
* deletion of all modules inside an array
* @param {Array} modules the connection to be moved
*/
function deleteSelection(modules) {
for(var i = 0; i < modules.length; i++) {
modules[i].delete();
}
}
/** K.F.
* connects two modules with a given connection element
* @param {Module} outElement the module whose output is to be connected with the connection element
* @param {CONNECTION} connectionElement the connection element which should be used for the connection
* @param {Module} inElement the module whose input is to be connected with the connection element
* @param {number} inElementInputIndex indicates to which input the connection element is to be connected
* @param {boolean} value indicates whether the connection should be activated
*/
function connect(outElement, connectionElement, inElement, inElementInputIndex, value) {
try {
if (outElement != null) {
outElement.addOutput(connectionElement);
connectionElement.moveStart(outElement.getX() + outElement.getOutputOffset()[0], outElement.getY() + outElement.getOutputOffset()[1]);
connectionElement.setInput(outElement);
}
if (value != null) {
connectionElement.setValue(value);
}
inElement.input[inElementInputIndex].push(connectionElement);
connectionElement.output = inElement;
connectionElement.outputID = inElement.id;
connectionElement.setOutputInputIndex(inElementInputIndex);
connectionElement.moveEnd(inElement.getX() + inElement.getInputOffset(inElementInputIndex)[0], inElement.getY() + inElement.getInputOffset(inElementInputIndex)[1]);
return true;
}
catch (x) {
//no connection possible
return false;
}
}
/** K.F.
* creates a context menu
* @param {Module} element element that triggered the context menu
*/
function menuLogic(element) {
//describing the context menu
var menu =
[
{
title: "replace...",
children:
[
{
title: "INPUT",
action: function () {
element.replace(new INPUT(element.x, element.y), element.id);
},
},
{
title: "AND",
action: function () {
element.replace(new AND(element.x, element.y, element.maxInputCount), element.id);
},
},
{
title: "NAND",
action: function () {
element.replace(new NAND(element.x, element.y, element.maxInputCount), element.id);
},
},
{
title: "OR",
action: function () {
element.replace(new OR(element.x, element.y, element.maxInputCount), element.id);
},
},
{
title: "NOR",
action: function () {
element.replace(new NOR(element.x, element.y, element.maxInputCount), element.id);
},
},
{
title: "XOR", // J.E.
action: function () {
element.replace(new XOR(element.x, element.y, element.maxInputCount), element.id);
},
},
{
title: "XNOR", // J.E.
action: function () {
element.replace(new XNOR(element.x, element.y, element.maxInputCount), element.id);
},
},
{
title: "NOT",
action: function () {
element.replace(new NOT(element.x, element.y), element.id);
},
},
{
title: "OUTPUT",
action: function () {
element.replace(new OUTPUT(element.x, element.y), element.id);
},
},
],
},
{
title: "change input number", // W.A.
children:
[
{
title: "2",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 2, element.id);
},
},
{
title: "3",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 3, element.id);
},
},
{
title: "4",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 4, element.id);
},
},
{
title: "5",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 5, element.id);
},
},
{
title: "6",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 6, element.id);
},
},
{
title: "7",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 7, element.id);
},
},
{
title: "8",
action: function () {
element.changeInputNumber(element.constructor.name, element.x, element.y, 8, element.id);
},
},
],
},
{
title: "rename", // J.E.
action: function () {
element.renameModule(element.constructor.name, element.x, element.y, element.id);
},
},
{
divider: true,
},
{
title: 'delete',
action: function () {
deleteSelection(getSelection(element)); //J.E.
}
}
];
//open the context menu
d3.contextMenu(menu)();
}
//#endregion
//#region classes
/** K.F.
* converts a raw text into a further processable equation and filters variables and result variables
*/
class Parser {
/**
* initializes all variables and calls the necessary methods to make the raw text usable
* @param {String} text the raw text that should be made usable
*/
constructor(text) {
this.array;
this.input;
this.vars;
try {
this.input = changeOperator(text);
this.input = changeSpaces(this.input);
this.array = checkInputOnEquals(this.input);
this.input = removeResultName(this.array);
this.vars = varFilter(this.input);
this.vars.pop();
this.array[0] = checkResultName(this.vars, this.array[0], this.array[2]);
this.equation = this.formEquation(this.array[1]);
this.addBrackets(this.equation);
}
catch (e) {
throw (e);
}
}
/**
* converts the given string to an array and merges variables
* @param {String} text the text to be handled
*/
formEquation(text) {
//convert string to an array, combine variables
var equation = new Array();
var variableList = new Array();
var delimiter = [" ", "(", ")", "ᴧ", "ᴠ", "¬", "⊕", "⊙", "↑", "↓", "="];
var variable;
for (var i = 0; i < text.length; i++) {
if (delimiter.includes(text[i])) {
if (variable != null) {
equation.push(variable);
variableList.push(variable);
variable = null;
}
if (text[i] != " ") {
equation.push(text[i]);
}
}
else {
if (variable == null) {
variable = text[i];
}
else {
variable = variable.concat(text[i]);
}
}
}
if (variable != null) {
equation.push(variable);
variableList.push(variable);
variable = null;
}