-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
zoommanager.js
594 lines (534 loc) · 17.5 KB
/
zoommanager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/**
@mainpage Helper classes from zoomifiers
Classes defined here:
- @ref UI : User interface management, interaction with HTML. SHouldn't be used directly by dezoomers.
- @ref ZoomManager : Helper to be used by dezoomers
*/
/**
User interface management, interaction with HTML
@class UI
*/
var UI = {};
UI.canvas = document.getElementById("rendering-canvas");
UI.dezoomers = document.getElementById("dezoomers");
UI.ratio = 1;
UI.MAX_CANVAS_AREA = 16384 * 16384; // See https://github.com/jhildenbiddle/canvas-size
/**
Adjusts the size of the image, so that is fits page width or page height
**/
UI.changeSize = function () {
var width = UI.canvas.width, height = UI.canvas.height;
switch (this.fit) {
case "width":
this.fit = "height";
UI.canvas.style.height = window.innerHeight + "px";
UI.canvas.style.width = window.innerHeight / height * width + "px";
break;
case "height":
this.fit = "none";
UI.canvas.style.width = width + "px";
UI.canvas.style.height = height + "px";
break;
default:
this.fit = "width";
UI.canvas.style.width = window.innerWidth + "px";
UI.canvas.style.height = window.innerWidth / width * height + "px";
}
};
/**
Sets the width and height of the canvas
@param {Object} data : Image source information, containing width and height of the image.
**/
UI.setupRendering = function (data) {
document.body.className = "loading";
document.getElementById("error").setAttribute("hidden", true);
var area = data.width * data.height;
for (var maxArea = UI.MAX_CANVAS_AREA; maxArea > 8; maxArea /= 2) {
UI.ratio = Math.min(Math.sqrt(maxArea / area), 1);
UI.canvas.width = data.width * UI.ratio;
UI.canvas.height = data.height * UI.ratio;
UI.ctx = UI.canvas.getContext("2d");
try {
UI.ctx.getImageData(0, 0, 1, 1); // Tests whether the canvas was successfully allocated
break;
} catch (_) { }
}
UI.canvas.onclick = UI.changeSize;
UI.changeSize();
};
/**
Draw a tile on the canvas, at the given position.
@param {Image} tile : The tile image
@param {Number} x position
@param {Number} y position
*/
UI.drawTile = function (tileImg, x, y) {
var r = UI.ratio, w = tileImg.width, h = tileImg.height;
UI.ctx.drawImage(tileImg,
Math.floor(x * r),
Math.floor(y * r),
Math.ceil(w * r),
Math.ceil(h * r)
);
};
/**
Display an error in the UI.
@param {String} errmsg The error message
*/
UI.error = function (errmsg) {
document.getElementById("percent").textContent = "";
document.getElementById("error").removeAttribute("hidden");
var error_img = "error.svg?error=" + encodeURIComponent(errmsg);
document.getElementById("error-img").src = error_img;
if (errmsg) {
document.getElementById("errormsg").textContent = errmsg;
var urltxt = document.getElementById("url").value;
try {
var url = new URL(urltxt);
} catch (e) { // not a valid URL
var url = new URL("invalid://invalid?source=" + urltxt);
}
document.getElementById("gh-search").href =
"https://github.com/lovasoa/dezoomify/issues?q=" +
encodeURIComponent(url.host);
document.getElementById("gh-open-issue").href =
"https://github.com/lovasoa/dezoomify/issues/new" +
"?labels=" + "new%20site%20support" +
"&title=" + encodeURIComponent(url.host) +
"&body=" + encodeURIComponent(
"Hello everyone,\n\n I am having issues when trying to download " + url +
"\n\nDezoomify reports:\n\n```\n" + errmsg + "\n```\n" +
"I don't understand this message. Can someone please help me ?"
);
}
};
window.onerror = function (errmsg, source, lineno) {
UI.error(errmsg + '\n\n(' + source + ':' + lineno + ')');
}
/**
Reset the UI to the initial state.
*/
UI.reset = function () {
document.getElementById("error").setAttribute("hidden", "hidden");
document.getElementById("status").className = "";
UI.canvas.width = UI.canvas.height = 0;
};
/**
Update the state of the progress bar.
@param {Number} percentage (between 0 and 100)
@param {String} description current state description
*/
UI.updateProgress = function (percent, text) {
if (!percent) {
document.getElementById("percent").innerHTML = text;
return;
}
percent = parseInt(percent);
document.getElementById("percent").innerHTML = text + ' (' + percent + "%)";
document.getElementById("progressbar").style.width = percent + "%";
document.getElementById("progressbar").setAttribute("aria-valuenow", percent);
document.title = "(" + percent + "%) Dezoomify";
};
/**
Update UI after the image has loaded.
*/
UI.loadEnd = function () {
var status = document.getElementById("status");
var a = document.createElement("a");
a.download = "dezoomify-result.jpg";
a.href = "#";
a.textContent = "Converting image...";
a.className = "button";
try {
// Try to export the image
UI.canvas.toBlob(function (blob) {
if (!(blob instanceof Blob)) {
console.error("Unable to access the canvas image data, got an unexpected value", blob);
status.className = "finished";
}
var url = URL.createObjectURL(blob);
a.href = url;
a.textContent = "Save image";
}, "image/jpeg", 0.95);
document.body.className = "download";
status.appendChild(a);
} catch (e) {
status.className = "finished";
}
};
/**
Add a new button for a new dezoomer.
@param {Object} dezoomer the dezoomer object
*/
UI.addDezoomer = function (dezoomer) {
var label = document.createElement("label")
var input = document.createElement("input");
input.type = "radio"
input.name = "dezoomer";
input.id = "dezoomer-" + dezoomer.name;
label.title = dezoomer.description;
input.onclick = function () {
ZoomManager.setDezoomer(dezoomer);
}
label.appendChild(input);
label.appendChild(document.createTextNode(dezoomer.name));
UI.dezoomers.appendChild(label);
};
/**
@brief Set the dezoomer that is currently used.
@param {String} dezoomerName name of the dezoomer
*/
UI.setDezoomer = function (dezoomerName) {
document.getElementById("dezoomer-" + dezoomerName).checked = true;
}
/**
Contains helper functions for dezoomers
@class
*/
var ZoomManager = {};
/**
@brief Signal an error
@param {String} errmsg The error text
@throws {Error} err The given error
*/
ZoomManager.error = function (errmsg) {
// Display only the first error, until the ZoomManager in reinitialized
if (!ZoomManager.status.error) {
ZoomManager.status.error = true;
UI.error(errmsg);
throw new Error(errmsg);
}
};
ZoomManager.updateProgress = function (progress, msg) {
UI.updateProgress(progress, msg);
};
ZoomManager.loadEnd = function () {
UI.loadEnd();
}
/**
Start listening for tile loads
@return {Number} The timer ID
*/
ZoomManager.startTimer = function () {
var wasLoaded = 0; // Number of tiles that were loaded last time we watched
var timer = setInterval(function () {
/*Update the User Interface each 500ms, and not in addTile, because it would
slow down the all process to update the UI too often.*/
var loaded = ZoomManager.status.loaded, total = ZoomManager.status.totalTiles;
if (loaded !== wasLoaded) {
// Update progress if new tiles were loaded
ZoomManager.updateProgress(100 * loaded / total, "Loading the tiles...");
wasLoaded = loaded;
}
if (loaded >= total) {
clearInterval(timer);
ZoomManager.loadEnd();
}
}, 500);
return timer;
};
/**
Tells that we are ready
*/
ZoomManager.readyToRender = function (data) {
if (ZoomManager.data) {
console.log("Only one dezoom can be active at a time", data);
return;
}
data.nbrTilesX = data.nbrTilesX || Math.ceil(data.width / data.tileSize);
data.nbrTilesY = data.nbrTilesY || Math.ceil(data.height / data.tileSize);
data.totalTiles = data.totalTiles || data.nbrTilesX * data.nbrTilesY;
data.zoomFactor = data.zoomFactor || 2;
data.baseZoomLevel = data.baseZoomLevel || 0;
data.overlap = data.overlap || 0;
ZoomManager.status.totalTiles = data.totalTiles;
ZoomManager.data = data;
UI.setupRendering(data);
ZoomManager.updateProgress(0, "Preparing tiles load...");
ZoomManager.startTimer();
var render = ZoomManager.dezoomer.render || ZoomManager.defaultRender;
setTimeout(render, 1, data); //Give time to refresh the UI, in case render would take a long time
};
ZoomManager.defaultRender = function (data) {
var zoom = data.maxZoomLevel || ZoomManager.findMaxZoom(data);
var x = 0, y = 0;
function addTile(url, x, y, data) {
if (typeof url === "string") {
if (data.origin) url = ZoomManager.resolveRelative(url, data.origin);
ZoomManager.addTile(url, x * data.tileSize - data.overlap, y * data.tileSize - data.overlap);
} else { // Promise
url.then(function (url) {
addTile(url, x, y, data)
}).catch(ZoomManager.error.bind(ZoomManager));
}
}
function nextTile() {
var url = ZoomManager.dezoomer.getTileURL(x, y, zoom, data);
if (typeof Promise !== "undefined") {
var x0 = x, y0 = y;
Promise.resolve(url)
.then(function (url) { addTile(url, x0, y0, data) })
.catch(ZoomManager.error);
} else {
addTile(url, x, y, data);
}
x++;
if (x >= data.nbrTilesX) { x = 0; y++; }
if (y < data.nbrTilesY) ZoomManager.nextTick(nextTile);
}
nextTile();
};
ZoomManager.MAX_REQUESTS_PER_SECOND = 5;
/**
@function nextTick
Call a function, but not immediatly
@param {Function} f - the function to call
*/
ZoomManager.nextTick = function (f) {
return setTimeout(f, 1000 / ZoomManager.MAX_REQUESTS_PER_SECOND);
};
/**
Request a tile from the server
@param {String} url - tile URL
@param {Number} x - position in px
@param {Number} y - position in px
@param {Number} [n=0] - Number of time the tile has already been requested
*/
ZoomManager.addTile = function addTile(url, x, y, ntries) {
//Request a tile from the server and display it once it loaded
ntries = ntries | 0; // Number of time the tile has already been requested
var img = new Image;
img.addEventListener("load", function () {
UI.drawTile(img, x, y);
ZoomManager.status.loaded++;
});
img.addEventListener("error", function (evt) {
if (ntries < 5) {
// Maybe the server is just busy right now, or we are running on a bad connection
nextTime = Math.pow(10 * Math.random(), ntries);
setTimeout(addTile, nextTime, url, x, y, ntries + 1);
} else {
ZoomManager.error("Unable to load tile.\n" +
"Check that your internet connection is working " +
"and that you can access this url:\n" + url);
}
});
if (ZoomManager.proxy_tiles) {
url = ZoomManager.proxy_tiles + "?url=" + encodeURIComponent(url);
if (ZoomManager.cookies.length > 0) {
url += "&cookies=" + encodeURIComponent(ZoomManager.cookies);
}
img.crossOrigin = "anonymous";
}
// Don't tell the tile host the request comes from dezoomify
img.referrerPolicy = "no-referrer";
img.src = url;
};
/**
Start the dezoomifying process
*/
ZoomManager.open = function (url) {
ZoomManager.init();
if (url.indexOf("http") !== 0) {
throw new Error("You must provide a valid HTTP URL.");
}
if (typeof ZoomManager.dezoomer.findFile === "function") {
ZoomManager.dezoomer.findFile(url, function foundFile(filePath, infos) {
ZoomManager.updateProgress(0, "Found image. Trying to open it...");
ZoomManager.dezoomer.open(ZoomManager.resolveRelative(filePath, url), infos);
});
ZoomManager.updateProgress(0, "The dezoomer is trying to locate the zoomable image...");
} else {
ZoomManager.dezoomer.open(url);
ZoomManager.updateProgress(0, "Launched dezoomer...");
}
};
/**
@callback fileCallback
@param {string|Document|Object} response
@param {XMLHttpRequest} request
*/
/**
Call callback with the contents of the page at url
@param {string} url
@param {{type:String, allow_failure?: boolean, error_callback: (err:string)=>any, is_tile?: boolean}} params
@param {fileCallback} callback - callback to call when the file is loaded
*/
ZoomManager.getFile = function (url, params, callback) {
var PHPSCRIPT = ZoomManager.proxy_url;
var type = params.type || "text";
var xhr = new XMLHttpRequest();
// The url we got MIGHT already have been encoded
// The url we give to the server MUST be encoded
if (url.match(/%[a-zA-Z0-9]{2}/) === null) url = encodeURI(url);
// We pass the URL itself as a query parameter, so we have to re-encode it
var codedurl = encodeURIComponent(url);
var requesturl = PHPSCRIPT + "?url=" + codedurl;
if (ZoomManager.cookies.length > 0) {
requesturl += "&cookies=" + encodeURIComponent(ZoomManager.cookies);
}
function onerror(error_msg) {
if (params.error_callback) params.error_callback(error_msg);
if (params.allow_failure) console.log("non-fatal error: ", error_msg);
else ZoomManager.error(error_msg);
}
xhr.open("GET", requesturl, true);
xhr.onloadstart = function () {
if (!params.is_tile)
ZoomManager.updateProgress(0, "Sent a request in order to get information about the image...");
};
xhr.onerror = function (e) {
onerror("Unable to connect to the proxy server " +
"to get the required information.\n\nXHR error:\n" + e);
};
xhr.onload = function () {
var response = xhr.response;
/// If the proxy failed to make the request
if (xhr.status === 500) {
var msg = "Unable to fetch " + url;
var responseText =
typeof response === "string" ? response :
(response instanceof ArrayBuffer) ? new TextDecoder("utf-8").decode(response) :
"";
if (responseText) {
msg += "\nThe server responded:\n" + responseText;
if (responseText.match(/403 forbidden/i)) {
msg += "\nSee dezoomify's wiki page about protected pages.";
}
}
return onerror(msg);
} else if (xhr.status === 429) {
var msg = "Our server has received too many requests, and our provider is blocking new requests. " +
"You can donate on https://github.com/sponsors/lovasoa to participate to the hosting fees. " +
"Once we collect over 5$/month overall, we will switch to a paid plan of the provider, allowing more requests to go through every day. " +
"For more details, see https://github.com/lovasoa/dezoomify/issues/337#issuecomment-773498488.";
return onerror(msg);
}
var cookie = xhr.getResponseHeader("X-Set-Cookie");
if (cookie) ZoomManager.cookies += cookie;
// Custom error message on invalid XML
if (type === "xml" &&
(response === null || response.documentElement.tagName === "parsererror")) {
return onerror("Invalid XML:\n" + url);
}
// Custom error message on invalid JSON
if (type === "json" && xhr.response === null) {
return onerror("Invalid JSON:\n" + url);
}
// Decode html encoded entities
if (type === "htmltext") {
response = ZoomManager.decodeHTMLentities(response);
}
callback(response, xhr);
};
switch (type) {
case "xml":
xhr.responseType = "document";
xhr.overrideMimeType("text/xml");
break;
case "json":
xhr.responseType = "json";
xhr.overrideMimeType("application/json");
break;
case "binary":
xhr.responseType = "arraybuffer";
break;
default:
xhr.responseType = "text";
xhr.overrideMimeType("text/plain");
}
xhr.send(null);
};
/**
Decode HTML special characaters such as "&", ">", ...
@function ZoomManager.decodeHTMLentities
@param {string} str
@return {string} decoded
*/
ZoomManager.decodeHTMLentities = (function () {
var dict = {
"&": "&",
"<": "<",
">": ">",
""": "\""
};
var regEx = /&(?:amp|lt|gt|quot|#(?:x[\da-f]+|\d+));/gi;
function replacer(entity) {
entity = entity.toLowerCase();
return dict[entity] ||
String.fromCharCode(parseInt('0' + entity.slice(2, -1)));
}
return function decodeHTMLentities(text) {
return text.replace(regEx, replacer);
};
})();
/**
Return the absolute path, given a relative path and a base
@param {string} path - the path, such as "path/to/other/file.jpg"
@param {string} base - the base URL, such as "http://test.com/path/to/first/file.html"
@return {string} resolved - the resolved path, such as "http://test.com/path/to/first/path/to/other/file.jpg"
*/
ZoomManager.resolveRelative = function resolveRelative(path, base) {
// absolute URL
if (path.match(/\w*:\/\//)) {
return path;
}
// Protocol-relative URL
if (path.indexOf("//") === 0) {
var protocol = base.match(/\w+:/) || ["http:"];
return protocol[0] + path;
}
// Upper directory
if (path.indexOf("../") === 0) {
return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
}
// Relative to the root
if (path[0] === '/') {
var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
return match[0] + path.slice(1);
}
//relative to the current directory
return base.replace(/\/[^\/]*$/, "") + '/' + path;
};
/**
Returns the maximum zoom level, knowing the image size, the tile size, and the multiplying factor between two consecutive zoom levels
@param {{width:number, height:number}} metadata
@return {number} maxzoom - the maximal zoom level
**/
ZoomManager.findMaxZoom = function (data) {
//For all zoom levels:
//size / zoomFactor^(maxZoomLevel - zoomlevel) = numTilesAtThisZoomLevel * tileSize
//For the baseZoomLevel (0 for zoomify), numTilesAtThisZoomLevel=1
var size = Math.max(data.width, data.height);
return Math.ceil(Math.log(size / data.tileSize) / Math.log(data.zoomFactor)) + (data.baseZoomLevel || 0);
};
ZoomManager.dezoomersList = {};
ZoomManager.addDezoomer = function (dezoomer) {
ZoomManager.dezoomersList[dezoomer.name] = dezoomer;
UI.addDezoomer(dezoomer);
}
/**
Set the active dezoomer
*/
ZoomManager.setDezoomer = function (dezoomer) {
ZoomManager.dezoomer = dezoomer;
UI.setDezoomer(dezoomer.name);
}
ZoomManager.reset = function () {
// This variable will store cookies set by previous requests
ZoomManager.setDezoomer(ZoomManager.dezoomersList["Select automatically"]);
};
/**
Initialize the ZoomManager
*/
ZoomManager.init = function () {
// Called before open()
if (!ZoomManager.cookies) ZoomManager.cookies = "";
if (!ZoomManager.proxy_url) ZoomManager.proxy_url = "proxy.php";
ZoomManager.status = {
"error": false,
"loaded": 0,
"totalTiles": 1
};
UI.reset();
};