Debian Codegraph @

texmf-dist/doc/latex/figput/javascript/development/widgets.ts

raw
1 /*
2 Widget management code.
3
4 Typically, widget management is done with a tightly siloed hierarchy, with
5 widgets in containers, which are in containers, etc. There is a hierarchy
6 like that here (though rather flat since I don't need much), but there's also
7 a global registry of widgets alongside the hierarchy. This makes widgets
8 easier to work with for the author of the latex document.
9
10 I've also avoided any kind of clever abstraction around the widget concept.
11 This can mean that there's a certain amount of boilerplate (not DRY), but
12 it also means that things aren't tangled up. Widgets can be individually
13 modified without worries about side-effects.
14
15 All widgets use a register() method rather than a constructor. This
16 is because the user should be able to specify a widget repeatedly
17 without actually creating a new one every time it's specified.
18
19 So, the user should say something like
20 let w = RandomWidgetType.register(arguments);
21 to create a widget from the drawing code. If register() has never been
22 called for the particular widget, then a new widget *is* created and
23 a reference to it is placed in global storage. If this widget was created
24 earlier, then the reference to it is taken from global storage and returned.
25 So, register() is something like an object factory, but it won't make the
26 same object more than once.
27
28 Every widget is distinguished by its type and the (name of the) figure it
29 belongs to. In addition, if a figure has several widgets of the same type,
30 then the user must provide an optional name for that particular widget. For
31 example, if there are three ButtonWidgets for a given figure, then they
32 might be created by
33 let b1 = ButtonWidget.register(whatever,"first");
34 let b2 = ButtonWidget.register(whatever,"second");
35 let b3 = ButtonWidget.register(whatever,"third");
36
37 -------------------------
38
39 One of the ticklish issues is how to associate widgets with their
40 figures. In most languages, this problem is solved by explicitly using
41 "this" somehow. In Java, you might say something like
42 new Widget(this);
43 to indicate that the owner of the widget is the class from which the widget
44 was constructed. I would rather not do that because it's the kind of
45 boilerplate arcana that the user shouldn't have to think about.
46
47 JS provides a couple of ways to determine who made a call to a particular
48 function. The easiest way is like this
49
50 function example() {
51 let caller = example.caller.name;
52 console.log(caller);
53 }
54
55 This should print the name of the function that invoked example().
56
57 Another way is very easy to do, but it's been deprecated. See
58 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
59 Even though it is deprecated, every browser supports it, according to the
60 above link. Also, my guess is that this is very commonly used since
61 it's so handy. They won't be getting rid of it any time soon.
62
63 If they do get rid of caller.name, then another way to obtain this
64 information is by creating a bogus Error and examining the call stack:
65
66 function example() {
67
68 let stack = new Error().stack;
69 let caller = stack.split('\n')[1].trim();
70
71 // caller is now inforamtion about the function calling this one,
72 // including the file name and a bunch of other stuff I don't care about.
73 // I just want to know the name of the function.
74 // It *appears* (but not extensively tested) that the function name
75 // occurs before the first '@'.;
76 let callingFcn = caller.split('@')[0];
77 console.log(callingFcn);
78 }
79
80 I wanted to use caller.name, even though it is deprecated, because it is
81 so much easier. Unfortunately, it is not allowed in strict mode.
82 Since everything that appears within a class is strict, that makes its use
83 awkward. I tried to get around this by defining a top-level function (outside
84 any class) that does nothing but return the value I want, but that doesn't
85 work either. It seems like, as soon as you enter a class, the data you want
86 is stripped off (or something). Also, now that I've moved to TypeScript any
87 violation of "strict" is even harder. Since I'll have to define a seperate class
88 anyway, go ahead and use the Error-based approach.
89
90 To top it off, the method via generating an Error is sensitive to the
91 broswer because different browsers format this information differently.
92
93 -------------------
94
95 BUG: Future Widgets...?
96
97 Because LoopWidget takes such a crazy number of options, it would be nice
98 to have several widgets that merely call LoopWidget. This wouldn't really
99 be any different, but would simplify things for the user. Basically, these
100 would have a reduced set of arguments to register() and just hand everything
101 off to LoopWidget. They would be a mere glue skeleton. Same goes for
102 OpenAnimWidget.
103
104 Image Building Widget
105 For something like (say) a Mandelbrot set. This takes time to generate
106 and you might want to draw it in an open-ended way. It's not reasonable
107 to allow the user to move through time and see the state of the image
108 at different time steps. The widget should store an off-screen image
109 and making the animation "run faster" would mean calling it more frequently
110 so that it can do more calculation. So it would use some of the same
111 animation infrastructure, but in a different way. The most that makes
112 sense here is a pause/run (to reduce computational load) and something
113 to increase or decrease the load. This would often be something for which
114 it does not make sense to generate tikz. Any JS rendering of a mandelbrot
115 set (say) would be terrible for inclusion in a book. You'd generate a
116 printed figure like that in some other way, even if an on-line animation
117 would be instructive.
118
119 Various restrictions on how a DraggableDot can be moved would be handy.
120 Restricting to a particular line or arc wouldn't be hard, but restricting to
121 fall on a given Path2D would be hard. The JS implementation of Path2D is
122 poor, and I would need to reimplement the entire thing from the
123 ground up. I might need to do some of that anyway for the best tikz output
124 (I did some stuff along those lines already).
125
126 Draggable Line
127 Similar to Draggable dot. In fact, it's not clear that this needs its own
128 widget. A line is determined by two points, so the user could use a
129 draggable dot and just draw the line himself. The only advantage I can
130 see to a draggable *line* is that the user could mouse-down on any
131 portion of the line. In fact, that could be done with DraggableDot since
132 the "dot" could be an entire line.
133
134 Scroll bar for number selection.
135 Similar to a spinner, but the user drags a dot along a line.
136 Not clear whether a numerical value should appear.
137
138 Checkboxes and Radio buttons
139 Gack
140
141 Drop-down menu
142 Stuff like this gets more fiddly. If you have a drop-down menu and
143 it has a vertical scroll bar for multiple selections, then it's even worse.
144
145 */
146
147
148 // There is only one of these, so everything is static. It manages all
149 // the widgets in the program.
150
151 class WidgetManager {
152
153 // All the widgets known to the program.
154 // Each of these is an instance of the Widget class.
155 // BUG: I could get rid of this and just use theWidgets. It's redundant,
156 // and theWidgets is actually easier.
157 // BUG: Yes, get rid of this.
158 static theList : Widget[] = [];
159
160 // Also a complete list of all widgets, but indexed by the figure
161 // to which the widget belongs. This makes it easier to pass events
162 // to the proper recipent. So this is a hash map taking a figure name
163 // (as a string) to an array of Widget objects.
164 static theWidgets : Map<AugmentedDrawingFunction,Widget[]> = new Map();
165
166 // This is BOGUS. Certain path operations require a CanvasRenderingContext2D,
167 // even when the question is one of pure abstract geometry, like
168 // isPointInPath(), and the only way to get one of these is from a canvas.
169 // Using the visible canvas and ctx for this is prone to all kinds of misuse
170 // and mistakes, so create a bogus ctx here.
171 // BUG: The long-term solution is not to rely on js for this at all. Write
172 // my own code for Bezier curves and the like. I'm partway there already.
173 static bogusCanvas : HTMLCanvasElement = document.createElement('canvas');
174 static bogusCtx : CanvasRenderingContext2D = WidgetManager.bogusCanvas.getContext('2d') !;
175
176 // Whether a widget "owns" a recent mouse-down event. This is needed
177 // for things like dragging. If this is null, then the next mouse-down
178 // is up for grabs. Otherwise, it points to the relevant Widget object.
179 static mouseOwner : Widget | null = null;
180
181 // This isn't being used yet, but it will be needed to handle keyboard
182 // events. The idea is that a widget ""takes ownership" of a mouse-down
183 // with mouseOwner, and that widget is the same one that has focus for
184 // any future keyboard events too. The only real difference is that
185 // focusOwner is "stickier." This goes to null whenever a user clicks
186 // on something other than a widget.
187 static focusOwner = null;
188
189
190 static register(w : Widget) : void {
191
192 this.theList.push(w);
193
194 if ( WidgetManager.theWidgets.has(w.betterOwner) )
195 WidgetManager.theWidgets.get(w.betterOwner) ! .push(w);
196 else
197 WidgetManager.theWidgets.set(w.betterOwner,[w]);
198 }
199
200 static knownWidget(o : string , t : string , n : string) : Widget | null {
201
202 // If there is a widget with the given owner (o), type (t) and name(n)
203 // in theList, then return it; return null otherwise.
204 // BUG: Using a string as owner feels particularly bad.
205 for (let i = 0; i < this.theList.length; i++)
206 {
207 let curW = this.theList[i];
208
209 if (o !== curW.owner)
210 continue;
211 if (t !== curW.type)
212 continue;
213 if (n === curW.name)
214 return curW;
215 }
216
217 return null;
218 }
219
220 static mouseDown(theFig : AugmentedDrawingFunction , x : number , y : number ) : void {
221
222 // theFig should match one of the Widget object's owner fields.
223 // (x,y) is given relative to he origin of the figure.
224 if (WidgetManager.theWidgets.has(theFig) === false)
225 return;
226
227 // The only thing to do here is to pass the event to each widget and
228 // see if it wants it. I suppose that I *could* store the area for
229 // each widget, and do an initial test here, but this is easier.
230 let wlist : Widget[] = WidgetManager.theWidgets.get(theFig) !;
231
232 for (let i = 0; i < wlist.length; i++)
233 {
234 if (wlist[i].mouseDown(x,y) === true)
235 // First come, first serve.
236 return;
237 }
238 }
239
240 static mouseMove(theFig : AugmentedDrawingFunction , x : number , y : number ) : void {
241
242 // As above.
243 if (WidgetManager.mouseOwner === null)
244 return;
245
246 if (WidgetManager.theWidgets.has(theFig) === false)
247 return;
248
249 // We only accept mouse moves if the mouse is on the figure that
250 // "owns" the mouse event.
251 if (WidgetManager.mouseOwner.betterOwner !== theFig)
252 return;
253
254 WidgetManager.mouseOwner.mouseMove(x,y);
255 }
256
257 static mouseUp(theFig : AugmentedDrawingFunction , x : number , y : number ) : void {
258
259 // As above.
260 if (WidgetManager.mouseOwner === null)
261 return;
262
263 if (WidgetManager.theWidgets.has(theFig) === false)
264 return;
265
266 if (WidgetManager.mouseOwner.betterOwner !== theFig)
267 // Mouse was released over *a* figure, but not the figure with
268 // the owning widget. Tell the correct widget about the release, using
269 // bogus coordinates so that the mouse-up is sure to be off the widget.
270 WidgetManager.mouseOwner.mouseUp(10000000000000,10000000000000);
271
272 //console.log("up up");
273 WidgetManager.mouseOwner.mouseUp(x,y);
274 }
275 }
276
277
278 function getCaller() : string {
279
280 // Irritating function to get around strict mode. See the comment at the
281 // top of the file. I want the caller of the thing that calls this.
282 //
283 // BUG: I was never entirely happy with this, and now that it depends
284 // on the particular browser, I am even less happy about it. It's a
285 // question of the lesser of two evils: this function or requiring
286 // the user to provide a boilerplate 'this' or the like.
287
288 let stack : string = new Error().stack !;
289
290 // The exact format of the information in stack depends on the particular
291 // browser. Firefox produces something like this:
292 //
293 // getCaller@http://localhost:8000/widgets.js:375:15
294 // register@http://localhost:8000/widgets.js:1557:18
295 // geartest01@http://localhost:8000/geartest01.js:142:26
296 // render@http://localhost:8000/layout.js:628:11
297 // renderFrame@http://localhost:8000/widgets.js:538:13
298 // etc.
299 //
300 // While MS Edge/Chrome produces
301 //
302 // Error
303 // at getCaller (widgets.js:375:15)
304 // at Function.register (widgets.js:1557:18)
305 // at geartest01 (geartest01.js:142:26)
306 // at FigurePanel.render (layout.js:628:5)
307 // etc.
308 //
309 // Depending on the Browser, stack needs to be parsed differently.
310 // theBrowser was defined in main.js.
311
312 // The digit value (e.g., '2') indicates how many steps back in the the
313 // stack to go.
314 if (theBrowser === "Firefox")
315 {
316 let caller = stack.split('\n')[2].trim();
317
318 // caller is now information about a function in the call stack,
319 // including the file name and a bunch of other stuff I don't care about.
320 // I just want to know the name of the function.
321 // The function name occurs before the first '@'.
322 let callingFcn = caller.split('@')[0];
323 return callingFcn;
324 }
325 else if (theBrowser === "Chrome")
326 {
327 let caller = stack.split('\n')[3].trim();
328
329 // Here, space-deliminting works better.
330 let callingFcn = caller.split(' ')[1];
331
332 // But this may return something like 'FigurePanel.bezier'; what I want
333 // is just 'bezier'.
334 if (callingFcn.indexOf('.') > -1)
335 callingFcn = callingFcn.split('.')[1];
336
337 return callingFcn;
338 }
339 else
340 {
341 console.log("IMPOSSIBLE ERROR DUE TO UNKNOWN BROWSER TYPE!!!");
342 return "";
343 }
344 }
345
346
347
348 // Base class for all widgets. No code outside this file should
349 // ever access this class directly. It's not abstract because there
350 // are certain actions common to every case in the constructor.
351
352 class Widget {
353
354 // Every widget is owned by a particular figure. The "owner" is
355 // the name of the figure function, just as in latex.
356 // BUG: Change this to the AugmentedDrawingFunction. Thus, get rid
357 // of this and use betterOwner.
358 owner : string = "";
359
360 betterOwner : AugmentedDrawingFunction;
361
362 // JS isn't very good about types, so it's clearer to tag sub-classes with
363 // the name of that sub-class rather than mess with typeof or whatever.
364 // This should be "LoopWidget" or whatever the name is of the sub-class.
365 type : string = "";
366
367 // Name to distinguish this widget from all others of the same
368 // type that belong to the same figure. So, the triple (owner,type,name)
369 // fully distinguishes this Widget from all others.
370 //
371 // In principle, this variable could have been avoided as a user-provided
372 // value and he wouldn't have to come up with an 'extra' name for the widget,
373 // but it wouldn't be easy. The WidgetManager (or something) would have to
374 // come up with a unique ID and *that* would require that the user invoke
375 // something like a "starting to create widgets" and "done creating widgets"
376 // commands. Overall, this seems less fussy for him.
377 name : string = "";
378
379 // The (x,y) is where the widget should be drawn relative to the
380 // rectangle of the figure. Often, widgetX will be negative to put the
381 // widget in the margin of the page.
382 // It's tempting to call these fields x and y, but it would
383 // be easy to accidentally reuse those names.
384 widgetX = 0;
385 widgetY = 0;
386
387 // To scale the drawing of a widget up or down.
388 scale = 1.0;
389
390 // Occassionally, it may make sense to hide a widget. This is different
391 // than being non-visible because the widget is off-screen. If the
392 // widget has hide == true, then it is *never* shown. For example, the
393 // way animations work, you have to have an animation widget to run the
394 // animation, even if you don't want to see the widget.
395 hide : boolean = true;
396
397
398 constructor(owner : string , type : string , x : number , y : number , scale : number ,
399 hide : boolean , name : string ) {
400
401 // Due to the fact that this tracks the owner of the widget, and how
402 // it is done, it is IMPORTANT that no sub-class has its own constructor.
403 this.owner = owner;
404 this.type = type;
405 this.widgetX = x;
406 this.widgetY = y;
407 this.scale = scale;
408 this.hide = hide;
409 this.name = name;
410 this.betterOwner = getAugmentedFunction(owner);
411
412 // When a widget is contructed it must be registered in a global list.
413 WidgetManager.register(this);
414 }
415
416 draw(ctx : CanvasRenderingContext2D) : void {
417 // Every sub-class must implement this method.
418 console.log("Called Widget.draw()!!!");
419 }
420
421 // BUG: These methods that are "never" supposed to be called
422 // will be called for the widgets based on the DOM, like ButtonWidget.
423 // That's fine -- don't panic! I want to get rid of these DOM-based
424 // widgets anyway. DOM = cesspool.
425 mouseDown(x : number , y : number ) : boolean {
426 // Every sub-class must implement this method.
427 // Return true iff the widget wants to "take ownership" of this event.
428 console.log("Called Widget.mouseDown()!!! " +this.name);
429 return false;
430 }
431
432 mouseMove(x : number , y : number ) : void {
433 // As above, but returns nothing.
434 console.log("Called Widget.mouseMove()!!!");
435 }
436
437 mouseUp(x : number , y : number ) : void {
438 // As above, but returns nothing.
439 console.log("Called Widget.mouseUp()!!!");
440 }
441 }
442
443
444 // Animations require some infrastructure.
445 // BUG: Maybe this stuff should be in AnimationWidget.
446
447 function doAnimation(theWidget : AnimationWidget) : void {
448
449 // This is called to render a frame of an animation. It is generated via
450 // the usual event-loop, so we schedule it just as we do for things like
451 // mouse-downs and scroll events.
452 // theWidget is the one that "runs" the animation, like a LoopWidget.
453 let id = Events.getID();
454 doAnimationGuts(id,theWidget);
455 }
456
457 async function doAnimationGuts(id : number , theWidget : AnimationWidget ) {
458
459 // Scheduling is handled in a way similar to doScroll() in main.ts.
460 await Events.waitMyTurn(id);
461
462 await renderFrame(theWidget);
463
464 // Advance to the next frame.
465 theWidget.curStep += theWidget.stepsPerFrame;
466 theWidget.advanceFrame();
467
468 // Don't forget this or the program is bricked!
469 Events.allDone(id);
470 }
471
472 async function renderFrame(theWidget : Widget ) {
473
474 // Calls the code to render the relevant figure. It renders the *entire*
475 // figure, widget and all.
476 //
477 // NOTE: This is used for animations, but it is also used to ensure
478 // that any change to a widget (and resulting changes to a figure)
479 // is shown.
480 //
481 // BUG: It's tempting to mention this in the user manual since users might
482 // find it useful. OTOH, that shouldn't be encouraged, and this is the kind
483 // of thing that might change in a later version.
484
485 // The "owner" is the function (from the latex document) that created
486 // theWidget.
487 let myFunc : AugmentedDrawingFunction = getAugmentedFunction( theWidget.owner );
488 let fpc : FigurePanel = myFunc.figurePanelClass !;
489
490 // This is generally synchronous, but it doesn't hurt anything to tack an
491 // async on here. Maybe somebody will write one that *is* asynchronous.
492 await fpc.render();
493 }
494
495 function getFigureRect(theWidget : Widget ) : { w : number , ha : number , hb : number } {
496
497 // Returns the width and height of the rectangle of the widget.
498 // The height is in two parts: the height above the x-axis, and the height
499 // below the x-axis.
500 // The units are pdf points, and the width is relative to the left
501 // margin. So the width matches the usual coordinate system for drawing
502 // the figure, and this width is equal to the text width, as reported
503 // by latex. So x in the range [0,width] should be limited to the area
504 // below the text.
505 let myFunc : AugmentedDrawingFunction = getAugmentedFunction( theWidget.owner );
506 let fpc : FigurePanel = myFunc.figurePanelClass ! ;
507
508 let answer = { w: fpc.textWidth, ha : fpc.h - fpc.lowerPadding , hb : fpc.lowerPadding };
509 return answer;
510 }
511
512 // Base class for widgets that run animations. See LoopAnimWidget and
513 // OpenAnimWidget. There is a fair amount of overlap between the two types
514 // of animation class, and it is tempting to pull more stuff up to this level for
515 // DRY reasons, but it seems cleaner and clearer to limit this to what's needed
516 // to run the animations with doAnimation() and related functions.
517
518 abstract class AnimationWidget extends Widget {
519
520 // Animations run as a series of frames, and this is the frame being displayed.
521 // This value may be open-ended or it may "loop back" so that animation repeats.
522 curStep = 0;
523
524 // How much to advance the above with each frame -- an integer. Animations
525 // can be made to run faster by increasing this value, thereby skipping frames.
526 stepsPerFrame = 1;
527
528 // The process id for the call to setInterval().
529 animID = 0;
530
531 advanceFrame() : void {
532 // This is why the class is abstract. It moves curStep to the next frame,
533 // however that should be done for the particular animation.
534 console.log("Calling abstract AnimationWidget.advanceFrame()!");
535 }
536 }
537
538 // A LoopWidget is to be used when an animiation runs in a repeating loop.
539 // You must have one of these for an animation to run, even if the widget
540 // itself is invisible.
541
542 class LoopAnimWidget extends AnimationWidget {
543
544 // These are useful to the user to help properly place things.
545 // These values are given with scale equal to 1, and are worked
546 // out from the actual drawing code.
547 // The TopHeight is the amount above the circle that is used for the
548 // time-step controls, and BottomHeight is the amount used for the
549 // faster/slower, pause/run contols. If you don't want the circle at
550 // all, then it's a little awkward to work out placement, but it works.
551 // There is some imprecision here due to line thickneses, but very close.
552 static Radius = 41.5;
553 static TopHeight = 24.5;
554 static BottomHeight = 21.0;
555
556 // When things are "selected," draw them in this color.
557 static sColor = "blue";
558
559 // These are as passed to register(). See that method for a description.
560 // They really shouldn't be touched outside this class. The boolean values
561 // are whether certain elements of the widget are visible (and hence
562 // available for interaction).
563 steps = 100;
564 start = 0;
565 timeStep = 20;
566 visSteps = true;
567 visFastSlow = true;
568 visPauseRun = true;
569 visCircle = true;
570 triGrab = true;
571
572 // This stuff is very much private.
573
574 // These are stored when the figure is drawn so that mouse events can find
575 // what was clicked more easily. It's simpler than recalculating with
576 // every event.
577 pCircle : Path2D | null = null;
578 pUpStep : Path2D | null = null;
579 pDownStep : Path2D | null = null;
580 pFaster : Path2D | null = null;
581 pSlower : Path2D | null = null;
582 pPauseRun : Path2D | null = null;
583
584 // The states of various parts of the widget; e.g., whether the pause
585 // or run icon is present, whether a part is "half-way clicked,"" etc.
586 // I'm using 'a' for 'active' and 's' for 'selected.'
587 //
588 // BUG: If I want to get *really* fancy, then I need another set of
589 // flags to indicate that the mouse *was* clicked on something, so it
590 // is "selected," but the user moved the mouse away from the item without
591 // a mouse-up, so that selected item should be drawn in normal color, not
592 // the highlighted color (sColor). If the mouse is moved back over the
593 // selected item, then the color can go back to being the selection color.
594 aRunning = true;
595 sCircle = false;
596 sPauseRun = false;
597 sFaster = false;
598 sSlower = false;
599 sUpStep = false;
600 sDownStep = false;
601
602
603 static register(ctx : CanvasRenderingContext2D , x : number , y : number , scale : number ,
604 visWidget : boolean , steps : number , start : number , timeStep : number ,
605 visSteps : boolean, visFastSlow : boolean , visPauseRun : boolean , visCircle : boolean ,
606 triGrab : boolean , name : string ) : LoopAnimWidget {
607
608 // BUG: Add an argument for the size of the steps so that
609 // curStep can be incremented by more than 1?
610
611 // This is used something like a constructor. It either creates a new
612 // LoopWidget and returns it, or returns one that was created earlier.
613
614 // Many of these arguments are the same as for Widget.constructor().
615 // In addition, we have
616 // * ctx is assumed to have a t-matrix prepared to properly draw
617 // the widget.
618 // * steps is the number of steps required to form a loop -- when it
619 // "rolls over" or the "steps per revolution."
620 // * start is the starting step, which will usually be zero.
621 // * timeStep, in milliseconds, is the time from frame to frame.
622 // It seems like anything less than about 10ms is pointless.
623 // My guess (?) is that the rate of event generation is throttled
624 // somehow. It could be that my various layers of management are
625 // slowing things down, but I don't think so. 10ms is an eternity
626 // on modern hardware. The eye can only follow about 20 frames per
627 // second, at most, or 50ms per frame, so this is no big deal.
628 // * visWidget is whether the widget is visible at all -- same as the
629 // vis argument to Widget.construtor().
630 // * visSteps is whether the time step controls (at the top) are visible.
631 // * visFastSlow is whether the faster/slower controls are visible (at
632 // the bottom)
633 // * visPauseRun is whether the pause/run controls are visible
634 // * visCircle is for the circle (with triangular indicator).
635 // * triGrab is whether the user is allowed to grab the indicator
636 // triangle and control the animation by dragging it. The indicator
637 // triangle is always there, but it might not be grabable.
638 // Note that if visCircle == false, then triGrab is implicitly false
639 // since the triangle isn't visible either.
640 // * name is as in Widget.constructor()
641 //
642 // There appears to be a tacit assumption that time is measured in
643 // integer steps, but fractional values are fine. So they aren't really
644 // time "steps," but more like time increments.
645 //
646 // BUG: Maybe I should have different classes for some of these choices.
647 // There are just too many. These could all use (internally) the
648 // same class, just not with such a crazy number of options.
649
650 // Instead of messing with LoopWidget.name or something, be explicit.
651 let type = "LoopWidget";
652
653 // Something like this line must appear with every regester() method
654 // for each widget.
655 let caller : string = getCaller();
656
657 // I am forcing the type here, but if the wrong type is returned,
658 // then there are bigger problems.
659 let w : LoopAnimWidget = <LoopAnimWidget> WidgetManager.knownWidget(caller,type,name);
660
661 if (w != null)
662 {
663 // Widget is known, but it needs to be drawn too.
664 w.draw(ctx);
665 return w;
666 }
667
668 // Got here, so this widget is not already known, and must be created.
669 // This class has NO construtor, by design, so this falls through to the
670 // super-class Widget constructor.
671 // Careful: Internally, I use an "is hidden" flag, but the user passes in
672 // an "is visible" flag.
673 // BUG: Change the names to be consistent.
674 w = new LoopAnimWidget(caller,type,x,y,scale,!visWidget,name);
675
676 // Now the additional stuff. This is what would be in a constructor
677 // if this class had one.
678 w.steps = steps;
679 w.start = start;
680 w.timeStep = timeStep;
681 w.visSteps = visSteps;
682 w.visFastSlow = visFastSlow;
683 w.visPauseRun = visPauseRun;
684 w.visCircle = visCircle;
685 w.triGrab = triGrab;
686
687 w.curStep = w.start;
688
689 // Note the existence of this widget for the future.
690 WidgetManager.register(w);
691
692 // This is a special case because it's an animiation. The animation
693 // needs to be scheduled. It may make sense not to call setInterval()
694 // immediately; rather, it may be better to call setTimeout() so that
695 // setInterval() is called after a brief pause. It depends on how these
696 // two work. Try an immediate call; it *should* be fine.
697 w.animID = setInterval(doAnimation,w.timeStep,w);
698
699 // Before returning the widget, it must be drawn.
700 w.draw(ctx);
701
702 return w;
703 }
704
705 advanceFrame() : void {
706
707 // This kind of animation repeats.
708 this.curStep += this.stepsPerFrame;
709 if (this.curStep >= this.steps)
710 this.curStep -= this.steps;
711 }
712
713 draw(ctx : CanvasRenderingContext2D) : void {
714
715 // This is drawn with (0,0) at the center of the circle. The ctx must be
716 // shifted and scaled based on where the user wants the widget relative
717 // to the larger drawing area.
718 if (this.hide === true)
719 return;
720
721 // Don't attempt to draw to a tikz file.
722 if (ctx instanceof CTX)
723 return;
724
725 let saveT = ctx.getTransform();
726 ctx.translate(this.widgetX,this.widgetY);
727 ctx.scale(this.scale,this.scale);
728
729 var p = new Path2D();
730
731 // These values determine where the entire drawing is. (cx,cy) is the
732 // center of the circular thing, with radius r.
733 // In unscaled terms, it's clear that cx should equal r to make the
734 // widget but up against x = 0. It's messier for the y-coordinate and you
735 // need to work backwards from what the values defined below. The total
736 // height is 2r (the circle), plus circWidth (circle line thickness),
737 // plus 2 * arrowHeight (the go fast/go slow things). Then we need to
738 // add the stuff on the top: upperGap, plus stepHeight, plus stepThick.
739 // This is silly and probably confusing to the user. Just place the
740 // widget relative to the center of the circle. In other words, set
741 // (cx,cy) = (0,0). The user just needs adjust accordingly, and
742 // exactly what he wants to do will be influenced by whether the upper
743 // and lower sub-controls are present.
744 var r = 40;
745 var cx = 0;
746 var cy = 0;
747 var circWidth = 3;
748
749 if (this.visCircle == true)
750 {
751 // Draw the circle. (cx,cy) is center r and r are the two axes of the
752 // elipse. 0 is that the ellipse isn't rotated, and the last two are
753 // the start and end angle.
754 p.ellipse(cx,cy,r,r,0,0,2*Math.PI);
755
756 // Note this circle for reference by mouse events.
757 this.pCircle = new Path2D(p);
758
759 ctx.lineWidth = circWidth;
760
761 if (this.sCircle == true)
762 ctx.strokeStyle = LoopAnimWidget.sColor;
763 else
764 ctx.strokeStyle = "black";
765
766 ctx.stroke(p);
767
768 ctx.lineWidth = 1;
769
770 // A little triangle to point to the location within the animation loop.
771 // This value is in radians, in [0,2pi).
772
773 // Location of indicator triangle around the perimeter of the circle.
774 // Minus so that it travels clock-wise, which seems to be our natural expectation.
775 var loc = -2*Math.PI * this.curStep / this.steps;
776
777 var triHeight = 10;
778
779 // This is half the full angle at the outer point.
780 var triAngle = Math.PI/20;
781
782 p = new Path2D();
783
784 var x = cx + (r-circWidth/2) * Math.cos(loc);
785 var y = cy + (r-circWidth/2) * Math.sin(loc);
786 p.moveTo(x,y);
787
788 x = cx + (r-triHeight) * Math.cos(loc + triAngle);
789 y = cy + (r-triHeight) * Math.sin(loc + triAngle);
790 p.lineTo(x,y);
791
792 x = cx + (r-triHeight) * Math.cos(loc - triAngle);
793 y = cy + (r-triHeight) * Math.sin(loc - triAngle);
794 p.lineTo(x,y);
795
796 p.closePath();
797
798 ctx.strokeStyle = "red";
799 ctx.stroke(p);
800 ctx.strokeStyle = "black";
801 }
802
803 // Next, some controls at the bottom for going faster/slower and
804 // pausing/running.
805 // First, a pair of '>' for going faster.
806 let arrowOffset = 18;
807 let lowerGap = 6;
808 let arrowHeight = 7;
809 let arrowDepth = 4;
810 let arrowPairSpace = 3;
811 let arrowThick = 1.25;
812
813 if (this.visFastSlow === true)
814 {
815 ctx.lineWidth = arrowThick;
816
817 if (this.sFaster == true)
818 ctx.strokeStyle = LoopAnimWidget.sColor;
819 else
820 ctx.strokeStyle = "black";
821
822 p = new Path2D();
823 p.moveTo(cx + arrowOffset,cy - r - circWidth/2 - lowerGap);
824 p.lineTo(cx + arrowOffset + arrowDepth,
825 cy - r - circWidth/2 - lowerGap - arrowHeight);
826 p.lineTo(cx + arrowOffset,
827 cy - r - circWidth/2 - lowerGap - 2*arrowHeight);
828 ctx.stroke(p);
829
830 // You can't just shift a path. Needs to be rebuilt.
831 // BUG: I need to add that ability to my FPath class.
832 // Maybe I have already?
833 p = new Path2D();
834 p.moveTo(cx + arrowOffset + arrowPairSpace,cy - r - circWidth/2 - lowerGap);
835 p.lineTo(cx + arrowOffset + arrowDepth + arrowPairSpace,
836 cy - r - circWidth/2 - lowerGap - arrowHeight);
837 p.lineTo(cx + arrowOffset + arrowPairSpace,
838 cy - r - circWidth/2 - lowerGap - 2*arrowHeight);
839 ctx.stroke(p);
840
841 // A rectangle for the clickable area.
842 this.pFaster = new Path2D();
843 this.pFaster.rect(cx + arrowOffset - arrowThick,cy - r - circWidth/2 - lowerGap - 2*arrowHeight,
844 arrowPairSpace + arrowDepth + 2*arrowThick,2*arrowHeight);
845
846 // ctx.strokeStyle = 'green';
847 // ctx.stroke(this.pFaster);
848
849 // Same idea: '<' to go slower.
850 if (this.sSlower == true)
851 ctx.strokeStyle = LoopAnimWidget.sColor;
852 else
853 ctx.strokeStyle = "black";
854
855 p = new Path2D();
856 p.moveTo(cx - arrowOffset,cy - r - circWidth/2 - lowerGap);
857 p.lineTo(cx - arrowOffset - arrowDepth,
858 cy - r - circWidth/2 - lowerGap - arrowHeight);
859 p.lineTo(cx - arrowOffset,
860 cy - r - circWidth/2 - lowerGap - 2*arrowHeight);
861 ctx.stroke(p);
862
863 p = new Path2D();
864 p.moveTo(cx - arrowOffset - arrowPairSpace,cy - r - circWidth/2 - lowerGap);
865 p.lineTo(cx - arrowOffset - arrowDepth - arrowPairSpace,
866 cy - r - circWidth/2 - lowerGap - arrowHeight);
867 p.lineTo(cx - arrowOffset - arrowPairSpace,
868 cy - r - circWidth/2 - lowerGap - 2*arrowHeight);
869 ctx.stroke(p);
870
871 // And the clickable area.
872 this.pSlower = new Path2D();
873 this.pSlower.rect(
874 cx - arrowOffset - arrowPairSpace - arrowDepth - arrowThick,
875 cy - r - circWidth/2 - lowerGap - 2*arrowHeight,
876 arrowPairSpace + arrowDepth + 2*arrowThick,2*arrowHeight);
877
878 // ctx.strokeStyle = 'green';
879 // ctx.stroke(this.pSlower);
880 }
881
882 ctx.lineWidth = 1;
883
884 if (this.visPauseRun === true)
885 {
886 // A || or triangle for pause or run.
887 let pauseSpace = 3.25;
888 let pauseThick = 1.5;
889 let pauseHeight = 2 * arrowHeight;
890
891 let runThick = 1.5;
892 let runLeftRight = 5;
893 let runHeight = 2 * arrowHeight;
894
895 if (this.sPauseRun == true)
896 ctx.strokeStyle = LoopAnimWidget.sColor;
897 else
898 ctx.strokeStyle = "black";
899
900 if (this.aRunning === true)
901 {
902 // The animation is running, so show || to allow pausing.
903 ctx.lineWidth = pauseThick;
904
905 p = new Path2D();
906 p.moveTo(cx + pauseSpace,cy - r - circWidth/2 - lowerGap);
907 p.lineTo(cx + pauseSpace,cy - r - circWidth/2 - lowerGap - pauseHeight);
908 ctx.stroke(p);
909
910 p = new Path2D();
911 p.moveTo(cx - pauseSpace,cy - r - circWidth/2 - lowerGap);
912 p.lineTo(cx - pauseSpace,cy - r - circWidth/2 - lowerGap - pauseHeight);
913 ctx.stroke(p);
914
915 ctx.lineWidth = 1;
916 }
917 else
918 {
919 // Animation is paused, so show triangle to run it again.
920 ctx.lineWidth = runThick;
921
922 p = new Path2D();
923 p.moveTo(cx - runLeftRight,cy - r - circWidth/2 - lowerGap);
924 p.lineTo(cx - runLeftRight,cy - r - circWidth/2 - lowerGap - runHeight);
925 p.lineTo(cx + runLeftRight,cy - r - circWidth/2 - lowerGap - runHeight/2);
926 p.closePath();
927 ctx.stroke(p);
928 }
929
930 // Either way (paused or running), we need the clickable area.
931 // This area is too generous for the "run" triangle, because
932 // I use the same rectangle for "pause" and "run," but no big deal.
933 this.pPauseRun = new Path2D();
934 this.pPauseRun.rect(cx - runLeftRight - runThick,
935 cy - r - circWidth/2 - lowerGap - runHeight - runThick,
936 2*runLeftRight + 2*runThick,runHeight + 2*runThick);
937
938 // ctx.strokeStyle = "blue";
939 // ctx.lineWidth = 0.5;
940 // ctx.stroke(this.pPauseRun);
941 // ctx.strokeStyle = "black";
942 }
943
944 ctx.lineWidth = 1;
945
946 // Now some symbols above the circle for adjusting the step size.
947
948 if (this.visSteps === true)
949 {
950 // Up and down arrows.
951 let stepSpace = 20;
952 let stepThick = 2.0;
953 let upperGap = 8;
954 let stepHeight = 15;
955 let stepArrowHeight = 8;
956 let stepArrowWidth = 5;
957
958 ctx.lineWidth = stepThick;
959
960 if (this.sDownStep == true)
961 {
962 ctx.strokeStyle = LoopAnimWidget.sColor;
963 ctx.fillStyle = LoopAnimWidget.sColor;
964 }
965 else
966 {
967 ctx.strokeStyle = "black";
968 ctx.fillStyle = "black";
969 }
970
971 // Vertical line
972 p = new Path2D();
973 p.moveTo(cx - stepSpace,cy + r + circWidth/2 + upperGap);
974 p.lineTo(cx - stepSpace,cy + r + circWidth/2 + upperGap + stepHeight);
975 ctx.stroke(p);
976
977 // Arrow head
978 p = new Path2D();
979 p.moveTo(cx - stepSpace,
980 cy + r + circWidth/2 + upperGap - stepThick);
981 p.lineTo(cx - stepSpace + stepArrowWidth,
982 cy + r + circWidth/2 + upperGap + stepArrowHeight - stepThick);
983 p.lineTo(cx - stepSpace - stepArrowWidth,
984 cy + r + circWidth/2 + upperGap + stepArrowHeight - stepThick);
985 p.closePath();
986 ctx.fill(p);
987
988 // Clickable area for down arrow.
989 this.pDownStep = new Path2D();
990 this.pDownStep.rect(cx - stepSpace - stepArrowWidth,
991 cy + r + circWidth/2 + upperGap - stepThick,
992 2*stepArrowWidth,stepHeight + stepThick);
993
994 // ctx.strokeStyle = "blue";
995 // ctx.lineWidth = 0.5;
996 // ctx.stroke(this.pDownStep);
997 // ctx.strokeStyle = "black";
998 // ctx.lineWidth = stepThick;
999
1000 // Again, to the right, arrow head up.
1001 if (this.sUpStep == true)
1002 {
1003 ctx.strokeStyle = LoopAnimWidget.sColor;
1004 ctx.fillStyle = LoopAnimWidget.sColor;
1005 }
1006 else
1007 {
1008 ctx.strokeStyle = "black";
1009 ctx.fillStyle = "black";
1010 }
1011
1012 p = new Path2D();
1013 p.moveTo(cx + stepSpace,cy + r + circWidth/2 + upperGap);
1014 p.lineTo(cx + stepSpace,cy + r + circWidth/2 + upperGap + stepHeight);
1015 ctx.stroke(p);
1016
1017 p = new Path2D();
1018 p.moveTo(cx + stepSpace,
1019 cy + r + circWidth/2 + upperGap + stepHeight + stepThick);
1020 p.lineTo(cx + stepSpace + stepArrowWidth,
1021 cy + r + circWidth/2 + upperGap + stepHeight - stepArrowHeight + stepThick);
1022 p.lineTo(cx + stepSpace - stepArrowWidth,
1023 cy + r + circWidth/2 + upperGap + stepHeight - stepArrowHeight + stepThick);
1024 p.closePath();
1025 ctx.fill(p);
1026
1027 // Clickable area for up arrow.
1028 this.pUpStep = new Path2D();
1029 this.pUpStep.rect(cx + stepSpace - stepArrowWidth,
1030 cy + r + circWidth/2 + upperGap,
1031 2*stepArrowWidth,stepHeight + stepThick);
1032
1033 // ctx.strokeStyle = "blue";
1034 // ctx.lineWidth = 0.5;
1035 // ctx.stroke(this.pUpStep);
1036 // ctx.strokeStyle = "black";
1037
1038 ctx.lineWidth = 1;
1039
1040 // A little step icon.
1041 ctx.strokeStyle = "black";
1042 ctx.fillStyle = "black";
1043 stepThick = 1.5;
1044 let stepSize = 6;
1045
1046 ctx.lineWidth = stepThick;
1047
1048 // Steps made as one path, starting at upper-left
1049 p = new Path2D();
1050 p.moveTo(cx - stepSize,cy + r + circWidth/2 + upperGap + 2*stepSize);
1051 p.lineTo(cx,cy + r + circWidth/2 + upperGap + 2*stepSize);
1052 p.lineTo(cx,cy + r + circWidth/2 + upperGap + stepSize);
1053 p.lineTo(cx + stepSize,cy + r + circWidth/2 + upperGap + stepSize);
1054 p.lineTo(cx + stepSize,cy + r + circWidth/2 + upperGap);
1055 ctx.stroke(p);
1056 }
1057
1058 ctx.lineWidth = 1;
1059
1060 // Used this to verify the constants. The rectangle barely encloses
1061 // the widget.
1062 //ctx.strokeRect(
1063 // -LoopWidget.Radius,-LoopWidget.Radius - LoopWidget.TopHeight,
1064 // 2*LoopWidget.Radius,
1065 // 2*LoopWidget.Radius + LoopWidget.TopHeight + LoopWidget.BottomHeight);
1066
1067 ctx.setTransform(saveT);
1068 }
1069
1070 mouseDown(x : number , y : number ) : boolean {
1071
1072 // (x,y) is given in coordinates relative to the owning figure.
1073 // Return true iff these coordinates apply to this widget.
1074 if (this.hide === true)
1075 return false;
1076
1077 // Adjust coordinates relative to what the draw() methods uses.
1078 // This way we can compare (x,y) to what is on the screen.
1079 x -= this.widgetX;
1080 y -= this.widgetY;
1081 x /= this.scale;
1082 y /= this.scale;
1083
1084 // The widget also has a scale, which must be taken into account.
1085 WidgetManager.bogusCtx.resetTransform();
1086
1087 // There is isPointInPath() and isPointInStroke().
1088 // It seems that isPointInPath() works on an abstract geometric basis;
1089 // the lineWidth of the ctx doesn't matter. OTOH, isPointInStroke()
1090 // is affected by the lineWidth -- as it must be to work in any
1091 // reasonable way.
1092 //
1093 // Note also that isPointInPath() defaults to the non-zero winding rule.
1094 // Pass "evenodd" as the final argument for that winding rule.
1095
1096 // Check the pause/run area first since it should be "on top of"
1097 // the circle area.
1098 if (this.pPauseRun !== null)
1099 {
1100 let isin = WidgetManager.bogusCtx.isPointInPath(this.pPauseRun,x,y);
1101 if (isin === true)
1102 {
1103 this.sPauseRun = true;
1104 WidgetManager.mouseOwner = this;
1105 renderFrame(this);
1106 return true;
1107 }
1108 }
1109
1110 // And the run faster area.
1111 if (this.pFaster !== null)
1112 {
1113 let isin = WidgetManager.bogusCtx.isPointInPath(this.pFaster,x,y);
1114 if (isin === true)
1115 {
1116 this.sFaster = true;
1117 WidgetManager.mouseOwner = this;
1118 renderFrame(this);
1119 return true;
1120 }
1121 }
1122
1123 // The run slower area.
1124 if (this.pSlower !== null)
1125 {
1126 let isin = WidgetManager.bogusCtx.isPointInPath(this.pSlower,x,y);
1127 if (isin === true)
1128 {
1129 this.sSlower = true;
1130 WidgetManager.mouseOwner = this;
1131 renderFrame(this);
1132 return true;
1133 }
1134 }
1135
1136 // The longer step area.
1137 if (this.pUpStep !== null)
1138 {
1139 let isin = WidgetManager.bogusCtx.isPointInPath(this.pUpStep,x,y);
1140 if (isin === true)
1141 {
1142 this.sUpStep = true;
1143 WidgetManager.mouseOwner = this;
1144 renderFrame(this);
1145 return true;
1146 }
1147 }
1148
1149 // The shorter step area.
1150 if (this.pDownStep !== null)
1151 {
1152 let isin = WidgetManager.bogusCtx.isPointInPath(this.pDownStep,x,y);
1153 if (isin === true)
1154 {
1155 this.sDownStep = true;
1156 WidgetManager.mouseOwner = this;
1157 renderFrame(this);
1158 return true;
1159 }
1160 }
1161
1162 // Last thing to check since it should be "underneath" everything.
1163 if (this.pCircle !== null)
1164 {
1165 // If the user clicked near the circle, then set the indicator and
1166 // current step to that position. Be generous with the clickable area.
1167 WidgetManager.bogusCtx.lineWidth = 15;
1168 let isin = WidgetManager.bogusCtx.isPointInStroke(this.pCircle,x,y);
1169
1170 if (isin === true)
1171 {
1172 // Act on this click and take ownership for future draggging.
1173 // Want an angle in [0,2pi].
1174 this.sCircle = true;
1175
1176 // Again, minus since clockwise.
1177 let alpha = -Math.atan2(y,x);
1178 if (alpha < 0)
1179 alpha += 2*Math.PI;
1180
1181 this.curStep = Math.floor(this.steps * alpha / (2*Math.PI));
1182
1183 WidgetManager.mouseOwner = this;
1184
1185 // The appearance of the widget has changed.
1186 renderFrame(this);
1187
1188 return true;
1189 }
1190 }
1191
1192 return false;
1193 }
1194
1195 mouseMove(x : number , y : number ) : void {
1196
1197 // As above.
1198 if (this.hide === true)
1199 return;
1200
1201 x -= this.widgetX;
1202 y -= this.widgetY;
1203 x /= this.scale;
1204 y /= this.scale;
1205 WidgetManager.bogusCtx.resetTransform();
1206
1207 if (this.sCircle === true)
1208 {
1209 // What I will do it check that the mouse is "close enough" to the
1210 // circle, but it can be a *long* ways away.
1211 WidgetManager.bogusCtx.lineWidth = 40;
1212 let isin = WidgetManager.bogusCtx.isPointInStroke(this.pCircle !,x,y);
1213
1214 if (isin == false)
1215 return;
1216
1217 // Minus to make clockwise.
1218 let alpha = -Math.atan2(y,x);
1219 if (alpha < 0)
1220 alpha += 2*Math.PI;
1221
1222 this.curStep = Math.floor(this.steps * alpha / (2*Math.PI));
1223
1224 // The appearance of the widget may have changed.
1225 renderFrame(this);
1226 }
1227
1228 // BUG: I might (?) want colors to change based on what the mouse
1229 // is over. See the BUG comment that goes with aRunning, sCircle, etc.,
1230 // at the top of the class.
1231 }
1232
1233 mouseUp(x : number , y : number ) : void {
1234
1235 // As above.
1236 if (this.hide === true)
1237 return;
1238
1239 x -= this.widgetX;
1240 y -= this.widgetY;
1241 x /= this.scale;
1242 y /= this.scale;
1243 WidgetManager.bogusCtx.resetTransform();
1244
1245 // The mouse is up, so nothing can remain selected. In most cases,
1246 // releasing the mouse over the selected item means that something
1247 // must be done since the "button" was properly pressed.
1248 this.sCircle = false;
1249
1250 if (this.sPauseRun)
1251 {
1252 // Did they *release* the mouse over the pause/run area?
1253 let isin = WidgetManager.bogusCtx.isPointInPath(this.pPauseRun ! ,x,y);
1254 if (isin === true)
1255 {
1256 // Start/stop the animation.
1257 if (this.aRunning === true)
1258 // Currently running. Pause it.
1259 clearInterval(this.animID);
1260 else
1261 // Currently paused. Restart it.
1262 this.animID = setInterval(doAnimation,this.timeStep,this);
1263
1264 // Change the pause/run icon too.
1265 if (this.aRunning === true)
1266 this.aRunning = false;
1267 else
1268 this.aRunning = true;
1269 }
1270
1271 this.sPauseRun = false;
1272 }
1273
1274 if (this.sFaster === true)
1275 {
1276 let isin = WidgetManager.bogusCtx.isPointInPath(this.pFaster ! ,x,y);
1277 if (isin === true)
1278 {
1279 // Make the animation run a bit faster by reducing the frame-to-
1280 // frame time step -- the animation speed. This could be done in
1281 // a lot of different ways, by using a factor of 1.4 seems about
1282 // right.
1283 this.timeStep /= 1.4;
1284 if (this.timeStep < 1)
1285 this.timeStep = 1;
1286
1287 // Stop the animation and restart it at the new speed,
1288 // but only if it is currently running. It restarts always, but
1289 // don't try to halt it if it's not running.
1290 if (this.aRunning === true)
1291 clearInterval(this.animID);
1292
1293 this.animID = setInterval(doAnimation,this.timeStep,this);
1294 this.aRunning = true;
1295 }
1296
1297 this.sFaster = false;
1298 }
1299
1300 if (this.sSlower === true)
1301 {
1302 // Just as above, but make it go slower.
1303 let isin = WidgetManager.bogusCtx.isPointInPath(this.pSlower ! ,x,y);
1304 if (isin === true)
1305 {
1306 this.timeStep *= 1.4;
1307
1308 // More than a second per frame is silly.
1309 if (this.timeStep > 1000)
1310 this.timeStep = 1000;
1311
1312 if (this.aRunning === true)
1313 clearInterval(this.animID);
1314
1315 this.animID = setInterval(doAnimation,this.timeStep,this);
1316 this.aRunning = true;
1317 }
1318
1319 this.sSlower = false;
1320 }
1321
1322 if (this.sUpStep === true)
1323 {
1324 // Make the number of time increments per frame larger.
1325 let isin = WidgetManager.bogusCtx.isPointInPath(this.pUpStep ! ,x,y);
1326 if (isin === true)
1327 {
1328 // Use a smaller ratio here. Conceptually, it seems like
1329 // this should be an integer, but it really doesn't have to be.
1330 this.stepsPerFrame *= 1.25;
1331
1332 // Fewer than 3 frames per cycle seems silly. For most animations,
1333 // you'd proably want at least 10 or 20, at a minimum.
1334 if (this.stepsPerFrame > this.steps / 3)
1335 this.stepsPerFrame = this.steps / 3;
1336 }
1337
1338 this.sUpStep = false;
1339 }
1340
1341 if (this.sDownStep === true)
1342 {
1343 // As above.
1344 let isin = WidgetManager.bogusCtx.isPointInPath(this.pDownStep ! ,x,y);
1345 if (isin === true)
1346 {
1347 this.stepsPerFrame /= 1.25;
1348
1349 // I am tempted to put a lower bound on this, but it's 'not
1350 // absolutely necessary.
1351 }
1352
1353 this.sDownStep = false;
1354 }
1355
1356 // The appearance of the widget may have changed.
1357 renderFrame(this);
1358
1359 }
1360 }
1361
1362
1363 // An OpenAnimWidget is for an open-ended animation that doesn't loop back
1364 // on itself and repeat. In many respects, it's similar to a LoopWidget.
1365 // It looks different because it's a long bar, sort of like a scroll bar.
1366 // It's so similar that there are minimal (for me) comments. See
1367 // LoopWidgets for certain details.
1368
1369 class OpenAnimWidget extends AnimationWidget {
1370
1371 // These are useful to the user to help properly place things.
1372 // The widget is placed based on the lower-left corner, and the
1373 // user can specify the width. The BarHeight is the height of the
1374 // bar portion -- it's essentially the radius of the indicator dot --
1375 // and ControlsHeight is for the controls.
1376 static BarHeight = 6.0;
1377 static ControlsHeight = 20.0;
1378
1379 // This is useful to help the user place stuff above the control.
1380 static TotalHeight = 32.0;
1381
1382
1383 // When things are "selected," draw them in this color.
1384 static sColor = "blue";
1385
1386 // These things are important to the animation drawing code, and are
1387 // meant to be public(ish).
1388
1389 // These are as passed to register().
1390 barLength = 100;
1391 timeStep = 25;
1392 decay = 1.0001;
1393 visSteps = true;
1394 visFastSlow = true;
1395 visPauseRun = true;
1396 visBar = true;
1397 barGrab = true;
1398
1399 // As for LoopWidth, width modest changes:
1400
1401 // Clickable areas:
1402 pBar : Path2D | null = null;
1403 pDot : Path2D | null = null;
1404 pFaster : Path2D | null = null;
1405 pSlower : Path2D | null = null;
1406 pPauseRun : Path2D | null = null;
1407 pUpStep : Path2D | null = null;
1408 pDownStep : Path2D | null = null;
1409
1410 // States of parts:
1411 //
1412 // BUG: If I want to get *really* fancy, then I need another set of
1413 // flags to indicate that the mouse *was* clicked on something, so it
1414 // is "selected," but the user moved the mouse away from the item without
1415 // a mouse-up, so that selected item should be drawn in normal color, not
1416 // the highlighted color (sColor). If the mouse is moved back over the
1417 // selected item, then the color can go back to being the selection color.
1418 aRunning = true;
1419 sDot = false;
1420 sFaster = false;
1421 sSlower = false;
1422 sPauseRun = false;
1423 sUpStep = false;
1424 sDownStep = false;
1425
1426
1427 static register(ctx : CanvasRenderingContext2D , x : number , y : number ,scale : number ,
1428 width : number , visWidget : boolean , timeStep : number , decay : number ,
1429 visSteps : boolean , visFastSlow : boolean , visPauseRun : boolean ,visBar : boolean ,
1430 barGrab : boolean , name : string ) : OpenAnimWidget {
1431
1432 // This is used something like a constructor. It either creates a new
1433 // LoopWidget and returns it, or returns one that was created earlier.
1434
1435 // Many of these arguments are the same as for Widget.constructor().
1436 // In addition, we have
1437 // * ctx is assumed to have a t-matrix prepared to properly draw
1438 // the widget.
1439 // * width is the length of the indicator bar. If you want both the
1440 // controls (time steps and fast/slow), then this should be at least
1441 // 200 so that the controls don't stick out. Of course, this is the
1442 // unscaled size, and you can make the entire thing smaller with the
1443 // scale argument.
1444 // * timeStep, in milliseconds, is the time from frame to frame.
1445 // * decay is complicated. The value of this.curStep must be mapped to
1446 // the linear bar, which is not infinite.
1447 // We need a map from [0,infty) to [0,width). Define
1448 // f(s) = 1 - 1/a^s
1449 // This maps [0,infty) to [0,1), provided that a > 1. Then
1450 // g(s) = w f(s)
1451 // is the function we want. But what about a? The closer a is to 1,
1452 // the faster g(s) will approach w. Typically, you'll want a to be
1453 // something like 1.001 or 1.0001, depending on the number of steps
1454 // in your animation. The decay argment determines a:
1455 // a = 1 + 1/decay, so you'll usually want decay to be somewhere in the
1456 // range from 100 to (maybe) 100,000. It depends how big the steps
1457 // are and how long you want the animiation to run. For comparison,
1458 // decay = 1,000 puts f(2000) = 0.86 and f(5000) = 0.99, while
1459 // decay = 10,000 puts f(2000) = 0.18, f(5000) = 0.39,
1460 // f(20,000) = 0.86. You can also work backwards. If you want
1461 // f(n) = x, where x is in [0,1), like x = 85%, then you want
1462 // 1 / (1 + 1/a)^n = x, or
1463 // a = 1 / [ x^(1/n) - 1 ]
1464 // That's not so informative, but you can write it as
1465 // a = 1 / [ exp(-ln(x)/n) - 1 ]
1466 // If we take x \approx 0.86 so that ln(x) = -0.15 (exactly), then
1467 // a = 1 / [ exp(-0.15/n) - 1 ]
1468 // Plug in the value for n at which you want to have reached the
1469 // 86% level, and you get a.
1470 // For brevity, in the code, I use this.decay as the value, a,
1471 // discussed above.
1472 // BUG: I feel like I made an algebra mistake, but that's the idea.
1473 // * visWidget is whether the widget is visible at all -- same as the
1474 // vis argument to Widget.construtor().
1475 // * visSteps is whether the time step controls (at the right) are visible.
1476 // * visFastSlow is whether the faster/slower controls are visible (at
1477 // the left)
1478 // * visPauseRun is whether the pause/run controls are visible.
1479 // * visBar is for the progress bar (with dot indicator).
1480 // * barGrab is whether the user is allowed to grab the dot indicator
1481 // triangle and control the animation by dragging it.
1482 // * name is as in Widget.constructor()
1483 //
1484 // BUG: Maybe I should have different classes for some of these choices.
1485 // There are just too many. These could all use (internally) the
1486 // same class, just not with such a crazy number of options.
1487
1488
1489 // As for LoopWidget.
1490 let type = "OpenAnimWidget";
1491 let caller = getCaller();
1492
1493 let w : OpenAnimWidget = <OpenAnimWidget> WidgetManager.knownWidget(caller,type,name);
1494
1495 if (w != null)
1496 {
1497 w.draw(ctx);
1498 return w;
1499 }
1500
1501 // Got here, so this widget is not already known, and must be created.
1502 w = new OpenAnimWidget(caller,type,x,y,scale,!visWidget,name);
1503
1504 // Adjust the length for the scale so that if the user asks for
1505 // a bar that is X px long, he gets it. So, the scale adjusts the size
1506 // of the "bits", not the total size.
1507 w.barLength = width / scale;
1508 w.timeStep = timeStep;
1509 w.visSteps = visSteps;
1510 w.visFastSlow = visFastSlow;
1511 w.visPauseRun = visPauseRun;
1512 w.visBar = visBar;
1513 w.barGrab = barGrab;
1514
1515 // For internal use, we convert the given decay to the value we use
1516 // for exponentiation.
1517 w.decay = 1 + 1/decay;
1518
1519 // Note the existence of this widget for the future.
1520 WidgetManager.register(w);
1521
1522 // This is a special case because it's an animiation, as with LoopWidget.
1523 w.animID = setInterval(doAnimation,w.timeStep,w);
1524
1525 // Before returning the widget, it must be drawn.
1526 w.draw(ctx);
1527
1528 return w;
1529 }
1530
1531 advanceFrame() : void {
1532
1533 // This animation is open-ended; curStep grows without limit (up to
1534 // E500 or whatever it is).
1535 this.curStep += this.stepsPerFrame;
1536 }
1537
1538 draw(ctx : CanvasRenderingContext2D ) : void {
1539
1540 // This is drawn with (0,0) at the lower-right corner.
1541 if (this.hide === true)
1542 return;
1543
1544 // Don't draw the widget to a tikz file.
1545 if (ctx instanceof CTX)
1546 return;
1547
1548 let saveT = ctx.getTransform();
1549 ctx.translate(this.widgetX,this.widgetY);
1550 ctx.scale(this.scale,this.scale);
1551
1552 var p = new Path2D();
1553
1554 if (this.visBar == true)
1555 {
1556 // These *could* be made accessible to the user, but we already
1557 // have a heap of arguments to create this thing.
1558 let indDotRadius = 5.0;
1559 let barThick = 3.0;
1560 let indDotThick = 2.0;
1561
1562 // Draw the indicator bar and dot.
1563 // Bar first.
1564 p.moveTo(0,indDotRadius + OpenAnimWidget.ControlsHeight);
1565 p.lineTo(this.barLength,indDotRadius + OpenAnimWidget.ControlsHeight);
1566
1567 // Note this circle for reference by mouse events.
1568 if (this.barGrab === true)
1569 this.pBar = new Path2D(p);
1570
1571 ctx.lineWidth = barThick;
1572
1573 ctx.stroke(p);
1574
1575 // Now the dot.
1576 p = new Path2D();
1577
1578 let dx = Math.pow(this.decay,this.curStep);
1579
1580 dx = this.barLength * (1 - 1/dx);
1581 p.ellipse(dx,indDotRadius + OpenAnimWidget.ControlsHeight,
1582 indDotRadius,indDotRadius,0,0,2*Math.PI);
1583
1584 if (this.barGrab === true)
1585 this.pDot = new Path2D(p);
1586
1587 if (this.sDot == true)
1588 ctx.fillStyle = OpenAnimWidget.sColor;
1589 else
1590 ctx.fillStyle = "red";
1591
1592 ctx.fill(p);
1593
1594 ctx.lineWidth = indDotThick;
1595 ctx.strokeStyle = "black";
1596 ctx.stroke(p);
1597 }
1598
1599 // There may be controls under the bar for faster/slower, pause/run
1600 // and larger/smaller steps. Whatever of these is present, they should be
1601 // centered, which is a pain. The total width of the pause/run controls
1602 // is 40.5, obtained by checking the size of the box necessary to
1603 // exactly enclose the controls. Height of that box is 14. I've set
1604 // things up so that the height of the "step size" controls is also 14,
1605 // and the width of that part is 32. These *could* be expressed in
1606 // terms of the various constants defined below, but hard-coding is
1607 // easier.
1608 // These controls are drawn relative to their individual centers,
1609 // so the shifting is done relative to those centers and their widths.
1610 let pauseRunWidth = 40;
1611 let stepsWidth = 32;
1612 let intraGap = 8;
1613
1614 // Here (compared to LoopWidget), I use cx and cy to shift the parts
1615 // of the control down and right. The right-shift is used for centering
1616 // Changing the t-matrix of ctx would work too.
1617 let cy = OpenAnimWidget.BarHeight - 4;
1618 let cx = this.barLength / 2;
1619
1620 // We position the right bit, based on whether the left bit is present.
1621 if (this.visSteps === true)
1622 cx += intraGap + (pauseRunWidth / 2);
1623
1624 // Used for both fast/slow "chevrons" and for up/down arrows.
1625 let arrowHeight = 7;
1626
1627 if (this.visFastSlow === true)
1628 {
1629
1630 // I made this a little tighter than for LoopWidget.
1631 let arrowOffset = 12;//18;
1632 let arrowDepth = 4;
1633 let arrowPairSpace = 3;
1634 let arrowThick = 1.25;
1635
1636 // First, a pair of '>' for going faster.
1637 ctx.lineWidth = arrowThick;
1638
1639 if (this.sFaster == true)
1640 ctx.strokeStyle = OpenAnimWidget.sColor;
1641 else
1642 ctx.strokeStyle = "black";
1643
1644 p = new Path2D();
1645 p.moveTo(cx + arrowOffset, cy);
1646 p.lineTo(cx + arrowOffset + arrowDepth,cy + arrowHeight);
1647 p.lineTo(cx + arrowOffset,cy + 2*arrowHeight);
1648 ctx.stroke(p);
1649
1650 // You can't just shift a path. Needs to be rebuilt.
1651 p = new Path2D();
1652 p.moveTo(cx + arrowOffset + arrowPairSpace,cy);
1653 p.lineTo(cx + arrowOffset + arrowDepth + arrowPairSpace,
1654 cy + arrowHeight);
1655 p.lineTo(cx + arrowOffset + arrowPairSpace,cy + 2*arrowHeight);
1656 ctx.stroke(p);
1657
1658 // A rectangle for the clickable area.
1659 this.pFaster = new Path2D();
1660 this.pFaster.rect(cx + arrowOffset - arrowThick,cy,
1661 arrowPairSpace + arrowDepth + 2*arrowThick,2*arrowHeight);
1662
1663 /*
1664 // BUG: testing
1665 ctx.strokeStyle = "green";
1666 ctx.lineWidth = 0.5;
1667 ctx.stroke(this.pFaster);
1668 ctx.strokeStyle = "black";
1669 ctx.lineWidth = arrowThick;
1670 */
1671
1672 // Same idea: '<' to go slower.
1673 if (this.sSlower == true)
1674 ctx.strokeStyle = LoopAnimWidget.sColor;
1675 else
1676 ctx.strokeStyle = "black";
1677
1678 p = new Path2D();
1679 p.moveTo(cx - arrowOffset,cy);
1680 p.lineTo(cx - arrowOffset - arrowDepth,cy + arrowHeight);
1681 p.lineTo(cx - arrowOffset,cy + 2*arrowHeight);
1682 ctx.stroke(p);
1683
1684 p = new Path2D();
1685 p.moveTo(cx - arrowOffset - arrowPairSpace,cy);
1686 p.lineTo(cx - arrowOffset - arrowDepth - arrowPairSpace,cy + arrowHeight);
1687 p.lineTo(cx - arrowOffset - arrowPairSpace,cy + 2*arrowHeight);
1688 ctx.stroke(p);
1689
1690 // And the clickable area.
1691 this.pSlower = new Path2D();
1692 this.pSlower.rect(cx - arrowOffset - arrowPairSpace - arrowDepth - arrowThick,
1693 cy,arrowPairSpace + arrowDepth + 2*arrowThick,2*arrowHeight);
1694
1695 /*
1696 // BUG: testing
1697 ctx.strokeStyle = "yellow";
1698 ctx.lineWidth = 0.5;
1699 ctx.stroke(this.pSlower);
1700 ctx.strokeStyle = "black";
1701 */
1702
1703 /*
1704 // BUG: test box around entire thing.
1705 p = new Path2D();
1706 p.rect(cx - arrowOffset - arrowPairSpace - arrowDepth - arrowThick,cy,
1707 2*(arrowOffset + arrowPairSpace + arrowDepth + arrowThick),
1708 2*arrowHeight);
1709
1710 //let temp = 2*(arrowOffset + arrowPairSpace + arrowDepth + arrowThick);
1711 //console.log("val: " +temp);
1712
1713 ctx.strokeStyle = "red";
1714 ctx.stroke(p);
1715 */
1716
1717 ctx.strokeStyle = "black";
1718 }
1719
1720 ctx.lineWidth = 1;
1721
1722 if (this.visPauseRun === true)
1723 {
1724 // A || or triangle for pause or run.
1725
1726 let pauseSpace = 3.25;
1727 let pauseThick = 1.5;
1728 let pauseHeight = 2 * arrowHeight;
1729
1730 let runThick = 1.5;
1731 let runLeftRight = 5;
1732 let runHeight = 2 * arrowHeight;
1733
1734 if (this.sPauseRun == true)
1735 ctx.strokeStyle = LoopAnimWidget.sColor;
1736 else
1737 ctx.strokeStyle = "black";
1738
1739 if (this.aRunning === true)
1740 {
1741 // The animation is running, so show || to allow pausing.
1742 ctx.lineWidth = pauseThick;
1743
1744 p = new Path2D();
1745 p.moveTo(cx + pauseSpace,cy);
1746 p.lineTo(cx + pauseSpace,cy + pauseHeight);
1747 ctx.stroke(p);
1748
1749 p = new Path2D();
1750 p.moveTo(cx - pauseSpace,cy);
1751 p.lineTo(cx - pauseSpace,cy + pauseHeight);
1752 ctx.stroke(p);
1753
1754 ctx.lineWidth = 1;
1755 }
1756 else
1757 {
1758 // Animation is paused, so show triangle to run it again.
1759 ctx.lineWidth = runThick;
1760
1761 p = new Path2D();
1762 p.moveTo(cx - runLeftRight,cy);
1763 p.lineTo(cx - runLeftRight,cy + runHeight);
1764 p.lineTo(cx + runLeftRight,cy + runHeight/2);
1765 p.closePath();
1766 ctx.stroke(p);
1767 }
1768
1769 // Either way (paused or running), we need the clickable area.
1770 // This area is too generous for the "run" triangle, because
1771 // I use the same rectangle for "pause" and "run," but no big deal.
1772 this.pPauseRun = new Path2D();
1773 this.pPauseRun.rect(cx - runLeftRight - runThick,
1774 cy - runThick,2*runLeftRight + 2*runThick,runHeight + 2*runThick);
1775
1776 /*
1777 // BUG: testing
1778 ctx.strokeStyle = "blue";
1779 ctx.lineWidth = 0.5;
1780 ctx.stroke(this.pPauseRun);
1781 ctx.strokeStyle = "black";
1782 */
1783 }
1784
1785 // And position the left controls, based on whether the ones on
1786 // the right are present.
1787 cy += 12.5;
1788 cx = this.barLength / 2;
1789 if ((this.visPauseRun === true) || (this.visFastSlow === true))
1790 cx -= intraGap + stepsWidth/2;
1791
1792 ctx.lineWidth = 1;
1793
1794 // Symbols for adjusting the step size.
1795 if (this.visSteps === true)
1796 {
1797 // Up and down arrows. This is a little smaller than for LoopWidget,
1798 // so that the height matches the paure/run controls. I also
1799 // tightened up the spacing a bit.
1800 // Note that I am also using stepThick as a proxy for adjustment
1801 // of the fact that the tip of the arrow head is a little tall.
1802 let stepSpace = 12;
1803 let stepThick = 2.0;
1804 let stepHeight = 12.5;
1805 let stepArrowHeight = 5.0;
1806 let stepArrowWidth = 4.0;
1807
1808 ctx.lineWidth = stepThick;
1809
1810 if (this.sDownStep === true)
1811 {
1812 ctx.strokeStyle = OpenAnimWidget.sColor;
1813 ctx.fillStyle = OpenAnimWidget.sColor;
1814 }
1815 else
1816 {
1817 ctx.strokeStyle = "black";
1818 ctx.fillStyle = "black";
1819 }
1820
1821 // Vertical line
1822 p = new Path2D();
1823 p.moveTo(cx - stepSpace,cy);
1824 p.lineTo(cx - stepSpace,cy- stepHeight);
1825 ctx.stroke(p);
1826
1827 // Arrow head
1828 p = new Path2D();
1829 p.moveTo(cx - stepSpace,cy + stepThick);
1830 p.lineTo(cx - stepSpace + stepArrowWidth,cy - stepArrowHeight + stepThick);
1831 p.lineTo(cx - stepSpace - stepArrowWidth,cy - stepArrowHeight + stepThick);
1832 p.closePath();
1833 ctx.fill(p);
1834
1835 // Clickable area for down arrow.
1836 this.pDownStep = new Path2D();
1837 this.pDownStep.rect(cx - stepSpace - stepArrowWidth,cy - stepHeight,
1838 2*stepArrowWidth,stepHeight + stepThick);
1839
1840 /*
1841 // BUG: testing
1842 ctx.strokeStyle = "blue";
1843 ctx.lineWidth = 0.5;
1844 ctx.stroke(this.pDownStep);
1845 ctx.strokeStyle = "black";
1846 ctx.lineWidth = stepThick;
1847 */
1848
1849 // Again, to the right, arrow head up.
1850 if (this.sUpStep === true)
1851 {
1852 ctx.strokeStyle = OpenAnimWidget.sColor;
1853 ctx.fillStyle = OpenAnimWidget.sColor;
1854 }
1855 else
1856 {
1857 ctx.strokeStyle = "black";
1858 ctx.fillStyle = "black";
1859 }
1860
1861 p = new Path2D();
1862 p.moveTo(cx + stepSpace,cy + stepThick);
1863 p.lineTo(cx + stepSpace,cy + stepThick - stepHeight);
1864 ctx.stroke(p);
1865
1866 p = new Path2D();
1867 p.moveTo(cx + stepSpace,cy - stepHeight);
1868 p.lineTo(cx + stepSpace + stepArrowWidth,
1869 cy - stepHeight + stepArrowHeight);
1870 p.lineTo(cx + stepSpace - stepArrowWidth,
1871 cy - stepHeight + stepArrowHeight);
1872 p.closePath();
1873 ctx.fill(p);
1874
1875 // Clickable area for up arrow.
1876 this.pUpStep = new Path2D();
1877 this.pUpStep.rect(cx + stepSpace - stepArrowWidth,
1878 cy - stepHeight,
1879 2*stepArrowWidth,stepHeight + stepThick);
1880
1881 /*
1882 // BUG: testing
1883 ctx.strokeStyle = "blue";
1884 ctx.lineWidth = 0.5;
1885 ctx.stroke(this.pUpStep);
1886 ctx.strokeStyle = "black";
1887 */
1888
1889 ctx.lineWidth = 1;
1890
1891 // A little step icon.
1892 ctx.strokeStyle = "black";
1893 ctx.fillStyle = "black";
1894 stepThick = 1.5;
1895 let stepSize = 5;
1896
1897 ctx.lineWidth = stepThick;
1898
1899 // Steps made as one path, starting at upper-left
1900 p = new Path2D();
1901 p.moveTo(cx - stepSize,cy - 2*stepSize);
1902 p.lineTo(cx,cy - 2*stepSize);
1903 p.lineTo(cx,cy - stepSize);
1904 p.lineTo(cx + stepSize,cy - stepSize);
1905 p.lineTo(cx + stepSize,cy);
1906 ctx.stroke(p);
1907
1908 /*
1909 // BUG: Testing box around it all.
1910 p = new Path2D();
1911 p.rect(cx - stepSpace - stepArrowWidth,cy - stepHeight,
1912 2*(stepSpace + stepArrowWidth),
1913 stepHeight + stepThick);
1914
1915 ctx.strokeStyle = "red";
1916 ctx.lineWidth = 0.5;
1917 ctx.stroke(p);
1918
1919 //let temp = 2*(stepSpace + stepArrowWidth);
1920 //let temp = stepHeight + stepThick;
1921 //console.log("val: " + temp);
1922 */
1923
1924 ctx.strokeStyle = "black";
1925
1926 }
1927
1928 ctx.lineWidth = 1;
1929
1930 ctx.setTransform(saveT);
1931 }
1932
1933 mouseDown( x : number , y : number ) : boolean {
1934
1935 // (x,y) is given in coordinates relative to the owning figure.
1936 // Return true iff these coordinates apply to this widget.
1937 // BUG: This is almost identical to LoopWidget. DRY?
1938 if (this.hide === true)
1939 return false;
1940
1941 // Adjust coordinates relative to what the draw() methods uses.
1942 x -= this.widgetX;
1943 y -= this.widgetY;
1944 x /= this.scale;
1945 y /= this.scale;
1946
1947 // The widget also has a scale, which must be taken into account.
1948 WidgetManager.bogusCtx.resetTransform();
1949
1950 // The run faster area.
1951 if (this.pFaster !== null)
1952 {
1953 let isin = WidgetManager.bogusCtx.isPointInPath(this.pFaster,x,y);
1954 if (isin === true)
1955 {
1956 this.sFaster = true;
1957 WidgetManager.mouseOwner = this;
1958 renderFrame(this);
1959 return true;
1960 }
1961 }
1962
1963 // The run slower area.
1964 if (this.pSlower !== null)
1965 {
1966 let isin = WidgetManager.bogusCtx.isPointInPath(this.pSlower,x,y);
1967 if (isin === true)
1968 {
1969 this.sSlower = true;
1970 WidgetManager.mouseOwner = this;
1971 renderFrame(this);
1972 return true;
1973 }
1974 }
1975
1976
1977 // The pause/run area.
1978 if (this.pPauseRun !== null)
1979 {
1980 let isin = WidgetManager.bogusCtx.isPointInPath(this.pPauseRun,x,y);
1981 if (isin === true)
1982 {
1983 this.sPauseRun = true;
1984 WidgetManager.mouseOwner = this;
1985 renderFrame(this);
1986 return true;
1987 }
1988 }
1989
1990 // The longer step area.
1991 if (this.pUpStep !== null)
1992 {
1993 let isin = WidgetManager.bogusCtx.isPointInPath(this.pUpStep,x,y);
1994 if (isin === true)
1995 {
1996 this.sUpStep = true;
1997 WidgetManager.mouseOwner = this;
1998 renderFrame(this);
1999 return true;
2000 }
2001 }
2002
2003 // The shorter step area.
2004 if (this.pDownStep !== null)
2005 {
2006 let isin = WidgetManager.bogusCtx.isPointInPath(this.pDownStep,x,y);
2007 if (isin === true)
2008 {
2009 this.sDownStep = true;
2010 WidgetManager.mouseOwner = this;
2011 renderFrame(this);
2012 return true;
2013 }
2014 }
2015
2016 // Last thing to check since it should be "underneath" everything,
2017 // although I don't think there's the same kind of overlap that
2018 // there was for LoopWidget.
2019 if (this.pDot !== null)
2020 {
2021 // See whether the user clicked on or near the dot. He must click
2022 // on the dot, not at some random point along the bar.
2023 WidgetManager.bogusCtx.lineWidth = 2;
2024 let isin = WidgetManager.bogusCtx.isPointInStroke(this.pDot,x,y);
2025 if (isin === false)
2026 isin = WidgetManager.bogusCtx.isPointInPath(this.pDot,x,y);
2027
2028 if (isin === true)
2029 {
2030 this.sDot = true;
2031
2032 // Move the dot (slightly) so that it is centered at (x,y).
2033 // We don't actually "move the dot;" instead we adjust
2034 // this.curStep to put the dot where we want it. That is, we
2035 // invert g(s) = w (1-1/a^s). See the discussion, in register(),
2036 // of this function. We have
2037 // x = w (1 - 1/a^s)
2038 // a^s = w / (w - x)
2039 // s = log_a [ w / (w - x) ]
2040 // And recall that log_a (z) = ln(z) / ln(a).
2041 let ratio = this.barLength / (this.barLength - x);
2042 let s = Math.log(ratio) / Math.log(this.decay);
2043 if (s < 0)
2044 s = 0;
2045 this.curStep = s;
2046
2047 WidgetManager.mouseOwner = this;
2048
2049 renderFrame(this);
2050
2051 return true;
2052 }
2053 }
2054
2055 return false;
2056 }
2057
2058 mouseMove( x : number , y : number ) : void {
2059
2060 // As above.
2061 if (this.hide === true)
2062 return;
2063
2064 x -= this.widgetX;
2065 y -= this.widgetY;
2066 x /= this.scale;
2067 y /= this.scale;
2068
2069 WidgetManager.bogusCtx.resetTransform();
2070
2071 if (this.sDot === true)
2072 {
2073 // What I will do it check that the mouse is "close enough" to the
2074 // bar, but it can be a long ways away.
2075 WidgetManager.bogusCtx.lineWidth = 20;
2076 let isin = WidgetManager.bogusCtx.isPointInStroke(this.pBar !,x,y);
2077
2078 if (isin == false)
2079 return;
2080
2081 let ratio = this.barLength / (this.barLength - x);
2082 let s = Math.log(ratio) / Math.log(this.decay);
2083 if (s < 0)
2084 s = 0;
2085 this.curStep = s;
2086
2087 // The appearance of the widget may have changed.
2088 renderFrame(this);
2089 }
2090
2091 // BUG: I might (?) want colors to change based on what the mouse
2092 // is over. See the BUG comment that goes with aRunning, sCircle, etc.,
2093 // at the top of the class.
2094 }
2095
2096 mouseUp( x : number , y : number ) : void {
2097
2098 // As above.
2099 if (this.hide === true)
2100 return;
2101
2102 x -= this.widgetX;
2103 y -= this.widgetY;
2104 x /= this.scale;
2105 y /= this.scale;
2106 WidgetManager.bogusCtx.resetTransform();
2107
2108 // The mouse is up, so nothing can remain selected. In most cases,
2109 // releasing the mouse over the selected item means that something
2110 // must be done since the "button" was properly pressed.
2111 this.sDot = false;
2112
2113 if (this.sFaster === true)
2114 {
2115 let isin = WidgetManager.bogusCtx.isPointInPath(this.pFaster ! ,x,y);
2116 if (isin === true)
2117 {
2118 this.timeStep /= 1.4;
2119 if (this.timeStep < 1)
2120 this.timeStep = 1;
2121
2122 // Stop the animation and restart it at the new speed
2123 if (this.aRunning === true)
2124 clearInterval(this.animID);
2125
2126 this.animID = setInterval(doAnimation,this.timeStep,this);
2127 this.aRunning = true;
2128 }
2129
2130 this.sFaster = false;
2131 }
2132
2133 if (this.sSlower === true)
2134 {
2135 // Just as above, but make it go slower.
2136 let isin = WidgetManager.bogusCtx.isPointInPath(this.pSlower ! ,x,y);
2137 if (isin === true)
2138 {
2139 this.timeStep *= 1.4;
2140
2141 // More than a second per frame is silly.
2142 if (this.timeStep > 1000)
2143 this.timeStep = 1000;
2144
2145 if (this.aRunning === true)
2146 clearInterval(this.animID);
2147
2148 this.animID = setInterval(doAnimation,this.timeStep,this);
2149 this.aRunning = true;
2150 }
2151
2152 this.sSlower = false;
2153 }
2154
2155 if (this.sPauseRun)
2156 {
2157 // Did they *release* the mouse over the pause/run area?
2158 let isin = WidgetManager.bogusCtx.isPointInPath(this.pPauseRun ! ,x,y);
2159 if (isin === true)
2160 {
2161 // Start/stop the animation.
2162 if (this.aRunning === true)
2163 // Currently running. Pause it.
2164 clearInterval(this.animID);
2165 else
2166 // Currently paused. Restart it.
2167 this.animID = setInterval(doAnimation,this.timeStep,this);
2168
2169 // Change the pause/run icon too.
2170 if (this.aRunning === true)
2171 this.aRunning = false;
2172 else
2173 this.aRunning = true;
2174 }
2175
2176 this.sPauseRun = false;
2177 }
2178
2179 if (this.sUpStep === true)
2180 {
2181 // Make the number of time increments per frame larger.
2182 let isin = WidgetManager.bogusCtx.isPointInPath(this.pUpStep ! ,x,y);
2183 if (isin === true)
2184 {
2185 // Use a smaller ratio here. Conceptually, it seems like
2186 // this should be an integer, but it really doesn't have to be.
2187 // Unlike LoopWidget, there's no upper limit on the number
2188 // of steps per frame.
2189 this.stepsPerFrame *= 1.25;
2190 }
2191
2192 this.sUpStep = false;
2193 }
2194
2195 if (this.sDownStep === true)
2196 {
2197 // As above.
2198 let isin = WidgetManager.bogusCtx.isPointInPath(this.pDownStep ! ,x,y);
2199 if (isin === true)
2200 this.stepsPerFrame /= 1.25;
2201
2202 this.sDownStep = false;
2203 }
2204
2205 // The appearance of the widget may have changed.
2206 renderFrame(this);
2207 }
2208 }
2209
2210
2211 // This is to allow dragging points around. After the much more complicated
2212 // animation widgets, this is a lot easier. One difference is that dots
2213 // are not drawn automatically; the user must call the widget's draw()
2214 // method. This is because the order of drawing may matter -- what should
2215 // be on top?
2216 //
2217 // At one point, this was more flexible, but -- see DraggableDrawWidget below
2218 // -- it seems better to keep this widget simple (just dots).
2219
2220 class DraggableDotWidget extends Widget {
2221
2222 // When things are "selected," draw them in this color.
2223 static sColor = "blue";
2224
2225 // The clickable area for the dot, and whether it is selected.
2226 // pDot : Path2D | null = null;
2227 pDot : FPath | null = null;
2228 selected = false;
2229
2230 // The default radius of a dot.
2231 dotRadius = 3.0;
2232
2233
2234 static register(ctx : CanvasRenderingContext2D , x : number , y : number ,
2235 name : string ) : DraggableDotWidget {
2236
2237 // As with other widgets. Note that there is no scale since it doesn't
2238 // make sense here.
2239 let type = "DraggableDotWidget";
2240 let caller = getCaller();
2241 let w = <DraggableDotWidget> WidgetManager.knownWidget(caller,type,name);
2242
2243 if (w != null)
2244 {
2245 return w;
2246 }
2247
2248 // Got here, so this widget is not already known, and must be created.
2249 // The 'false' here means that we always assume the dot is visible. Leting
2250 // this be invisible would be pointless, although it is hidable by
2251 // directly changing the Widget.hide field.
2252 w = new DraggableDotWidget(caller,type,x,y,1.0,false,name);
2253
2254 // Note the existence of this widget for the future.
2255 WidgetManager.register(w);
2256
2257 // Note that we do *not* draw this widget here.
2258
2259 return w;
2260 }
2261
2262 draw(ctx : CanvasRenderingContext2D ) : void {
2263
2264 // Because these widgets might be drawn for tikz output, this uses
2265 // FPath instead of Path2D.
2266 //
2267 // BUG: As a rule, I don't think people will want most widgets (like
2268 // LoopWidget) to be drawn to the paper version, but I suppose it should
2269 // be possible. *I* would like it for documentation purposes.
2270
2271 if (this.hide === true)
2272 return;
2273
2274 // Adjusting the coordinates this way feels a little weird, but it's
2275 // how the other widgets work, and it's actually easier.
2276 let saveT = ctx.getTransform();
2277 ctx.translate(this.widgetX,this.widgetY);
2278 ctx.scale(this.scale,this.scale);
2279
2280 // BUG: Somehow, sometimes using FPath puts hair on these dots??
2281 // It looks like it happens where the segments meet. There's probably
2282 // some algebra mistake. Either that or the JS implementation of
2283 // bezier curves sucks. For now, I do not use bezier curves, and
2284 // leave it as an ellipse internally.
2285 let p = new FPath();
2286 //let p = new Path2D();
2287
2288 let r = this.dotRadius;
2289
2290 p.ellipse(0,0,r,r,0,0,2*Math.PI,true);
2291
2292 //this.pDot = new Path2D(p);
2293 // this.pDot = new FPath(p);
2294 this.pDot = p;
2295
2296 if (this.selected === true)
2297 ctx.fillStyle = DraggableDotWidget.sColor;
2298 else
2299 ctx.fillStyle = "red";
2300
2301 ctx.fill(p);
2302
2303 ctx.setTransform(saveT);
2304 }
2305
2306 mouseDown(x: number , y : number ) : boolean {
2307
2308 if (this.hide === true)
2309 return false;
2310
2311 // Adjust coordinates relative to what the draw() methods uses.
2312 x -= this.widgetX;
2313 y -= this.widgetY;
2314 x /= this.scale;
2315 y /= this.scale;
2316
2317 // The widget also has a scale, which must be taken into account.
2318 WidgetManager.bogusCtx.resetTransform();
2319
2320 if (this.pDot !== null)
2321 {
2322 let isin = WidgetManager.bogusCtx.isPointInPath(this.pDot,x,y);
2323 if (isin === true)
2324 {
2325 this.selected = true;
2326 WidgetManager.mouseOwner = this;
2327 renderFrame(this);
2328 return true;
2329 }
2330 }
2331
2332 return false;
2333 }
2334
2335 mouseMove(x : number , y : number ) : void {
2336
2337 // As above.
2338 if (this.hide === true)
2339 return;
2340
2341 // Restrict to be within the figure area, at the least.
2342 // By default (the code here, not this.drawSelFcn, whatever that might
2343 // do), the dot doesn't get "lost," but it can be drawn partially outside
2344 // the figure proper, leaving "crumbs" that aren't erased until you
2345 // scroll the page.
2346 let wh = getFigureRect(this);
2347
2348 // Rrestrict to the entire figure rectangle, tightened up a bit.
2349 wh.w -= 2 * this.dotRadius;
2350 wh.ha -= 2 * this.dotRadius;
2351 wh.hb -= 2 * this.dotRadius;
2352
2353 // Note the minus with hb. The "height below" is a postive value, but
2354 // we are comparing to a potentially negative y.
2355 if (x <= this.dotRadius) return;
2356 if (x >= wh.w) return;
2357 if (y <= -wh.hb) return;
2358 if (y >= wh.ha) return;
2359
2360 if (this.selected === true)
2361 {
2362 this.widgetX = x;
2363 this.widgetY = y;
2364
2365 renderFrame(this);
2366 }
2367 }
2368
2369 mouseUp( x : number , y : number ) : void {
2370
2371 if (this.hide === true)
2372 return;
2373
2374 // This is more round-about because of the possibility that the
2375 // mouse-up occured outside the figure area. We need to reach
2376 // the renderFrame() line whatever happens.
2377 if (this.selected === true)
2378 {
2379 this.selected = false;
2380
2381 let wh = getFigureRect(this);
2382
2383 wh.w -= 2 * this.dotRadius;
2384 wh.ha -= 2 * this.dotRadius;
2385 wh.hb -= 2 * this.dotRadius;
2386
2387 // Note the minus with hb. The "height below" is a postive value, but
2388 // we are comparing to a potentially negative y.
2389 if ((x > this.dotRadius) && (x < wh.w) &&
2390 // (y > this.dotRadius) && (y < wh.h))
2391 (y > -wh.hb) && (y < wh.ha))
2392 {
2393 this.widgetX = x;
2394 this.widgetY = y;
2395 }
2396
2397 renderFrame(this);
2398 }
2399 }
2400 }
2401
2402
2403 // This is almost idential to DraggableDotWidget, except that
2404 // there is no default drawing behavior. The user must provide it.
2405 //
2406 // Maybe...
2407 // * The user might want dots to be drawn in different ways, like a solid
2408 // circle, an open circle with or without a fill of some other color, or
2409 // even a square "dot."
2410 // * The motion of the point, when dragging, needs to be restricted to a
2411 // limited path or region. By default, the point is limited to the entire
2412 // figure area, but that may not suffice.
2413 // * To address the two previous points, register() takes functions
2414 // for drawing the "dot" (which need not be a dot at all), depending
2415 // on whether the dot is to be drawn in selected form or unselected form.
2416
2417 type SimpleDrawFunction = (ctx : CanvasRenderingContext2D) => FPath;
2418 type AcceptedDrawLocationFunction = (x : number, y : number, w : number ,
2419 ha : number , hb : number) => boolean;
2420
2421 class DraggableDrawWidget extends Widget {
2422
2423 // When things are "selected," draw them in this color.
2424 static sColor = "blue";
2425
2426 // The clickable area for the "dot" (which could have any shape)
2427 // and whether it is selected.
2428 pDot : FPath | null = null;
2429 selected = false;
2430
2431 // The user must provide these functions.
2432 // Note the litle cheat to make the ts compiler shut its yapper.
2433 drawFcn : SimpleDrawFunction = null as any;
2434 drawSelFcn : SimpleDrawFunction = null as any;
2435 testPosFcn : AcceptedDrawLocationFunction = null as any;
2436
2437
2438 static register(ctx : CanvasRenderingContext2D , x : number , y : number ,
2439 drawFcn : SimpleDrawFunction, drawSelFcn : SimpleDrawFunction,
2440 testPosFcn : AcceptedDrawLocationFunction , name : string ) : DraggableDrawWidget{
2441
2442 // The drawFcn should be defined to draw whatevever it wants.
2443 // It should take the ctx as the sole argument, and return a path
2444 // such that a click in the path (using ctx.isPointInPath()).
2445 //
2446 // The drawSelFcn is similar, but is used for drawing when the
2447 // item is selected -- so that the user can change the color or
2448 // whatever.
2449 //
2450 // The testPosFcn receives (x,y) as an argument, along with the (w,h)
2451 // of the figure area (in pdf points) and should return
2452 // true (point is acceptable) or false (not acceptable).
2453
2454 let type = "DraggableDrawWidget";
2455 let caller = getCaller();
2456 let w = <DraggableDrawWidget> WidgetManager.knownWidget(caller,type,name);
2457
2458 if (w != null)
2459 {
2460 return w;
2461 }
2462
2463 // Got here, so this widget is not already known, and must be created.
2464 // The 'false' here means that we always assume the dot is visible. Leting
2465 // this be invisible would be pointless, although it is hidable by
2466 // directly changing the Widget.hide field.
2467 w = new DraggableDrawWidget(caller,type,x,y,1.0,false,name);
2468
2469 w.drawFcn = drawFcn;
2470 w.drawSelFcn = drawSelFcn;
2471 w.testPosFcn = testPosFcn;
2472
2473 // Note the existence of this widget for the future.
2474 WidgetManager.register(w);
2475
2476 return w;
2477 }
2478
2479 draw(ctx : CanvasRenderingContext2D ) : void {
2480
2481 // Because these widgets might be drawn for tikz output, this uses
2482 // FPath instead of Path2D.
2483 //
2484 // BUG: As a rule, I don't think people will want most widgets (like
2485 // LoopWidget) to be drawn to the paper version, but I suppose it should
2486 // be possible. *I* would like it for documentation purposes.
2487 if (this.hide === true)
2488 return;
2489
2490 // Adjusting the coordinates this way feels a little weird, but it's
2491 // how the other widgets work, and it's actually easier.
2492 let saveT = ctx.getTransform();
2493 ctx.translate(this.widgetX,this.widgetY);
2494 ctx.scale(this.scale,this.scale);
2495
2496 if (this.selected === true)
2497 this.pDot = this.drawSelFcn(ctx);
2498 else
2499 this.pDot = this.drawFcn(ctx);
2500
2501 ctx.setTransform(saveT);
2502 }
2503
2504 mouseDown(x: number , y : number ) : boolean {
2505
2506 //console.log("dot down");
2507
2508 if (this.hide === true)
2509 return false;
2510
2511 // Adjust coordinates relative to what the draw() methods uses.
2512 x -= this.widgetX;
2513 y -= this.widgetY;
2514 x /= this.scale;
2515 y /= this.scale;
2516
2517 WidgetManager.bogusCtx.resetTransform();
2518
2519 if (this.pDot !== null)
2520 {
2521 let isin = WidgetManager.bogusCtx.isPointInPath(this.pDot,x,y);
2522 if (isin === true)
2523 {
2524 this.selected = true;
2525 WidgetManager.mouseOwner = this;
2526 renderFrame(this);
2527 return true;
2528 }
2529 }
2530
2531 return false;
2532 }
2533
2534 mouseMove(x : number , y : number ) : void {
2535
2536 // As above.
2537 if (this.hide === true)
2538 return;
2539
2540 // Restrict to be within the figure area, at the least.
2541 // By default (the code here, not this.drawSelFcn, whatever that might
2542 // do), the dot doesn't get "lost," but it can be drawn partially outside
2543 // the figure proper, leaving "crumbs" that aren't erased until you
2544 // scroll the page.
2545 let wh = getFigureRect(this);
2546
2547 if (this.testPosFcn(x,y,wh.w,wh.ha,wh.hb) === false)
2548 return;
2549
2550 if (this.selected === true)
2551 {
2552 this.widgetX = x;
2553 this.widgetY = y;
2554
2555 renderFrame(this);
2556 }
2557 }
2558
2559 mouseUp( x : number , y : number ) : void {
2560
2561 if (this.hide === true)
2562 return;
2563
2564 // This is more round-about because of the possibility that the
2565 // mouse-up occured outside the figure area. We need to reach
2566 // the renderFrame() line whatever happens.
2567 if (this.selected === true)
2568 {
2569 this.selected = false;
2570
2571 let wh = getFigureRect(this);
2572
2573 if (this.testPosFcn(x,y,wh.w,wh.ha,wh.hb) === true)
2574 {
2575 this.widgetX = x;
2576 this.widgetY = y;
2577 }
2578
2579 renderFrame(this);
2580 }
2581 }
2582
2583 }
2584
2585
2586 // A numerical value widget. This uses an HTML <input type = "number">
2587 // thing by putting it on top of the canvas. Using HTML this way is not the
2588 // direction I want to go, but I do want to see if it's feasible and what's
2589 // involved. Certain widgets that already exist in HTML are probably not
2590 // worth building from scratch as "pure canvas" widgets. Also, this
2591 // allows me to delay dealing with keyboard events.
2592 //
2593 // The idea is to put the HTML widget on top of the canvas, with absolute
2594 // placement.
2595 //
2596 // NOTE: Firefox generates a warning about "ansynchronous panning." Somehow
2597 // it sees that I'm doing something tricky and warns about it. As far as I
2598 // can tell, I'm not doing anything likely to be deprecated or problematic
2599 // in the future. Edge doesn't complain.
2600
2601 class NumberInputWidget extends Widget {
2602
2603 // An HTML <input type = "number"> thing. This is the HTML DOM element,
2604 // like from document.getElementById() or createElement("input").
2605 theWidget : HTMLInputElement | null = null;
2606
2607
2608 static register( ctx : CanvasRenderingContext2D , x : number , y : number ,
2609 v : number , name : string ) : NumberInputWidget {
2610
2611 // Even fewer arguments than usual.
2612 // v = initial value;
2613 let type = "NumberInputWidget";
2614 let caller = getCaller();
2615 let w = <NumberInputWidget> WidgetManager.knownWidget(caller,type,name);
2616
2617 if (w != null)
2618 {
2619 w.draw(ctx);
2620 return w;
2621 }
2622
2623 // Got here, so this widget is not already known, and must be created.
2624 w = new NumberInputWidget(caller,type,x,y,1.0,false,name);
2625
2626 // Note the existence of this widget for the future.
2627 WidgetManager.register(w);
2628
2629 // The usual syntax for this within HTML is
2630 // <input type="number" id="something" name="whatever" min="10" max="100">
2631 // There are some other possible settings too. See
2632 // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
2633 //
2634 // BUG: There's some funny business here that I don't like at all.
2635 // These DOM elements are placed relative to the body as a whole,
2636 // not the canvas. So, I need to know where the figure containing
2637 // this widget falls on the entire document. The body height is adjusted
2638 // when I tweak the scroll bars (mainbody.style.height and width),
2639 // and the widget needs to be placed relative to that.
2640 //
2641 // As a result, every time the user zooms (or resizes the window),
2642 // every widget placed in the DOM this way needs to be repositioned.
2643 // One reasonable way to deal with that is to recalculate the position
2644 // every time draw() is called.
2645 //
2646 // So this isn't really a BUG; it works as intended. But using
2647 // HTML this way is an entirely different (and unpleasant) approach.
2648
2649 w.theWidget = document.createElement("input");
2650 w.theWidget.setAttribute("type","number");
2651 w.theWidget.value = v.toString();
2652
2653 w.theWidget.style.position = "absolute";
2654 w.theWidget.style.display = "block";
2655 w.theWidget.style.left = 400+"px";
2656 w.theWidget.style.top = 900+"px";
2657 w.theWidget.style.width = 50+"px";
2658 w.theWidget.style.height = 10+"px";
2659 w.theWidget.style.zIndex = "99";
2660
2661 document.body.appendChild(w.theWidget);
2662
2663 // The owner will want to redraw it's figure when this changes.
2664 w.theWidget.onchange = function() {
2665
2666 // console.log("change");
2667
2668 let myFunc : AugmentedDrawingFunction = getAugmentedFunction( w.owner );
2669 let fpc : FigurePanel = myFunc.figurePanelClass !;
2670 fpc.render( );
2671 };
2672
2673 // Before returning the widget, it must be drawn.
2674 w.draw(ctx);
2675
2676 return w;
2677 }
2678
2679 getValue() {
2680
2681 // Return the numerical value.
2682 //
2683 // BUG: This seems to return a string -- whatever is in the field.
2684 // The caller will typically need to do parseInt() or parseFloat()
2685 // on the result. If this widget were better, then it would know
2686 // what it's supposed to return and limit the possible things it can hold.
2687
2688 // BUG: I should probably have getter functions for everything in
2689 // all widgets instead of having the user access fields directly.
2690 // So, define LoopWidget.getCurStep(), etc.
2691 // It doesn't *really* matter, but it makes it clearer to the user
2692 // what he's supposed to have access to.
2693 return this.theWidget ! .value;
2694 }
2695
2696 draw(ctx : CanvasRenderingContext2D ) : void {
2697
2698 // This widget is really an HTML DOM element, so this function doesn't
2699 // actually draw the widget. It repositions the element in the DOM.
2700 // See the discussion in register().
2701
2702 // BUG: make accessing this information a function, like I did
2703 // for getFigureRect().
2704
2705 let myFunc : AugmentedDrawingFunction = getAugmentedFunction( this.owner );
2706 let fpc : FigurePanel = myFunc.figurePanelClass !;
2707 let totalV = fpc.totalV;
2708
2709 // The vertical position is relatively easy, but the horizontal position
2710 // requires a calculation similar to fullRender() since the page
2711 // is centered. Also, the vertical position must be given in LH coordinates
2712 // relative to the entire document.
2713 // BUG: Make this calculation a function used in main.js too.
2714 // Can I combine with what's done for mouse events there too?
2715 // In fact, this is more like the mouse calculation than like fullRender().
2716 let vpos = fpc.totalV + fpc.h - this.widgetY;
2717 // let vpos = totalV + this.widgetY;
2718
2719
2720 // BUG: I don't like reaching into the DOM this way to get the canvas,
2721 // but what is the alternative?
2722 let hpos = this.widgetX;
2723 let canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
2724 let visWidth = document.documentElement.clientWidth;
2725 let totWidth = FullPanel.getFullWidth();
2726
2727 if (visWidth > totWidth)
2728 {
2729 // No horizontal scroll bar. Center it.
2730 let canvasCenter = canvas.width / 2;
2731 let docCenter = FullPanel.getFullWidth() / 2;
2732 canvasCenter = canvasCenter / PDFDocument.getZoom();
2733
2734 hpos = hpos + (canvasCenter - docCenter);
2735 }
2736 else
2737 {
2738 // Shift according to the horizontal scroll bar.
2739 hpos = hpos - window.scrollX;
2740 }
2741
2742 hpos += fpc.margin;
2743
2744 //console.log("wid at " +hpos+ " " +vpos);
2745
2746 // Don't forget the stupid "px"!
2747 this.theWidget ! .style.top = vpos +"px";
2748 this.theWidget ! .style.left = hpos +"px";
2749 }
2750 }
2751
2752 // Another DOM-based widget. A simple button.
2753
2754 class ButtonWidget extends Widget {
2755
2756 // An HTML <input type = "button"> thing.
2757 theWidget : HTMLButtonElement | null = null;
2758
2759 // Sometimes you want to treat the button as a boolean
2760 // Each time the button is clicked, this toggles.
2761 clickState = false;
2762
2763 // And this is set to true whenever the button is clicked.
2764 resetState = false;
2765
2766 static register(ctx : CanvasRenderingContext2D , x : number , y : number ,
2767 text : string , name : string ) : Widget {
2768
2769 // Even fewer arguments than usual.
2770 let type = "ButtonWidget";
2771 let caller = getCaller();
2772 let w = <ButtonWidget> WidgetManager.knownWidget(caller,type,name);
2773
2774 if (w != null)
2775 {
2776 w.draw(ctx);
2777 return w;
2778 }
2779
2780 // Got here, so this widget is not already known, and must be created.
2781 w = new ButtonWidget(caller,type,x,y,1.0,false,name);
2782
2783 // Note the existence of this widget for the future.
2784 WidgetManager.register(w);
2785
2786 // The usual syntax for this within HTML is
2787 // <button type="button" id="something" name="whatever">
2788 //
2789 // BUG: There's some funny business here that I don't like at all.
2790 // These DOM elements are placed relative to the body as a whole,
2791 // not the canvas. So, I need to know where the figure containing
2792 // this widget falls on the entire document. The body height is adjusted
2793 // when I tweak the scroll bars (mainbody.style.height and width),
2794 // and the widget needs to be placed relative to that.
2795 //
2796 // As a result, every time the user zooms (or resizes the window),
2797 // every widget placed in the DOM this way needs to be repositioned.
2798 // One reasonable way to deal with that is to recalculate the position
2799 // every time draw() is called.
2800 //
2801 // So this isn't really a BUG; it works as intended. But using
2802 // HTML this way is an entirely different (and unpleasant) approach.
2803
2804 w.theWidget = document.createElement("button");
2805 w.theWidget.setAttribute("type","button");
2806 w.theWidget.style.fontSize = "10px";
2807 w.theWidget.textContent = text;
2808
2809 w.theWidget.style.position = "absolute";
2810 w.theWidget.style.display = "block";
2811 w.theWidget.style.left = 400+"px";
2812 w.theWidget.style.top = 900+"px";
2813 //w.theWidget.style.width = 100+"px"; // Width automatic, based on text.
2814 w.theWidget.style.height = 18+"px";
2815 w.theWidget.style.zIndex = "99";
2816
2817 document.body.appendChild(w.theWidget);
2818
2819 // Need to hear about clicks....
2820 // BUG: I would have thought that this would work, but I don't think that
2821 // the doClick() method is seeing the correct class instance or something.
2822 //w.theWidget.addEventListener('click',w.doClick,false);
2823
2824 // Instead, define the action here.
2825 w.theWidget.addEventListener('click',() => {
2826
2827 if (w.clickState === false)
2828 w.clickState = true;
2829 else
2830 {
2831 w.clickState = false;
2832 w.resetState = true;
2833 }
2834
2835
2836 // If the figure is part of an animation, then it will be drawn taking
2837 // into account this click in the next frame. If the figure is *not*
2838 // an animation, then we need to refresh.
2839 let myFunc : AugmentedDrawingFunction = getAugmentedFunction( w.owner );
2840 let fpc : FigurePanel = myFunc.figurePanelClass !;
2841 fpc.render();
2842 },false);
2843
2844 // Before returning the widget, it must be drawn.
2845 w.draw(ctx);
2846
2847 return w;
2848 }
2849
2850 doClick() {
2851 // BUG: This doesn't work. See above.
2852 if (this.clickState === false)
2853 this.clickState = true;
2854 else
2855 this.clickState = false;
2856
2857 //console.log("swapped click");
2858 }
2859
2860 draw( ctx : CanvasRenderingContext2D ) : void {
2861
2862 // This widget is really an HTML DOM element, so this function doesn't
2863 // actually draw the widget. It repositions the element in the DOM.
2864 // See the discussion in register().
2865
2866 let myFunc : AugmentedDrawingFunction = getAugmentedFunction( this.owner );
2867 let fpc : FigurePanel = myFunc.figurePanelClass !;
2868
2869 // The horizontal position requires a calculation similar to fullRender()
2870 // since the page is centered and the vertical position must be given
2871 // in LH coordinates relative to the entire document.
2872 // BUG: Make this calculation a function used in main.js too.
2873 // Can I combine with what's done for mouse events there too?
2874 // In fact, this is more like the mouse calculation than like fullRender().
2875 let vpos = fpc.totalV + fpc.h - this.widgetY;
2876
2877 let hpos = this.widgetX;
2878 // BUG: Again, with the DOM access.
2879 let canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
2880 let visWidth = document.documentElement.clientWidth;
2881 let totWidth = FullPanel.getFullWidth();
2882
2883 if (visWidth > totWidth)
2884 {
2885 // No horizontal scroll bar. Center it.
2886 let canvasCenter = canvas.width / 2;
2887 let docCenter = FullPanel.getFullWidth() / 2;
2888 canvasCenter = canvasCenter / PDFDocument.getZoom();
2889
2890 hpos = hpos + (canvasCenter - docCenter);
2891 }
2892 else
2893 {
2894 // Shift according to the horizontal scroll bar.
2895 hpos = hpos - window.scrollX;
2896 }
2897
2898 hpos += fpc.margin;
2899
2900 // It seems that these must be placed using style.top, not style.bottom.
2901 // The clientHeight seems to be the height of the text in the button,
2902 // which style.height is the actually button. Don't forget the stupid "px"!
2903 let w : HTMLButtonElement = this.theWidget ! ;
2904 w.style.top = (vpos - parseInt(w.style.height , 10) ) +"px";
2905 w.style.left = hpos +"px";
2906 }
2907 }
2908