chiark / gitweb /
New front end! To complement the webification of my puzzles via Java
[sgt-puzzles.git] / emcclib.js
1 /*
2  * emcclib.js: one of the Javascript components of an Emscripten-based
3  * web/Javascript front end for Puzzles.
4  *
5  * The other parts of this system live in emcc.c and emccpre.js.
6  *
7  * This file contains a set of Javascript functions which we insert
8  * into Emscripten's library object via the --js-library option; this
9  * allows us to provide JS code which can be called from the
10  * Emscripten-compiled C, mostly dealing with UI interaction of
11  * various kinds.
12  */
13
14 mergeInto(LibraryManager.library, {
15     /*
16      * void js_debug(const char *message);
17      *
18      * A function to write a diagnostic to the Javascript console.
19      * Unused in production, but handy in development.
20      */
21     js_debug: function(ptr) {
22         console.log(Pointer_stringify(ptr));
23     },
24
25     /*
26      * void js_error_box(const char *message);
27      *
28      * A wrapper around Javascript's alert(), so the C code can print
29      * simple error message boxes (e.g. when invalid data is entered
30      * in a configuration dialog).
31      */
32     js_error_box: function(ptr) {
33         alert(Pointer_stringify(ptr));
34     },
35
36     /*
37      * void js_remove_type_dropdown(void);
38      *
39      * Get rid of the drop-down list on the web page for selecting
40      * game presets. Called at setup time if the game back end
41      * provides neither presets nor configurability.
42      */
43     js_remove_type_dropdown: function() {
44         document.getElementById("gametype").style.display = "none";
45     },
46
47     /*
48      * void js_remove_solve_button(void);
49      *
50      * Get rid of the Solve button on the web page. Called at setup
51      * time if the game doesn't support an in-game solve function.
52      */
53     js_remove_solve_button: function() {
54         document.getElementById("solve").style.display = "none";
55     },
56
57     /*
58      * void js_add_preset(const char *name);
59      *
60      * Add a preset to the drop-down types menu. The provided text is
61      * the name of the preset. (The corresponding game_params stays on
62      * the C side and never comes out this far; we just pass a numeric
63      * index back to the C code when a selection is made.)
64      */
65     js_add_preset: function(ptr) {
66         var option = document.createElement("option");
67         option.value = Pointer_stringify(ptr);
68         option.innerHTML = Pointer_stringify(ptr);
69         gametypeselector.appendChild(option);
70         gametypeoptions.push(option);
71     },
72
73     /*
74      * int js_get_selected_preset(void);
75      *
76      * Return the index of the currently selected value in the type
77      * dropdown.
78      */
79     js_get_selected_preset: function() {
80         var val = 0;
81         for (var i in gametypeoptions) {
82             if (gametypeoptions[i].selected) {
83                 val = i;
84                 break;
85             }
86         }
87         return val;
88     },
89
90     /*
91      * void js_select_preset(int n);
92      *
93      * Cause a different value to be selected in the type dropdown
94      * (for when the user selects values from the Custom configurer
95      * which turn out to exactly match a preset).
96      */
97     js_select_preset: function(n) {
98         gametypeoptions[n].selected = true;
99     },
100
101     /*
102      * void js_get_date_64(unsigned *p);
103      *
104      * Return the current date, in milliseconds since the epoch
105      * (Javascript's native format), as a 64-bit integer. Used to
106      * invent an initial random seed for puzzle generation.
107      */
108     js_get_date_64: function(ptr) {
109         var d = (new Date()).valueOf();
110         setValue(ptr, d, 'i64');
111     },
112
113     /*
114      * void js_update_permalinks(const char *desc, const char *seed);
115      *
116      * Update the permalinks on the web page for a new game
117      * description and optional random seed. desc can never be NULL,
118      * but seed might be (if the game was generated by entering a
119      * descriptive id by hand), in which case we suppress display of
120      * the random seed permalink.
121      */
122     js_update_permalinks: function(desc, seed) {
123         desc = Pointer_stringify(desc);
124         permalink_desc.href = "#" + desc;
125
126         if (seed == 0) {
127             permalink_seed.style.display = "none";
128         } else {
129             seed = Pointer_stringify(seed);
130             permalink_seed.href = "#" + seed;
131             permalink_seed.style.display = "inline";
132         }
133     },
134
135     /*
136      * void js_enable_undo_redo(int undo, int redo);
137      *
138      * Set the enabled/disabled states of the undo and redo buttons,
139      * after a move.
140      */
141     js_enable_undo_redo: function(undo, redo) {
142         undo_button.disabled = (undo == 0);
143         redo_button.disabled = (redo == 0);
144     },
145
146     /*
147      * void js_activate_timer();
148      *
149      * Start calling the C timer_callback() function every 20ms.
150      */
151     js_activate_timer: function() {
152         if (timer === null) {
153             timer_reference_date = (new Date()).valueOf();
154             timer = setInterval(function() {
155                 var now = (new Date()).valueOf();
156                 timer_callback((now - timer_reference_date) / 1000.0);
157                 timer_reference_date = now;
158                 return true;
159             }, 20);
160         }
161     },
162
163     /*
164      * void js_deactivate_timer();
165      *
166      * Stop calling the C timer_callback() function every 20ms.
167      */
168     js_deactivate_timer: function() {
169         if (timer !== null) {
170             clearInterval(timer);
171             timer = null;
172         }
173     },
174
175     /*
176      * void js_canvas_start_draw(void);
177      *
178      * Prepare to do some drawing on the canvas.
179      */
180     js_canvas_start_draw: function() {
181         ctx = offscreen_canvas.getContext('2d');
182         update_xmin = update_xmax = update_ymin = update_ymax = undefined;
183     },
184
185     /*
186      * void js_canvas_draw_update(int x, int y, int w, int h);
187      *
188      * Mark a rectangle of the off-screen canvas as needing to be
189      * copied to the on-screen one.
190      */
191     js_canvas_draw_update: function(x, y, w, h) {
192         /*
193          * Currently we do this in a really simple way, just by taking
194          * the smallest rectangle containing all updates so far. We
195          * could instead keep the data in a richer form (e.g. retain
196          * multiple smaller rectangles needing update, and only redraw
197          * the whole thing beyond a certain threshold) but this will
198          * do for now.
199          */
200         if (update_xmin === undefined || update_xmin > x) update_xmin = x;
201         if (update_ymin === undefined || update_ymin > y) update_ymin = y;
202         if (update_xmax === undefined || update_xmax < x+w) update_xmax = x+w;
203         if (update_ymax === undefined || update_ymax < y+h) update_ymax = y+h;
204     },
205
206     /*
207      * void js_canvas_end_draw(void);
208      *
209      * Finish the drawing, by actually copying the newly drawn stuff
210      * to the on-screen canvas.
211      */
212     js_canvas_end_draw: function() {
213         if (update_xmin !== undefined) {
214             var onscreen_ctx = onscreen_canvas.getContext('2d');
215             onscreen_ctx.drawImage(offscreen_canvas,
216                                    update_xmin, update_ymin,
217                                    update_xmax - update_xmin,
218                                    update_ymax - update_ymin,
219                                    update_xmin, update_ymin,
220                                    update_xmax - update_xmin,
221                                    update_ymax - update_ymin);
222         }
223         ctx = null;
224     },
225
226     /*
227      * void js_canvas_draw_rect(int x, int y, int w, int h,
228      *                          const char *colour);
229      * 
230      * Draw a rectangle.
231      */
232     js_canvas_draw_rect: function(x, y, w, h, colptr) {
233         ctx.fillStyle = Pointer_stringify(colptr);
234         ctx.fillRect(x, y, w, h);
235     },
236
237     /*
238      * void js_canvas_clip_rect(int x, int y, int w, int h);
239      * 
240      * Set a clipping rectangle.
241      */
242     js_canvas_clip_rect: function(x, y, w, h) {
243         ctx.save();
244         ctx.beginPath();
245         ctx.rect(x, y, w, h);
246         ctx.clip();
247     },
248
249     /*
250      * void js_canvas_unclip(void);
251      * 
252      * Reset to no clipping.
253      */
254     js_canvas_unclip: function() {
255         ctx.restore();
256     },
257
258     /*
259      * void js_canvas_draw_line(float x1, float y1, float x2, float y2,
260      *                          int width, const char *colour);
261      * 
262      * Draw a line. We must adjust the coordinates by 0.5 because
263      * Javascript's canvas coordinates appear to be pixel corners,
264      * whereas we want pixel centres. Also, we manually draw the pixel
265      * at each end of the line, which our clients will expect but
266      * Javascript won't reliably do by default (in common with other
267      * Postscriptish drawing frameworks).
268      */
269     js_canvas_draw_line: function(x1, y1, x2, y2, width, colour) {
270         colour = Pointer_stringify(colour);
271
272         ctx.beginPath();
273         ctx.moveTo(x1 + 0.5, y1 + 0.5);
274         ctx.lineTo(x2 + 0.5, y2 + 0.5);
275         ctx.lineWidth = width;
276         ctx.lineCap = '1';
277         ctx.lineJoin = '1';
278         ctx.strokeStyle = colour;
279         ctx.stroke();
280         ctx.fillStyle = colour;
281         ctx.fillRect(x1, y1, 1, 1);
282         ctx.fillRect(x2, y2, 1, 1);
283     },
284
285     /*
286      * void js_canvas_draw_poly(int *points, int npoints,
287      *                          const char *fillcolour,
288      *                          const char *outlinecolour);
289      * 
290      * Draw a polygon.
291      */
292     js_canvas_draw_poly: function(pointptr, npoints, fill, outline) {
293         ctx.beginPath();
294         ctx.moveTo(getValue(pointptr  , 'i32') + 0.5,
295                    getValue(pointptr+4, 'i32') + 0.5);
296         for (var i = 1; i < npoints; i++)
297             ctx.lineTo(getValue(pointptr+8*i  , 'i32') + 0.5,
298                        getValue(pointptr+8*i+4, 'i32') + 0.5);
299         ctx.closePath();
300         if (fill != 0) {
301             ctx.fillStyle = Pointer_stringify(fill);
302             ctx.fill();
303         }
304         ctx.lineWidth = '1';
305         ctx.lineCap = '1';
306         ctx.lineJoin = '1';
307         ctx.strokeStyle = Pointer_stringify(outline);
308         ctx.stroke();
309     },
310
311     /*
312      * void js_canvas_draw_circle(int x, int y, int r,
313      *                            const char *fillcolour,
314      *                            const char *outlinecolour);
315      * 
316      * Draw a circle.
317      */
318     js_canvas_draw_circle: function(x, y, r, fill, outline) {
319         ctx.beginPath();
320         ctx.arc(x + 0.5, y + 0.5, r, 0, 2*Math.PI);
321         if (fill != 0) {
322             ctx.fillStyle = Pointer_stringify(fill);
323             ctx.fill();
324         }
325         ctx.lineWidth = '1';
326         ctx.lineCap = '1';
327         ctx.lineJoin = '1';
328         ctx.strokeStyle = Pointer_stringify(outline);
329         ctx.stroke();
330     },
331
332     /*
333      * int js_canvas_find_font_midpoint(int height, const char *fontptr);
334      * 
335      * Return the adjustment required for text displayed using
336      * ALIGN_VCENTRE. We want to place the midpoint between the
337      * baseline and the cap-height at the specified position; so this
338      * function returns the adjustment which, when added to the
339      * desired centre point, returns the y-coordinate at which you
340      * should put the baseline.
341      *
342      * There is no sensible method of querying this kind of font
343      * metric in Javascript, so instead we render a piece of test text
344      * to a throwaway offscreen canvas and then read the pixel data
345      * back out to find the highest and lowest pixels. That's good
346      * _enough_ (in that we only needed the answer to the nearest
347      * pixel anyway), but rather disgusting!
348      *
349      * Since this is a very expensive operation, we cache the results
350      * per (font,height) pair.
351      */
352     js_canvas_find_font_midpoint: function(height, font) {
353         font = Pointer_stringify(font);
354
355         // Reuse cached value if possible
356         if (midpoint_cache[font] !== undefined)
357             return midpoint_cache[font];
358
359         // Find the width of the string
360         var ctx1 = onscreen_canvas.getContext('2d');
361         ctx1.font = font;
362         var width = ctx1.measureText(midpoint_test_str).width;
363
364         // Construct a test canvas of appropriate size, initialise it to
365         // black, and draw the string on it in white
366         var measure_canvas = document.createElement('canvas');
367         var ctx2 = measure_canvas.getContext('2d');
368         ctx2.canvas.width = width;
369         ctx2.canvas.height = 2*height;
370         ctx2.fillStyle = "#000000";
371         ctx2.fillRect(0, 0, width, 2*height);
372         var baseline = (1.5*height) | 0;
373         ctx2.fillStyle = "#ffffff";
374         ctx2.font = font;
375         ctx2.fillText(midpoint_test_str, 0, baseline);
376
377         // Scan the contents of the test canvas to find the top and bottom
378         // set pixels.
379         var pixels = ctx2.getImageData(0, 0, width, 2*height).data;
380         var ymin = 2*height, ymax = -1;
381         for (var y = 0; y < 2*height; y++) {
382             for (var x = 0; x < width; x++) {
383                 if (pixels[4*(y*width+x)] != 0) {
384                     if (ymin > y) ymin = y;
385                     if (ymax < y) ymax = y;
386                     break;
387                 }
388             }
389         }
390
391         var ret = (baseline - (ymin + ymax) / 2) | 0;
392         midpoint_cache[font] = ret;
393         return ret;
394     },
395
396     /*
397      * void js_canvas_draw_text(int x, int y, int halign,
398      *                          const char *colptr, const char *fontptr,
399      *                          const char *text);
400      * 
401      * Draw text. Vertical alignment has been taken care of on the C
402      * side, by optionally calling the above function. Horizontal
403      * alignment is handled here, since we can get the canvas draw
404      * function to do it for us with almost no extra effort.
405      */
406     js_canvas_draw_text: function(x, y, halign, colptr, fontptr, text) {
407         ctx.font = Pointer_stringify(fontptr);
408         ctx.fillStyle = Pointer_stringify(colptr);
409         ctx.textAlign = (halign == 0 ? 'left' :
410                          halign == 1 ? 'center' : 'right');
411         ctx.textBaseline = 'alphabetic';
412         ctx.fillText(Pointer_stringify(text), x, y);
413     },
414
415     /*
416      * int js_canvas_new_blitter(int w, int h);
417      * 
418      * Create a new blitter object, which is just an offscreen canvas
419      * of the specified size.
420      */
421     js_canvas_new_blitter: function(w, h) {
422         var id = blittercount++;
423         blitters[id] = document.createElement("canvas");
424         blitters[id].width = w;
425         blitters[id].height = h;
426     },
427
428     /*
429      * void js_canvas_free_blitter(int id);
430      * 
431      * Free a blitter (or rather, destroy our reference to it so JS
432      * can garbage-collect it, and also enforce that we don't
433      * accidentally use it again afterwards).
434      */
435     js_canvas_free_blitter: function(id) {
436         blitters[id] = null;
437     },
438
439     /*
440      * void js_canvas_copy_to_blitter(int id, int x, int y, int w, int h);
441      * 
442      * Copy from the puzzle image to a blitter. The size is passed to
443      * us, partly so we don't have to remember the size of each
444      * blitter, but mostly so that the C side can adjust the copy
445      * rectangle in the case where it partially overlaps the edge of
446      * the screen.
447      */
448     js_canvas_copy_to_blitter: function(id, x, y, w, h) {
449         var blitter_ctx = blitters[id].getContext('2d');
450         blitter_ctx.drawImage(offscreen_canvas,
451                               x, y, w, h,
452                               0, 0, w, h);
453     },
454
455     /*
456      * void js_canvas_copy_from_blitter(int id, int x, int y, int w, int h);
457      * 
458      * Copy from a blitter back to the puzzle image. As above, the
459      * size of the copied rectangle is passed to us from the C side
460      * and may already have been modified.
461      */
462     js_canvas_copy_from_blitter: function(id, x, y, w, h) {
463         ctx.drawImage(blitters[id],
464                       0, 0, w, h,
465                       x, y, w, h);
466     },
467
468     /*
469      * void js_canvas_make_statusbar(void);
470      * 
471      * Cause a status bar to exist. Called at setup time if the puzzle
472      * back end turns out to want one.
473      */
474     js_canvas_make_statusbar: function() {
475         var statustd = document.getElementById("statusbarholder");
476         statusbar = document.createElement("div");
477         statusbar.style.overflow = "hidden";
478         statusbar.style.width = onscreen_canvas.width - 4;
479         statusbar.style.height = "1.2em";
480         statusbar.style.background = "#d8d8d8";
481         statusbar.style.borderLeft = '2px solid #c8c8c8';
482         statusbar.style.borderTop = '2px solid #c8c8c8';
483         statusbar.style.borderRight = '2px solid #e8e8e8';
484         statusbar.style.borderBottom = '2px solid #e8e8e8';
485         statusbar.appendChild(document.createTextNode(" "));
486         statustd.appendChild(statusbar);
487     },
488
489     /*
490      * void js_canvas_set_statusbar(const char *text);
491      * 
492      * Set the text in the status bar.
493      */
494     js_canvas_set_statusbar: function(ptr) {
495         var text = Pointer_stringify(ptr);
496         statusbar.replaceChild(document.createTextNode(text),
497                                statusbar.lastChild);
498     },
499
500     /*
501      * void js_canvas_set_size(int w, int h);
502      * 
503      * Set the size of the puzzle canvas. Called at setup, and every
504      * time the user picks new puzzle settings requiring a different
505      * size.
506      */
507     js_canvas_set_size: function(w, h) {
508         onscreen_canvas.width = w;
509         offscreen_canvas.width = w;
510         if (statusbar !== null)
511             statusbar.style.width = w - 4;
512
513         onscreen_canvas.height = h;
514         offscreen_canvas.height = h;
515     },
516
517     /*
518      * void js_dialog_init(const char *title);
519      * 
520      * Begin constructing a 'dialog box' which will be popped up in an
521      * overlay on top of the rest of the puzzle web page.
522      */
523     js_dialog_init: function(titletext) {
524         // Create an overlay on the page which darkens everything
525         // beneath it.
526         dlg_dimmer = document.createElement("div");
527         dlg_dimmer.style.width = "100%";
528         dlg_dimmer.style.height = "100%";
529         dlg_dimmer.style.background = '#000000';
530         dlg_dimmer.style.position = 'fixed';
531         dlg_dimmer.style.opacity = 0.3;
532         dlg_dimmer.style.top = dlg_dimmer.style.left = 0;
533         dlg_dimmer.style["z-index"] = 99;
534
535         // Now create a form which sits on top of that in turn.
536         dlg_form = document.createElement("form");
537         dlg_form.style.width =  window.innerWidth * 2 / 3;
538         dlg_form.style.opacity = 1;
539         dlg_form.style.background = '#ffffff';
540         dlg_form.style.color = '#000000';
541         dlg_form.style.position = 'absolute';
542         dlg_form.style.border = "2px solid black";
543         dlg_form.style.padding = 20;
544         dlg_form.style.top = window.innerHeight / 10;
545         dlg_form.style.left = window.innerWidth / 6;
546         dlg_form.style["z-index"] = 100;
547
548         var title = document.createElement("p");
549         title.style.marginTop = "0px";
550         title.appendChild(document.createTextNode
551                           (Pointer_stringify(titletext)));
552         dlg_form.appendChild(title);
553
554         dlg_return_funcs = [];
555         dlg_next_id = 0;
556     },
557
558     /*
559      * void js_dialog_string(int i, const char *title, const char *initvalue);
560      * 
561      * Add a string control (that is, an edit box) to the dialog under
562      * construction.
563      */
564     js_dialog_string: function(index, title, initialtext) {
565         dlg_form.appendChild(document.createTextNode(Pointer_stringify(title)));
566         var editbox = document.createElement("input");
567         editbox.type = "text";
568         editbox.value = Pointer_stringify(initialtext);
569         dlg_form.appendChild(editbox);
570         dlg_form.appendChild(document.createElement("br"));
571
572         dlg_return_funcs.push(function() {
573             dlg_return_sval(index, editbox.value);
574         });
575     },
576
577     /*
578      * void js_dialog_choices(int i, const char *title, const char *choicelist,
579      *                        int initvalue);
580      * 
581      * Add a choices control (i.e. a drop-down list) to the dialog
582      * under construction. The 'choicelist' parameter is unchanged
583      * from the way the puzzle back end will have supplied it: i.e.
584      * it's still encoded as a single string whose first character
585      * gives the separator.
586      */
587     js_dialog_choices: function(index, title, choicelist, initvalue) {
588         dlg_form.appendChild(document.createTextNode(Pointer_stringify(title)));
589         var dropdown = document.createElement("select");
590         var choicestr = Pointer_stringify(choicelist);
591         var items = choicestr.slice(1).split(choicestr[0]);
592         var options = [];
593         for (var i in items) {
594             var option = document.createElement("option");
595             option.value = items[i];
596             option.innerHTML = items[i];
597             if (i == initvalue) option.selected = true;
598             dropdown.appendChild(option);
599             options.push(option);
600         }
601         dlg_form.appendChild(dropdown);
602         dlg_form.appendChild(document.createElement("br"));
603
604         dlg_return_funcs.push(function() {
605             var val = 0;
606             for (var i in options) {
607                 if (options[i].selected) {
608                     val = i;
609                     break;
610                 }
611             }
612             dlg_return_ival(index, val);
613         });
614     },
615
616     /*
617      * void js_dialog_boolean(int i, const char *title, int initvalue);
618      * 
619      * Add a boolean control (a checkbox) to the dialog under
620      * construction. Checkboxes are generally expected to be sensitive
621      * on their label text as well as the box itself, so for this
622      * control we create an actual label rather than merely a text
623      * node (and hence we must allocate an id to the checkbox so that
624      * the label can refer to it).
625      */
626     js_dialog_boolean: function(index, title, initvalue) {
627         var checkbox = document.createElement("input");
628         checkbox.type = "checkbox";
629         checkbox.id = "cb" + String(dlg_next_id++);
630         checkbox.checked = (initvalue != 0);
631         dlg_form.appendChild(checkbox);
632         var checkboxlabel = document.createElement("label");
633         checkboxlabel.setAttribute("for", checkbox.id);
634         checkboxlabel.textContent = Pointer_stringify(title);
635         dlg_form.appendChild(checkboxlabel);
636         dlg_form.appendChild(document.createElement("br"));
637
638         dlg_return_funcs.push(function() {
639             dlg_return_ival(index, checkbox.checked ? 1 : 0);
640         });
641     },
642
643     /*
644      * void js_dialog_launch(void);
645      * 
646      * Finish constructing a dialog, and actually display it, dimming
647      * everything else on the page.
648      */
649     js_dialog_launch: function() {
650         // Put in the OK and Cancel buttons at the bottom.
651         var button;
652
653         button = document.createElement("input");
654         button.type = "button";
655         button.value = "OK";
656         button.onclick = function(event) {
657             for (var i in dlg_return_funcs)
658                 dlg_return_funcs[i]();
659             command(3);
660         }
661         dlg_form.appendChild(button);
662
663         button = document.createElement("input");
664         button.type = "button";
665         button.value = "Cancel";
666         button.onclick = function(event) {
667             command(4);
668         }
669         dlg_form.appendChild(button);
670
671         document.body.appendChild(dlg_dimmer);
672         document.body.appendChild(dlg_form);
673     },
674
675     /*
676      * void js_dialog_cleanup(void);
677      * 
678      * Stop displaying a dialog, and clean up the internal state
679      * associated with it.
680      */
681     js_dialog_cleanup: function() {
682         document.body.removeChild(dlg_dimmer);
683         document.body.removeChild(dlg_form);
684         dlg_dimmer = dlg_form = null;
685         onscreen_canvas.focus();
686     },
687
688     /*
689      * void js_focus_canvas(void);
690      * 
691      * Return keyboard focus to the puzzle canvas. Called after a
692      * puzzle-control button is pressed, which tends to have the side
693      * effect of taking focus away from the canvas.
694      */
695     js_focus_canvas: function() {
696         onscreen_canvas.focus();
697     },
698 });