Debian Codegraph @

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

raw
1 /*
2
3 Main entry point for all the js code behind the browser interface.
4
5 This has the initialization code, to load the pdf and the data specifying
6 how figures are drawn and laid out, plus the top-level stuff to direct
7 events to the proper place for handling.
8
9 The same code is used for developing the document, and for serving it
10 from a public-facing website, with a few changes. Look for "PUBLIC FACING"
11 annotations. Note also that it would be possible to strip considerably
12 more code away for the public-facing version, but there's no pressing
13 reason to do it -- the savings would be tiny -- and it could lead to
14 an error of some kind due to unforeseen dependencies on the deleted
15 code.
16
17 */
18
19
20 // In rare cases, I need to know the browser. Note it first, before doing
21 // anything else. This userAgent is a longish bit of blather specifying
22 // the browser, and the easiest way to deal with it is to check whether
23 // certain strings appear.
24
25 var theBrowser = function() {
26
27 let blah = navigator.userAgent;
28
29 if (blah.indexOf("Firefox") > -1)
30 return "Firefox";
31
32 // MS Edge is also "Chrome," at least for my purposes.
33 if (blah.indexOf("Chrome") > -1)
34 return "Chrome";
35
36 // Assume "Chrome" as the default.
37 console.log("MAKING DEFAULT 'CHROME' ASSUMPTION ABOUT THE BROWSWER!!!");
38 return "Chrome";
39 }();
40
41
42 // JS has poor to non-existent facilities for dealing with thread scheduling.
43 // In a lot of JS code that doesn't matter, but the pdf.js library, on which
44 // this entire thing rests, makes heavy use of Promises and workers. Fortunately,
45 // there's a simple way of managing this.
46 //
47 // To use this, the caller says
48 // await sleep(100);
49 // and the "await" is crucial. This works because setTimeout() takes a
50 // function to run, and some amount of time to wait before running that
51 // function.
52 //
53 // This isn't a satisfying solution because it requires "await."
54 // For that reason it can only be used in async functions.
55
56 function sleep(ms : number) : Promise<unknown> {
57
58 // ms is milliseconds, not microseconds.
59 return new Promise(resolve => setTimeout(resolve,ms));
60 }
61
62
63 // Some semi-bogus stuff to quiet the ts compiler...
64
65 // This makes the external library known to tsc.
66 declare var pdfjsLib : any;
67
68 // And this provides the properties known to pdfjs that belong to a pdf.
69 // I had hoped to define a blank type, and have done with it, but we need
70 // access to certain fields. This provides the type information that
71 // pdf.js lacks -- or at least the minimal information that I need.
72 type LoadedPDF = {
73 numPages : number;
74 getPage : (n : number) => Promise<any>;
75 };
76
77 // This is less bogus. It's the type of the functions called to draw the figures.
78 // These functions have an added property that points to the
79 // correct FigurePanel widget. See the layout code.
80 // Declaring these types serves to warn the programmer what's ahead. It also
81 // provides tsc with the information it needs to prevent certain mistakes.
82 type BaseDrawingFunction = (ctx : CanvasRenderingContext2D | CTX) => void;
83 type AugmentedDrawingFunction = BaseDrawingFunction & { figurePanelClass : FigurePanel | null; };
84
85
86 function getAugmentedFunction(fcnName : string ) : AugmentedDrawingFunction {
87
88 // This converts from a function name, as specified by the user in their latex
89 // document to the internally more useful AugmentedDrawingFunction. Doing this
90 // kind of conversion feels icky, but any alternative I've come up with requires
91 // that the person using FigPut know more than the absolute minimum about what's
92 // behind the curtain.
93 //
94 // References to these functions come into the program at two points. First, when
95 // the document is loaded, a list of the relevant drawing functions is provided
96 // by latex. Second, when the user creates widgets within his drawings, these
97 // widgets must belong to a particular drawing and the function (or its name, as
98 // a string) is used as the key under which the widget is filed.
99
100 // BUG: This double-cast and use of 'any' is horrible, but is there
101 // anything better?
102 return <AugmentedDrawingFunction> <unknown> window[ fcnName as any ];
103 }
104
105
106 // Data related to the document pages and figures. Each page
107 // has one of these in PDFDocument.pageSpecs. This is all
108 // static data once the document has been loaded.
109
110 // BUG: Should this be a type? An interface?
111
112 class PageData {
113
114 // Note that pageHeight is the height of a *printed* page. If the page
115 // has a figure whose height is different than the deleted height, then
116 // the page height, as rendered, will be different than this value.
117 // Also, the margins and textWidth are only valid when there is a
118 // figure to render since they come from figures.aux.
119 // For reference, 8.5 x 11 inch paper is 612 x 792 pts;
120 // A4 paper is 8.27 x 11.69 inch or 595.44 x 841.68 pts.
121 // However, it seems that latex sometimes produces slightly different
122 // dimensions of what must be A4 paper.
123 pageHeight : number = 0;
124 pageWidth : number = 0;
125 leftMargin : number = 0;
126 rightMargin : number = 0;
127 textWidth : number = 0;
128
129 // These arrays have one entry for each interactive figure on the page.
130 // insertPoint is the position, from the top, at which the figure is
131 // inserted. deleteHeight is how much of the latex doc is omitted, and
132 // above/belowHeight is how much room to leave in the browser window for
133 // the figure. name is the name of the function to call to draw the
134 // figure, done is whether to generate new tikz
135 insertPoint : number[] = [];
136 deleteHeight : number[] = [];
137 aboveHeight : number[] = [];
138 belowHeight : number[] = [];
139 name : string[] = [];
140 done : boolean[] = [];
141
142 // For each figure, there is a corresponding function (that will be
143 // augmented with a drawing target). These values make the name values
144 // given above conceptually redundant.
145 drawFcn : AugmentedDrawingFunction[] = [];
146 }
147
148
149 // Everything related to the pdf document is here. Its main purpose is
150 // to handle off-screen rendering. It's all static since there can only be
151 // one pdf open at a time. It does include data about how to lay out the
152 // figures, but none of the code that does it.
153 //
154 // I tried making this a module, but really no advantage over a class,
155 // and definitely some disadvantages.
156
157 class PDFDocument {
158
159 // The document, as returned by pdfjsLib.getDocument.
160 private static pdf : LoadedPDF;
161
162 // Total number of pages in the above document.
163 public static numberOfPages = 0;
164
165 // This is the scale at which to to render the pages offscreen. Setting
166 // this equal to 1 means that each px of the off-screen canvas is 1 pdf
167 // point.
168 private static zoom : number = 1;
169
170 // Information about the layout, one for each page.
171 public static pageSpecs : PageData[] = [];
172
173 // The fields below are a temporary buffer of pages rendered offscreen.
174 // This speeds up the process so that we aren't re-rendering pages.
175 // My original intent was for these arrays to have no more than
176 // pageBufSize entries, but the way async/promise works makes that
177 // difficult (impossible?). I want render() to render a given page
178 // to an offscreen canvas and store that canvas here, which means
179 // that all these calls to render() share the variables below.
180 // Each call to render() is, unavoidably, in a different thread, and
181 // that means that they are all trying to manipulate these varaibles
182 // in an order that is unpredictable. The only way that I can see to
183 // make this happen in a predicatable way is for each page to have
184 // its own canvas. It's OK for render() to put things into its designated
185 // spot in an array, but it can't touch anything that some other invocation
186 // of render might touch.
187 //
188 // This is wasteful, but I see no other way to do it without using
189 // a mutex. It's not that bad since we're talking about a few bytes for
190 // every page, but still annoying.
191 //
192 // Aside: JS does have the Atomics object, as of ECMA 2017, and it
193 // might (?) be possible to use that somehow as a way to synchronize
194 // threads, but I'd rather not mess with it.
195
196
197 // The total number of pages that may be held. This needs to be at least
198 // as large as the number of pages that may be visible at one time if you
199 // zoom all the way out, plus a couple extra due to possible problems
200 // resulting from race conditions that I can't (?) avoid.
201 private static pageBufSize : number = 6;
202
203 // This holds a copy of page to be copied to the screen. Every page has
204 // its own entry, although all but (at most) pageBufSize will be null.
205 private static theCanvases : (HTMLCanvasElement | null)[] = [];
206
207 // The renderCount is how many times we've rendered any page. It's used like
208 // a time since I have no confidence in window.performance.now, which is
209 // supposed to return the current time in nanoseconds. Every time a page
210 // is asked to be rendered, this value increments, and is stored in
211 // pageAge[i], where i is the index of the page rendered. It may not
212 // actually be rendered if it would be a re-render, but the time is updated.
213 // We need this to flush older pages from the buffer when there are too many.
214 //
215 // NOTE: This variable is shared by the various invocations of render()
216 // and something like
217 // ++renderCount
218 // is not an atomic operation. The way I am using this, the fact that
219 // the value of renderCount may be incorrect isn't a disaster. It can
220 // only be wrong by a few steps. This is why pageBufSize is bumped up to be a
221 // little larger than strictly necessary. Worst case, things are re-rendered
222 // and you waste some CPU.
223 private static renderCount : number = 0;
224
225 // One of these for each page, indexed by page number. Holds the value
226 // or renderCount at the time when the page was rendered (or re-rendered).
227 private static pageAge : number[] = [];
228
229
230 public static async setPDF(thePDF : LoadedPDF) {
231
232 // Take the newly loaded pdf and note some of it's stats.
233 // Once this is loaded, thePDF never needs to be accessed again
234 // from outside this class.
235 this.pdf = thePDF;
236
237 this.numberOfPages = thePDF.numPages;
238
239 // It seems that pdfjs counts pages from one, not zero.
240 for (let i = 1; i <= this.numberOfPages; i++)
241 {
242 await thePDF.getPage(i).then(function(page) {
243
244 // Note the i-1 here since I want arrays to start at zero.
245 PDFDocument.pageSpecs[i-1] = new PageData();
246 PDFDocument.pageSpecs[i-1].pageWidth = page.view[2];
247 PDFDocument.pageSpecs[i-1].pageHeight = page.view[3];
248
249 // Make sure that the shared buffer arrays are all fully allocated.
250 PDFDocument.theCanvases[i-1] = null;
251 PDFDocument.pageAge[i-1] = 0;
252 });
253 }
254 }
255
256 public static isLoaded() : boolean {
257 if (this.pdf === null)
258 return false;
259 else
260 return true;
261 }
262
263 public static getZoom() : number {
264 return this.zoom;
265 }
266
267 public static setZoom(z : number) : void {
268
269 this.zoom = z;
270 this.flushBuffer();
271 }
272
273 public static getCanvas(n : number) {
274
275 // Return the canvas for page number n (counting from zero).
276 // This assumes that the canvas is available due to a previous
277 // call to render(n) -- which must have resolved by the time this
278 // method is called.
279
280 // BUG: This shouldn't happen, but maybe I should create a fake
281 // blank canvas anyway.
282 if (this.theCanvases[n] === null)
283 console.log("ERROR! Canvas for page missing: " +n);
284
285 return this.theCanvases[n];
286 }
287
288 public static async render(n : number ) {
289
290 // Render page n offscreen, where the pages are counted from zero.
291
292 // See if the page is already there.
293 if (PDFDocument.theCanvases[n] !== null)
294 return;
295
296 // Note the +1 here since pdf.js counts pages from 1, not zero.
297 let thePage = await PDFDocument.pdf.getPage(n + 1);
298
299 let newCanvas : HTMLCanvasElement = document.createElement('canvas');
300 PDFDocument.theCanvases[n] = newCanvas;
301 PDFDocument.pageAge[n] = PDFDocument.renderCount;
302 ++PDFDocument.renderCount;
303
304 let offctx = newCanvas.getContext('2d');
305 let viewport = thePage.getViewport(PDFDocument.zoom);
306
307 newCanvas.width = viewport.width;
308 newCanvas.height = viewport.height;
309
310 await thePage.render({
311 canvasContext: offctx,
312 viewport: viewport
313 });
314 }
315
316 public static trimBuffer() : void {
317
318 // Call this periodically, like after making a series of calls to
319 // render(), to remove excess canvases from the buffer arrays.
320 // Due to the risk of race conditions -- which I think is minimal --
321 // it's best not to call this until reaching a point at which it
322 // doesn't matter if *all* the offscreen canvases are deleted (although
323 // that outcome would be inefficient). The unlikely possiblitity of
324 // problems due to race conditions is why this is not part of render().
325 let ctot = 0;
326 for (let i = 0; i < PDFDocument.numberOfPages; i++)
327 {
328 if (PDFDocument.theCanvases[i] !== null)
329 ++ctot;
330 }
331
332 // Delete excess offscreen canvases.
333 while (ctot > PDFDocument.pageBufSize)
334 {
335 PDFDocument.removeOldestPage();
336 --ctot;
337 }
338 }
339
340 private static removeOldestPage() : void {
341
342 // Remove the oldest single canvas from this.theCanvases.
343 let oldestIndex = -1;
344 let oldestAge = this.pageAge[0];
345 for (let i = 0; i < this.numberOfPages; i++)
346 {
347 if (this.theCanvases[i] === null)
348 continue;
349
350 if (this.pageAge[i] < oldestAge)
351 {
352 oldestAge= this.pageAge[i];
353 oldestIndex = i;
354 }
355 }
356 this.theCanvases[oldestIndex] = null;
357 }
358
359 public static flushBuffer() : void {
360
361 // Removes all offscreen canvases in the buffer. This is needed, e.g.,
362 // when resizing so that you don't use a canvas of the wrong scale.
363 for (let i = 0; i < this.numberOfPages; i++)
364 this.theCanvases[i] = null;
365 }
366 }
367
368
369 // A class for scheduling event handling.
370 //
371 // Everything is static because there is only one of these for all events.
372 // It is used to mediate the event loop so that everything happens
373 // syncrhonously, even when async functions are involved. It is used for
374 // things like scroll and mouse-down events; it is also used for animations,
375 // which are created by certain widgets.
376 //
377 // The idea is that you call getID() to get your ticket (like at the
378 // butcher's). Then call await waitMyTurn() until the butcher is ready.
379 // The 'await' is crucial! Then call allDone() to thank the butcher and
380 // leave so that he can take the next customer.
381 //
382 // For this to work properly, calls to getID() must be made outside
383 // of async functions. Otherwise the IDs could get out of order.
384 //
385 // BUG: I could use this in a DRY-er way. Define a method called
386 // getInLine() that takes the function to be invoked. Have getInLine()
387 // call getID(), waitMyTurn(), run the job, then call allDone().
388 //
389 // BUG: It may be that someone who is more expert in JS could use
390 // Promises somehow to make this scheme unnecessary. OTOH, this may
391 // be easier to understand and use than something more clever.
392 class Events {
393
394 // A count of events that have come in. Each event gets its own unique
395 // ID by calling getID().
396 private static count : number = 0;
397
398 // The ID number of the event whose handling was most recently completed.
399 private static complete : number = -1;
400
401 public static getID() {
402 let answer = this.count;
403 this.count++;
404 return answer;
405 }
406
407 public static async waitMyTurn(id : number) {
408 while (id !== Events.complete + 1)
409 await sleep(5);
410 }
411
412 public static allDone(id : number) {
413 Events.complete = id;
414 }
415 }
416
417
418 async function doOpenDocument(latexName : string , scrollPos : number ) {
419
420 // Called when the body of the page loads (onload).
421 // latexName is the base of the name of the pdf. Thus, latexName.pdf
422 // is what is to be opened. The scrollPos value is the position on the
423 // page. This is provided by doBeforeUnload(), noted by the server, and
424 // given back in the course of the reload.
425
426 // The "Get TikZ" button is fixed, and it is always on top.
427 // PUBLIC FACING: Comment this block of code out when running serving from a
428 // public-facing website. There's no reason to provide this "Get TikZ" button
429 // and the server won't now how to handle the resulting messages.
430
431 let fmenu = document.createElement("button");
432 fmenu.style.position = "fixed";
433 fmenu.style.display = "block";
434 fmenu.style.left = "0px";
435 fmenu.style.top = "0px";
436 fmenu.style.width = "80px";
437 fmenu.style.height = "18px";
438 fmenu.style.fontSize = "10px";
439 fmenu.textContent = "Get TikZ";
440 fmenu.style.zIndex = "99";
441 fmenu.onclick = doTikzClick;
442 document.body.appendChild(fmenu);
443
444
445 let theCanvas = <HTMLCanvasElement> document.getElementById("pdf_renderer")!;
446 theCanvas.style.position = "fixed";
447
448 // It might happen that the program starts with some level of zoom.
449 PDFDocument.setZoom(window.devicePixelRatio);
450
451 // So that the canvas exactly fills the window.
452 adjustCanvas();
453
454 // Mouse events are registered on the canvas rather than the document
455 // (as is done for resize and scroll), but I'm not sure there's any
456 // practical difference since the canvas is the whole document.
457 // Note that this does *not* listen for onclick events. In a few cases,
458 // they might be a more natural choice (like for buttons), but they make
459 // things like coloring a "halfway clicked" widget difficult.
460 // Note that this does not distinguish between left, right and middle
461 // buttons; a click is a click.
462 // Also, the mouseup listener is registered on the window, not the canvas,
463 // so that we hear about mouse-ups even when they happen outside the
464 // browswer window entirely.
465 theCanvas.addEventListener("mousedown",doMouseDown);
466 theCanvas.addEventListener("mousemove",doMouseMove);
467 theCanvas.addEventListener("mouseup",doMouseUp);
468
469 // I considered registering listeners for mouseenter/mouseleave, but
470 // they're not needed.
471
472 /*
473 BUG: I have not tested this much on touch devices. Everything
474 works fine on some phones, but not on others. It's a hard to imagine
475 people trying to use this on a phone, but I should test on things
476 like iPads.
477 theCanvas.addEventListener("touchstart",doTouchDown);
478 theCanvas.addEventListener("touchend",doTouchUp);
479 theCanvas.addEventListener("touchmove",doTouchMove);
480 */
481
482 // Open the pdf and digest figures.aux.
483 await getDocumentData(latexName);
484
485 // Create the various Panel objects that make up the document as a whole.
486 // This does the "page layout."
487 FullPanel.init(PDFDocument.pageSpecs);
488
489 // Now that page layout is done, set the range for the scroll bars on
490 // the browswer window.
491 adjustScrollBars();
492
493 // When reloading, we don't want things to move back to the top of
494 // the first page.
495 window.scrollTo(0 , scrollPos);
496
497 // Render for the very first time.
498 fullRender();
499 }
500
501 async function getDocumentData(latexName : string) {
502
503 // This opens and digests the data files and the pdf itself.
504 let thePDF : LoadedPDF = await pdfjsLib.getDocument(latexName+ '.pdf');
505 await PDFDocument.setPDF(thePDF);
506
507 // Open and digest figures.aux.
508 let fname = latexName + ".fig.aux";
509
510 // fetch() is the new XMLHttpRequest(), which has been deprecated.
511 // Thanks to Dan Pratt for pointing that out.
512 let fetchPromise = await fetch(fname);
513 let allText = await fetchPromise.text();
514 await getFigureInfo(allText);
515 }
516
517 async function syncLoad(scriptName : string) {
518
519 // Load the script with the given name and append to the DOM, and
520 // don't return until the load is complete. So this should typically
521 // be called with 'await'.
522 //
523 // Thanks to Dan Pratt for this tidy solution. This works because the
524 // promise can't resolve (either way) until appendChild() completes
525 // because you can't resolve or reject until the code is loaded
526 // or fails to load. Note that the 'once' argument means that the function
527 // is called once, then flushed. That's exactly what I want so that they
528 // don't hang around and consume resources.
529 let theCode = document.createElement("script");
530 theCode.type = "application/javascript";
531 theCode.src = scriptName;
532
533 var p = new Promise((resolve, reject) => {
534 theCode.addEventListener("load", resolve, { once: true});
535 theCode.addEventListener("error", reject, { once: true});
536 });
537
538 document.body.appendChild(theCode);
539
540 await p;
541 }
542
543 async function getFigureInfo(textBody : string) {
544
545 // textBody is the complete contents of the .aux file. Parse it and
546 // use the data to fill in PDFDocument.PageSpecs.
547 let lines = textBody.split('\n');
548
549 for (let i = 0; i < lines.length; i++)
550 {
551 if (lines[i].length < 2)
552 // Last line might be blank.
553 break;
554
555 var parts = lines[i].split(' ');
556
557 if (parts[0] === "load")
558 {
559 // Load a single .js file and move on.
560 await syncLoad(parts[1]);
561 continue;
562 }
563
564 var pnum = parseInt(parts[0]);
565 var innerMargin = parseFloat(parts[1]);
566 var outerMargin = parseFloat(parts[2]);
567 var textWidth = parseFloat(parts[3]);
568 var vpos = parseFloat(parts[4]);
569 var hLatex = parseFloat(parts[5]);
570 var hAbove = parseFloat(parts[6]);
571 var hBelow = parseFloat(parts[7]);
572 var name : string = parts[8];
573
574 // Careful: JS weirdness means that Boolean(parts[9]) is ALWAYS true
575 // (unless parts[9] is empty).
576 var done : boolean = (parts[9] === 'true');
577 var externLoad : boolean = (parts[10] === 'true');
578
579 // Page numbers should start at zero (not 1 as reported by latex).
580 pnum -= 1;
581
582 // Load the JS now, if necessary.
583 // NOTE: In earlier versions, up to v23, I looked to either a
584 // .js file or an .fjs file. Individual files are now assumed
585 // to be .fjs files. This is much simpler.
586 if (externLoad === true)
587 await syncLoad(name + ".fjs");
588
589 // NOTE: This assumes that the relevant function has been loaded,
590 // perhaps as an external file from \LoadFigureCode.
591 let augFcn : AugmentedDrawingFunction = getAugmentedFunction( name );
592 if (typeof augFcn === "undefined")
593 alert(name + " not found. Is the function name correct?");
594
595 // Note this for the future.
596 augFcn.figurePanelClass = null;
597 PDFDocument.pageSpecs[pnum].drawFcn.push(augFcn);
598
599 // Copy the remaining fields over.
600
601 // Adjust the vertical position to be given relative to the top
602 // of the page, rather than the bottom.
603 vpos = PDFDocument.pageSpecs[pnum].pageHeight - vpos;
604
605 // If there are multiple figures on a particular page, then this
606 // is redundant, but harmless.
607 if (pnum % 2 === 0)
608 {
609 PDFDocument.pageSpecs[pnum].leftMargin = innerMargin;
610 PDFDocument.pageSpecs[pnum].rightMargin = outerMargin;
611 }
612 else
613 {
614 PDFDocument.pageSpecs[pnum].leftMargin = outerMargin;
615 PDFDocument.pageSpecs[pnum].rightMargin = innerMargin;
616 }
617 PDFDocument.pageSpecs[pnum].textWidth = textWidth;
618
619 // The per-figure data.
620 PDFDocument.pageSpecs[pnum].insertPoint.push(vpos);
621 PDFDocument.pageSpecs[pnum].deleteHeight.push(hLatex);
622 PDFDocument.pageSpecs[pnum].aboveHeight.push(hAbove);
623 PDFDocument.pageSpecs[pnum].belowHeight.push(hBelow);
624 PDFDocument.pageSpecs[pnum].name.push(name);
625 PDFDocument.pageSpecs[pnum].done.push(done);
626 }
627
628 // Make sure that all the figure names are distinct.
629 for (let i = 0; i < PDFDocument.numberOfPages; i++)
630 {
631 // Loop over each figure on the current page.
632 for (let fig = 0; fig < PDFDocument.pageSpecs[i].name.length; fig++)
633 {
634 let curName = PDFDocument.pageSpecs[i].name[fig];
635
636 // See if this name matches a name on any other page/figure.
637 // Consider the current page first.
638 for (let subfig = fig + 1; subfig < PDFDocument.pageSpecs[i].name.length; subfig++)
639 {
640 if (curName === PDFDocument.pageSpecs[i].name[subfig])
641 {
642 alert("The figure name " +curName+ " is used more than once.");
643 throw new Error();
644 }
645 }
646
647 // Continue with all the remaining pages.
648 for (let j = i + 1; j < PDFDocument.numberOfPages; j++)
649 {
650 for (let subfig = 0; subfig < PDFDocument.pageSpecs[j].name.length; subfig++)
651 {
652 if (curName === PDFDocument.pageSpecs[j].name[subfig])
653 {
654 alert("The figure name " +curName+ " is used more than once.");
655 throw new Error();
656 }
657 }
658 }
659 }
660 }
661 }
662
663 function adjustScrollBars() : void {
664
665 // Based on the page size and document length, adjust the range of the
666 // browswer's scroll bars.
667 var body = <HTMLElement> document.getElementById("mainbody");
668
669 // I don't see any way to set the range of the scroll bar directly, so
670 // I'm fooling the browser to think that it has a body of a certain
671 // height, in px, when the body is really no bigger than the visible
672 // area of the window. What I want is a height such that, when the scroll
673 // bar is at the bottom, the lower edge of the last page is barely visible
674 // in the bottom of the window.
675 //
676 // There was some mental debate about whether it's better to let the
677 // bottom of the last page scroll up beyond the bottom of the window, but
678 // this is easier to program, and it's probably more natural for most people.
679 let totHeight = FullPanel.totalHeight();
680 let visHeight = document.documentElement.clientHeight;
681 body.style.height = totHeight + "px";
682
683 // The horizontal scroll bar is expressed in terms of pdf pts. This is
684 // simpler than above since I don't want to be able to scroll so that the
685 // right edge of the document is barely off the window; I want to be able
686 // to scroll just far enough so that the right edge of the document meets
687 // the right edge of the window. The size of the window becomes irrelevant
688 // (i.e., the browser deals with it).
689 // However, we do need to know whether a scroll bar is needed at all,
690 // so we can't totally ignore the visible width.
691 let visWidth = document.documentElement.clientWidth;
692 let totWidth = FullPanel.getFullWidth();
693
694 if (visWidth > totWidth)
695 {
696 // No need for horizontal scroll. It seems like "0px" works, but "0 px"
697 // does not. Maybe the space causes a (silent) parse error?
698 body.style.width = "0px";
699 return;
700 }
701
702 body.style.width = totWidth + "px";
703 }
704
705 function ctxTopLevelAdjust( ) : CanvasRenderingContext2D {
706
707 // Each function should call this before doing any drawing.
708 // Rendering is done relative to the ctx (obviously) with the t-matrix
709 // adjusted accordingly. This brings the t-matrix from being the
710 // identity to being relative to the entire document.
711 //
712 // In earlier versions, the ctx was being passed around and adjusted
713 // as the layout manager descended to a particular portion of the document.
714 // In some ways that is the cleaner and more modular way to do things,
715 // but it can be confusing because the adjustments to the t-matrix aren't
716 // done in a central place.
717 var canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
718 let ctx : CanvasRenderingContext2D = canvas.getContext('2d') ! ;
719
720 ctx.resetTransform();
721
722 // Center the document. Rather than mess with CSS to center the canvas,
723 // leave the canvas at the size of the entire window, and shift the origin
724 // so the document is rendered in the center of the canvas.
725 //
726 // However, if the window is smaller than the document, then we do
727 // NOT want to center the document. If we did center it, then it would
728 // be impossible to scroll over to the left since we can't have "negative
729 // scroll;" window.scrollX is always non-negative (unfortunately).
730 let visWidth = document.documentElement.clientWidth;
731 let totWidth = FullPanel.getFullWidth();
732 let z = PDFDocument.getZoom();
733 if (visWidth > totWidth)
734 {
735 // No horizontal scroll bar. Center it.
736 let canvasCenter = canvas.width / 2;
737 let docCenter = FullPanel.getFullWidth() / 2;
738 docCenter *= PDFDocument.getZoom();
739
740 ctx.translate(canvasCenter - docCenter,0);
741 }
742 else
743 {
744 // Shift according to the horizontal scroll bar, leaving the document
745 // against the left edge. Note the scaling by the zoom factor so
746 // as to be consistent with the above.
747 ctx.translate(-window.scrollX * PDFDocument.getZoom(),0);
748 }
749
750 return ctx;
751 }
752
753 async function fullRender() {
754
755 // Render all the pages of the pdf, together with the figures.
756 var canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
757
758 // This shouldn't be necessary, but do it as a fail-safe.
759 var ctx = <CanvasRenderingContext2D> canvas.getContext('2d');
760 ctx.resetTransform();
761
762 let visWidth = document.documentElement.clientWidth;
763
764 let z = PDFDocument.getZoom();
765
766 // BUG: Could lead to flicker? It is necessary to clear everything
767 // because widgets could be drawn outside the page. I suppose that I could
768 // only erase the area outside the pages, which would reduce any flicker.
769 // I really don't want to double-buffer everything if it can be avoided.
770 // It may be the only solution. The problem is that, if a widget extends
771 // outside the page, and is animated (like LoopAnimWidget) so that it's
772 // drawn as part of an animation, then you must erase the entire page to
773 // avoid "leftovers," and *that* requires that you redraw the entire
774 // document (or what is visible) with every frame of an animation.
775 //
776 // BUG: So the correct solution is double-buffering everything, but I don't
777 // feel that it's pressing. For now, either restrict any widgets to
778 // draw within a page or accept that it might leave spoogey leftovers.
779 ctx.clearRect(0,0,visWidth*z,document.documentElement.clientHeight*z);
780
781 await FullPanel.renderAll(canvas.height);
782 }
783
784 function adjustCanvas() : void {
785
786 // Call when the window has been zoomed or re-sized.
787 //
788 // canvas has two different dimensions: canvas.style.width and height, and
789 // canvas.width and height. The style values determine the size of the canvas
790 // on the screen -- so-called ""CSS styling." The straight values (no style)
791 // are the number of px in the canvas. By keeping the style values constant and
792 // varying the straight values, you can have more or less resolution for the
793 // canvas, EVEN WHEN ZOOMED IN.
794 //
795 // The bottom line is that if we adjust the straight pixel sizes, then
796 // we can always have one px for every physical pixel -- up to the accuracy
797 // of window.devicePixelRatio.
798 //
799 // BUG: Check for things with super high pixel density, like phones. I
800 // think the devicePixelRatio is somehow wrong for those. It may not matter.
801 var canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer") ;
802
803 // Adjust the visible width to match the window size.
804 //
805 // NOTE: For debugging, it can be helpful to subtract off a bit from these
806 // values, like 1, 10 or 50, depending. In earlier versions, there was
807 // also a bit of CSS in the html that put a visible rectangle around the canvas.
808 //canvas.style.width = (document.documentElement.clientWidth - 50) + "px";
809 //canvas.style.height = (document.documentElement.clientHeight - 50) + "px";
810 canvas.style.width = document.documentElement.clientWidth + "px";
811 canvas.style.height = document.documentElement.clientHeight + "px";
812
813 // The visible width of the canvas has just been fixed. Now change the
814 // number of px so that the number of px per inch on the screen varies with
815 // the level of browser zoom. There seems to be no means of direct access
816 // to the phyical pixels of the monitor, but this is close, and may be
817 // exactly equivalent in many situations.
818 canvas.width = document.documentElement.clientWidth * window.devicePixelRatio;
819 canvas.height = document.documentElement.clientHeight * window.devicePixelRatio;
820 }
821
822 async function doScrollGuts(id : number) {
823
824 // Wait for any active event handler to finish and then wait until it is
825 // the turn of current id to run.
826 await Events.waitMyTurn(id);
827
828 await fullRender();
829
830 // Give your ticket to the butcher so that he can take the next customer.
831 Events.allDone(id);
832 }
833
834 function doScroll() : void {
835
836 // Scroll events are registered below to call this function.
837 // It redraws the contents of the main canvas.
838
839 // This appears to be called when the page is opened, before almost
840 // anything else, so return until page initialization is complete.
841 if (PDFDocument.isLoaded() == false)
842 return;
843
844 // Get a unique ID for this event.
845 // This must be done outside any async function to ensure proper order.
846 let id = Events.getID();
847
848 doScrollGuts(id);
849 }
850
851 async function doResizeGuts(id : number) {
852
853 // As with scrolling, wait for any earlier event handler to complete.
854 await Events.waitMyTurn(id);
855
856 // None of the buffered offscreen canvases are valid anymore.
857 // In theory, I could test for whether this was merely a window
858 // resize and not a zoom, but it's not worth fooling with.
859 PDFDocument.flushBuffer();
860
861 console.log("ratio: " + window.devicePixelRatio);
862
863 // The other thing that needs to be adjusted is the zoom level
864 // used when rendering the pdfs.
865 adjustCanvas();
866
867 // Here is the magic. Effectively, this value is now the level of zoom.
868 // If you take out this line, and leave PDFDocument.zoom always equal to
869 // default value of 1, then zooming does nothing, although the mismatch
870 // between the resolution of the off-screen canvas and the resolution on
871 // the screen can make things blurry or blocky.
872 PDFDocument.setZoom(window.devicePixelRatio);
873
874 // If the size of the window changed, then this needs to be adjusted too.
875 // This must be done after adjustCanvas().
876 adjustScrollBars();
877
878 // Render the pages too.
879 await fullRender();
880
881 // Final bit of scheduling magic.
882 Events.allDone(id);
883 }
884
885 function doResize() : void {
886
887 // This is called whenever the user zooms and also if the
888 // entire broswer window is resized.
889 let id = Events.getID();
890 doResizeGuts(id);
891 }
892
893 async function mouseDownGuts(id : number , x : number , y : number ) {
894
895 // (x,y) is the location of the mouse click, in pdf points, but
896 // relative to the window.
897 await Events.waitMyTurn(id);
898
899 // Just as we have to tweak the t-matrix to determine where to draw things,
900 // we need to do something similar to figure out where (x,y) is on the page.
901 // The difference is that the ctx.translate() operations become adjustments
902 // to x and y.
903 let visWidth = document.documentElement.clientWidth;
904 let totWidth = FullPanel.getFullWidth();
905 let canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
906
907 if (visWidth > totWidth)
908 {
909 // No horizontal scroll bar. The document is centered.
910 let canvasCenter = canvas.width / 2;
911 let docCenter = FullPanel.getFullWidth() / 2;
912 canvasCenter = canvasCenter / PDFDocument.getZoom();
913
914 x = x - (canvasCenter - docCenter);
915 }
916 else
917 {
918 // Shift according to the horizontal scroll bar.
919 x = x + window.scrollX;
920 }
921
922 // Fix up the y-coordinate too.
923 y = y + window.scrollY;
924
925 FullPanel.mouseDown(x,y);
926
927 // Don't forget!
928 Events.allDone(id);
929 }
930
931 function doMouseDown(e : MouseEvent) : void {
932
933 // This is an event like any other, so the usual scheduling rigmarole.
934 let id = Events.getID();
935 mouseDownGuts(id,e.x,e.y);
936 }
937
938 async function mouseMoveGuts(id : number , x : number , y : number ) {
939
940 // As above.
941 // BUG: Common code. Not DRY.
942 await Events.waitMyTurn(id);
943
944 // As for mouse-down.
945 let visWidth = document.documentElement.clientWidth;
946 let totWidth = FullPanel.getFullWidth();
947 let canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
948
949 if (visWidth > totWidth)
950 {
951 // No horizontal scroll bar. The document is centered.
952 let canvasCenter = canvas.width / 2;
953 let docCenter = FullPanel.getFullWidth() / 2;
954 canvasCenter = canvasCenter / PDFDocument.getZoom();
955
956 x = x - (canvasCenter - docCenter);
957 }
958 else
959 {
960 // Shift according to the horizontal scroll bar.
961 x = x + window.scrollX;
962 }
963
964 // Fix up the y-coordinate too.
965 y = y + window.scrollY;
966 FullPanel.mouseMove(x,y);
967
968 // Don't forget!
969 Events.allDone(id);
970 }
971
972 function doMouseMove(e : MouseEvent) :void {
973
974 // As above.
975 let id = Events.getID();
976 mouseMoveGuts(id,e.x,e.y);
977 }
978
979 async function mouseUpGuts(id : number , x : number , y : number ) {
980
981 // As above.
982 // BUG: Common code. Not DRY.
983 await Events.waitMyTurn(id);
984
985 let visWidth = document.documentElement.clientWidth;
986 let totWidth = FullPanel.getFullWidth();
987 let canvas = <HTMLCanvasElement> document.getElementById("pdf_renderer");
988
989 if (visWidth > totWidth)
990 {
991 // No horizontal scroll bar. The document is centered.
992 let canvasCenter = canvas.width / 2;
993 let docCenter = FullPanel.getFullWidth() / 2;
994 canvasCenter = canvasCenter / PDFDocument.getZoom();
995
996 x = x - (canvasCenter - docCenter);
997 }
998 else
999 {
1000 // Shift according to the horizontal scroll bar.
1001 x = x + window.scrollX;
1002 }
1003
1004 // Fix up the y-coordinate too.
1005 y = y + window.scrollY;
1006 FullPanel.mouseUp(x,y);
1007
1008 // Don't forget!
1009 Events.allDone(id);
1010 }
1011
1012 function doMouseUp(e : MouseEvent ) : void {
1013
1014 // As above.
1015 let id = Events.getID();
1016 mouseUpGuts(id,e.x,e.y);
1017 }
1018
1019 function doTikzClick() : void {
1020
1021 // Tikz button was clicked. Generate output file(s).
1022 //
1023 // Cycle over every figure and let it generate tikz data.
1024 for (let pi = 0; pi < PDFDocument.pageSpecs.length; pi++)
1025 {
1026 let pd = PDFDocument.pageSpecs[pi] !;
1027 if (pd.name.length === 0)
1028 // No figures on this page.
1029 continue;
1030
1031 for (let fi = 0; fi < pd.name.length; fi++)
1032 {
1033 if (pd.done[fi] == true)
1034 // User said to skip this one.
1035 continue;
1036
1037 let theFcn : AugmentedDrawingFunction = pd.drawFcn[fi];
1038
1039 if (theFcn.figurePanelClass === null)
1040 // Hasn't been loaded, because was never visible.
1041 continue;
1042
1043 let ctx = new CTX(pd.name[fi]);
1044 theFcn(ctx);
1045 ctx.close();
1046 }
1047 }
1048 }
1049
1050
1051 function doBeforeUnload(e : Event) {
1052
1053 // This is *very* non-standard. Pass a made-up WHERE message with the position
1054 // on the document.
1055 // BUG: This only informs the server of the vertical scroll position.
1056 // Dealing with horizontal scroll would be more painful. See fullRender()
1057 // and adjustScrollBars().
1058 // If *everything* were double-buffered, then this would be a bit easier.
1059 let req = new XMLHttpRequest();
1060
1061 // We don't care about the second argument. In a POST this would be
1062 // something like a file name. The third argument, 'false', forces the request
1063 // to be handled synchronously. If it's done async, then the unload proceeds
1064 // and completes before this task finishes.
1065 req.open("WHERE","bogus", false );
1066
1067 req.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
1068
1069 // Send the postion as the message. It could probaby be sent instead of
1070 // 'bogus' above, and this could be blank.
1071 let msg = window.scrollY.toString();
1072
1073 // BUG: Firefox generates "Uncaught DOMException: A network error occurred."
1074 // on this. It might be that XMLHttpRequest is deprecated?
1075 req.send(msg);
1076 }
1077
1078 // Register additional event handlers. The main (and only) canvas had
1079 // listeners registered for mouse events in doOpenDocument().
1080 document.addEventListener('scroll',doScroll);
1081 window.addEventListener('resize', doResize);
1082
1083 // PUBLIC FACING: Comment this out. It's doing something *very* non-standard,
1084 // and any normal web-server will choke on it.
1085 window.addEventListener('beforeunload',doBeforeUnload);
1086