chiark / gitweb /
script: Fiddle with CSS to try to get cursor to update
[otter.git] / templates / script.ts
1 // -*- JavaScript -*-
2
3 // Copyright 2020-2021 Ian Jackson and contributors to Otter
4 // SPDX-License-Identifier: AGPL-3.0-or-later
5 // There is NO WARRANTY.
6
7 // elemnts for a piece
8 //
9 // In svg toplevel
10 //
11 //   uelem
12 //      #use{}
13 //      <use id="use{}", href="#piece{}" x= y= >
14 //         .piece   piece id (static)
15 //      container to allow quick movement and hang stuff off
16 //
17 //   delem
18 //      #defs{}
19 //      <def id="defs{}">
20 //
21 // And in each delem
22 //
23 //   pelem
24 //   #piece{}
25 //         .dragraise   dragged more than this ?  raise to top!
26 //         .special     enum RenderSpecial
27 //      <g id="piece{}" >
28 //      currently-displayed version of the piece
29 //      to allow addition/removal of selected indication
30 //      contains 1 or 3 subelements:
31 //      one is straight from server and not modified
32 //      one is possible <use href="#select{}" >
33 //      one is possible <use href="#halo{}" >
34 //
35 //   #select{}
36 //      generated by server, referenced by JS in pelem for selection
37 //
38 //   #def.{}.stuff
39 //      generated by server, reserved for Piece trait impl
40
41 type PieceId = string;
42 type PlayerId = string;
43 type Pos = [number, number];
44 type Rect = [Pos, Pos];
45 type ClientSeq = number;
46 type Generation = number;
47 type UoKind = 'Client' | "Global"| "Piece" | "ClientExtra" | "GlobalExtra";
48 type WhatResponseToClientOp = "Predictable" | "Unpredictable" | "UpdateSvg";
49 type HeldUsRaising = "NotYet" | "Lowered" | "Raised"
50 type Timestamp = number; // unix time_t, will break in 285My
51 type Layout = 'Portrait' | 'Landscape';
52 type PieceMoveable = "No" | "IfWresting" | "Yes";
53 type CompassAngle = number;
54 type FaceId = number;
55
56 type UoDescription = {
57   kind: UoKind;
58   wrc: WhatResponseToClientOp,
59   def_key: string,
60   opname: string,
61   desc: string,
62 }
63
64 type UoRecord = UoDescription & {
65   targets: PieceId[] | null,
66 }
67
68 type ZCoord = string;
69
70 // On load, starts from SessionPieceLoadJson (Rust-only)
71 // On update, updated field-by-field from PreparedPieceState (Rust&JS)
72 type PieceInfo = {
73   held : PlayerId | null,
74   cseq_main : number | null,
75   cseq_loose: number | null,
76   cseq_updatesvg : number | null,
77   z : ZCoord,
78   zg : Generation,
79   angle: CompassAngle,
80   pinned: boolean,
81   moveable: PieceMoveable,
82   rotateable: boolean,
83   multigrab: boolean,
84   desc: string,
85   uos : UoDescription[],
86   uelem : SVGGraphicsElement,
87   delem : SVGGraphicsElement,
88   pelem : SVGGraphicsElement,
89   queued_moves : number,
90   last_seen_moved : DOMHighResTimeStamp | null, // non-0 means halo'd
91   held_us_inoccult: boolean,
92   held_us_raising: HeldUsRaising,
93   bbox: Rect,
94   drag_delta: number,
95   special: SpecialRendering | null,
96 }
97
98 type SpecialRendering = {
99   kind: string,
100   stop: SpecialRenderingCallback,
101 }
102
103 let wasm : InitOutput;
104
105 var pieces : { [piece: string]: PieceInfo } = Object.create(null);
106
107 type MessageHandler = (op: Object) => void;
108 type PieceHandler = (piece: PieceId, p: PieceInfo, info: Object) => void;
109 type PieceErrorHandler = (piece: PieceId, p: PieceInfo, m: PieceOpError)
110   => boolean;
111 type SpecialRenderingCallback =
112   (piece: PieceId, p: PieceInfo, s: SpecialRendering) => void;
113 interface DispatchTable<H> { [key: string]: H };
114
115 var otter_debug: boolean;
116
117 // from header
118 var movehist_len_i: number;
119 var movehist_len_max: number;
120 var movehist_lens: number[];
121
122 // todo turn all var into let
123 // todo any exceptions should have otter in them or something
124 var globalinfo_elem : HTMLElement;
125 var layout: Layout;
126 var held_surround_colour: string;
127 var general_timeout : number = 10000;
128 var messages : DispatchTable<MessageHandler> = Object();
129 var special_renderings : DispatchTable<SpecialRenderingCallback> = Object();
130 var pieceops : DispatchTable<PieceHandler> = Object();
131 var update_error_handlers : DispatchTable<MessageHandler> = Object();
132 var piece_error_handlers : DispatchTable<PieceErrorHandler> = Object();
133 var our_dnd_type = "text/puvnex-game-server-dummy";
134 var api_queue : [string, Object][] = [];
135 var api_posting = false;
136 var us : PlayerId;
137 var gen : Generation = 0;
138 var cseq : ClientSeq = 0;
139 var ctoken : string;
140 var uo_map : { [k: string]: UoRecord | null } = Object.create(null);
141 var keyops_local : { [opname: string]: (uo: UoRecord) => void } = Object();
142 var last_log_ts: wasm_bindgen.TimestampAbbreviator;
143 var last_zoom_factor : number = 1.0;
144 var firefox_bug_zoom_factor_compensation : number = 1.0;
145 var test_update_hook : () => void;
146
147 var svg_ns : string;
148 var space : SVGGraphicsElement;
149 var pieces_marker : SVGGraphicsElement;
150 var defs_marker : SVGGraphicsElement;
151 var movehist_start: SVGGraphicsElement;
152 var movehist_end: SVGGraphicsElement;
153 var rectsel_path: SVGGraphicsElement;
154 var log_elem : HTMLElement;
155 var logscroll_elem : HTMLElement;
156 var status_node : HTMLElement;
157 var uos_node : HTMLElement;
158 var zoom_val : HTMLInputElement;
159 var zoom_btn : HTMLInputElement;
160 var links_elem : HTMLElement;
161 var wresting: boolean;
162 var occregions: wasm_bindgen.RegionList;
163 let special_count: number | null;
164
165 var movehist_gen: number = 0;
166 const MOVEHIST_ENDS = 2.5;
167 const SPECIAL_MULTI_DELTA_EACH = 3;
168 const SPECIAL_MULTI_DELTA_MAX = 18;
169
170 type PaneName = string;
171 const pane_keys : { [key: string]: PaneName } = {
172   "H" : "help",
173   "U" : "players",
174   "B" : "bundles",
175 };
176
177 const uo_kind_prec : { [kind: string]: number } = {
178   'GlobalExtra' :  50,
179   'Client'      :  70,
180   'Global'      : 100,
181   'Piece'       : 200,
182   'ClientExtra' : 500,
183 }
184
185 type PlayerInfo = {
186   dasharray : string,
187   nick: string,
188 }
189 var players : { [player: string]: PlayerInfo };
190
191 type MovementRecord = { // for yellow halo, unrelasted to movehist
192   piece: PieceId,
193   p: PieceInfo,
194   this_motion: DOMHighResTimeStamp,
195 }
196 var movements : MovementRecord[] = [];
197
198 function xhr_post_then(url : string, data: string,
199                        good : (xhr: XMLHttpRequest) => void) {
200   var xhr : XMLHttpRequest = new XMLHttpRequest();
201   xhr.onreadystatechange = function(){
202     if (xhr.readyState != XMLHttpRequest.DONE) { return; }
203     if (xhr.status != 200) { xhr_report_error(xhr); }
204     else { good(xhr); }
205   };
206   xhr.timeout = general_timeout;
207   xhr.open('POST',url);
208   xhr.setRequestHeader('Content-Type','application/json');
209   xhr.send(data);
210 }
211
212 function xhr_report_error(xhr: XMLHttpRequest) {
213   json_report_error({
214     statusText : xhr.statusText,
215     responseText : xhr.responseText,
216   });
217 }
218
219 function json_report_error(error_for_json: Object) {
220   let error_message = JSON.stringify(error_for_json);
221   string_report_error(error_message);
222 }
223
224 function string_report_error(error_message: String) {
225   string_report_error_raw('Error (reloading may help?): ' + error_message)
226 }
227 function string_report_error_raw(error_message: String) {
228   let errornode = document.getElementById('error')!;
229   errornode.textContent += '\n' + error_message;
230   console.error("ERROR reported via log", error_message);
231   // todo want to fix this for at least basic game reconfigs, auto-reload?
232 }
233
234 function api_immediate(meth: string, data: Object) {
235   api_queue.push([meth, data]);
236   api_check();
237 }
238 function api_delay(meth: string, data: Object) {
239   if (api_queue.length==0) window.setTimeout(api_check, 10);
240   api_queue.push([meth, data]);
241 }
242 function api_check() {
243   if (api_posting) { return; }
244   if (!api_queue.length) { test_update_hook(); return; }
245   do {
246     var [meth, data] = api_queue.shift()!;
247     if (meth != 'm') break;
248     let piece = (data as any).piece;
249     let p = pieces[piece];
250     if (p == null) break;
251     p.queued_moves--;
252     if (p.queued_moves == 0) break;
253   } while (api_queue.length);
254   api_posting = true;
255   xhr_post_then('/_/api/'+meth, JSON.stringify(data), api_posted);
256 }
257 function api_posted() {
258   api_posting = false;
259   api_check();
260 }
261
262 function api_piece_x(f: (meth: string, payload: Object) => void,
263                      loose: boolean,
264                      meth: string,
265                      piece: PieceId, p: PieceInfo,
266                      op: Object) {
267   clear_halo(piece,p);
268   cseq += 1;
269   if (loose) {
270     p.cseq_loose = cseq;
271   } else {
272     p.cseq_main = cseq;
273     p.cseq_loose = null;
274   }
275   f(meth, {
276     ctoken : ctoken,
277     piece : piece,
278     gen : gen,
279     cseq : cseq,
280     op : op,
281     loose: loose,
282   })
283 }
284 function api_piece(meth: string,
285                    piece: PieceId, p: PieceInfo,
286                    op: Object) {
287   api_piece_x(api_immediate, false,meth, piece, p, op);
288 }
289
290 function svg_element(id: string): SVGGraphicsElement | null {
291   let elem = document.getElementById(id);
292   return elem as unknown as (SVGGraphicsElement | null);
293 }
294 function piece_element(base: string, piece: PieceId): SVGGraphicsElement | null
295 {
296   return svg_element(base+piece);
297 }
298
299 function piece_moveable(p: PieceInfo) {
300   return p.moveable == 'Yes' || p.moveable == 'IfWresting' && wresting;
301 }
302
303 // ----- key handling -----
304
305 function recompute_keybindings() {
306   uo_map = Object.create(null);
307   let all_targets = [];
308   for (let piece of Object.keys(pieces)) {
309     let p = pieces[piece];
310     if (p.held != us) continue;
311     all_targets.push(piece);
312     for (var uo of p.uos) {
313       let currently = uo_map[uo.def_key];
314       if (currently === null) continue;
315       if (currently !== undefined) {
316         if (currently.opname != uo.opname) {
317           uo_map[uo.def_key] = null;
318           continue;
319         }
320       } else {
321         currently = {
322           targets: [],
323           ...uo
324         };
325         uo_map[uo.def_key] = currently;
326       }
327       currently.desc = currently.desc < uo.desc ? currently.desc : uo.desc;
328       currently.targets!.push(piece);
329     }
330   }
331   all_targets.sort(pieceid_z_cmp);
332   let add_uo = function(targets: PieceId[] | null, uo: UoDescription) {
333     uo_map[uo.def_key] = {
334       targets: targets,
335       ...uo
336     };
337   };
338   if (all_targets.length) {
339     let got_rotateable = false;
340     for (let t of all_targets) {
341       if (pieces[t]!.rotateable)
342         got_rotateable = true;
343     }
344     if (got_rotateable) {
345       add_uo(all_targets, {
346         def_key: 'l',
347         kind: 'Client',
348         wrc: 'Predictable',
349         opname: "left",
350         desc: "rotate left",
351       });
352       add_uo(all_targets, {
353         def_key: 'r',
354         kind: 'Client',
355         wrc: 'Predictable',
356         opname: "right",
357         desc: "rotate right",
358       });
359     }
360     add_uo(all_targets, {
361       def_key: 'b',
362       kind: 'Client',
363       wrc: 'Predictable',
364       opname: "lower",
365       desc: "send to bottom (below other pieces)",
366     });
367     add_uo(all_targets, {
368       def_key: 't',
369       kind: 'Client',
370       wrc: 'Predictable',
371       opname: "raise",
372       desc: "raise to top",
373     });
374   }
375   if (all_targets.length) {
376     let got = 0;
377     for (let t of all_targets) {
378       got |= 1 << Number(pieces[t]!.pinned);
379     }
380     if (got == 1) {
381       add_uo(all_targets, {
382         def_key: 'P',
383         kind: 'ClientExtra',
384         opname: 'pin',
385         desc: 'Pin to table',
386         wrc: 'Predictable',
387       });
388     } else if (got == 2) {
389       add_uo(all_targets, {
390         def_key: 'P',
391         kind: 'ClientExtra',
392         opname: 'unpin',
393         desc: 'Unpin from table',
394         wrc: 'Predictable',
395       });
396     }
397   }
398   add_uo(null, {
399     def_key: 'W',
400     kind: 'ClientExtra',
401     opname: 'wrest',
402     desc: wresting ? 'Exit wresting mode' : 'Enter wresting mode',
403     wrc: 'Predictable',
404   });
405   if (special_count != null) {
406     let desc;
407     if (special_count == 0) {
408       desc = 'select bottommost';
409     } else {
410       desc = `select ${special_count}`;
411     }
412     desc = `cancel <strong style="color:purple">${desc}</strong>`;
413     add_uo(null, {
414       def_key: 'SPC', // won't match key event; we handle this ad-hoc
415       kind: 'ClientExtra',
416       opname: 'cancel-special',
417       desc: desc,
418       wrc: 'Predictable',
419     });
420   }
421   add_uo(null, {
422     def_key: 'h',
423     kind: 'ClientExtra',
424     opname: 'motion-hint-history',
425     desc: 'Recent history display',
426     wrc: 'Predictable',
427   });
428   var uo_keys = Object.keys(uo_map);
429   uo_keys.sort(function (ak,bk) {
430     let a = uo_map[ak];
431     let b = uo_map[bk];
432     if (a==null || b==null) return (
433       ( (!!a) as any ) -
434       ( (!!b) as any )
435     );
436     return uo_kind_prec[a.kind] - uo_kind_prec[b.kind]
437       || ak.localeCompare(bk);
438   });
439   let mid_elem = null;
440   for (let celem = uos_node.firstElementChild;
441        celem != null;
442        celem = nextelem) {
443     var nextelem = celem.nextElementSibling;
444     let cid = celem.getAttribute("id");
445     if (cid == "uos-mid") mid_elem = celem;
446     else if (celem.getAttribute("class") == 'uos-mid') { }
447     else celem.remove();
448   }
449   for (var kk of uo_keys) {
450     let uo = uo_map[kk];
451     if (!uo) continue;
452     let prec = uo_kind_prec[uo.kind];
453     let ent = document.createElement('div');
454     ent.innerHTML = '<b>' + kk + '</b> ' + uo.desc;
455     if (prec < 400) {
456       ent.setAttribute('class','uokey-l');
457       uos_node.insertBefore(ent, mid_elem);
458     } else {
459       ent.setAttribute('class','uokey-r');
460       uos_node.appendChild(ent);
461     }
462   }
463 }
464
465 function some_keydown(e: KeyboardEvent) {
466   // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
467   // says to do this, something to do with CJK composition.
468   // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
469   // says that keyCode is deprecated
470   // my tsc says this isComposing thing doesn't exist.  wat.
471   if ((e as any).isComposing /* || e.keyCode === 229 */) return;
472   if (e.ctrlKey || e.altKey || e.metaKey) return;
473   if (e.target) {
474     // someone else is dealing with it ?
475     let tag = (e.target as HTMLElement).tagName;
476     if (tag == 'INPUT') return;
477   }
478
479   let y = function() { e.preventDefault(); e.stopPropagation(); }
480
481   let pane = pane_keys[e.key];
482   if (pane) {
483     y();
484     return pane_switch(pane);
485   }
486
487   let special_count_key = parseInt(e.key);
488   if (isFinite(special_count_key)) {
489     y();
490     if (special_count == null) special_count = 0;
491     special_count *= 10;
492     special_count += special_count_key;
493     special_count %= 100000;
494     mousecursor_etc_reupdate();
495     return;
496   }
497   if (e.key == ' ') {
498     y();
499     special_count = null;
500     mousecursor_etc_reupdate();
501     return;
502   }
503
504   let uo = uo_map[e.key];
505   if (uo === undefined || uo === null) return;
506
507   y();
508   console.log('KEY UO', e, uo);
509   if (uo.kind == 'Client' || uo.kind == 'ClientExtra') {
510     let f = keyops_local[uo.opname];
511     f(uo);
512     return;
513   }
514   if (!(uo.kind == 'Global' || uo.kind == 'GlobalExtra' || uo.kind == 'Piece'))
515     throw 'bad kind '+uo.kind;
516
517   for (var piece of uo.targets!) {
518     let p = pieces[piece]!;
519     api_piece('k', piece, p, { opname: uo.opname, wrc: uo.wrc });
520     if (uo.wrc == 'UpdateSvg') {
521       // No UpdateSvg is loose, so no need to check p.cseq_loose
522       p.cseq_updatesvg = p.cseq_main;
523       redisplay_ancillaries(piece,p);
524     }
525   }
526 }
527
528 function pane_switch(newpane: PaneName) {
529   let new_e;
530   for (;;) {
531     new_e = document.getElementById('pane_' + newpane)!;
532     let style = new_e.getAttribute('style');
533     if (style || newpane == 'help') break;
534     newpane = 'help';
535   }
536   for (let old_e = new_e.parentElement!.firstElementChild;
537        old_e;
538        old_e = old_e.nextElementSibling) {
539     old_e.setAttribute('style','display: none;');
540   }
541   new_e.removeAttribute('style');
542 }
543
544 function mousecursor_etc_reupdate() {
545   let style_elem = document.getElementById("space-cursor-style")!;
546   let style_text;
547   let svg;
548   let xy;
549   let path = 'stroke-linecap="square" d="M -10 -10 10 10 M 10 -10 -10 10"';
550   
551   if (wresting) {
552     let text;
553     if (special_count == null) {
554       text = "WREST";
555     } else if (special_count == 0) {
556       text = "W v";
557     } else {
558       text = "W " + special_count;
559     }
560     xy = '60 15';
561     svg =
562 `<svg xmlns="http://www.w3.org/2000/svg"
563      viewBox="-60 -15 120 60" width="120" height="60">
564   <g transform="translate(0 0)">
565     <path stroke-width="8" stroke="black" ${path}/>
566     <path stroke-width="4" stroke="#cc0" ${path}/>
567  <text x="0" y="40" fill="black" stroke="#cc0" stroke-width="1.7" text-align="center" text-anchor="middle"
568  font-family="sans-serif" font-size="30">${text}</text>
569   </g></svg>`;
570   } else if (special_count == null) {
571   } else {
572     if (special_count != 0) {
573       let text_len = special_count.toString().length;
574       let text_x = text_len <= 3 ? 0 : -15;
575       let text_size = text_len <= 3 ? 50 : 45 * (4/text_len);
576       xy = '15 50';
577       svg = 
578 `<svg xmlns="http://www.w3.org/2000/svg"
579      viewBox="-15 0 120 65" width="120" height="65">
580   <g transform="translate(0 50)">
581     <path stroke-width="8" stroke="#fcf" ${path}/>
582     <path stroke-width="4" stroke="purple" ${path}/>
583     <text x="${text_x}" y="0" fill="purple" stroke="#fcf" stroke-width="2"
584        font-family="sans-serif" font-size="${text_size}">${special_count}</text>
585   </g></svg>`;
586     } else {
587       let path = 'stroke-linecap="square" d="M -10 -10 0 0 10 -10 M 0 0 0 -20"';
588       xy = '15 30';
589       svg =
590 `<svg xmlns="http://www.w3.org/2000/svg"
591      viewBox="-15 -25 30 30" width="30" height="30">
592   <g transform="translate(0 0)">
593     <path stroke-width="8" stroke="#fcf" ${path}/>
594     <path stroke-width="4" stroke="purple" ${path}/>
595   </g></svg>`;
596     }
597   }
598   // Empirically, setting this to '' and then back to the SVG data
599   // seems to cause Firefox to update it more promptly.
600   style_elem.innerHTML = '';
601   if (svg !== undefined) {
602     let svg_data = btoa(svg);
603     style_text =
604 `svg[id=space] {
605   cursor: url(data:image/svg+xml;base64,${svg_data}) ${xy}, auto;
606 }`;
607     style_elem.innerHTML = style_text;
608   }
609   recompute_keybindings();
610 }
611
612 keyops_local['left' ] = function (uo: UoRecord) { rotate_targets(uo, +1); }
613 keyops_local['right'] = function (uo: UoRecord) { rotate_targets(uo, -1); }
614
615 function rotate_targets(uo: UoRecord, dangle: number): boolean {
616   for (let piece of uo.targets!) {
617     let p = pieces[piece]!;
618     if (!p.rotateable) continue;
619     p.angle += dangle + 8;
620     p.angle %= 8;
621     let transform = wasm_bindgen.angle_transform(p.angle);
622     p.pelem.setAttributeNS(null,'transform',transform);
623     api_piece('rotate', piece,p, p.angle);
624   }
625   recompute_keybindings();
626   return true;
627 }
628
629 // ----- lower -----
630
631 type LowerTodoItem = {
632   piece: PieceId,
633   p: PieceInfo,
634   heavy: boolean,
635 };
636
637 type LowerTodoList = { [piece: string]: LowerTodoItem };
638
639 keyops_local['lower'] = function (uo: UoRecord) { lower_targets(uo); }
640
641 function lower_heavy(p: PieceInfo): boolean {
642   return wresting || p.pinned || p.moveable == "No";
643 }
644
645 function lower_targets(uo: UoRecord): boolean {
646   let targets_todo : LowerTodoList = Object.create(null);
647
648   for (let piece of uo.targets!) {
649     let p = pieces[piece]!;
650     let heavy = lower_heavy(p);
651     targets_todo[piece] = { p, piece, heavy, };
652   }
653   let problem = lower_pieces(targets_todo);
654   if (problem !== null) {
655     add_log_message('Cannot lower: ' + problem);
656     return false;
657   }
658   return true;
659 }
660
661 function lower_pieces(targets_todo: LowerTodoList):
662  string | null
663 {
664   // This is a bit subtle.  We don't want to lower below heavy pieces
665   // (unless we are heavy too, or the user is wresting).  But maybe
666   // the heavy pieces aren't already at the bottom.  For now we will
667   // declare that all heavy pieces "should" be below all light
668   // ones.  Not as an invariant, but as a thing we will do here to try
669   // to make a sensible result.  We implement this as follows: if we
670   // find heavy pieces above light pieces, we move those heavy
671   // pieces to the bottom too, just below us, preserving their
672   // relative order.
673   //
674   // Disregarding heavy targets:
675   //
676   // Z     <some stuff not including any light targets>
677   // Z
678   //       topmost light target           *
679   // B (
680   // B     light non-target
681   // B |   light target                   *
682   // B |   heavy non-target, mis-stacked  *
683   // B )*
684   // B
685   //       bottommost light non-target
686   //        if that is below topmost light target
687   //            <- tomove_light: insert targets from * here           Q ->
688   //            <- tomove_misstacked: insert non-targets from * here  Q ->
689   //            <- heavy non-targets with clashing Z Coords           X ->
690   // A
691   // A     heavy non-targets (nomove_heavy)
692   //            <- tomove_heavy: insert all heavy targets here        P ->
693   //
694   // When wresting, treat all targets as heavy.
695
696   type Entry = {
697     piece: PieceId,
698     p: PieceInfo,
699   };
700   // bottom of the stack order first
701   let tomove_light       : Entry[] = [];
702   let tomove_misstacked  : Entry[] = [];
703   let nomove_heavy       : Entry[] = [];
704   let tomove_heavy       : Entry[] = [];
705
706                                                     //  A      B      Z
707   let q_z_top : ZCoord | null = null;               //  null   some   some
708   let n_targets_todo_light = 0;                     //                0
709
710   let any_targets = false;
711   for (const piece of Object.keys(targets_todo)) {
712     any_targets = true;
713     let p = targets_todo[piece];
714     if (!p.heavy) n_targets_todo_light++;
715   }
716   if (!any_targets) return 'Nothing to lower!';
717
718   let walk = pieces_marker;
719   for (;;) { // starting at the bottom of the stack order
720     if (Object.keys(targets_todo).length == 0 &&
721        q_z_top !== null) {
722       // no targets left, state Z, we can stop now
723       console.log('LOWER STATE Z FINISHED');
724       break;
725     }
726
727     let new_walk = walk.nextElementSibling;
728     if (new_walk == null) {
729       console.log('LOWER WALK NO SIBLING!');
730       break;
731     }
732     walk = new_walk as SVGGraphicsElement;
733     let piece = walk.dataset.piece;
734     if (piece == null) {
735       console.log('LOWER WALK REACHED TOP');
736       break;
737     }
738
739     let p = pieces[piece]!;
740     let todo = targets_todo[piece];
741     if (todo) {
742       let xst = '';
743       if (q_z_top === null && !todo.heavy) {
744         q_z_top = p.z;
745         xst = 'STATE -> B';
746       }
747       console.log('LOWER WALK', piece, 'TODO', todo.heavy ? "H" : "_", xst);
748       delete targets_todo[piece];
749       if (!todo.heavy) n_targets_todo_light--;
750       (todo.heavy ? tomove_heavy : tomove_light).push(todo);
751       continue;
752     }
753
754     let p_heavy = lower_heavy(p);
755     if (q_z_top === null) { // state A
756       if (!p_heavy) {
757         console.log('LOWER WALK', piece, 'STATE A -> Z');
758         q_z_top = p.z;
759       } else {
760         console.log('LOWER WALK', piece, 'STATE A');
761         nomove_heavy.push({ p, piece });
762       }
763       continue;
764     }
765
766     // state B
767     if (p_heavy) {
768       console.log('LOWER WALK', piece, 'STATE B MIS-STACKED');
769       tomove_misstacked.push({ p, piece });
770     } else {
771       console.log('LOWER WALK', piece, 'STATE B');
772     }
773   }
774
775   if (q_z_top === null) {
776     // Somehow we didn't find the top of Q, so we didn't meet any
777     // targets.  (In the walk loop, we always set q_z_top if todo.)
778     q_z_top =
779       tomove_misstacked.length ? tomove_misstacked[0].p.z :
780       tomove_light     .length ? tomove_light     [0].p.z :
781                                  tomove_heavy     [0].p.z;
782   }
783
784   while (nomove_heavy.length &&
785          (tomove_light.length || tomove_misstacked.length) &&
786          nomove_heavy[nomove_heavy.length-1].p.z == q_z_top) {
787     // Yowzer.  We have to reset the Z coordinates on these heavy
788     // pieces, whose Z coordinate is the same as the stuff we are not
789     // touching, because otherwise there is no gap.
790     //
791     // Treating them as misstacked instead is sufficient, provided
792     // we put them at the front (bottom end) of the misstacked list.
793     //
794     // This is X in the chart.
795     //
796     let restack = nomove_heavy.pop()!;
797     console.log('LOWER CLASHING Z - RESTACKING', restack);
798     tomove_misstacked.unshift(restack);
799   }
800
801   type PlanEntry = {
802     content: Entry[], // bottom to top
803     z_top: ZCoord,
804     z_bot: ZCoord | null,
805   };
806
807   let plan : PlanEntry[] = [];
808
809   console.log('LOWER PARTQ X', tomove_misstacked);
810   console.log('LOWER PARTQ L', tomove_light);
811   console.log('LOWER PARTP H', tomove_heavy);
812   let partQ = tomove_misstacked.concat(tomove_light);
813   let partP = tomove_heavy;
814
815   if (nomove_heavy.length == 0) {
816     plan.push({
817       content: partP.concat(partQ),
818       z_top: q_z_top,
819       z_bot : null,
820     });
821   } else {
822     plan.push({
823       content: partQ,
824       z_top: q_z_top,
825       z_bot: nomove_heavy[nomove_heavy.length-1].p.z,
826     }, {
827       content: partP,
828       z_top: nomove_heavy[0].p.z,
829       z_bot: null,
830     });
831   }
832
833   console.log('LOWER PLAN', plan);
834
835   for (const pe of plan) {
836     for (const e of pe.content) {
837       if (e.p.held != null && e.p.held != us) {
838         return "lowering would disturb a piece held by another player";
839       }
840     }
841   }
842
843   for (const pe of plan) {
844     let z_top = pe.z_top;
845     let z_bot = pe.z_bot;
846     if (! pe.content.length) continue;
847     if (z_bot == null) {
848       let first_z = pe.content[0].p.z;
849       if (z_top >= first_z)
850         z_top = first_z;
851     }
852     let zrange = wasm_bindgen.range(z_bot, z_top, pe.content.length);
853     console.log('LOQER PLAN PE',
854                 pe, z_bot, z_top, pe.content.length, zrange.debug());
855     for (const e of pe.content) {
856       let p = e.p;
857       p.held_us_raising = "Lowered";
858       piece_set_zlevel(e.piece, p, (oldtop_piece) => {
859         let z = zrange.next();
860         p.z = z;
861         api_piece("setz", e.piece, e.p, { z });
862       });
863     }
864   }
865   return null;
866 }
867
868 keyops_local['wrest'] = function (uo: UoRecord) {
869   wresting = !wresting;
870   document.getElementById('wresting-warning')!.innerHTML = !wresting ? "" :
871     " <strong>(wresting mode!)</strong>";
872   ungrab_all();
873   mousecursor_etc_reupdate();
874 }
875
876 keyops_local['motion-hint-history'] = function (uo: UoRecord) {
877   movehist_len_i ++;
878   movehist_len_i %= movehist_lens.length;
879   movehist_revisible();
880 }
881
882 keyops_local['pin'  ] = function (uo) {
883   if (!lower_targets(uo)) return;
884   pin_unpin(uo, true);
885 }
886 keyops_local['unpin'] = function (uo) {
887   pin_unpin(uo, false);
888 }
889
890 function pin_unpin(uo: UoRecord, newpin: boolean) {
891   for (let piece of uo.targets!) {
892     let p = pieces[piece]!;
893     p.pinned = newpin;
894     api_piece('pin', piece,p, newpin);
895     redisplay_ancillaries(piece,p);
896   }
897   recompute_keybindings();
898 }
899
900 // ----- raising -----
901
902 keyops_local['raise'] = function (uo: UoRecord) { raise_targets(uo); }
903
904 function raise_targets(uo: UoRecord) {
905   let any = false;
906   for (let piece of uo.targets!) {
907     let p = pieces[piece]!;
908     if (p.pinned || !piece_moveable(p)) continue;
909     any = true;
910     piece_raise(piece, p, "NotYet");
911   }
912   if (!any) { 
913     add_log_message('No pieces could be raised.');
914   }
915 }
916
917 function piece_raise(piece: PieceId, p: PieceInfo,
918                      new_held_us_raising: HeldUsRaising,
919   implement: (piece: PieceId, p: PieceInfo, z: ZCoord) => void
920   = function(piece: PieceId, p: PieceInfo, z: ZCoord) {
921     api_piece("setz", piece,p, { z: z });
922   })
923 {
924   p.held_us_raising = new_held_us_raising;
925   piece_set_zlevel(piece,p, (oldtop_piece) => {
926     let oldtop_p = pieces[oldtop_piece]!;
927     let z = wasm_bindgen.increment(oldtop_p.z);
928     p.z = z;
929     implement(piece,p,z);
930   });
931 }
932
933 // ----- clicking/dragging pieces -----
934
935 type DragInfo = {
936   piece : PieceId,
937   dox : number,
938   doy : number,
939 }
940
941 enum DRAGGING { // bitmask
942   NO           = 0x00,
943   MAYBE_GRAB   = 0x01,
944   MAYBE_UNGRAB = 0x02,
945   YES          = 0x04,
946   RAISED       = 0x08,
947 };
948
949 var drag_pieces : DragInfo[] = [];
950 var dragging = DRAGGING.NO;
951 var dcx : number | null;
952 var dcy : number | null;
953
954 const DRAGTHRESH = 5;
955
956 let rectsel_start: Pos | null;
957 let rectsel_shifted: boolean | null;
958 const RECTSELTHRESH = 5;
959
960 function piece_xy(p: PieceInfo): Pos {
961   return [ parseFloat(p.uelem.getAttributeNS(null,"x")!),
962            parseFloat(p.uelem.getAttributeNS(null,"y")!) ];
963 }
964
965 function drag_start_prepare(new_dragging: DRAGGING) {
966   dragging = new_dragging;
967
968   let spos_map = Object.create(null);
969   for (let piece of Object.keys(pieces)) {
970     let p = pieces[piece]!;
971     if (p.held != us) continue;
972     let spos = piece_xy(p);
973     let sposk = `${spos[0]} ${spos[1]}`;
974     if (spos_map[sposk] === undefined) spos_map[sposk] = [spos, []];
975     spos_map[sposk][1].push([spos, piece,p]);
976   }
977
978   for (let sposk of Object.keys(spos_map)) {
979     let [[dox, doy], ents] = spos_map[sposk];
980     for (let i=0; i<ents.length; i++) {
981       let [p, piece] = ents[i];
982       let delta = (-(ents.length-1)/2 + i) * SPECIAL_MULTI_DELTA_EACH;
983       p.drag_delta = Math.min(Math.max(delta, -SPECIAL_MULTI_DELTA_MAX),
984                                               +SPECIAL_MULTI_DELTA_MAX);
985       drag_pieces.push({
986         piece: piece,
987         dox: dox + p.drag_delta,
988         doy: doy,
989       });
990     }
991   }
992 }
993
994 function some_mousedown(e : MouseEvent) {
995   console.log('mousedown', e, e.clientX, e.clientY, e.target);
996
997   if (e.button != 0) { return }
998   if (e.altKey) { return }
999   if (e.metaKey) { return }
1000   if (e.ctrlKey) {
1001     return;
1002   } else {
1003     drag_mousedown(e, e.shiftKey);
1004   }
1005 }
1006
1007 type MouseFindClicked = null | {
1008   clicked: PieceId[],
1009   held: PlayerId | null,
1010   pinned: boolean,
1011   multigrab?: number,
1012 };
1013
1014 type PieceSet = { [piece: string]: true };
1015
1016 function grab_clicked(clicked: PieceId[], loose: boolean,
1017                       multigrab: number | undefined) {
1018   for (let piece of clicked) {
1019     let p = pieces[piece]!;
1020     set_grab_us(piece,p);
1021     if (multigrab === undefined) {
1022       api_piece_x(api_immediate, loose,
1023                   wresting ? 'wrest' : 'grab', piece,p, { });
1024     } else {
1025       piece_raise(piece,p, 'Raised', function(piece,p,z) {
1026         api_piece_x(api_immediate, loose, 'multigrab',
1027                     piece,p, { n: multigrab, z: z });
1028       })
1029     }
1030   }
1031 }
1032 function ungrab_clicked(clicked: PieceId[]) {
1033   let todo: [PieceId, PieceInfo][] = [];
1034   for (let tpiece of clicked) {
1035     let tp = pieces[tpiece]!;
1036     todo.push([tpiece, tp]);
1037   }
1038   do_ungrab_n(todo);
1039 }
1040
1041 function mouse_clicked_one(piece: PieceId, p: PieceInfo): MouseFindClicked {
1042   let held = p.held;
1043   let pinned = p.pinned;
1044   return { clicked: [piece], held, pinned };
1045 }
1046
1047 function mouse_find_predicate(
1048   wanted: number | null,
1049   allow_for_deselect: boolean,
1050   note_already: PieceSet | null,
1051   predicate: (p: PieceInfo) => boolean
1052 ): MouseFindClicked {
1053   let clicked: PieceId[];
1054   let held: string | null;
1055   let pinned = false;
1056   let already_count = 0;
1057
1058   clicked = [];
1059   let uelem = defs_marker;
1060   while (wanted == null || (clicked.length + already_count) < wanted) {
1061     let i = clicked.length;
1062     uelem = uelem.previousElementSibling as any;
1063     if (uelem == pieces_marker) {
1064       if (wanted != null) {
1065         add_log_message(`Not enough pieces!  Stopped after ${i}.`);
1066         return null;
1067       }
1068       break;
1069     }
1070     let piece = uelem.dataset.piece!;
1071
1072     function is_already() {
1073       if (note_already != null) {
1074         already_count++;
1075         note_already[piece] = true;
1076       }
1077     }
1078
1079     let p = pieces[piece];
1080     if (p.pinned && !wresting) continue;
1081     if (p.held && p.held != us && !wresting) continue;
1082     if (i > 0 && !piece_moveable(p))
1083       continue;
1084     if (!predicate(p)) {
1085       continue;
1086     }
1087     if (p.pinned) pinned = true;
1088
1089     if (i == 0) {
1090       held = p.held;
1091       if (held == us && !allow_for_deselect) held = null;
1092     }
1093     if (held! == us) {
1094       // user is going to be deselecting
1095       if (p.held != us) {
1096         // skip ones we don't have
1097         is_already();
1098         continue;
1099       }
1100     } else { // user is going to be selecting
1101       if (p.held == us) {
1102         is_already();
1103         continue; // skip ones we have already
1104       } else if (p.held == null) {
1105       } else {
1106         held = p.held; // wrestish
1107       }
1108     }
1109     clicked.push(piece);
1110   }
1111   if (clicked.length == 0) return null;
1112   else return { clicked, held: held!, pinned: pinned! };
1113 }
1114
1115 function mouse_find_lowest(e: MouseEvent) {
1116   let clickpos = mouseevent_pos(e);
1117   let uelem = pieces_marker;
1118   for (;;) {
1119     uelem = uelem.nextElementSibling as any;
1120     if (uelem == defs_marker) break;
1121     let piece = uelem.dataset.piece!;
1122     let p = pieces[piece]!;
1123     if (p_bbox_contains(p, clickpos)) {
1124       return mouse_clicked_one(piece, p);
1125     }
1126   }
1127   return null;
1128 }
1129
1130 function mouse_find_clicked(e: MouseEvent,
1131                             target: SVGGraphicsElement, piece: PieceId,
1132                             count_allow_for_deselect: boolean,
1133                             note_already: PieceSet | null,
1134                             ): MouseFindClicked
1135 {
1136   let p = pieces[piece]!;
1137   if (special_count == null) {
1138     return mouse_clicked_one(piece, p);
1139   } else if (special_count == 0) {
1140     return mouse_find_lowest(e);
1141   } else { // special_count > 0
1142     if (p.multigrab && !wresting) {
1143       let clicked = mouse_clicked_one(piece, p);
1144       if (clicked) clicked.multigrab = special_count;
1145       return clicked;
1146     } else {
1147       if (special_count > 99) {
1148         add_log_message(
1149           `Refusing to try to select ${special_count} pieces (max is 99)`);
1150         return null;
1151       }
1152       let clickpos = mouseevent_pos(e);
1153       return mouse_find_predicate(
1154         special_count, count_allow_for_deselect, note_already,
1155         function(p) { return p_bbox_contains(p, clickpos); }
1156       )
1157     }
1158   }
1159 }
1160
1161 function drag_mousedown(e : MouseEvent, shifted: boolean) {
1162   let target = e.target as SVGGraphicsElement; // we check this just now!
1163   let piece: PieceId | undefined = target.dataset.piece;
1164
1165   if (!piece) {
1166     rectsel_start = mouseevent_pos(e);
1167     rectsel_shifted = shifted;
1168     window.addEventListener('mousemove', rectsel_mousemove, true);
1169     window.addEventListener('mouseup',   rectsel_mouseup,   true);
1170     return;
1171   }
1172
1173   let note_already = shifted ? null : Object.create(null);
1174
1175   let c = mouse_find_clicked(e, target, piece, false, note_already);
1176   if (c == null) return;
1177   let clicked = c.clicked;
1178   let held = c.held;
1179   let pinned = c.pinned;
1180   let multigrab = c.multigrab;
1181
1182   special_count = null;
1183   mousecursor_etc_reupdate();
1184   drag_cancel();
1185
1186   drag_pieces = [];
1187   if (held == us) {
1188     if (shifted) {
1189       ungrab_clicked(clicked);
1190       return;
1191     }
1192     drag_start_prepare(DRAGGING.MAYBE_UNGRAB);
1193   } else if (held == null || wresting) {
1194     if (!shifted) {
1195       ungrab_all_except(note_already);
1196     }
1197     if (pinned && !wresting) {
1198       let p = pieces[c.clicked[0]!]!;
1199       add_log_message('That piece ('+p.desc+') is pinned to the table.');
1200       return;
1201     }
1202     grab_clicked(clicked, !wresting, multigrab);
1203     drag_start_prepare(DRAGGING.MAYBE_GRAB);
1204   } else {
1205     add_log_message('That piece is held by another player.');
1206     return;
1207   }
1208   dcx = e.clientX;
1209   dcy = e.clientY;
1210
1211   window.addEventListener('mousemove', drag_mousemove, true);
1212   window.addEventListener('mouseup',   drag_mouseup,   true);
1213 }
1214
1215 function mouseevent_pos(e: MouseEvent): Pos {
1216   let ctm = space.getScreenCTM()!;
1217   let px = (e.clientX - ctm.e)/(ctm.a * firefox_bug_zoom_factor_compensation);
1218   let py = (e.clientY - ctm.f)/(ctm.d * firefox_bug_zoom_factor_compensation);
1219   let pos: Pos = [px, py];
1220   console.log('mouseevent_pos', pos);
1221   return pos;
1222 }
1223
1224 function p_bbox_contains(p: PieceInfo, test: Pos) {
1225   let ctr = piece_xy(p);
1226   for (let i of [0,1]) {
1227     let offset = test[i] - ctr[i];
1228     if (offset < p.bbox[0][i] || offset > p.bbox[1][i])
1229       return false;
1230   }
1231   return true;
1232 }
1233
1234 function do_ungrab_n(todo: [PieceId, PieceInfo][]) {
1235   function sort_with(a: [PieceId, PieceInfo],
1236                      b: [PieceId, PieceInfo]): number {
1237     return piece_z_cmp(a[1], b[1]);
1238   }
1239   todo.sort(sort_with);
1240   for (let [tpiece, tp] of todo) {
1241     do_ungrab_1(tpiece, tp);
1242   }
1243 }
1244 function ungrab_all_except(dont: PieceSet | null) {
1245   let todo: [PieceId, PieceInfo][] =  [];
1246   for (let tpiece of Object.keys(pieces)) {
1247     if (dont && dont[tpiece]) continue;
1248     let tp = pieces[tpiece]!;
1249     if (tp.held == us) {
1250       todo.push([tpiece, tp]);
1251     }
1252   }
1253   do_ungrab_n(todo);
1254 }
1255 function ungrab_all() {
1256   ungrab_all_except(null);
1257 }
1258
1259 function set_grab_us(piece: PieceId, p: PieceInfo) {
1260   p.held = us;
1261   p.held_us_raising = "NotYet";
1262   p.drag_delta = 0;
1263   redisplay_ancillaries(piece,p);
1264   recompute_keybindings();
1265 }
1266 function do_ungrab_1(piece: PieceId, p: PieceInfo) {
1267   let autoraise = p.held_us_raising == "Raised";
1268   p.held = null;
1269   p.held_us_raising = "NotYet";
1270   p.drag_delta = 0;
1271   redisplay_ancillaries(piece,p);
1272   recompute_keybindings();
1273   api_piece('ungrab', piece,p, { autoraise });
1274 }
1275
1276 function clear_halo(piece: PieceId, p: PieceInfo) {
1277   let was = p.last_seen_moved;
1278   p.last_seen_moved = null;
1279   if (was) redisplay_ancillaries(piece,p);
1280 }
1281
1282 function ancillary_node(piece: PieceId, stroke: string): SVGGraphicsElement {
1283   var nelem = document.createElementNS(svg_ns,'use');
1284   nelem.setAttributeNS(null,'href','#surround'+piece);
1285   nelem.setAttributeNS(null,'stroke',stroke);
1286   nelem.setAttributeNS(null,'fill','none');
1287   return nelem as any;
1288 }
1289
1290 function redisplay_ancillaries(piece: PieceId, p: PieceInfo) {
1291   let href = '#surround'+piece;
1292   console.log('REDISPLAY ANCILLARIES',href);
1293
1294   for (let celem = p.pelem.firstElementChild;
1295        celem != null;
1296        celem = nextelem) {
1297     var nextelem = celem.nextElementSibling
1298     let thref = celem.getAttributeNS(null,"href");
1299     if (thref == href) {
1300       celem.remove();
1301     }
1302   }
1303
1304   let halo_colour = null;
1305   if (p.cseq_updatesvg != null) {
1306     halo_colour = 'purple';
1307   } else if (p.last_seen_moved != null) {
1308     halo_colour = 'yellow';
1309   } else if (p.held != null && p.pinned) {
1310     halo_colour = '#8cf';
1311   }
1312   if (halo_colour != null) {
1313     let nelem = ancillary_node(piece, halo_colour);
1314     if (p.held != null) {
1315       // value 2ps is also in src/pieces.rs SELECT_STROKE_WIDTH
1316       nelem.setAttributeNS(null,'stroke-width','2px');
1317     }
1318     p.pelem.prepend(nelem);
1319   } 
1320   if (p.held != null) {
1321     let da = null;
1322     if (p.held != us) {
1323       da = players[p.held!]!.dasharray;
1324     } else {
1325       let [px, py] = piece_xy(p);
1326       let inoccult = occregions.contains_pos(px, py);
1327       p.held_us_inoccult = inoccult;
1328       if (inoccult) {
1329         da = "0.9 0.6"; // dotted dasharray
1330       }
1331     }
1332     let nelem = ancillary_node(piece, held_surround_colour);
1333     if (da !== null) {
1334       nelem.setAttributeNS(null,'stroke-dasharray',da);
1335     }
1336     p.pelem.appendChild(nelem);
1337   }
1338 }
1339
1340 function drag_mousemove(e: MouseEvent) {
1341   var ctm = space.getScreenCTM()!;
1342   var ddx = (e.clientX - dcx!)/(ctm.a * firefox_bug_zoom_factor_compensation);
1343   var ddy = (e.clientY - dcy!)/(ctm.d * firefox_bug_zoom_factor_compensation);
1344   var ddr2 = ddx*ddx + ddy*ddy;
1345   if (!(dragging & DRAGGING.YES)) {
1346     if (ddr2 > DRAGTHRESH) {
1347       for (let dp of drag_pieces) {
1348         let tpiece = dp.piece;
1349         let tp = pieces[tpiece]!;
1350         if (tp.moveable == "Yes") {
1351           continue;
1352         } else if (tp.moveable == "IfWresting") {
1353           if (wresting) continue;
1354           add_log_message('That piece can only be moved when Wresting.');
1355         } else {
1356           add_log_message('That piece cannot be moved at the moment.');
1357         }
1358         return ddr2;
1359       }
1360       dragging |= DRAGGING.YES;
1361     }
1362   }
1363   //console.log('mousemove', ddx, ddy, dragging);
1364   if (dragging & DRAGGING.YES) {
1365     console.log('DRAG PIECES',drag_pieces);
1366     for (let dp of drag_pieces) {
1367       console.log('DRAG PIECES PIECE',dp);
1368       let tpiece = dp.piece;
1369       let tp = pieces[tpiece]!;
1370       var x = Math.round(dp.dox + ddx);
1371       var y = Math.round(dp.doy + ddy);
1372       let need_redisplay_ancillaries = (
1373         tp.held == us &&
1374         occregions.contains_pos(x,y) != tp.held_us_inoccult
1375       );
1376       piece_set_pos_core(tp, x, y);
1377       tp.queued_moves++;
1378       api_piece_x(api_delay, false, 'm', tpiece,tp, [x, y] );
1379       if (need_redisplay_ancillaries) redisplay_ancillaries(tpiece, tp);
1380     }
1381     if (!(dragging & DRAGGING.RAISED)) {
1382       sort_drag_pieces();
1383       for (let dp of drag_pieces) {
1384         let piece = dp.piece;
1385         let p = pieces[piece]!;
1386         if (p.held_us_raising == "Lowered") continue;
1387         let dragraise = +p.pelem.dataset.dragraise!;
1388         if (dragraise > 0 && ddr2 >= dragraise*dragraise) {
1389           dragging |= DRAGGING.RAISED;
1390           console.log('CHECK RAISE ', dragraise, dragraise*dragraise, ddr2);
1391           piece_raise(piece,p,"Raised");
1392         }
1393       }
1394     }
1395   }
1396   return ddr2;
1397 }
1398 function sort_drag_pieces() {
1399   function sort_with(a: DragInfo, b: DragInfo): number {
1400     return pieceid_z_cmp(a.piece,
1401                          b.piece);
1402   }
1403   drag_pieces.sort(sort_with);
1404 }
1405
1406 function drag_mouseup(e: MouseEvent) {
1407   console.log('mouseup', dragging);
1408   let ddr2 : number = drag_mousemove(e);
1409   drag_end();
1410 }
1411
1412 function drag_end() {
1413   if (dragging == DRAGGING.MAYBE_UNGRAB ||
1414       (dragging & ~DRAGGING.RAISED) == (DRAGGING.MAYBE_GRAB | DRAGGING.YES)) {
1415     sort_drag_pieces();
1416     for (let dp of drag_pieces) {
1417       let piece = dp.piece;
1418       let p = pieces[piece]!;
1419       do_ungrab_1(piece,p);
1420     }
1421   }
1422   drag_cancel();
1423 }
1424
1425 function drag_cancel() {
1426   window.removeEventListener('mousemove', drag_mousemove, true);
1427   window.removeEventListener('mouseup',   drag_mouseup,   true);
1428   dragging = DRAGGING.NO;
1429   drag_pieces = [];
1430 }
1431
1432 function rectsel_nontrivial_pos2(e: MouseEvent): Pos | null {
1433   let pos2 = mouseevent_pos(e);
1434   let d2 = 0;
1435   for (let i of [0,1]) {
1436     let d = pos2[i] - rectsel_start![i];
1437     d2 += d*d;
1438   }
1439   return d2 > RECTSELTHRESH*RECTSELTHRESH ? pos2 : null;
1440 }
1441
1442 function rectsel_mousemove(e: MouseEvent) {
1443   let pos2 = rectsel_nontrivial_pos2(e);
1444   let path;
1445   if (pos2 == null) {
1446     path = "";
1447   } else {
1448     let pos1 = rectsel_start!;
1449     path = `M ${ pos1 [0]} ${ pos1 [1] }
1450               ${ pos2 [0]} ${ pos1 [1] }
1451             M ${ pos1 [0]} ${ pos2 [1] }
1452               ${ pos2 [0]} ${ pos2 [1] }
1453             M ${ pos1 [0]} ${ pos1 [1] }
1454               ${ pos1 [0]} ${ pos2 [1] }
1455             M ${ pos2 [0]} ${ pos1 [1] }
1456               ${ pos2 [0]} ${ pos2 [1] }`;
1457   }
1458   rectsel_path.firstElementChild!.setAttributeNS(null,'d',path);
1459 }
1460
1461 function rectsel_mouseup(e: MouseEvent) {
1462   console.log('rectsel mouseup');
1463   window.removeEventListener('mousemove', rectsel_mousemove, true);
1464   window.removeEventListener('mouseup',   rectsel_mouseup,   true);
1465   rectsel_path.firstElementChild!.setAttributeNS(null,'d','');
1466   let pos2 = rectsel_nontrivial_pos2(e);
1467
1468   if (pos2 == null) {
1469     // clicked not on a piece, and didn't drag
1470     special_count = null;
1471     mousecursor_etc_reupdate();
1472     // we'll bail in a moment, after possibly unselecting things
1473   }
1474
1475   let note_already = Object.create(null);
1476   let c = null;
1477
1478   if (pos2 != null) {
1479     if (special_count != null && special_count == 0) {
1480       add_log_message(`Cannot drag-select lowest.`);
1481       return;
1482     }
1483     let tl = [0,0];
1484     let br = [0,0];
1485     for (let i of [0,1]) {
1486       tl[i] = Math.min(rectsel_start![i], pos2[i]);
1487       br[i] = Math.max(rectsel_start![i], pos2[i]);
1488     }
1489     c = mouse_find_predicate(
1490       special_count, rectsel_shifted!, note_already,
1491       function(p: PieceInfo) {
1492         let pp = piece_xy(p);
1493         for (let i of [0,1]) {
1494           if (pp[i] < tl[i] || pp[i] > br[i]) return false;
1495         }
1496         return true;
1497       }
1498     );
1499   }
1500
1501   if (!c) {
1502     // clicked not on a piece, didn't end up selecting anything
1503     // either because drag region had nothing in it, or special
1504     // failed, or some such.
1505     if (!rectsel_shifted) {
1506       let mr;
1507       while (mr = movements.pop()) {
1508         mr.p.last_seen_moved = null;
1509         redisplay_ancillaries(mr.piece, mr.p);
1510       }
1511       ungrab_all();
1512     }
1513     return;
1514   }
1515
1516   // did the special
1517   special_count = null;
1518   mousecursor_etc_reupdate();
1519
1520   if (rectsel_shifted && c.held == us) {
1521     ungrab_clicked(c.clicked);
1522     return;
1523   } else {
1524     if (!rectsel_shifted) {
1525       ungrab_all_except(note_already);
1526     }
1527     grab_clicked(c.clicked, false, undefined);
1528   }
1529 }
1530
1531 // ----- general -----
1532
1533 type PlayersUpdate = { new_info_pane: string };
1534
1535 messages.SetPlayer = <MessageHandler>function
1536 (j: { player: string, data: PlayerInfo } & PlayersUpdate) {
1537   players[j.player] = j.data;
1538   player_info_pane_set(j);
1539 }
1540
1541 messages.RemovePlayer = <MessageHandler>function
1542 (j: { player: string } & PlayersUpdate ) {
1543   delete players[j.player];
1544   player_info_pane_set(j);
1545 }
1546
1547 function player_info_pane_set(j: PlayersUpdate) {
1548   document.getElementById('player_list')!
1549     .innerHTML = j.new_info_pane;
1550 }
1551
1552 messages.UpdateBundles = <MessageHandler>function
1553 (j: { new_info_pane: string }) {
1554   document.getElementById('bundle_list')!
1555     .innerHTML = j.new_info_pane;
1556 }
1557
1558 messages.SetTableSize = <MessageHandler>function
1559 ([x, y]: [number, number]) {
1560   function set_attrs(elem: Element, l: [string,string][]) {
1561     for (let a of l) {
1562       elem.setAttributeNS(null,a[0],a[1]);
1563     }
1564   }
1565   let rect = document.getElementById('table_rect')!;
1566   set_attrs(space, wasm_bindgen.space_table_attrs(x, y));
1567   set_attrs(rect,  wasm_bindgen.space_table_attrs(x, y));
1568 }
1569
1570 messages.SetTableColour = <MessageHandler>function
1571 (c: string) {
1572   let rect = document.getElementById('table_rect')!;
1573   rect.setAttributeNS(null, 'fill', c);
1574 }
1575
1576 messages.SetLinks = <MessageHandler>function
1577 (msg: string) {
1578   if (msg.length != 0 && layout == 'Portrait') {
1579     msg += " |";
1580   }
1581   links_elem.innerHTML = msg
1582 }
1583
1584 // ---------- movehist ----------
1585
1586 type MoveHistEnt = {
1587   held: PlayerId,
1588   posx: [MoveHistPosx, MoveHistPosx],
1589   diff: { 'Moved': { d: number } },
1590 }
1591 type MoveHistPosx = {
1592   pos: Pos,
1593   angle: CompassAngle,
1594   facehint: FaceId | null,
1595 }
1596
1597 messages.MoveHistEnt = <MessageHandler>movehist_record;
1598 messages.MoveHistClear = <MessageHandler>function() {
1599   movehist_revisible_custmax(0);
1600 }
1601
1602 function movehist_record(ent: MoveHistEnt) {
1603   let old_pos = ent.posx[0].pos;
1604   let new_pos = ent.posx[1].pos;
1605
1606   movehist_gen++;
1607   movehist_gen %= (movehist_len_max * 2);
1608   let meid = 'motionhint-marker-' + movehist_gen;
1609
1610   let moved = ent.diff['Moved'];
1611   if (moved) {
1612     let d = moved.d;
1613     let ends = [];
1614     for (let end of [0,1]) {
1615       let s = (!end ? MOVEHIST_ENDS : d - MOVEHIST_ENDS) / d;
1616       ends.push([ (1-s) * old_pos[0] + s * new_pos[0],
1617                   (1-s) * old_pos[1] + s * new_pos[1] ]);
1618     }
1619     let g = document.createElementNS(svg_ns,'g');
1620     let sz = 4;
1621     let pi = players[ent.held];
1622     let nick = pi ? pi.nick : '';
1623     // todo: would be nice to place text variously along arrow, rotated
1624     let svg = `
1625       <marker id="${meid}" viewBox="2 0 ${sz} ${sz}" 
1626         refX="${sz}" refY="${sz/2}"
1627         markerWidth="${sz + 2}" markerHeight="${sz}"
1628         stroke="yellow" fill="none"
1629         orient="auto-start-reverse" stroke-linejoin="miter">
1630         <path d="M 0 0 L ${sz} ${sz/2} L 0 ${sz}" />
1631       </marker>
1632       <line x1="${ends[0][0].toString()}"
1633             y1="${ends[0][1].toString()}"
1634             x2="${ends[1][0].toString()}"
1635             y2="${ends[1][1].toString()}"
1636             stroke="yellow"
1637             stroke-width="1" pointer-events="none"
1638             marker-end="url(#${meid})" />
1639       <text x="${((ends[0][0] + ends[1][0]) / 2).toString()}"
1640             y="${((ends[0][1] + ends[1][1]) / 2).toString()}"
1641             font-size="5" pointer-events="none"
1642             stroke-width="0.1">${nick}</text>
1643     `;
1644     g.innerHTML = svg;
1645     space.insertBefore(g, movehist_end);
1646     movehist_revisible();
1647   }
1648 }
1649
1650 function movehist_revisible() { 
1651   movehist_revisible_custmax(movehist_len_max);
1652 }
1653
1654 function movehist_revisible_custmax(len_max: number) {
1655   let n = movehist_lens[movehist_len_i];
1656   let i = 0;
1657   let node = movehist_end;
1658   while (i < len_max) {
1659     i++; // i now eg 1..10
1660     node = node.previousElementSibling! as SVGGraphicsElement;
1661     if (node == movehist_start)
1662       return;
1663     let prop = i > n ? 0 : (n-i+1)/n;
1664     let stroke = (prop * 1.0).toString();
1665     let marker = node.firstElementChild!;
1666     marker.setAttributeNS(null,'stroke-width',stroke);
1667     let line = marker.nextElementSibling!;
1668     line.setAttributeNS(null,'stroke-width',stroke);
1669     let text = line.nextElementSibling!;
1670     if (!prop) {
1671       text.setAttributeNS(null,'stroke','none');
1672       text.setAttributeNS(null,'fill','none');
1673     } else {
1674       text.setAttributeNS(null,'fill','yellow');
1675       text.setAttributeNS(null,'stroke','orange');
1676     }
1677   }
1678   for (;;) {
1679     let del = node.previousElementSibling!;
1680     if (del == movehist_start)
1681       return;
1682     del.remove();
1683   }
1684 }  
1685
1686 // ----- logs -----
1687
1688 messages.Log = <MessageHandler>function
1689 (j: { when: string, logent: { html: string } }) {
1690   add_timestamped_log_message(j.when, j.logent.html);
1691 }
1692
1693 function add_log_message(msg_html: string) {
1694   add_timestamped_log_message('', msg_html);
1695 }
1696
1697 function add_timestamped_log_message(ts_html: string, msg_html: string) {
1698   var lastent = log_elem.lastElementChild;
1699   var in_scrollback =
1700     lastent == null ||
1701     // inspired by
1702     //   https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling/21627295#21627295
1703     // rejected
1704       //   https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
1705       (() => {
1706         let le_top = lastent.getBoundingClientRect()!.top;
1707         let le_bot = lastent.getBoundingClientRect()!.bottom;
1708         let ld_bot = logscroll_elem.getBoundingClientRect()!.bottom;
1709         console.log("ADD_LOG_MESSAGE bboxes: le t b, bb",
1710                     le_top, le_bot, ld_bot);
1711         return 0.5 * (le_bot + le_top) > ld_bot;
1712       })();
1713
1714   console.log('ADD LOG MESSAGE ',in_scrollback, layout, msg_html);
1715
1716   var ne : HTMLElement;
1717
1718   function add_thing(elemname: string, cl: string, html: string) {
1719     var ie = document.createElement(elemname);
1720     ie.innerHTML = html;
1721     ie.setAttribute("class", cl);
1722     ne.appendChild(ie);
1723   }
1724
1725   if (layout == 'Portrait') {
1726     ne = document.createElement('tr');
1727     add_thing('td', 'logmsg', msg_html);
1728     add_thing('td', 'logts',  ts_html);
1729   } else if (layout == 'Landscape') {
1730     ts_html = last_log_ts.update(ts_html);
1731     ne = document.createElement('div');
1732     add_thing('span', 'logts',  ts_html);
1733     ne.appendChild(document.createElement('br'));
1734     add_thing('span', 'logmsg', msg_html);
1735     ne.appendChild(document.createElement('br'));
1736   } else {
1737     throw 'bad layout ' + layout;
1738   }
1739   log_elem.appendChild(ne);
1740
1741   if (!in_scrollback) {
1742     logscroll_elem.scrollTop = logscroll_elem.scrollHeight;
1743   }
1744 }
1745
1746 // ----- zoom -----
1747
1748 function zoom_pct (): number | undefined {
1749   let str = zoom_val.value;
1750   let val = parseFloat(str);
1751   if (isNaN(val)) {
1752     return undefined;
1753   } else {
1754     return val;
1755   }
1756 }
1757
1758 function zoom_enable() {
1759   zoom_btn.disabled = (zoom_pct() === undefined);
1760 }
1761
1762 function zoom_activate() {
1763   let pct = zoom_pct();
1764   if (pct !== undefined) {
1765     let fact = pct * 0.01;
1766     let last_ctm_a = space.getScreenCTM()!.a;
1767     (document.getElementsByTagName('body')[0] as HTMLElement)
1768       .style.transform = 'scale('+fact+','+fact+')';
1769     if (fact != last_zoom_factor) {
1770       if (last_ctm_a == space.getScreenCTM()!.a) {
1771         console.log('FIREFOX GETSCREENCTM BUG');
1772         firefox_bug_zoom_factor_compensation = fact;
1773       } else {
1774         console.log('No firefox getscreenctm bug');
1775         firefox_bug_zoom_factor_compensation = 1.0;
1776       }
1777       last_zoom_factor = fact;
1778     }
1779   }
1780   zoom_btn.disabled = true;
1781 }
1782
1783 // ----- test counter, startup -----
1784
1785 type TransmitUpdateEntry_Piece = {
1786   piece: PieceId,
1787   op: Object,
1788 };
1789 type ErrorTransmitUpdateEntry_Piece = TransmitUpdateEntry_Piece & {
1790   cseq: ClientSeq | null,
1791 };
1792
1793 function handle_piece_update(j: TransmitUpdateEntry_Piece) {
1794   console.log('PIECE UPDATE ',j)
1795   var piece = j.piece;
1796   var m = j.op as { [k: string]: Object };
1797   var k = Object.keys(m)[0];
1798   let p = pieces[piece];
1799   pieceops[k](piece,p, m[k]);
1800 };
1801
1802 messages.Piece = <MessageHandler>handle_piece_update;
1803
1804 type PreparedPieceState = {
1805   pos: Pos,
1806   svg: string,
1807   desc: string,
1808   held: PlayerId | null,
1809   z: ZCoord,
1810   zg: Generation,
1811   pinned: boolean,
1812   angle: number,
1813   uos: UoDescription[],
1814   moveable: PieceMoveable,
1815   rotateable: boolean,
1816   multigrab: boolean,
1817   occregion: string | null,
1818   bbox: Rect,
1819 }
1820
1821 pieceops.ModifyQuiet = <PieceHandler>function
1822 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1823   console.log('PIECE UPDATE MODIFY QUIET ',piece,info)
1824   piece_modify(piece, p, info);
1825 }
1826
1827 pieceops.Modify = <PieceHandler>function
1828 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1829   console.log('PIECE UPDATE MODIFY LOuD ',piece,info)
1830   piece_note_moved(piece,p);
1831   piece_modify(piece, p, info);
1832 }
1833
1834 pieceops.InsertQuiet = <PieceHandler>(insert_piece as any);
1835 pieceops.Insert = <PieceHandler>function
1836 (piece: PieceId, xp: any, info: PreparedPieceState) {
1837   let p = insert_piece(piece,xp,info);
1838   piece_note_moved(piece,p);
1839 }
1840
1841 function insert_piece(piece: PieceId, xp: any,
1842                       info: PreparedPieceState): PieceInfo
1843 {
1844   console.log('PIECE UPDATE INSERT ',piece,info)
1845   let delem = document.createElementNS(svg_ns,'defs');
1846   delem.setAttributeNS(null,'id','defs'+piece);
1847   delem.innerHTML = info.svg;
1848   defs_marker.insertAdjacentElement('afterend', delem);
1849   let pelem = piece_element('piece',piece);
1850   let uelem = document.createElementNS(svg_ns,'use');
1851   uelem.setAttributeNS(null,'id',"use"+piece);
1852   uelem.setAttributeNS(null,'href',"#piece"+piece);
1853   uelem.setAttributeNS(null,'data-piece',piece);
1854   let p = {
1855     uelem: uelem,
1856     pelem: pelem,
1857     delem: delem,
1858   } as any as PieceInfo; // fudge this, piece_modify_core will fix it
1859   pieces[piece] = p;
1860   p.uos = info.uos;
1861   p.queued_moves = 0;
1862   piece_resolve_special(piece, p);
1863   piece_modify_core(piece, p, info);
1864   return p;
1865 }
1866
1867 pieceops.Delete = <PieceHandler>function
1868 (piece: PieceId, p: PieceInfo, info: {}) {
1869   console.log('PIECE UPDATE DELETE ', piece)
1870   piece_stop_special(piece, p);
1871   p.uelem.remove();
1872   p.delem.remove();
1873   delete pieces[piece];
1874   if (p.held == us) {
1875     recompute_keybindings();
1876   }
1877 }
1878
1879 piece_error_handlers.PosOffTable = <PieceErrorHandler>function()
1880 { return true ; }
1881 piece_error_handlers.Conflict = <PieceErrorHandler>function()
1882 { return true ; }
1883
1884 function piece_modify_image(piece: PieceId, p: PieceInfo,
1885                             info: PreparedPieceImage) {
1886   p.delem.innerHTML = info.svg;
1887   p.pelem= piece_element('piece',piece)!;
1888   p.uos = info.uos;
1889   p.bbox = info.bbox;
1890   p.desc = info.desc;
1891   piece_resolve_special(piece, p);
1892 }
1893
1894 function piece_resolve_special(piece: PieceId, p: PieceInfo) {
1895   let new_special =
1896       p.pelem.dataset.special ?
1897       JSON.parse(p.pelem.dataset.special) : null;
1898   let new_special_kind = new_special ? new_special.kind : '';
1899   let old_special_kind = p  .special ? p  .special.kind : '';
1900
1901   if (new_special_kind != old_special_kind) {
1902     piece_stop_special(piece, p);
1903   }
1904   if (new_special) {
1905     console.log('SPECIAL START', new_special);
1906     new_special.stop = function() { };
1907     p.special = new_special;
1908     special_renderings[new_special_kind](piece, p, new_special);
1909   }
1910 }
1911
1912 function piece_stop_special(piece: PieceId, p: PieceInfo) {
1913   let s = p.special;
1914   p.special = null;
1915   if (s) {
1916     console.log('SPECIAL STOP', s);
1917     s.stop(piece, p, s);
1918   }
1919 }
1920
1921 function piece_modify(piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1922   piece_modify_image(piece, p, info);
1923   piece_modify_core(piece, p, info);
1924 }
1925                        
1926 function piece_set_pos_core(p: PieceInfo, x: number, y: number) {
1927   p.uelem.setAttributeNS(null, "x", x+"");
1928   p.uelem.setAttributeNS(null, "y", y+"");
1929 }
1930
1931 function piece_modify_core(piece: PieceId, p: PieceInfo,
1932                            info: PreparedPieceState) {
1933   p.uelem.setAttributeNS(null, "x", info.pos[0]+"");
1934   p.uelem.setAttributeNS(null, "y", info.pos[1]+"");
1935   p.held = info.held;
1936   p.held_us_raising = "NotYet";
1937   p.pinned = info.pinned;
1938   p.moveable = info.moveable;
1939   p.rotateable = info.rotateable;
1940   p.multigrab = info.multigrab;
1941   p.angle = info.angle;
1942   p.bbox = info.bbox;
1943   piece_set_zlevel_from(piece,p,info);
1944   let occregions_changed = occregion_update(piece, p, info);
1945   piece_checkconflict_nrda(piece,p);
1946   redisplay_ancillaries(piece,p);
1947   if (occregions_changed) redisplay_held_ancillaries();
1948   recompute_keybindings();
1949   console.log('MODIFY DONE');
1950 }
1951 function occregion_update(piece: PieceId, p: PieceInfo,
1952                           info: PreparedPieceState) {
1953   let occregions_changed = (
1954     info.occregion != null
1955       ? occregions.insert(piece, info.occregion)
1956       : occregions.remove(piece)
1957   );
1958   return occregions_changed;
1959 }
1960 function redisplay_held_ancillaries() {
1961   for (let piece of Object.keys(pieces)) {
1962     let p = pieces[piece];
1963     if (p.held != us) continue;
1964     redisplay_ancillaries(piece,p);
1965   }
1966 }
1967
1968 type PreparedPieceImage = {
1969   svg: string,
1970   desc: string,
1971   uos: UoDescription[],
1972   bbox: Rect,
1973 }
1974
1975 type TransmitUpdateEntry_Image = {
1976   piece: PieceId,
1977   im: PreparedPieceImage,
1978 };
1979
1980 messages.Image = <MessageHandler>function(j: TransmitUpdateEntry_Image) {
1981   console.log('IMAGE UPDATE ',j)
1982   var piece = j.piece;
1983   let p = pieces[piece]!;
1984   piece_modify_image(piece, p, j.im);
1985   redisplay_ancillaries(piece,p);
1986   recompute_keybindings();
1987   console.log('IMAGE DONE');
1988 }
1989
1990 function piece_set_zlevel(piece: PieceId, p: PieceInfo,
1991                           modify : (oldtop_piece: PieceId) => void) {
1992   // Calls modify, which should set .z and/or .gz, and/or
1993   // make any necessary API call.
1994   //
1995   // Then moves uelem to the right place in the DOM.  This is done
1996   // by assuming that uelem ought to go at the end, so this is
1997   // O(new depth), which is right (since the UI for inserting
1998   // an object is itself O(new depth) UI operations to prepare.
1999
2000   let oldtop_elem = (defs_marker.previousElementSibling! as
2001                      unknown as SVGGraphicsElement);
2002   let oldtop_piece = oldtop_elem.dataset.piece!;
2003   modify(oldtop_piece);
2004
2005   let ins_before = defs_marker
2006   let earlier_elem;
2007   for (; ; ins_before = earlier_elem) {
2008     earlier_elem = (ins_before.previousElementSibling! as
2009                    unknown as SVGGraphicsElement);
2010     if (earlier_elem == pieces_marker) break;
2011     if (earlier_elem == p.uelem) continue;
2012     let earlier_p = pieces[earlier_elem.dataset.piece!]!;
2013     if (!piece_z_before(p, earlier_p)) break;
2014   }
2015   if (ins_before != p.uelem)
2016     space.insertBefore(p.uelem, ins_before);
2017
2018   check_z_order();
2019 }
2020
2021 function check_z_order() {
2022   if (!otter_debug) return;
2023   let s = pieces_marker;
2024   let last_z = "";
2025   for (;;) {
2026     s = s.nextElementSibling as SVGGraphicsElement;
2027     if (s == defs_marker) break;
2028     let piece = s.dataset.piece!;
2029     let z = pieces[piece].z;
2030     if (z < last_z) {
2031       json_report_error(['Z ORDER INCONSISTENCY!', piece, z, last_z]);
2032     }
2033     last_z = z;
2034   }
2035 }
2036
2037 function piece_note_moved(piece: PieceId, p: PieceInfo) {
2038   let now = performance.now();
2039
2040   let need_redisplay = p.last_seen_moved == null;
2041   p.last_seen_moved = now;
2042   if (need_redisplay) redisplay_ancillaries(piece,p);
2043
2044   let cutoff = now-1000.;
2045   while (movements.length > 0 && movements[0].this_motion < cutoff) {
2046     let mr = movements.shift()!;
2047     if (mr.p.last_seen_moved != null &&
2048         mr.p.last_seen_moved < cutoff) {
2049       mr.p.last_seen_moved = null;
2050       redisplay_ancillaries(mr.piece,mr.p);
2051     }
2052   }
2053
2054   movements.push({ piece: piece, p: p, this_motion: now });
2055 }
2056
2057 function piece_z_cmp(a: PieceInfo, b: PieceInfo) {
2058   if (a.z  < b.z ) return -1;
2059   if (a.z  > b.z ) return +1;
2060   if (a.zg < b.zg) return -1;
2061   if (a.zg > b.zg) return +1;
2062   return 0;
2063 }
2064
2065 function piece_z_before(a: PieceInfo, b: PieceInfo) {
2066   return piece_z_cmp(a,
2067                      b) < 0;
2068 }
2069
2070 function pieceid_z_cmp(a: PieceId, b: PieceId) {
2071   return piece_z_cmp(pieces[a]!,
2072                      pieces[b]!);
2073 }
2074
2075 pieceops.Move = <PieceHandler>function
2076 (piece,p, info: Pos ) {
2077   piece_checkconflict_nrda(piece,p);
2078   piece_note_moved(piece, p);
2079   piece_set_pos_core(p, info[0], info[1]);
2080 }
2081
2082 pieceops.MoveQuiet = <PieceHandler>function
2083 (piece,p, info: Pos ) {
2084   piece_checkconflict_nrda(piece,p);
2085   piece_set_pos_core(p, info[0], info[1]);
2086 }
2087
2088 pieceops.SetZLevel = <PieceHandler>function
2089 (piece,p, info: { z: ZCoord, zg: Generation }) {
2090   piece_note_moved(piece,p);
2091   piece_set_zlevel_from(piece,p,info);
2092 }
2093
2094 pieceops.SetZLevelQuiet = <PieceHandler>function
2095 (piece,p, info: { z: ZCoord, zg: Generation }) {
2096   piece_set_zlevel_from(piece,p,info);
2097 }
2098
2099 function piece_set_zlevel_from(piece: PieceId, p: PieceInfo,
2100                                info: { z: ZCoord, zg: Generation }) {
2101   piece_set_zlevel(piece,p, (oldtop_piece)=>{
2102     p.z  = info.z;
2103     p.zg = info.zg;
2104   });
2105 }
2106
2107 messages.Recorded = <MessageHandler>function
2108 (j: { piece: PieceId, cseq: ClientSeq,
2109       zg: Generation|null, svg: string | null, desc: string | null } ) {
2110   let piece = j.piece;
2111   let p = pieces[piece]!;
2112   piece_recorded_cseq(p, j);
2113   if (p.cseq_updatesvg != null && j.cseq >= p.cseq_updatesvg) {
2114     p.cseq_updatesvg = null;
2115     redisplay_ancillaries(piece,p);
2116   }
2117   if (j.svg != null) {
2118     p.delem.innerHTML = j.svg;
2119     p.pelem= piece_element('piece',piece)!;
2120     piece_resolve_special(piece, p);
2121     redisplay_ancillaries(piece,p);
2122   }
2123   if (j.zg != null) {
2124     var zg_new = j.zg; // type narrowing doesn't propagate :-/
2125     piece_set_zlevel(piece,p, (oldtop_piece: PieceId)=>{
2126       p.zg = zg_new;
2127     });
2128   }
2129   if (j.desc != null) {
2130     p.desc = j.desc;
2131   }
2132 }
2133
2134 function piece_recorded_cseq(p: PieceInfo, j: { cseq: ClientSeq }) {
2135   if (p.cseq_main  != null && j.cseq >= p.cseq_main ) { p.cseq_main  = null; }
2136   if (p.cseq_loose != null && j.cseq >= p.cseq_loose) { p.cseq_loose = null; }
2137 }
2138
2139 messages.RecordedUnpredictable = <MessageHandler>function
2140 (j: { piece: PieceId, cseq: ClientSeq, ns: PreparedPieceState } ) {
2141   let piece = j.piece;
2142   let p = pieces[piece]!;
2143   piece_recorded_cseq(p, j);
2144   piece_modify(piece, p, j.ns);
2145 }
2146
2147 messages.Error = <MessageHandler>function
2148 (m: any) {
2149   console.log('ERROR UPDATE ', m);
2150   var k = Object.keys(m)[0];
2151   update_error_handlers[k](m[k]);
2152 }
2153
2154 type PieceOpError = {
2155   error: string,
2156   error_msg: string,
2157   state: ErrorTransmitUpdateEntry_Piece,
2158 };
2159
2160 update_error_handlers.PieceOpError = <MessageHandler>function
2161 (m: PieceOpError) {
2162   let piece = m.state.piece;
2163   let cseq = m.state.cseq;
2164   let p = pieces[piece];
2165   console.log('ERROR UPDATE PIECE ', piece, cseq, m, m.error_msg, p);
2166   if (p == null) return; // who can say!
2167   if (m.error != 'Conflict') {
2168     // Our gen was high enough we we sent this, that it ought to have
2169     // worked.  Report it as a problem, then.
2170     add_log_message('Problem manipulating piece: ' + m.error_msg);
2171     // Mark aus as having no outstanding requests, and cancel any drag.
2172     piece_checkconflict_nrda(piece, p, true);
2173   }
2174   handle_piece_update(m.state);
2175 }
2176
2177 function piece_checkconflict_nrda(piece: PieceId, p: PieceInfo,
2178                                   already_logged: boolean = false) {
2179   // Our state machine for cseq:
2180   //
2181   // When we send an update (api_piece_x) we always set cseq.  If the
2182   // update is loose we also set cseq_beforeloose.  Whenever we
2183   // clear cseq we clear cseq_beforeloose too.
2184   //
2185   // The result is that if cseq_beforeloose is non-null precisely if
2186   // the last op we sent was loose.
2187   //
2188   // We track separately the last loose, and the last non-loose,
2189   // outstanding API request.  (We discard our idea of the last
2190   // loose request if we follow it with a non-loose one.)
2191   //
2192   // So
2193   //     cseq_main > cseq_loose         one loose request then some non-loose
2194   //     cseq_main, no cseq_loose       just non-loose requests
2195   //     no cseq_main, but cseq_loose   just one loose request
2196   //     neither                        no outstanding requests
2197   //
2198   // If our only outstanding update is loose, we ignore a detected
2199   // conflict.  We expect the server to send us a proper
2200   // (non-Conflict) error later.
2201   if (p.cseq_main != null || p.cseq_loose != null) {
2202     if (drag_pieces.some(function(dp) { return dp.piece == piece; })) {
2203       console.log('drag end due to conflict');
2204       drag_end();
2205     }
2206   }
2207   if (p.cseq_main != null) {
2208     if (!already_logged)
2209       add_log_message('Conflict! - simultaneous update');
2210   }
2211   p.cseq_main = null;
2212   p.cseq_loose = null;
2213 }
2214
2215 function test_swap_stack() {
2216   let old_bot = pieces_marker.nextElementSibling!;
2217   let container = old_bot.parentElement!;
2218   container.insertBefore(old_bot, defs_marker);
2219   window.setTimeout(test_swap_stack, 1000);
2220 }
2221
2222 function startup() {
2223   console.log('STARTUP');
2224   console.log(wasm_bindgen.setup("OK"));
2225
2226   var body = document.getElementById("main-body")!;
2227   zoom_btn = document.getElementById("zoom-btn") as any;
2228   zoom_val = document.getElementById("zoom-val") as any;
2229   links_elem = document.getElementById("links") as any;
2230   ctoken = body.dataset.ctoken!;
2231   us = body.dataset.us!;
2232   gen = +body.dataset.gen!;
2233   let sse_url_prefix = body.dataset.sseUrlPrefix!;
2234   status_node = document.getElementById('status')!;
2235   status_node.innerHTML = 'js-done';
2236   log_elem = document.getElementById("log")!;
2237   logscroll_elem = document.getElementById("logscroll") || log_elem;
2238   let dataload = JSON.parse(body.dataset.load!);
2239   held_surround_colour = dataload.held_surround_colour!;
2240   players = dataload.players!;
2241   delete body.dataset.load;
2242   uos_node = document.getElementById("uos")!;
2243   occregions = wasm_bindgen.empty_region_list();
2244
2245   space = svg_element('space')!;
2246   pieces_marker = svg_element("pieces_marker")!;
2247   defs_marker = svg_element("defs_marker")!;
2248   movehist_start = svg_element('movehist_marker')!;
2249   movehist_end = svg_element('movehist_end')!;
2250   rectsel_path = svg_element('rectsel_path')!;
2251   svg_ns = space.getAttribute('xmlns')!;
2252
2253   for (let uelem = pieces_marker.nextElementSibling! as SVGGraphicsElement;
2254        uelem != defs_marker;
2255        uelem = uelem.nextElementSibling! as SVGGraphicsElement) {
2256     let piece = uelem.dataset.piece!;
2257     let p = JSON.parse(uelem.dataset.info!);
2258     p.uelem = uelem;
2259     p.delem = piece_element('defs',piece);
2260     p.pelem = piece_element('piece',piece);
2261     p.queued_moves = 0;
2262     occregion_update(piece, p, p); delete p.occregion;
2263     delete uelem.dataset.info;
2264     pieces[piece] = p;
2265     piece_resolve_special(piece,p);
2266     redisplay_ancillaries(piece,p);
2267   }
2268
2269   if (test_update_hook == null) test_update_hook = function() { };
2270   test_update_hook();
2271
2272   last_log_ts = wasm_bindgen.timestamp_abbreviator(dataload.last_log_ts);
2273
2274   for (let ent of dataload.movehist.hist) {
2275     movehist_record(ent);
2276   }
2277
2278   var es = new EventSource(
2279     sse_url_prefix + "/_/updates?ctoken="+ctoken+'&gen='+gen
2280   );
2281   es.onmessage = function(event) {
2282     console.log('GOTEVE', event.data);
2283     var k;
2284     var m;
2285     try {
2286       var [tgen, ms] = JSON.parse(event.data);
2287       for (m of ms) {
2288         k = Object.keys(m)[0];
2289         messages[k](m[k]);
2290       }
2291       gen = tgen;
2292       test_update_hook();
2293     } catch (exc) {
2294       var s = exc.toString();
2295       string_report_error('exception handling update '
2296                           + k + ': ' + JSON.stringify(m) + ': ' + s);
2297     }
2298   }
2299   es.addEventListener('commsworking', function(event) {
2300     console.log('GOTDATA', (event as any).data);
2301     status_node.innerHTML = (event as any).data;
2302   });
2303   es.addEventListener('player-gone', function(event) {
2304     console.log('PLAYER-GONE', event);
2305     status_node.innerHTML = (event as any).data;
2306     add_log_message('<strong>You are no longer in the game</strong>');
2307     space.removeEventListener('mousedown', some_mousedown);
2308     document.removeEventListener('keydown', some_keydown);
2309     es.close();
2310   });
2311   es.addEventListener('updates-expired', function(event) {
2312     console.log('UPDATES-EXPIRED', event);
2313     string_report_error('connection to server interrupted too long');
2314   });
2315   es.onerror = function(e) {
2316     let info = {
2317       updates_error : e,
2318       updates_event_source : es,
2319       updates_event_source_ready : es.readyState,
2320       update_oe : (e as any).className,
2321     };
2322     if (es.readyState == 2) {
2323       json_report_error({
2324         reason: "TOTAL SSE FAILURE",
2325         info: info,
2326       })
2327     } else {
2328       console.log('SSE error event', info);
2329     }
2330   }
2331   recompute_keybindings();
2332   space.addEventListener('mousedown', some_mousedown);
2333   space.addEventListener('dragstart', function (e) {
2334     e.preventDefault();
2335     e.stopPropagation();
2336   }, true);
2337   document.addEventListener('keydown',   some_keydown);
2338   check_z_order();
2339 }
2340
2341 type DieSpecialRendering = SpecialRendering & {
2342   cd_path: SVGPathElement,
2343   loaded_ts: DOMHighResTimeStamp,
2344   loaded_remprop: number,
2345   total_ms: number,
2346   radius: number,
2347   anim_id: number | null,
2348 };
2349 special_renderings['Die'] = function(piece: PieceId, p: PieceInfo,
2350                                      s: DieSpecialRendering) {
2351   let cd_path = document.getElementById('def.'+piece+'.die.cd');
2352   if (!cd_path) return;
2353
2354   s.cd_path = cd_path as any as SVGPathElement;
2355   s.loaded_ts = performance.now();
2356   s.loaded_remprop = parseFloat(cd_path.dataset.remprop!)!;
2357   s.total_ms       = parseFloat(cd_path.dataset.total_ms!)!;
2358   s.radius         = parseFloat(cd_path.dataset.radius!)!;
2359
2360   s.stop = die_rendering_stop as any;
2361   die_request_animation(piece, p, s);
2362 } as any;
2363 function die_request_animation(piece: PieceId, p: PieceInfo,
2364                                s: DieSpecialRendering) {
2365   s.anim_id = window.requestAnimationFrame(
2366     function(ts) { die_render_frame(piece, p, s, ts) }
2367   );
2368 }
2369 function die_render_frame(piece: PieceId, p: PieceInfo,
2370                           s: DieSpecialRendering, ts: DOMHighResTimeStamp) {
2371   s.anim_id = null;
2372   let remprop = s.loaded_remprop - (ts - s.loaded_ts) / s.total_ms;
2373   //console.log('DIE RENDER', piece, s, remprop);
2374   if (remprop <= 0) {
2375     console.log('DIE COMPLETE', piece, s, remprop);
2376     let to_remove: Element = s.cd_path;
2377     for (;;) {
2378       let previous = to_remove.previousElementSibling!;
2379       // see dice/overlya-template-extractor
2380       if (to_remove.tagName == 'text') break;
2381       to_remove.remove();
2382       to_remove = previous;
2383     }
2384   } else {
2385     let path_d = wasm_bindgen.die_cooldown_path(s.radius, remprop);
2386     s.cd_path.setAttributeNS(null, "d", path_d);
2387     die_request_animation(piece, p, s);
2388   }
2389 }
2390 function die_rendering_stop(piece: PieceId, p: PieceInfo,
2391                             s: DieSpecialRendering) {
2392   let anim_id = s.anim_id;
2393   if (anim_id == null) return;
2394   s.anim_id = null;
2395   window.cancelAnimationFrame(anim_id);
2396 }    
2397
2398 declare var wasm_input : any;
2399 var wasm_promise : Promise<any>;;
2400
2401 function doload(){
2402   console.log('DOLOAD');
2403   globalinfo_elem = document.getElementById('global-info')!;
2404   layout = globalinfo_elem!.dataset!.layout! as any;
2405   var elem = document.getElementById('loading_token')!;
2406   var ptoken = elem.dataset.ptoken;
2407   xhr_post_then('/_/session/' + layout, 
2408                 JSON.stringify({ ptoken : ptoken }),
2409                 loaded);
2410
2411   wasm_promise = wasm_input
2412     .then(wasm_bindgen);
2413 }
2414
2415 function loaded(xhr: XMLHttpRequest){
2416   console.log('LOADED');
2417   var body = document.getElementById('loading_body')!;
2418   wasm_promise.then((got_wasm) => {
2419     wasm = got_wasm;
2420     body.outerHTML = xhr.response;
2421     try {
2422       startup();
2423     } catch (exc) {
2424       let s = exc.toString();
2425       string_report_error_raw('Exception on load, unrecoverable: ' + s);
2426     }
2427   });
2428 }
2429
2430 // todo scroll of log messages to bottom did not always work somehow
2431 //    think I have fixed this with approximation
2432
2433 //@@notest
2434 doload();