// ==UserScript== // @name Picviewer CE+ // @name:zh-CN Picviewer CE+ // @name:zh-TW Picviewer CE+ // @name:ja Picviewer CE+ // @name:pt-BR Picviewer CE+ // @name:ru Picviewer CE+ // @author NLF && ywzhaiqi && hoothin // @description Powerful picture viewing tool online, which can popup/scale/rotate/batch save pictures automatically // @description:zh-CN 在线看图工具,支持图片翻转、旋转、缩放、弹出大图、批量保存 // @description:zh-TW 線上看圖工具,支援圖片翻轉、旋轉、縮放、彈出大圖、批量儲存 // @description:ja オンラインで画像を強力に閲覧できるツール。ポップアップ表示、拡大・縮小、回転、一括保存などの機能を自動で実行できます // @description:pt-BR Poderosa ferramenta de visualização de imagens on-line, que pode pop-up/dimensionar/girar/salvar em lote imagens automaticamente // @description:ru Мощный онлайн-инструмент для просмотра изображений, который может автоматически отображать/масштабировать/вращать/пакетно сохранять изображения // @version 2024.5.29.1 // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAAV1BMVEUAAAD////29vbKysoqKioiIiKysrKhoaGTk5N9fX3z8/Pv7+/r6+vk5OTb29vOzs6Ojo5UVFQzMzMZGRkREREMDAy4uLisrKylpaV4eHhkZGRPT08/Pz/IfxjQAAAAgklEQVQoz53RRw7DIBBAUb5pxr2m3/+ckfDImwyJlL9DDzQgDIUMRu1vWOxTBdeM+onApENF0qHjpkOk2VTwLVEF40Kbfj1wK8AVu2pQA1aBBYDHJ1wy9Cf4cXD5chzNAvsAnc8TjoLAhIzsBao9w1rlVTIvkOYMd9nm6xPi168t9AYkbANdajpjcwAAAABJRU5ErkJggg== // @namespace https://github.com/hoothin/UserScripts // @homepage https://www.hoothin.com // @supportURL https://github.com/hoothin/UserScripts/issues // @connect www.google.com // @connect www.google.com.hk // @connect www.google.co.jp // @connect ipv4.google.com // @connect image.baidu.com // @connect www.tineye.com // @connect hoothin.com // @connect * // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_addStyle // @grant GM_openInTab // @grant GM_setClipboard // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @grant GM_notification // @grant GM_download // @grant GM.getValue // @grant GM.setValue // @grant GM.deleteValue // @grant GM.addStyle // @grant GM.openInTab // @grant GM.setClipboard // @grant GM.xmlHttpRequest // @grant GM.registerMenuCommand // @grant GM.notification // @grant unsafeWindow // @require https://update.greasyfork.org/scripts/6158/23710/GM_config%20CN.js // @require https://update.greasyfork.org/scripts/438080/1384302/pvcep_rules.js // @require https://update.greasyfork.org/scripts/440698/1383389/pvcep_lang.js // @match *://*/* // @exclude http://www.toodledo.com/tasks/* // @exclude http*://maps.google.com*/* // @exclude *://www.google.*/_/chrome/newtab* // @exclude *://mega.*/* // @exclude *://*.mega.*/* // @exclude *://onedrive.live.com/* // @run-at document-body // @created 2011-6-15 // @contributionURL https://ko-fi.com/hoothin // @contributionAmount 1 // @downloadURL none // ==/UserScript== if (window.top != window.self) { try { if (window.self.innerWidth < 250 || window.self.innerHeight < 250) { return; } } catch(e) { return; } } (function (global, factory) { if (typeof define === "function" && define.amd) { define([], factory); } else if (typeof exports !== "undefined") { factory(); } else { var mod = { exports: {} }; factory(); global.FileSaver = mod.exports; } })(this, function () { "use strict"; /* * FileSaver.js * A saveAs() FileSaver implementation. * * By Eli Grey, http://eligrey.com * * License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT) * source : http://purl.eligrey.com/github/FileSaver.js */ // The one and only way of getting global scope in all environments // https://stackoverflow.com/q/3277182/1008999 var _global = typeof window === 'object' && window.window === window ? window : typeof self === 'object' && self.self === self ? self : typeof global === 'object' && global.global === global ? global : void 0; function bom(blob, opts) { if (typeof opts === 'undefined') opts = { autoBom: false };else if (typeof opts !== 'object') { console.warn('Deprecated: Expected third argument to be a object'); opts = { autoBom: !opts }; } // prepend BOM for UTF-8 XML and text/* types (including HTML) // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF if (opts.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type }); } return blob; } function download(url, name, opts) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'blob'; xhr.onload = function () { saveAs(xhr.response, name, opts); }; xhr.onerror = function () { console.error('could not download file'); }; xhr.send(); } function corsEnabled(url) { var xhr = new XMLHttpRequest(); // use sync to avoid popup blocker xhr.open('HEAD', url, false); try { xhr.send(); } catch (e) {} return xhr.status >= 200 && xhr.status <= 299; } // `a.click()` doesn't work for all browsers (#465) function click(node) { try { node.dispatchEvent(new MouseEvent('click')); } catch (e) { var evt = document.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); node.dispatchEvent(evt); } } // Detect WebView inside a native macOS app by ruling out all browsers // We just need to check for 'Safari' because all other browsers (besides Firefox) include that too // https://www.whatismybrowser.com/guides/the-latest-user-agent/macos var isMacOSWebView = _global.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent); var URL = _global.URL || _global.webkitURL; var revokeObjectURL = URL.revokeObjectURL; var createObjectURL = URL.createObjectURL; var saveAs = _global.saveAs || ( // probably in some web worker typeof window !== 'object' || window !== _global ? function saveAs() {} /* noop */ // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView : 'download' in HTMLAnchorElement.prototype && !isMacOSWebView ? function saveAs(blob, name, opts) { var URL = _global.URL || _global.webkitURL; var a = document.createElement('a'); name = name || blob.name || 'download'; a.download = name; a.rel = 'noopener'; // tabnabbing // TODO: detect chrome extensions & packaged apps // a.target = '_blank' if (typeof blob === 'string') { // Support regular links a.href = blob; if (a.origin !== location.origin) { corsEnabled(a.href) ? download(blob, name, opts) : click(a, a.target = '_blank'); } else { click(a); } } else { // Support blobs a.href = createObjectURL(blob); setTimeout(function () { revokeObjectURL(a.href); }, 4E4); // 40s setTimeout(function () { click(a); }, 0); } } // Use msSaveOrOpenBlob as a second approach : 'msSaveOrOpenBlob' in navigator ? function saveAs(blob, name, opts) { name = name || blob.name || 'download'; if (typeof blob === 'string') { if (corsEnabled(blob)) { download(blob, name, opts); } else { var a = document.createElement('a'); a.href = blob; a.target = '_blank'; setTimeout(function () { click(a); }); } } else { navigator.msSaveOrOpenBlob(bom(blob, opts), name); } } // Fallback to using FileReader and a popup : function saveAs(blob, name, opts, popup) { // Open a popup immediately do go around popup blocker // Mostly only available on user interaction and the fileReader is async so... popup = popup || open('', '_blank'); if (popup) { popup.document.title = popup.document.body.innerText = 'downloading...'; } if (typeof blob === 'string') return download(blob, name, opts); var force = blob.type === 'application/octet-stream'; var isSafari = /constructor/i.test(_global.HTMLElement) || _global.safari; var isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent); if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== 'undefined') { // Safari doesn't allow downloading of blob URLs var reader = new FileReader(); reader.onloadend = function () { var url = reader.result; url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, 'data:attachment/file;'); if (popup) popup.location.href = url;else location = url; popup = null; // reverse-tabnabbing #460 }; reader.readAsDataURL(blob); } else { var url = createObjectURL(blob); if (popup) popup.location = url;else location.href = url; popup = null; // reverse-tabnabbing #460 setTimeout(function () { revokeObjectURL(url); }, 4E4); // 40s } }); _global.saveAs = saveAs.saveAs = saveAs; if (typeof module !== 'undefined') { module.exports = saveAs; } }); /*! JSZip v3.7.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/master/LICENSE */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64; enc4 = remainingBytes > 2 ? (chr3 & 63) : 64; output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); } return output.join(""); }; // public method for decoding exports.decode = function(input) { var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0, resultIndex = 0; var dataUrlPrefix = "data:"; if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { // This is a common error: people give a data url // (data:image/png;base64,iVBOR...) with a {base64: true} and // wonders why things don't work. // We can detect that the string input looks like a data url but we // *can't* be sure it is one: removing everything up to the comma would // be too dangerous. throw new Error("Invalid base64 input, it looks like a data url."); } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); var totalLength = input.length * 3 / 4; if(input.charAt(input.length - 1) === _keyStr.charAt(64)) { totalLength--; } if(input.charAt(input.length - 2) === _keyStr.charAt(64)) { totalLength--; } if (totalLength % 1 !== 0) { // totalLength is not an integer, the length does not match a valid // base64 content. That can happen if: // - the input is not a base64 content // - the input is *almost* a base64 content, with a extra chars at the // beginning or at the end // - the input uses a base64 variant (base64url for example) throw new Error("Invalid base64 input, bad content length."); } var output; if (support.uint8array) { output = new Uint8Array(totalLength|0); } else { output = new Array(totalLength|0); } while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output[resultIndex++] = chr1; if (enc3 !== 64) { output[resultIndex++] = chr2; } if (enc4 !== 64) { output[resultIndex++] = chr3; } } return output; }; },{"./support":30,"./utils":32}],2:[function(require,module,exports){ 'use strict'; var external = require("./external"); var DataWorker = require('./stream/DataWorker'); var Crc32Probe = require('./stream/Crc32Probe'); var DataLengthProbe = require('./stream/DataLengthProbe'); /** * Represent a compressed object, with everything needed to decompress it. * @constructor * @param {number} compressedSize the size of the data compressed. * @param {number} uncompressedSize the size of the data after decompression. * @param {number} crc32 the crc32 of the decompressed file. * @param {object} compression the type of compression, see lib/compressions.js. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data. */ function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) { this.compressedSize = compressedSize; this.uncompressedSize = uncompressedSize; this.crc32 = crc32; this.compression = compression; this.compressedContent = data; } CompressedObject.prototype = { /** * Create a worker to get the uncompressed content. * @return {GenericWorker} the worker. */ getContentWorker: function () { var worker = new DataWorker(external.Promise.resolve(this.compressedContent)) .pipe(this.compression.uncompressWorker()) .pipe(new DataLengthProbe("data_length")); var that = this; worker.on("end", function () { if (this.streamInfo['data_length'] !== that.uncompressedSize) { throw new Error("Bug : uncompressed data size mismatch"); } }); return worker; }, /** * Create a worker to get the compressed content. * @return {GenericWorker} the worker. */ getCompressedWorker: function () { return new DataWorker(external.Promise.resolve(this.compressedContent)) .withStreamInfo("compressedSize", this.compressedSize) .withStreamInfo("uncompressedSize", this.uncompressedSize) .withStreamInfo("crc32", this.crc32) .withStreamInfo("compression", this.compression) ; } }; /** * Chain the given worker with other workers to compress the content with the * given compression. * @param {GenericWorker} uncompressedWorker the worker to pipe. * @param {Object} compression the compression object. * @param {Object} compressionOptions the options to use when compressing. * @return {GenericWorker} the new worker compressing the content. */ CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) { return uncompressedWorker .pipe(new Crc32Probe()) .pipe(new DataLengthProbe("uncompressedSize")) .pipe(compression.compressWorker(compressionOptions)) .pipe(new DataLengthProbe("compressedSize")) .withStreamInfo("compression", compression); }; module.exports = CompressedObject; },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){ 'use strict'; var GenericWorker = require("./stream/GenericWorker"); exports.STORE = { magic: "\x00\x00", compressWorker : function (compressionOptions) { return new GenericWorker("STORE compression"); }, uncompressWorker : function () { return new GenericWorker("STORE decompression"); } }; exports.DEFLATE = require('./flate'); },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); /** * The following functions come from pako, from pako/lib/zlib/crc32.js * released under the MIT license, see pako https://github.com/nodeca/pako/ */ // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for(var n =0; n < 256; n++){ c = n; for(var k =0; k < 8; k++){ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++ ) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } // That's all for the pako functions. /** * Compute the crc32 of a string. * This is almost the same as the function crc32, but for strings. Using the * same function for the two use cases leads to horrible performances. * @param {Number} crc the starting value of the crc. * @param {String} str the string to use. * @param {Number} len the length of the string. * @param {Number} pos the starting position for the crc32 computation. * @return {Number} the computed crc32. */ function crc32str(crc, str, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++ ) { crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = function crc32wrapper(input, crc) { if (typeof input === "undefined" || !input.length) { return 0; } var isArray = utils.getTypeOf(input) !== "string"; if(isArray) { return crc32(crc|0, input, input.length, 0); } else { return crc32str(crc|0, input, input.length, 0); } }; },{"./utils":32}],5:[function(require,module,exports){ 'use strict'; exports.base64 = false; exports.binary = false; exports.dir = false; exports.createFolders = true; exports.date = null; exports.compression = null; exports.compressionOptions = null; exports.comment = null; exports.unixPermissions = null; exports.dosPermissions = null; },{}],6:[function(require,module,exports){ /* global Promise */ 'use strict'; // load the global object first: // - it should be better integrated in the system (unhandledRejection in node) // - the environment may have a custom Promise implementation (see zone.js) var ES6Promise = null; if (typeof Promise !== "undefined") { ES6Promise = Promise; } else { ES6Promise = require("lie"); } /** * Let the user use/change some implementations. */ module.exports = { Promise: ES6Promise }; },{"lie":37}],7:[function(require,module,exports){ 'use strict'; var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); var pako = require("pako"); var utils = require("./utils"); var GenericWorker = require("./stream/GenericWorker"); var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; exports.magic = "\x08\x00"; /** * Create a worker that uses pako to inflate/deflate. * @constructor * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate". * @param {Object} options the options to use when (de)compressing. */ function FlateWorker(action, options) { GenericWorker.call(this, "FlateWorker/" + action); this._pako = null; this._pakoAction = action; this._pakoOptions = options; // the `meta` object from the last chunk received // this allow this worker to pass around metadata this.meta = {}; } utils.inherits(FlateWorker, GenericWorker); /** * @see GenericWorker.processChunk */ FlateWorker.prototype.processChunk = function (chunk) { this.meta = chunk.meta; if (this._pako === null) { this._createPako(); } this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); }; /** * @see GenericWorker.flush */ FlateWorker.prototype.flush = function () { GenericWorker.prototype.flush.call(this); if (this._pako === null) { this._createPako(); } this._pako.push([], true); }; /** * @see GenericWorker.cleanUp */ FlateWorker.prototype.cleanUp = function () { GenericWorker.prototype.cleanUp.call(this); this._pako = null; }; /** * Create the _pako object. * TODO: lazy-loading this object isn't the best solution but it's the * quickest. The best solution is to lazy-load the worker list. See also the * issue #446. */ FlateWorker.prototype._createPako = function () { this._pako = new pako[this._pakoAction]({ raw: true, level: this._pakoOptions.level || -1 // default compression }); var self = this; this._pako.onData = function(data) { self.push({ data : data, meta : self.meta }); }; }; exports.compressWorker = function (compressionOptions) { return new FlateWorker("Deflate", compressionOptions); }; exports.uncompressWorker = function () { return new FlateWorker("Inflate", {}); }; },{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var GenericWorker = require('../stream/GenericWorker'); var utf8 = require('../utf8'); var crc32 = require('../crc32'); var signature = require('../signature'); /** * Transform an integer into a string in hexadecimal. * @private * @param {number} dec the number to convert. * @param {number} bytes the number of bytes to generate. * @returns {string} the result. */ var decToHex = function(dec, bytes) { var hex = "", i; for (i = 0; i < bytes; i++) { hex += String.fromCharCode(dec & 0xff); dec = dec >>> 8; } return hex; }; /** * Generate the UNIX part of the external file attributes. * @param {Object} unixPermissions the unix permissions or null. * @param {Boolean} isDir true if the entry is a directory, false otherwise. * @return {Number} a 32 bit integer. * * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : * * TTTTsstrwxrwxrwx0000000000ADVSHR * ^^^^____________________________ file type, see zipinfo.c (UNX_*) * ^^^_________________________ setuid, setgid, sticky * ^^^^^^^^^________________ permissions * ^^^^^^^^^^______ not used ? * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only */ var generateUnixExternalFileAttr = function (unixPermissions, isDir) { var result = unixPermissions; if (!unixPermissions) { // I can't use octal values in strict mode, hence the hexa. // 040775 => 0x41fd // 0100664 => 0x81b4 result = isDir ? 0x41fd : 0x81b4; } return (result & 0xFFFF) << 16; }; /** * Generate the DOS part of the external file attributes. * @param {Object} dosPermissions the dos permissions or null. * @param {Boolean} isDir true if the entry is a directory, false otherwise. * @return {Number} a 32 bit integer. * * Bit 0 Read-Only * Bit 1 Hidden * Bit 2 System * Bit 3 Volume Label * Bit 4 Directory * Bit 5 Archive */ var generateDosExternalFileAttr = function (dosPermissions, isDir) { // the dir flag is already set for compatibility return (dosPermissions || 0) & 0x3F; }; /** * Generate the various parts used in the construction of the final zip file. * @param {Object} streamInfo the hash with information about the compressed file. * @param {Boolean} streamedContent is the content streamed ? * @param {Boolean} streamingEnded is the stream finished ? * @param {number} offset the current offset from the start of the zip file. * @param {String} platform let's pretend we are this platform (change platform dependents fields) * @param {Function} encodeFileName the function to encode the file name / comment. * @return {Object} the zip parts. */ var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { var file = streamInfo['file'], compression = streamInfo['compression'], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date; var dataInfo = { crc32 : 0, compressedSize : 0, uncompressedSize : 0 }; // if the content is streamed, the sizes/crc32 are only available AFTER // the end of the stream. if (!streamedContent || streamingEnded) { dataInfo.crc32 = streamInfo['crc32']; dataInfo.compressedSize = streamInfo['compressedSize']; dataInfo.uncompressedSize = streamInfo['uncompressedSize']; } var bitflag = 0; if (streamedContent) { // Bit 3: the sizes/crc32 are set to zero in the local header. // The correct values are put in the data descriptor immediately // following the compressed data. bitflag |= 0x0008; } if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { // Bit 11: Language encoding flag (EFS). bitflag |= 0x0800; } var extFileAttr = 0; var versionMadeBy = 0; if (dir) { // dos or unix, we set the dos dir flag extFileAttr |= 0x00010; } if(platform === "UNIX") { versionMadeBy = 0x031E; // UNIX, version 3.0 extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); } else { // DOS or other, fallback to DOS versionMadeBy = 0x0014; // DOS, version 2.0 extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); } // date // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html dosTime = date.getUTCHours(); dosTime = dosTime << 6; dosTime = dosTime | date.getUTCMinutes(); dosTime = dosTime << 5; dosTime = dosTime | date.getUTCSeconds() / 2; dosDate = date.getUTCFullYear() - 1980; dosDate = dosDate << 4; dosDate = dosDate | (date.getUTCMonth() + 1); dosDate = dosDate << 5; dosDate = dosDate | date.getUTCDate(); if (useUTF8ForFileName) { // set the unicode path extra field. unzip needs at least one extra // field to correctly handle unicode path, so using the path is as good // as any other information. This could improve the situation with // other archive managers too. // This field is usually used without the utf8 flag, with a non // unicode path in the header (winrar, winzip). This helps (a bit) // with the messy Windows' default compressed folders feature but // breaks on p7zip which doesn't seek the unicode path extra field. // So for now, UTF-8 everywhere ! unicodePathExtraField = // Version decToHex(1, 1) + // NameCRC32 decToHex(crc32(encodedFileName), 4) + // UnicodeName utfEncodedFileName; extraFields += // Info-ZIP Unicode Path Extra Field "\x75\x70" + // size decToHex(unicodePathExtraField.length, 2) + // content unicodePathExtraField; } if(useUTF8ForComment) { unicodeCommentExtraField = // Version decToHex(1, 1) + // CommentCRC32 decToHex(crc32(encodedComment), 4) + // UnicodeName utfEncodedComment; extraFields += // Info-ZIP Unicode Path Extra Field "\x75\x63" + // size decToHex(unicodeCommentExtraField.length, 2) + // content unicodeCommentExtraField; } var header = ""; // version needed to extract header += "\x0A\x00"; // general purpose bit flag header += decToHex(bitflag, 2); // compression method header += compression.magic; // last mod file time header += decToHex(dosTime, 2); // last mod file date header += decToHex(dosDate, 2); // crc-32 header += decToHex(dataInfo.crc32, 4); // compressed size header += decToHex(dataInfo.compressedSize, 4); // uncompressed size header += decToHex(dataInfo.uncompressedSize, 4); // file name length header += decToHex(encodedFileName.length, 2); // extra field length header += decToHex(extraFields.length, 2); var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; var dirRecord = signature.CENTRAL_FILE_HEADER + // version made by (00: DOS) decToHex(versionMadeBy, 2) + // file header (common to file and central directory) header + // file comment length decToHex(encodedComment.length, 2) + // disk number start "\x00\x00" + // internal file attributes TODO "\x00\x00" + // external file attributes decToHex(extFileAttr, 4) + // relative offset of local header decToHex(offset, 4) + // file name encodedFileName + // extra field extraFields + // file comment encodedComment; return { fileRecord: fileRecord, dirRecord: dirRecord }; }; /** * Generate the EOCD record. * @param {Number} entriesCount the number of entries in the zip file. * @param {Number} centralDirLength the length (in bytes) of the central dir. * @param {Number} localDirLength the length (in bytes) of the local dir. * @param {String} comment the zip file comment as a binary string. * @param {Function} encodeFileName the function to encode the comment. * @return {String} the EOCD record. */ var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { var dirEnd = ""; var encodedComment = utils.transformTo("string", encodeFileName(comment)); // end of central dir signature dirEnd = signature.CENTRAL_DIRECTORY_END + // number of this disk "\x00\x00" + // number of the disk with the start of the central directory "\x00\x00" + // total number of entries in the central directory on this disk decToHex(entriesCount, 2) + // total number of entries in the central directory decToHex(entriesCount, 2) + // size of the central directory 4 bytes decToHex(centralDirLength, 4) + // offset of start of central directory with respect to the starting disk number decToHex(localDirLength, 4) + // .ZIP file comment length decToHex(encodedComment.length, 2) + // .ZIP file comment encodedComment; return dirEnd; }; /** * Generate data descriptors for a file entry. * @param {Object} streamInfo the hash generated by a worker, containing information * on the file entry. * @return {String} the data descriptors. */ var generateDataDescriptors = function (streamInfo) { var descriptor = ""; descriptor = signature.DATA_DESCRIPTOR + // crc-32 4 bytes decToHex(streamInfo['crc32'], 4) + // compressed size 4 bytes decToHex(streamInfo['compressedSize'], 4) + // uncompressed size 4 bytes decToHex(streamInfo['uncompressedSize'], 4); return descriptor; }; /** * A worker to concatenate other workers to create a zip file. * @param {Boolean} streamFiles `true` to stream the content of the files, * `false` to accumulate it. * @param {String} comment the comment to use. * @param {String} platform the platform to use, "UNIX" or "DOS". * @param {Function} encodeFileName the function to encode file names and comments. */ function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { GenericWorker.call(this, "ZipFileWorker"); // The number of bytes written so far. This doesn't count accumulated chunks. this.bytesWritten = 0; // The comment of the zip file this.zipComment = comment; // The platform "generating" the zip file. this.zipPlatform = platform; // the function to encode file names and comments. this.encodeFileName = encodeFileName; // Should we stream the content of the files ? this.streamFiles = streamFiles; // If `streamFiles` is false, we will need to accumulate the content of the // files to calculate sizes / crc32 (and write them *before* the content). // This boolean indicates if we are accumulating chunks (it will change a lot // during the lifetime of this worker). this.accumulate = false; // The buffer receiving chunks when accumulating content. this.contentBuffer = []; // The list of generated directory records. this.dirRecords = []; // The offset (in bytes) from the beginning of the zip file for the current source. this.currentSourceOffset = 0; // The total number of entries in this zip file. this.entriesCount = 0; // the name of the file currently being added, null when handling the end of the zip file. // Used for the emitted metadata. this.currentFile = null; this._sources = []; } utils.inherits(ZipFileWorker, GenericWorker); /** * @see GenericWorker.push */ ZipFileWorker.prototype.push = function (chunk) { var currentFilePercent = chunk.meta.percent || 0; var entriesCount = this.entriesCount; var remainingFiles = this._sources.length; if(this.accumulate) { this.contentBuffer.push(chunk); } else { this.bytesWritten += chunk.data.length; GenericWorker.prototype.push.call(this, { data : chunk.data, meta : { currentFile : this.currentFile, percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 } }); } }; /** * The worker started a new source (an other worker). * @param {Object} streamInfo the streamInfo object from the new source. */ ZipFileWorker.prototype.openedSource = function (streamInfo) { this.currentSourceOffset = this.bytesWritten; this.currentFile = streamInfo['file'].name; var streamedContent = this.streamFiles && !streamInfo['file'].dir; // don't stream folders (because they don't have any content) if(streamedContent) { var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); this.push({ data : record.fileRecord, meta : {percent:0} }); } else { // we need to wait for the whole file before pushing anything this.accumulate = true; } }; /** * The worker finished a source (an other worker). * @param {Object} streamInfo the streamInfo object from the finished source. */ ZipFileWorker.prototype.closedSource = function (streamInfo) { this.accumulate = false; var streamedContent = this.streamFiles && !streamInfo['file'].dir; var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); this.dirRecords.push(record.dirRecord); if(streamedContent) { // after the streamed file, we put data descriptors this.push({ data : generateDataDescriptors(streamInfo), meta : {percent:100} }); } else { // the content wasn't streamed, we need to push everything now // first the file record, then the content this.push({ data : record.fileRecord, meta : {percent:0} }); while(this.contentBuffer.length) { this.push(this.contentBuffer.shift()); } } this.currentFile = null; }; /** * @see GenericWorker.flush */ ZipFileWorker.prototype.flush = function () { var localDirLength = this.bytesWritten; for(var i = 0; i < this.dirRecords.length; i++) { this.push({ data : this.dirRecords[i], meta : {percent:100} }); } var centralDirLength = this.bytesWritten - localDirLength; var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); this.push({ data : dirEnd, meta : {percent:100} }); }; /** * Prepare the next source to be read. */ ZipFileWorker.prototype.prepareNextSource = function () { this.previous = this._sources.shift(); this.openedSource(this.previous.streamInfo); if (this.isPaused) { this.previous.pause(); } else { this.previous.resume(); } }; /** * @see GenericWorker.registerPrevious */ ZipFileWorker.prototype.registerPrevious = function (previous) { this._sources.push(previous); var self = this; previous.on('data', function (chunk) { self.processChunk(chunk); }); previous.on('end', function () { self.closedSource(self.previous.streamInfo); if(self._sources.length) { self.prepareNextSource(); } else { self.end(); } }); previous.on('error', function (e) { self.error(e); }); return this; }; /** * @see GenericWorker.resume */ ZipFileWorker.prototype.resume = function () { if(!GenericWorker.prototype.resume.call(this)) { return false; } if (!this.previous && this._sources.length) { this.prepareNextSource(); return true; } if (!this.previous && !this._sources.length && !this.generatedError) { this.end(); return true; } }; /** * @see GenericWorker.error */ ZipFileWorker.prototype.error = function (e) { var sources = this._sources; if(!GenericWorker.prototype.error.call(this, e)) { return false; } for(var i = 0; i < sources.length; i++) { try { sources[i].error(e); } catch(e) { // the `error` exploded, nothing to do } } return true; }; /** * @see GenericWorker.lock */ ZipFileWorker.prototype.lock = function () { GenericWorker.prototype.lock.call(this); var sources = this._sources; for(var i = 0; i < sources.length; i++) { sources[i].lock(); } }; module.exports = ZipFileWorker; },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){ 'use strict'; var compressions = require('../compressions'); var ZipFileWorker = require('./ZipFileWorker'); /** * Find the compression to use. * @param {String} fileCompression the compression defined at the file level, if any. * @param {String} zipCompression the compression defined at the load() level. * @return {Object} the compression object to use. */ var getCompression = function (fileCompression, zipCompression) { var compressionName = fileCompression || zipCompression; var compression = compressions[compressionName]; if (!compression) { throw new Error(compressionName + " is not a valid compression method !"); } return compression; }; /** * Create a worker to generate a zip file. * @param {JSZip} zip the JSZip instance at the right root level. * @param {Object} options to generate the zip file. * @param {String} comment the comment to use. */ exports.generateWorker = function (zip, options, comment) { var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); var entriesCount = 0; try { zip.forEach(function (relativePath, file) { entriesCount++; var compression = getCompression(file.options.compression, options.compression); var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; var dir = file.dir, date = file.date; file._compressWorker(compression, compressionOptions) .withStreamInfo("file", { name : relativePath, dir : dir, date : date, comment : file.comment || "", unixPermissions : file.unixPermissions, dosPermissions : file.dosPermissions }) .pipe(zipFileWorker); }); zipFileWorker.entriesCount = entriesCount; } catch (e) { zipFileWorker.error(e); } return zipFileWorker; }; },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){ 'use strict'; /** * Representation a of zip file in js * @constructor */ function JSZip() { // if this constructor is used without `new`, it adds `new` before itself: if(!(this instanceof JSZip)) { return new JSZip(); } if(arguments.length) { throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); } // object containing the files : // { // "folder/" : {...}, // "folder/data.txt" : {...} // } // NOTE: we use a null prototype because we do not // want filenames like "toString" coming from a zip file // to overwrite methods and attributes in a normal Object. this.files = Object.create(null); this.comment = null; // Where we are in the hierarchy this.root = ""; this.clone = function() { var newObj = new JSZip(); for (var i in this) { if (typeof this[i] !== "function") { newObj[i] = this[i]; } } return newObj; }; } JSZip.prototype = require('./object'); JSZip.prototype.loadAsync = require('./load'); JSZip.support = require('./support'); JSZip.defaults = require('./defaults'); // TODO find a better way to handle this version, // a require('package.json').version doesn't work with webpack, see #327 JSZip.version = "3.7.1"; JSZip.loadAsync = function (content, options) { return new JSZip().loadAsync(content, options); }; JSZip.external = require("./external"); module.exports = JSZip; },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var external = require("./external"); var utf8 = require('./utf8'); var ZipEntries = require('./zipEntries'); var Crc32Probe = require('./stream/Crc32Probe'); var nodejsUtils = require("./nodejsUtils"); /** * Check the CRC32 of an entry. * @param {ZipEntry} zipEntry the zip entry to check. * @return {Promise} the result. */ function checkEntryCRC32(zipEntry) { return new external.Promise(function (resolve, reject) { var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe()); worker.on("error", function (e) { reject(e); }) .on("end", function () { if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { reject(new Error("Corrupted zip : CRC32 mismatch")); } else { resolve(); } }) .resume(); }); } module.exports = function (data, options) { var zip = this; options = utils.extend(options || {}, { base64: false, checkCRC32: false, optimizedBinaryString: false, createFolders: false, decodeFileName: utf8.utf8decode }); if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); } return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64) .then(function (data) { var zipEntries = new ZipEntries(options); zipEntries.load(data); return zipEntries; }).then(function checkCRC32(zipEntries) { var promises = [external.Promise.resolve(zipEntries)]; var files = zipEntries.files; if (options.checkCRC32) { for (var i = 0; i < files.length; i++) { promises.push(checkEntryCRC32(files[i])); } } return external.Promise.all(promises); }).then(function addFiles(results) { var zipEntries = results.shift(); var files = zipEntries.files; for (var i = 0; i < files.length; i++) { var input = files[i]; zip.file(input.fileNameStr, input.decompressed, { binary: true, optimizedBinaryString: true, date: input.date, dir: input.dir, comment: input.fileCommentStr.length ? input.fileCommentStr : null, unixPermissions: input.unixPermissions, dosPermissions: input.dosPermissions, createFolders: options.createFolders }); } if (zipEntries.zipComment.length) { zip.comment = zipEntries.zipComment; } return zip; }); }; },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){ "use strict"; var utils = require('../utils'); var GenericWorker = require('../stream/GenericWorker'); /** * A worker that use a nodejs stream as source. * @constructor * @param {String} filename the name of the file entry for this stream. * @param {Readable} stream the nodejs stream. */ function NodejsStreamInputAdapter(filename, stream) { GenericWorker.call(this, "Nodejs stream input adapter for " + filename); this._upstreamEnded = false; this._bindStream(stream); } utils.inherits(NodejsStreamInputAdapter, GenericWorker); /** * Prepare the stream and bind the callbacks on it. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work. * @param {Stream} stream the nodejs stream to use. */ NodejsStreamInputAdapter.prototype._bindStream = function (stream) { var self = this; this._stream = stream; stream.pause(); stream .on("data", function (chunk) { self.push({ data: chunk, meta : { percent : 0 } }); }) .on("error", function (e) { if(self.isPaused) { this.generatedError = e; } else { self.error(e); } }) .on("end", function () { if(self.isPaused) { self._upstreamEnded = true; } else { self.end(); } }); }; NodejsStreamInputAdapter.prototype.pause = function () { if(!GenericWorker.prototype.pause.call(this)) { return false; } this._stream.pause(); return true; }; NodejsStreamInputAdapter.prototype.resume = function () { if(!GenericWorker.prototype.resume.call(this)) { return false; } if(this._upstreamEnded) { this.end(); } else { this._stream.resume(); } return true; }; module.exports = NodejsStreamInputAdapter; },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){ 'use strict'; var Readable = require('readable-stream').Readable; var utils = require('../utils'); utils.inherits(NodejsStreamOutputAdapter, Readable); /** * A nodejs stream using a worker as source. * @see the SourceWrapper in http://nodejs.org/api/stream.html * @constructor * @param {StreamHelper} helper the helper wrapping the worker * @param {Object} options the nodejs stream options * @param {Function} updateCb the update callback. */ function NodejsStreamOutputAdapter(helper, options, updateCb) { Readable.call(this, options); this._helper = helper; var self = this; helper.on("data", function (data, meta) { if (!self.push(data)) { self._helper.pause(); } if(updateCb) { updateCb(meta); } }) .on("error", function(e) { self.emit('error', e); }) .on("end", function () { self.push(null); }); } NodejsStreamOutputAdapter.prototype._read = function() { this._helper.resume(); }; module.exports = NodejsStreamOutputAdapter; },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){ 'use strict'; module.exports = { /** * True if this is running in Nodejs, will be undefined in a browser. * In a browser, browserify won't include this file and the whole module * will be resolved an empty object. */ isNode : typeof Buffer !== "undefined", /** * Create a new nodejs Buffer from an existing content. * @param {Object} data the data to pass to the constructor. * @param {String} encoding the encoding to use. * @return {Buffer} a new Buffer. */ newBufferFrom: function(data, encoding) { if (Buffer.from && Buffer.from !== Uint8Array.from) { return Buffer.from(data, encoding); } else { if (typeof data === "number") { // Safeguard for old Node.js versions. On newer versions, // Buffer.from(number) / Buffer(number, encoding) already throw. throw new Error("The \"data\" argument must not be a number"); } return new Buffer(data, encoding); } }, /** * Create a new nodejs Buffer with the specified size. * @param {Integer} size the size of the buffer. * @return {Buffer} a new Buffer. */ allocBuffer: function (size) { if (Buffer.alloc) { return Buffer.alloc(size); } else { var buf = new Buffer(size); buf.fill(0); return buf; } }, /** * Find out if an object is a Buffer. * @param {Object} b the object to test. * @return {Boolean} true if the object is a Buffer, false otherwise. */ isBuffer : function(b){ return Buffer.isBuffer(b); }, isStream : function (obj) { return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function"; } }; },{}],15:[function(require,module,exports){ 'use strict'; var utf8 = require('./utf8'); var utils = require('./utils'); var GenericWorker = require('./stream/GenericWorker'); var StreamHelper = require('./stream/StreamHelper'); var defaults = require('./defaults'); var CompressedObject = require('./compressedObject'); var ZipObject = require('./zipObject'); var generate = require("./generate"); var nodejsUtils = require("./nodejsUtils"); var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter"); /** * Add a file in the current folder. * @private * @param {string} name the name of the file * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file * @param {Object} originalOptions the options of the file * @return {Object} the new file. */ var fileAdd = function(name, data, originalOptions) { // be sure sub folders exist var dataType = utils.getTypeOf(data), parent; /* * Correct options. */ var o = utils.extend(originalOptions || {}, defaults); o.date = o.date || new Date(); if (o.compression !== null) { o.compression = o.compression.toUpperCase(); } if (typeof o.unixPermissions === "string") { o.unixPermissions = parseInt(o.unixPermissions, 8); } // UNX_IFDIR 0040000 see zipinfo.c if (o.unixPermissions && (o.unixPermissions & 0x4000)) { o.dir = true; } // Bit 4 Directory if (o.dosPermissions && (o.dosPermissions & 0x0010)) { o.dir = true; } if (o.dir) { name = forceTrailingSlash(name); } if (o.createFolders && (parent = parentFolder(name))) { folderAdd.call(this, parent, true); } var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; if (!originalOptions || typeof originalOptions.binary === "undefined") { o.binary = !isUnicodeString; } var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0; if (isCompressedEmpty || o.dir || !data || data.length === 0) { o.base64 = false; o.binary = true; data = ""; o.compression = "STORE"; dataType = "string"; } /* * Convert content to fit. */ var zipObjectContent = null; if (data instanceof CompressedObject || data instanceof GenericWorker) { zipObjectContent = data; } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { zipObjectContent = new NodejsStreamInputAdapter(name, data); } else { zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64); } var object = new ZipObject(name, zipObjectContent, o); this.files[name] = object; /* TODO: we can't throw an exception because we have async promises (we can have a promise of a Date() for example) but returning a promise is useless because file(name, data) returns the JSZip object for chaining. Should we break that to allow the user to catch the error ? return external.Promise.resolve(zipObjectContent) .then(function () { return object; }); */ }; /** * Find the parent folder of the path. * @private * @param {string} path the path to use * @return {string} the parent folder, or "" */ var parentFolder = function (path) { if (path.slice(-1) === '/') { path = path.substring(0, path.length - 1); } var lastSlash = path.lastIndexOf('/'); return (lastSlash > 0) ? path.substring(0, lastSlash) : ""; }; /** * Returns the path with a slash at the end. * @private * @param {String} path the path to check. * @return {String} the path with a trailing slash. */ var forceTrailingSlash = function(path) { // Check the name ends with a / if (path.slice(-1) !== "/") { path += "/"; // IE doesn't like substr(-1) } return path; }; /** * Add a (sub) folder in the current folder. * @private * @param {string} name the folder's name * @param {boolean=} [createFolders] If true, automatically create sub * folders. Defaults to false. * @return {Object} the new folder. */ var folderAdd = function(name, createFolders) { createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders; name = forceTrailingSlash(name); // Does this folder already exist? if (!this.files[name]) { fileAdd.call(this, name, null, { dir: true, createFolders: createFolders }); } return this.files[name]; }; /** * Cross-window, cross-Node-context regular expression detection * @param {Object} object Anything * @return {Boolean} true if the object is a regular expression, * false otherwise */ function isRegExp(object) { return Object.prototype.toString.call(object) === "[object RegExp]"; } // return the actual prototype of JSZip var out = { /** * @see loadAsync */ load: function() { throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); }, /** * Call a callback function for each entry at this folder level. * @param {Function} cb the callback function: * function (relativePath, file) {...} * It takes 2 arguments : the relative path and the file. */ forEach: function(cb) { var filename, relativePath, file; /* jshint ignore:start */ // ignore warning about unwanted properties because this.files is a null prototype object for (filename in this.files) { file = this.files[filename]; relativePath = filename.slice(this.root.length, filename.length); if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn... } } /* jshint ignore:end */ }, /** * Filter nested files/folders with the specified function. * @param {Function} search the predicate to use : * function (relativePath, file) {...} * It takes 2 arguments : the relative path and the file. * @return {Array} An array of matching elements. */ filter: function(search) { var result = []; this.forEach(function (relativePath, entry) { if (search(relativePath, entry)) { // the file matches the function result.push(entry); } }); return result; }, /** * Add a file to the zip file, or search a file. * @param {string|RegExp} name The name of the file to add (if data is defined), * the name of the file to find (if no data) or a regex to match files. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded * @param {Object} o File options * @return {JSZip|Object|Array} this JSZip object (when adding a file), * a file (when searching by string) or an array of files (when searching by regex). */ file: function(name, data, o) { if (arguments.length === 1) { if (isRegExp(name)) { var regexp = name; return this.filter(function(relativePath, file) { return !file.dir && regexp.test(relativePath); }); } else { // text var obj = this.files[this.root + name]; if (obj && !obj.dir) { return obj; } else { return null; } } } else { // more than one argument : we have data ! name = this.root + name; fileAdd.call(this, name, data, o); } return this; }, /** * Add a directory to the zip file, or search. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. */ folder: function(arg) { if (!arg) { return this; } if (isRegExp(arg)) { return this.filter(function(relativePath, file) { return file.dir && arg.test(relativePath); }); } // else, name is a new folder var name = this.root + arg; var newFolder = folderAdd.call(this, name); // Allow chaining by returning a new object with this folder as the root var ret = this.clone(); ret.root = newFolder.name; return ret; }, /** * Delete a file, or a directory and all sub-files, from the zip * @param {string} name the name of the file to delete * @return {JSZip} this JSZip object */ remove: function(name) { name = this.root + name; var file = this.files[name]; if (!file) { // Look for any folders if (name.slice(-1) !== "/") { name += "/"; } file = this.files[name]; } if (file && !file.dir) { // file delete this.files[name]; } else { // maybe a folder, delete recursively var kids = this.filter(function(relativePath, file) { return file.name.slice(0, name.length) === name; }); for (var i = 0; i < kids.length; i++) { delete this.files[kids[i].name]; } } return this; }, /** * Generate the complete zip file * @param {Object} options the options to generate the zip file : * - compression, "STORE" by default. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file */ generate: function(options) { throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); }, /** * Generate the complete zip file as an internal stream. * @param {Object} options the options to generate the zip file : * - compression, "STORE" by default. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. * @return {StreamHelper} the streamed zip file. */ generateInternalStream: function(options) { var worker, opts = {}; try { opts = utils.extend(options || {}, { streamFiles: false, compression: "STORE", compressionOptions : null, type: "", platform: "DOS", comment: null, mimeType: 'application/zip', encodeFileName: utf8.utf8encode }); opts.type = opts.type.toLowerCase(); opts.compression = opts.compression.toUpperCase(); // "binarystring" is preferred but the internals use "string". if(opts.type === "binarystring") { opts.type = "string"; } if (!opts.type) { throw new Error("No output type specified."); } utils.checkSupport(opts.type); // accept nodejs `process.platform` if( opts.platform === 'darwin' || opts.platform === 'freebsd' || opts.platform === 'linux' || opts.platform === 'sunos' ) { opts.platform = "UNIX"; } if (opts.platform === 'win32') { opts.platform = "DOS"; } var comment = opts.comment || this.comment || ""; worker = generate.generateWorker(this, opts, comment); } catch (e) { worker = new GenericWorker("error"); worker.error(e); } return new StreamHelper(worker, opts.type || "string", opts.mimeType); }, /** * Generate the complete zip file asynchronously. * @see generateInternalStream */ generateAsync: function(options, onUpdate) { return this.generateInternalStream(options).accumulate(onUpdate); }, /** * Generate the complete zip file asynchronously. * @see generateInternalStream */ generateNodeStream: function(options, onUpdate) { options = options || {}; if (!options.type) { options.type = "nodebuffer"; } return this.generateInternalStream(options).toNodejsStream(onUpdate); } }; module.exports = out; },{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){ /* * This file is used by module bundlers (browserify/webpack/etc) when * including a stream implementation. We use "readable-stream" to get a * consistent behavior between nodejs versions but bundlers often have a shim * for "stream". Using this shim greatly improve the compatibility and greatly * reduce the final size of the bundle (only one stream implementation, not * two). */ module.exports = require("stream"); },{"stream":undefined}],17:[function(require,module,exports){ 'use strict'; var DataReader = require('./DataReader'); var utils = require('../utils'); function ArrayReader(data) { DataReader.call(this, data); for(var i = 0; i < this.data.length; i++) { data[i] = data[i] & 0xFF; } } utils.inherits(ArrayReader, DataReader); /** * @see DataReader.byteAt */ ArrayReader.prototype.byteAt = function(i) { return this.data[this.zero + i]; }; /** * @see DataReader.lastIndexOfSignature */ ArrayReader.prototype.lastIndexOfSignature = function(sig) { var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); for (var i = this.length - 4; i >= 0; --i) { if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { return i - this.zero; } } return -1; }; /** * @see DataReader.readAndCheckSignature */ ArrayReader.prototype.readAndCheckSignature = function (sig) { var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data = this.readData(4); return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3]; }; /** * @see DataReader.readData */ ArrayReader.prototype.readData = function(size) { this.checkOffset(size); if(size === 0) { return []; } var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); this.index += size; return result; }; module.exports = ArrayReader; },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); function DataReader(data) { this.data = data; // type : see implementation this.length = data.length; this.index = 0; this.zero = 0; } DataReader.prototype = { /** * Check that the offset will not go too far. * @param {string} offset the additional offset to check. * @throws {Error} an Error if the offset is out of bounds. */ checkOffset: function(offset) { this.checkIndex(this.index + offset); }, /** * Check that the specified index will not be too far. * @param {string} newIndex the index to check. * @throws {Error} an Error if the index is out of bounds. */ checkIndex: function(newIndex) { if (this.length < this.zero + newIndex || newIndex < 0) { throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); } }, /** * Change the index. * @param {number} newIndex The new index. * @throws {Error} if the new index is out of the data. */ setIndex: function(newIndex) { this.checkIndex(newIndex); this.index = newIndex; }, /** * Skip the next n bytes. * @param {number} n the number of bytes to skip. * @throws {Error} if the new index is out of the data. */ skip: function(n) { this.setIndex(this.index + n); }, /** * Get the byte at the specified index. * @param {number} i the index to use. * @return {number} a byte. */ byteAt: function(i) { // see implementations }, /** * Get the next number with a given byte size. * @param {number} size the number of bytes to read. * @return {number} the corresponding number. */ readInt: function(size) { var result = 0, i; this.checkOffset(size); for (i = this.index + size - 1; i >= this.index; i--) { result = (result << 8) + this.byteAt(i); } this.index += size; return result; }, /** * Get the next string with a given byte size. * @param {number} size the number of bytes to read. * @return {string} the corresponding string. */ readString: function(size) { return utils.transformTo("string", this.readData(size)); }, /** * Get raw data without conversion, bytes. * @param {number} size the number of bytes to read. * @return {Object} the raw data, implementation specific. */ readData: function(size) { // see implementations }, /** * Find the last occurrence of a zip signature (4 bytes). * @param {string} sig the signature to find. * @return {number} the index of the last occurrence, -1 if not found. */ lastIndexOfSignature: function(sig) { // see implementations }, /** * Read the signature (4 bytes) at the current position and compare it with sig. * @param {string} sig the expected signature * @return {boolean} true if the signature matches, false otherwise. */ readAndCheckSignature: function(sig) { // see implementations }, /** * Get the next date. * @return {Date} the date. */ readDate: function() { var dostime = this.readInt(4); return new Date(Date.UTC( ((dostime >> 25) & 0x7f) + 1980, // year ((dostime >> 21) & 0x0f) - 1, // month (dostime >> 16) & 0x1f, // day (dostime >> 11) & 0x1f, // hour (dostime >> 5) & 0x3f, // minute (dostime & 0x1f) << 1)); // second } }; module.exports = DataReader; },{"../utils":32}],19:[function(require,module,exports){ 'use strict'; var Uint8ArrayReader = require('./Uint8ArrayReader'); var utils = require('../utils'); function NodeBufferReader(data) { Uint8ArrayReader.call(this, data); } utils.inherits(NodeBufferReader, Uint8ArrayReader); /** * @see DataReader.readData */ NodeBufferReader.prototype.readData = function(size) { this.checkOffset(size); var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); this.index += size; return result; }; module.exports = NodeBufferReader; },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){ 'use strict'; var DataReader = require('./DataReader'); var utils = require('../utils'); function StringReader(data) { DataReader.call(this, data); } utils.inherits(StringReader, DataReader); /** * @see DataReader.byteAt */ StringReader.prototype.byteAt = function(i) { return this.data.charCodeAt(this.zero + i); }; /** * @see DataReader.lastIndexOfSignature */ StringReader.prototype.lastIndexOfSignature = function(sig) { return this.data.lastIndexOf(sig) - this.zero; }; /** * @see DataReader.readAndCheckSignature */ StringReader.prototype.readAndCheckSignature = function (sig) { var data = this.readData(4); return sig === data; }; /** * @see DataReader.readData */ StringReader.prototype.readData = function(size) { this.checkOffset(size); // this will work because the constructor applied the "& 0xff" mask. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); this.index += size; return result; }; module.exports = StringReader; },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){ 'use strict'; var ArrayReader = require('./ArrayReader'); var utils = require('../utils'); function Uint8ArrayReader(data) { ArrayReader.call(this, data); } utils.inherits(Uint8ArrayReader, ArrayReader); /** * @see DataReader.readData */ Uint8ArrayReader.prototype.readData = function(size) { this.checkOffset(size); if(size === 0) { // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. return new Uint8Array(0); } var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); this.index += size; return result; }; module.exports = Uint8ArrayReader; },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var support = require('../support'); var ArrayReader = require('./ArrayReader'); var StringReader = require('./StringReader'); var NodeBufferReader = require('./NodeBufferReader'); var Uint8ArrayReader = require('./Uint8ArrayReader'); /** * Create a reader adapted to the data. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read. * @return {DataReader} the data reader. */ module.exports = function (data) { var type = utils.getTypeOf(data); utils.checkSupport(type); if (type === "string" && !support.uint8array) { return new StringReader(data); } if (type === "nodebuffer") { return new NodeBufferReader(data); } if (support.uint8array) { return new Uint8ArrayReader(utils.transformTo("uint8array", data)); } return new ArrayReader(utils.transformTo("array", data)); }; },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){ 'use strict'; exports.LOCAL_FILE_HEADER = "PK\x03\x04"; exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; exports.DATA_DESCRIPTOR = "PK\x07\x08"; },{}],24:[function(require,module,exports){ 'use strict'; var GenericWorker = require('./GenericWorker'); var utils = require('../utils'); /** * A worker which convert chunks to a specified type. * @constructor * @param {String} destType the destination type. */ function ConvertWorker(destType) { GenericWorker.call(this, "ConvertWorker to " + destType); this.destType = destType; } utils.inherits(ConvertWorker, GenericWorker); /** * @see GenericWorker.processChunk */ ConvertWorker.prototype.processChunk = function (chunk) { this.push({ data : utils.transformTo(this.destType, chunk.data), meta : chunk.meta }); }; module.exports = ConvertWorker; },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){ 'use strict'; var GenericWorker = require('./GenericWorker'); var crc32 = require('../crc32'); var utils = require('../utils'); /** * A worker which calculate the crc32 of the data flowing through. * @constructor */ function Crc32Probe() { GenericWorker.call(this, "Crc32Probe"); this.withStreamInfo("crc32", 0); } utils.inherits(Crc32Probe, GenericWorker); /** * @see GenericWorker.processChunk */ Crc32Probe.prototype.processChunk = function (chunk) { this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); this.push(chunk); }; module.exports = Crc32Probe; },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var GenericWorker = require('./GenericWorker'); /** * A worker which calculate the total length of the data flowing through. * @constructor * @param {String} propName the name used to expose the length */ function DataLengthProbe(propName) { GenericWorker.call(this, "DataLengthProbe for " + propName); this.propName = propName; this.withStreamInfo(propName, 0); } utils.inherits(DataLengthProbe, GenericWorker); /** * @see GenericWorker.processChunk */ DataLengthProbe.prototype.processChunk = function (chunk) { if(chunk) { var length = this.streamInfo[this.propName] || 0; this.streamInfo[this.propName] = length + chunk.data.length; } GenericWorker.prototype.processChunk.call(this, chunk); }; module.exports = DataLengthProbe; },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var GenericWorker = require('./GenericWorker'); // the size of the generated chunks // TODO expose this as a public variable var DEFAULT_BLOCK_SIZE = 16 * 1024; /** * A worker that reads a content and emits chunks. * @constructor * @param {Promise} dataP the promise of the data to split */ function DataWorker(dataP) { GenericWorker.call(this, "DataWorker"); var self = this; this.dataIsReady = false; this.index = 0; this.max = 0; this.data = null; this.type = ""; this._tickScheduled = false; dataP.then(function (data) { self.dataIsReady = true; self.data = data; self.max = data && data.length || 0; self.type = utils.getTypeOf(data); if(!self.isPaused) { self._tickAndRepeat(); } }, function (e) { self.error(e); }); } utils.inherits(DataWorker, GenericWorker); /** * @see GenericWorker.cleanUp */ DataWorker.prototype.cleanUp = function () { GenericWorker.prototype.cleanUp.call(this); this.data = null; }; /** * @see GenericWorker.resume */ DataWorker.prototype.resume = function () { if(!GenericWorker.prototype.resume.call(this)) { return false; } if (!this._tickScheduled && this.dataIsReady) { this._tickScheduled = true; utils.delay(this._tickAndRepeat, [], this); } return true; }; /** * Trigger a tick a schedule an other call to this function. */ DataWorker.prototype._tickAndRepeat = function() { this._tickScheduled = false; if(this.isPaused || this.isFinished) { return; } this._tick(); if(!this.isFinished) { utils.delay(this._tickAndRepeat, [], this); this._tickScheduled = true; } }; /** * Read and push a chunk. */ DataWorker.prototype._tick = function() { if(this.isPaused || this.isFinished) { return false; } var size = DEFAULT_BLOCK_SIZE; var data = null, nextIndex = Math.min(this.max, this.index + size); if (this.index >= this.max) { // EOF return this.end(); } else { switch(this.type) { case "string": data = this.data.substring(this.index, nextIndex); break; case "uint8array": data = this.data.subarray(this.index, nextIndex); break; case "array": case "nodebuffer": data = this.data.slice(this.index, nextIndex); break; } this.index = nextIndex; return this.push({ data : data, meta : { percent : this.max ? this.index / this.max * 100 : 0 } }); } }; module.exports = DataWorker; },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){ 'use strict'; /** * A worker that does nothing but passing chunks to the next one. This is like * a nodejs stream but with some differences. On the good side : * - it works on IE 6-9 without any issue / polyfill * - it weights less than the full dependencies bundled with browserify * - it forwards errors (no need to declare an error handler EVERYWHERE) * * A chunk is an object with 2 attributes : `meta` and `data`. The former is an * object containing anything (`percent` for example), see each worker for more * details. The latter is the real data (String, Uint8Array, etc). * * @constructor * @param {String} name the name of the stream (mainly used for debugging purposes) */ function GenericWorker(name) { // the name of the worker this.name = name || "default"; // an object containing metadata about the workers chain this.streamInfo = {}; // an error which happened when the worker was paused this.generatedError = null; // an object containing metadata to be merged by this worker into the general metadata this.extraStreamInfo = {}; // true if the stream is paused (and should not do anything), false otherwise this.isPaused = true; // true if the stream is finished (and should not do anything), false otherwise this.isFinished = false; // true if the stream is locked to prevent further structure updates (pipe), false otherwise this.isLocked = false; // the event listeners this._listeners = { 'data':[], 'end':[], 'error':[] }; // the previous worker, if any this.previous = null; } GenericWorker.prototype = { /** * Push a chunk to the next workers. * @param {Object} chunk the chunk to push */ push : function (chunk) { this.emit("data", chunk); }, /** * End the stream. * @return {Boolean} true if this call ended the worker, false otherwise. */ end : function () { if (this.isFinished) { return false; } this.flush(); try { this.emit("end"); this.cleanUp(); this.isFinished = true; } catch (e) { this.emit("error", e); } return true; }, /** * End the stream with an error. * @param {Error} e the error which caused the premature end. * @return {Boolean} true if this call ended the worker with an error, false otherwise. */ error : function (e) { if (this.isFinished) { return false; } if(this.isPaused) { this.generatedError = e; } else { this.isFinished = true; this.emit("error", e); // in the workers chain exploded in the middle of the chain, // the error event will go downward but we also need to notify // workers upward that there has been an error. if(this.previous) { this.previous.error(e); } this.cleanUp(); } return true; }, /** * Add a callback on an event. * @param {String} name the name of the event (data, end, error) * @param {Function} listener the function to call when the event is triggered * @return {GenericWorker} the current object for chainability */ on : function (name, listener) { this._listeners[name].push(listener); return this; }, /** * Clean any references when a worker is ending. */ cleanUp : function () { this.streamInfo = this.generatedError = this.extraStreamInfo = null; this._listeners = []; }, /** * Trigger an event. This will call registered callback with the provided arg. * @param {String} name the name of the event (data, end, error) * @param {Object} arg the argument to call the callback with. */ emit : function (name, arg) { if (this._listeners[name]) { for(var i = 0; i < this._listeners[name].length; i++) { this._listeners[name][i].call(this, arg); } } }, /** * Chain a worker with an other. * @param {Worker} next the worker receiving events from the current one. * @return {worker} the next worker for chainability */ pipe : function (next) { return next.registerPrevious(this); }, /** * Same as `pipe` in the other direction. * Using an API with `pipe(next)` is very easy. * Implementing the API with the point of view of the next one registering * a source is easier, see the ZipFileWorker. * @param {Worker} previous the previous worker, sending events to this one * @return {Worker} the current worker for chainability */ registerPrevious : function (previous) { if (this.isLocked) { throw new Error("The stream '" + this + "' has already been used."); } // sharing the streamInfo... this.streamInfo = previous.streamInfo; // ... and adding our own bits this.mergeStreamInfo(); this.previous = previous; var self = this; previous.on('data', function (chunk) { self.processChunk(chunk); }); previous.on('end', function () { self.end(); }); previous.on('error', function (e) { self.error(e); }); return this; }, /** * Pause the stream so it doesn't send events anymore. * @return {Boolean} true if this call paused the worker, false otherwise. */ pause : function () { if(this.isPaused || this.isFinished) { return false; } this.isPaused = true; if(this.previous) { this.previous.pause(); } return true; }, /** * Resume a paused stream. * @return {Boolean} true if this call resumed the worker, false otherwise. */ resume : function () { if(!this.isPaused || this.isFinished) { return false; } this.isPaused = false; // if true, the worker tried to resume but failed var withError = false; if(this.generatedError) { this.error(this.generatedError); withError = true; } if(this.previous) { this.previous.resume(); } return !withError; }, /** * Flush any remaining bytes as the stream is ending. */ flush : function () {}, /** * Process a chunk. This is usually the method overridden. * @param {Object} chunk the chunk to process. */ processChunk : function(chunk) { this.push(chunk); }, /** * Add a key/value to be added in the workers chain streamInfo once activated. * @param {String} key the key to use * @param {Object} value the associated value * @return {Worker} the current worker for chainability */ withStreamInfo : function (key, value) { this.extraStreamInfo[key] = value; this.mergeStreamInfo(); return this; }, /** * Merge this worker's streamInfo into the chain's streamInfo. */ mergeStreamInfo : function () { for(var key in this.extraStreamInfo) { if (!this.extraStreamInfo.hasOwnProperty(key)) { continue; } this.streamInfo[key] = this.extraStreamInfo[key]; } }, /** * Lock the stream to prevent further updates on the workers chain. * After calling this method, all calls to pipe will fail. */ lock: function () { if (this.isLocked) { throw new Error("The stream '" + this + "' has already been used."); } this.isLocked = true; if (this.previous) { this.previous.lock(); } }, /** * * Pretty print the workers chain. */ toString : function () { var me = "Worker " + this.name; if (this.previous) { return this.previous + " -> " + me; } else { return me; } } }; module.exports = GenericWorker; },{}],29:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var ConvertWorker = require('./ConvertWorker'); var GenericWorker = require('./GenericWorker'); var base64 = require('../base64'); var support = require("../support"); var external = require("../external"); var NodejsStreamOutputAdapter = null; if (support.nodestream) { try { NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter'); } catch(e) {} } /** * Apply the final transformation of the data. If the user wants a Blob for * example, it's easier to work with an U8intArray and finally do the * ArrayBuffer/Blob conversion. * @param {String} type the name of the final type * @param {String|Uint8Array|Buffer} content the content to transform * @param {String} mimeType the mime type of the content, if applicable. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format. */ function transformZipOutput(type, content, mimeType) { switch(type) { case "blob" : return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType); case "base64" : return base64.encode(content); default : return utils.transformTo(type, content); } } /** * Concatenate an array of data of the given type. * @param {String} type the type of the data in the given array. * @param {Array} dataArray the array containing the data chunks to concatenate * @return {String|Uint8Array|Buffer} the concatenated data * @throws Error if the asked type is unsupported */ function concat (type, dataArray) { var i, index = 0, res = null, totalLength = 0; for(i = 0; i < dataArray.length; i++) { totalLength += dataArray[i].length; } switch(type) { case "string": return dataArray.join(""); case "array": return Array.prototype.concat.apply([], dataArray); case "uint8array": res = new Uint8Array(totalLength); for(i = 0; i < dataArray.length; i++) { res.set(dataArray[i], index); index += dataArray[i].length; } return res; case "nodebuffer": return Buffer.concat(dataArray); default: throw new Error("concat : unsupported type '" + type + "'"); } } /** * Listen a StreamHelper, accumulate its content and concatenate it into a * complete block. * @param {StreamHelper} helper the helper to use. * @param {Function} updateCallback a callback called on each update. Called * with one arg : * - the metadata linked to the update received. * @return Promise the promise for the accumulation. */ function accumulate(helper, updateCallback) { return new external.Promise(function (resolve, reject){ var dataArray = []; var chunkType = helper._internalType, resultType = helper._outputType, mimeType = helper._mimeType; helper .on('data', function (data, meta) { dataArray.push(data); if(updateCallback) { updateCallback(meta); } }) .on('error', function(err) { dataArray = []; reject(err); }) .on('end', function (){ try { var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); resolve(result); } catch (e) { reject(e); } dataArray = []; }) .resume(); }); } /** * An helper to easily use workers outside of JSZip. * @constructor * @param {Worker} worker the worker to wrap * @param {String} outputType the type of data expected by the use * @param {String} mimeType the mime type of the content, if applicable. */ function StreamHelper(worker, outputType, mimeType) { var internalType = outputType; switch(outputType) { case "blob": case "arraybuffer": internalType = "uint8array"; break; case "base64": internalType = "string"; break; } try { // the type used internally this._internalType = internalType; // the type used to output results this._outputType = outputType; // the mime type this._mimeType = mimeType; utils.checkSupport(internalType); this._worker = worker.pipe(new ConvertWorker(internalType)); // the last workers can be rewired without issues but we need to // prevent any updates on previous workers. worker.lock(); } catch(e) { this._worker = new GenericWorker("error"); this._worker.error(e); } } StreamHelper.prototype = { /** * Listen a StreamHelper, accumulate its content and concatenate it into a * complete block. * @param {Function} updateCb the update callback. * @return Promise the promise for the accumulation. */ accumulate : function (updateCb) { return accumulate(this, updateCb); }, /** * Add a listener on an event triggered on a stream. * @param {String} evt the name of the event * @param {Function} fn the listener * @return {StreamHelper} the current helper. */ on : function (evt, fn) { var self = this; if(evt === "data") { this._worker.on(evt, function (chunk) { fn.call(self, chunk.data, chunk.meta); }); } else { this._worker.on(evt, function () { utils.delay(fn, arguments, self); }); } return this; }, /** * Resume the flow of chunks. * @return {StreamHelper} the current helper. */ resume : function () { utils.delay(this._worker.resume, [], this._worker); return this; }, /** * Pause the flow of chunks. * @return {StreamHelper} the current helper. */ pause : function () { this._worker.pause(); return this; }, /** * Return a nodejs stream for this helper. * @param {Function} updateCb the update callback. * @return {NodejsStreamOutputAdapter} the nodejs stream. */ toNodejsStream : function (updateCb) { utils.checkSupport("nodestream"); if (this._outputType !== "nodebuffer") { // an object stream containing blob/arraybuffer/uint8array/string // is strange and I don't know if it would be useful. // I you find this comment and have a good usecase, please open a // bug report ! throw new Error(this._outputType + " is not supported by this method"); } return new NodejsStreamOutputAdapter(this, { objectMode : this._outputType !== "nodebuffer" }, updateCb); } }; module.exports = StreamHelper; },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){ 'use strict'; exports.base64 = true; exports.array = true; exports.string = true; exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; exports.nodebuffer = typeof Buffer !== "undefined"; // contains true if JSZip can read/generate Uint8Array, false otherwise. exports.uint8array = typeof Uint8Array !== "undefined"; if (typeof ArrayBuffer === "undefined") { exports.blob = false; } else { var buffer = new ArrayBuffer(0); try { exports.blob = new Blob([buffer], { type: "application/zip" }).size === 0; } catch (e) { try { var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; var builder = new Builder(); builder.append(buffer); exports.blob = builder.getBlob('application/zip').size === 0; } catch (e) { exports.blob = false; } } } try { exports.nodestream = !!require('readable-stream').Readable; } catch(e) { exports.nodestream = false; } },{"readable-stream":16}],31:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var support = require('./support'); var nodejsUtils = require('./nodejsUtils'); var GenericWorker = require('./stream/GenericWorker'); /** * The following functions come from pako, from pako/lib/utils/strings * released under the MIT license, see pako https://github.com/nodeca/pako/ */ // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new Array(256); for (var i=0; i<256; i++) { _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) var string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer if (support.uint8array) { buf = new Uint8Array(buf_len); } else { buf = new Array(buf_len); } // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); var utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; // convert array to string var buf2string = function (buf) { var str, i, out, c, c_len; var len = buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } // shrinkBuf(utf16buf, out) if (utf16buf.length !== out) { if(utf16buf.subarray) { utf16buf = utf16buf.subarray(0, out); } else { utf16buf.length = out; } } // return String.fromCharCode.apply(null, utf16buf); return utils.applyFromCharCode(utf16buf); }; // That's all for the pako functions. /** * Transform a javascript string into an array (typed if possible) of bytes, * UTF-8 encoded. * @param {String} str the string to encode * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. */ exports.utf8encode = function utf8encode(str) { if (support.nodebuffer) { return nodejsUtils.newBufferFrom(str, "utf-8"); } return string2buf(str); }; /** * Transform a bytes array (or a representation) representing an UTF-8 encoded * string into a javascript string. * @param {Array|Uint8Array|Buffer} buf the data de decode * @return {String} the decoded string. */ exports.utf8decode = function utf8decode(buf) { if (support.nodebuffer) { return utils.transformTo("nodebuffer", buf).toString("utf-8"); } buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); return buf2string(buf); }; /** * A worker to decode utf8 encoded binary chunks into string chunks. * @constructor */ function Utf8DecodeWorker() { GenericWorker.call(this, "utf-8 decode"); // the last bytes if a chunk didn't end with a complete codepoint. this.leftOver = null; } utils.inherits(Utf8DecodeWorker, GenericWorker); /** * @see GenericWorker.processChunk */ Utf8DecodeWorker.prototype.processChunk = function (chunk) { var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); // 1st step, re-use what's left of the previous chunk if (this.leftOver && this.leftOver.length) { if(support.uint8array) { var previousData = data; data = new Uint8Array(previousData.length + this.leftOver.length); data.set(this.leftOver, 0); data.set(previousData, this.leftOver.length); } else { data = this.leftOver.concat(data); } this.leftOver = null; } var nextBoundary = utf8border(data); var usableData = data; if (nextBoundary !== data.length) { if (support.uint8array) { usableData = data.subarray(0, nextBoundary); this.leftOver = data.subarray(nextBoundary, data.length); } else { usableData = data.slice(0, nextBoundary); this.leftOver = data.slice(nextBoundary, data.length); } } this.push({ data : exports.utf8decode(usableData), meta : chunk.meta }); }; /** * @see GenericWorker.flush */ Utf8DecodeWorker.prototype.flush = function () { if(this.leftOver && this.leftOver.length) { this.push({ data : exports.utf8decode(this.leftOver), meta : {} }); this.leftOver = null; } }; exports.Utf8DecodeWorker = Utf8DecodeWorker; /** * A worker to endcode string chunks into utf8 encoded binary chunks. * @constructor */ function Utf8EncodeWorker() { GenericWorker.call(this, "utf-8 encode"); } utils.inherits(Utf8EncodeWorker, GenericWorker); /** * @see GenericWorker.processChunk */ Utf8EncodeWorker.prototype.processChunk = function (chunk) { this.push({ data : exports.utf8encode(chunk.data), meta : chunk.meta }); }; exports.Utf8EncodeWorker = Utf8EncodeWorker; },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){ 'use strict'; var support = require('./support'); var base64 = require('./base64'); var nodejsUtils = require('./nodejsUtils'); var setImmediate = require('set-immediate-shim'); var external = require("./external"); /** * Convert a string that pass as a "binary string": it should represent a byte * array but may have > 255 char codes. Be sure to take only the first byte * and returns the byte array. * @param {String} str the string to transform. * @return {Array|Uint8Array} the string in a binary format. */ function string2binary(str) { var result = null; if (support.uint8array) { result = new Uint8Array(str.length); } else { result = new Array(str.length); } return stringToArrayLike(str, result); } /** * Create a new blob with the given content and the given type. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use * an Uint8Array because the stock browser of android 4 won't accept it (it * will be silently converted to a string, "[object Uint8Array]"). * * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge: * when a large amount of Array is used to create the Blob, the amount of * memory consumed is nearly 100 times the original data amount. * * @param {String} type the mime type of the blob. * @return {Blob} the created blob. */ exports.newBlob = function(part, type) { exports.checkSupport("blob"); try { // Blob constructor return new Blob([part], { type: type }); } catch (e) { try { // deprecated, browser only, old way var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; var builder = new Builder(); builder.append(part); return builder.getBlob(type); } catch (e) { // well, fuck ?! throw new Error("Bug : can't construct the Blob."); } } }; /** * The identity function. * @param {Object} input the input. * @return {Object} the same input. */ function identity(input) { return input; } /** * Fill in an array with a string. * @param {String} str the string to use. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. */ function stringToArrayLike(str, array) { for (var i = 0; i < str.length; ++i) { array[i] = str.charCodeAt(i) & 0xFF; } return array; } /** * An helper for the function arrayLikeToString. * This contains static information and functions that * can be optimized by the browser JIT compiler. */ var arrayToStringHelper = { /** * Transform an array of int into a string, chunk by chunk. * See the performances notes on arrayLikeToString. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @param {String} type the type of the array. * @param {Integer} chunk the chunk size. * @return {String} the resulting string. * @throws Error if the chunk is too big for the stack. */ stringifyByChunk: function(array, type, chunk) { var result = [], k = 0, len = array.length; // shortcut if (len <= chunk) { return String.fromCharCode.apply(null, array); } while (k < len) { if (type === "array" || type === "nodebuffer") { result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); } else { result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); } k += chunk; } return result.join(""); }, /** * Call String.fromCharCode on every item in the array. * This is the naive implementation, which generate A LOT of intermediate string. * This should be used when everything else fail. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @return {String} the result. */ stringifyByChar: function(array){ var resultStr = ""; for(var i = 0; i < array.length; i++) { resultStr += String.fromCharCode(array[i]); } return resultStr; }, applyCanBeUsed : { /** * true if the browser accepts to use String.fromCharCode on Uint8Array */ uint8array : (function () { try { return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; } catch (e) { return false; } })(), /** * true if the browser accepts to use String.fromCharCode on nodejs Buffer. */ nodebuffer : (function () { try { return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; } catch (e) { return false; } })() } }; /** * Transform an array-like object to a string. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @return {String} the result. */ function arrayLikeToString(array) { // Performances notes : // -------------------- // String.fromCharCode.apply(null, array) is the fastest, see // see http://jsperf.com/converting-a-uint8array-to-a-string/2 // but the stack is limited (and we can get huge arrays !). // // result += String.fromCharCode(array[i]); generate too many strings ! // // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 // TODO : we now have workers that split the work. Do we still need that ? var chunk = 65536, type = exports.getTypeOf(array), canUseApply = true; if (type === "uint8array") { canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; } else if (type === "nodebuffer") { canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; } if (canUseApply) { while (chunk > 1) { try { return arrayToStringHelper.stringifyByChunk(array, type, chunk); } catch (e) { chunk = Math.floor(chunk / 2); } } } // no apply or chunk error : slow and painful algorithm // default browser on android 4.* return arrayToStringHelper.stringifyByChar(array); } exports.applyFromCharCode = arrayLikeToString; /** * Copy the data from an array-like to an other array-like. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. */ function arrayLikeToArrayLike(arrayFrom, arrayTo) { for (var i = 0; i < arrayFrom.length; i++) { arrayTo[i] = arrayFrom[i]; } return arrayTo; } // a matrix containing functions to transform everything into everything. var transform = {}; // string to ? transform["string"] = { "string": identity, "array": function(input) { return stringToArrayLike(input, new Array(input.length)); }, "arraybuffer": function(input) { return transform["string"]["uint8array"](input).buffer; }, "uint8array": function(input) { return stringToArrayLike(input, new Uint8Array(input.length)); }, "nodebuffer": function(input) { return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); } }; // array to ? transform["array"] = { "string": arrayLikeToString, "array": identity, "arraybuffer": function(input) { return (new Uint8Array(input)).buffer; }, "uint8array": function(input) { return new Uint8Array(input); }, "nodebuffer": function(input) { return nodejsUtils.newBufferFrom(input); } }; // arraybuffer to ? transform["arraybuffer"] = { "string": function(input) { return arrayLikeToString(new Uint8Array(input)); }, "array": function(input) { return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); }, "arraybuffer": identity, "uint8array": function(input) { return new Uint8Array(input); }, "nodebuffer": function(input) { return nodejsUtils.newBufferFrom(new Uint8Array(input)); } }; // uint8array to ? transform["uint8array"] = { "string": arrayLikeToString, "array": function(input) { return arrayLikeToArrayLike(input, new Array(input.length)); }, "arraybuffer": function(input) { return input.buffer; }, "uint8array": identity, "nodebuffer": function(input) { return nodejsUtils.newBufferFrom(input); } }; // nodebuffer to ? transform["nodebuffer"] = { "string": arrayLikeToString, "array": function(input) { return arrayLikeToArrayLike(input, new Array(input.length)); }, "arraybuffer": function(input) { return transform["nodebuffer"]["uint8array"](input).buffer; }, "uint8array": function(input) { return arrayLikeToArrayLike(input, new Uint8Array(input.length)); }, "nodebuffer": identity }; /** * Transform an input into any type. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. * If no output type is specified, the unmodified input will be returned. * @param {String} outputType the output type. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. * @throws {Error} an Error if the browser doesn't support the requested output type. */ exports.transformTo = function(outputType, input) { if (!input) { // undefined, null, etc // an empty string won't harm. input = ""; } if (!outputType) { return input; } exports.checkSupport(outputType); var inputType = exports.getTypeOf(input); var result = transform[inputType][outputType](input); return result; }; /** * Return the type of the input. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. * @param {Object} input the input to identify. * @return {String} the (lowercase) type of the input. */ exports.getTypeOf = function(input) { if (typeof input === "string") { return "string"; } if (Object.prototype.toString.call(input) === "[object Array]") { return "array"; } if (support.nodebuffer && nodejsUtils.isBuffer(input)) { return "nodebuffer"; } if (support.uint8array && input instanceof Uint8Array) { return "uint8array"; } if (support.arraybuffer && input instanceof ArrayBuffer) { return "arraybuffer"; } }; /** * Throw an exception if the type is not supported. * @param {String} type the type to check. * @throws {Error} an Error if the browser doesn't support the requested type. */ exports.checkSupport = function(type) { var supported = support[type.toLowerCase()]; if (!supported) { throw new Error(type + " is not supported by this platform"); } }; exports.MAX_VALUE_16BITS = 65535; exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 /** * Prettify a string read as binary. * @param {string} str the string to prettify. * @return {string} a pretty string. */ exports.pretty = function(str) { var res = '', code, i; for (i = 0; i < (str || "").length; i++) { code = str.charCodeAt(i); res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); } return res; }; /** * Defer the call of a function. * @param {Function} callback the function to call asynchronously. * @param {Array} args the arguments to give to the callback. */ exports.delay = function(callback, args, self) { setImmediate(function () { callback.apply(self || null, args || []); }); }; /** * Extends a prototype with an other, without calling a constructor with * side effects. Inspired by nodejs' `utils.inherits` * @param {Function} ctor the constructor to augment * @param {Function} superCtor the parent constructor to use */ exports.inherits = function (ctor, superCtor) { var Obj = function() {}; Obj.prototype = superCtor.prototype; ctor.prototype = new Obj(); }; /** * Merge the objects passed as parameters into a new one. * @private * @param {...Object} var_args All objects to merge. * @return {Object} a new object with the data of the others. */ exports.extend = function() { var result = {}, i, attr; for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers for (attr in arguments[i]) { if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { result[attr] = arguments[i][attr]; } } } return result; }; /** * Transform arbitrary content into a Promise. * @param {String} name a name for the content being processed. * @param {Object} inputData the content to process. * @param {Boolean} isBinary true if the content is not an unicode string * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character. * @param {Boolean} isBase64 true if the string content is encoded with base64. * @return {Promise} a promise in a format usable by JSZip. */ exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) { // if inputData is already a promise, this flatten it. var promise = external.Promise.resolve(inputData).then(function(data) { var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1); if (isBlob && typeof FileReader !== "undefined") { return new external.Promise(function (resolve, reject) { var reader = new FileReader(); reader.onload = function(e) { resolve(e.target.result); }; reader.onerror = function(e) { reject(e.target.error); }; reader.readAsArrayBuffer(data); }); } else { return data; } }); return promise.then(function(data) { var dataType = exports.getTypeOf(data); if (!dataType) { return external.Promise.reject( new Error("Can't read the data of '" + name + "'. Is it " + "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?") ); } // special case : it's way easier to work with Uint8Array than with ArrayBuffer if (dataType === "arraybuffer") { data = exports.transformTo("uint8array", data); } else if (dataType === "string") { if (isBase64) { data = base64.decode(data); } else if (isBinary) { // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask if (isOptimizedBinaryString !== true) { // this is a string, not in a base64 format. // Be sure that this is a correct "binary string" data = string2binary(data); } } } return data; }); }; },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"set-immediate-shim":54}],33:[function(require,module,exports){ 'use strict'; var readerFor = require('./reader/readerFor'); var utils = require('./utils'); var sig = require('./signature'); var ZipEntry = require('./zipEntry'); var utf8 = require('./utf8'); var support = require('./support'); // class ZipEntries {{{ /** * All the entries in the zip file. * @constructor * @param {Object} loadOptions Options for loading the stream. */ function ZipEntries(loadOptions) { this.files = []; this.loadOptions = loadOptions; } ZipEntries.prototype = { /** * Check that the reader is on the specified signature. * @param {string} expectedSignature the expected signature. * @throws {Error} if it is an other signature. */ checkSignature: function(expectedSignature) { if (!this.reader.readAndCheckSignature(expectedSignature)) { this.reader.index -= 4; var signature = this.reader.readString(4); throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); } }, /** * Check if the given signature is at the given index. * @param {number} askedIndex the index to check. * @param {string} expectedSignature the signature to expect. * @return {boolean} true if the signature is here, false otherwise. */ isSignature: function(askedIndex, expectedSignature) { var currentIndex = this.reader.index; this.reader.setIndex(askedIndex); var signature = this.reader.readString(4); var result = signature === expectedSignature; this.reader.setIndex(currentIndex); return result; }, /** * Read the end of the central directory. */ readBlockEndOfCentral: function() { this.diskNumber = this.reader.readInt(2); this.diskWithCentralDirStart = this.reader.readInt(2); this.centralDirRecordsOnThisDisk = this.reader.readInt(2); this.centralDirRecords = this.reader.readInt(2); this.centralDirSize = this.reader.readInt(4); this.centralDirOffset = this.reader.readInt(4); this.zipCommentLength = this.reader.readInt(2); // warning : the encoding depends of the system locale // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. // On a windows machine, this field is encoded with the localized windows code page. var zipComment = this.reader.readData(this.zipCommentLength); var decodeParamType = support.uint8array ? "uint8array" : "array"; // To get consistent behavior with the generation part, we will assume that // this is utf8 encoded unless specified otherwise. var decodeContent = utils.transformTo(decodeParamType, zipComment); this.zipComment = this.loadOptions.decodeFileName(decodeContent); }, /** * Read the end of the Zip 64 central directory. * Not merged with the method readEndOfCentral : * The end of central can coexist with its Zip64 brother, * I don't want to read the wrong number of bytes ! */ readBlockZip64EndOfCentral: function() { this.zip64EndOfCentralSize = this.reader.readInt(8); this.reader.skip(4); // this.versionMadeBy = this.reader.readString(2); // this.versionNeeded = this.reader.readInt(2); this.diskNumber = this.reader.readInt(4); this.diskWithCentralDirStart = this.reader.readInt(4); this.centralDirRecordsOnThisDisk = this.reader.readInt(8); this.centralDirRecords = this.reader.readInt(8); this.centralDirSize = this.reader.readInt(8); this.centralDirOffset = this.reader.readInt(8); this.zip64ExtensibleData = {}; var extraDataSize = this.zip64EndOfCentralSize - 44, index = 0, extraFieldId, extraFieldLength, extraFieldValue; while (index < extraDataSize) { extraFieldId = this.reader.readInt(2); extraFieldLength = this.reader.readInt(4); extraFieldValue = this.reader.readData(extraFieldLength); this.zip64ExtensibleData[extraFieldId] = { id: extraFieldId, length: extraFieldLength, value: extraFieldValue }; } }, /** * Read the end of the Zip 64 central directory locator. */ readBlockZip64EndOfCentralLocator: function() { this.diskWithZip64CentralDirStart = this.reader.readInt(4); this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); this.disksCount = this.reader.readInt(4); if (this.disksCount > 1) { throw new Error("Multi-volumes zip are not supported"); } }, /** * Read the local files, based on the offset read in the central part. */ readLocalFiles: function() { var i, file; for (i = 0; i < this.files.length; i++) { file = this.files[i]; this.reader.setIndex(file.localHeaderOffset); this.checkSignature(sig.LOCAL_FILE_HEADER); file.readLocalPart(this.reader); file.handleUTF8(); file.processAttributes(); } }, /** * Read the central directory. */ readCentralDir: function() { var file; this.reader.setIndex(this.centralDirOffset); while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { file = new ZipEntry({ zip64: this.zip64 }, this.loadOptions); file.readCentralPart(this.reader); this.files.push(file); } if (this.centralDirRecords !== this.files.length) { if (this.centralDirRecords !== 0 && this.files.length === 0) { // We expected some records but couldn't find ANY. // This is really suspicious, as if something went wrong. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); } else { // We found some records but not all. // Something is wrong but we got something for the user: no error here. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length); } } }, /** * Read the end of central directory. */ readEndOfCentral: function() { var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); if (offset < 0) { // Check if the content is a truncated zip or complete garbage. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto // extractible zip for example) but it can give a good hint. // If an ajax request was used without responseType, we will also // get unreadable data. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); if (isGarbage) { throw new Error("Can't find end of central directory : is this a zip file ? " + "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); } else { throw new Error("Corrupted zip: can't find end of central directory"); } } this.reader.setIndex(offset); var endOfCentralDirOffset = offset; this.checkSignature(sig.CENTRAL_DIRECTORY_END); this.readBlockEndOfCentral(); /* extract from the zip spec : 4) If one of the fields in the end of central directory record is too small to hold required data, the field should be set to -1 (0xFFFF or 0xFFFFFFFF) and the ZIP64 format record should be created. 5) The end of central directory record and the Zip64 end of central directory locator record must reside on the same disk when splitting or spanning an archive. */ if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { this.zip64 = true; /* Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents all numbers as 64-bit double precision IEEE 754 floating point numbers. So, we have 53bits for integers and bitwise operations treat everything as 32bits. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 */ // should look for a zip64 EOCD locator offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); if (offset < 0) { throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); } this.reader.setIndex(offset); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); this.readBlockZip64EndOfCentralLocator(); // now the zip64 EOCD record if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { // console.warn("ZIP64 end of central directory not where expected."); this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); if (this.relativeOffsetEndOfZip64CentralDir < 0) { throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); } } this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); this.readBlockZip64EndOfCentral(); } var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; if (this.zip64) { expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize; } var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; if (extraBytes > 0) { // console.warn(extraBytes, "extra bytes at beginning or within zipfile"); if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { // The offsets seem wrong, but we have something at the specified offset. // So… we keep it. } else { // the offset is wrong, update the "zero" of the reader // this happens if data has been prepended (crx files for example) this.reader.zero = extraBytes; } } else if (extraBytes < 0) { throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); } }, prepareReader: function(data) { this.reader = readerFor(data); }, /** * Read a zip file and create ZipEntries. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. */ load: function(data) { this.prepareReader(data); this.readEndOfCentral(); this.readCentralDir(); this.readLocalFiles(); } }; // }}} end of ZipEntries module.exports = ZipEntries; },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){ 'use strict'; var readerFor = require('./reader/readerFor'); var utils = require('./utils'); var CompressedObject = require('./compressedObject'); var crc32fn = require('./crc32'); var utf8 = require('./utf8'); var compressions = require('./compressions'); var support = require('./support'); var MADE_BY_DOS = 0x00; var MADE_BY_UNIX = 0x03; /** * Find a compression registered in JSZip. * @param {string} compressionMethod the method magic to find. * @return {Object|null} the JSZip compression object, null if none found. */ var findCompression = function(compressionMethod) { for (var method in compressions) { if (!compressions.hasOwnProperty(method)) { continue; } if (compressions[method].magic === compressionMethod) { return compressions[method]; } } return null; }; // class ZipEntry {{{ /** * An entry in the zip file. * @constructor * @param {Object} options Options of the current file. * @param {Object} loadOptions Options for loading the stream. */ function ZipEntry(options, loadOptions) { this.options = options; this.loadOptions = loadOptions; } ZipEntry.prototype = { /** * say if the file is encrypted. * @return {boolean} true if the file is encrypted, false otherwise. */ isEncrypted: function() { // bit 1 is set return (this.bitFlag & 0x0001) === 0x0001; }, /** * say if the file has utf-8 filename/comment. * @return {boolean} true if the filename/comment is in utf-8, false otherwise. */ useUTF8: function() { // bit 11 is set return (this.bitFlag & 0x0800) === 0x0800; }, /** * Read the local part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readLocalPart: function(reader) { var compression, localExtraFieldsLength; // we already know everything from the central dir ! // If the central dir data are false, we are doomed. // On the bright side, the local part is scary : zip64, data descriptors, both, etc. // The less data we get here, the more reliable this should be. // Let's skip the whole header and dash to the data ! reader.skip(22); // in some zip created on windows, the filename stored in the central dir contains \ instead of /. // Strangely, the filename here is OK. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... // Search "unzip mismatching "local" filename continuing with "central" filename version" on // the internet. // // I think I see the logic here : the central directory is used to display // content and the local directory is used to extract the files. Mixing / and \ // may be used to display \ to windows users and use / when extracting the files. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 this.fileNameLength = reader.readInt(2); localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding. this.fileName = reader.readData(this.fileNameLength); reader.skip(localExtraFieldsLength); if (this.compressedSize === -1 || this.uncompressedSize === -1) { throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); } compression = findCompression(this.compressionMethod); if (compression === null) { // no compression found throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); } this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); }, /** * Read the central part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readCentralPart: function(reader) { this.versionMadeBy = reader.readInt(2); reader.skip(2); // this.versionNeeded = reader.readInt(2); this.bitFlag = reader.readInt(2); this.compressionMethod = reader.readString(2); this.date = reader.readDate(); this.crc32 = reader.readInt(4); this.compressedSize = reader.readInt(4); this.uncompressedSize = reader.readInt(4); var fileNameLength = reader.readInt(2); this.extraFieldsLength = reader.readInt(2); this.fileCommentLength = reader.readInt(2); this.diskNumberStart = reader.readInt(2); this.internalFileAttributes = reader.readInt(2); this.externalFileAttributes = reader.readInt(4); this.localHeaderOffset = reader.readInt(4); if (this.isEncrypted()) { throw new Error("Encrypted zip are not supported"); } // will be read in the local part, see the comments there reader.skip(fileNameLength); this.readExtraFields(reader); this.parseZIP64ExtraField(reader); this.fileComment = reader.readData(this.fileCommentLength); }, /** * Parse the external file attributes and get the unix/dos permissions. */ processAttributes: function () { this.unixPermissions = null; this.dosPermissions = null; var madeBy = this.versionMadeBy >> 8; // Check if we have the DOS directory flag set. // We look for it in the DOS and UNIX permissions // but some unknown platform could set it as a compatibility flag. this.dir = this.externalFileAttributes & 0x0010 ? true : false; if(madeBy === MADE_BY_DOS) { // first 6 bits (0 to 5) this.dosPermissions = this.externalFileAttributes & 0x3F; } if(madeBy === MADE_BY_UNIX) { this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF; // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); } // fail safe : if the name ends with a / it probably means a folder if (!this.dir && this.fileNameStr.slice(-1) === '/') { this.dir = true; } }, /** * Parse the ZIP64 extra field and merge the info in the current ZipEntry. * @param {DataReader} reader the reader to use. */ parseZIP64ExtraField: function(reader) { if (!this.extraFields[0x0001]) { return; } // should be something, preparing the extra reader var extraReader = readerFor(this.extraFields[0x0001].value); // I really hope that these 64bits integer can fit in 32 bits integer, because js // won't let us have more. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { this.uncompressedSize = extraReader.readInt(8); } if (this.compressedSize === utils.MAX_VALUE_32BITS) { this.compressedSize = extraReader.readInt(8); } if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { this.localHeaderOffset = extraReader.readInt(8); } if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { this.diskNumberStart = extraReader.readInt(4); } }, /** * Read the central part of a zip file and add the info in this object. * @param {DataReader} reader the reader to use. */ readExtraFields: function(reader) { var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; if (!this.extraFields) { this.extraFields = {}; } while (reader.index + 4 < end) { extraFieldId = reader.readInt(2); extraFieldLength = reader.readInt(2); extraFieldValue = reader.readData(extraFieldLength); this.extraFields[extraFieldId] = { id: extraFieldId, length: extraFieldLength, value: extraFieldValue }; } reader.setIndex(end); }, /** * Apply an UTF8 transformation if needed. */ handleUTF8: function() { var decodeParamType = support.uint8array ? "uint8array" : "array"; if (this.useUTF8()) { this.fileNameStr = utf8.utf8decode(this.fileName); this.fileCommentStr = utf8.utf8decode(this.fileComment); } else { var upath = this.findExtraFieldUnicodePath(); if (upath !== null) { this.fileNameStr = upath; } else { // ASCII text or unsupported code page var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); } var ucomment = this.findExtraFieldUnicodeComment(); if (ucomment !== null) { this.fileCommentStr = ucomment; } else { // ASCII text or unsupported code page var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); } } }, /** * Find the unicode path declared in the extra field, if any. * @return {String} the unicode path, null otherwise. */ findExtraFieldUnicodePath: function() { var upathField = this.extraFields[0x7075]; if (upathField) { var extraReader = readerFor(upathField.value); // wrong version if (extraReader.readInt(1) !== 1) { return null; } // the crc of the filename changed, this field is out of date. if (crc32fn(this.fileName) !== extraReader.readInt(4)) { return null; } return utf8.utf8decode(extraReader.readData(upathField.length - 5)); } return null; }, /** * Find the unicode comment declared in the extra field, if any. * @return {String} the unicode comment, null otherwise. */ findExtraFieldUnicodeComment: function() { var ucommentField = this.extraFields[0x6375]; if (ucommentField) { var extraReader = readerFor(ucommentField.value); // wrong version if (extraReader.readInt(1) !== 1) { return null; } // the crc of the comment changed, this field is out of date. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { return null; } return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); } return null; } }; module.exports = ZipEntry; },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){ 'use strict'; var StreamHelper = require('./stream/StreamHelper'); var DataWorker = require('./stream/DataWorker'); var utf8 = require('./utf8'); var CompressedObject = require('./compressedObject'); var GenericWorker = require('./stream/GenericWorker'); /** * A simple object representing a file in the zip file. * @constructor * @param {string} name the name of the file * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data * @param {Object} options the options of the file */ var ZipObject = function(name, data, options) { this.name = name; this.dir = options.dir; this.date = options.date; this.comment = options.comment; this.unixPermissions = options.unixPermissions; this.dosPermissions = options.dosPermissions; this._data = data; this._dataBinary = options.binary; // keep only the compression this.options = { compression : options.compression, compressionOptions : options.compressionOptions }; }; ZipObject.prototype = { /** * Create an internal stream for the content of this object. * @param {String} type the type of each chunk. * @return StreamHelper the stream. */ internalStream: function (type) { var result = null, outputType = "string"; try { if (!type) { throw new Error("No output type specified."); } outputType = type.toLowerCase(); var askUnicodeString = outputType === "string" || outputType === "text"; if (outputType === "binarystring" || outputType === "text") { outputType = "string"; } result = this._decompressWorker(); var isUnicodeString = !this._dataBinary; if (isUnicodeString && !askUnicodeString) { result = result.pipe(new utf8.Utf8EncodeWorker()); } if (!isUnicodeString && askUnicodeString) { result = result.pipe(new utf8.Utf8DecodeWorker()); } } catch (e) { result = new GenericWorker("error"); result.error(e); } return new StreamHelper(result, outputType, ""); }, /** * Prepare the content in the asked type. * @param {String} type the type of the result. * @param {Function} onUpdate a function to call on each internal update. * @return Promise the promise of the result. */ async: function (type, onUpdate) { return this.internalStream(type).accumulate(onUpdate); }, /** * Prepare the content as a nodejs stream. * @param {String} type the type of each chunk. * @param {Function} onUpdate a function to call on each internal update. * @return Stream the stream. */ nodeStream: function (type, onUpdate) { return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); }, /** * Return a worker for the compressed content. * @private * @param {Object} compression the compression object to use. * @param {Object} compressionOptions the options to use when compressing. * @return Worker the worker. */ _compressWorker: function (compression, compressionOptions) { if ( this._data instanceof CompressedObject && this._data.compression.magic === compression.magic ) { return this._data.getCompressedWorker(); } else { var result = this._decompressWorker(); if(!this._dataBinary) { result = result.pipe(new utf8.Utf8EncodeWorker()); } return CompressedObject.createWorkerFrom(result, compression, compressionOptions); } }, /** * Return a worker for the decompressed content. * @private * @return Worker the worker. */ _decompressWorker : function () { if (this._data instanceof CompressedObject) { return this._data.getContentWorker(); } else if (this._data instanceof GenericWorker) { return this._data; } else { return new DataWorker(this._data); } } }; var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; var removedFn = function () { throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); }; for(var i = 0; i < removedMethods.length; i++) { ZipObject.prototype[removedMethods[i]] = removedFn; } module.exports = ZipObject; },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){ (function (global){ 'use strict'; var Mutation = global.MutationObserver || global.WebKitMutationObserver; var scheduleDrain; { if (Mutation) { var called = 0; var observer = new Mutation(nextTick); var element = global.document.createTextNode(''); observer.observe(element, { characterData: true }); scheduleDrain = function () { element.data = (called = ++called % 2); }; } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { var channel = new global.MessageChannel(); channel.port1.onmessage = nextTick; scheduleDrain = function () { channel.port2.postMessage(0); }; } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { scheduleDrain = function () { // Create a '; if (navigator.userAgent.indexOf("Firefox") != -1) { let c = unsafeWindow.open("", "_blank"); c.document.write(html); c.document.close(); } else { _GM_openInTab('data:text/html;charset=utf-8,' + encodeURIComponent(html),{active:true}); } }, copyImages: function(isAlert) { var nodes = this.eleMaps['sidebar-thumbnails-container'].querySelectorAll('.pv-gallery-sidebar-thumb-container[data-src]'); var urls = []; [].forEach.call(nodes, function(node){ if(unsafeWindow.getComputedStyle(node).display!="none"){ urls.push(node.dataset.src); } }); let copyData = urls.join("\n"); _GM_setClipboard(copyData); this.urlsTextarea.value = copyData; this.urlsTextareaCon.style.display = "block"; if (isAlert) { this.showTips(i18n("copySuccess",urls.length)); } }, Preload:function(ele,oriThis){ this.ele=ele; this.oriThis=oriThis;//主this this.init(); }, Scrollbar:function(scrollbar,container,isHorizontal){ this.scrollbar=scrollbar; this.container=container; this.isHorizontal=isHorizontal this.init(); }, addStyle:function(){ if (GalleryC.style) { if (!GalleryC.style.parentNode) { GalleryC.style = _GM_addStyle(GalleryC.style.innerText); this.globalSSheet = GalleryC.style.sheet; } return; } GalleryC.style=_GM_addStyle('\ /*最外层容器*/\ .pv-gallery-container {\ position: fixed;\ top: 0;\ left: 0;\ width: 100%;\ height: 100%;\ min-width:unset;\ min-height:unset;\ padding: 0;\ margin: 0;\ border: none;\ z-index:'+prefs.imgWindow.zIndex+';\ background-color: transparent;\ display: initial;\ }\ /*全局border-box*/\ .pv-gallery-container span{\ -moz-box-sizing: border-box;\ box-sizing: border-box;\ line-height: 1.6;\ text-overflow: unset;\ background-image: initial;\ float: initial;\ }\ .pv-gallery-container * {\ font-size: 14px;\ display: initial;\ flex-direction: row;\ }\ /*点击还原的工具条*/\ span.pv-gallery-maximize-trigger{\ position:fixed;\ bottom:15px;\ left:15px;\ display:none;\ background:#000;\ opacity:0.6;\ padding-left:10px;\ font-size:16px;\ line-height:0;\ color:white;\ cursor:pointer;\ box-shadow:3px 3px 0 0 #333;\ z-index:899999998;\ }\ .pv-gallery-maximize-trigger:hover{\ opacity:0.9;\ }\ span.pv-gallery-maximize-trigger-close{\ display:inline-block;\ padding-left:10px;\ vertical-align:middle;\ height:30px;\ padding:10px 0;\ width:24px;\ background:url("'+prefs.icons.loadingCancle+'") center no-repeat;\ }\ .pv-gallery-maximize-trigger-close:hover{\ background-color:#333;\ }\ span.pv-gallery-head-command-close{\ position:absolute;\ top:0;\ width:40px;\ border-left: 1px solid #333333;\ background:transparent no-repeat center;\ background-image:url("'+prefs.icons.loadingCancle+'");\ }\ @media only screen and (max-width: 600px) {\ .pv-gallery-maximize-container>.maximizeChild{\ width:calc(50vw - 5px);\ }\ }\ @media only screen and (min-width: 600px) {\ .pv-gallery-maximize-container>.maximizeChild{\ width:calc(33vw - 5px);\ }\ }\ @media only screen and (min-width: 800px) {\ .pv-gallery-maximize-container>.maximizeChild{\ width:calc(25vw - 5px);\ }\ }\ @media only screen and (min-width: 1000px) {\ .pv-gallery-maximize-container>.maximizeChild{\ width:calc(20vw - 5px);\ }\ }\ @media only screen and (min-width: 1130px) {\ .pv-gallery-maximize-container>.maximizeChild{\ width:calc(16.6vw - 6px);\ }\ }\ @media only screen and (max-width: 799px) {\ .pv-gallery-range-box>input {\ display: none;\ }\ .pv-gallery-head-command-drop-list {\ right: 10px;\ }\ span.pv-gallery-head {\ white-space: nowrap;\ }\ span.pv-gallery-sidebar-toggle-content {\ font-size: 30px!important;\ }\ span.pv-gallery-sidebar-toggle {\ height: 30px!important;\ opacity: 0.6;\ border-radius: 0!important;\ }\ .pv-gallery-sidebar-viewmore:not(.showmore) {\ opacity: 0!important;\ }\ .pv-gallery-maximize-container{\ margin-top: 200px;\ }\ .pv-gallery-sidebar-viewmore.showmore{\ transform: scale(3.5);\ bottom: 50px;\ }\ .pv-gallery-maximize-container span>p{\ opacity: 0.6;\ }\ span.pv-gallery-head-command-close {\ position: fixed!important;\ right: 0!important;\ height: 29px!important;\ background-color: black;\ }\ }\ @media only screen and (min-width: 799px) {\ .pv-gallery-maximize-container{\ margin-top: 30px;\ }\ .pv-gallery-maximize-container span>p{\ opacity: 0;\ }\ }\ span.pv-gallery-tipsWords{\ font-size: 50px;\ font-weight: bold;\ font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",\ "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",\ "Segoe UI Emoji", "Segoe UI Symbol";\ color: #ffffff;\ height: 70px;\ line-height: 70px;\ position: fixed;\ left: 50%;\ top: 10%;\ margin-left: -150px;\ padding: 0 10px;\ z-index: 999999999;\ background-color: #000;\ border: 1px solid black;\ border-radius: 10px;\ opacity: 0;\ filter: alpha(opacity=65);\ box-shadow: 5px 5px 20px 0px #000;\ -moz-transition:opacity 0.3s ease-in-out 0s;\ -webkit-transition:opacity 0.3s ease-in-out 0s;\ transition:opacity 0.3s ease-in-out 0s;\ pointer-events: none;\ overflow: hidden;\ text-overflow: ellipsis;\ white-space: nowrap;\ max-width: 65%;\ }\ /*顶栏*/\ span.pv-gallery-head {\ position: absolute;\ top: 0;\ left: 0;\ width: 100%;\ min-height: 30px;\ height: auto;\ z-index:1;\ background-color:rgb(0,0,0);\ border:none;\ border-bottom:1px solid #333333;\ text-align:right;\ line-height:0;\ font-size: 14px;\ color:#757575;\ padding-right:42px;\ display: block;\ overflow-x: visible;\ overflow-y: auto;\ scrollbar-width: none;\ -ms-overflow-style: none;\ }\ span.pv-gallery-head::-webkit-scrollbar {\ width: 0 !important;\ height: 0 !important;\ }\ .pv-gallery-head > span{\ vertical-align:middle;\ }\ /*顶栏左边*/\ span.pv-gallery-head-float-left{\ float:left;\ height:100%;\ text-align:left;\ padding-left:5px;\ display: table;\ }\ .pv-gallery-head-float-left > span{\ display:inline-block;\ height:100%;\ vertical-align:middle;\ }\ .pv-gallery-head-float-left > span > *{\ vertical-align:middle;\ }\ .pv-gallery-head-left-img-info{\ cursor:help;\ }\ .pv-gallery-head-left-img-info-description {\ margin-left: 10px;\ margin-right: 10px;\ overflow: hidden;\ text-overflow: ellipsis;\ white-space: nowrap;\ max-width: 6em;\ display: inherit;\ }\ .pv-gallery-range-box{\ display: inline-flex;\ justify-content: center;\ align-items: center;\ }\ .pv-gallery-range-box>span{\ padding: 0 5px 0 5px;\ white-space: nowrap;\ }\ .pv-gallery-range-box>input{\ background: white;\ min-height: auto;\ padding: 0;\ -webkit-appearance: auto;\ }\ /*顶栏里面的按钮样式-开始*/\ .pv-gallery-head-command{\ display:inline-block;\ cursor:pointer;\ height:100%;\ padding:0 8px;\ text-align:center;\ position:relative;\ z-index:1;\ vertical-align:middle;\ -o-user-select: none;\ -ms-user-select: none;\ -webkit-user-select: none;\ -moz-user-select: -moz-none;\ user-select: none;\ }\ /*辅助点击事件的生成,countdown*/\ .pv-gallery-head-command_overlayer{\ top:0;\ left:0;\ right:0;\ bottom:0;\ position:absolute;\ opacity:0;\ }\ .pv-gallery-head-command > *{\ vertical-align:middle;\ }\ .pv-gallery-head-command-slide-show-countdown{\ font-size:0.8em;\ }\ span.pv-gallery-head-command-slide-show-button{\ border-radius:36px;\ display:inline-block;\ width:18px;\ height:18px;\ border:2px solid #757575;\ margin-right:3px;\ line-height:0;\ }\ .pv-gallery-head-command-slide-show-button-inner{\ display:inline-block;\ border:none;\ border-top:4px solid transparent;\ border-bottom:4px solid transparent;\ border-left:8px solid #757575;\ vertical-align:middle;\ margin-left: 1px;\ }\ .pv-gallery-head-command-slide-show-button-inner_stop{\ border-color:#757575;\ margin-left: 0px;\ }\ span.pv-gallery-head-command-collect-icon{\ display:inline-block;\ height:20px;\ width:20px;\ background:transparent url("' + prefs.icons.fivePointedStar + '") 0 0 no-repeat;\ }\ span.pv-gallery-head-left-lock-icon{\ display:inline-block;\ height:20px;\ width:20px;\ cursor:pointer;\ background:transparent url("' + prefs.icons.lock + '") 0 0 no-repeat;\ }\ span.pv-gallery-head-left-filter-icon{\ display:inline-block;\ height:20px;\ width:20px;\ cursor:pointer;\ background:transparent url("' + prefs.icons.filter + '") 0 0 no-repeat;\ }\ .pv-gallery-head-command-collect-icon ~ .pv-gallery-head-command-collect-text::after{\ content:"'+i18n("collect")+'";\ }\ .pv-gallery-head-command-collect-favorite > .pv-gallery-head-command-collect-icon{\ background-position:-40px 0 !important;\ }\ .pv-gallery-head-command-collect-favorite > .pv-gallery-head-command-collect-text::after{\ content:"'+i18n("collected")+'";\ }\ .pv-gallery-head-command-exit-collection{\ color:#939300 !important;\ display:none;\ }\ .pv-gallery-head-command-urlFilter{\ color:#e9cccc !important;\ display:none;\ }\ .pv-gallery-head-command:hover{\ background-color:#272727;\ color:#ccc;\ }\ /*droplist*/\ .pv-gallery-head-command-drop-list{\ position:fixed;\ display:none;\ box-shadow:0 0 3px #808080;\ background-color:#272727;\ line-height: 1.6;\ text-align:left;\ padding:10px;\ color:#ccc;\ margin-top:-1px;\ z-index:9;\ }\ .pv-gallery-head-command-drop-list-item{\ display:block;\ padding:2px 5px;\ cursor:pointer;\ white-space:nowrap;\ }\ .pv-gallery-head-command-drop-list-item-collect-description{\ cursor:default;\ }\ .pv-gallery-head-command-drop-list-item-collect-description > textarea{\ resize:both;\ width:auto;\ height:auto;\ }\ .pv-gallery-head-command-drop-list-item_disabled{\ color:#757575;\ }\ .pv-gallery-head-command-drop-list-item input + *{\ padding-left:3px;\ }\ .pv-gallery-head-command-drop-list-item input[type=number]{\ text-align:left;\ max-width:50px;\ height:20px;\ background: white;\ color: black;\ box-sizing: border-box;\ display: initial;\ margin: 0 5px;\ padding: 0 5px;\ }\ .pv-gallery-head-command-drop-list-item input[type=checkbox]{\ width:20px;\ box-sizing: border-box;\ display: initial;\ margin: 0 5px;\ opacity: 1;\ position: initial;\ }\ .pv-gallery-head-command-drop-list-item > * {\ vertical-align:middle;\ width: auto;\ opacity: 1;\ height: auto;\ padding: 0;\ margin: 0;\ }\ .pv-gallery-head-command-drop-list-item label {\ font-weight: normal;\ display:inline;\ font-size:unset;\ line-height: initial;\ color: inherit;\ }\ .pv-gallery-head-command-drop-list-item label:after {\ display:none;\ }\ .pv-gallery-head-command-drop-list-item:hover{\ background-color:#404040;\ }\ /*container*/\ .pv-gallery-head-command-container{\ display:inline-block;\ height:100%;\ position:relative;\ }\ /* after伪类生成标识下拉菜单的三角图标*/\ .pv-gallery-head-command-container > .pv-gallery-head-command::after{\ content:"";\ display:inline-block;\ vertical-align:middle;\ border:none;\ border-top:7px solid #757575;\ border-left:5px solid transparent;\ border-right:5px solid transparent;\ margin-left:5px;\ -moz-transition:all 0.3s ease-in-out 0s;\ -webkit-transition:all 0.3s ease-in-out 0s;\ transition:all 0.3s ease-in-out 0s;\ }\ .pv-gallery-head-command-container:hover{\ box-shadow:0 0 3px #808080;\ }\ .pv-gallery-head-command-container:hover > .pv-gallery-head-command{\ background-color:#272727;\ color:#ccc;\ }\ .pv-gallery-head-command-container:hover > .pv-gallery-head-command::after{\ -webkit-transform:rotate(180deg);\ -moz-transform:rotate(180deg);\ transform:rotate(180deg);\ border-top:7px solid #ccc;\ }\ .pv-gallery-head-command-container:hover .pv-gallery-head-command-collect-icon{\ background-position:-20px 0;\ }\ .pv-gallery-head-command-container:hover .pv-gallery-head-command-slide-show-button{\ border-color:#ccc;\ }\ .pv-gallery-head-command-container:hover .pv-gallery-head-command-slide-show-button-inner{\ border-left-color:#ccc;\ }\ .pv-gallery-head-command-container:hover .pv-gallery-head-command-slide-show-button-inner_stop{\ border-color:#ccc;\ }\ .pv-gallery-head-command-container:hover > .pv-gallery-head-command-drop-list,.pv-gallery-head-command-container > .pv-gallery-head-command-drop-list.focus{\ display:block;\ }\ /*顶栏里面的按钮样式-结束*/\ .pv-gallery-body {\ display: block;\ height: 100%;\ width: 100%;\ margin: 0;\ padding: 0;\ border: none;\ border-top: 30px solid transparent;\ position: relative;\ background-clip: padding-box;\ z-index:0;\ }\ .pv-gallery-img-container {\ display: block;\ padding: 0;\ margin: 0;\ border: none;\ height: 100%;\ width: 100%;\ background-clip: padding-box;\ background-color: ' + (prefs.gallery.backgroundColor || 'rgba(20,20,20,0.75)') + ';\ position:relative;\ transition: background-color .3s ease;\ }\ .pv-gallery-img-container-top {\ border-top: '+ prefs.gallery.sidebarSize +'px solid transparent;\ }\ .pv-gallery-img-container-right {\ border-right: '+ prefs.gallery.sidebarSize +'px solid transparent;\ }\ .pv-gallery-img-container-bottom {\ border-bottom: '+ prefs.gallery.sidebarSize +'px solid transparent;\ }\ .pv-gallery-img-container-left {\ border-left: '+ prefs.gallery.sidebarSize +'px solid transparent;\ }\ /*大图区域的切换控制按钮*/\ .pv-gallery-img-controler{\ position:absolute;\ top:50%;\ height:60px;\ width:50px;\ margin-top:-30px;\ cursor:pointer;\ opacity:0.3;\ z-index:1;\ transition: opacity .5s ease;\ }\ .pv-gallery-sidebar-toggle-hide .pv-gallery-img-controler{\ opacity:0;\ }\ span.pv-gallery-img-controler-pre{\ background:rgba(70,70,70,0.8) url("'+prefs.icons.arrowLeft+'") no-repeat center;\ left:10px;\ }\ span.pv-gallery-img-controler-next{\ background:rgba(70,70,70,0.8) url("'+prefs.icons.arrowRight+'") no-repeat center;\ right:10px;\ }\ .pv-gallery-img-controler:hover{\ background-color:rgba(140,140,140,0.8);\ opacity:0.9;\ z-index:2;\ }\ /*滚动条样式--开始*/\ .pv-gallery-scrollbar-h,\ .pv-gallery-scrollbar-v{\ display:none;\ z-index:1;\ position:absolute;\ margin:0;\ padding:0;\ border:none;\ }\ .pv-gallery-scrollbar-h{\ bottom:10px;\ left:0;\ right:0;\ height:10px;\ margin:0 2px;\ }\ .pv-gallery-scrollbar-v{\ top:0;\ bottom:0;\ right:10px;\ width:10px;\ margin:2px 0;\ }\ .pv-gallery-scrollbar-h:hover{\ height:25px;\ bottom:0;\ }\ .pv-gallery-scrollbar-v:hover{\ width:25px;\ }\ .pv-gallery-scrollbar-h:hover,\ .pv-gallery-scrollbar-v:hover{\ background-color:rgba(100,100,100,0.9);\ z-index:2;\ }\ .pv-gallery-scrollbar-h-track,\ .pv-gallery-scrollbar-v-track{\ position:absolute;\ top:0;\ left:0;\ right:0;\ bottom:0;\ background-color:rgba(100,100,100,0.3);\ border:2px solid transparent;\ }\ .pv-gallery-scrollbar-h-handle,\ .pv-gallery-scrollbar-v-handle{\ position:absolute;\ background-color:rgba(0,0,0,0.5);\ }\ .pv-gallery-scrollbar-h-handle{\ height:100%;\ }\ .pv-gallery-scrollbar-v-handle{\ width:100%;\ right: 0;\ }\ .pv-gallery-scrollbar-h-handle:hover,\ .pv-gallery-scrollbar-v-handle:hover{\ background-color:rgba(80,33,33,1);\ border: 2px solid #585757;\ }\ .pv-gallery-scrollbar-h-handle:active,\ .pv-gallery-scrollbar-v-handle:active{\ background-color:rgba(57,26,26,1);\ border: 2px solid #878484;\ }\ /*滚动条样式--结束*/\ .pv-gallery-img-content{\ display:block;\ width:100%;\ height:100%;\ overflow:hidden;\ text-align:center;\ padding:0;\ border:none;\ margin:0;\ line-height:0;\ font-size:0;\ white-space:nowrap;\ }\ .pv-gallery-img-parent{\ display:inline-flex;\ align-items: center;\ vertical-align: middle;\ justify-content: center;\ line-height:0;\ }\ .pv-gallery-img_broken{\ display:none;\ cursor:pointer;\ }\ .pv-gallery-img{\ position:relative;\/*辅助e.layerX,layerY*/\ display:inline-block;\ vertical-align:middle;\ width:auto;\ height:auto;\ padding:0;\ border:5px solid #313131;\ margin:1px;\ opacity:0.3;\ box-sizing: content-box;\ background-color: #282828cc;\ background-position: center 0;\ background-repeat: no-repeat;\ background-size: cover;\ -webkit-background-size: cover;\ -o-background-size: cover;\ '+ (prefs.gallery.transition ? ('\ -webkit-transition: opacity 0.5s ease;\ -moz-transition: opacity 0.5s ease;\ transition: opacity 0.5s ease;\ ') : '') + '\ }\ .pv-gallery-img_zoom-out{\ cursor:'+support.cssCursorValue.zoomOut+';\ }\ .pv-gallery-img_zoom-in{\ cursor:'+support.cssCursorValue.zoomIn+';\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide .pv-gallery-img{\ border:0px;\ }\ span.pv-gallery-sidebar-toggle{\ position:absolute;\ line-height:12px;\ text-align:center;\ background-color:rgb(0,0,0);\ color:#757575;\ white-space:nowrap;\ cursor:pointer;\ z-index:2;\ transition: background-color .3s ease, opacity .3s ease;\ justify-content: center;\ display:none;\ }\ :fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide span.pv-gallery-sidebar-toggle {\ opacity: 0!important;\ }\ :-webkit-full-screen .pv-gallery-container.pv-gallery-sidebar-toggle-hide span.pv-gallery-sidebar-toggle {\ opacity: 0!important;\ }\ :-ms-fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide span.pv-gallery-sidebar-toggle {\ opacity: 0!important;\ }\ :fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide span.pv-gallery-sidebar-toggle:hover {\ opacity: 1!important;\ }\ :-webkit-full-screen .pv-gallery-container.pv-gallery-sidebar-toggle-hide span.pv-gallery-sidebar-toggle:hover {\ opacity: 1!important;\ }\ :-ms-fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide span.pv-gallery-sidebar-toggle:hover {\ opacity: 1!important;\ }\ :fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head {\ opacity: 0!important;\ }\ :-webkit-full-screen .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head {\ opacity: 0!important;\ }\ :-ms-fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head {\ opacity: 0!important;\ }\ :fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head:hover {\ opacity: 1!important;\ }\ :-webkit-full-screen .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head:hover {\ opacity: 1!important;\ }\ :-ms-fullscreen .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head:hover {\ opacity: 1!important;\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-body>.pv-gallery-img-container>span.pv-gallery-sidebar-toggle{\ opacity: 0.6;\ padding: 15px;\ background-color:#00000000;\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-body>.pv-gallery-img-container>span.pv-gallery-sidebar-toggle:hover{\ opacity: 1;\ background-color:rgb(0 0 0 / 50%);\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-body{\ border-top: 0px solid transparent;\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head{\ opacity: 0.1;\ transition: opacity .3s ease;\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-body>.pv-gallery-img-container{\ background-color: black;\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide>.pv-gallery-head:hover{\ opacity: 1;\ }\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide .pv-gallery-img-parent,\ .pv-gallery-container.pv-gallery-sidebar-toggle-hide .pv-gallery-img{\ cursor: none;\ }\ .pv-gallery-sidebar-viewmore{\ position:absolute;\ line-height:0;\ text-align:center;\ background-color:#00000030;\ color:#a1a1a1;\ white-space:nowrap;\ cursor:pointer;\ z-index:1;\ display:none;\ height: 30px;\ width:30px;\ border-radius: 15px;\ line-height: 2 !important;\ font-family: auto;\ transition: background-color .3s ease;\ }\ .pv-gallery-sidebar-viewmore:hover{\ opacity: 1;\ background-color:#000000;\ }\ .pv-gallery-maximize-container+p{\ position: fixed;\ width: 100%;\ text-align: center;\ pointer-events: none;\ margin-bottom: 45px;\ left: 0;\ bottom: 0;\ opacity: 0;\ transition: all .3s ease;\ }\ .pv-gallery-maximize-container+p:hover,.pv-gallery-maximize-container.checked+p:hover{\ opacity: 1;\ }\ .pv-gallery-maximize-container.checked+p{\ opacity: 0.8;\ }\ .pv-gallery-maximize-container+p>.need-checked{\ display: none;\ }\ .pv-gallery-maximize-container.checked+p>.need-checked{\ display: inline-block;\ }\ .pv-gallery-maximize-container+p>input{\ pointer-events: all;\ color: white;\ background-color: black;\ border: 0;\ opacity: 0.8;\ padding: 5px 10px;\ cursor: pointer;\ margin: 1px;\ font-size: 20px;\ }\ .pv-gallery-maximize-container+p>input:hover{\ color: red;\ }\ .pv-gallery-maximize-container{\ min-width: 100%;\ display: block;\ background: black;\ margin-left: 3px;\ }\ .pv-gallery-maximize-container.pv-gallery-flex-maximize{\ column-count: unset;\ -moz-column-count: unset;\ -webkit-column-count: unset;\ display: flex;\ flex-flow: wrap;\ justify-content: center;\ }\ .pv-gallery-maximize-container.pv-gallery-flex-maximize span{\ width: 18.5%;\ height: 30vh;\ }\ .pv-gallery-maximize-container.pv-gallery-flex-maximize img{\ position: relative;\ width: unset;\ max-height: 100%;\ max-width: 100%;\ top: 50%;\ transform: translateY(-50%) scale3d(1, 1, 1);\ }\ .pv-gallery-maximize-container.pv-gallery-flex-maximize img:hover {\ transform: translateY(-50%) scale3d(1.1, 1.1, 1.1);\ }\ .pv-gallery-maximize-container span{\ -moz-page-break-inside: avoid;\ -webkit-column-break-inside: avoid;\ break-inside: avoid;\ float: left;\ margin-bottom: 15px;\ margin-right: 15px;\ overflow: hidden;\ position: relative;\ }\ .pv-gallery-maximize-container>.maximizeChild{\ display: inline-block;\ vertical-align: middle;\ text-align: center;\ background-color: rgba(40, 40, 40, 0.8);\ border: 5px solid #000000;\ }\ .pv-gallery-maximize-container>.maximizeChild:hover{\ background: linear-gradient( 45deg, rgba(255, 255, 255, 0.4) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.4) 75%, rgba(255, 255, 255, 0.4) 100% ), linear-gradient( 45deg, rgba(255, 255, 255, 0.4) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.4) 75%, rgba(255, 255, 255, 0.4) 100% );\ background-size: 20px 20px;\ background-position: 0 0, 10px 10px;\ }\ .pv-gallery-maximize-container>.maximizeChild.selected{\ border: 5px solid #ff0000;\ }\ .pv-gallery-maximize-container img{\ max-width: 100%;\ transition: transform .3s ease 0s;\ transform: scale3d(1, 1, 1);\ cursor: zoom-in;\ min-height: 88px;\ }\ .pv-gallery-maximize-container>.maximizeChild:hover img {\ transform: scale3d(1.1, 1.1, 1.1);\ filter: brightness(1.1) !important;\ }\ .pv-gallery-maximize-container.pv-gallery-flex-maximize>.maximizeChild:hover img {\ transform: translateY(-50%) scale3d(1.1, 1.1, 1.1);\ }\ .pv-gallery-maximize-container span>p{\ position: absolute;\ width: 100%;\ max-height: 40%;\ font-size: 18px;\ text-align: center;\ background: #00000080;\ color: #fff;\ left: 0;\ user-select: none;\ word-break: break-all;\ display: inline;\ margin: 0 auto;\ }\ .pv-gallery-maximize-container span>p.pv-bottom-banner{\ bottom: 0;\ height: 35px;\ cursor: pointer;\ line-height: 40px;\ }\ .pv-gallery-maximize-container span>p.pv-bottom-banner>svg{\ width: 20px;\ height: 20px;\ vertical-align: middle;\ fill: currentColor;\ overflow: hidden;\ }\ .pv-gallery-maximize-container span>p.pv-top-banner{\ top: 0;\ height: 25px;\ cursor: pointer;\ }\ .pv-gallery-maximize-container span:hover>p{\ opacity: 1;\ }\ .pv-gallery-maximize-container span>p.pv-bottom-banner:hover{\ color:red;\ font-weight:bold;\ }\ .pv-gallery-maximize-container span>input{\ position: absolute;\ top: 2px;\ width: 20px;\ height: 20px;\ opacity: 0;\ left: 0;\ display: inline;\ cursor: pointer;\ }\ .pv-gallery-maximize-container.checked span>input{\ opacity: 1;\ }\ .pv-gallery-maximize-container.checked span>.pv-top-banner{\ opacity: 0.6;\ }\ .pv-gallery-maximize-container+p>input.compareBtn{\ display: none;\ }\ .pv-gallery-maximize-container.canCompare+p>input.compareBtn{\ display: inline;\ }\ .pv-gallery-maximize-container span:hover>input{\ opacity: 1;\ }\ .pv-gallery-maximize-scroll{\ overflow-y: scroll;\ overflow-x: hidden;\ height: 100%;\ width: 100%;\ position: absolute;\ display: none;\ top: 0;\ left: 0;\ background: black;\ }\ .pv-gallery-sidebar-toggle:hover,.pv-gallery-sidebar-viewmore:hover{\ color:#ccc;\ }\ .pv-gallery-sidebar-toggle-h{\ width:80px;\ margin-left:-40px;\ left:50%;\ }\ .pv-gallery-sidebar-viewmore-h{\ margin-left:-15px;\ left:50%;\ }\ .pv-gallery-sidebar-toggle-v{\ height:80px;\ margin-top:-40px;\ top:50%;\ }\ .pv-gallery-sidebar-viewmore-v{\ height:30px;\ top:6%;\ }\ .pv-gallery-sidebar-toggle-top{\ top:-3px;\ }\ .pv-gallery-sidebar-viewmore-top{\ top:15px;\ }\ .pv-gallery-sidebar-toggle-right,.pv-gallery-sidebar-viewmore-right{\ right:-3px;\ }\ .pv-gallery-sidebar-toggle-bottom{\ bottom:-3px;\ }\ .pv-gallery-sidebar-viewmore-bottom{\ display: block;\ bottom:15px;\ }\ .pv-gallery-sidebar-viewmore-bottom.showmore{\ background-color: rgb(42, 42, 42);\ opacity: 1;\ }\ .pv-gallery-sidebar-toggle-left,.pv-gallery-sidebar-viewmore-left{\ left:-3px;\ }\ span.pv-gallery-sidebar-toggle-content{\ display:inline-block;\ vertical-align:middle;\ white-space:normal;\ word-wrap:break-word;\ overflow-wrap:break-word;\ line-height:1.1;\ font-size:18px;\ text-align:center;\ margin-bottom:8px;\ }\ span.pv-gallery-sidebar-viewmore-content{\ display:inline-block;\ vertical-align:middle;\ white-space:normal;\ word-wrap:break-word;\ overflow-wrap:break-word;\ line-height:1;\ font-size:16px;\ text-align:center;\ }\ .pv-gallery-sidebar-toggle-content-v,.pv-gallery-sidebar-viewmore-content-v{\ width:1.1em;\ }\ /*侧边栏开始*/\ .pv-gallery-sidebar-container {\ position: absolute;\ background-color:rgb(0,0,0);\ padding:5px;\ border:none;\ margin:0;\ text-align:center;\ line-height:0;\ white-space:nowrap;\ -o-user-select: none;\ -webkit-user-select: none;\ -moz-user-select: -moz-none;\ user-select: none;\ }\ .pv-gallery-sidebar-container-h {\ height: '+ prefs.gallery.sidebarSize +'px;\ width: 100%;\ }\ .pv-gallery-sidebar-container-v {\ width: '+ prefs.gallery.sidebarSize +'px;\ height: 100%;\ }\ .pv-gallery-sidebar-container-top {\ top: 0;\ left: 0;\ border-bottom:1px solid #333333;\ }\ .pv-gallery-sidebar-container-right {\ top: 0;\ right: 0;\ border-left:1px solid #333333;\ }\ .pv-gallery-sidebar-container-bottom {\ bottom: 0;\ left: 0;\ border-top:1px solid #333333;\ }\ .pv-gallery-sidebar-container-left {\ top: 0;\ left: 0;\ border-right:1px solid #333333;\ }\ .pv-gallery-sidebar-content {\ display: inline-block;\ margin: 0;\ padding: 0;\ border: none;\ background-clip: padding-box;\ vertical-align:middle;\ position:relative;\ text-align:left;\ }\ .pv-gallery-sidebar-content-h {\ height: 100%;\ width: 90%;\ border-left: 40px solid transparent;\ border-right: 40px solid transparent;\ }\ .pv-gallery-sidebar-content-v {\ height: 90%;\ width: 100%;\ border-top: 40px solid transparent;\ border-bottom: 40px solid transparent;\ }\ span.pv-gallery-sidebar-controler{\ cursor:pointer;\ position:absolute;\ background:rgba(255,255,255,0.1) no-repeat center;\ }\ .pv-gallery-sidebar-controler:hover{\ background-color:rgba(255,255,255,0.3);\ }\ .pv-gallery-sidebar-controler-pre-h,\ .pv-gallery-sidebar-controler-next-h{\ top:0;\ width:36px;\ height:100%;\ }\ .pv-gallery-sidebar-controler-pre-v,\ .pv-gallery-sidebar-controler-next-v{\ left:0;\ width:100%;\ height:36px;\ }\ span.pv-gallery-sidebar-controler-pre-h {\ left: -40px;\ background-image: url("'+prefs.icons.arrowLeft+'");\ }\ span.pv-gallery-sidebar-controler-next-h {\ right: -40px;\ background-image: url("'+prefs.icons.arrowRight+'");\ }\ span.pv-gallery-sidebar-controler-pre-v {\ top: -40px;\ background-image: url("'+prefs.icons.arrowTop+'");\ }\ span.pv-gallery-sidebar-controler-next-v {\ bottom: -40px;\ background-image: url("'+prefs.icons.arrowBottom+'");\ }\ .pv-gallery-sidebar-thumbnails-container {\ display: block;\ overflow: hidden;\ height: 100%;\ width: 100%;\ margin:0;\ border:none;\ padding:0;\ line-height:0;\ position:relative;\ }\ .pv-gallery-sidebar-thumbnails-container span{\ vertical-align:middle;\ }\ .pv-gallery-sidebar-thumbnails-container-h{\ border-left:1px solid #464646;\ border-right:1px solid #464646;\ white-space:nowrap;\ }\ .pv-gallery-sidebar-thumbnails-container-v{\ border-top:1px solid #464646;\ border-bottom:1px solid #464646;\ white-space:normal;\ }\ .pv-gallery-sidebar-thumbnails-container-top {\ padding-bottom:5px;\ }\ .pv-gallery-sidebar-thumbnails-container-right {\ padding-left:5px;\ }\ .pv-gallery-sidebar-thumbnails-container-bottom {\ padding-top:5px;\ }\ .pv-gallery-sidebar-thumbnails-container-left {\ padding-right:5px;\ }\ span.pv-gallery-sidebar-thumb-container {\ display:inline-block;\ text-align: center;\ border:2px solid rgb(52,52,52);\ background: linear-gradient( 45deg, rgba(255, 255, 255, 0.4) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.4) 75%, rgba(255, 255, 255, 0.4) 100% ), linear-gradient( 45deg, rgba(255, 255, 255, 0.4) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.4) 75%, rgba(255, 255, 255, 0.4) 100% );\ background-size: 20px 20px;\ background-position: 0 0, 10px 10px;\ cursor:pointer;\ position:relative;\ padding:2px;\ font-size:0;\ line-height:0;\ white-space:nowrap;\ vertical-align: middle;\ top:0;\ left:0;\ -webkit-transition:all 0.2s ease-in-out;\ transition:all 0.2s ease-in-out;\ }\ .pv-gallery-sidebar-thumbnails-container-h .pv-gallery-sidebar-thumb-container {\ margin:0 2px;\ height:100%;\ }\ .pv-gallery-sidebar-thumbnails-container-v .pv-gallery-sidebar-thumb-container {\ margin:2px 0;\ width:100%;\ }\ .pv-gallery-sidebar-thumbnails_hide-span > .pv-gallery-sidebar-thumb-container {\ display:none;\ }\ .pv-gallery-sidebar-thumb-container:hover {\ border:2px solid rgb(57,149,211);\ }\ span.pv-gallery-sidebar-thumb_selected {\ border:2px solid rgb(229,59,62);\ }\ .pv-gallery-sidebar-thumb_selected-top {\ top:5px;\ }\ .pv-gallery-sidebar-thumb_selected-right {\ left:-5px;\ }\ .pv-gallery-sidebar-thumb_selected-bottom {\ top:-5px;\ }\ .pv-gallery-sidebar-thumb_selected-left {\ left:5px;\ }\ span.pv-gallery-sidebar-thumb-loading{\ position:absolute;\ top:0;\ left:0;\ text-align:center;\ width:100%;\ height:100%;\ display:none;\ opacity:0.6;\ background:black url("' + prefs.icons.loading + '") no-repeat center ;\ }\ .pv-gallery-sidebar-thumb-loading:hover{\ opacity:0.8;\ }\ .pv-gallery-sidebar-thumb {\ display: inline-block;\ vertical-align: middle;\ max-width: 100% !important;\ max-height: 100% !important;\ height: auto !important;\ width: auto !important;\ min-width: 10%;\ min-height: 10%;\ }\ .pv-gallery-urls-textarea {\ display: none;\ position: fixed;\ top: 10vh;\ left: 10vw;\ z-index: 100;\ }\ .pv-gallery-urls-textarea>textarea {\ width: 80vw;\ height: 80vh;\ border: 10px solid #272727;\ background: #ffffffee;\ }\ span.pv-gallery-urls-textarea-close,\ span.pv-gallery-urls-textarea-download{\ height: 40px;\ top: -25px;\ background: #272727 no-repeat center;\ color: white;\ border-radius: 50%;\ cursor: pointer;\ }\ span.pv-gallery-urls-textarea-close:hover,\ span.pv-gallery-urls-textarea-download:hover {\ background-color: black;\ }\ span.pv-gallery-urls-textarea-close {\ position:absolute;\ right: -25px;\ width:40px;\ background-image:url("'+prefs.icons.loadingCancle+'");\ }\ span.pv-gallery-urls-textarea-download {\ position: absolute;\ left: -25px;\ width: 40px;\ display: flex;\ align-items: center;\ justify-content: center;\ }\ span.pv-gallery-urls-textarea-download>svg {\ height: 15px;\ width: 15px;\ fill: white;\ }\ .pv-gallery-vertical-align-helper{\ display:inline-block;\ vertical-align:middle;\ width:0;\ height:100%;\ margin:0;\ border:0;\ padding:0;\ visibility:hidden;\ white-space:nowrap;\ background-color:red;\ }\ '); this.globalSSheet=GalleryC.style.sheet; var head=document.head; var style2=document.createElement('style'); this.thumbVisibleStyle=style2; style2.type='text/css'; head.appendChild(style2); // 让 description 的文字内容溢出用点点点(...)省略号表示 // .pv-gallery-head-left-img-info-description { // overflow: hidden; // text-overflow: ellipsis; // white-space: nowrap; // width: 27em; // } }, }; GalleryC.prototype.Preload.prototype={//预读对象 init:function(){ if(!this.container){//预读的图片都仍里面 var div=document.createElement('div'); div.className='pv-gallery-preloaded-img-container'; div.style.display='none'; getBody(document).appendChild(div); GalleryC.prototype.Preload.prototype.container=div; }; this.max=prefs.gallery.max; this.nextNumber=0; this.nextEle=this.ele; this.preNumber=0; this.preEle=this.ele; this.direction='pre'; }, preload:function(){ var ele=this.getPreloadEle(); if(!ele){ return; }; this.waitForReady(ele); }, waitForReady: function(ele) { var self = this; var beginLoadImg = () => { self.imgReady = imgReady(dataset(ele,'src'), { loadEnd: function(e) { if (self.aborted) { return; } if (e.type == 'error') { var srcs = dataset(ele, 'srcs'); if (srcs) srcs = srcs.split(","); if (srcs && srcs.length > 0) { var src = srcs.shift(); dataset(ele, 'srcs', srcs.join(",")); if (src) { dataset(ele, 'src', src); self.waitForReady(ele); return; } } } dataset(ele,'preloaded','true') self.container.appendChild(this); self.preload(); }, time:60 * 1000,//限时一分钟,否则强制结束并开始预读下一张。 }); }; var xhr = dataset(ele, 'xhr') !== 'stop' && this.oriThis.getPropBySpanMark(ele, 'xhr'); if (xhr) { var xhrError = function() { dataset(ele, 'xhr', 'stop'); dataset(ele, 'src', dataset(ele, 'thumbSrc')); beginLoadImg(); }; xhrLoad.load({ url: dataset(ele,'src'), xhr: xhr, cb: function(imgSrc, imgSrcs, caption) { if (imgSrc) { dataset(ele, 'src', imgSrc); dataset(ele, 'xhr', 'stop'); if (caption) dataset(ele, 'description', caption); beginLoadImg(); } else { xhrError(); } }, onerror: xhrError }); } else { beginLoadImg(); } }, getPreloadEle:function(){ if((this.max<=this.nextNumber && this.max<=this.preNumber) || (!this.nextEle && !this.preEle)){ return; }; var ele=this.direction=='pre'? this.getNext() : this.getPrevious(); if(ele && !dataset(ele,'preloaded')){ return ele; }else{ return this.getPreloadEle(); }; }, getNext:function(){ this.nextNumber++; this.direction='next'; if(!this.nextEle)return; return (this.nextEle = this.oriThis.getThumSpan(false,this.nextEle)); }, getPrevious:function(){ this.preNumber++; this.direction='pre'; if(!this.preEle)return; return (this.preEle = this.oriThis.getThumSpan(true,this.preEle)); }, abort:function(){ this.aborted=true; if(this.imgReady){ this.imgReady.abort(); }; }, }; GalleryC.prototype.Scrollbar.prototype={//滚动条对象 init:function(){ var bar=this.scrollbar.bar; this.shown=bar.offsetWidth!=0; var self=this; bar.addEventListener('mousedown',function(e){//点击滚动条区域,该干点什么! e.preventDefault(); var target=e.target; var handle=self.scrollbar.handle; var track=self.scrollbar.track; switch(target){ case handle:{//手柄;功能,拖动手柄来滚动窗口 let pro=self.isHorizontal ? ['left','clientX'] : ['top','clientY']; var oHOffset=parseFloat(handle.style[pro[0]]); var oClient=e[pro[1]]; var moveHandler=function(e){ self.scroll(oHOffset + e[pro[1]] - oClient,true); }; let upHandler=function(){ document.removeEventListener('mousemove',moveHandler,true); document.removeEventListener('mouseup',upHandler,true); }; document.addEventListener('mousemove',moveHandler,true); document.addEventListener('mouseup',upHandler,true); }break; case track:{//轨道;功能,按住不放来连续滚动一个页面的距离 let pro=self.isHorizontal ? ['left','offsetX','layerX','clientWidth','offsetWidth'] : ['top' , 'offsetY' ,'layerY','clientHeight','offsetHeight']; var clickOffset=typeof e[pro[1]]=='undefined' ? e[pro[2]] : e[pro[1]]; var handleOffset=parseFloat(handle.style[pro[0]]); var handleSize=handle[pro[4]]; var under= clickOffset > handleOffset ;//点击在滚动手柄的下方 var containerSize=self.container[pro[3]]; var scroll=function(){ self.scrollBy(under? (containerSize - 10) : (-containerSize + 10));//滚动一个页面距离少一点 }; scroll(); var checkStop=function(){//当手柄到达点击位置时停止 var handleOffset=parseFloat(handle.style[pro[0]]); if(clickOffset >= handleOffset && clickOffset <= (handleOffset + handleSize)){ clearTimeout(scrollTimeout); clearInterval(scrollInterval); }; }; var scrollInterval; var scrollTimeout=setTimeout(function(){ scroll(); scrollInterval=setInterval(function(){ scroll(); checkStop(); },120); checkStop(); },300); checkStop(); let upHandler=function(){ clearTimeout(scrollTimeout); clearInterval(scrollInterval); document.removeEventListener('mouseup',upHandler,true); }; document.addEventListener('mouseup',upHandler,true); }break; }; },true); }, reset:function(){//判断滚动条该显示还是隐藏 var pro=this.isHorizontal ? ['scrollWidth','clientWidth','width'] : ['scrollHeight','clientHeight','height']; //如果内容大于容器的content区域 var scrollSize=this.container[pro[0]]; var clientSize=this.container[pro[1]]; var scrollMax=scrollSize - clientSize; this.scrollMax=scrollMax; if(scrollMax>0){ this.show(); var trackSize=this.scrollbar.track[pro[1]]; this.trackSize=trackSize; var handleSize=Math.floor((clientSize/scrollSize) * trackSize); handleSize=Math.max(20,handleSize);//限制手柄的最小大小; this.handleSize=handleSize; this.one=(trackSize-handleSize) / scrollMax;//一个像素对应的滚动条长度 this.scrollbar.handle.style[pro[2]]= handleSize + 'px'; this.scroll(this.getScrolled()); }else{ this.hide(); }; }, show:function(){ if(this.shown)return; this.shown=true; this.scrollbar.bar.style.display='block'; }, hide:function(){ if(!this.shown)return; this.shown=false; this.scrollbar.bar.style.display='none'; }, scrollBy:function(distance,handleDistance){ return this.scroll(this.getScrolled() + (handleDistance? distance / this.one : distance)); }, scrollByPages:function(num){ this.scroll(this.getScrolled() + (this.container[(this.isHorizontal ? 'clientWidth' : 'clientHeight')] - 10) * num); }, scroll:function(distance,handleDistance,transition){ if(!this.shown)return; //滚动实际滚动条 var _distance=distance; _distance=handleDistance? distance / this.one : distance; _distance=Math.max(0,_distance); _distance=Math.min(_distance,this.scrollMax); var pro=this.isHorizontal? ['left','scrollLeft'] : ['top','scrollTop']; //滚动虚拟滚动条 //根据比例转换为滚动条上应该滚动的距离。 distance=handleDistance? distance : this.one * distance; //处理非法值 distance=Math.max(0,distance);//如果值小于0那么取0 distance=Math.min(distance,this.trackSize - this.handleSize);//大于极限值,取极限值 var shs=this.scrollbar.handle.style; var container=this.container; if(transition){ clearInterval(this.transitionInterval); var start=0; var duration=10; var cStart=this.getScrolled(); var cChange=_distance-cStart; var sStart=parseFloat(shs[pro[0]]); var sChange=distance-sStart; var transitionInterval=setInterval(function(){ var cEnd=Tween.Cubic.easeInOut(start,cStart,cChange,duration); var sEnd=Tween.Cubic.easeInOut(start,sStart,sChange,duration); container[pro[1]]=cEnd; shs[pro[0]]=sEnd + 'px'; start++; if(start>=duration){ clearInterval(transitionInterval); }; },35); this.transitionInterval=transitionInterval; return; }; var noScroll=shs[pro[0]].replace(/(\.\d*)?\s*px/,"")==Math.floor(distance); shs[pro[0]]=distance + 'px'; container[pro[1]]=_distance; return noScroll; }, getScrolled:function(){ return this.container[(this.isHorizontal ? 'scrollLeft' : 'scrollTop')]; }, }; //放大镜 function MagnifierC(img,data){ this.img=img; this.data=data; this.init(); }; MagnifierC.all=[]; MagnifierC.styleZIndex=900000000;//全局z-index; MagnifierC.prototype={ init:function(){ MagnifierC.zoomRange=prefs.magnifier.wheelZoom.range.slice(0).sort((a, b)=>{return a - b}); MagnifierC.zoomRangeR=MagnifierC.zoomRange.slice(0).reverse();//降序 this.addStyle(); MagnifierC.all.push(this); var container=document.createElement('span'); container.className='pv-magnifier-container'; getBody(document).appendChild(container); this.magnifier=container; var imgNaturalSize={ h:this.img.naturalHeight, w:this.img.naturalWidth, }; this.imgNaturalSize=imgNaturalSize; var cs=container.style; cs.zIndex=MagnifierC.styleZIndex++; var maxDia=Math.ceil(Math.sqrt(Math.pow(1/2*imgNaturalSize.w,2) + Math.pow(1/2*imgNaturalSize.h,2)) * 2); this.maxDia=maxDia; var radius=prefs.magnifier.radius; radius=Math.min(maxDia/2,radius); this.radius=radius; var diameter=radius * 2; this.diameter=diameter; cs.width=diameter + 'px'; cs.height=diameter + 'px'; cs.borderRadius=radius+1 + 'px'; cs.backgroundImage='url("'+ this.img.src +'")'; cs.marginLeft= -radius +'px'; cs.marginTop= -radius +'px'; var imgPos=getContentClientRect(this.data.img); var wScrolled=getScrolled(); var imgRange={//图片所在范围 x:[imgPos.left + wScrolled.x , imgPos.right + wScrolled.x], y:[imgPos.top + wScrolled.y, imgPos.bottom + wScrolled.y], }; var imgW=imgRange.x[1] - imgRange.x[0]; var imgH=imgRange.y[1] - imgRange.y[0]; //如果图片太小的话,进行范围扩大。 var minSize=60; if(imgW < minSize){ imgRange.x[1] +=(minSize - imgW)/2; imgRange.x[0] -=(minSize - imgW)/2; imgW=minSize; }; if(imgH < minSize){ imgRange.y[1] +=(minSize - imgH)/2; imgRange.y[0] -=(minSize - imgH)/2; imgH=minSize; }; this.imgSize={ w:imgW, h:imgH, }; this.imgRange=imgRange; this.setMouseRange(); this.move({ pageX:imgRange.x[0], pageY:imgRange.y[0], }); this._focus=this.focus.bind(this); this._blur=this.blur.bind(this); this._move=this.move.bind(this); this._remove=this.remove.bind(this); this._pause=this.pause.bind(this); this._zoom=this.zoom.bind(this); this._clickOut=this.clickOut.bind(this); this._keydown=this.keydown.bind(this); if (prefs.magnifier.wheelZoom.enabled || prefs.magnifier.wheelZoom.scaleImage !== false) { this.zoomLevel=1; this.defaultDia=diameter; addWheelEvent(container,this._zoom,false); } container.addEventListener('mouseover',this._focus,false); container.addEventListener('mouseout',this._blur,false); container.addEventListener('dblclick',this._remove,false); container.addEventListener('click',this._pause,false); document.addEventListener('keydown',this._keydown, true); document.addEventListener('mousemove',this._move,true); document.addEventListener('mouseup',this._clickOut,true); }, addStyle:function(){ if (MagnifierC.style) { if (!MagnifierC.style.parentNode) { MagnifierC.style = _GM_addStyle(MagnifierC.style.innerText); } return; } MagnifierC.style=_GM_addStyle('\ .pv-magnifier-container{\ position:absolute;\ padding:0;\ margin:0;\ background-origin:border-box;\ -moz-box-sizing:border-box;\ box-sizing:border-box;\ border:3px solid #CCCCCC;\ background:rgba(40, 40, 40, 0.9) no-repeat;\ }\ .pv-magnifier-container_focus{\ box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.7);\ }\ .pv-magnifier-container_pause{\ border-color:red;\ }\ '); }, clickOut:function(e){ if(!this.magnifier.classList.contains("pv-magnifier-container_focus")){ this.remove(e); } }, focus:function(){ this.magnifier.classList.add('pv-magnifier-container_focus'); this.magnifier.style.zIndex=MagnifierC.styleZIndex++; }, blur:function(){ this.magnifier.classList.remove('pv-magnifier-container_focus'); }, move:function(e){ var mouseCoor={ x:e.pageX, y:e.pageY, }; var mouseRange=this.mouseRange; var imgRange=this.imgRange; if( !(mouseCoor.x >= mouseRange.x[0] && mouseCoor.x <= mouseRange.x[1] && mouseCoor.y >= mouseRange.y[0] && mouseCoor.y <= mouseRange.y[1]))return;//如果不再鼠标范围 if(mouseCoor.x > imgRange.x[1]){ mouseCoor.x = imgRange.x[1]; }else if(mouseCoor.x < imgRange.x[0]){ mouseCoor.x = imgRange.x[0]; }; if(mouseCoor.y > imgRange.y[1]){ mouseCoor.y = imgRange.y[1]; }else if(mouseCoor.y < imgRange.y[0]){ mouseCoor.y = imgRange.y[0]; }; var ms=this.magnifier.style; ms.top= mouseCoor.y + 'px'; ms.left= mouseCoor.x + 'px'; var radius=this.radius; var imgSize=this.imgSize; var imgNaturalSize=this.imgNaturalSize; var px=-((mouseCoor.x-imgRange.x[0])/imgSize.w * imgNaturalSize.w) + radius +'px'; var py=-((mouseCoor.y-imgRange.y[0])/imgSize.h * imgNaturalSize.h) + radius +'px'; ms.backgroundPosition=px + ' ' + py; }, getNextZoomLevel:function(){ var level; var self=this; if(this.zoomOut){//缩小 let found = MagnifierC.zoomRangeR.find(function(value){ if(value < self.zoomLevel){ level=value; return true; } }) if (!found) { level = self.zoomLevel * 0.9; } }else{ let found = MagnifierC.zoomRange.find(function(value){ if(value > self.zoomLevel){ level=value; return true; }; }); if (!found) { level = self.zoomLevel * 1.1; } } return level; }, zoom:function(e){ if ((e.metaKey != !!prefs.magnifier.wheelZoom.meta) || (e.altKey != !!prefs.magnifier.wheelZoom.alt) || (e.ctrlKey != !!prefs.magnifier.wheelZoom.ctrl) || (e.shiftKey != !!prefs.magnifier.wheelZoom.shift)) { return; } if(e.deltaY===0)return;//非Y轴的滚动 var ms=this.magnifier.style; if(prefs.magnifier.wheelZoom.pauseFirst && !this.paused){ if (prefs.magnifier.wheelZoom.scaleImage !== false) { let curScale = ms.transform.match(/[\d\.]+/); if (curScale) { curScale = parseFloat(curScale[0]); } else curScale = 1; if (e.deltaY < 0) { curScale += 0.1; } else { curScale -= 0.1; } if (curScale < 0.5) curScale = 0.5; ms.transform = `scale(${curScale})`; e.preventDefault(); } return; } if(!prefs.magnifier.wheelZoom.enabled)return; e.preventDefault(); if(e.deltaY < 0){//向上滚,放大; if(this.diameter >= this.maxDia)return; this.zoomOut=false; }else{ this.zoomOut=true; }; var level=this.getNextZoomLevel(); if(!level)return; this.zoomLevel=level; var diameter=this.defaultDia * level; if(diameter > this.maxDia){ diameter = this.maxDia; }; var radius=diameter/2 this.diameter=diameter; var bRadius=this.radius; this.radius=radius; this.setMouseRange(); ms.width=diameter+'px'; ms.height=diameter+'px'; ms.borderRadius=radius+1 + 'px'; ms.marginLeft=-radius+'px'; ms.marginTop=-radius+'px'; var bBP=ms.backgroundPosition.split(' '); ms.backgroundPosition=parseFloat(bBP[0]) + (radius - bRadius) + 'px' + ' ' + (parseFloat(bBP[1]) + ( radius - bRadius) + 'px'); }, pause:function(){ if(this.paused){ this.magnifier.classList.remove('pv-magnifier-container_pause'); document.addEventListener('mousemove',this._move,true); }else{ this.magnifier.classList.add('pv-magnifier-container_pause'); document.removeEventListener('mousemove',this._move,true); }; this.paused=!this.paused; }, setMouseRange:function(){ var imgRange=this.imgRange; var radius=this.radius; this.mouseRange={//鼠标活动范围 x:[imgRange.x[0]-radius , imgRange.x[1] + radius], y:[imgRange.y[0]-radius , imgRange.y[1] + radius], }; }, keydown:function(e){ if (e) { e.preventDefault(); e.stopPropagation(); if (e.keyCode == 27) this.remove(); } }, remove:function(e){ if (e) { e.preventDefault(); e.stopPropagation(); } if (this.magnifier.parentNode) { this.magnifier.parentNode.removeChild(this.magnifier); MagnifierC.all.splice(MagnifierC.all.indexOf(this),1); } document.removeEventListener('mousemove',this._move,true); document.removeEventListener('mouseup',this._clickOut,true); document.removeEventListener('keydown',this._keydown, true); }, }; //图片窗口 function ImgWindowC(img, data, actual, initPos, preview){ this.loaded = false; this.img = img; this.actual = !!actual; this.src = data?data.src:img.src; this.data = data; this.initPos = initPos || false; this.preview = !!preview; this.isImg = this.img.nodeName.toUpperCase() == 'IMG'; this.init(); if (data && this.isImg) { this.img.src = location.protocol == "https" ? data.src.replace(/^http:/,"https:") : data.src; } }; ImgWindowC.all=[];//所有的窗口对象 ImgWindowC.overlayer=null; ImgWindowC.prototype={ init:function(){ ImgWindowC.showing = true; ImgWindowC.zoomRange=prefs.imgWindow.zoom.range.slice(0).sort((a, b)=>{return a - b}); ImgWindowC.zoomRangeR=ImgWindowC.zoomRange.slice(0).reverse();//降序 var self=this; if(uniqueImgWin && !uniqueImgWin.removed){ uniqueImgWin.remove(); } if (!this.preview) { //图片是否已经被打开 if(ImgWindowC.all.find(function(iwin){ if(iwin.src==self.src){ iwin.firstOpen(); return true; }; }))return; } this.addStyle(); var img=this.img; img.className='pv-pic-window-pic pv-pic-ignored'; img.style.cssText='\ top:0px;\ left:0px;\ '; var imgNaturalSize={ h:img.naturalHeight, w:img.naturalWidth, }; this.imgNaturalSize=imgNaturalSize; this.following=false; var container=document.createElement('span'); container.style.cssText='\ cursor:pointer;\ top:0px;\ left:0px;\ opacity:0;\ background:black url("'+prefs.icons.loading+'") center no-repeat;\ '; container.className='pv-pic-window-container'; container.innerHTML=createHTML( ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ '0'+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ '0'+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ '' + '' + '' + //'' + '' + ''+ ''+ ''+ ''+ ''+prefs.icons.downloadSvgBtn+ ''); container.firstChild.appendChild(img); this.imgWindow=container; var toolMap={ 'hand':container.querySelector('.pv-pic-window-tb-hand'), 'rotate':container.querySelector('.pv-pic-window-tb-rotate'), 'zoom':container.querySelector('.pv-pic-window-tb-zoom'), 'fh':container.querySelector('.pv-pic-window-tb-flip-horizontal'), 'fv':container.querySelector('.pv-pic-window-tb-flip-vertical'), 'compare':container.querySelector('.pv-pic-window-tb-compare') }; this.toolMap=toolMap; var preButton=container.querySelector('.pv-pic-window-pre'); preButton.addEventListener('click',function(e){ e.preventDefault(); e.stopPropagation(); self.switchImage(false); },false); var nextButton=container.querySelector('.pv-pic-window-next'); nextButton.addEventListener('click',function(e){ e.preventDefault(); e.stopPropagation(); self.switchImage(true); },false); if (gallery && (gallery.shown || gallery.minimized)) { preButton.style.display = "none"; nextButton.style.display = "none"; } this.imgStateBox = container.querySelector('.pv-pic-search-state'); this.imgState = container.querySelector('.pv-pic-search-state>span'); this.preButton = container.querySelector('.pv-pic-window-pre'); this.nextButton = container.querySelector('.pv-pic-window-next'); let downloadIcon = container.querySelector('.pv-pic-search-state>svg'); downloadIcon.addEventListener('click', function(e) { if (!self.data || !self.img) { debug(self); return; } downloadImg(self.img.src, (self.data.img.title || self.data.img.alt), prefs.saveName); }); //关闭 var closeButton=container.querySelector('.pv-pic-window-close'); closeButton.style.cssText='top: -22px;right: 0px;'; this.closeButton=closeButton; closeButton.addEventListener('click',function(e){ self.remove(); },false); var maxButton=container.querySelector('.pv-pic-window-max'); maxButton.style.cssText='top: -22px;right: 46px;'; this.maxButton=maxButton; maxButton.addEventListener('click',async function(e){ if(!gallery){ gallery=new GalleryC(); gallery.data=[]; } var allData=await gallery.getAllValidImgs(); if(allData.length<1)return; allData.target={src:img.src}; gallery.data=allData; gallery.load(gallery.data); self.remove(); },false); //var searchButton=container.querySelector('.pv-pic-window-search'); //searchButton.style.cssText='top: -22px;right: 50px;'; //this.searchButton=searchButton; var srcs, from; img.onerror=function(e){ //setSearchState(i18n("loadNextSimilar"),img.parentNode); if(self.removed || !self.isImg)return; console.info(img.src+" "+i18n("loadError")); if(!self.data)return; var src; if(self.data.srcs) src=self.data.srcs.shift(); if(src)img.src=src; else{ if(img.src!=self.data.imgSrc) img.src=self.data.imgSrc; return; if(from 1) { for (let i = 0; i < this.data.all.length; i++) { if (this.data.all[i] == this.data.src) { this.curIndex = i; break; } } } img.onload = function(e) { if (self.removed) return; self.loaded = true; container.style.background=''; if (self.preview && img.naturalHeight == 1 && img.naturalWidth == 1) { self.remove(); return; } self.imgWindow.style.display = ""; self.imgNaturalSize = { h:img.naturalHeight, w:img.naturalWidth, }; self.setToolBadge('zoom',self.zoomLevel); if (self==uniqueImgWin && prefs.floatBar.globalkeys.previewFollowMouse) { self.following=true; self.followPos(uniqueImgWinInitX, uniqueImgWinInitY); } else { if (!self.zoomed) { if (!self.imgWindow.classList.contains("pv-pic-window-scroll")) { self.zoomLevel=0; self.zoom(1); } if (self == uniqueImgWin) { self.initMaxSize(); } if (prefs.imgWindow.fitToScreen) { self.fitToScreen(); } if (self.initPos) { self.imgWindow.style.left = self.initPos.left; self.imgWindow.style.top = self.initPos.top; } else self.center(true, true); } } self.imgWindow.style.opacity = 1; self.keepScreenInside(); var wSize = getWindowSize(); wSize.h -= 16; wSize.w -= 16; self.isLongImg = self.imgNaturalSize.h >= wSize.h && self.imgNaturalSize.h / self.imgNaturalSize.w > 2.5; } if (imgNaturalSize.h && imgNaturalSize.w) { container.style.background=''; setSearchState(img.naturalWidth + " x " + img.naturalHeight, self.imgState); } if (!this.isImg) { img.naturalHeight = img.videoHeight || 80; img.naturalWidth = img.videoWidth || 300; setTimeout(() => { img.onload(); }, 0); } /*searchButton.addEventListener('click',function(e){ sortSearch(); searchImgByImg(self.img.src, self.img.parentNode, function(srcs, index){ from=index; self.srcs=srcs; self.img.src=srcs.shift(); }); },false);*/ /** * 说明 * 1、对原来的适应屏幕等功能会有影响,暂时禁用。 * 2、分为 absolute 和默认的2种情况 */ if (this.data) { var descriptionSpan = container.querySelector('.pv-pic-window-description'); let desc = (this.data.description || '').trim(); descriptionSpan.textContent = desc; this.imgStateBox.title = desc; descriptionSpan.style.display = desc ? "inline" : "none"; this.descriptionSpan = descriptionSpan; } var toolbar=container.querySelector('.pv-pic-window-toolbar'); toolbar.style.cssText='\ top: 0px;\ left: -42px;\ '; this.toolbar=toolbar; this.selectedToolClass='pv-pic-window-tb-tool-selected'; this.viewRange=container.querySelector('.pv-pic-window-range'); this.rotateIndicator=container.querySelector('.pv-pic-window-rotate-indicator'); this.rotateIPointer=container.querySelector('.pv-pic-window-rotate-indicator-pointer'); this.rotateOverlayer=container.querySelector('.pv-pic-window-rotate-overlayer'); this.hKeyUp=true; this.rKeyUp=true; this.zKeyUp=true; this.spaceKeyUp=true; this.ctrlKeyUp=true; this.altKeyUp=true; this.shiftKeyUp=true; this.moving=false; //缩放工具的扩展菜单 container.querySelector('.pv-pic-window-tb-tool-extend-menu-zoom').addEventListener('click',function(e){ var target=e.target; var text=target.title; var value; switch(text){ case '1':{ value=1; }break; case '+0.1':{ value=self.zoomLevel + 0.1; }break; case '-0.1':{ value=self.zoomLevel - 0.1; }break; }; if(typeof value!='undefined'){ self.zoom(value,{x:0,y:0}); }; },true); //旋转工具的扩展菜单 container.querySelector('.pv-pic-window-tb-tool-extend-menu-rotate').addEventListener('click',function(e){ var target=e.target; var text=target.title; var value; function convert(deg){ return deg * Math.PI/180; }; switch(text){ case '0':{ value=0; }break; case '+90':{ value=self.rotatedRadians + convert(90); }break; case '-90':{ value=self.rotatedRadians - convert(90); }break; }; var PI=Math.PI; if(typeof value!='undefined'){ if(value>=2*PI){ value-=2*PI; }else if(value<0){ value+=2*PI; }; self.rotate(value,true); }; },true); toolbar.addEventListener('mousedown',function(e){//鼠标按下选择工具 self.toolbarEventHandler(e); },false); toolbar.addEventListener('click',function(e){ e.preventDefault(); e.stopPropagation(); },false); toolbar.addEventListener('dblclick',function(e){//鼠标双击工具 self.toolbarEventHandler(e); },false); //阻止浏览器对图片的默认控制行为 img.addEventListener('mousedown',function(e){ e.preventDefault(); },false); container.addEventListener('mousedown',function(e){//当按下的时,执行平移,缩放,旋转操作 self.imgWindowEventHandler(e); },false); container.addEventListener('touchstart',function(e){//当按下的时,执行平移,缩放,旋转操作 self.imgWindowEventHandler(e); },{ passive: true, capture: false }); container.addEventListener('click',function(e){//阻止opera ctrl+点击保存图片 self.imgWindowEventHandler(e); },false); if(prefs.imgWindow.zoom.mouseWheelZoom){//是否使用鼠标缩放 addWheelEvent(container,function(e){//滚轮缩放 self.imgWindowEventHandler(e); },false); }; //是否点击图片外部关闭 if(prefs.imgWindow.overlayer.shown && prefs.imgWindow.close.clickOutside){ var clickOutside=function(e){ var target=e.target; if(!container.contains(target)){ self.remove(); document.removeEventListener(prefs.imgWindow.close.clickOutside,clickOutside,true); }; }; this.clickOutside=clickOutside; document.addEventListener(prefs.imgWindow.close.clickOutside,clickOutside,true); }; //是否双击图片本身关闭 if(prefs.imgWindow.close.dblClickImgWindow){ var dblClickImgWindow=function(e){ var target=e.target; if(target==container || target==img || target==self.imgState || target==self.rotateOverlayer){ self.remove(); e.stopPropagation(); }; e.preventDefault(); }; container.addEventListener('dblclick',dblClickImgWindow,true); }; if (!this.preview) { ImgWindowC.all.push(this); } this._blur=this.blur.bind(this); this._focusedKeydown=this.focusedKeydown.bind(this); this._focusedKeyup=this.focusedKeyup.bind(this); if(prefs.imgWindow.overlayer.shown){//是否显示覆盖层 var overlayer=ImgWindowC.overlayer; if(!overlayer){ overlayer=document.createElement('span'); ImgWindowC.overlayer=overlayer; overlayer.className='pv-pic-window-overlayer'; }; overlayer.style.backgroundColor=prefs.imgWindow.overlayer.color; getBody(document).appendChild(overlayer); overlayer.style.display='block'; }; if(prefs.imgWindow.backgroundColor){ this.imgWindow.style.backgroundColor=prefs.imgWindow.backgroundColor; } getBody(document).appendChild(container); this.rotatedRadians=0;//已经旋转的角度 this.zoomLevel=0; this.zoom(1); this.setToolBadge('zoom',1); this.firstOpen(); this.imgWindow.style.opacity=1; //选中默认工具 this.selectTool(prefs.imgWindow.defaultTool); }, geneCompareImg: function(src, percent) { let parent = document.createElement("div"); let compareImgCon = document.createElement("div"); compareImgCon.className = "compareImgCon"; let compareImg = document.createElement("img"); let compareSlider = document.createElement("div"); compareSlider.className = "compareSlider"; compareSlider.title = "Right mouse to bottom, hold to top"; compareImgCon.style.width = percent + "%"; compareSlider.style.left = percent + "%"; let compareSliderButton = document.createElement("button"); let self = this; let upTimer; let mouseMoveHandler = e => { clearTimeout(upTimer); if (compareSliderButton.style.display == "") { document.removeEventListener("mousemove", mouseMoveHandler); document.removeEventListener("touchmove", mouseMoveHandler); return; } e = (e.changedTouches) ? e.changedTouches[0] : e; let a = self.img.getBoundingClientRect(); let x = e.pageX - a.left; x = x - window.pageXOffset; if (x < 0) x = 0; if (x > a.width) x = a.width; compareImgCon.style.width = x / a.width * 100 + "%"; compareSlider.style.left = x / a.width * 100 + "%"; }; let beginSlide = e => { compareSliderButton.style.display = "none"; clearTimeout(upTimer); upTimer = setTimeout(() => { self.compareBox.appendChild(parent); }, 1000); document.addEventListener("mousemove", mouseMoveHandler); document.addEventListener("touchmove", mouseMoveHandler); e.preventDefault(); e.stopPropagation(); let mouseUpHandler = e => { clearTimeout(upTimer); compareSliderButton.style.display = ""; document.removeEventListener("mousemove", mouseMoveHandler); }; document.addEventListener("mouseup", mouseUpHandler); document.addEventListener("touchend", mouseUpHandler); }; compareSlider.addEventListener("mousedown", beginSlide); compareSlider.addEventListener("contextmenu", e => { self.compareBox.insertBefore(parent, self.compareBox.firstChild); e.preventDefault(); e.stopPropagation(); }); compareSlider.addEventListener("touchstart", beginSlide); compareSlider.appendChild(compareSliderButton); compareImg.src = src; compareImgCon.appendChild(compareImg); parent.appendChild(compareImgCon); parent.appendChild(compareSlider); return parent; }, compare: function(otherSrcs) { if (!otherSrcs || otherSrcs.length === 0) return; if (!this.compareBox) { let compareBox = document.createElement("div"); compareBox.className = "compareBox"; this.compareBox = compareBox; this.img.parentNode.appendChild(compareBox); this.imgWindow.classList.add("compare"); } this.compareBox.innerHTML = createHTML(""); let self = this, count = 0, compareImgConList = [], targetCompareImg; otherSrcs.forEach(src => { count++; let percent = 100 - count * (100 / (otherSrcs.length + 1)); let compareImg = self.geneCompareImg(src, percent); self.compareBox.appendChild(compareImg); compareImgConList.unshift(compareImg.children[0]); }); this.img.addEventListener("mousedown", e => { targetCompareImg = null; let percentX = e.offsetX / self.img.clientWidth * 100; for (let i = 0; i < compareImgConList.length; i++) { let compareImgCon = compareImgConList[i]; let compareWidth = parseInt(compareImgCon.style.width); if (percentX < compareWidth) { targetCompareImg = compareImgCon; targetCompareImg.style.opacity = 0; break; } } if (targetCompareImg == null) { self.img.style.opacity = 0; compareImgConList[compareImgConList.length - 1].style.overflow = "visible"; } }); this.img.addEventListener("mouseup", e => { if (targetCompareImg) { targetCompareImg.style.opacity = ""; } else { self.img.style.opacity = ""; compareImgConList[compareImgConList.length - 1].style.overflow = ""; } }); this.preButton.style.display = "none"; this.nextButton.style.display = "none"; }, switchImage:async function(fw){ if (this.data && this.data.all && this.data.all.length > 1) { let initPos = prefs.imgWindow.switchStoreLoc ? {left: this.imgWindow.style.left, top: this.imgWindow.style.top} : false; this.remove(); let imgData = this.data; let curIndex; for (curIndex = 0; curIndex < this.data.all.length; curIndex++) { if (this.data.all[curIndex] == this.data.src) break; } if (fw) { curIndex++; if (curIndex == this.data.all.length) curIndex = 0; } else { curIndex--; if (curIndex == -1) curIndex = this.data.all.length - 1; } imgData.xhr = null; imgData.src = this.data.all[curIndex]; let openType = "actual"; if (uniqueImgWin && uniqueImgWin == this) { uniqueImgWin = null; openType = "popup"; } new LoadingAnimC(imgData, openType, false, true, initPos); return; } if (!gallery) { gallery = new GalleryC(); gallery.data = []; } if (gallery.shown || gallery.minimized) { return; } var allData = await gallery.getAllValidImgs(false, true); if (allData.length <= 1) return; const validData = (data, src) => { if (!data || !data.img || !data.img.parentNode) return false; if (data.img.parentNode.classList.contains("pv-pic-window-container")) return false; if (data.src == src) return false; if (data.src && /^data:/.test(data.src) && data.src.length < 250) return false; return true; }; for (let i = 0; i < allData.length; i++) { let imgData = allData[i]; if (imgData.img == this.data.img) { if (fw) { if (i != allData.length - 1) { i++; imgData = allData[i]; while (!validData(imgData, this.data.src)) { i++; if (i == allData.length) return; imgData = allData[i]; } if (imgData && imgData.img) { let initPos = prefs.imgWindow.switchStoreLoc ? {left: this.imgWindow.style.left, top: this.imgWindow.style.top} : false; this.remove(); new LoadingAnimC(imgData, (this.actual ? "actual" : "current"), false, true, initPos); } } } else { if (i != 0) { i--; imgData = allData[i]; while (!validData(imgData, this.data.src)) { i--; if (i == -1) return; imgData = allData[i]; } if (imgData) { let initPos = prefs.imgWindow.switchStoreLoc ? {left: this.imgWindow.style.left, top: this.imgWindow.style.top} : false; this.remove(); new LoadingAnimC(imgData, (this.actual ? "actual" : "current"), false, true, initPos); } } } return; } } }, changeData:function(result){ if(this.src != result.src){ this.loaded = false; this.data = result; this.src = result.src; this.img.src = location.protocol == "https"?result.src.replace(/^https?:/,""):result.src; } }, addStyle:function(){ if (ImgWindowC.style) { if (!ImgWindowC.style.parentNode) { ImgWindowC.style = _GM_addStyle(ImgWindowC.style.innerText); } return; } ImgWindowC.style=_GM_addStyle('\ .pv-pic-window-container {\ ' + (prefs.imgWindow.fixed ? 'position: fixed;' : 'position: absolute;') + '\ background-image: initial;\ padding: 0;\ border: 3px solid rgb(255 255 255 / 50%);\ border-radius: 1px;\ line-height: 0;\ text-align: left;\ box-sizing: content-box;\ -webkit-transition: opacity 0.2s ease-out;\ transition: opacity 0.1s ease-out;\ overscroll-behavior: none;\ box-shadow: 0 0 10px 5px rgba(0,0,0,0.35);\ box-sizing: content-box;\ display: initial;\ }\ .pv-pic-window-container span {\ background-image: initial;\ float: initial;\ }\ .pv-pic-window-transition-all{\ -webkit-transition: top 0.2s ease, left 0.2s ease;\ transition: top 0.2s ease, left 0.2s ease;\ }\ .pv-pic-window-imgbox {\ position: relative;\ display: block;\ overflow: hidden;\ background-color: rgba(40, 40, 40, 0.65);\ }\ .pv-pic-window-container .compareBox {\ position: absolute;\ top: 0;\ left: 0;\ width: 100%;\ height: 100%;\ pointer-events: none;\ }\ .pv-pic-window-container .compareBox>div {\ width: 100%;\ height: 100%;\ position: absolute;\ }\ .pv-pic-window-container .compareBox>div>.compareImgCon {\ width: 100%;\ max-width: 100%;\ height: 100%;\ overflow: hidden;\ }\ .pv-pic-window-container .compareBox>div>.compareImgCon>img {\ width: auto;\ height: 100%;\ max-width: unset;\ }\ .pv-pic-window-container .compareBox>div>.compareSlider {\ position: absolute;\ top: 0;\ bottom: 0;\ width: 2px;\ background-color: rgba(255,255,255,.5);\ border-top: 0;\ border-bottom: 0;\ box-shadow: 0 0 2px rgba(0,0,0,.5);\ overflow: visible;\ z-index: 9;\ }\ .pv-pic-window-container .compareBox>div>.compareSlider>button {\ position: absolute;\ top: calc(50% - 40px);\ left: -4px;\ width: 10px;\ background-color: #ddd;\ border: 4px solid #fff;\ height: 80px;\ text-align: center;\ padding: 0;\ outline: 0;\ cursor: ew-resize;\ box-shadow: 0 0 2px rgba(0,0,0,.5);\ pointer-events: all;\ box-sizing: border-box;\ background-image: none;\ }\ .pv-pic-window-container .compareBox>div>.compareSlider>button:hover {\ background-color: #777;\ }\ .pv-pic-window-close,\ .pv-pic-window-max,\ .pv-pic-window-search,\ .pv-pic-window-toolbar,\ .pv-pic-window-tb-tool-extend-menu{\ -webkit-transition: opacity 0.2s ease-in-out;\ transition: opacity 0.2s ease-in-out;\ box-sizing: content-box;\ }\ .pv-pic-window-toolbar {\ position: absolute;\ background-color: #535353;\ padding: 0;\ opacity: 0.5;\ display: none;\ cursor: default;\ -o-user-select: none;\ -webkit-user-select: none;\ -moz-user-select: -moz-none;\ user-select: none;\ }\ .pv-pic-window-toolbar:hover {\ opacity: 1;\ }\ .pv-pic-window-container_focus:not(.preview)>.pv-pic-window-toolbar {\ display: block;\ }\ .pv-pic-window-container:hover>.pv-pic-window-max,\ .pv-pic-window-container:hover>.pv-pic-window-close{\ opacity: 0.5!important;\ }\ span.pv-pic-window-close {\ cursor: pointer;\ position: absolute;\ right: 0px;\ top: -22px;\ background: url("'+prefs.icons.close+'") no-repeat center bottom;\ height: 17px;\ width: 46px;\ opacity: 0.5;\ border:none;\ padding:0;\ padding-top:2px;\ background-color:#1771FF;\ display: none;\ z-index: 2;\ }\ .pv-pic-window-container>.pv-pic-window-close:hover {\ background-color:red;\ opacity: 1!important;\ }\ .pv-pic-window-container_focus:not(.preview)>.pv-pic-window-close {\ display: block;\ }\ span.pv-pic-window-search {\ cursor: pointer;\ position: absolute;\ right: 50px;\ top: -22px;\ background: url("'+prefs.icons.searchBtn+'") no-repeat center bottom;\ height: 17px;\ width: 46px;\ opacity: 0.9;\ border:none;\ padding:0;\ padding-top:2px;\ background-color:#1771FF;\ display: none;\ }\ span.pv-pic-window-max {\ cursor: pointer;\ position: absolute;\ right: 46px;\ top: -22px;\ background: url("'+prefs.icons.maxBtn+'") no-repeat center bottom;\ height: 17px;\ width: 46px;\ opacity: 0.5;\ border:none;\ border-right: 1px solid #868686;\ padding:0;\ padding-top:2px;\ background-color:#1771FF;\ display: none;\ z-index: 2;\ }\ .pv-pic-window-container>.pv-pic-window-max:hover {\ background-color:red;\ opacity: 1!important;\ }\ .pv-pic-window-container_focus:not(.preview)>.pv-pic-window-max {\ display: block;\ }\ .pv-pic-window-search:hover {\ background-color:red;\ opacity: 1;\ }\ .pv-pic-window-container_focus:not(.preview)>.pv-pic-window-search {\ display: block;\ }\ .pv-pic-window-description {\ display: none;\ background: yellow;\ margin: 0 -5px 0 15px;\ padding: 3px;\ color: black;\ text-shadow: 0 0 0px black;\ }\ .pv-pic-window-description::before {\ display: inline-block;\ content:"";\ position: absolute;\ border: 10px solid transparent;\ margin-left: -22px;\ border-right-color: yellow;\ }\ span.pv-pic-window-pre,\ span.pv-pic-window-next{\ -webkit-transition: opacity 0.3s ease;\ transition: opacity 0.3s ease;\ position: absolute;\ height: 100px;\ top: calc(50% - 50px);\ width: 36px;\ background: #ffffff60 no-repeat center;\ opacity: 0;\ cursor: pointer;\ pointer-events: none;\ }\ span.pv-pic-window-pre {\ left: 0;\ background-image: url("'+prefs.icons.arrowLeft+'");\ }\ span.pv-pic-window-next {\ right: 0;\ background-image: url("'+prefs.icons.arrowRight+'");\ }\ .compare>.pv-pic-search-state{\ display: none;\ }\ .pv-pic-window-container_focus:not(.preview) .pv-pic-window-imgbox:hover~.pv-pic-window-pre,\ .pv-pic-window-container_focus:not(.preview) .pv-pic-window-imgbox:hover~.pv-pic-window-next{\ opacity:0.3;\ pointer-events: all;\ }\ .pv-pic-window-container>.pv-pic-window-pre:hover,\ .pv-pic-window-container>.pv-pic-window-next:hover{\ opacity:1;\ pointer-events: all;\ }\ .pv-pic-window-container:hover>.pv-pic-search-state{\ border-radius: 0 0 8px 0;\ top: 0px;\ opacity:0.5;\ }\ .pv-pic-window-container>.pv-pic-window-pre:hover~span.pv-pic-search-state,\ .pv-pic-window-container>.pv-pic-window-next:hover~span.pv-pic-search-state{\ opacity:0;\ }\ .pv-pic-window-container>span.pv-pic-search-state:hover{\ overflow:visible;\ background:none;\ }\ .pv-pic-window-container>span.pv-pic-search-state:hover>span{\ opacity: 0;\ }\ .pv-pic-window-container>span.pv-pic-search-state:hover>svg{\ display: block;\ }\ span.pv-pic-search-state {\ top: -21px;\ left: 0px;\ display: block;\ position: absolute;\ z-index: 1;\ color: #ffff00;\ height: 18px;\ line-height: 18px;\ opacity:0.8;\ font-size: small;\ transition: all 0.3s ease;\ user-select: none;\ -webkit-box-sizing: content-box;\ box-sizing: content-box;\ border-radius: 1px;\ background: rgb(0 0 0 / 80%);\ max-width: 100%;\ overflow: hidden;\ }\ .pv-pic-search-state>span {\ pointer-events: none;\ padding: 1px 5px;\ white-space: nowrap;\ overflow: hidden;\ }\ .pv-pic-search-state>span>b {\ background: yellow;\ color: black;\ margin-right: -5px;\ padding: 3px;\ }\ span.pv-pic-search-state>.pv-icon {\ width: 20px;\ height: 20px;\ vertical-align: middle;\ fill: currentColor;\ overflow: hidden;\ position: absolute;\ left: 1px;\ top: 1px;\ background: black;\ border-radius: 15px;\ padding: 5px;\ color: white;\ cursor: pointer;\ display: none;\ transition: all 0.3s ease;\ }\ .pv-pic-search-state>.pv-icon:hover {\ color: #ffff00;\ }\ .pv-pic-search-state>.pv-icon * {\ pointer-events: none;\ }\ .pv-pic-window-container_focus:not(.preview)>.pv-pic-search-state {\ opacity:0.8;\ }\ .pv-pic-window-scrollSign {\ display: none;\ width: 100px;\ height: auto;\ fill: black;\ top: 10px;\ right: 0px;\ position: absolute;\ opacity: 0;\ -webkit-animation: scroll_sign_opacity 2s 3 ease-in-out;\ animation: scroll_sign_opacity 2s 3 ease-in-out;\ }\ @-webkit-keyframes scroll_sign_opacity {\ 0% { opacity: 0 }\ 50% { opacity: 1 }\ 100% { opacity: 0 }\ }\ @keyframes scroll_sign_opacity {\ 0% { opacity: 0 }\ 50% { opacity: 1 }\ 100% { opacity: 0 }\ }\ .pv-pic-window-scroll {\ max-height: calc(100vh - 2px);\ max-width: 100vw;\ }\ .pv-pic-window-scroll>.pv-pic-window-imgbox {\ max-height: calc(100vh - 2px);\ max-width: 100vw;\ overflow-y: scroll;\ overflow-x: hidden;\ overscroll-behavior: contain;\ -ms-scroll-chaining: contain;\ }\ .pv-pic-window-scroll>.pv-pic-window-scrollSign {\ display: block;\ }\ .pv-pic-window-scroll>.pv-pic-window-close,\ .pv-pic-window-scroll>.pv-pic-window-max {\ display: none;\ }\ .transition-transform{\ transition: transform 0.3s ease;\ }\ .transition-all{\ transition: all 0.3s ease;\ }\ .pv-pic-window-pic {\ position: relative;\ display:inline-block;\/*opera把图片设置display:block会出现渲染问题,会有残影,还会引发其他各种问题,吓尿*/\ max-width:unset;\ min-width:unset;\ max-height:unset;\ min-height:unset;\ width:inherit;\ height:inherit;\ padding:0;\ margin:0;\ border:none;\ vertical-align:middle;\ }\ .pv-pic-window-container.preview {\ pointer-events: none;\ }\ .pv-pic-window-container_focus:not(.preview) .pv-pic-window-imgbox {\ box-shadow: 0 0 6px black;\ }\ span.pv-pic-window-container_focus:not(.preview) .pv-pic-window-pic {\ background: linear-gradient( 45deg, rgba(255, 255, 255, 0.4) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.4) 75%, rgba(255, 255, 255, 0.4) 100% ), linear-gradient( 45deg, rgba(255, 255, 255, 0.4) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.4) 75%, rgba(255, 255, 255, 0.4) 100% );\ background-size: 20px 20px;\ background-position: 0 0, 10px 10px;\ }\ span.pv-pic-window-tb-tool,\ span.pv-pic-window-tb-command{\ box-sizing:content-box;\ -moz-box-sizing:content-box;\ -webkit-box-sizing:content-box;\ height: 24px;\ width: 24px;\ padding: 12px 8px 6px 6px;\ margin:0;\ display: block;\ background: transparent no-repeat center;\ cursor: pointer;\ position: relative;\ border: none;\ border-left: 2px solid transparent;\ border-bottom: 1px solid #868686;\ background-origin: content-box;\ }\ .pv-pic-window-toolbar > span:last-child {\ border-bottom: none;\ }\ .pv-pic-window-tb-tool:hover,\ .pv-pic-window-tb-command:hover{\ border-left: 2px solid red;\ }\ .pv-pic-window-tb-tool-selected{\ box-shadow: inset 0 21px 0 rgba(255,255,255,0.3) ,inset 0 -21px 0 rgba(0,0,0,0.3);\ border-left:2px solid #1771FF;\ }\ span.pv-pic-window-tb-hand {\ background-image: url("'+prefs.icons.hand+'");\ }\ span.pv-pic-window-tb-rotate {\ background-image: url("'+prefs.icons.rotate+'");\ }\ span.pv-pic-window-tb-zoom {\ background-image: url("'+prefs.icons.zoom+'");\ }\ span.pv-pic-window-tb-flip-horizontal {\ background-image: url("'+prefs.icons.flipHorizontal+'");\ }\ span.pv-pic-window-tb-flip-vertical {\ background-image: url("'+prefs.icons.flipVertical+'");\ }\ span.pv-pic-window-tb-compare {\ background-image: url("'+prefs.icons.compare+'");\ }\ .pv-pic-window-tb-tool-badge-container {\ display: block;\ position: relative;\ }\ span.pv-pic-window-tb-tool-badge {\ position: absolute;\ top: -3px;\ right: 1px;\ font-size: 10px;\ line-height: 1.5;\ padding: 0 3px;\ background-color: #F93;\ border-radius: 50px;\ opacity: 0.5;\ color: black;\ }\ span.pv-pic-window-tb-tool-extend-menu{\ position:absolute;\ top:0;\ margin-left:-1px;\ background-color:#535353;\ display:none;\ left:40px;\ color:#C3C3C3;\ font-size:12px;\ text-shadow:0px -1px 0px black;\ opacity:0.7;\ }\ .pv-pic-window-tb-tool-extend-menu:hover{\ opacity:0.9;\ }\ .pv-pic-window-tb-tool-extend-menu-item{\ display:block;\ line-height:1.5;\ text-align:center;\ padding:10px;\ cursor:pointer;\ border: none;\ border-right: 2px solid transparent;\ border-bottom: 1px solid #868686;\ font-size: 20px;\ }\ .pv-pic-window-tb-tool-extend-menu-item>svg{\ pointer-events: none;\ }\ .pv-pic-window-tb-tool-extend-menu-item:last-child{\ border-bottom: none;\ }\ .pv-pic-window-tb-tool-extend-menu-item:hover{\ border-right:2px solid red;\ }\ .pv-pic-window-tb-tool-extend-menu-item:active{\ padding:11px 9px 9px 11px;\ }\ .pv-pic-window-tb-tool-extend-menu-container:hover .pv-pic-window-tb-tool{\ border-left:2px solid red;\ }\ .pv-pic-window-tb-tool-extend-menu-container:hover .pv-pic-window-tb-tool-extend-menu{\ display:block;\ }\ .pv-pic-window-tb-tool-extend-menu-container::after{\ content:"";\ position:absolute;\ right:1px;\ bottom:2px;\ width:0;\ height:0;\ padding:0;\ margin:0;\ border:3px solid #C3C3C3;\ border-top-color:transparent;\ border-left-color:transparent;\ opacity:0.5;\ }\ .pv-pic-window-overlayer{\ height:100%;\ width:100%;\ position:fixed;\ top:0;\ left:0;\ z-index: '+prefs.imgWindow.zIndex+';\ }\ span.pv-pic-window-rotate-indicator{\ display:none;\ position:fixed;\ width:250px;\ height:250px;\ padding:10px;\ margin-top:-135px;\ margin-left:-135px;\ background:transparent url("'+ prefs.icons.rotateIndicatorBG +'") no-repeat center;\ }\ span.pv-pic-window-rotate-indicator-pointer{\ display:block;\ margin-left:auto;\ margin-right:auto;\ background:transparent url("'+ prefs.icons.rotateIndicatorPointer +'") no-repeat center;\ width:60px;\ height:240px;\ position:relative;\ top:5px;\ transform:rotate(0.1deg);\ }\ .pv-pic-window-rotate-overlayer{/*当切换到旋转工具的时候显示这个覆盖层,然后旋转指示器显示在这个覆盖层的下面*/\ position:absolute;\ top:0;\ bottom:0;\ left:0;\ right:0;\ display:none;\ background-color:transparent;\ }\ .pv-pic-window-range{\ position:absolute;\ border:none;\ width:100px;\ height:100px;\ box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.8);\ display:none;\ padding:0;\ background-color:rgba(255, 0, 0, 0.150);\ }\ .pv-pic-window-container::-webkit-scrollbar, .pv-pic-window-container>.pv-pic-window-imgbox::-webkit-scrollbar { width: 0 !important }\ .pv-pic-window-container, .pv-pic-window-container>.pv-pic-window-imgbox { -ms-overflow-style: none;overflow: -moz-scrollbars-none; }\ '); }, firstOpen:function(){ ImgWindowC.selectedTool='hand'; this.imgWindow.classList.remove("pv-pic-window-scroll"); this.focus(); var imgWindow=this.imgWindow; var scrolled=prefs.imgWindow.fixed ? {x:0, y:0} : getScrolled(); imgWindow.style.left=-5 + scrolled.x + 'px'; imgWindow.style.top=-5 + scrolled.y + 'px'; //window的尺寸 var wSize=getWindowSize(); //空隙 wSize.h -= 16; wSize.w -= 16; var imgWindowCS=unsafeWindow.getComputedStyle(imgWindow); var rectSize={ h:parseFloat(imgWindowCS.height), w:parseFloat(imgWindowCS.width), }; this.isLongImg=rectSize.h > wSize.h && rectSize.h/rectSize.w > 2.5; if(prefs.imgWindow.suitLongImg && this.isLongImg){ this.center(rectSize.w <= wSize.w,false); this.imgWindow.classList.add("pv-pic-window-scroll"); }else if(prefs.imgWindow.fitToScreen){ this.fitToScreen(); this.center(true,true); }else{ this.center(rectSize.w <= wSize.w , rectSize.h <= wSize.h); } if (this.initPos) { this.imgWindow.style.left = this.initPos.left; this.imgWindow.style.top = this.initPos.top; } this.keepScreenInside(); }, keepScreenInside:function(){//保持按钮在屏幕里面. var imgWindow=this.imgWindow; var imgWindowFullSize={ h:imgWindow.offsetHeight, w:imgWindow.offsetWidth, }; var windowSize=getWindowSize(); function keepSI(obj,offsetDirection,defaultValue, out){ var objRect=obj.getBoundingClientRect(); var objStyle=obj.style; while(offsetDirection.length){ var oD=offsetDirection[0]; var oDV=defaultValue[0]; var outV=0; if(out)outV=out.shift(); offsetDirection.shift(); defaultValue.shift(); var oValue=parseFloat(objStyle[oD]); var newValue; switch(oD){ case 'top': newValue=oValue - objRect.top - outV; if(objRect.top-outV<=0){ newValue=Math.min(newValue,imgWindowFullSize.h); }else{ newValue=Math.max(newValue,oDV); }; break; case 'right': newValue=oValue + (objRect.right - windowSize.w) + outV; if(objRect.right+outV >= windowSize.w){//屏幕外 newValue=Math.min(newValue,imgWindowFullSize.w); }else{ newValue=Math.max(newValue,oDV); }; break; case 'bottom': newValue=oValue + (objRect.bottom - windowSize.h) + outV; if(objRect.bottom+outV >= windowSize.h){//屏幕外 newValue=Math.min(newValue,imgWindowFullSize.h); }else{ newValue=Math.max(newValue,oDV); }; break; case 'left': newValue=oValue - objRect.left - outV; if(objRect.left-outV<=0){ newValue=Math.min(newValue,imgWindowFullSize.w); }else{ newValue=Math.max(newValue,oDV); } break; } objStyle[oD]=newValue + 'px'; } } keepSI(this.closeButton,['top','right'],[-22,0]); keepSI(this.maxButton,['top','right'],[-22,46],[0,46]); //keepSI(this.searchButton,['top','right'],[-22,50]); keepSI(this.toolbar,['top','left'],[0,-42]); // 保持注释在图片里面 //keepSI(this.descriptionSpan,['bottom', 'left'],[-40, 10]); }, initMaxSize: function() { let wSize = getWindowSize(); let maxWidth = wSize.w - 50, maxHeight = wSize.h - 50, left, top; if (prefs.floatBar.previewMaxSizeW && maxWidth > prefs.floatBar.previewMaxSizeW) { maxWidth = prefs.floatBar.previewMaxSizeW; } if (prefs.floatBar.previewMaxSizeW && maxHeight > prefs.floatBar.previewMaxSizeH) { maxHeight = prefs.floatBar.previewMaxSizeH; } if (this.zoomLevel === 1) { this.zoomLevel = 0; this.zoom(1); } let imgWindowCS = unsafeWindow.getComputedStyle(this.imgWindow); let rectSize = { h: parseFloat(imgWindowCS.height), w: parseFloat(imgWindowCS.width), }; let size, containsScroll = this.imgWindow.classList.contains("pv-pic-window-scroll"); if (prefs.imgWindow.fitToScreenSmall || rectSize.w > maxWidth || rectSize.h > maxHeight) { if (rectSize.w / rectSize.h > maxWidth / maxHeight) { size = { w: maxWidth, h: maxWidth / (rectSize.w / rectSize.h), }; } else if (!containsScroll) { size = { h: maxHeight, w: maxHeight * (rectSize.w / rectSize.h), } }; let cs = this.getRotatedImgCliSize(size); let ns = this.imgNaturalSize; if (cs && ns && cs.w && ns.w) { this.zoom(cs.w / ns.w); } } }, followPos: function(posX, posY) { if (this.removed) return; if (!prefs.floatBar.globalkeys.previewFollowMouse) return; let imgWindow = this.imgWindow; if (!imgWindow) return; this.followPosX = posX; this.followPosY = posY; if (!this.following) { clearTimeout(this.followPosTimer); this.followPosTimer = setTimeout(() => { if (this.previewed) return; this.following = true; imgWindow.classList.add("pv-pic-window-transition-all"); this.followPos(this.followPosX, this.followPosY); }, 50); return; } this.following = false; let wSize = getWindowSize(); let padding1 = Math.min(250, wSize.h>>2, wSize.w>>2), padding2 = 50, left, top;//内外侧间距 let scrolled = prefs.imgWindow.fixed ? {x: 0, y: 0} : getScrolled(); this.initMaxSize(); if (imgWindow.offsetWidth / imgWindow.offsetHeight > wSize.w / wSize.h) { //宽条,上下半屏 if (posY > wSize.h / 2) { //上 top = posY - imgWindow.offsetHeight - padding1 + scrolled.y; if (top < padding2>>1) top = padding2>>1; imgWindow.style.top = top + 'px'; } else { //下 top = posY + padding1 + scrolled.y; if (top > wSize.h - imgWindow.offsetHeight - 1) top = wSize.h - imgWindow.offsetHeight - 1; imgWindow.style.top = top + 'px'; } left = (wSize.w - imgWindow.offsetWidth) / 2; let maxLeft = posX + padding1; if (left > maxLeft) left = maxLeft; else { let minLeft = posX - imgWindow.offsetWidth - padding1; if (left < minLeft) left = minLeft; } imgWindow.style.left = left + scrolled.x + 'px'; } else { //窄条,左右半屏 if (posX > wSize.w / 2) { //左 left = posX - imgWindow.offsetWidth - padding1 + scrolled.x; if (left < 1) left = 1; imgWindow.style.left = left + 'px'; } else { //右 left = posX + padding1 + scrolled.x; if (left > wSize.w - imgWindow.offsetWidth - 1) left = wSize.w - imgWindow.offsetWidth - 1; imgWindow.style.left = left + 'px'; } top = (wSize.h - imgWindow.offsetHeight) / 2; let maxTop = posY + padding1; if (top > maxTop) top = maxTop; else { let minTop = posY - imgWindow.offsetHeight - padding1; if (top < minTop) top = minTop; } imgWindow.style.top = top + scrolled.y + 'px'; } }, fitToScreen:function(){ let imgWindow = this.imgWindow; if (!prefs.imgWindow.fitToScreen) return; let wSize=getWindowSize(); //空隙 wSize.h -= 6; wSize.w -= 6; let imgWindowCS = unsafeWindow.getComputedStyle(imgWindow); let rectSize = { h: parseFloat(imgWindowCS.height), w: parseFloat(imgWindowCS.width), }; let size, containsScroll = imgWindow.classList.contains("pv-pic-window-scroll"); if (prefs.imgWindow.fitToScreenSmall || rectSize.w - wSize.w > 0 || rectSize.h - wSize.h > 0) {//超出屏幕,那么缩小。 if (rectSize.w / rectSize.h > wSize.w / wSize.h) { size = { w: wSize.w, h: wSize.w / (rectSize.w / rectSize.h), }; } else if (!containsScroll) { size = { h: wSize.h, w: wSize.h * (rectSize.w / rectSize.h), } }; let cs = this.getRotatedImgCliSize(size); let ns = this.imgNaturalSize; if (cs && ns && cs.w && ns.w) { this.zoom(cs.w / ns.w); } }; }, center:function(horizontal,vertical){ if(!horizontal && !vertical)return; var imgWindow=this.imgWindow; if(!imgWindow)return; var wSize=getWindowSize(); var scrolled=prefs.imgWindow.fixed ? {x:0, y:0} : getScrolled(); if(horizontal)imgWindow.style.left = (wSize.w - imgWindow.offsetWidth)/2 + scrolled.x +'px'; if(vertical)imgWindow.style.top = (wSize.h - imgWindow.offsetHeight)/2 + scrolled.y +'px'; }, move:function(e){ this.working=true; var cursor=this.cursor; this.changeCursor('handing'); var mouseCoor={ x:e.pageX || e.touches[0].pageX, y:e.pageY || e.touches[0].pageY, }; var imgWindow=this.imgWindow; var imgWStyle=imgWindow.style; var oriOffset={ left:parseFloat(imgWStyle.left), top:parseFloat(imgWStyle.top), }; var self=this; var moveHandler=function(e){ imgWStyle.left=oriOffset.left+ (e.pageX || e.touches[0].pageX)-mouseCoor.x +'px'; imgWStyle.top=oriOffset.top + (e.pageY || e.touches[0].pageY)-mouseCoor.y +'px'; self.keepScreenInside(); self.moving=true; }; var mouseupHandler=function(){ e.preventDefault(); self.changeCursor(cursor); self.working=false; if(self.tempHand && self.spaceKeyUp){//如果是临时切换到抓手工具,平移完成后返回上个工具 self.tempHand=false; self.changeCursor(self.selectedTool); }; document.removeEventListener('mousemove',moveHandler,true); document.removeEventListener('mouseup',mouseupHandler,true); document.removeEventListener('touchmove',moveHandler,true); document.removeEventListener('touchend',mouseupHandler,true); }; document.addEventListener('mousemove',moveHandler,true); document.addEventListener('mouseup',mouseupHandler,true); document.addEventListener('touchmove',moveHandler,true); document.addEventListener('touchend',mouseupHandler,true); }, rotate:function(origin,topLeft){ var img=this.img; var imgWindow=this.imgWindow; imgWindow.classList.remove("pv-pic-window-scroll"); var iTransform=img.style[support.cssTransform].replace(/rotate\([^)]*\)/i,''); var imgWindowCS=unsafeWindow.getComputedStyle(imgWindow); var imgRectSize={ h:parseFloat(imgWindowCS.height), w:parseFloat(imgWindowCS.width), }; var rectOffset={ top:parseFloat(imgWindow.style.top), left:parseFloat(imgWindow.style.left), }; var imgSize={ h:img.clientHeight, w:img.clientWidth, }; var imgOffset={ top:parseFloat(img.parentNode.style.top), left:parseFloat(img.parentNode.style.left), }; var self=this; var PI=Math.PI; var rotate = function (radians) { if (self.rotatedRadians == radians) return; if (self.working) { img.parentNode.style[support.cssTransform] = ' rotate(' + radians + 'rad) ' + iTransform; } else { img.parentNode.classList.remove("transition-transform"); img.parentNode.style[support.cssTransform] = ' rotate('+ radians +'rad) ' + iTransform; setTimeout(()=>{ img.parentNode.classList.add("transition-transform"); },0); } self.rotateIPointer.style[support.cssTransform]='rotate('+ radians +'rad)';//旋转指示器 self.rotatedRadians=radians; self.setToolBadge('rotate',radians/(PI/180)); var afterimgRectSize=self.getRotatedImgRectSize( radians, imgSize ); imgWindow.style.width=afterimgRectSize.w +'px'; imgWindow.style.height=afterimgRectSize.h + 'px'; if(!topLeft){ self.setImgWindowOffset(rectOffset,imgRectSize,afterimgRectSize); }; self.setImgOffset(imgOffset,imgRectSize,afterimgRectSize); self.keepScreenInside(); }; if(typeof origin=='number'){ rotate(origin); return; }; this.working=true; var lastRotatedRadians=this.rotatedRadians; this.shiftKeyUp=true; var shiftRotateStep=prefs.imgWindow.shiftRotateStep / (180/Math.PI);//转成弧度 var moveHandler=function(e){ self.rotateIndicator.style.display='block'; var radians=lastRotatedRadians + Math.atan2( e.clientY - origin.y, e.clientX - origin.x ); if(radians>=2*PI){ radians-=2*PI; }else if(radians<0){ radians+=2*PI; }; if(!self.shiftKeyUp){//如果按下了shift键,那么步进缩放 radians -= radians % shiftRotateStep; radians += shiftRotateStep; }; rotate(radians); }; var mouseupHandler=function(){ self.working=false; self.rotateIndicator.style.display='none'; document.removeEventListener('mousemove',moveHandler,true); document.removeEventListener('mouseup',mouseupHandler,true); self.img.parentNode.classList.add("transition-transform"); }; self.img.parentNode.classList.remove("transition-transform"); document.addEventListener('mousemove',moveHandler,true); document.addEventListener('mouseup',mouseupHandler,true); }, convertToValidRadians:function(radians){ //转成0-90的等价角度。 var PI=Math.PI; if(radians > PI){ radians = 2*PI - radians; }; if(radians > 1/2*PI){ radians = PI - radians; }; return radians; }, getRotatedImgRectSize:function( radians, imgSize ){//通过旋转后的角度和图片的大小,求虚拟矩形的大小 imgSize= imgSize ? imgSize :{ h:this.img.clientHeight, w:this.img.clentWidth, }; if(typeof radians==='undefined'){ radians = this.rotatedRadians; }; radians=this.convertToValidRadians(radians); return { h:this.notExponential(imgSize.h* Math.cos(radians) + imgSize.w * Math.sin(radians)), w:this.notExponential(imgSize.h* Math.sin(radians) + imgSize.w * Math.cos(radians)), }; }, getRotatedImgCliSize:function(rectSize,radians){//通过虚拟矩形的大小和图片的旋转角度,求图片的大小 if(typeof radians==='undefined'){ radians = this.rotatedRadians; }; radians=this.convertToValidRadians(radians); if(radians==0){ //radians=Math.PI/180 * 1/100; return rectSize; }; var h=(rectSize.h-rectSize.w * Math.tan(radians))/(Math.cos(radians)-Math.sin(radians)*Math.tan(radians)); var w=(rectSize.h - h*Math.cos(radians))/Math.sin(radians); return { h:h, w:w, }; }, setImgOffset:function(oriOffset,bImgSize,aImgSize){ var imgStyle=this.img.parentNode.style; //避免出现指数形式的数字和单位相加,导致变成无效值 var top=this.notExponential(oriOffset.top + (aImgSize.h-bImgSize.h)*1/2) + 'px'; var left=this.notExponential(oriOffset.left + (aImgSize.w-bImgSize.w)*1/2) + 'px'; imgStyle.top= top; imgStyle.left= left; }, setImgWindowOffset:function(oriOffset,bImgWindowSize,aImgWidnowSize,ratio){ ratio= ratio? ratio : {x:1/2,y:1/2}; var imgWindowStyle=this.imgWindow.style; var top=oriOffset.top - (aImgWidnowSize.h-bImgWindowSize.h)*ratio.y + 'px'; var left=oriOffset.left - (aImgWidnowSize.w-bImgWindowSize.w)*ratio.x + 'px'; imgWindowStyle.top= top; imgWindowStyle.left= left; }, zoom:function(e,ratio){//e可能是undefined,可能是事件对象,可能是直接的缩放级别数字 var imgWindow=this.imgWindow; var imgWindowCS=unsafeWindow.getComputedStyle(imgWindow); var imgRectSize={ h:parseFloat(imgWindowCS.height), w:parseFloat(imgWindowCS.width), }; var rectOffset={ top:parseFloat(imgWindow.style.top), left:parseFloat(imgWindow.style.left), }; var img=this.img; var self=this; var zoom=function(level){//缩放到指定级别 if(typeof level=='undefined' || level<0 || level==self.zoomLevel)return; var afterImgSize={ h:self.imgNaturalSize.h * level || 10, w:self.imgNaturalSize.w * level || 10, }; img.width=afterImgSize.w; img.height=afterImgSize.h; img.parentNode.style.width=afterImgSize.w + 'px'; img.parentNode.style.height=afterImgSize.h + 'px'; if (afterImgSize.w < 60) { self.imgState.style.display = "none"; } else { self.imgState.style.display = ""; } if (afterImgSize.w < 220) { self.maxButton.style.opacity = "0"; self.closeButton.style.opacity = "0"; } else { self.maxButton.style.opacity = ""; self.closeButton.style.opacity = ""; } if (afterImgSize.w < 100 || afterImgSize.h < 100) { self.preButton.style.left = "-36px"; self.nextButton.style.right = "-36px"; } else { self.preButton.style.left = "0px"; self.nextButton.style.right = "0px"; } var afterimgRectSize=self.getRotatedImgRectSize( self.rotatedRadians, afterImgSize ); imgWindow.style.width=afterimgRectSize.w +'px'; imgWindow.style.height=afterimgRectSize.h + 'px'; self.setImgWindowOffset(rectOffset,imgRectSize,afterimgRectSize,ratio); self.setImgOffset({top:0,left:0},afterImgSize,afterimgRectSize);//如果旋转了,调整偏移 self.zoomLevel=level; self.setToolBadge('zoom',level); self.keepScreenInside(); }; if(typeof e!='object'){ ratio=ratio? ratio : { x:1/2, y:1/2, }; zoom(e); return; }; this.working=true; ratio=this.getZoomRatio({ x:e.clientX, y:e.clientY, }); var moved; var lastPageX=e.pageX; var currentLevel=this.zoomLevel; var moveFired=0; var moveHandler=function(e){ moveFired++ if(moveFired < 2){//有时候点击的时候不小心会触发一发move return; }; moved=true; var pageX=e.pageX; var level; if(pageX > lastPageX){//向右移,zoomin扩大 self.changeCursor('zoom',false); level=0.05; }else{//向左移,zoomout缩小 self.changeCursor('zoom',true); level=-0.05; }; lastPageX=pageX; currentLevel += level; zoom(currentLevel); }; var mouseupHandler=function(e){ self.working=false; document.removeEventListener('mousemove',moveHandler,true); document.removeEventListener('mouseup',mouseupHandler,true); var level=self.getNextZoomLevel(); if(self.zoomOut && self.altKeyUp){ self.zoomOut=false; }; if(!moved){//如果没有平移缩放。 zoom(level); }; self.changeCursor('zoom',self.zoomOut); if(self.tempZoom && self.ctrlKeyUp && self.altKeyUp){ self.tempZoom=false; self.changeCursor(self.selectedTool); }; }; document.addEventListener('mousemove',moveHandler,true); document.addEventListener('mouseup',mouseupHandler,true); }, getNextZoomLevel:function(){ var level; var self=this; if(this.zoomOut){//缩小 let found = ImgWindowC.zoomRangeR.find(function(value){ if(value < self.zoomLevel){ level=value; return true; } }); if (!found) { level = self.zoomLevel * 0.9; } }else{ let found = ImgWindowC.zoomRange.find(function(value){ if(value > self.zoomLevel){ level=value; return true; }; }); if (!found) { level = self.zoomLevel * 1.1; } } return level; }, getZoomRatio:function(mouseCoor){ var ibcRect=this.img.getBoundingClientRect(); var ratio={ x:(mouseCoor.x-ibcRect.left)/ibcRect.width, y:(mouseCoor.y-ibcRect.top)/ibcRect.height, }; if(ratio.x<0){ ratio.x=0 }else if(ratio.x>1){ ratio.x=1 }; if(ratio.y<0){ ratio.y=0 }else if(ratio.y>1){ ratio.y=1 }; return ratio; }, aerialView:function(e){ this.working=true; //记住现在的缩放比例 var cLevel=this.zoomLevel; var wSize=getWindowSize(); wSize.h -= 16; wSize.w -= 16; var imgWindow=this.imgWindow; var imgWindowCS=unsafeWindow.getComputedStyle(imgWindow); var rectSize={ h:parseFloat(imgWindowCS.height), w:parseFloat(imgWindowCS.width), }; var rectRatio=rectSize.h/rectSize.w; var windowRatio=wSize.h/wSize.w; var size; var rangeSize={}; if(rectRatio > windowRatio){ size={ h:wSize.h, w:wSize.h / rectRatio, }; rangeSize.h=Math.min(wSize.h * (size.h / rectSize.h), size.h); rangeSize.w=Math.min(rangeSize.h / windowRatio , size.w); }else{ size={ w:wSize.w, h:wSize.w * rectRatio, }; rangeSize.w=Math.min(wSize.w * (size.w / rectSize.w), size.w); rangeSize.h=Math.min(rangeSize.w * windowRatio , size.h); }; this.zoom(this.getRotatedImgCliSize(size).w/this.imgNaturalSize.w); this.center(true,true); this.keepScreenInside(); var viewRange=this.viewRange; var vRS=viewRange.style; vRS.display='block'; vRS.height=rangeSize.h + 'px'; vRS.width=rangeSize.w + 'px'; vRS.top=0 + 'px'; vRS.left=0 + 'px'; var viewRangeRect=viewRange.getBoundingClientRect(); var scrolled=prefs.imgWindow.fixed ? {x:0, y:0} : getScrolled(); var viewRangeCenterCoor={ x:viewRangeRect.left + scrolled.x + 1/2 * rangeSize.w, y:viewRangeRect.top + scrolled.y + 1/2 * rangeSize.h, }; var self=this; var moveRange={ x:[8,8+size.w-rangeSize.w], y:[8,8+size.h-rangeSize.h] }; function setViewRangePosition(pageXY){ var top=pageXY.y - viewRangeCenterCoor.y; var left=pageXY.x - viewRangeCenterCoor.x; if(top<=moveRange.y[0]){ top=moveRange.y[0]; }else if(top>=moveRange.y[1]){ top=moveRange.y[1]; }; vRS.top= top + 'px'; if(left<=moveRange.x[0]){ left=moveRange.x[0]; }else if(left>=moveRange.x[1]){ left=moveRange.x[1]; }; vRS.left= left + 'px'; }; setViewRangePosition({ x:e.pageX, y:e.pageY, }); var moveHandler=function(e){ setViewRangePosition({ x:e.pageX, y:e.pageY, }); }; var mouseupHandler=function(){ self.working=false; viewRange.style.display='none'; self.zoom(cLevel); var scrolled=prefs.imgWindow.fixed ? {x:0, y:0} : getScrolled(); imgWindow.style.top= -13 - rectSize.h * ((parseFloat(vRS.top) - moveRange.y[0])/size.h) + scrolled.y +'px'; imgWindow.style.left= -13 - rectSize.w * ((parseFloat(vRS.left) - moveRange.x[0])/size.w) + scrolled.x +'px'; //说明图片的高度没有屏幕高,居中 //说明图片的宽度没有屏幕宽,居中 self.center(rangeSize.w == size.w , rangeSize.h == size.h); self.keepScreenInside(); document.removeEventListener('mousemove',moveHandler,true); document.removeEventListener('mouseup',mouseupHandler,true); }; document.addEventListener('mousemove',moveHandler,true); document.addEventListener('mouseup',mouseupHandler,true); }, setToolBadge:function(tool,content){ var scale=0; switch(tool){ case 'zoom':{ scale=2; if (this.img.naturalWidth) { setSearchState(this.img.naturalWidth + " x " + this.img.naturalHeight + " (" + parseInt(content * 100) + "%)" + (this.curIndex >=0 ? ` [${this.curIndex + 1}/${this.data.all.length}]` : ""), this.imgState); this.descriptionSpan && this.imgState.appendChild(this.descriptionSpan); } }break; case 'rotate':{ scale=1; }break; default:break; } content=typeof content=='string'? content : content.toFixed(scale); this.toolMap[tool].nextElementSibling.textContent=content; }, notExponential:function(num){//不要转为指数形势 if(num>0){ if(num >= 999999999999999934463){ return 999999999999999934463; }else if(num <= 0.000001){ return 0.000001; }; }else if(num < 0){ if(num >= -0.000001){ return -0.000001; }else if(num <= -999999999999999934463){ return -999999999999999934463 }; }; return num; }, blur:function(e){ if(!this.focused)return; ImgWindowC.showing = false; var imgWindow =this.imgWindow; //点击imgWinodw的外部的时候失去焦点 if(e!==true && imgWindow.contains(e.target))return; imgWindow.classList.remove('pv-pic-window-container_focus'); document.removeEventListener('mousedown',this._blur,true); document.removeEventListener('keydown',this._focusedKeydown,false); document.removeEventListener('keyup',this._focusedKeyup,true); this.changeCursor('default'); ImgWindowC.selectedTool=this.selectedTool; this.imgWindow.style.zIndex= prefs.imgWindow.zIndex; this.zIndex=prefs.imgWindow.zIndex; this.focused=false; }, focus:function(){ if(this.focused)return; this.toolMap.compare.style.display = ImgWindowC.all.length > 1 ? "" : "none"; ImgWindowC.showing = true; this.imgWindow.classList.add('pv-pic-window-container_focus'); this.imgWindow.style.zIndex=prefs.imgWindow.zIndex+1; this.zIndex=prefs.imgWindow.zIndex+1; document.addEventListener('keydown',this._focusedKeydown,false); document.addEventListener('keyup',this._focusedKeyup,true); document.addEventListener('mousedown',this._blur,true); //还原鼠标样式。 this.changeCursor(this.selectedTool); if(prefs.imgWindow.syncSelectedTool && ImgWindowC.selectedTool){ this.selectTool(ImgWindowC.selectedTool); }; this.focused=true; }, focusedKeyup:function(e){ var keyCode=e.keyCode; var valid=[32,18,16,72,17,72,82,90,67,37,39]; if(valid.indexOf(keyCode)==-1)return; e.preventDefault(); switch(keyCode){ case 32:{//空格键,临时切换到移动 this.spaceKeyUp=true; if(!this.tempHand)return;//如果之前没有临时切换到抓手工具(当已经在工作的时候,按下空格不会临时切换到抓手工具) if(!this.working){//松开按键的时候,没有在继续平移了。 this.tempHand=false; this.changeCursor(this.selectedTool); }; }break; case 18:{//alt键盘切换缩小放大。 this.altKeyUp=true; if(!this.zoomOut)return; if(!this.working){ this.zoomOut=false; this.changeCursor('zoom'); if(this.tempZoom && this.ctrlKeyUp){ this.tempZoom=false; this.changeCursor(this.selectedTool); }; }; }break; case 16://shift键,旋转的时候按住shift键,步进缩放。 this.shiftKeyUp=true; break; case 17:{//ctrl键 clearTimeout(this.ctrlkeyDownTimer); if(!this.justCKeyUp){//如果刚才没有松开c,规避划词软件的ctrl+c松开 this.ctrlKeyUp=true; if(!this.tempZoom)return;//如果没有切换到了缩放 if(!this.working && this.altKeyUp){ this.tempZoom=false; this.changeCursor(this.selectedTool); }; }; }break; case 67:{//c键 this.justCKeyUp=true; var self=this; clearTimeout(this.justCKeyUpTimer); this.justCKeyUpTimer=setTimeout(function(){ self.justCKeyUp=false; _GM_setClipboard(self.src); },100) }break; case 72://h键 this.hKeyUp=true; break; case 82://r键 this.rKeyUp=true; break; case 90://z键 this.zKeyUp=true; break; case 39: this.switchImage(true); break; case 37: this.switchImage(false); break; default:break; }; if([72,82,90].indexOf(keyCode)!=-1){ if(!this.working && this.restoreBeforeTool){ this.restoreBeforeTool=false; this.selectTool(this.beforeTool); }; }; }, focusedKeydown:async function(e){ var keyCode=e.keyCode; if (this.data && this.data.img && e.key.toLowerCase() == prefs.floatBar.keys.download) { downloadImg(this.img.src, (this.data.img.title || this.data.img.alt), prefs.saveName); e.preventDefault(); e.stopPropagation(); return; } var valid=[32,82,72,90,18,16,17,27,67,71];//有效的按键 if(valid.indexOf(keyCode)==-1) return; e.preventDefault(); if(this.working){//working的时候也可以接受按下shift键,以便旋转的时候可以任何时候按下 if(keyCode==16){//shift键 this.shiftKeyUp=false; }; return; }; if (e.key == prefs.floatBar.keys.gallery) { if (!gallery) { gallery = new GalleryC(); gallery.data = []; } var allData = await gallery.getAllValidImgs(); if (allData.length < 1) return; allData.target = {src: this.img.src}; gallery.data = allData; gallery.load(gallery.data); this.remove(); } else { switch(keyCode){ case 82:{//r键,切换到旋转工具 if(this.rKeyUp){ this.rKeyUp=false; this.beforeTool=this.selectedTool; if (this.beforeTool != 'rotate') { this.selectTool('rotate'); } var PI = Math.PI; var value = this.rotatedRadians + (e.shiftKey ? -90 : 90) * PI / 180; if (value >= 2 * PI) { value -= 2 * PI; } else if (value < 0) { value += 2 * PI; } this.rotate(value,true); }; }break; case 72:{//h键,切换到抓手工具 if(this.hKeyUp){ this.hKeyUp=false; this.beforeTool=this.selectedTool; this.selectTool('hand'); }; }break; case 90:{//z键,切换到缩放工具 if(this.zKeyUp){ this.zKeyUp=false; this.beforeTool=this.selectedTool; this.selectTool('zoom'); let level = e.shiftKey ? (this.zoomLevel - 0.5) : (this.zoomLevel + 0.5); if (typeof level != 'undefined') { this.zoom(level, { x: 0, y: 0}); } }; }break; case 32:{//空格键阻止,临时切换到抓手功能 if(this.spaceKeyUp){ this.spaceKeyUp=false; if(this.selectedTool!='hand'){ this.tempHand=true; this.changeCursor('hand'); }; }; }break; case 18:{//alt键,在当前选择是缩放工具的时候,按下的时候切换到缩小功能 if(this.altKeyUp){ if((this.selectedTool!='zoom' && !this.tempZoom) || this.zoomOut)return; this.zoomOut=true; this.altKeyUp=false; this.changeCursor('zoom',true); }; }break; case 17:{//ctrl键临时切换到缩放工具 if(this.ctrlKeyUp){ var self=this; this.ctrlkeyDownTimer=setTimeout(function(){//规避词典软件的ctrl+c,一瞬间切换到缩放的问题 self.ctrlKeyUp=false; if(self.selectedTool!='zoom'){ self.tempZoom=true; self.changeCursor('zoom'); }; },100); }; }break; case 67:{//c键 clearTimeout(this.ctrlkeyDownTimer); }break; case 27:{//ese关闭窗口 if(prefs.imgWindow.close.escKey){ this.remove(); }; }break; default:break; } } e.stopPropagation(); return false; }, toolbarEventHandler:function(e){ e.preventDefault(); e.stopPropagation(); var target=e.target; var toolMap=this.toolMap; for(var i in toolMap){ if(toolMap.hasOwnProperty(i) && toolMap[i]==target){ switch(e.type){ case 'mousedown':{ this.selectTool(i); }break; case 'dblclick':{ this.dblclickCommand(i); }break; default:break; }; break; }; }; }, imgWindowEventHandler:function(e){ if (e.button == 0) { e.stopPropagation(); } var selectedTool=this.selectedTool; if(selectedTool == "hand" && prefs.imgWindow.suitLongImg && this.isLongImg){ var inScroll=this.imgWindow.classList.contains("pv-pic-window-scroll"); if(e.type == "wheel" && inScroll) return; if(e.type == "click" && !this.moving){ var wSize=getWindowSize(); var imgWindow=this.imgWindow; var scrolled=prefs.imgWindow.fixed ? {x:0, y:0} : getScrolled(); var origTop=parseFloat(imgWindow.style.top); if(inScroll){ imgWindow.style.top = parseFloat(imgWindow.style.top) - getScrolled(imgWindow.children[0]).y +'px'; this.imgWindow.classList.remove("pv-pic-window-scroll"); } else { this.rotate(0,true); this.imgWindow.classList.add("pv-pic-window-scroll"); imgWindow.children[0].scrollTop = -parseInt(imgWindow.style.top); } //this.center(true , true); if(!inScroll){ imgWindow.style.top= (wSize.h - imgWindow.offsetHeight)/2 + scrolled.y +'px'; var scrollTop=parseFloat(imgWindow.style.top)-origTop; if(this.imgWindow.scrollTop)this.imgWindow.scrollTop = scrollTop; else if(this.imgWindow.pageYOffset)this.imgWindow.pageYOffset = scrollTop; else if(this.imgWindow.scrollY)this.imgWindow.scrollY = scrollTop; } this.keepScreenInside(); } } switch(e.type){ case 'click':{//阻止opera的图片保存 this.moving=false; if(e.ctrlKey && e.target.nodeName.toUpperCase()=='IMG'){ e.preventDefault(); } }break; case 'mousedown': case 'touchstart':{ if(!this.focused){//如果没有focus,先focus this.focus(); this.keepScreenInside(); }; var target=e.target; if(e.button==2){//由于rotate时候的覆盖层问题,修复右键的图片菜单弹出 if(target!=this.rotateOverlayer)return; var self=this; this.rotateOverlayer.style.display='none'; var upHandler=function(){ document.removeEventListener('mouseup',upHandler,true); setTimeout(function(){ self.rotateOverlayer.style.display='block'; },10); }; document.addEventListener('mouseup',upHandler,true); return; }; if((e.button!=0 && e.type!="touchstart") || (target!=this.imgWindow && target!=this.img && target!=this.rotateOverlayer && target!=this.imgState))return; e.preventDefault(); if(this.tempHand){ this.move(e); }else if(this.tempZoom){ this.zoom(e); }else if(selectedTool=='hand'){ this.restoreBeforeTool=!this.hKeyUp; if(this.hKeyUp){ this.move(e); }else{//鸟瞰视图 this.aerialView(e); }; }else if(selectedTool=='rotate'){ var origin={//旋转原点 x:e.clientX - 30,//稍微偏左一点。 y:e.clientY , }; var rIS=this.rotateIndicator.style; //rIS.display='block'; rIS.top=origin.y + 'px'; rIS.left=origin.x + 'px'; this.restoreBeforeTool=!this.rKeyUp; this.rotate(origin); }else if(selectedTool=='zoom'){ this.restoreBeforeTool=!this.zKeyUp; this.zoom(e); }; }break; case 'wheel':{ if(!this.focused)return;//如果没有focus if(e.deltaY===0)return;//非Y轴的滚动 e.preventDefault(); if(this.working)return; var oriZoomOut=this.zoomOut; this.zoomOut = !!(e.deltaY > 0); var ratio=this.getZoomRatio({ x:e.clientX, y:e.clientY, }); var level=this.getNextZoomLevel(); this.zoomed=true; this.zoom(level,ratio); this.zoomOut=oriZoomOut; }break; default:break; }; }, dblclickCommand:function(tool){ var done; switch(tool){ case 'hand':{//双击居中,并且适应屏幕 this.zoom(1); this.fitToScreen(); this.center(true,true); this.keepScreenInside(); }break; case 'rotate':{//双击还原旋转 if(this.rotatedRadians==0)return; done=true; this.rotate(0,true); }break; case 'zoom':{//双击还原缩放 if(this.zoomLevel==1)return; done=true; this.zoom(1,{x:0,y:0}); }break; default:break; }; if((tool=='rotate' || tool=='zoom') && done){ var scrolled=prefs.imgWindow.fixed ? {x:0, y:0} : getScrolled(); var imgWindow=this.imgWindow; var imgWinodowRect=imgWindow.getBoundingClientRect(); var imgWindowStyle=imgWindow.style; if(imgWinodowRect.left<40){ imgWindowStyle.left=40 + scrolled.x + 'px'; }; if(imgWinodowRect.top<-5){ imgWindowStyle.top=-5 + scrolled.y +'px'; }; this.keepScreenInside(); }; }, doFlipCommand:function(command){ var map={ fv:[/scaleY\([^)]*\)/i,' scaleY(-1) '], fh:[/scaleX\([^)]*\)/i,' scaleX(-1) '], }; var iTransform=this.img.parentNode.style[support.cssTransform]; var toolClassList=this.toolMap[command].classList; if(map[command][0].test(iTransform)){ iTransform=iTransform.replace(map[command][0],''); toolClassList.remove(this.selectedToolClass); }else{ iTransform += map[command][1]; toolClassList.add(this.selectedToolClass); }; this.img.parentNode.style[support.cssTransform]=iTransform; }, selectTool:function(tool){ var command=['fv','fh']; if(command.indexOf(tool)==-1){//工具选择 if(this.selectedTool==tool){ return; } let self=this; if(tool=="compare"){ var topmost=0, topmostWin; ImgWindowC.all.forEach(function(iwin){ if(iwin.zIndex >= topmost && iwin!=self){ topmost=iwin.zIndex; topmostWin=iwin; }; }); if(topmostWin){ this.toolMap.compare.style.display="none"; this.compare([topmostWin.img.src]); }; return; } var selectedTool=this.selectedTool; this.selectedTool=tool; if(this.tempHand || this.tempZoom){//临时工具中。不变鼠标 return; }; this.rotateOverlayer.style.display=(tool=='rotate'? 'block' : 'none');//这个覆盖层是为了捕捉双击或者单击事件。 if(selectedTool){ this.toolMap[selectedTool].classList.remove(this.selectedToolClass); }; this.toolMap[tool].classList.add(this.selectedToolClass); this.changeCursor(tool); }else{//命令 this.doFlipCommand(tool); }; }, changeCursor:function(tool,zoomOut){ if(tool=='zoom'){ tool+=zoomOut? '-out' : '-in'; }; if(this.cursor==tool)return; this.cursor=tool; var cursor; switch(tool){ case 'hand':{ cursor=support.cssCursorValue.grab || 'pointer'; }break; case 'handing':{ cursor=support.cssCursorValue.grabbing || 'pointer'; }break; case 'zoom-in':{ cursor=support.cssCursorValue.zoomIn; }break; case 'zoom-out':{ cursor=support.cssCursorValue.zoomOut; }break; case 'rotate':{ cursor='progress'; }break; case 'default':{ cursor=''; }break; }; if(typeof cursor!='undefined'){ this.imgWindow.style.cursor=cursor; }; }, remove:function(opacity){ if(this.removed)return; this.removed=true; //this.imgWindow.classList.remove("pv-pic-window-transition-all"); this.blur(true); if(!opacity)this.imgWindow.style.opacity=0; let self = this; setTimeout(function(){ if (self.isImg) self.img.src= prefs.icons.brokenImg_small;//如果在加载中取消,图片也取消读取。 self.imgWindow.parentNode.removeChild(self.imgWindow); },300); if (!this.preview) { var index=ImgWindowC.all.indexOf(this); ImgWindowC.all.splice(index,1); } var removeEvent=document.createEvent('CustomEvent'); removeEvent.initCustomEvent('pv-removeImgWindow',false,false); this.imgWindow.dispatchEvent(removeEvent); //focus next if(ImgWindowC.all.length==0){ if(ImgWindowC.overlayer){ ImgWindowC.overlayer.style.display='none'; }; }else{ var topmost=0, topmostWin; ImgWindowC.all.forEach(function(iwin){ if(iwin.zIndex >= topmost){ topmost=iwin.zIndex; topmostWin=iwin; } }); if(topmostWin){ topmostWin.focus(); } } }, }; addWheelEvent(getBody(document), e => { if (uniqueImgWin && !uniqueImgWin.removed) { if (uniqueImgWin.isLongImg) { e.preventDefault(); e.stopPropagation(); uniqueImgWin.img.parentNode.scrollTop += e.deltaY; } else if (uniqueImgWin.curIndex >= 0) { e.preventDefault(); e.stopPropagation(); uniqueImgWin.switchImage(e.deltaY > 0); } } }, true); // 载入动画 function LoadingAnimC(data, buttonType, waitImgLoad, openInTopWindow, initPos) { if (LoadingAnimC.all.find(function(item, index, array) { if (data.src == item.data.src || data.img == item.data.img) { return true; } })) return false; this.args = arrayFn.slice.call(arguments, 0); if (data.src != data.imgSrc && !data.srcs) { data.srcs = [data.imgSrc]; } this.data = data;//data this.buttonType = buttonType;//点击的按钮类型 this.openInTopWindow = openInTopWindow;//是否在顶层窗口打开,如果在frame里面的话 this.waitImgLoad = waitImgLoad;//是否等待完全读取后打开 this.initPos = initPos || false; this.init(); } LoadingAnimC.all=[]; LoadingAnimC.prototype={ init:function(){ LoadingAnimC.all.push(this); this.addStyle(); var container=document.createElement('span'); container.className='pv-loading-container'; this.loadingAnim=container; container.title=i18n("loading")+':' + this.data.src; let retrySpan=document.createElement('span'); retrySpan.className='pv-loading-button pv-loading-retry'; retrySpan.title='Retry'; container.appendChild(retrySpan); let cancelSpan=document.createElement('span'); cancelSpan.className='pv-loading-button pv-loading-cancle'; cancelSpan.title='Cancel'; container.appendChild(cancelSpan); /*container.innerHTML= ''+ '';*/ if (this.buttonType == 'popup'){ container.style.pointerEvents="none"; } getBody(document).appendChild(container); var self = this; container.addEventListener('click',function(e){ var tcl=e.target.classList; if(tcl.contains('pv-loading-cancle')){ self.imgReady && self.imgReady.abort(); self.remove(); }else if(tcl.contains('pv-loading-retry')){ self.remove(); new LoadingAnimC(self.args[0],self.args[1],self.args[2],self.args[3]); }; },true); this.setPosition(); if (!this.data.noActual && (this.buttonType == 'current' || this.buttonType == 'gallery')) { this.loadImg(this.data.imgSrc); } else { if (!this.data.xhr) { if(this.buttonType == 'search'){ sortSearch(); let from=0; let searchFun=function(){ searchImgByImg(self.data.imgSrc, null, function(srcs, index){ let src=srcs.shift(); if(index==3){ self.loadImg(src, srcs); }else{ from=index+1; self.loadImg(src, srcs, searchFun); } },function(e) { self.error("网络错误"); },function(e) { self.error("没有找到原图"); }, from); }; searchFun(); }else{ this.loadImg(this.data.src||this.data.imgSrc, this.data.srcs); } } else { xhrLoad.load({ url: this.data.src, xhr: this.data.xhr, cb: function(imgSrc, imgSrcs, caption) { if (imgSrc) { self.data.src = imgSrc; self.data.all = imgSrcs; if (caption) self.data.description = caption; self.loadImg(imgSrc, imgSrcs); } else { self.error(); } }, onerror: function() { self.error(); } }); } } }, addStyle:function(){ if (LoadingAnimC.style) { if (!LoadingAnimC.style.parentNode) { LoadingAnimC.style = _GM_addStyle(LoadingAnimC.style.innerText); } return; } LoadingAnimC.style=_GM_addStyle('\ .pv-loading-container {\ position: absolute;\ z-index:999999997;\ background: black url("'+prefs.icons.loading+'") center no-repeat;\ background-origin: content-box;\ border: none;\ padding: 1px 30px 1px 2px;\ margin: 0;\ opacity: 0.5;\ height: 24px;\ min-width: 24px;\ box-shadow: 2px 2px 0px #666;\ -webkit-transition: opacity 0.15s ease-in-out;\ transition: opacity 0.15s ease-in-out;\ width: initial;\ }\ .pv-loading-container:hover {\ opacity: 0.9;\ }\ .pv-loading-button {\ cursor: pointer;\ height: 24px;\ width: 24px;\ position: absolute;\ right: 0;\ top: 0;\ opacity: 0.4;\ background:transparent center no-repeat;\ -webkit-transition: opacity 0.15s ease-in-out;\ transition: opacity 0.15s ease-in-out;\ }\ .pv-loading-button:hover {\ opacity: 1;\ }\ .pv-loading-cancle{\ pointer-events: all;\ background-image: url("'+prefs.icons.loadingCancle+'");\ }\ .pv-loading-retry{\ display:none;\ pointer-events: all;\ background-image: url("'+prefs.icons.retry+'");\ }\ .pv-loading-container_error{\ background-image:none;\ }\ .pv-loading-container_error::after{\ content:"'+i18n("loadError")+'";\ line-height: 24px;\ color: red;\ font-size: 14px;\ display:inline;\ }\ .pv-loading-container_error .pv-loading-cancle{\ display:none;\ }\ .pv-loading-container_error .pv-loading-retry{\ display:block;\ }\ '); }, remove:function(){ if(!this.removed){ this.removed=true; this.loadingAnim.parentNode.removeChild(this.loadingAnim); LoadingAnimC.all.splice(LoadingAnimC.all.indexOf(this),1); }; }, error:function(msg,img,e){ if(msg)debug(msg); this.loadingAnim.style.pointerEvents=""; this.loadingAnim.classList.add('pv-loading-container_error'); debug('Picviewer CE+ 载入大图错误:%o', this.data); var self=this; setTimeout(function(){ self.remove(); },3000); }, setPosition:function(){ var position=getContentClientRect(this.data.img); var cs=this.loadingAnim.style; var scrolled=getScrolled(); cs.top=position.top + scrolled.y +1 + 'px'; cs.left=position.left + scrolled.x +1 + 'px'; cs.removeProperty('display'); }, // 根据 imgSrc 载入图片,imgSrcs 为备用图片地址,imgSrc 加载失败备用 loadImg: function(imgSrc, imgSrcs, nextFun) { var self = this; var mode = matchedRule.getMode(imgSrc); var media; if (this.buttonType === 'magnifier') { media = document.createElement('img'); media.src = (mode === "video" || mode === "audio") ? this.data.imgSrc : imgSrc; mode = ""; } else { switch (mode) { case "video": media = document.createElement('video'); media.style.width = 0; media.style.height = 0; media.controls = true; media.loop = true; media.autoplay = true; imgSrc = imgSrc.replace(/^video:/, ""); if (imgSrc.indexOf('.mkv') !== -1) media.type = 'video/mp4'; break; case "audio": media = document.createElement('audio'); media.controls = true; media.autoplay = true; media.volume = 1; imgSrc = imgSrc.replace(/^audio:/, ""); break; default: media = document.createElement('img'); break; } media.src = imgSrc; } var opts = { error: function(e) { if (Array.isArray(imgSrcs)) { var src = imgSrcs.shift(); if (src) { self.loadImg(src, imgSrcs, nextFun); return; } } if(nextFun) nextFun(); else self.error('', this, e); }, }; opts[self.waitImgLoad ? 'load' : 'ready'] = function(e) { self.load(this, e); }; if (mode === 'video' || mode === 'audio') { let loaded = function() { media.play(); self.load(this); media.removeEventListener('loadeddata', loaded); } media.addEventListener('loadeddata', loaded); media.load(); } else { self.imgReady = imgReady(media, opts); } }, load:async function(img,e){ this.remove(); this.img=img; var buttonType=this.buttonType; if(buttonType=='gallery'){ if(!gallery){ gallery=new GalleryC(); gallery.data=[]; } var allData=await gallery.getAllValidImgs(); allData.target=this.data; this.data=allData; }; var self=this; function openInTop(){ var data=self.data; //删除不能发送的项。 var delCantClone=function(obj){ if(!obj)return; delete obj.img; delete obj.imgPA; }; if(Array.isArray(data)){ frameSentSuccessData=frameSentData; frameSentData=cloneObject(data,true); delCantClone(data.target); data.forEach(function(obj){ delCantClone(obj); }); }else{ delCantClone(data); }; window.postMessage({ messageID:messageID, src:img.src, data:data, command:'open', buttonType:buttonType, to:'top', },'*'); }; if(this.openInTopWindow && isFrame && topWindowValid!==false && buttonType!='magnifier'){ if(topWindowValid){ openInTop(); }else{//先发消息问问顶层窗口是不是非frameset窗口 window.postMessage({ messageID:messageID, command:'topWindowValid', to:'top', },'*'); document.addEventListener('pv-topWindowValid',function(e){ topWindowValid=e.detail; if(topWindowValid){//如果顶层窗口有效 openInTop(); }else{ self.open(); }; },true); }; }else{ this.open(); }; }, open:function(){ switch(this.buttonType){ case 'popup': if(uniqueImgWin && uniqueImgWin.src != this.data.src && (!this.data.srcs || !this.data.srcs.includes(uniqueImgWin.src))){ uniqueImgWin.remove(); } if(!uniqueImgWin || uniqueImgWin.removed){ this.data.src=this.img.src; uniqueImgWin = new ImgWindowC(this.img, this.data, null, null, true); //uniqueImgWin.imgWindow.classList.add("pv-pic-window-transition-all"); } //uniqueImgWin.blur({target:this.data.img}); if(!uniqueImgWin.loaded){ if(prefs.waitImgLoad){ uniqueImgWin.imgWindow.style.display = "none"; uniqueImgWin.imgWindow.style.opacity = 0; }else{ if (prefs.floatBar.globalkeys.previewFollowMouse) { uniqueImgWin.following=true; uniqueImgWin.followPos(uniqueImgWinInitX, uniqueImgWinInitY); } else { uniqueImgWin.initMaxSize(); uniqueImgWin.center(true,true); if(centerInterval)clearInterval(centerInterval); centerInterval=setInterval(function(){ if(!uniqueImgWin || uniqueImgWin.removed || uniqueImgWin.loaded){ clearInterval(centerInterval); }else{ uniqueImgWin.center(true,true); } },300); } } } uniqueImgWin.imgWindow.classList.add("preview"); break; case 'gallery': if(!gallery){ gallery=new GalleryC(); }; gallery.load(this.data,this.from); gallery.changeMinView(); break; case 'magnifier': new MagnifierC(this.img,this.data); break; case 'download': downloadImg(this.data.src || this.data.imgSrc, (this.data.img.title || this.data.img.alt), prefs.saveName); break; case "copy": _GM_setClipboard(this.data.src || this.data.imgSrc); break; case "open": _GM_openInTab(this.data.src || this.data.imgSrc, {active:false}); break; case "copyImg": copyData(this.data.src || this.data.imgSrc); break; case 'actual': case 'search': case 'current': case 'original'://original 是为了兼容以前的规则 if(this.data.src!=this.img.src)this.data.src=this.img.src; new ImgWindowC(this.img, this.data, this.buttonType == 'actual', this.initPos || false); break; }; }, }; function copyData(url) { if (typeof ClipboardItem != 'undefined') { urlToBlob(url, (blob, ext) => { if (blob) { try { navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); } catch (error) { console.error(error); } } }, true); } else _GM_setClipboard(url); } //工具栏 function FloatBarC(){ this.init(); }; FloatBarC.prototype={ init:function(){ this.addStyle(); var container=document.createElement('span'); container.id='pv-float-bar-container'; getBody(document).appendChild(container); for(let i=0;i<5;i++){ let spanChild=document.createElement('span'); spanChild.className='pv-float-bar-button'; container.appendChild(spanChild); } /*container.innerHTML= ''+ ''+ ''+ ''+ '';*/ var buttons={ }; this.buttons=buttons; this.children=container.children; arrayFn.forEach.call(this.children,function(child,index){ var titleMap={ actual:i18n("actualBtn").replace(/ ?\(A\)/,` (${prefs.floatBar.keys.actual.toUpperCase()})`), search:i18n("searchBtn").replace(/ ?\(S\)/,` (${prefs.floatBar.keys.search.toUpperCase()})`), gallery:i18n("galleryBtn").replace(/ ?\(G\)/,` (${prefs.floatBar.keys.gallery.toUpperCase()})`), current:i18n("currentBtn").replace(/ ?\(C\)/,` (${prefs.floatBar.keys.current.toUpperCase()})`), magnifier:i18n("magnifierBtn").replace(/ ?\(M\)/,` (${prefs.floatBar.keys.magnifier.toUpperCase()})`), download:i18n("download")+` (${prefs.floatBar.keys.download.toUpperCase()})`, }; var buttonName=prefs.floatBar.butonOrder[index]; if(!buttonName){ child.style.display="none"; return; } buttons[buttonName]=child; child.title=titleMap[buttonName]; child.classList.add('pv-float-bar-button-' + buttonName); }); this.floatBar=container; var self=this; container.addEventListener('click',function(e){ var buttonType; var target=e.target; for(var type in buttons){ if(!buttons.hasOwnProperty(type))return; if(target==buttons[type]){ buttonType=type; break; }; }; if(!buttonType)return; self.hide(); self.open(e,buttonType); },true); addCusMouseEvent('mouseleave',container,function(e){ clearTimeout(self.hideTimer); self.hideTimer=setTimeout(function(){ self.hide(); },prefs.floatBar.hideDelay); }); addCusMouseEvent('mouseenter',container,function(e){ clearTimeout(self.hideTimer); clearTimeout(self.showTimer); clearTimeout(self.globarOutTimer); }); this._scrollHandler=this.scrollHandler.bind(this); }, addStyle:function(){ if (FloatBarC.style) { if (!FloatBarC.style.parentNode) { FloatBarC.style = _GM_addStyle(FloatBarC.style.innerText); } return; } FloatBarC.style=_GM_addStyle('\ #pv-float-bar-container {\ position: absolute;\ background-image: initial;\ top: 0px;\ left: 0px;\ z-index:2147483640;\ padding: 5px;\ margin: 0;\ border: none;\ opacity: 0.35;\ line-height: 0;\ -webkit-transition: opacity 0.2s ease-in-out;\ transition: opacity 0.2s ease-in-out;\ display:none;\ }\ #pv-float-bar-container:hover {\ opacity: 1;\ }\ #pv-float-bar-container .pv-float-bar-button {\ vertical-align:middle;\ cursor: pointer;\ width: 18px;\ height: 18px;\ padding: 0;\ margin:0;\ border: none;\ display: inline-block;\ position: relative;\ box-shadow: 1px 0 3px 0px rgba(0,0,0,0.9);\ background: transparent center no-repeat;\ background-size:100% 100%;\ background-origin: content-box;\ -webkit-transition: margin-right 0.15s ease-in-out , width 0.15s ease-in-out , height 0.15s ease-in-out ;\ transition: margin-right 0.15s ease-in-out , width 0.15s ease-in-out , height 0.15s ease-in-out ;\ }\ #pv-float-bar-container .pv-float-bar-button:not(:last-child){\ margin-right: -14px;\ }\ #pv-float-bar-container .pv-float-bar-button:first-child {\ z-index: 4;\ }\ #pv-float-bar-container .pv-float-bar-button:nth-child(2) {\ z-index: 3;\ }\ #pv-float-bar-container .pv-float-bar-button:nth-child(3) {\ z-index: 2;\ }\ #pv-float-bar-container .pv-float-bar-button:last-child {\ z-index: 1;\ }\ #pv-float-bar-container:hover > .pv-float-bar-button {\ width: 24px;\ height: 24px;\ }\ #pv-float-bar-container:hover > .pv-float-bar-button:not(:last-child) {\ margin-right: 4px;\ }\ #pv-float-bar-container .pv-float-bar-button-actual {\ background-image:url("'+ prefs.icons.actual +'");\ }\ #pv-float-bar-container .pv-float-bar-button-search {\ background-image:url("'+ prefs.icons.search +'");\ }\ #pv-float-bar-container .pv-float-bar-button-gallery {\ background-image:url("'+ prefs.icons.gallery +'");\ }\ #pv-float-bar-container .pv-float-bar-button-current {\ background-image:url("'+ prefs.icons.current +'");\ }\ #pv-float-bar-container .pv-float-bar-button-magnifier {\ background-image:url("'+ prefs.icons.magnifier +'");\ }\ #pv-float-bar-container .pv-float-bar-button-download {\ background-image:url("'+ prefs.icons.download +'");\ }\ '); }, start:function(data){ //读取中的图片,不显示浮动栏,调整读取图标的位置. if(LoadingAnimC.all.find(function(item,index,array){ if (data.src == item.data.src || data.img == item.data.img) { return true; } })) return false; //被放大镜盯上的图片,不要显示浮动栏. if(MagnifierC.all.find(function(item,index,array){ if(data.src==item.data.src){ return true; }; }))return false; var self=this; clearTimeout(this.hideTimer); var imgOutHandler=function(e){ document.removeEventListener('mouseout',imgOutHandler,true); clearTimeout(self.showTimer); clearTimeout(self.hideTimer); self.hideTimer=setTimeout(function(){ self.hide(); },prefs.floatBar.hideDelay); }; clearTimeout(this.globarOutTimer); this.globarOutTimer=setTimeout(function(){//稍微延时。错开由于css hover样式发生的out; document.addEventListener('mouseout',imgOutHandler,true); },150); clearTimeout(this.showTimer); self.data=data; if (data.hide) { this.show(); this.floatBar.style.display = 'none'; this.floatBar.style.opacity = 0; return false; } if(!this.shown || self.data.img!=data.img){ this.floatBar.style.transition="unset"; this.floatBar.style.opacity=0.01; } this.showTimer=setTimeout(function(){ self.show(); },prefs.floatBar.showDelay); return true; }, setButton:function(){ if(this.buttons['actual']){ if(this.data.noActual){ this.buttons['actual'].style.display='none'; }else{ this.buttons['actual'].style.removeProperty('display'); } } if(this.buttons['magnifier']){ if(this.data.type != "force" && this.data.img.nodeName.toUpperCase() == 'IMG'){ this.buttons['magnifier'].style.removeProperty('display'); }else{ this.buttons['magnifier'].style.display='none'; } } if (this.data.img.nodeName.toUpperCase() != 'IMG') { //this.buttons['gallery'].style.display = 'none'; //this.buttons['current'].style.display = 'none'; } else { //this.buttons['gallery'].style.removeProperty('display'); //this.buttons['current'].style.removeProperty('display'); } }, setPosition: function() { //如果图片被删除了,或者隐藏了。 if (this.data.img.offsetWidth == 0) { return true; } var targetPosi = getContentClientRect(this.data.img); var pa = this.data.img.parentNode; if (pa && pa.scrollHeight > 30 && pa.scrollWidth > 30) { var paPosi=getContentClientRect(pa); if (paPosi.width > 30 && paPosi.height > 30) { if (this.data.img.offsetTop != 0) { if (paPosi.height < targetPosi.height - 3) { targetPosi.top = paPosi.top; } } if (this.data.img.offsetLeft != 0) { if (paPosi.width < targetPosi.width - 3) { targetPosi.left = paPosi.left; } } } } var windowSize=getWindowSize(); var img=this.data.img; var floatBarPosi=prefs.floatBar.position.toLowerCase().split(/\s+/); var offsetX=prefs.floatBar.offset.x; var offsetY=prefs.floatBar.offset.y; let body = getBody(document); let offsetParent, bodyPosi; if (unsafeWindow.getComputedStyle(body).position === "static") { offsetParent = document.documentElement; bodyPosi = { top: 0, bottom: windowSize.h, left: 0, right: windowSize.w }; } else { offsetParent = body; bodyPosi = offsetParent.getBoundingClientRect(); } var scrolled=getScrolled(offsetParent); targetPosi.top = targetPosi.top - bodyPosi.top + scrolled.y; targetPosi.left = targetPosi.left - bodyPosi.left + scrolled.x; targetPosi.bottom = bodyPosi.bottom - targetPosi.bottom - scrolled.y; targetPosi.right = bodyPosi.right - targetPosi.right - scrolled.x; var fbs = this.floatBar.style; var setPosition = { top:function() { var top = targetPosi.top; if (top + offsetY - scrolled.y < 10) { top = scrolled.y; offsetY = 0; } else { if (prefs.floatBar.stayOut) { top = top + offsetY - 10 - prefs.floatBar.stayOutOffsetY; } else { top = top + offsetY; } if (targetPosi.height <= 50) top -= 10; } fbs.bottom = 'unset'; fbs.top = top + 'px'; }, right:function() { var right = targetPosi.right; if (prefs.floatBar.stayOut) { right = right - offsetX - prefs.floatBar.stayOutOffsetX; } else { right = right - offsetX; } if (targetPosi.width <= 50) right += 10; fbs.left = 'unset'; fbs.right = right + 'px'; }, bottom:function() { var bottom = targetPosi.bottom; if (prefs.floatBar.stayOut) { bottom = bottom - offsetY - 40 - prefs.floatBar.stayOutOffsetY; } else { bottom = bottom - offsetY - 30; } if (targetPosi.height <= 50) bottom += 10; fbs.top = 'unset'; fbs.bottom = bottom + 'px'; }, left:function() { var left = targetPosi.left; if (left + offsetX - scrolled.x < 0) { left = scrolled.x; offsetX = 0; } else { if (prefs.floatBar.stayOut) { left = left + offsetX - prefs.floatBar.stayOutOffsetX; } else { left = left + offsetX; } if (targetPosi.width <= 50) left -= 10; } fbs.right = 'unset'; fbs.left = left + 'px'; }, center:function() { var left = targetPosi.left + offsetX; fbs.left = left + targetPosi.width / 2 + 'px'; }, hide:function(){ var top=targetPosi.top; var left=targetPosi.left; if(prefs.floatBar.stayOut){ top=top + offsetY - 10 - prefs.floatBar.stayOutOffsetY; left=left + offsetX - prefs.floatBar.stayOutOffsetX; }else{ top=top + offsetY; left=left + offsetX; } if(targetPosi.height<=50)top-=10; fbs.top=top + 'px'; if(targetPosi.width<=50)left-=10; fbs.left=left + 'px'; }, }; setPosition[floatBarPosi[0]](); if(floatBarPosi.length>1){ setPosition[floatBarPosi[1]](); } }, show:function(){ if(this.setPosition())return; this.shown=true; this.addStyle(); this.setButton(); this.floatBar.style.transition=""; this.floatBar.style.display='block'; this.floatBar.style.opacity=""; clearTimeout(this.hideTimer); window.removeEventListener('scroll',this._scrollHandler,true); window.addEventListener('scroll',this._scrollHandler,true); }, hide:function(){ clearTimeout(this.showTimer); this.floatBar.style.opacity=0.01; this.shown=false; this.floatBar.style.display='none'; window.removeEventListener('scroll',this._scrollHandler,true); }, scrollHandler:function(){//更新坐标 clearTimeout(this.scrollUpdateTimer); var self=this; this.scrollUpdateTimer=setTimeout(function(){ self.setPosition(); },100); }, open:async function(e,buttonType){ if (this.data.imgSrc.indexOf("blob:") === 0) { let blobUrl = await getBase64FromBlobUrl(this.data.imgSrc); if (blobUrl) { let sameSrc = (this.data.src === this.data.imgSrc); this.data.imgSrc = blobUrl; this.data.srcs = [this.data.imgSrc]; if (sameSrc) { this.data.src = blobUrl; } } } if (buttonType === 'download' && !this.data.xhr) { downloadImg(this.data.src || this.data.imgSrc, (this.data.img.title || this.data.img.alt), prefs.saveName); return; } else { let altKey = e.altKey; if (e.type != "click" && prefs.floatBar.globalkeys.invertInitShow && prefs.floatBar.globalkeys.alt) { altKey = false; } let additionEnable = prefs.floatBar.invertAdditionalFeature ? !altKey : altKey; if (additionEnable) { let src, feature = prefs.floatBar.additionalFeature; if (buttonType == 'actual') { if (this.data.xhr) { buttonType = feature || "open"; } else { src = this.data.src || this.data.imgSrc; } } else if (buttonType == 'current') { src = this.data.imgSrc; } if (src) { switch(feature) { case "copy": _GM_setClipboard(src); break; case "open": _GM_openInTab(src, {active:false}); break; case "copyImg": copyData(src); break; } return; } } } var waitImgLoad = e && e.ctrlKey ? !prefs.waitImgLoad : prefs.waitImgLoad; //按住ctrl取反向值 var openInTopWindow = e && e.shiftKey ? !prefs.framesPicOpenInTopWindow : prefs.framesPicOpenInTopWindow; //按住shift取反向值 if (!waitImgLoad && buttonType == 'magnifier' && !envir.chrome) { //非chrome的background-image需要全部载入后才能显示出来 waitImgLoad = true; }; new LoadingAnimC(this.data, buttonType, waitImgLoad, openInTopWindow); if (e.type == "click") { floatBar.hide(); } }, update:function(img,src){ if(this.data.img==img && this.data.imgSrc!=src){ this.data.src=src; this.data.noActual=false; this.data.type="rule"; if(this.shown){ this.setButton(); } } } }; /** * 提取自 Mouseover Popup Image Viewer 脚本,用于 xhr 方式的获取 */ var xhrLoad = function() { var _ = {}; var caches = {}; var handleError; var cacheNum = 0; var xhr; /** * @param q 图片的选择器或函数 * @param c 图片说明的选择器或函数 */ function parsePage(url, q, c, post, cb, headers, after) { downloadPage(url, post, headers, async function(html) { var iurl, iurls = [], cap, caps, doc = createDoc(html); if(typeof q == 'function') { iurl = await q(html, doc, url, xhr); if (iurl) { if(iurl.url) { cap = iurl.cap; iurl = iurl.url; } if (Array.isArray(iurl)) { iurl = iurl.map(u => after(u)); iurls = iurl; iurl = iurls[0]; } else iurl = after(iurl); } } else { var inodes = findNodes(q, doc); inodes.forEach(function(node) { iurls.push(after(findFile(node, url))); }); iurl = iurls[0]; } if (c) { if(typeof c == 'function') { cap = await c(html, doc, url, xhr); } else { var cnodes = findNodes(c, doc); cap = cnodes.length ? findCaption(cnodes[0]) : false; } if (Array.isArray(cap)) { caps = cap; cap = caps[0]; } } // 缓存 if (iurl) { let cacheData = { iurl: iurl, iurls: iurls, cap: cap, caps: caps }; caches[url] = cacheData; if (cacheNum) { storage.setListItem("xhrCache", url, cacheData, cacheNum); } } cb(iurl, iurls, cap, caps); }); } async function downloadPage(url, post, headers, cb) { var opts = { method: 'GET', url: url, onload: function(req) { try { if(req.status > 399) throw 'Server error: ' + req.status; cb(req.responseText, req.finalUrl || url); } catch(ex) { handleError(ex); } }, onerror: handleError }; if (post) { opts.method = 'POST'; opts.data = post; opts.headers = {'Content-Type':'application/x-www-form-urlencoded','Referer':url}; } if (headers) { if (typeof headers == 'function') { headers = await headers(url, xhr); } opts.headers = headers; } _GM_xmlhttpRequest(opts); } function createDoc(text) { var doc = document.implementation.createHTMLDocument('PicViewerCE'); doc.documentElement.innerHTML = text; return doc; } function findNodes(q, doc) { var nodes = [], node; if (!Array.isArray(q)) q = [q]; for (var i = 0, len = q.length; i < len; i++) { node = qs(q[i], doc); if (node && node.length) { [].forEach.call(node, n => { nodes.push(n); }); } } return nodes; } function findFile(n, url) { pretreatment(n, true); var path = n.src || n.href || (n.children && n.children[0] && n.children[0].src); return path ? path.trim() : false; } function findCaption(n) { return n.getAttribute('content') || n.getAttribute('title') || n.textContent; } function qs(s, n) { return n.querySelectorAll(s); } _.load = function(opt) { xhr = opt.xhr; var info = caches[opt.url] || storage.getListItem("xhrCache", opt.url); cacheNum = xhr.cacheNum || 0; if (info) { opt.cb(info.iurl, info.iurls, info.cap, info.caps); return; } handleError = opt.onerror || function() {}; let postParams = opt.url.match(/#p{(.*)}$/); if (!opt.post && postParams) { opt.post = postParams[1]; opt.url = opt.url.replace(/#p{.*/, ""); } parsePage(opt.url, xhr.query || xhr.q, xhr.caption || xhr.c, xhr.post, opt.cb, xhr.headers, xhr.after); }; return _; }(); // ------------------- run ------------------------- function pretreatment(img, fetchImg) { if (img.removeAttribute) img.removeAttribute("loading"); if (img.nodeName.toUpperCase() != "IMG" || (!fetchImg && img.src && !/^data/.test(img.src))) return; let src; tprules.find(function(rule, index, array) { try { src = rule.call(img); if (src) { return true; } } catch(err) { debug(err); } }); if (src) { img.src = src; } } function findPic(img){ var imgPN=img; var imgPA,imgPE=[]; while(imgPN=imgPN.parentElement){ if(imgPN.nodeName.toUpperCase()=='A'){ imgPA=imgPN; break; } } imgPN=img; while(imgPN=imgPN.parentElement){ if(imgPN.nodeName.toUpperCase()=='BODY'){ break; }else{ imgPE.push(imgPN); } } var iPASrc=imgPA? imgPA.href : ''; //base64字符串过长导致正则匹配卡死浏览器 var base64Img=/^data:/i.test(img.src); var src, // 大图地址 srcs, // 备用的大图地址 type, // 类别 noActual = false, //没有原图 imgSrc = img.currentSrc||img.src||img.dataset.lazySrc, // img 节点的 src xhr, description; // 图片的注释 var imgCStyle = unsafeWindow.getComputedStyle(img); if (!/IMG/i.test(img.nodeName) && imgCStyle && imgCStyle.backgroundImage && imgCStyle.backgroundImage != "none") { let sh = imgCStyle.height, sw = imgCStyle.width; if (!img.offsetWidth) sw = 10; if (!img.offsetHeight) sh = 10; if (imgCStyle.backgroundRepeatX == "repeat") { sw = 10; } if (imgCStyle.backgroundRepeatY == "repeat") { sh = 10; } imgCStyle = {height:sh, width:sw}; } var imgCS={ h: parseFloat(imgCStyle.height)||img.height||img.offsetHeight, w: parseFloat(imgCStyle.width)||img.width||img.offsetWidth, }; var imgAS={//实际尺寸。 h:img.naturalHeight||imgCS.h, w:img.naturalWidth||imgCS.w, }; if(!src && matchedRule.rules.length>0){// 通过高级规则获取. // 排除 try{ let newSrc=matchedRule.getImage(img,imgPA,imgPE); if(newSrc && imgSrc!=newSrc) src=newSrc; }catch(err){ throwErrorInfo(err); } if(src) { if (Array.isArray(src)) { srcs = src; src = srcs.shift(); } type = 'rule'; xhr = matchedRule.xhr; if (matchedRule.lazyAttr) { // 由于采用了延迟加载技术,所以图片可能为 loading.gif imgSrc = img.getAttribute(matchedRule.lazyAttr) || img.src; } if (matchedRule.description) { let desc = matchedRule.description, attr; if (Array.isArray(desc) && desc.length === 2) { attr = desc[1]; desc = desc[0]; } var node = getElementMix(desc, img); if (node) { description = attr ? node.getAttribute(attr) : (node.getAttribute('title') || node.textContent); } } } } if(/^IMG$/i.test(img.nodeName) && !src && iPASrc){//链接可能是一张图片... if(iPASrc!=img.src && imageReg.test(iPASrc)){ src=iPASrc; } if(src)type='scale'; } if(!src && !base64Img){//遍历通配规则 tprules.find(function(rule,index,array){ try{ src=rule.call(img,imgPA); if(src){ return true; }; }catch(err){ throwErrorInfo(err); }; }); if(src)type='tpRule'; } if(!src || src==imgSrc){//本图片是否被缩放. noActual=true; if(!(imgAS.w==imgCS.w && imgAS.h==imgCS.h)){//如果不是两者完全相等,那么被缩放了. src=imgSrc; type='scale'; if (imgAS.h < prefs.gallery.scaleSmallSize && imgAS.w < prefs.gallery.scaleSmallSize) { type='scaleSmall'; } }else{ src=imgSrc; type='force'; } } if(!src)return; var ret = { src: src, // 得到的src srcs: srcs, // 多个 src,失败了会尝试下一个 type: type, // 通过哪种方式得到的 imgSrc: imgSrc, // 处理的图片的src iPASrc: iPASrc, // 图片的第一个父a元素的链接地址 sizeH:imgAS.h, sizeW:imgAS.w, imgCS:imgCS, imgAS:imgAS, noActual:noActual, xhr: xhr, description: description || img.title || img.alt || '', img: img, // 处理的图片 imgPA: imgPA, // 图片的第一个父a元素 }; return ret; } function getMatchedRule() { return new MatchedRuleC(); /*var rule = siteInfo.find(function(site, index, array) { if (site.enabled != false && site.url && toRE(site.url).test(_URL)) { return true; } }); return rule;*/ } function MatchedRuleC(){ this.init(); } const videoExtensions = new Set(['3gpp', 'm4v', 'mkv', 'mp4', 'ogv', 'webm']); const audioExtensions = new Set(['flac', 'm4a', 'mp3', 'oga', 'ogg', 'opus', 'wav']); function isVideoLink(url) { if (url.indexOf('.video') !== -1 || url.indexOf('video:') === 0) return true; url = url.replace(/.gif(\?width=\d*&|\?)format=mp4/, '.mp4?'); if (url.lastIndexOf('?') > 0) url = url.substring(0, url.lastIndexOf('?')); const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase(); return videoExtensions.has(ext) || url.indexOf('googlevideo.com/videoplayback') > 0 || url.indexOf('v.redd.it') > 0; } function isAudioLink(url) { if (url.indexOf('.audio') !== -1 || url.indexOf('audio:') === 0) return true; if (url.lastIndexOf('?') > 0) url = url.substring(0, url.lastIndexOf('?')); const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase(); return audioExtensions.has(ext); } MatchedRuleC.prototype={ init:function(){ if (prefs.customRules) { if (prefs.customRules == `[ /* { name: "Example, can be deleted safely", url: /^https?:\\/\\/www\\.google\\.com\\/search\\?/, getImage: function(a) {}, src: /avatar/i, r: /\\?.*$/i, s: '' } */]`) { prefs.customRules = "[]"; } try { var customRules; if (prefs.customRules.indexOf("name:") !== -1) { if (!isunsafe()) { customRules = unsafeWindow.eval(createScript(prefs.customRules)); } } else { customRules = JSON.parse(prefs.customRules); } if (Array.isArray(customRules)) { customRules.forEach(rule => { rule.custom = true; let hasRule = false; for (let s = 0; s < siteInfo.length; s++) { if (siteInfo[s].name == rule.name) { hasRule = true; for (let si in rule) { siteInfo[s][si] = rule[si]; } break; } } if (!hasRule) siteInfo.unshift(rule); }) } } catch(e) { console.log("Wrong rule for Picviewer CE+"); console.log(e); } } if (unsafeWindow.pvcepRules && Array.isArray(unsafeWindow.pvcepRules)) { unsafeWindow.pvcepRules.forEach(rule => { rule.custom = true; let hasRule = false; for (let s = 0; s < siteInfo.length; s++) { if (siteInfo[s].name == rule.name) { hasRule = true; for (let si in rule) { siteInfo[s][si] = rule[si]; } break; } } if (!hasRule) siteInfo.unshift(rule); }) } var self=this,r=0; self.rules=[]; function searchByTime(){ setTimeout(()=>{ let end=r+20; end=end>siteInfo.length?siteInfo.length:end; for(;r { let newSrc = self.replaceByRule(src, site, true); if (Array.isArray(newSrc)) newSrc = newSrc[0]; return newSrc && newSrc.length ? newSrc : src; }; let reMatch = typeof site.xhr.url === "string" && site.xhr.url.match(/^\/(.*)\/(\w*)$/); if (reMatch) { site.xhr.url = toRE(reMatch[1], reMatch[2]); } } if (site.url) { if (site.css) { var style = _GM_addStyle(site.css); style.id = 'gm-picviewer-site-style'; } if (site.lazyAttr) { self.lazyAttr = site.lazyAttr; } if (site.description) { self.description = site.description; } if (site.clickToOpen) { self.clickToOpen = site.clickToOpen; } if (site.ext) { self.ext = site.ext; } if (site.video) { let reMatch = typeof site.video === "string" && site.video.match(/^\/(.*)\/(\w*)$/); if (reMatch) { site.video = toRE(reMatch[1], reMatch[2]); } self.video = site.video; } if (site.audio) { let reMatch = typeof site.audio === "string" && site.audio.match(/^\/(.*)\/(\w*)$/); if (reMatch) { site.audio = toRE(reMatch[1], reMatch[2]); } self.audio = site.audio; } if (site.getExtSrc) { self.getExtSrc = site.getExtSrc; } if (site.xhr) { let siteXhr = site.xhr; if (siteXhr.url && !self.getExtSrc) { self.getExtSrc = function (ele) { ele = ele || this; let newSrc; let a; if (ele && ele.href) { a = ele; } else { a = ele.parentNode; if (!a || !a.href) { a = null; } } if (siteXhr.url.test) { if (a && siteXhr.url.test(a.href)) { newSrc = a.href; } } else if (typeof siteXhr.url === 'string') { try { if (a && ele.matches(siteXhr.url)) { newSrc = a.href; } } catch(e) { debug(e); } } else { newSrc = siteXhr.url.call(ele, a, [], siteXhr); } if (newSrc) { self.xhr = siteXhr; return newSrc; } else { self.xhr = null; } return newSrc; } } } } self.rules.push(site); } } if(end { if (a.custom && !b.custom) return -1; if (!a.custom && b.custom) return 1; if (a.url && !b.url) return -1; if (!a.url && b.url) return 1; return 0; }); } },1); } searchByTime(); }, replace:function(str, r, s){ var results=[],rt; let reMatch = typeof r === "string" && r.match(/^\/(.*)\/(\w+)$/); if (reMatch) { r = toRE(reMatch[1], reMatch[2]); } if(Array.isArray(s)){ s.forEach(_s=>{ rt=str.replace(r, _s); if(rt && rt!=str)results.push(rt); }); }else{ rt=str.replace(r, s); if(rt && rt!=str)return rt; } return results; }, replaceByRule: function(src, rule, check) { if (check) { if (!rule.r || /^data:/i.test(src)) return src; } let newSrc; if (Array.isArray(rule.r)) {//r最多一层 for (var j = 0; j < rule.r.length; j++) { var _r = rule.r[j]; if (_r) { if (Array.isArray(rule.s)) {//s对上r最多两层 var _s = rule.s[j]; newSrc = this.replace(src, _r, _s); } else { newSrc = this.replace(src, _r, rule.s); } if (newSrc && newSrc.length && newSrc !== src) { break; } } } } else { newSrc = this.replace(src, rule.r, rule.s); } return newSrc; }, getMode: function(src) { if (!src || !src.length) return ""; if (this.video && this.video.test(src)) { return "video"; } if (this.audio && this.audio.test(src)) { return "audio"; } if (isVideoLink(src)) { return "video"; } if (isAudioLink(src)) { return "audio"; } return ""; }, getImage: function(img, a, p, target) { var newSrc, rule; var base64Img = /^data:/i.test(img.src); for (var i = 0; i < this.rules.length; i++) { rule = this.rules[i]; if (rule.xhr) { if (rule.xhr.url) { if (rule.xhr.url.test) { if (a && rule.xhr.url.test(a.href)) { newSrc = a.href; } } else if (typeof rule.xhr.url === 'string') { try { if (a && a.matches(rule.xhr.url)) { newSrc = a.href; } } catch(e) { debug(e); } } else { newSrc = rule.xhr.url.call(target || img, a, p, rule.xhr); } if (newSrc) { this.xhr = rule.xhr; return newSrc; } else { this.xhr = null; } } else if (a) { newSrc = a.href; } } if (base64Img && (!rule.url || !rule.getImage)) continue; if (rule.src && !toRE(rule.src).test(img.src)) continue; if (rule.exclude && toRE(rule.exclude).test(img.src)) continue; if (newSrc) { this.xhr = rule.xhr; return newSrc; } if (rule.getImage) { newSrc = rule.getImage.call(target || img, a, p, rule); } else newSrc = null; if (!base64Img && rule.r) { if (!newSrc) newSrc = img.src; newSrc = this.replaceByRule(newSrc, rule); } if (newSrc && newSrc.length > 0 && newSrc != (img.currentSrc || img.src)) { debug(rule); break; } else newSrc = null; } if (newSrc && newSrc.length == 0) newSrc = null; return newSrc; } }; var isFrame=window!=window.parent; var topWindowValid; var frameSentData; var frameSentSuccessData; function handleMessage(e){ var data=e.data; if( !data || !data.messageID || data.messageID != messageID )return; var source=e.source,command,cusEvent; if(typeof source=='undefined' || source!==window){ if(!isFrame){ command=data.command; switch(command){ case 'open':{ if (data.buttonType === 'download') { downloadImg(data.src, document.title, prefs.saveName); return; } var img=document.createElement('img'); img.src=data.src; imgReady(img,{ ready:function(){ LoadingAnimC.prototype.open.call({ img:img, data:data.data, buttonType:data.buttonType, from:data.from, }); }, }); }break; case 'navigateToImg':{ cusEvent=document.createEvent('CustomEvent'); cusEvent.initCustomEvent('pv-navigateToImg',false,false,data.exist); document.dispatchEvent(cusEvent); }break; case 'topWindowValid':{ if(data.from) window.postMessage({ messageID:messageID, command:'topWindowValid_frame', valid:getBody(document).nodeName.toUpperCase()!='FRAMESET', to:data.from, },'*'); }break; }; }else{ command=data.command; switch(command){ case 'navigateToImg':{ if(!frameSentData.unique){ var unique=GalleryC.prototype.unique(frameSentData); frameSentData=unique.data; frameSentData.unique=true; }; var targetImg=frameSentData[data.index].img; var exist=(document.documentElement.contains(targetImg) && unsafeWindow.getComputedStyle(targetImg).display!='none'); if(exist){ if(gallery && gallery.shown){ gallery.minimize(); }; setTimeout(function(){ GalleryC.prototype.navigateToImg(targetImg); flashEle(targetImg); },0); }; window.postMessage({ messageID:messageID, command:'navigateToImg', exist:exist, to:data.from, },'*'); }break; case 'sendFail':{ frameSentData=frameSentSuccessData; }break; case 'topWindowValid_frame':{ cusEvent=document.createEvent('CustomEvent'); cusEvent.initCustomEvent('pv-topWindowValid',false,false,data.valid); document.dispatchEvent(cusEvent); }break; }; }; }; } //页面脚本用来转发消息 //原因chrome的contentscript无法访问非自己外的别的窗口。都会返回undefined,自然也无法向其他的窗口发送信息,这里用pagescript做个中间代理 //通讯逻辑..A页面的contentscript发送到A页面的pagescript,pagescript转交给B页面的contentscript var messageID='pv-0.5106795670312598'; var _isunsafe = null; function isunsafe(){ if (_isunsafe === null) { try { _isunsafe = unsafeWindow.eval(createScript("false")); } catch (e) { console.debug("unsafe"); _isunsafe = true; } } return _isunsafe; } function addPageScript() { if(isunsafe())return; var pageScript=document.createElement('script'); pageScript.id = 'picviewer-page-script'; var pageScriptText=function(messageID){ var frameID=Math.random(); var frames={ top:window.top, }; window.addEventListener('message',function(e){ var data=e.data; if( !data || !data.messageID || data.messageID != messageID )return;//通信ID认证 var source=e.source; if(source===window){//来自contentscript,发送出去,或者干嘛。 if(data.to){ data.from=frameID; frames[data.to].postMessage(data,'*'); }else{ switch(data.command){ case 'getIframeObject':{ var frameWindow=frames[data.windowId]; var iframes=document.getElementsByTagName('iframe'); var iframe; var targetIframe; for(var i=iframes.length-1 ; i>=0 ; i--){ iframe=iframes[i]; if(iframe.contentWindow===frameWindow){ targetIframe=iframe; break; }; }; var cusEvent=document.createEvent('CustomEvent'); cusEvent.initCustomEvent('pv-getIframeObject',false,false,targetIframe); document.dispatchEvent(cusEvent); }break; }; }; }else{//来自别的窗口的,contentscript可以直接接收,这里保存下来自的窗口的引用 frames[data.from]=source; }; },true) }; pageScript.textContent=createScript('(' + pageScriptText.toString() + ')('+ JSON.stringify(messageID) +')'); if(document.head)document.head.appendChild(pageScript); } function clickToOpen(data){ var preventDefault = matchedRule.clickToOpen.preventDefault; var button = matchedRule.clickToOpen.button || 0; var alt = !!matchedRule.clickToOpen.alt; var ctrl = !!matchedRule.clickToOpen.ctrl; var shift = !!matchedRule.clickToOpen.shift; var meta = !!matchedRule.clickToOpen.meta; function mouseout(){ document.removeEventListener('mouseout', mouseout, true); document.removeEventListener(button == 2 ? 'contextmenu' : 'mousedown', click, true); if(data.imgPA && preventDefault){ data.imgPA.removeEventListener('click', clickA, true); }; }; function checkLimit(e){ if(e.button!=button || e.altKey!=alt || e.ctrlKey!=ctrl || e.shiftKey!=shift || e.metaKey!=meta){ return false; } return true; } function click(e){ if(!checkLimit(e))return; FloatBarC.prototype.open.call({ data:data, },e,matchedRule.clickToOpen.type); if(preventDefault){ e.preventDefault(); e.stopPropagation(); return false; } }; function clickA(e){//阻止a的默认行为 if(!checkLimit(e))return; e.preventDefault(); }; document.addEventListener(button == 2 ? 'contextmenu' : 'mousedown', click, true); if(data.imgPA && preventDefault){ data.imgPA.addEventListener('click', clickA, true); }; setTimeout(function(){//稍微延时。错开由于css hover样式发生的out; document.addEventListener('mouseout', mouseout, true); },100); return function(){ mouseout(); }; } var canclePreCTO,uniqueImgWin,centerInterval,globalFuncEnabled=false; function checkGlobalKeydown(e){ return(!((!e.ctrlKey && e.key !== 'Control' && prefs.floatBar.globalkeys.ctrl)|| (!e.altKey && e.key !== 'Alt' && prefs.floatBar.globalkeys.alt)|| (!e.shiftKey && e.key !== 'Shift' && prefs.floatBar.globalkeys.shift)|| (!e.metaKey && e.key !== 'Meta' && prefs.floatBar.globalkeys.command)|| (!prefs.floatBar.globalkeys.ctrl && !prefs.floatBar.globalkeys.alt && !prefs.floatBar.globalkeys.shift && !prefs.floatBar.globalkeys.command))); } function checkPreview(e){ let selStr; try { selStr = !selectionClientRect && document.getSelection().toString(); }catch(e){} if (selStr) return false; let keyActive=(prefs.floatBar.globalkeys.type == "hold" && checkGlobalKeydown(e)) || (prefs.floatBar.globalkeys.type == "press" && globalFuncEnabled); return prefs.floatBar.globalkeys.invertInitShow?!keyActive:keyActive; } var untilMoveTimer, moveHandler, uniqueImgWinInitX, uniqueImgWinInitY; function waitUntilMove(target, callback) { if (moveHandler) document.removeEventListener('mousemove', moveHandler, true); if (untilMoveTimer) clearTimeout(untilMoveTimer); moveHandler = e => { uniqueImgWinInitX = e.clientX; uniqueImgWinInitY = e.clientY; if (target != e.target) { let preRect = target.getBoundingClientRect(); let nextRect = e.target.getBoundingClientRect(); if (preRect && nextRect && (preRect.left > nextRect.left || preRect.right < nextRect.right || preRect.top > nextRect.top || preRect.bottom < nextRect.bottom)) { document.removeEventListener('mousemove', moveHandler, true); clearTimeout(untilMoveTimer); } } } document.addEventListener('mousemove', moveHandler, true); untilMoveTimer = setTimeout(() => { document.removeEventListener('mousemove', moveHandler, true); callback(); }, prefs.floatBar.showDelay || 0) } function checkFloatBar(_target, type, canPreview, clientX, clientY, altKey) { let target = _target; if (!target || target.id == "pv-float-bar-container" || (target.parentNode && (target.parentNode.id == "icons" || target.parentNode.className == "search-jumper-btn")) || (target.className && (/^pv\-/.test(target.className) || target.className == "whx-a" || target.className == "whx-a-node" || target.className == "search-jumper-btn" || target.classList.contains("pv-icon") || target.classList.contains("ks-imagezoom-lens")))) { return; } if (target.nodeName.toUpperCase() == "PICTURE"){ target = target.querySelector("img"); } if (type == "mousemove") { if ((uniqueImgWin && !uniqueImgWin.removed && !uniqueImgWin.previewed)) { uniqueImgWin.followPos(clientX, clientY); if (!canPreview) { uniqueImgWin.remove(); } return; } else if (target.nodeName.toUpperCase() != 'IMG' || !canPreview) { return; } } // 扩展模式,检查前面一个是否为 img if (target.nodeName.toUpperCase() != 'IMG' && matchedRule.rules.length > 0 && matchedRule.ext) { var _type = typeof matchedRule.ext; if (_type == 'string') { switch (matchedRule.ext) { case 'previous': target = target.previousElementSibling || target; break; case 'next': target = target.nextElementSibling || target; break; case 'previous-2': target = (target.previousElementSibling && target.previousElementSibling.previousElementSibling) || target; break; } } else if (_type == 'function') { try { target = matchedRule.ext(target) || target; } catch(ex) { throwErrorInfo(ex); } if (!target) return; } } let bgReg = /.*url\(\s*["']?([^ad\s'"].+?)["']?\s*\)([^'"]|$)/i; let bgRegLong = /^\s*url\(\s*["']?([^ad\s'"].+?)["']?\s*\)([^'"]|$)/i; let result, targetBg, hasBg = node => { if(node.nodeName.toUpperCase() == "HTML" || node.nodeName == "#document"){ return false; } if (node.clientWidth <= prefs.floatBar.minSizeLimit.w || node.clientHeight <= prefs.floatBar.minSizeLimit.h) { return false; } targetBg = ""; let nodeStyle = unsafeWindow.getComputedStyle(node); let bg = nodeStyle.backgroundRepeatX != "repeat" && nodeStyle.backgroundRepeatY != "repeat" && nodeStyle.backgroundImage; if (bg && bg !== "none") { targetBg = nodeStyle.backgroundImage.match(bg.length > 500 ? bgRegLong : bgReg); } if (!targetBg) { nodeStyle = unsafeWindow.getComputedStyle(node, "::before"); bg = nodeStyle.backgroundRepeatX != "repeat" && nodeStyle.backgroundRepeatY != "repeat" && nodeStyle.backgroundImage; if (bg && bg !== "none") { targetBg = nodeStyle.backgroundImage.match(bg.length > 500 ? bgRegLong : bgReg); } } if (!targetBg) { nodeStyle = unsafeWindow.getComputedStyle(node, "::after"); bg = nodeStyle.backgroundRepeatX != "repeat" && nodeStyle.backgroundRepeatY != "repeat" && nodeStyle.backgroundImage; if (bg && bg !== "none") { targetBg = nodeStyle.backgroundImage.match(bg.length > 500 ? bgRegLong : bgReg); } } if (targetBg) { targetBg = targetBg[1].replace(/\\"/g, '"'); } return targetBg; }; if (target.nodeName.toUpperCase() != 'IMG' && matchedRule.getExtSrc) { let nsrc; try { nsrc = matchedRule.getExtSrc.call(target); } catch(ex) { throwErrorInfo(ex); } if (nsrc) { let src = nsrc, imgSrc = nsrc; if (Array.isArray(nsrc) && nsrc.length == 2) { imgSrc = nsrc[0]; src = nsrc[1]; } result = { src: src, type: "rule", imgSrc: imgSrc, noActual: src === imgSrc, img: target, xhr: matchedRule.xhr }; } } if (!result) { if (target.nodeName.toUpperCase() != 'IMG' && target.dataset.role == "img") { let img = target.parentNode.querySelector('img'); if (img) target = img; } if (target.nodeName.toUpperCase() == 'IMAGE') { let src = target.href && target.href.baseVal; if (src) { result = { src: src, type: "rule", imgSrc: src, noActual: true, img: target.parentNode }; } } else if (target.nodeName.toUpperCase() != 'IMG') { if (target.nodeName.toUpperCase() == "AREA") target = target.parentNode; var broEle, broImg; if (target.nodeName.toUpperCase() != 'A' && target.parentNode && target.parentNode.style && !/flex|grid|table/.test(getComputedStyle(target.parentNode).display)) { broEle = target.previousElementSibling; while (broEle) { if (broEle.nodeName == "IMG") broImg = broEle; else if (broEle.nodeName == "PICTURE") broImg = broEle.querySelector("img"); if (getComputedStyle(broEle).position !== "absolute") break; broEle = broEle.previousElementSibling; } if (broEle == target) broEle = null; else if (!broEle) { broEle = target.nextElementSibling; while (broEle) { if (broEle.nodeName == "IMG") broImg = broEle; else if (broEle.nodeName == "PICTURE") broImg = broEle.querySelector("img"); if (getComputedStyle(broEle).position == "absolute") break; broEle = broEle.nextElementSibling; } if (broEle == target) broEle = null; } } if (prefs.floatBar.listenBg && hasBg(target)) { let src = targetBg, nsrc = src, noActual = true, type = "scale"; result = { src: nsrc, type: type, imgSrc: src, noActual:noActual, img: target }; } else if (broImg) { target = broImg; } else if (target.nodeName.toUpperCase() == 'CANVAS') { let src = target.src || target.dataset.src; if (src) { let nsrc = src, noActual = true, type = "scale"; result = { src: nsrc, type: type, imgSrc: src, noActual:noActual, img: target }; } } else if (target.children.length == 1 && target.children[0].nodeName == "IMG") { target = target.children[0]; } else if (prefs.floatBar.listenBg && broEle && hasBg(broEle)) { let src = targetBg, nsrc = src, noActual = true, type = "scale"; result = { src: nsrc, type: type, imgSrc: src, noActual:noActual, img: target }; } else if (target.parentNode) { let imgs; if (target.nodeName == 'A') { imgs = target.querySelectorAll('img'); } if (imgs && imgs.length == 1) { target = imgs[0]; } else if (target.parentNode.nodeName.toUpperCase() == 'IMG') { target = target.parentNode; } else if (prefs.floatBar.listenBg && hasBg(target.parentNode)) { target = target.parentNode; let src = targetBg, nsrc = src, noActual = true, type = "scale"; result = { src: nsrc, type: type, imgSrc: src, noActual:noActual, img: target }; } } if (!result) { let checkEle = target; while(checkEle && checkEle.children.length === 1) { checkEle = checkEle.children[0]; if (checkEle.nodeName === "IMG") { target = checkEle; break; } else if (prefs.floatBar.listenBg && hasBg(checkEle)) { let src = targetBg, nsrc = src, noActual = true, type = "scale"; result = { src: nsrc, type: type, imgSrc: src, noActual:noActual, img: checkEle }; break; } } } if (!result && document.elementsFromPoint) { let elements = document.elementsFromPoint(clientX, clientY); let checkLen = Math.min(elements.length, 5); for (let i = 0; i < checkLen; i++) { let ele = elements[i]; if (!ele) continue; if (/img/i.test(ele.nodeName)) { target = ele; result = null; break; } else if (prefs.floatBar.listenBg && hasBg(ele)) { target = ele; let src = targetBg, nsrc = src, noActual = true, type = "scale"; result = { src: nsrc, type: type, imgSrc: src, noActual:noActual, img: target }; break; } } } if (!result && target.shadowRoot) { let imgs = target.shadowRoot.querySelectorAll('img'); if (imgs.length === 1) target = imgs[0]; } if (result && !/^data:/i.test(result.src)) { if (matchedRule.rules.length > 0 && target.nodeName.toUpperCase() != 'IMG') { let src = result.src, img = {src: src}, type, imgSrc = src; try { var imgPN=target; var imgPA,imgPE=[]; while(imgPN=imgPN.parentElement){ if(imgPN.nodeName.toUpperCase()=='A'){ imgPA=imgPN; break; } } imgPN=target; while(imgPN=imgPN.parentElement){ if(imgPN.nodeName.toUpperCase()=='BODY'){ break; }else{ imgPE.push(imgPN); } } var newSrc = matchedRule.getImage(img, imgPA, imgPE, target); if (newSrc && imgSrc != newSrc) { let srcs, description; src = newSrc; if (Array.isArray(src)) { srcs = src; src = srcs.shift(); } type = 'rule'; if (matchedRule.description) { let desc = matchedRule.description, attr; if (Array.isArray(desc) && desc.length === 2) { attr = desc[1]; desc = desc[0]; } var node = getElementMix(desc, img); if (node) { description = attr ? node.getAttribute(attr) : (node.getAttribute('title') || node.textContent); } } result.src = src; result.type = type; result.noActual = false; result.xhr = matchedRule.xhr; result.description = description || ''; } } catch(err) {} if (result.type != "rule") { tprules.find(function(rule, index, array) { try { src = rule.call(img); if (src) { return true; }; } catch(err) { } }); if (src && src != imgSrc) { result.src = src; result.type = "tpRule"; result.noActual = false; } } } } } } var checkUniqueImgWin = function() { if (canPreview) { if (result.type != "link" && result.type != "rule" && result.src == result.imgSrc) { if (result.imgAS.w <= result.imgCS.w && result.imgAS.h <= result.imgCS.h) { if (result.img && result.img.childElementCount) return false; var wSize = getWindowSize(); if (result.imgAS.w <= wSize.w && result.imgAS.h <= wSize.h) return false; } } uniqueImgWinInitX = clientX; uniqueImgWinInitY = clientY; if (uniqueImgWin && !uniqueImgWin.removed) { if (uniqueImgWin.src == result.src) return true; uniqueImgWin.remove(); } waitUntilMove(_target, () => { new LoadingAnimC(result, 'popup', prefs.waitImgLoad, prefs.framesPicOpenInTopWindow); }); return true; } else { return false; } }; if (!result && target.nodeName.toUpperCase() != 'IMG') { if (selectionClientRect && clientX > selectionClientRect.left && clientX < selectionClientRect.left + selectionClientRect.width && clientY > selectionClientRect.top && clientY < selectionClientRect.top + selectionClientRect.height) { result = { src: selectionStr, type: "link", imgSrc: selectionStr, noActual:true, img: target }; checkUniqueImgWin(); return; } if (target.nodeName.toUpperCase() == 'A' && imageReg.test(target.href)) { } else if (target.parentNode && target.parentNode.nodeName.toUpperCase() == 'A' && imageReg.test(target.parentNode.href)) { target = target.parentNode; } else { target = null; } if (target) { result = { src: target.href, type: "link", imgSrc: target.href, noActual:true, img: target, description: target.title }; checkUniqueImgWin(); } return; } let sizeHide = false; if (!result) { pretreatment(target) result = findPic(target); if (!result) return; } if (result) { if (!result.imgAS && !result.imgCS) { let sizeInfo = { w: result.img.offsetWidth || result.img.scrollWidth || target.offsetWidth || target.scrollWidth, h: result.img.offsetHeight || result.img.scrollHeight || target.offsetHeight || target.scrollHeight } result.imgAS = sizeInfo; result.imgCS = sizeInfo; } if (prefs.floatBar.showWithRules && result.type == "rule") { } else if (!(result.imgAS.w == result.imgCS.w && result.imgAS.h == result.imgCS.h)) {//如果不是两者完全相等,那么被缩放了. if (prefs.floatBar.sizeLimitOr) { if (result.imgCS.h <= prefs.floatBar.minSizeLimit.h && result.imgCS.w <= prefs.floatBar.minSizeLimit.w) {//最小限定判断. sizeHide = true; } }else{ if (result.imgCS.h <= prefs.floatBar.minSizeLimit.h || result.imgCS.w <= prefs.floatBar.minSizeLimit.w) {//最小限定判断. sizeHide = true; } } } else { if (prefs.floatBar.sizeLimitOr) { if (result.imgCS.w <= prefs.floatBar.forceShow.size.w && result.imgCS.h <= prefs.floatBar.forceShow.size.h) { sizeHide = true; } } else { if (result.imgCS.w <= prefs.floatBar.forceShow.size.w || result.imgCS.h <= prefs.floatBar.forceShow.size.h) { sizeHide = true; } } } debug(result); if (!result.noActual) { if (!result.srcs) { result.srcs = [result.imgSrc]; } else { if (result.imgSrc && result.srcs.join(" ").indexOf(result.imgSrc) == -1) { result.srcs.push(result.imgSrc); } } } if (!floatBar) { floatBar = new FloatBarC(); } if (result.type == 'rule' && matchedRule.clickToOpen && matchedRule.clickToOpen.enabled) { if (canclePreCTO) {//取消上次的,防止一次点击打开多张图片 canclePreCTO(); } canclePreCTO = clickToOpen(result); } let hide = sizeHide || (prefs.floatBar.position == "hide" ? !altKey : altKey); result.hide = hide; let canShow = floatBar.start(result); if (!checkUniqueImgWin() && canShow) { if (floatBar.floatBar.style.opacity == 0) { floatBar.floatBar.style.opacity = ""; } floatBar.floatBar.style.display = "initial"; } } } var checkFloatBarTimer; function globalMouseoverHandler(e) { if (galleryMode) return;//库模式全屏中...... if (e.target == ImgWindowC.overlayer) return; let canPreview = checkPreview(e); if (e.type == "mousemove") { if ((uniqueImgWin && !uniqueImgWin.removed && !uniqueImgWin.previewed)) { if (canPreview) { uniqueImgWin.followPos(e.clientX, e.clientY); } else { uniqueImgWin.remove(); } return; } else { if (!canPreview) return; let target = e.target; if (target.nodeName.toUpperCase() == "PICTURE"){ target = target.querySelector("img") || target; } if (target.nodeName.toUpperCase() != 'IMG') return; } } clearTimeout(checkFloatBarTimer); checkFloatBarTimer = setTimeout(function() { if (!e || !e.target || !e.target.parentNode) return; if (gallery && gallery.shown) return; checkFloatBar(e.target, e.type, canPreview, e.clientX, e.clientY, e.altKey); }, 50); } var selectionClientRect, selectionStr, selectionChanging = false; document.addEventListener('selectionchange', (e) => { if (selectionChanging) return; selectionChanging = true; setTimeout(() => { selectionChanging = false; const selection = window.getSelection(); selectionStr = selection.toString(); if (selectionStr && selectionStr.length < 500 && imageReg.test(selectionStr)) { const range = selection.getRangeAt(0); selectionClientRect = range.getBoundingClientRect(); } else { selectionClientRect = null; } }, 300); }); async function input(sel, v) { await new Promise((resolve) => { let checkInv = setInterval(() => { let input = document.querySelector(sel); if (input) { input.focus(); input.scrollIntoView(); let lastValue = input.value; if (input.nodeName == "INPUT") { var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; nativeInputValueSetter.call(input, v); } else { var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set; nativeTextareaValueSetter.call(input, v); } let event = new Event('focus', { bubbles: true }); input.dispatchEvent(event); event = new Event('input', { bubbles: true }); let tracker = input._valueTracker; if (tracker) { tracker.setValue(lastValue); } input.dispatchEvent(event); event = new Event('change', { bubbles: true }); input.dispatchEvent(event); clearInterval(checkInv); resolve(); } }, 100); }); } function emuClick(btn){ if(!PointerEvent)return btn.click(); let eventParam={ isTrusted: true, altKey: false, azimuthAngle: 0, bubbles: true, button: 0, buttons: 0, clientX: 1, clientY: 1, cancelBubble: false, cancelable: true, composed: true, ctrlKey: false, defaultPrevented: false, detail: 1, eventPhase: 2, fromElement: null, height: 1, isPrimary: false, metaKey: false, pointerId: 1, pointerType: "mouse", pressure: 0, relatedTarget: null, returnValue: true, shiftKey: false, toElement: null, twist: 0, which: 1 }; btn.focus(); var mouseclick = new PointerEvent("mouseover",eventParam); btn.dispatchEvent(mouseclick); mouseclick = new PointerEvent("pointerover",eventParam); btn.dispatchEvent(mouseclick); mouseclick = new PointerEvent("mousedown",eventParam); btn.dispatchEvent(mouseclick); mouseclick = new PointerEvent("pointerdown",eventParam); btn.dispatchEvent(mouseclick); mouseclick = new PointerEvent("mouseup",eventParam); btn.dispatchEvent(mouseclick); mouseclick = new PointerEvent("pointerup",eventParam); btn.dispatchEvent(mouseclick); btn.click(); } async function clickEle(sel, failAction) { await new Promise((resolve) => { let checkInv = setInterval(() => { let ele = document.querySelector(sel); if (ele) { clearInterval(checkInv); emuClick(ele); resolve(); }else if(failAction) { failAction(); } }, 100); }); } async function sleep(time) { await new Promise((resolve) => { setTimeout(() => { resolve(); }, time); }) } function isKeyDownEffectiveTarget(target) { var localName = (target.shadowRoot ? (target.shadowRoot.activeElement || target) : target).localName; // 确保光标不是定位在文字输入框或选择框 if (localName == 'textarea' || localName == 'input' || localName == 'select'){ return false; } // 视频播放器 if (localName == 'object' || localName == 'embed'){ return false; } // 百度贴吧回复输入的问题 if (target.getAttribute('contenteditable') == 'true'){ return false; } return true; } async function openGallery(){ if(!gallery){ gallery=new GalleryC(); gallery.data=[]; } var allData=await gallery.getAllValidImgs(); if(allData.length<1)return; gallery.data=allData; gallery.load(gallery.data); return gallery; } function getActiveElement(root) { const activeEl = root.activeElement; if (!activeEl) { return null; } if (activeEl.shadowRoot) { return getActiveElement(activeEl.shadowRoot); } else { return activeEl; } } function inputActive(doc) { let activeEl = getActiveElement(doc); if (activeEl && ((/INPUT|TEXTAREA/i.test(activeEl.nodeName) && activeEl.getAttribute("aria-readonly") != "true" ) || activeEl.contentEditable == 'true' ) ) { return true; } else { while (activeEl && activeEl.nodeName) { if (activeEl.contentEditable == 'true') return true; if (activeEl.nodeName.toUpperCase() == 'BODY') { break; } activeEl = activeEl.parentNode; } } return false; } function keydown(event) { if (ImgWindowC.showing) return; if (gallery && gallery.shown) return; if (inputActive(document)) { return; } var key = event.key; if(checkGlobalKeydown(event)){ if(prefs.floatBar.keys.enable && key==prefs.floatBar.keys.gallery){ openGallery(); event.stopPropagation(); event.preventDefault(); globalFuncEnabled = !globalFuncEnabled; return true; }else if((!gallery || (!gallery.shown && !gallery.minimized)) && prefs.floatBar.globalkeys.type == "press"){ globalFuncEnabled = !globalFuncEnabled; return true; } } if (!prefs.floatBar.keys.enable){ return false; } if (event && (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) && window.getSelection().toString()) { return false; } if (key == 'c' && event && (event.ctrlKey || event.metaKey)) return false; if (floatBar && isKeyDownEffectiveTarget(event.target)) { Object.keys(prefs.floatBar.keys).some(function(action) { if (action == 'enable' || action == 'search') return; if (key == prefs.floatBar.keys[action]) { floatBar.open(event, action); event.preventDefault(); return true; } }); } } function keyup(event) { let isFuncKey = event.key == 'Alt' || event.key == 'Control' || event.key == 'Shift' || event.key == 'Meta'; if(isFuncKey && (prefs.floatBar.globalkeys.type == "hold" || !checkPreview(event)) && (uniqueImgWin && !uniqueImgWin.removed)){ clearTimeout(checkFloatBarTimer); if(prefs.floatBar.globalkeys.closeAfterPreview){ if (uniqueImgWin) { uniqueImgWin.remove(); } }else{ uniqueImgWin.focus(); uniqueImgWin.imgWindow.classList.remove("pv-pic-window-transition-all"); uniqueImgWin.imgWindow.classList.remove("preview"); uniqueImgWin.previewed=true; uniqueImgWin = null; } } } function createEleFromJson(json) { let collection = document.createDocumentFragment(); json.forEach(data => { let ele = document.createElement(data.node); if (data.text) { ele.innerText = data.text; } if (data.attr) { Object.keys(data.attr).forEach(key => { ele.setAttribute(key, data.attr[key]); }); } if (data.children) { let children = createEleFromJson(data.children); ele.appendChild(children); } collection.appendChild(ele); }); return collection; } window.addEventListener('message', handleMessage, true); addPageScript(); document.addEventListener('keyup', keyup, false); document.addEventListener('mouseenter', globalMouseoverHandler, true); document.addEventListener('mousemove', globalMouseoverHandler, true); document.addEventListener('mouseout',e=>{ if (e.relatedTarget == ImgWindowC.overlayer) return; if(uniqueImgWin && !uniqueImgWin.removed){ if(checkPreview(e)){ let showArea=uniqueImgWin.data.img.getBoundingClientRect(); if(e.clientX < showArea.left + 20 || e.clientX > showArea.right - 20 || e.clientY < showArea.top + 20 || e.clientY > showArea.bottom - 20){ uniqueImgWin && uniqueImgWin.remove(); } } } }, true); var editSitesFunc={ "Lunapic": (src, initOpen) => { _GM_openInTab('https://www.lunapic.com/editor/index.php?action=url&url=' + src, {active:true}); }, "Pixlr easy": async (src, initOpen) => { if(initOpen){ storage.setItem("editUrl", src); _GM_openInTab('https://pixlr.com/x/', {active:true}); }else{ storage.setItem("editUrl", ""); if(/^https:\/\/pixlr\.com\//.test(location.href)){ await sleep(1000); await clickEle('#splash-file-menu'); await clickEle('#splash-file-url'); await input('#image-url', src); await clickEle('.dialog>.buttons>a.button.positive'); } } }, "Pixlr advanced": async (src, initOpen) => { if(initOpen){ storage.setItem("editUrl", src); _GM_openInTab('https://pixlr.com/e/', {active:true}); }else{ storage.setItem("editUrl", ""); if(/^https:\/\/pixlr\.com\//.test(location.href)){ await sleep(1000); await clickEle('#splash-file-menu'); await clickEle('#splash-file-url'); await input('#image-url', src); await clickEle('.dialog>.buttons>a.button.positive'); } } }, "Photopea": async (src, initOpen) => { if(initOpen){ storage.setItem("editUrl", src); _GM_openInTab('https://www.photopea.com/', {active:true}); }else{ storage.setItem("editUrl", ""); if(/^https:\/\/www\.photopea\.com\//.test(location.href)){ await sleep(1000); await clickEle('.topbar>span>button'); await clickEle('.cmanager>.contextpanel>div:nth-child(4)'); await clickEle('.cmanager>div:last-child>div:nth-child(3)'); await input('span.fitem.tinput>input', src); await clickEle('.form>button'); } } } }; var editSitesName={}; for(let key in editSitesFunc){ editSitesName[key]=key; } var newsInited = false, newsNode = null; initLang(); var customLangOption={ 'auto': i18n("defaultLang") }; for(let key in langList){ customLangOption[key]=langList[key]; } GM_config.init({ id: 'pv-prefs', title: GM_config.create('a', { href: 'https://greasyfork.org/scripts/24204-picviewer-ce', target: '_blank', textContent: 'Picviewer CE+ '+i18n("config"), title: i18n("openHomePage") }), isTabs: true, skin: 'tab', frameStyle: { minWidth: "350px", width: ((visualLength((i18n("floatBar") + i18n("magnifier") + i18n("gallery") + i18n("imgWindow") + i18n("others")),"14px","arial,tahoma,myriad pro,sans-serif") + 250) || 480) + 'px', zIndex:'2147483648', margin: '1px', border: '2px solid rgb(0, 0, 0)' }, css: [ "#pv-prefs input[type='text'] { width: 50px; } ", "#pv-prefs input[type='number'] { width: 50px; } ", "#pv-prefs .inline .config_var { margin-left: 6px; }", "#pv-prefs label.size { width: 205px; }", "#pv-prefs span.sep-x { margin-left: 0px !important; }", "#pv-prefs label.sep-x { margin-right: 5px; }", "#pv-prefs label.floatBar-key { margin-left: 20px; width: 100px; }", "#pv-prefs input.color { width: 120px; }", "#pv-prefs input.order { width: 250px; }", "#pv-prefs .config_header>a { border-bottom: solid 2px; }", "#pv-prefs a:hover { color: #9f9f9f; }", "#pv-prefs a { color: black; }", "#pv-prefs .section_header_holder { padding-right: 10px; }", "#pv-prefs textarea { width: 100%; }", "#pv-prefs .nav-tabs { white-space: nowrap; width: fit-content; max-width: 100%; margin: 20 auto; display: flex; overflow-x: auto; overflow-y: visible; }", ].join('\n'), fields: { // 浮动工具栏 'floatBar.position': { label: i18n("position"), title: i18n("positionTips"), type: 'select', options: { 'top left': i18n("topLeft"), 'top right': i18n("topRight"), 'bottom right': i18n("bottomRight"), 'bottom left': i18n("bottomLeft"), 'top center': i18n("topCenter"), 'bottom center': i18n("bottomCenter"), 'hide': i18n("hide") }, "default": prefs.floatBar.position, section: [i18n("floatBar")], }, 'floatBar.stayOut': { label: i18n("stayOut"), type: 'checkbox', "default": prefs.floatBar.stayOut, line: 'start' }, 'floatBar.stayOutOffsetX': { label: 'X:', type: 'int', "default": prefs.floatBar.stayOutOffsetX }, 'floatBar.stayOutOffsetY': { label: 'Y:', type: 'int', "default": prefs.floatBar.stayOutOffsetY, after: ' '+i18n("px"), line: 'end' }, 'floatBar.showDelay': { label: i18n("showDelay"), type: 'int', "default": prefs.floatBar.showDelay, after: ' '+i18n("ms"), }, 'floatBar.hideDelay': { label: i18n("hideDelay"), type: 'int', className: 'hideDelay', "default": prefs.floatBar.hideDelay, after: ' '+i18n("ms") }, 'floatBar.forceShow.size.w': { label: i18n("forceShow"), type: 'int', className: 'size', "default": prefs.floatBar.forceShow.size.w, title: i18n("forceShowTip"), line: 'start', }, 'floatBar.forceShow.size.h': { label: ' x ', type: 'int', className: 'sep-x', after: ' '+i18n("px"), "default": prefs.floatBar.forceShow.size.h, line: 'end', }, 'floatBar.minSizeLimit.w': { label: i18n("minSizeLimit"), type: 'int', className: 'size', "default": prefs.floatBar.minSizeLimit.w, title: i18n("minSizeLimitTip"), line: 'start', }, 'floatBar.minSizeLimit.h': { label: ' x ', type: 'int', className: 'sep-x', after: ' '+i18n("px"), "default": prefs.floatBar.minSizeLimit.h, line: 'end', }, 'floatBar.sizeLimitOr': { label: i18n("sizeLimitOr"), type: "checkbox", "default": false }, 'floatBar.showWithRules': { label: i18n("showWithRules"), type: "checkbox", "default": prefs.floatBar.showWithRules, title: i18n("showWithRulesTip"), }, 'floatBar.butonOrder': { label: i18n("butonOrder"), type: 'text', className: 'order', title: 'actual,current,gallery,magnifier,download', "default": prefs.floatBar.butonOrder.join(', '), }, 'floatBar.additionalFeature': { label: i18n("additionalFeature"), type: 'select', options: { 'copy': i18n("copy"), 'copyImg': i18n("copyImg"), 'open': i18n("openInNewTab") }, "default": prefs.floatBar.additionalFeature || 'open' }, 'floatBar.invertAdditionalFeature': { label: i18n("invertAdditionalFeature"), type: 'checkbox', "default": prefs.floatBar.invertAdditionalFeature }, 'floatBar.listenBg': { label: i18n("listenBg"), type: 'checkbox', "default": prefs.floatBar.listenBg, title: i18n("listenBgTip") }, 'floatBar.globalkeys.ctrl': { label: i18n("globalkeys"), type: 'checkbox', after: "CTRL +", "default": true, line: 'start' }, 'floatBar.globalkeys.alt': { after: "ALT +", type: 'checkbox', className: 'sep-x', "default": false, }, 'floatBar.globalkeys.shift': { after: "SHIFT +", type: 'checkbox', className: 'sep-x', "default": false, }, 'floatBar.globalkeys.command': { after: "META", type: 'checkbox', className: 'sep-x', "default": false, line: 'end', }, 'floatBar.globalkeys.type': { label: i18n("globalkeysType"), type: 'select', options: { 'press': i18n("globalkeysPress"), 'hold': i18n("globalkeysHold") }, "default": prefs.floatBar.globalkeys.type }, 'floatBar.globalkeys.closeAfterPreview': { label: i18n("closeAfterPreview"), type: 'checkbox', "default": prefs.floatBar.globalkeys.closeAfterPreview }, 'floatBar.previewMaxSizeW': { label: i18n("previewMaxSize"), type: 'int', className: 'size', "default": prefs.previewMaxSizeW || 0, title: i18n("previewMaxSizeTip"), line: 'start', }, 'floatBar.previewMaxSizeH': { label: ' x ', type: 'int', className: 'sep-x', after: ' '+i18n("px"), "default": prefs.previewMaxSizeH || 0, line: 'end', }, 'floatBar.globalkeys.invertInitShow': { label: i18n("initShow"), type: 'checkbox', "default": prefs.floatBar.globalkeys.invertInitShow }, 'floatBar.globalkeys.previewFollowMouse': { label: i18n("previewFollowMouse"), type: 'checkbox', "default": prefs.floatBar.globalkeys.previewFollowMouse }, // 按键 'floatBar.keys.enable': { label: i18n("keysEnable"), type: 'checkbox', "default": prefs.floatBar.keys.enable }, 'floatBar.keys.actual': { label: i18n("keysActual"), type: 'text', className: 'floatBar-key', "default": prefs.floatBar.keys.actual, title: i18n("keysActualTip") }, /*'floatBar.keys.search': { label: i18n("keysSearch"), type: 'text', className: 'floatBar-key', "default": prefs.floatBar.keys.search, title: i18n("keysSearchTip") },*/ 'floatBar.keys.current': { label: i18n("keysCurrent"), type: 'text', className: 'floatBar-key', "default": prefs.floatBar.keys.current, title: i18n("keysCurrentTip") }, 'floatBar.keys.magnifier': { label: i18n("keysMagnifier"), type: 'text', className: 'floatBar-key', "default": prefs.floatBar.keys.magnifier, title: i18n("keysMagnifierTip") }, 'floatBar.keys.gallery': { label: i18n("keysGallery"), type: 'text', className: 'floatBar-key', "default": prefs.floatBar.keys.gallery, title: i18n("keysGalleryTip") }, 'floatBar.keys.download': { label: i18n("download"), type: 'text', className: 'floatBar-key', "default": prefs.floatBar.keys.download }, // 放大镜 'magnifier.radius': { label: i18n("magnifierRadius"), type: 'int', "default": prefs.magnifier.radius, section: [i18n("magnifier")], after: ' '+i18n("px") }, 'magnifier.wheelZoom.enabled': { label: i18n("magnifierWheelZoomEnabled"), type: 'checkbox', "default": prefs.magnifier.wheelZoom.enabled, }, 'magnifier.wheelZoom.scaleImage': { label: i18n("magnifierScaleImage"), type: 'checkbox', "default": prefs.magnifier.wheelZoom.scaleImage !== false, }, 'magnifier.wheelZoom.ctrl': { label: '', type: 'checkbox', after: "CTRL +", "default": false, line: 'start' }, 'magnifier.wheelZoom.alt': { after: "ALT +", type: 'checkbox', className: 'sep-x', "default": false, }, 'magnifier.wheelZoom.shift': { after: "SHIFT +", type: 'checkbox', className: 'sep-x', "default": false, }, 'magnifier.wheelZoom.meta': { after: "META", type: 'checkbox', className: 'sep-x', "default": false, line: 'end', }, 'magnifier.wheelZoom.range': { label: i18n("magnifierWheelZoomRange"), type: 'textarea', "default": prefs.magnifier.wheelZoom.range.join(', '), }, // 图库 'gallery.defaultSizeLimit.w': { label: i18n("defaultSizeLimit"), type: 'int', className: 'size', section: [i18n("gallery")], "default": prefs.gallery.defaultSizeLimit.w, line: 'start', }, 'gallery.defaultSizeLimit.h': { label: ' x ', type: 'int', className: 'sep-x', after: ' '+i18n("px"), "default": prefs.gallery.defaultSizeLimit.h, line: 'end', }, 'gallery.fitToScreen': { label: i18n("galleryFitToScreen"), type: 'checkbox', "default": prefs.gallery.fitToScreen, title: i18n("galleryFitToScreenTip"), line: 'start', }, 'gallery.fitToScreenSmall': { label: i18n("galleryFitToScreenSmall"), type: 'checkbox', "default": prefs.gallery.fitToScreenSmall, line: 'end', }, 'gallery.scrollEndToChange': { label: i18n("galleryScrollEndToChange"), type: 'checkbox', "default": prefs.gallery.scrollEndToChange, title: i18n("galleryScrollEndToChangeTip") }, 'gallery.backgroundColor': { label: i18n("backgroundColor"), type: 'text', className: 'color', "default": prefs.gallery.backgroundColor || 'rgba(20,20,20,0.75)', line: 'end' }, 'gallery.exportType': { label: i18n("galleryExportType"), type: 'select', options: { 'grid': i18n("grid"), 'gridBig': i18n("gridBig"), 'list': i18n("list") }, "default": prefs.gallery.exportType, }, 'gallery.loadMore': { label: i18n("galleryAutoLoad"), type: 'checkbox', "default": prefs.gallery.loadMore }, 'gallery.loadAll': { label: i18n("galleryLoadAll"), type: 'checkbox', "default": prefs.gallery.loadAll, title: i18n("galleryLoadAllTip") }, 'gallery.viewmoreEndless': { label: i18n("viewmoreEndless"), type: 'checkbox', "default": prefs.gallery.viewmoreEndless }, 'gallery.downloadWithZip': { label: i18n("galleryDownloadWithZip"), type: 'checkbox', "default": prefs.gallery.downloadWithZip }, 'gallery.downloadGap': { label: i18n("galleryDownloadGap"), type: 'int', "default": prefs.gallery.downloadGap, after: ' ms', }, 'gallery.formatConversion': { label: i18n("formatConversion"), type: 'textarea', "default": prefs.gallery.formatConversion || '' }, 'gallery.scaleSmallSize': { label: i18n("galleryScaleSmallSize1"), type: 'int', "default": prefs.gallery.scaleSmallSize, after: i18n("galleryScaleSmallSize2") }, 'gallery.showSmallSize':{ label: i18n("galleryShowSmallSize"), type: 'checkbox', "default": prefs.gallery.showSmallSize }, 'gallery.transition': { label: i18n("galleryTransition"), type: 'checkbox', "default": prefs.gallery.transition }, 'gallery.disableArrow': { label: i18n("galleryDisableArrow"), type: 'checkbox', "default": prefs.gallery.disableArrow }, 'gallery.sidebarPosition': { label: i18n("gallerySidebarPosition"), type: 'select', options: { 'bottom': i18n("bottom"), 'right': i18n("right"), 'left': i18n("left"), 'top': i18n("top") }, "default": prefs.gallery.sidebarPosition, line: 'start', }, 'gallery.sidebarSize': { label: i18n("gallerySidebarSize"), type: 'int', "default": prefs.gallery.sidebarSize, title: i18n("gallerySidebarSizeTip"), after: ' '+i18n("px"), line: 'end', }, 'gallery.max': { label: i18n("galleryMax1"), type: 'number', "default": prefs.gallery.max, after: i18n("galleryMax2") }, 'gallery.autoZoom': { label: i18n("galleryAutoZoom"), type: 'checkbox', "default": prefs.gallery.autoZoom, title: i18n("galleryAutoZoomTip") }, 'gallery.descriptionLength': { label: i18n("galleryDescriptionLength1"), type: 'int', "default": prefs.gallery.descriptionLength, after: i18n("galleryDescriptionLength2") }, 'gallery.autoOpenViewmore': { label: i18n("autoOpenViewmore"), type: 'checkbox', "default": prefs.gallery.autoOpenViewmore }, 'gallery.autoOpenSites': { label: i18n("galleryAutoOpenSites"), type: 'textarea', "default": prefs.gallery.autoOpenSites }, 'gallery.searchData': { label: i18n("gallerySearchData"), type: 'textarea', "default": prefs.gallery.searchData }, 'gallery.editSite': { label: i18n("galleryEditSite"), type: 'select', options: editSitesName, "default": prefs.gallery.editSite, }, // 图片窗口 'imgWindow.fitToScreen': { label: i18n("imgWindowFitToScreen"), type: 'checkbox', "default": prefs.imgWindow.fitToScreen, section: [i18n("imgWindow")], title: i18n("imgWindowFitToScreenTip"), }, 'imgWindow.fitToScreenSmall': { label: i18n("imgWindowFitToScreenWhenSmall"), type: 'checkbox', "default": prefs.imgWindow.fitToScreenSmall }, 'imgWindow.suitLongImg': { label: i18n("suitLongImg"), type: 'checkbox', "default": prefs.imgWindow.suitLongImg }, 'imgWindow.switchStoreLoc': { label: i18n("switchStoreLoc"), type: 'checkbox', "default": prefs.imgWindow.switchStoreLoc }, 'imgWindow.defaultTool': { label: i18n("imgWindowDefaultTool"), type: 'select', options: { 'hand': i18n("hand"), 'rotate': i18n("rotate"), 'zoom': i18n("zoom"), }, "default": prefs.imgWindow.defaultTool, }, 'imgWindow.close.escKey': { label: i18n("imgWindowEscKey"), type: 'checkbox', "default": prefs.imgWindow.close.escKey, line: 'start', }, 'imgWindow.close.dblClickImgWindow': { label: i18n("imgWindowDblClickImgWindow"), type: 'checkbox', "default": prefs.imgWindow.close.dblClickImgWindow, }, 'imgWindow.close.clickOutside': { label: i18n("imgWindowClickOutside"), type: 'select', options: { '': i18n("none"), 'click': i18n("click"), 'dblclick': i18n("dblclick"), }, "default": prefs.imgWindow.close.clickOutside, title: i18n("imgWindowClickOutsideTip"), line: 'end', }, 'imgWindow.backgroundColor': { label: i18n("backgroundColor"), type: 'text', className: 'color', "default": prefs.imgWindow.backgroundColor, line: 'end' }, 'imgWindow.overlayer.shown': { label: i18n("imgWindowOverlayerShown"), type: 'checkbox', "default": prefs.imgWindow.overlayer.shown, line: 'start', }, 'imgWindow.overlayer.color': { label: i18n("imgWindowOverlayerColor"), type: 'text', className: 'color', "default": prefs.imgWindow.overlayer.color, line: 'end' }, 'imgWindow.shiftRotateStep': { label: i18n("imgWindowShiftRotateStep1"), type: 'int', "default": prefs.imgWindow.shiftRotateStep, after: i18n("imgWindowShiftRotateStep2") }, 'imgWindow.zoom.mouseWheelZoom': { label: i18n("imgWindowMouseWheelZoom"), type: 'checkbox', "default": prefs.imgWindow.zoom.mouseWheelZoom, }, 'imgWindow.zoom.range': { label: i18n("imgWindowZoomRange"), type: 'textarea', "default": prefs.imgWindow.zoom.range.join(', '), title: i18n("imgWindowZoomRangeTip"), attr: { "spellcheck": "false" } }, 'imgWindow.fixed': { label: i18n("positionFixed"), "default": prefs.imgWindow.fixed, type: 'checkbox', }, 'imgWindow.zIndex': { label: "z-Index", "default": prefs.imgWindow.zIndex, type: 'int', }, // 其它 'waitImgLoad': { label: i18n("waitImgLoad"), type: 'checkbox', "default": prefs.waitImgLoad, section: [i18n("others")], title: i18n("waitImgLoadTip") }, 'customLang': { label: i18n("customLang"), type: 'select', options: customLangOption, "default": prefs.customLang, line: 'end', }, 'saveName': { label: i18n("saveName"), type: 'select', options: { 0: i18n("default"), 1: i18n("textFirst"), 2: i18n("onlyUrl"), 3: i18n("urlAndText") }, "default": (prefs.saveName || 0), title: i18n("saveNameTip"), }, 'debug': { label: i18n("debug"), type: 'checkbox', "default": prefs.debug }, 'customRules': { label: GM_config.create('a', { href: 'https://github.com/hoothin/UserScripts/tree/master/Picviewer%20CE%2B#-custom-rules-example', target: '_blank', textContent: i18n("customRules") }), type: 'textarea', "default": prefs.customRules } /*'firstEngine': { label: i18n("firstEngine"), type: 'select', options: { "Tineye":"Tineye", "Google":"Google", "Baidu":"Baidu" }, "default": prefs.firstEngine, },*/ }, events: { open: async function(doc, win, frame) { let saveBtn = doc.querySelector("#"+this.id+"_saveBtn"); let closeBtn = doc.querySelector("#"+this.id+"_closeBtn"); let resetLink = doc.querySelector("#"+this.id+"_resetLink"); let customInput = doc.querySelector("#"+this.id+"_field_customRules"); customInput.style.height = "188px"; customInput.setAttribute("spellcheck", "false"); saveBtn.textContent = i18n("saveBtn"); saveBtn.title = i18n("saveBtnTips"); saveBtn.addEventListener('click', e => { if (customInput.value) { if (customInput.value.trim().indexOf("[") != 0) { e.stopPropagation(); e.preventDefault(); alert("The rules must be enclosed in square brackets ([])."); return; } try { var customRules; if (customInput.value.indexOf("name:") !== -1) { if (!isunsafe()) { unsafeWindow.eval(createScript(customInput.value)); } } else { customInput.value = JSON.stringify(JSON.parse(customInput.value), null, 4); } } catch(err) { e.stopPropagation(); e.preventDefault(); alert("Wrong rule:" + err.toString()); } } }, true); closeBtn.textContent=i18n("closeBtn"); closeBtn.title=i18n("closeBtnTips"); resetLink.textContent=i18n("resetLink"); resetLink.title=i18n("resetLinkTips"); let searchData=doc.getElementById(this.id+"_field_gallery.searchData"); if(searchData && searchData.value==""){ searchData.value=defaultSearchData; } let about = doc.getElementById(this.id + "_section_4"); if (about) { if (!newsNode) { newsNode = document.createElement("div"); let newsEles = createEleFromJson([ { node: "div", text: "Made with ❤️ by @", attr: { style: "width: calc(100% - 8px); text-align: center;" }, children: [ { node: "a", text: "Hoothin", attr: { "href": "mailto:rixixi@gmail.com" } }, { node: "br" }, { node: "span", text: "Join our " }, { node: "a", text: "Discord", attr: { href: "https://discord.com/invite/keqypXC6wD", target: "_blank" } } ] }, { node: "img", attr: { src: "https://s2.loli.net/2023/02/06/afTMxeASm48z5vE.jpg", style: "width: 100%; margin-top: 5px; max-height: 180px; display: none;", onload: "this.style.display=''" } }, { node: "div", attr: { style: "width: 100%; display: flex; align-items: center; justify-content: center; margin-top: 5px; font-size: 14px;" }, children: [ { node: "img", attr: { src: "https://ko-fi.com/favicon-32x32.png", style: "margin-right: 5px; height: 25px; display: none;", onload: "this.style.display=''" } }, { node: "a", text: "Ko-fi", attr: { href: "https://ko-fi.com/hoothin", style: "margin-right: 10px;", target: "_blank" } }, { node: "img", attr: { src: "https://static.afdiancdn.com/favicon.ico", style: "margin-right: 5px; height: 20px; display: none;", onload: "this.style.display=''" } }, { node: "a", text: "爱发电", attr: { href: "https://afdian.net/@hoothin", target: "_blank" } } ] } ]); newsNode.style.padding = "5px"; newsNode.appendChild(newsEles); about.appendChild(newsNode); } if (!newsInited) { let news = await GM_fetch(`https://hoothin.com/scripts/pvcep/${lang}`).then(response => response.json()).catch(e => {}); newsInited = true; if (!news) return; let newsEles = createEleFromJson(news); if (newsEles && newsEles.childElementCount) { if (newsNode) about.removeChild(newsNode); newsNode = document.createElement("div"); newsNode.appendChild(newsEles); } } about.appendChild(newsNode); } }, save: function() { loadPrefs(); storage.setItem("customLang", prefs.customLang); } } }); loadPrefs(); var hideIcon=storage.getListItem("hideIcon", location.hostname) || false; var hideIconStyle=document.createElement('style'); hideIconStyle.textContent=`#pv-float-bar-container{display:none!important}`; if(hideIcon){ document.head.appendChild(hideIconStyle); } _GM_registerMenuCommand(i18n("openConfig"), openPrefs); _GM_registerMenuCommand(i18n("openGallery"), openGallery); _GM_registerMenuCommand(i18n("hideIcon") + (hideIcon ? "☑️" : ""), () => { hideIcon=!hideIcon; storage.setListItem("hideIcon", location.hostname, hideIcon); if(hideIcon){ document.head.appendChild(hideIconStyle); }else{ document.head.removeChild(hideIconStyle); } }); _GM_registerMenuCommand(i18n("ruleRequest"), () => { _GM_openInTab("https://github.com/hoothin/UserScripts/issues/new?labels=Picviewer%20CE%2B&template=custom-rule-request.md&title=Request%20Picviewer%20CE%2B%20support%20for%20" + location.hostname, {active:true}); }); function initKeyInputs() { if (!GM_config.frame || !GM_config.frame.contentDocument) return; let keyInputs = GM_config.frame.contentDocument.querySelectorAll('input.floatBar-key'); [].forEach.call(keyInputs, input => { input.setAttribute('readOnly', 'readonly'); input.addEventListener("keydown", e => { if (e.key === 'Escape' || e.key === 'Backspace') input.value = ''; else input.value = e.key; e.stopPropagation(); e.preventDefault(); }); }); } matchedRule = getMatchedRule(); let editUrl=storage.getItem("editUrl"); if(editUrl){ let editFunc=editSitesFunc[prefs.gallery.editSite]; if(!editFunc)editFunc=editSitesFunc[Object.keys(editSitesFunc)[0]]; if(editFunc){ if (document.readyState == 'complete'){ editFunc(editUrl); }else{ let readystatechangeHandler = e => { if (document.readyState == 'complete') { editFunc(editUrl); document.removeEventListener('readystatechange', readystatechangeHandler); } }; document.addEventListener('readystatechange', readystatechangeHandler); } } } var configStyle = document.createElement("style"); configStyle.textContent = "#pv-prefs { display: initial; }"; configStyle.type = 'text/css'; if (location.hostname == "hoothin.github.io" && location.pathname == "/UserScripts/Picviewer%20CE+/") { openPrefs(); } else if (location.hostname == "hoothin.github.io" && location.pathname == "/UserScripts/Picviewer%20CE+/gallery.html") { let gallery = new GalleryC(); gallery.data = []; gallery.lockGallery = true; var allData = await gallery.getAllValidImgs(); gallery.data = allData; gallery.load(gallery.data); let searchParams = new URLSearchParams(location.search); let viewMore = searchParams.get("mode"); let imgs = searchParams.get("imgs"); if (imgs) { gallery.addImageUrls(imgs); } if (viewMore == "1") { gallery.maximizeSidebar(); } } else if (prefs.gallery.autoOpenSites) { var sitesArr=prefs.gallery.autoOpenSites.split("\n"); for(let s=0;s { if (!ruleImportUrlReg.test(location.href)) return; if (/pre|code/i.test(e.target.nodeName)) { let content = e.target.innerText.trim(); if (/"name":/.test(content) && /"(r|xhr)":/.test(content)) { try { localStorage.setItem('picviewerCE.config.curTab', 4); let webRule = JSON.parse(content); let customRules; let fieldsCustomRules = GM_config.fields.customRules; if (prefs.customRules.indexOf('"name":') !== -1) { customRules = JSON.parse(prefs.customRules); } else { customRules = []; } customRules.push(webRule); fieldsCustomRules.value = JSON.stringify(customRules, null, 4); openPrefs(); } catch (e) { alert(e.toString()); } } } }, true); } function openPrefs() { let fieldsSearchData = GM_config.fields["gallery.searchData"]; if (fieldsSearchData && fieldsSearchData.value) { fieldsSearchData.value = fieldsSearchData.value.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&").replace(/>/g, ">").replace(/").replace(/</g, "<").replace(/&/g, "&").replace(/>/g, ">").replace(/{ if (GM_config.frame && GM_config.frame.contentDocument.body.innerHTML === "") { _GM_openInTab("https://hoothin.github.io/UserScripts/Picviewer%20CE+/", {active:true}); return; } if (GM_config.frame && GM_config.frame.style && GM_config.frame.style.display == "none") { GM_config.frame.src=""; } initKeyInputs(); }, 1000); } function loadPrefs() { // 根据 GM_config 的 key 载入设置到 prefs Object.keys(GM_config.fields).forEach(function(keyStr) { var keys = keyStr.split('.'); var lastKey = keys.pop(); var lastPref = prefs; var curKey = keys.shift(); while(curKey){ lastPref = lastPref[curKey]; curKey = keys.shift(); } var value = GM_config.get(keyStr); if (typeof value != 'undefined') { // 特殊的 if (keyStr == 'magnifier.wheelZoom.range' || keyStr == 'imgWindow.zoom.range') { lastPref[lastKey] = value.split(/[,,]\s*/).map(function(s) { return parseFloat(s)}); } else if(keyStr == 'floatBar.butonOrder') { lastPref[lastKey] = value.trim().split(/\s*[,,]\s*/); } else { lastPref[lastKey] = value; } } }); try { if (localStorage && localStorage.setItem) { if (!storage.getItem('inited')) { localStorage.setItem('picviewerCE.config.curTab', 4); storage.setItem('inited', true); } } } catch(e) {} if (typeof prefs.gallery.formatConversion == 'undefined') { prefs.gallery.formatConversion = "webp>png"; } prefs.gallery.formatConversion.split("\n").forEach(str => { let pair = str.split(">"); if (pair.length !== 2) return; formatDict.set(pair[0].trim(), pair[1].trim()); }); debug = prefs.debug ? console.log.bind(console) : function() {}; } }; function drawTobase64(img){ canvas.width = img.naturalWidth || img.width; canvas.height = img.naturalHeight || img.height; let ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0); return canvas.toDataURL("image/png"); } function init2(){ init(topObject,window,document,arrayFn,envir,storage,unsafeWindow); }; //大致检测运行环境 var envir={ ie:typeof document.documentMode == 'number', firefox:typeof XPCNativeWrapper == 'function', opera:!!window.opera, chrome:!!window.chrome, }; //ie的话,不支持 < ie9的版本 if(envir.ie && document.documentMode < 9){ return; }; var arrayFn=(function(){ var arrayProto=Array.prototype; return { find:arrayProto.find, slice:arrayProto.slice, forEach:arrayProto.forEach, some:arrayProto.some, every:arrayProto.every, map:arrayProto.map, filter:arrayProto.filter, indexOf:arrayProto.indexOf, lastIndexOf:arrayProto.lastIndexOf, }; })(); var storage={ supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',//chrome的gm函数式空函数 mxAppStorage:(function(){//傲游扩展储存接口 try{ return window.external.mxGetRuntime().storage; }catch(e){ }; })(), operaUJSStorage:(function(){//opera userjs全局存储接口 try{ return window.opera.scriptStorage; }catch(e){ }; })(), setItem:function(key,value){ if (this.supportGM) { GM_setValue(key, value); if (value === "" && typeof GM_deleteValue != 'undefined') { GM_deleteValue(key); } } else if (this.operaUJSStorage) { this.operaUJSStorage.setItem(key, value); } else if (this.mxAppStorage) { this.mxAppStorage.setConfig(key, value); } else if (window.localStorage) { window.localStorage.setItem(key, value); } }, getItem:function(key){ var value; if(this.supportGM){ value=GM_getValue(key); }else if(this.operaUJSStorage){ value=this.operaUJSStorage.getItem(key); }else if(this.mxAppStorage){ value=this.mxAppStorage.getConfig(key); }else if(window.localStorage){ value=window.localStorage.getItem(key); }; return value; }, getListItem: function(list, key) { var value; var listData = this.getItem(list); if (listData) { for(var i = 0; i < listData.length; i++) { var data = listData[i]; if (data.k == key) { value = data.v; break; } } } return value; }, setListItem: function(list, key, value, limitNum = 50) { var listData = this.getItem(list); if (!listData || !listData.filter) listData = []; listData = listData.filter(data => data && data.k != key); if (value) { listData.unshift({k: key, v: value}); if (listData.length > limitNum) listData.pop(); } this.setItem(list, listData); } }; function getUrl(url, callback, onError){ _GM_xmlhttpRequest({ method: 'GET', url: url.trim(), onload: callback, onerror: onError }); } function setSearchState(words, imgState){ if (imgState) imgState.innerHTML=createHTML(words); } var searchSort=["Tineye","Google","Baidu"]; function sortSearch(){ for(var i=0;i2)break; srcs.push(imgData.objURL); } setSearchState(i18n("findOverBeginLoad",["百度",srcs.length]),imgCon); callBackFun(srcs); }else{ searchNext(); return; } }, onError); }; var searchGoogle=function(){ setSearchState(i18n("beginSearchImg","Google"),imgCon); getUrl("https://www.google.com/searchbyimage?safe=off&image_url="+encodeURIComponent(imgSrc), function(d){ let googleHtml=document.implementation.createHTMLDocument(''); googleHtml.documentElement.innerHTML = d.responseText; let sizeUrl=googleHtml.querySelector("div.card-section>div>div>span.gl>a"); if(sizeUrl){ getUrl("https://www.google.com"+sizeUrl.getAttribute("href"), function(d){ googleHtml.documentElement.innerHTML = d.responseText; let imgs=googleHtml.querySelectorAll("div.rg_meta"); if(imgs.length==0){searchNext();return;} srcs=[]; for(var i=0;i2)break; let jsonData=JSON.parse(imgs[i].innerHTML); srcs.push(jsonData.ou); } setSearchState(i18n("findOverBeginLoad",["Google",srcs.length]),imgCon); callBackFun(srcs); }, onError); }else{ searchNext(); } }, onError); }; var searchTineye=function(){ setSearchState(i18n("beginSearchImg","Tineye"),imgCon); getUrl("https://www.tineye.com/search?url="+encodeURIComponent(imgSrc)+"&sort=size", function(d){ let tineyeHtml=document.implementation.createHTMLDocument(''); tineyeHtml.documentElement.innerHTML = d.responseText; let searchImg=tineyeHtml.querySelectorAll(".match-details>div.match:first-of-type>p.image-link:first-of-type>a"); if(searchImg.length>0){ srcs=[]; for(var i=0;i2)break; srcs.push(searchImg[i].href); } setSearchState(i18n("findOverBeginLoad",["Tineye",srcs.length]),imgCon); callBackFun(srcs); }else{ searchNext(); } }, onError); }; var searchNext=function(){ searchFrom++; if(searchFrom<=searchSort.length)switchSearch(); else{ if(noneResult)noneResult(); setSearchState(i18n("findNoPic"),imgCon); setTimeout(function(){ setSearchState("",imgCon); },2000); } }; var callBackFun=function(srcs){ callBack(srcs, searchFrom); }; if(!searchFrom)searchFrom=1; var switchSearch=function(){ switch(searchSort[searchFrom-1]){ case "Baidu": searchBaidu(); break; case "Google": searchGoogle(); break; case "Tineye": searchTineye(); break; default: searchTineye(); break; } }; switchSearch(); } init2(); })(this,window,document,(typeof unsafeWindow=='undefined'? window : unsafeWindow));