-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAppB_Libraries.html
More file actions
824 lines (785 loc) · 39.9 KB
/
AppB_Libraries.html
File metadata and controls
824 lines (785 loc) · 39.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript: AppB Libraries</title>
<meta name="title" content="Variations on a Theme: JavaScript: AppB Libraries">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta charset="UTF-8">
<meta name="description" content="An object-oriented Introduction">
<meta name="keywords" content="JavaScript,object orientation,introduction">
<meta name="author" content="Ralph P. Lano">
<meta name="robots" content="index,follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="book.css">
</head>
<body>
<center>
<div id="wrap">
<ul class="sidenav">
<p><a href="../index.html">Variations on a Theme</a><a href="index.html">JavaScript</a></p>
<li><a href="Ch1_Karel.html">Karel</a></li>
<li><a href="Ch2_Graphics.html">Graphics</a></li>
<li><a href="Ch3_Console.html">Console</a></li>
<li><a href="Ch4_Agrar.html">Agrar</a></li>
<li><a href="Ch5_MindReader.html">MindReader</a></li>
<li><a href="Ch6_Swing.html">Swing</a></li>
<li><a href="Ch7_Asteroids.html">Asteroids</a></li>
<li><a href="Ch8_Stocks.html">Stocks</a></li>
<li><a href="index.html"> </a></li>
<li><a href="AppA_Primer.html">Primer</a></li>
<li><a href="AppB_Libraries.html">Libraries</a></li>
<li><a href="AppC_Ideas.html">Ideas</a></li>
</ul>
<div class="content">
<h1>
Libraries</h1>
<p>
How does it all work? In this chapter we take a look behind the scenes. If you look at the tryItFrame.html file, you will notice the following imports in the head section:</p>
<pre style="margin-left: 40px;">
<head>
...
<!-- order is importent! -->
<script src="./libraries/p5.min.js"></script>
<!-- <script src="./libraries/p5.sound.min.js"></script> -->
<script src="./libraries/<span style="color:#0000ff;">gui.js</span>"></script>
<script src="./libraries/<span style="color:#0000ff;">graphics.js</span>"></script>
<script src="./libraries/<span style="color:#0000ff;">console.js</span>"></script>
<script src="./libraries/<span style="color:#0000ff;">utils.js</span>"></script>
</head>
</pre>
<p>
The first library is the standard p5.js library from Processing. The other four are what we will explain on the pages below.</p>
<p>
.</p>
<h2>
Console Programs</h2>
<p>
A console program is an HTML text area widget that is used to display text. Console programs are very simple, and you can use the following commands</p>
<ul>
<li>
print()</li>
<li>
println()</li>
<li>
readLine()</li>
<li>
readInt()</li>
<li>
readDouble()</li>
<li>
clear()</li>
</ul>
<p>
Using a text area widget for a console seems straight forward, but there are a few things that makes this tricky:</p>
<ol>
<li>
the functions print() and clear() are already defined in p5.js</li>
<li>
there is no read() function, the only thing that allows user input is the prompt() function</li>
</ol>
<h3>
Example</h3>
<p>
A simple example of our console program looks like this:</p>
<pre style="margin-left: 40px;">
<span style="color:#ff0000;">async</span> function setup() {
<span style="color:#0000ff;">createConsole</span>();
<span style="color:#0000ff;">println</span>('This program adds two numbers.');
let n1 = <span style="color:#ff0000;">await</span> <span style="color:#0000ff;">readInt</span>('Enter number one: ');
let n2 = <span style="color:#ff0000;">await</span> <span style="color:#0000ff;">readInt</span>('Enter number two: ');
let sum = n1 + n2;
<span style="color:#0000ff;">println</span>( 'The sum is: ' + sum );
}</pre>
<p>
You may notice the somewhat unusual <em>async</em> and <em>await</em> keywords. More on this in a moment.</p>
<h3>
print() and clear()</h3>
<p>
Since both print() and clear() already exist, we need to redefine them. This is done in the createConsole() function:</p>
<pre style="margin-left: 40px;">
function createConsole(_ROWS, _COLS) {
// redefine print():
print = function (msg) {
if (msg === undefined) {
msg = '';
}
// textarea.append(msg);
textarea.value += msg;
}
// redefine clear():
clear = function () {
textarea.value = '';
}
}
</pre>
<h3>
readLine()</h3>
<p>
The hard part is reading from console. JavaScript only has the prompt to do that. And JavaScript does not have a pause(). One elegant way to get the desired functionality is via promises.</p>
<pre style="margin-left: 40px;">
function readLine(msg) {
if (msg === undefined) {
msg = '';
}
textarea.value += msg;
enterPressed = false;
textEntered = '';
return new Promise((resolveOuter) => {
resolveOuter(
new Promise((resolveInner) => {
var check = function () {
if (enterPressed) {
// print('Enter');
textarea.value += '\n';
resolveInner(textEntered);
} else {
// print('No Enter');
setTimeout(check, 100); // check again in a second
}
}
check();
})
);
});
}</pre>
<p>
This is the reason why we have to use async and await when using any of the read function.</p>
<p>
.</p>
<h2>
Graphics Programs</h2>
<p>
A graphics program uses the HTML canvas tag for drawing and animation. However, we do not use it directly, but instead use p5.js for most of the drawing. Our graphics library is basically a wrapper around p5.js. In our graphics programs you can use the following commands:</p>
<ul>
<li>
add(obj, x, y)</li>
<li>
getElementAt(x, y)</li>
<li>
getElementsAt(x, y)</li>
<li>
removeAll()</li>
<li>
removeObj(obj)</li>
<li>
setBackground(color)</li>
<li>
update()</li>
</ul>
<h3>
p5.js</h3>
<p>
p5.js comes from the Processing Foundation, that also created Processing for Java. The idea is very similar, make JavaScript as easy to use as possible. We use p5.js, because it is well developed and maintained, and it runs on most browsers, even the mobile ones. Also, a key feature is its support and abstraction for various hardware, such as webcam and microphone, but also playing videos and 3D drawing are made easy with p5.js.</p>
<p>
Basically all p5.js programs have the same structure:</p>
<pre style="margin-left: 40px;">
function setup() {
createCanvas(400, 400);
frameRate(25);
//noLoop();
}
function draw() {
background(220);
ellipse(0, 0, 50, 50);
}</pre>
<p>
The <em>setup()</em> method is called once at the start of the program. In addition there is a <em>draw()</em> method that is called repeatedly, depending on what frame rate was chosen. It is also possible to not call the <em>draw()</em> method at all via the <em>noLoop()</em> command. The <em>ellipse()</em> function is one of p5.js many drawing functions.</p>
<p>
If you save the above code in a file named <em>sketch.js</em>, then the following HTML is all that is needed to run it:</p>
<pre style="margin-left: 40px;">
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/p5@1.6.0/lib/p5.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html></pre>
<p>
Naturally, all the magic lies in the p5.js file.</p>
<h3>
Graphics Objects</h3>
<p>
Writing code in p5.js is not all that object oriented, or rather, there is a strong tendency to not write object oriented code when working with p5.js. For small projects that is perfectly allright. But as soon as things get a little more complicated and objects start interacting, like collisions, or a user clicking on them, things get rather tedious. </p>
<p>
This is why we wrote wrapper graphics objects around the p5.js drawing functions, strongly inspired by the ACM graphics library for Java:</p>
<ul>
<li>
GArc</li>
<li>
GCompound</li>
<li>
GImage</li>
<li>
GLabel</li>
<li>
GLine</li>
<li>
GObject</li>
<li>
GOval</li>
<li>
GPixel</li>
<li>
GPolygon</li>
<li>
GRect</li>
<li>
GVideo</li>
<li>
GVideoPreview</li>
<li>
GWebCam</li>
<li>
GWebCamPreview</li>
</ul>
<p>
Most graphics objects are quite simple, GImage and GCompound maybe a little more involved.</p>
<h3>
Example</h3>
<p>
Just to get an idea how the combination of p5.js and graphics objects work, consider the following example:</p>
<pre style="margin-left: 40px;">
function setup() {
createCanvas(300, 150);
frameRate(5);
let fritz = new GRect(150, 100, 50, 50);
fritz.setColor(color('blue'));
fritz.setFilled(true);
fritz.setFillColor(color('yellow'));
<span style="color:#0000ff;">add(fritz)</span>;
}
function draw() {
<span style="color:#0000ff;">update()</span>;
}</pre>
<p>
In the setup we create the canvas, set the frame rate, and then create a GRect object. In the <em>draw()</em> function we simply call the <em>update()</em> function. The <em>update()</em> function is very simple:</p>
<pre style="margin-left: 40px;">
function update() {
background(backgroundColor);
for (let i = 0; i < gobjects.length; i++) {
gobjects[i].draw();
}
}</pre>
<p>
It iterates through all the gobjects and calls their respective <em>draw()</em> functions. The <em>add()</em> method above, adds graphics objects to the <em>gobjects</em> array.</p>
<pre style="margin-left: 40px;">
function add(obj, x, y) {
if ((x !== undefined) && (y !== undefined)) {
obj.setLocation(x, y);
}
gobjects.push(obj);
}</pre>
<h3>
GObject</h3>
<p>
The class GObject is the parent class of all other graphics objects:</p>
<pre style="margin-left: 40px;">
class GObject {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = 'black';
this.filled = false;
this.fillColor = 'white';
...
}
contains(x, y) {
...
}
...
}</pre>
<p>
Meaning every graphics object has a location and a size, a color, a fillColor and is either filled or not. GObject should be considered an abstract class, but JavaScript does not have that concept.</p>
<p>
As a concrete implementation of GObject we will only consider GRect, all other graphics classes are very similar:</p>
<pre style="margin-left: 40px;">
class GRect extends GObject {
constructor(x, y, width, height) {
if ((width === undefined) && (height === undefined)) {
// new GRect(50,50) has width and height = 50, but x and y = 0!
super(0, 0, x, y);
} else {
super(x, y, width, height);
}
}
draw() {
<span style="color:#0000ff;">noFill</span>();
<span style="color:#0000ff;">stroke</span>(this.color);
<span style="color:#0000ff;">rect</span>(this.x, this.y, this.width, this.height);
}
}</pre>
<p>
Here the functions <em>noFill()</em>, <em>stroke()</em>, and <em>rect()</em> are standard p5.js functions.</p>
<h3>
GImage</h3>
<p>
Of the graphics classes the GImage class is a little more complicated, because loading of images in p5.js happens asynchronously. p5.js has the <em>loadImage(path, [successCallback], [failureCallback])</em> function, which allows for a callback in case of success or failure. Per se, this is not a problem. However, if we want to access the pixels of the image via the <em>getPixelArray()</em> method, there could be a problem: assume it takes a little longer for the image to load, then the call to the <em>getPixelArray()</em> method might happen before the image is loaded.</p>
<p>
To solve this, we need two steps: First, we introduce a property <em>imageLoaded</em>, which initially is set to false, and only after the image has been successfully loaded it will be true. But here comes another subtle problem: the <em>this</em> of the callback is different from the <em>this</em> of our GImage. The standard solution is to get a value on the GImage's <em>this</em> and call it <em>that</em>:</p>
<pre style="margin-left: 40px;">
...
this.pixelArray1 = [];
this.imageLoaded = false;
<span style="color:#0000ff;">let that = this;</span>
this.image = loadImage(imageName, img => {
image(<span style="color:#0000ff;">that</span>.image, <span style="color:#0000ff;">that</span>.x, <span style="color:#0000ff;">that</span>.y);
<span style="color:#0000ff;">that</span>.image.loadPixels();
// remember pixels for modification
for (let i = 0; i < <span style="color:#0000ff;">that</span>.image.pixels.length; i++) {
<span style="color:#0000ff;">that</span>.pixelArray1[i] = <span style="color:#0000ff;">that</span>.image.pixels[i];
}
<span style="color:#0000ff;">that</span>.image.updatePixels();
<span style="color:#0000ff;">that</span>.imageLoaded = true;
});
...
</pre>
<p>
Second, before allowing usage of the <em>getPixelArray()</em> method, we need to make sure, that the image has loaded, i.e. we have to wait until <em>imageLoaded</em> is true. We can do that using a promise:</p>
<pre style="margin-left: 40px;">
getPixelArray() {
return new Promise((resolveOuter) => {
let that = this;
resolveOuter(
new Promise((resolveInner) => {
var check = function () {
if (<span style="color:#0000ff;">that.imageLoaded</span>) {
resolveInner(that.pixelArray1);
} else {
setTimeout(check, 100); // check again in a second
}
}
check();
})
);
});
}</pre>
<p>
Subtle, also here we have to remember the <em>this</em> using <em>that</em>. As I said, it is a little tricky.</p>
<p>
.</p>
<h2>
UI Programs</h2>
<p>
For writing UI programs, we use standard HTML widgets with thin JavaScript wrappers around them. A design challenge was: could you make the resulting code look almost like a Java Swing program? Turns out that very little has to be changed, for the standard HTML widgets to behave like their corresponding Swing counterparts.</p>
<p>
In UI programs you can use the following commands:</p>
<ul>
<li>
createGUI(width, height)</li>
<li>
addWidget(obj, where)</li>
<li>
removeWidget(obj, where)</li>
<li>
setLayout(_layout, _cols)</li>
<li>
addActionListener(obj)</li>
<li>
addChangeListener(obj)</li>
</ul>
<h3>
Example</h3>
<p>
To see how a simple UI program is implemented with our UI library, consider the following example:</p>
<pre style="margin-left: 40px;">
let tf;
function setup() {
createGUI(300, 150);
setLayout('border');
let lbl = new JSLabel("Name: ");
addWidget(lbl, 'SOUTH');
tf = new JSTextField(10);
addWidget(tf, 'SOUTH');
let btn = new JSButton("Login");
addWidget(btn, 'SOUTH');
}
function actionPerformed(ev) {
print("Name: " + tf.getText());
}</pre>
<p>
If you are familiar with Swing, you will recognize the respective classes easily.</p>
<h3>
UI Widgets</h3>
<p>
Just for demonstration purposes we implemented a handful of the UI widgets:</p>
<ul>
<li>
JSObject</li>
<li>
JSLabel</li>
<li>
JSTextField</li>
<li>
JSTextArea</li>
<li>
JSAbstractButton</li>
<li>
JSButton</li>
<li>
JSCheckBox</li>
<li>
JSRadioButton</li>
<li>
JSComboBox</li>
<li>
JSLink</li>
<li>
JSFileUpload</li>
<li>
JSOptionPane</li>
<li>
JSPanel</li>
<li>
JSCanvas</li>
</ul>
<p>
If desired you can add as many as you like. Most are really easy to implement, but somewhat trickier were the JSPanel and the JSCanvas.</p>
<h3>
JSObject</h3>
<p>
The class JSObject is the parent class of all other UI widgets:</p>
<pre style="margin-left: 40px;">
class JSObject {
constructor() {
this.element = document.createElement('span');
}
setStyle(css) {
this.element.style = css;
}
addStyle(css) {
this.element.style.cssText += css;
}
getWidth() {
return this.element.width;
}
getHeight() {
return this.element.height;
}
}</pre>
<p>
Every widget is based on an underlying HTML element, in case of the JSObject it is the <span> tag. Look and feel is changed via cascading style sheets. Being able to use CSS for styling is very convenient. Really, there is not much more to this.</p>
<p>
As a second example, let's look at the JLabel:</p>
<pre style="margin-left: 40px;">
class JSLabel extends JSObject {
constructor(text) {
super();
this.element = document.createElement('span');
this.element.style.padding = DEFAULT_PADDING;
this.element.style.margin = DEFAULT_MARGIN;
this.element.innerHTML = text;
}
getText() {
return this.element.innerHTML;
}
setText(text) {
this.element.innerHTML = text;
}
}</pre>
<p>
I think you get the idea. A side note: if you have read Douglas Crockford's book, then you know that using <em>innerHTML</em> is not such a good idea. If you have not read Douglas Crockford's book, you should.</p>
<h3>
Event Handling</h3>
<p>
Again, we don't really have to do much. The standard HTML events will do just fine. Whenever we add a widget, we add an EventListener for it:</p>
<pre style="margin-left: 40px;">
function addActionListener(obj) {
if (obj instanceof JSAbstractButton) {
obj.element.addEventListener('click',
function (ev) {
let ae = new ActionEvent(ev.target.id, obj);
window.actionPerformed(ae);
}
);
} else if (obj instanceof JSCanvas) {
obj.element.addEventListener('click',
function (ev) {
const rect = obj.element.getBoundingClientRect();
window.canvasClicked(ev.clientX - rect.left,
ev.clientY - rect.top);
}
);
} else if (obj instanceof JSTextField) {
obj.element.addEventListener("keyup",
function (ev) {
if (ev.key === "Enter") {
let ae = new ActionEvent(ev.target.id, obj);
window.actionPerformed(ae);
}
}
);
}
}</pre>
<p>
Adding an EventListener for every widget seems a little overkill, but we do not expect very large programs to be written with this library.</p>
<p>
Just in case you are curious, the ActionEvent is a really thin wrapper around two instance variables, <em>command</em> and <em>source</em>:</p>
<pre style="margin-left: 40px;">
class ActionEvent {
constructor(id, obj) {
this.command = '' + id;
this.source = obj;
}
getActionCommand() {
return this.command;
}
getSource() {
return this.source;
}
}</pre>
<h3>
JSPanel</h3>
<p>
Now the one class that is a really tricky is the JSPanel class. From an HTML point of view it is just a <div> tag. What makes it complicated are two things: first, it can have child widgets, including JSPanels. And second, it can have three different layouts: <em>flow</em>, <em>grid</em> and <em>border</em>. </p>
<h4>
Layout</h4>
<p>
Let's talk about the layouts first: <em>flow</em> and <em>grid</em> are simple, all we do we set the style of the <div> tag. In the case for <em>flow</em> it is one line,</p>
<pre style="margin-left: 40px;">
this.element.style.display = 'inline-block';</pre>
<p>
in the case for <em>grid</em> it is four lines:</p>
<pre style="margin-left: 40px;">
this.element.style.display = 'inline-block';
this.element.setAttribute('class', 'wrapper');
this.element.style.display = 'grid';
this.element.style.gridTemplateColumns =
'repeat(' + _cols + ', ' + Math.trunc(100 / _cols) + '%)';
</pre>
<p>
If you know your CSS the above should make some sense.</p>
<p>
The tricky one is the <em>border</em> layout. For this we use the <em>flex</em> layout. This can be horizontal or vertical. So we are not doing a real border layout, but more of a box layout. But if you combine a horizontal box layout and nest inside it a vertical box layout, you do have a border layout. </p>
<p>
So the first thing we do, we dynamically add a style to an existing HTML page, by inserting it into the <head> tag:</p>
<pre style="margin-left: 40px;">
let stle = document.createElement("style");
stle.innerHTML = ".flexbox-parent {
width: 100%; height: 100%; display: flex; flex-direction: column;
justify-content: flex-start; align-items: stretch; align-content: stretch;}";
stle.innerHTML += ".flexbox-item-grow { flex: 1;}";
stle.innerHTML += ".fill-area-content { overflow: auto;}";
document.getElementsByTagName("head")[0].appendChild(stle);</pre>
<p>
Now, this is totally not needed, and I am sure will cause real problems if you had several of them, but I just thought this is so cool...</p>
<p>
Anyways, once we have the style, we use it:</p>
<pre style="margin-left: 40px;">
this.element.style.display = '';
this.element.setAttribute('class', 'flexbox-parent');
if (_cols == 'horizontal') {
this.element.style.flexDirection = 'row';
}
this.north = new JSPanel('flow');
this.north.element.setAttribute('class', 'flexbox-item header');
this.north.element.setAttribute('align', 'center');
this.element.appendChild(this.north.element);
this.center = new JSPanel('flow');
this.center.element.setAttribute('class', 'fill-area-content flexbox-item-grow');
this.center.element.setAttribute('align', 'center');
this.element.appendChild(this.center.element);
this.south = new JSPanel('flow');
this.south.element.setAttribute('class', 'flexbox-item footer');
this.south.element.setAttribute('align', 'center');
this.element.appendChild(this.south.element);
</pre>
<p>
Again, if you know your CSS, this is pretty straight forward. But you also see, why this is a little complicated, we introduce three new JSPanels, one for each region, <em>north</em>, <em>center</em>, and <em>south</em>.</p>
<h4>
Child Widgets</h4>
<p>
Adding the children is trivial for <em>flow</em>, and <em>grid</em>: you simply call <em>this.element.appendChild()</em>. For the <em>border</em> layout, we need to make sure we add it to the correct child: </p>
<pre style="margin-left: 40px;">
add(obj, where) {
...
if (this.layout == 'border') {
if (where.toLowerCase() == 'north' ||
where.toLowerCase() == 'west') {
this.north.add(obj);
} else if (where.toLowerCase() == 'south' ||
where.toLowerCase() == 'east') {
this.south.add(obj);
} else {
this.center.add(obj);
}
} else if (this.layout == 'grid') {
this.element.appendChild(obj.element);
} else {
this.element.appendChild(obj.element);
}
}</pre>
<p>
</p>
<p>
What we did not show, is code that adds the event listeners and treats the case where we add a JSPanel to a JSPanel, but you can look it up in the code.</p>
<h3>
JSCanvas</h3>
<p>
The other class I would not want to mess around with much, because I am happy that it kind of works, is the JSCanvas class. It allows us to draw graphics inside a UI application. For this it uses the canvas tag from p5.js:</p>
<pre style="margin-left: 40px;">
class JSCanvas extends JSObject {
constructor() {
super();
// get the p5js canvas:
this.element = document.getElementById("defaultCanvas0");
this.element.style.padding = DEFAULT_PADDING;
this.element.style.margin = DEFAULT_MARGIN;
this.element.style = 'border: 1px solid green;';
this.gobjects = [];
}
...
}</pre>
<p>
</p>
<p>
As you see it gets a handle on p5.js's canvas, which happens to be called "defaultCanvas0". This is not really documented, and as soon as p5.js would change the name, this wouldn't work anymore. You also see the array of <em>gobjects</em>, and most of the methods are one-to-one equivalents to the graphics program functions. One things that is different, however, is the <em>updateJSCanvas()</em> function, take a look if you are interested.</p>
<p>
.</p>
<h2>
Util Library</h2>
<p>
What is the point of the Util library? Well, as I stated before, I wanted to transfer my existing Java code to JavaScript with as little changes as possible. For the standard Java classes, I was first considering to use one of a transpilers like J2CL [1], JSweet [2], or the old GWT [3]. But the JavaScript code these transpilers generate is ugly as hell, and humongous in size. Since I needed just a handful of classes, I decided to write them myself, as there are:</p>
<ul>
<li>
RandomGenerator</li>
<li>
StringTokenizer</li>
<li>
ArrayList</li>
<li>
HashMap</li>
<li>
HashSet</li>
<li>
FileReader</li>
<li>
FileWriter</li>
<li>
StorageReader</li>
<li>
StorageWriter</li>
<li>
URLReader</li>
</ul>
<p>
The last three do not exist in Java, but lend themselves to the use in a browser. Again, here ES6 came in real handy, and what other people might call syntactic sugar, I call a life safer.</p>
<p>
The classes are really trivial. The RandomGenerator is a wrapper around Math.random(), the StringTokenizer a wrapper around JavaScripts string functions, and ArrayList, HashMap, and HashSet wrap their corresponding JavaScripts classes Array, Map and Set. </p>
<p>
Similarily, FileReader is a wrapper around an XMLHttpRequest, and FileWriter is an <a> tag, stupid as it may sound, but works. One word on the FileReader: in ES6, there exists a class with the name FileReader in the new file API, hence we had to call ours Utils.FileReader, which on the other hand allowed us to introduce the concept of what we call <em>namespace</em>. Actually, all the different libraries should be made namespaces, but that would reduce the simplicity of use of our libraries by quite a bit.</p>
<h3>
include()</h3>
<p>
I wanted to call it <em>import</em>, but that name was taken. The idea was to import JavaScript classes as you can in Java using the import statements at the top of a Java file. Usually to import another JavaScript file you have to do this in the HTML header:</p>
<pre style="margin-left: 40px;">
<html>
<head>
<script src="./libraries/utils.js"></script>
<span style="color:#0000ff;"><script src="./ticTacToeLogic.js"></script></span>
</head>
...
</pre>
<p>
But I did not want to have to modify the HTML file everytime I wanted to just import a little class. As usual the internet has the answers to all your questions:</p>
<pre style="margin-left: 40px;">
/* https://www.educative.io/answers/how-to-dynamically-load-a-js-file-in-javascript */
function include(file, async = false) {
let script = document.createElement("script");
script.setAttribute("src", file);
script.setAttribute("type", "text/javascript");
script.setAttribute("async", async);
document.body.appendChild(script);
// success event
script.addEventListener("load", () => {
//console.log("File loaded")
});
// error event
script.addEventListener("error", (ev) => {
console.log("Error loading file", ev);
});
}
</pre>
<p>
Now all you have to do, add this line at the top of you code,</p>
<pre style="margin-left: 40px;">
include("Pr4_Agrar/ticTacToeLogic.js");</pre>
<p>
and you can use your own handwritten classes.</p>
<p>
.</p>
<p>
[1] J2CL, https://github.com/google/j2cl<br />
[2] JSweet: http://www.jsweet.org/<br />
[3] GWT: https://padlet.com/lofidewanto/gwtintro<br />
[4] FileAPI, https://w3c.github.io/FileAPI/</p>
<p>
.</p>
<h2>
Karel Programs</h2>
<p>
Last, but not least we come to Karel. It is how we start to learn programming, and hence you would think it is the easiest to implement, but quite the opposite. </p>
<p>
The core problem is that you do not want the code to run through at once, but instead, you want one line to be executed, then wait a second, then go to the next line, wait a second, and so on. JavaScript does not have a pause() method. And while doing so, you want to see the actual state and position Karel is in. JavaScript is not multithreaded. And in addition you have if-conditions and for- and while-loops in the Karel code, which makes simulating it a difficult task. Here JavaScript does have a very attractive feature: the eval() function. So, how do you circumvent the problems, and use the features?</p>
<p>
From our point of view Karel programs are simply graphics programs. Karel is represented by four GImages, one for each direction he can move to. The p5.js draw() function looks like this:</p>
<pre style="margin-left: 40px;">
function draw() {
eval(codeLines[codePointer]);
codePointer++;
if (codePointer >= codeLines.length) {
noLoop();
}
update();
}</pre>
<p>
We basically set the framerate to one frame per second, and every second we execute one line of Karel code, which has been parsed into an array. This actually solves our first and second problem.</p>
<p>
For each of the Karel commands, like <em>move()</em> or <em>putBeeper()</em>, we have a function. For instance, for move it looks like this:</p>
<pre style="margin-left: 40px;">
function move() {
if (karelIsAlive) {
if (frontIsClear()) {
switch (karelDir) {
case 0:
// this.karel.x += SIZE;
karel.move(SIZE, 0);
break;
...
}
</pre>
<p>
That is what allows us to simply use JavaScript's eval() function.</p>
<p>
The one problem that remains, are infinite loops. Hypothetically, one could just ignore the problem: it does not happen often, and when it does, you just restart the browser. But from a didactic point of view, and that is what Karel is all about, this is not very helpful. </p>
<p>
However, one can tackle the problem. If we realize, that it is basically only the while-loops that can be problematic, we only need to look at those. One could try a static code analysis of while loops. To me, however, this looks quite a bit like the famous halting problem (I said Karel is tricky). Instead, we insert a little piece of code after every while we encounter. The following two lines of regular expression magic do that:</p>
<pre style="margin-left: 40px;">
const regex = /(while\s*)\(([ a-zA-Z\(\)]+)\)\s*\{/g;
code = code.replaceAll(regex, " $1 ( $2 ) { catchInfiniteLoops();");</pre>
<p>
The <em>catchInfiniteLoops()</em> function is a simple counter:</p>
<pre style="margin-left: 40px;">
let infiniteLoopCounter = 0;
function catchInfiniteLoops() {
infiniteLoopCounter++;
if (infiniteLoopCounter > 200) {
throw new InfiniteLoopError("Most likely infinite loop!");
}
}</pre>
<p>
We simplify our halting problem: if this method has been called more than 200 times, we say we have an infinite loop and throw an error. Thus executing the code in a simulation run with eval(code), will always stop, even if there is an infinite loop. And we can tell our users that their code most likely has an infinite loop.</p>
<p>
There are a few more code gems in Karel (or hacks as some might call them), but you have to discover them for yourself!</p>
<p>
.</p>
<p class="footer">
Copyright © 2016-2023 <a href="http://www.lano.de">Ralph P. Lano</a>. All rights reserved.
</p>
</div>
</div>
</center>
</body>
</html>