Debian Codegraph @

texmf-dist/doc/latex/figput/javascript/main.js

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