app.js 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PDFViewerApplication = exports.PDFPrintServiceFactory = exports.DefaultExternalServices = void 0;
  27. var _ui_utils = require("./ui_utils.js");
  28. var _app_options = require("./app_options.js");
  29. var _pdf = require("../pdf");
  30. var _pdf_cursor_tools = require("./pdf_cursor_tools.js");
  31. var _pdf_rendering_queue = require("./pdf_rendering_queue.js");
  32. var _overlay_manager = require("./overlay_manager.js");
  33. var _password_prompt = require("./password_prompt.js");
  34. var _pdf_attachment_viewer = require("./pdf_attachment_viewer.js");
  35. var _pdf_document_properties = require("./pdf_document_properties.js");
  36. var _pdf_find_bar = require("./pdf_find_bar.js");
  37. var _pdf_find_controller = require("./pdf_find_controller.js");
  38. var _pdf_history = require("./pdf_history.js");
  39. var _pdf_layer_viewer = require("./pdf_layer_viewer.js");
  40. var _pdf_link_service = require("./pdf_link_service.js");
  41. var _pdf_outline_viewer = require("./pdf_outline_viewer.js");
  42. var _pdf_presentation_mode = require("./pdf_presentation_mode.js");
  43. var _pdf_sidebar = require("./pdf_sidebar.js");
  44. var _pdf_sidebar_resizer = require("./pdf_sidebar_resizer.js");
  45. var _pdf_thumbnail_viewer = require("./pdf_thumbnail_viewer.js");
  46. var _pdf_viewer = require("./pdf_viewer.js");
  47. var _secondary_toolbar = require("./secondary_toolbar.js");
  48. var _toolbar = require("./toolbar.js");
  49. var _viewer_compatibility = require("./viewer_compatibility.js");
  50. var _view_history = require("./view_history.js");
  51. const DEFAULT_SCALE_DELTA = 1.1;
  52. const DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000;
  53. const FORCE_PAGES_LOADED_TIMEOUT = 10000;
  54. const WHEEL_ZOOM_DISABLED_TIMEOUT = 1000;
  55. const ENABLE_PERMISSIONS_CLASS = "enablePermissions";
  56. const ViewOnLoad = {
  57. UNKNOWN: -1,
  58. PREVIOUS: 0,
  59. INITIAL: 1
  60. };
  61. const ViewerCssTheme = {
  62. AUTOMATIC: 0,
  63. LIGHT: 1,
  64. DARK: 2
  65. };
  66. const KNOWN_VERSIONS = ["1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2.0", "2.1", "2.2", "2.3"];
  67. const KNOWN_GENERATORS = ["acrobat distiller", "acrobat pdfwriter", "adobe livecycle", "adobe pdf library", "adobe photoshop", "ghostscript", "tcpdf", "cairo", "dvipdfm", "dvips", "pdftex", "pdfkit", "itext", "prince", "quarkxpress", "mac os x", "microsoft", "openoffice", "oracle", "luradocument", "pdf-xchange", "antenna house", "aspose.cells", "fpdf"];
  68. class DefaultExternalServices {
  69. constructor() {
  70. throw new Error("Cannot initialize DefaultExternalServices.");
  71. }
  72. static updateFindControlState(data) {}
  73. static updateFindMatchesCount(data) {}
  74. static initPassiveLoading(callbacks) {}
  75. static async fallback(data) {}
  76. static reportTelemetry(data) {}
  77. static createDownloadManager(options) {
  78. throw new Error("Not implemented: createDownloadManager");
  79. }
  80. static createPreferences() {
  81. throw new Error("Not implemented: createPreferences");
  82. }
  83. static createL10n(options) {
  84. throw new Error("Not implemented: createL10n");
  85. }
  86. static createScripting(options) {
  87. throw new Error("Not implemented: createScripting");
  88. }
  89. static get supportsIntegratedFind() {
  90. return (0, _pdf.shadow)(this, "supportsIntegratedFind", false);
  91. }
  92. static get supportsDocumentFonts() {
  93. return (0, _pdf.shadow)(this, "supportsDocumentFonts", true);
  94. }
  95. static get supportedMouseWheelZoomModifierKeys() {
  96. return (0, _pdf.shadow)(this, "supportedMouseWheelZoomModifierKeys", {
  97. ctrlKey: true,
  98. metaKey: true
  99. });
  100. }
  101. static get isInAutomation() {
  102. return (0, _pdf.shadow)(this, "isInAutomation", false);
  103. }
  104. }
  105. exports.DefaultExternalServices = DefaultExternalServices;
  106. const PDFViewerApplication = {
  107. initialBookmark: document.location.hash.substring(1),
  108. _initializedCapability: (0, _pdf.createPromiseCapability)(),
  109. fellback: false,
  110. appConfig: null,
  111. pdfDocument: null,
  112. pdfLoadingTask: null,
  113. printService: null,
  114. pdfViewer: null,
  115. pdfThumbnailViewer: null,
  116. pdfRenderingQueue: null,
  117. pdfPresentationMode: null,
  118. pdfDocumentProperties: null,
  119. pdfLinkService: null,
  120. pdfHistory: null,
  121. pdfSidebar: null,
  122. pdfSidebarResizer: null,
  123. pdfOutlineViewer: null,
  124. pdfAttachmentViewer: null,
  125. pdfLayerViewer: null,
  126. pdfCursorTools: null,
  127. store: null,
  128. downloadManager: null,
  129. overlayManager: null,
  130. preferences: null,
  131. toolbar: null,
  132. secondaryToolbar: null,
  133. eventBus: null,
  134. l10n: null,
  135. isInitialViewSet: false,
  136. downloadComplete: false,
  137. isViewerEmbedded: window.parent !== window,
  138. url: "",
  139. baseUrl: "",
  140. externalServices: DefaultExternalServices,
  141. _boundEvents: Object.create(null),
  142. documentInfo: null,
  143. metadata: null,
  144. _contentDispositionFilename: null,
  145. _contentLength: null,
  146. triggerDelayedFallback: null,
  147. _saveInProgress: false,
  148. _wheelUnusedTicks: 0,
  149. _idleCallbacks: new Set(),
  150. _scriptingInstance: null,
  151. _mouseState: Object.create(null),
  152. async initialize(appConfig) {
  153. this.preferences = this.externalServices.createPreferences();
  154. this.appConfig = appConfig;
  155. await this._readPreferences();
  156. await this._parseHashParameters();
  157. this._forceCssTheme();
  158. await this._initializeL10n();
  159. if (this.isViewerEmbedded && _app_options.AppOptions.get("externalLinkTarget") === _pdf.LinkTarget.NONE) {
  160. _app_options.AppOptions.set("externalLinkTarget", _pdf.LinkTarget.TOP);
  161. }
  162. await this._initializeViewerComponents();
  163. this.bindEvents();
  164. this.bindWindowEvents();
  165. const appContainer = appConfig.appContainer || document.documentElement;
  166. this.l10n.translate(appContainer).then(() => {
  167. this.eventBus.dispatch("localized", {
  168. source: this
  169. });
  170. });
  171. this._initializedCapability.resolve();
  172. },
  173. async _readPreferences() {
  174. if (_app_options.AppOptions.get("disablePreferences")) {
  175. return;
  176. }
  177. try {
  178. _app_options.AppOptions.setAll(await this.preferences.getAll());
  179. } catch (reason) {
  180. console.error(`_readPreferences: "${reason?.message}".`);
  181. }
  182. },
  183. async _parseHashParameters() {
  184. if (!_app_options.AppOptions.get("pdfBugEnabled")) {
  185. return undefined;
  186. }
  187. const hash = document.location.hash.substring(1);
  188. if (!hash) {
  189. return undefined;
  190. }
  191. const hashParams = (0, _ui_utils.parseQueryString)(hash),
  192. waitOn = [];
  193. if ("disableworker" in hashParams && hashParams.disableworker === "true") {
  194. waitOn.push(loadFakeWorker());
  195. }
  196. if ("disablerange" in hashParams) {
  197. _app_options.AppOptions.set("disableRange", hashParams.disablerange === "true");
  198. }
  199. if ("disablestream" in hashParams) {
  200. _app_options.AppOptions.set("disableStream", hashParams.disablestream === "true");
  201. }
  202. if ("disableautofetch" in hashParams) {
  203. _app_options.AppOptions.set("disableAutoFetch", hashParams.disableautofetch === "true");
  204. }
  205. if ("disablefontface" in hashParams) {
  206. _app_options.AppOptions.set("disableFontFace", hashParams.disablefontface === "true");
  207. }
  208. if ("disablehistory" in hashParams) {
  209. _app_options.AppOptions.set("disableHistory", hashParams.disablehistory === "true");
  210. }
  211. if ("webgl" in hashParams) {
  212. _app_options.AppOptions.set("enableWebGL", hashParams.webgl === "true");
  213. }
  214. if ("verbosity" in hashParams) {
  215. _app_options.AppOptions.set("verbosity", hashParams.verbosity | 0);
  216. }
  217. if ("textlayer" in hashParams) {
  218. switch (hashParams.textlayer) {
  219. case "off":
  220. _app_options.AppOptions.set("textLayerMode", _ui_utils.TextLayerMode.DISABLE);
  221. break;
  222. case "visible":
  223. case "shadow":
  224. case "hover":
  225. const viewer = this.appConfig.viewerContainer;
  226. viewer.classList.add("textLayer-" + hashParams.textlayer);
  227. break;
  228. }
  229. }
  230. if ("pdfbug" in hashParams) {
  231. _app_options.AppOptions.set("pdfBug", true);
  232. _app_options.AppOptions.set("fontExtraProperties", true);
  233. const enabled = hashParams.pdfbug.split(",");
  234. waitOn.push(loadAndEnablePDFBug(enabled));
  235. }
  236. if ("locale" in hashParams) {
  237. _app_options.AppOptions.set("locale", hashParams.locale);
  238. }
  239. if (waitOn.length === 0) {
  240. return undefined;
  241. }
  242. return Promise.all(waitOn).catch(reason => {
  243. console.error(`_parseHashParameters: "${reason.message}".`);
  244. });
  245. },
  246. async _initializeL10n() {
  247. this.l10n = this.externalServices.createL10n({
  248. locale: _app_options.AppOptions.get("locale")
  249. });
  250. const dir = await this.l10n.getDirection();
  251. document.getElementsByTagName("html")[0].dir = dir;
  252. },
  253. _forceCssTheme() {
  254. const cssTheme = _app_options.AppOptions.get("viewerCssTheme");
  255. if (cssTheme === ViewerCssTheme.AUTOMATIC || !Object.values(ViewerCssTheme).includes(cssTheme)) {
  256. return;
  257. }
  258. try {
  259. const styleSheet = document.styleSheets[0];
  260. const cssRules = styleSheet?.cssRules || [];
  261. for (let i = 0, ii = cssRules.length; i < ii; i++) {
  262. const rule = cssRules[i];
  263. if (rule instanceof CSSMediaRule && rule.media?.[0] === "(prefers-color-scheme: dark)") {
  264. if (cssTheme === ViewerCssTheme.LIGHT) {
  265. styleSheet.deleteRule(i);
  266. return;
  267. }
  268. const darkRules = /^@media \(prefers-color-scheme: dark\) {\n\s*([\w\s-.,:;/\\{}()]+)\n}$/.exec(rule.cssText);
  269. if (darkRules?.[1]) {
  270. styleSheet.deleteRule(i);
  271. styleSheet.insertRule(darkRules[1], i);
  272. }
  273. return;
  274. }
  275. }
  276. } catch (reason) {
  277. console.error(`_forceCssTheme: "${reason?.message}".`);
  278. }
  279. },
  280. async _initializeViewerComponents() {
  281. const appConfig = this.appConfig;
  282. const eventBus = appConfig.eventBus || new _ui_utils.EventBus({
  283. isInAutomation: this.externalServices.isInAutomation
  284. });
  285. this.eventBus = eventBus;
  286. this.overlayManager = new _overlay_manager.OverlayManager();
  287. const pdfRenderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
  288. pdfRenderingQueue.onIdle = this.cleanup.bind(this);
  289. this.pdfRenderingQueue = pdfRenderingQueue;
  290. const pdfLinkService = new _pdf_link_service.PDFLinkService({
  291. eventBus,
  292. externalLinkTarget: _app_options.AppOptions.get("externalLinkTarget"),
  293. externalLinkRel: _app_options.AppOptions.get("externalLinkRel"),
  294. ignoreDestinationZoom: _app_options.AppOptions.get("ignoreDestinationZoom")
  295. });
  296. this.pdfLinkService = pdfLinkService;
  297. const downloadManager = this.externalServices.createDownloadManager();
  298. this.downloadManager = downloadManager;
  299. const findController = new _pdf_find_controller.PDFFindController({
  300. linkService: pdfLinkService,
  301. eventBus
  302. });
  303. this.findController = findController;
  304. const container = appConfig.mainContainer;
  305. const viewer = appConfig.viewerContainer;
  306. this.pdfViewer = new _pdf_viewer.PDFViewer({
  307. container,
  308. viewer,
  309. eventBus,
  310. renderingQueue: pdfRenderingQueue,
  311. linkService: pdfLinkService,
  312. downloadManager,
  313. findController,
  314. renderer: _app_options.AppOptions.get("renderer"),
  315. enableWebGL: _app_options.AppOptions.get("enableWebGL"),
  316. l10n: this.l10n,
  317. textLayerMode: _app_options.AppOptions.get("textLayerMode"),
  318. imageResourcesPath: _app_options.AppOptions.get("imageResourcesPath"),
  319. renderInteractiveForms: _app_options.AppOptions.get("renderInteractiveForms"),
  320. enablePrintAutoRotate: _app_options.AppOptions.get("enablePrintAutoRotate"),
  321. useOnlyCssZoom: _app_options.AppOptions.get("useOnlyCssZoom"),
  322. maxCanvasPixels: _app_options.AppOptions.get("maxCanvasPixels"),
  323. enableScripting: _app_options.AppOptions.get("enableScripting"),
  324. mouseState: this._mouseState
  325. });
  326. pdfRenderingQueue.setViewer(this.pdfViewer);
  327. pdfLinkService.setViewer(this.pdfViewer);
  328. this.pdfThumbnailViewer = new _pdf_thumbnail_viewer.PDFThumbnailViewer({
  329. container: appConfig.sidebar.thumbnailView,
  330. eventBus,
  331. renderingQueue: pdfRenderingQueue,
  332. linkService: pdfLinkService,
  333. l10n: this.l10n
  334. });
  335. pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
  336. this.pdfHistory = new _pdf_history.PDFHistory({
  337. linkService: pdfLinkService,
  338. eventBus
  339. });
  340. pdfLinkService.setHistory(this.pdfHistory);
  341. if (!this.supportsIntegratedFind) {
  342. this.findBar = new _pdf_find_bar.PDFFindBar(appConfig.findBar, eventBus, this.l10n);
  343. }
  344. this.pdfDocumentProperties = new _pdf_document_properties.PDFDocumentProperties(appConfig.documentProperties, this.overlayManager, eventBus, this.l10n);
  345. this.pdfCursorTools = new _pdf_cursor_tools.PDFCursorTools({
  346. container,
  347. eventBus,
  348. cursorToolOnLoad: _app_options.AppOptions.get("cursorToolOnLoad")
  349. });
  350. this.toolbar = new _toolbar.Toolbar(appConfig.toolbar, eventBus, this.l10n);
  351. this.secondaryToolbar = new _secondary_toolbar.SecondaryToolbar(appConfig.secondaryToolbar, container, eventBus);
  352. if (this.supportsFullscreen) {
  353. this.pdfPresentationMode = new _pdf_presentation_mode.PDFPresentationMode({
  354. container,
  355. pdfViewer: this.pdfViewer,
  356. eventBus,
  357. contextMenuItems: appConfig.fullscreen
  358. });
  359. }
  360. this.passwordPrompt = new _password_prompt.PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, this.l10n);
  361. this.pdfOutlineViewer = new _pdf_outline_viewer.PDFOutlineViewer({
  362. container: appConfig.sidebar.outlineView,
  363. eventBus,
  364. linkService: pdfLinkService
  365. });
  366. this.pdfAttachmentViewer = new _pdf_attachment_viewer.PDFAttachmentViewer({
  367. container: appConfig.sidebar.attachmentsView,
  368. eventBus,
  369. downloadManager
  370. });
  371. this.pdfLayerViewer = new _pdf_layer_viewer.PDFLayerViewer({
  372. container: appConfig.sidebar.layersView,
  373. eventBus,
  374. l10n: this.l10n
  375. });
  376. this.pdfSidebar = new _pdf_sidebar.PDFSidebar({
  377. elements: appConfig.sidebar,
  378. pdfViewer: this.pdfViewer,
  379. pdfThumbnailViewer: this.pdfThumbnailViewer,
  380. eventBus,
  381. l10n: this.l10n
  382. });
  383. this.pdfSidebar.onToggled = this.forceRendering.bind(this);
  384. this.pdfSidebarResizer = new _pdf_sidebar_resizer.PDFSidebarResizer(appConfig.sidebarResizer, eventBus, this.l10n);
  385. },
  386. run(config) {
  387. this.initialize(config).then(webViewerInitialized);
  388. },
  389. get initialized() {
  390. return this._initializedCapability.settled;
  391. },
  392. get initializedPromise() {
  393. return this._initializedCapability.promise;
  394. },
  395. zoomIn(ticks) {
  396. if (this.pdfViewer.isInPresentationMode) {
  397. return;
  398. }
  399. let newScale = this.pdfViewer.currentScale;
  400. do {
  401. newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
  402. newScale = Math.ceil(newScale * 10) / 10;
  403. newScale = Math.min(_ui_utils.MAX_SCALE, newScale);
  404. } while (--ticks > 0 && newScale < _ui_utils.MAX_SCALE);
  405. this.pdfViewer.currentScaleValue = newScale;
  406. },
  407. zoomOut(ticks) {
  408. if (this.pdfViewer.isInPresentationMode) {
  409. return;
  410. }
  411. let newScale = this.pdfViewer.currentScale;
  412. do {
  413. newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
  414. newScale = Math.floor(newScale * 10) / 10;
  415. newScale = Math.max(_ui_utils.MIN_SCALE, newScale);
  416. } while (--ticks > 0 && newScale > _ui_utils.MIN_SCALE);
  417. this.pdfViewer.currentScaleValue = newScale;
  418. },
  419. zoomReset() {
  420. if (this.pdfViewer.isInPresentationMode) {
  421. return;
  422. }
  423. this.pdfViewer.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  424. },
  425. get pagesCount() {
  426. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  427. },
  428. get page() {
  429. return this.pdfViewer.currentPageNumber;
  430. },
  431. set page(val) {
  432. this.pdfViewer.currentPageNumber = val;
  433. },
  434. get supportsPrinting() {
  435. return PDFPrintServiceFactory.instance.supportsPrinting;
  436. },
  437. get supportsFullscreen() {
  438. let support;
  439. const doc = document.documentElement;
  440. support = !!(doc.requestFullscreen || doc.mozRequestFullScreen || doc.webkitRequestFullScreen);
  441. if (document.fullscreenEnabled === false || document.mozFullScreenEnabled === false || document.webkitFullscreenEnabled === false) {
  442. support = false;
  443. }
  444. return (0, _pdf.shadow)(this, "supportsFullscreen", support);
  445. },
  446. get supportsIntegratedFind() {
  447. return this.externalServices.supportsIntegratedFind;
  448. },
  449. get supportsDocumentFonts() {
  450. return this.externalServices.supportsDocumentFonts;
  451. },
  452. get loadingBar() {
  453. const bar = new _ui_utils.ProgressBar("#loadingBar");
  454. return (0, _pdf.shadow)(this, "loadingBar", bar);
  455. },
  456. get supportedMouseWheelZoomModifierKeys() {
  457. return this.externalServices.supportedMouseWheelZoomModifierKeys;
  458. },
  459. initPassiveLoading() {
  460. throw new Error("Not implemented: initPassiveLoading");
  461. },
  462. setTitleUsingUrl(url = "") {
  463. this.url = url;
  464. this.baseUrl = url.split("#")[0];
  465. let title = (0, _ui_utils.getPDFFileNameFromURL)(url, "");
  466. if (!title) {
  467. try {
  468. title = decodeURIComponent((0, _pdf.getFilenameFromUrl)(url)) || url;
  469. } catch (ex) {
  470. title = url;
  471. }
  472. }
  473. this.setTitle(title);
  474. },
  475. setTitle(title) {
  476. if (this.isViewerEmbedded) {
  477. return;
  478. }
  479. document.title = title;
  480. },
  481. get _docFilename() {
  482. return this._contentDispositionFilename || (0, _ui_utils.getPDFFileNameFromURL)(this.url);
  483. },
  484. _cancelIdleCallbacks() {
  485. if (!this._idleCallbacks.size) {
  486. return;
  487. }
  488. for (const callback of this._idleCallbacks) {
  489. window.cancelIdleCallback(callback);
  490. }
  491. this._idleCallbacks.clear();
  492. },
  493. async _destroyScriptingInstance() {
  494. if (!this._scriptingInstance) {
  495. return;
  496. }
  497. const {
  498. scripting,
  499. internalEvents,
  500. domEvents
  501. } = this._scriptingInstance;
  502. try {
  503. await scripting.destroySandbox();
  504. } catch (ex) {}
  505. for (const [name, listener] of internalEvents) {
  506. this.eventBus._off(name, listener);
  507. }
  508. internalEvents.clear();
  509. for (const [name, listener] of domEvents) {
  510. window.removeEventListener(name, listener);
  511. }
  512. domEvents.clear();
  513. delete this._mouseState.isDown;
  514. this._scriptingInstance = null;
  515. },
  516. async close() {
  517. const errorWrapper = this.appConfig.errorWrapper.container;
  518. errorWrapper.setAttribute("hidden", "true");
  519. if (!this.pdfLoadingTask) {
  520. return undefined;
  521. }
  522. const promises = [];
  523. promises.push(this.pdfLoadingTask.destroy());
  524. this.pdfLoadingTask = null;
  525. if (this.pdfDocument) {
  526. this.pdfDocument = null;
  527. this.pdfThumbnailViewer.setDocument(null);
  528. this.pdfViewer.setDocument(null);
  529. this.pdfLinkService.setDocument(null);
  530. this.pdfDocumentProperties.setDocument(null);
  531. }
  532. webViewerResetPermissions();
  533. this.store = null;
  534. this.isInitialViewSet = false;
  535. this.downloadComplete = false;
  536. this.url = "";
  537. this.baseUrl = "";
  538. this.documentInfo = null;
  539. this.metadata = null;
  540. this._contentDispositionFilename = null;
  541. this._contentLength = null;
  542. this.triggerDelayedFallback = null;
  543. this._saveInProgress = false;
  544. this._cancelIdleCallbacks();
  545. promises.push(this._destroyScriptingInstance());
  546. this.pdfSidebar.reset();
  547. this.pdfOutlineViewer.reset();
  548. this.pdfAttachmentViewer.reset();
  549. this.pdfLayerViewer.reset();
  550. if (this.pdfHistory) {
  551. this.pdfHistory.reset();
  552. }
  553. if (this.findBar) {
  554. this.findBar.reset();
  555. }
  556. this.toolbar.reset();
  557. this.secondaryToolbar.reset();
  558. if (typeof PDFBug !== "undefined") {
  559. PDFBug.cleanup();
  560. }
  561. await Promise.all(promises);
  562. return undefined;
  563. },
  564. async open(file, args) {
  565. if (this.pdfLoadingTask) {
  566. await this.close();
  567. }
  568. const workerParameters = _app_options.AppOptions.getAll(_app_options.OptionKind.WORKER);
  569. for (const key in workerParameters) {
  570. _pdf.GlobalWorkerOptions[key] = workerParameters[key];
  571. }
  572. const parameters = Object.create(null);
  573. if (typeof file === "string") {
  574. this.setTitleUsingUrl(file);
  575. parameters.url = file;
  576. } else if (file && "byteLength" in file) {
  577. parameters.data = file;
  578. } else if (file.url && file.originalUrl) {
  579. this.setTitleUsingUrl(file.originalUrl);
  580. parameters.url = file.url;
  581. }
  582. const apiParameters = _app_options.AppOptions.getAll(_app_options.OptionKind.API);
  583. for (const key in apiParameters) {
  584. let value = apiParameters[key];
  585. if (key === "docBaseUrl" && !value) {}
  586. parameters[key] = value;
  587. }
  588. if (args) {
  589. for (const key in args) {
  590. parameters[key] = args[key];
  591. }
  592. }
  593. const loadingTask = (0, _pdf.getDocument)(parameters);
  594. this.pdfLoadingTask = loadingTask;
  595. loadingTask.onPassword = (updateCallback, reason) => {
  596. this.pdfLinkService.externalLinkEnabled = false;
  597. this.passwordPrompt.setUpdateCallback(updateCallback, reason);
  598. this.passwordPrompt.open();
  599. };
  600. loadingTask.onProgress = ({
  601. loaded,
  602. total
  603. }) => {
  604. this.progress(loaded / total);
  605. };
  606. loadingTask.onUnsupportedFeature = this.fallback.bind(this);
  607. return loadingTask.promise.then(pdfDocument => {
  608. this.load(pdfDocument);
  609. }, exception => {
  610. if (loadingTask !== this.pdfLoadingTask) {
  611. return undefined;
  612. }
  613. const message = exception?.message;
  614. let loadingErrorMessage;
  615. if (exception instanceof _pdf.InvalidPDFException) {
  616. loadingErrorMessage = this.l10n.get("invalid_file_error", null, "Invalid or corrupted PDF file.");
  617. } else if (exception instanceof _pdf.MissingPDFException) {
  618. loadingErrorMessage = this.l10n.get("missing_file_error", null, "Missing PDF file.");
  619. } else if (exception instanceof _pdf.UnexpectedResponseException) {
  620. loadingErrorMessage = this.l10n.get("unexpected_response_error", null, "Unexpected server response.");
  621. } else {
  622. loadingErrorMessage = this.l10n.get("loading_error", null, "An error occurred while loading the PDF.");
  623. }
  624. return loadingErrorMessage.then(msg => {
  625. this.error(msg, {
  626. message
  627. });
  628. throw exception;
  629. });
  630. });
  631. },
  632. download({
  633. sourceEventType = "download"
  634. } = {}) {
  635. function downloadByUrl() {
  636. downloadManager.downloadUrl(url, filename);
  637. }
  638. const downloadManager = this.downloadManager,
  639. url = this.baseUrl,
  640. filename = this._docFilename;
  641. if (!this.pdfDocument || !this.downloadComplete) {
  642. downloadByUrl();
  643. return;
  644. }
  645. this.pdfDocument.getData().then(function (data) {
  646. const blob = new Blob([data], {
  647. type: "application/pdf"
  648. });
  649. downloadManager.download(blob, url, filename, sourceEventType);
  650. }).catch(downloadByUrl);
  651. },
  652. async save({
  653. sourceEventType = "download"
  654. } = {}) {
  655. if (this._saveInProgress) {
  656. return;
  657. }
  658. const downloadManager = this.downloadManager,
  659. url = this.baseUrl,
  660. filename = this._docFilename;
  661. if (!this.pdfDocument || !this.downloadComplete) {
  662. this.download({
  663. sourceEventType
  664. });
  665. return;
  666. }
  667. this._saveInProgress = true;
  668. await this._scriptingInstance?.scripting.dispatchEventInSandbox({
  669. id: "doc",
  670. name: "WillSave"
  671. });
  672. this.pdfDocument.saveDocument(this.pdfDocument.annotationStorage).then(data => {
  673. const blob = new Blob([data], {
  674. type: "application/pdf"
  675. });
  676. downloadManager.download(blob, url, filename, sourceEventType);
  677. }).catch(() => {
  678. this.download({
  679. sourceEventType
  680. });
  681. }).finally(async () => {
  682. await this._scriptingInstance?.scripting.dispatchEventInSandbox({
  683. id: "doc",
  684. name: "DidSave"
  685. });
  686. this._saveInProgress = false;
  687. });
  688. },
  689. downloadOrSave(options) {
  690. if (this.pdfDocument?.annotationStorage.size > 0) {
  691. this.save(options);
  692. } else {
  693. this.download(options);
  694. }
  695. },
  696. _delayedFallback(featureId) {
  697. this.externalServices.reportTelemetry({
  698. type: "unsupportedFeature",
  699. featureId
  700. });
  701. if (!this.triggerDelayedFallback) {
  702. this.triggerDelayedFallback = () => {
  703. this.fallback(featureId);
  704. this.triggerDelayedFallback = null;
  705. };
  706. }
  707. },
  708. fallback(featureId) {
  709. this.externalServices.reportTelemetry({
  710. type: "unsupportedFeature",
  711. featureId
  712. });
  713. if (this.fellback) {
  714. return;
  715. }
  716. this.fellback = true;
  717. this.externalServices.fallback({
  718. featureId,
  719. url: this.baseUrl
  720. }).then(download => {
  721. if (!download) {
  722. return;
  723. }
  724. this.download({
  725. sourceEventType: "download"
  726. });
  727. });
  728. },
  729. error(message, moreInfo) {
  730. const moreInfoText = [this.l10n.get("error_version_info", {
  731. version: _pdf.version || "?",
  732. build: _pdf.build || "?"
  733. }, "PDF.js v{{version}} (build: {{build}})")];
  734. if (moreInfo) {
  735. moreInfoText.push(this.l10n.get("error_message", {
  736. message: moreInfo.message
  737. }, "Message: {{message}}"));
  738. if (moreInfo.stack) {
  739. moreInfoText.push(this.l10n.get("error_stack", {
  740. stack: moreInfo.stack
  741. }, "Stack: {{stack}}"));
  742. } else {
  743. if (moreInfo.filename) {
  744. moreInfoText.push(this.l10n.get("error_file", {
  745. file: moreInfo.filename
  746. }, "File: {{file}}"));
  747. }
  748. if (moreInfo.lineNumber) {
  749. moreInfoText.push(this.l10n.get("error_line", {
  750. line: moreInfo.lineNumber
  751. }, "Line: {{line}}"));
  752. }
  753. }
  754. }
  755. const errorWrapperConfig = this.appConfig.errorWrapper;
  756. const errorWrapper = errorWrapperConfig.container;
  757. errorWrapper.removeAttribute("hidden");
  758. const errorMessage = errorWrapperConfig.errorMessage;
  759. errorMessage.textContent = message;
  760. const closeButton = errorWrapperConfig.closeButton;
  761. closeButton.onclick = function () {
  762. errorWrapper.setAttribute("hidden", "true");
  763. };
  764. const errorMoreInfo = errorWrapperConfig.errorMoreInfo;
  765. const moreInfoButton = errorWrapperConfig.moreInfoButton;
  766. const lessInfoButton = errorWrapperConfig.lessInfoButton;
  767. moreInfoButton.onclick = function () {
  768. errorMoreInfo.removeAttribute("hidden");
  769. moreInfoButton.setAttribute("hidden", "true");
  770. lessInfoButton.removeAttribute("hidden");
  771. errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px";
  772. };
  773. lessInfoButton.onclick = function () {
  774. errorMoreInfo.setAttribute("hidden", "true");
  775. moreInfoButton.removeAttribute("hidden");
  776. lessInfoButton.setAttribute("hidden", "true");
  777. };
  778. moreInfoButton.oncontextmenu = _ui_utils.noContextMenuHandler;
  779. lessInfoButton.oncontextmenu = _ui_utils.noContextMenuHandler;
  780. closeButton.oncontextmenu = _ui_utils.noContextMenuHandler;
  781. moreInfoButton.removeAttribute("hidden");
  782. lessInfoButton.setAttribute("hidden", "true");
  783. Promise.all(moreInfoText).then(parts => {
  784. errorMoreInfo.value = parts.join("\n");
  785. });
  786. },
  787. progress(level) {
  788. if (this.downloadComplete) {
  789. return;
  790. }
  791. const percent = Math.round(level * 100);
  792. if (percent > this.loadingBar.percent || isNaN(percent)) {
  793. this.loadingBar.percent = percent;
  794. const disableAutoFetch = this.pdfDocument ? this.pdfDocument.loadingParams.disableAutoFetch : _app_options.AppOptions.get("disableAutoFetch");
  795. if (disableAutoFetch && percent) {
  796. if (this.disableAutoFetchLoadingBarTimeout) {
  797. clearTimeout(this.disableAutoFetchLoadingBarTimeout);
  798. this.disableAutoFetchLoadingBarTimeout = null;
  799. }
  800. this.loadingBar.show();
  801. this.disableAutoFetchLoadingBarTimeout = setTimeout(() => {
  802. this.loadingBar.hide();
  803. this.disableAutoFetchLoadingBarTimeout = null;
  804. }, DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT);
  805. }
  806. }
  807. },
  808. load(pdfDocument) {
  809. this.pdfDocument = pdfDocument;
  810. pdfDocument.getDownloadInfo().then(({
  811. length
  812. }) => {
  813. this._contentLength = length;
  814. this.downloadComplete = true;
  815. this.loadingBar.hide();
  816. firstPagePromise.then(() => {
  817. this.eventBus.dispatch("documentloaded", {
  818. source: this
  819. });
  820. });
  821. });
  822. const pageLayoutPromise = pdfDocument.getPageLayout().catch(function () {});
  823. const pageModePromise = pdfDocument.getPageMode().catch(function () {});
  824. const openActionPromise = pdfDocument.getOpenAction().catch(function () {});
  825. this.toolbar.setPagesCount(pdfDocument.numPages, false);
  826. this.secondaryToolbar.setPagesCount(pdfDocument.numPages);
  827. let baseDocumentUrl;
  828. baseDocumentUrl = null;
  829. this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl);
  830. this.pdfDocumentProperties.setDocument(pdfDocument, this.url);
  831. const pdfViewer = this.pdfViewer;
  832. pdfViewer.setDocument(pdfDocument);
  833. const {
  834. firstPagePromise,
  835. onePageRendered,
  836. pagesPromise
  837. } = pdfViewer;
  838. const pdfThumbnailViewer = this.pdfThumbnailViewer;
  839. pdfThumbnailViewer.setDocument(pdfDocument);
  840. const storedPromise = (this.store = new _view_history.ViewHistory(pdfDocument.fingerprint)).getMultiple({
  841. page: null,
  842. zoom: _ui_utils.DEFAULT_SCALE_VALUE,
  843. scrollLeft: "0",
  844. scrollTop: "0",
  845. rotation: null,
  846. sidebarView: _ui_utils.SidebarView.UNKNOWN,
  847. scrollMode: _ui_utils.ScrollMode.UNKNOWN,
  848. spreadMode: _ui_utils.SpreadMode.UNKNOWN
  849. }).catch(() => {
  850. return Object.create(null);
  851. });
  852. firstPagePromise.then(pdfPage => {
  853. this.loadingBar.setWidth(this.appConfig.viewerContainer);
  854. this._initializeAnnotationStorageCallbacks(pdfDocument);
  855. Promise.all([_ui_utils.animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise]).then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => {
  856. const viewOnLoad = _app_options.AppOptions.get("viewOnLoad");
  857. this._initializePdfHistory({
  858. fingerprint: pdfDocument.fingerprint,
  859. viewOnLoad,
  860. initialDest: openAction && openAction.dest
  861. });
  862. const initialBookmark = this.initialBookmark;
  863. const zoom = _app_options.AppOptions.get("defaultZoomValue");
  864. let hash = zoom ? `zoom=${zoom}` : null;
  865. let rotation = null;
  866. let sidebarView = _app_options.AppOptions.get("sidebarViewOnLoad");
  867. let scrollMode = _app_options.AppOptions.get("scrollModeOnLoad");
  868. let spreadMode = _app_options.AppOptions.get("spreadModeOnLoad");
  869. if (stored.page && viewOnLoad !== ViewOnLoad.INITIAL) {
  870. hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`;
  871. rotation = parseInt(stored.rotation, 10);
  872. if (sidebarView === _ui_utils.SidebarView.UNKNOWN) {
  873. sidebarView = stored.sidebarView | 0;
  874. }
  875. if (scrollMode === _ui_utils.ScrollMode.UNKNOWN) {
  876. scrollMode = stored.scrollMode | 0;
  877. }
  878. if (spreadMode === _ui_utils.SpreadMode.UNKNOWN) {
  879. spreadMode = stored.spreadMode | 0;
  880. }
  881. }
  882. if (pageMode && sidebarView === _ui_utils.SidebarView.UNKNOWN) {
  883. sidebarView = apiPageModeToSidebarView(pageMode);
  884. }
  885. if (pageLayout && spreadMode === _ui_utils.SpreadMode.UNKNOWN) {
  886. spreadMode = apiPageLayoutToSpreadMode(pageLayout);
  887. }
  888. this.setInitialView(hash, {
  889. rotation,
  890. sidebarView,
  891. scrollMode,
  892. spreadMode
  893. });
  894. this.eventBus.dispatch("documentinit", {
  895. source: this
  896. });
  897. if (!this.isViewerEmbedded) {
  898. pdfViewer.focus();
  899. }
  900. this._initializePermissions(pdfDocument);
  901. await Promise.race([pagesPromise, new Promise(resolve => {
  902. setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT);
  903. })]);
  904. if (!initialBookmark && !hash) {
  905. return;
  906. }
  907. if (pdfViewer.hasEqualPageSizes) {
  908. return;
  909. }
  910. this.initialBookmark = initialBookmark;
  911. pdfViewer.currentScaleValue = pdfViewer.currentScaleValue;
  912. this.setInitialView(hash);
  913. }).catch(() => {
  914. this.setInitialView();
  915. }).then(function () {
  916. pdfViewer.update();
  917. });
  918. });
  919. pagesPromise.then(() => {
  920. this._initializeAutoPrint(pdfDocument, openActionPromise);
  921. });
  922. onePageRendered.then(() => {
  923. pdfDocument.getOutline().then(outline => {
  924. this.pdfOutlineViewer.render({
  925. outline,
  926. pdfDocument
  927. });
  928. });
  929. pdfDocument.getAttachments().then(attachments => {
  930. this.pdfAttachmentViewer.render({
  931. attachments
  932. });
  933. });
  934. pdfViewer.optionalContentConfigPromise.then(optionalContentConfig => {
  935. this.pdfLayerViewer.render({
  936. optionalContentConfig,
  937. pdfDocument
  938. });
  939. });
  940. if ("requestIdleCallback" in window) {
  941. const callback = window.requestIdleCallback(() => {
  942. this._collectTelemetry(pdfDocument);
  943. this._idleCallbacks.delete(callback);
  944. }, {
  945. timeout: 1000
  946. });
  947. this._idleCallbacks.add(callback);
  948. }
  949. this._initializeJavaScript(pdfDocument);
  950. });
  951. this._initializePageLabels(pdfDocument);
  952. this._initializeMetadata(pdfDocument);
  953. },
  954. async _initializeJavaScript(pdfDocument) {
  955. if (!_app_options.AppOptions.get("enableScripting")) {
  956. return;
  957. }
  958. const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]);
  959. if (!objects && !docActions) {
  960. return;
  961. }
  962. if (pdfDocument !== this.pdfDocument) {
  963. return;
  964. }
  965. const scripting = this.externalServices.createScripting({
  966. sandboxBundleSrc: _app_options.AppOptions.get("sandboxBundleSrc")
  967. });
  968. const internalEvents = new Map(),
  969. domEvents = new Map();
  970. this._scriptingInstance = {
  971. scripting,
  972. ready: false,
  973. internalEvents,
  974. domEvents
  975. };
  976. if (!this.documentInfo) {
  977. await new Promise(resolve => {
  978. this.eventBus._on("metadataloaded", evt => {
  979. resolve();
  980. }, {
  981. once: true
  982. });
  983. });
  984. if (pdfDocument !== this.pdfDocument) {
  985. return;
  986. }
  987. }
  988. if (!this._contentLength) {
  989. await new Promise(resolve => {
  990. this.eventBus._on("documentloaded", evt => {
  991. resolve();
  992. }, {
  993. once: true
  994. });
  995. });
  996. if (pdfDocument !== this.pdfDocument) {
  997. return;
  998. }
  999. }
  1000. const updateFromSandbox = ({
  1001. detail
  1002. }) => {
  1003. const {
  1004. id,
  1005. command,
  1006. value
  1007. } = detail;
  1008. if (!id) {
  1009. switch (command) {
  1010. case "clear":
  1011. console.clear();
  1012. break;
  1013. case "error":
  1014. console.error(value);
  1015. break;
  1016. case "layout":
  1017. this.pdfViewer.spreadMode = apiPageLayoutToSpreadMode(value);
  1018. break;
  1019. case "page-num":
  1020. this.pdfViewer.currentPageNumber = value + 1;
  1021. break;
  1022. case "print":
  1023. this.pdfViewer.pagesPromise.then(() => {
  1024. this.triggerPrinting();
  1025. });
  1026. break;
  1027. case "println":
  1028. console.log(value);
  1029. break;
  1030. case "zoom":
  1031. this.pdfViewer.currentScaleValue = value;
  1032. break;
  1033. }
  1034. return;
  1035. }
  1036. const element = document.getElementById(id);
  1037. if (element) {
  1038. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  1039. detail
  1040. }));
  1041. } else {
  1042. if (value !== undefined && value !== null) {
  1043. pdfDocument.annotationStorage.setValue(id, value);
  1044. }
  1045. }
  1046. };
  1047. internalEvents.set("updatefromsandbox", updateFromSandbox);
  1048. const visitedPages = new Map();
  1049. const pageOpen = ({
  1050. pageNumber,
  1051. actionsPromise
  1052. }) => {
  1053. visitedPages.set(pageNumber, (async () => {
  1054. let actions = null;
  1055. if (!visitedPages.has(pageNumber)) {
  1056. actions = await actionsPromise;
  1057. if (pdfDocument !== this.pdfDocument) {
  1058. return;
  1059. }
  1060. }
  1061. await this._scriptingInstance?.scripting.dispatchEventInSandbox({
  1062. id: "page",
  1063. name: "PageOpen",
  1064. pageNumber,
  1065. actions
  1066. });
  1067. })());
  1068. };
  1069. const pageClose = async ({
  1070. pageNumber
  1071. }) => {
  1072. const actionsPromise = visitedPages.get(pageNumber);
  1073. if (!actionsPromise) {
  1074. return;
  1075. }
  1076. visitedPages.set(pageNumber, null);
  1077. await actionsPromise;
  1078. if (pdfDocument !== this.pdfDocument) {
  1079. return;
  1080. }
  1081. await this._scriptingInstance?.scripting.dispatchEventInSandbox({
  1082. id: "page",
  1083. name: "PageClose",
  1084. pageNumber
  1085. });
  1086. };
  1087. internalEvents.set("pageopen", pageOpen);
  1088. internalEvents.set("pageclose", pageClose);
  1089. const dispatchEventInSandbox = ({
  1090. detail
  1091. }) => {
  1092. scripting.dispatchEventInSandbox(detail);
  1093. };
  1094. internalEvents.set("dispatcheventinsandbox", dispatchEventInSandbox);
  1095. const mouseDown = event => {
  1096. this._mouseState.isDown = true;
  1097. };
  1098. domEvents.set("mousedown", mouseDown);
  1099. const mouseUp = event => {
  1100. this._mouseState.isDown = false;
  1101. };
  1102. domEvents.set("mouseup", mouseUp);
  1103. for (const [name, listener] of internalEvents) {
  1104. this.eventBus._on(name, listener);
  1105. }
  1106. for (const [name, listener] of domEvents) {
  1107. window.addEventListener(name, listener);
  1108. }
  1109. try {
  1110. await scripting.createSandbox({
  1111. objects,
  1112. calculationOrder,
  1113. appInfo: {
  1114. platform: navigator.platform,
  1115. language: navigator.language
  1116. },
  1117. docInfo: { ...this.documentInfo,
  1118. baseURL: this.baseUrl,
  1119. filesize: this._contentLength,
  1120. filename: this._docFilename,
  1121. metadata: this.metadata?.getRaw(),
  1122. authors: this.metadata?.get("dc:creator"),
  1123. numPages: pdfDocument.numPages,
  1124. URL: this.url,
  1125. actions: docActions
  1126. }
  1127. });
  1128. if (this.externalServices.isInAutomation) {
  1129. this.eventBus.dispatch("sandboxcreated", {
  1130. source: this
  1131. });
  1132. }
  1133. } catch (error) {
  1134. console.error(`_initializeJavaScript: "${error?.message}".`);
  1135. this._destroyScriptingInstance();
  1136. return;
  1137. }
  1138. await scripting.dispatchEventInSandbox({
  1139. id: "doc",
  1140. name: "Open"
  1141. });
  1142. await this.pdfViewer.initializeScriptingEvents();
  1143. Promise.resolve().then(() => {
  1144. if (this._scriptingInstance) {
  1145. this._scriptingInstance.ready = true;
  1146. }
  1147. });
  1148. },
  1149. async _collectTelemetry(pdfDocument) {
  1150. const markInfo = await this.pdfDocument.getMarkInfo();
  1151. if (pdfDocument !== this.pdfDocument) {
  1152. return;
  1153. }
  1154. const tagged = markInfo?.Marked || false;
  1155. this.externalServices.reportTelemetry({
  1156. type: "tagged",
  1157. tagged
  1158. });
  1159. },
  1160. async _initializeAutoPrint(pdfDocument, openActionPromise) {
  1161. const [openAction, javaScript] = await Promise.all([openActionPromise, !_app_options.AppOptions.get("enableScripting") ? pdfDocument.getJavaScript() : null]);
  1162. if (pdfDocument !== this.pdfDocument) {
  1163. return;
  1164. }
  1165. let triggerAutoPrint = false;
  1166. if (openAction?.action === "Print") {
  1167. triggerAutoPrint = true;
  1168. }
  1169. if (javaScript) {
  1170. javaScript.some(js => {
  1171. if (!js) {
  1172. return false;
  1173. }
  1174. console.warn("Warning: JavaScript is not supported");
  1175. this._delayedFallback(_pdf.UNSUPPORTED_FEATURES.javaScript);
  1176. return true;
  1177. });
  1178. if (!triggerAutoPrint) {
  1179. for (const js of javaScript) {
  1180. if (js && _ui_utils.AutoPrintRegExp.test(js)) {
  1181. triggerAutoPrint = true;
  1182. break;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. if (triggerAutoPrint) {
  1188. this.triggerPrinting();
  1189. }
  1190. },
  1191. async _initializeMetadata(pdfDocument) {
  1192. const {
  1193. info,
  1194. metadata,
  1195. contentDispositionFilename,
  1196. contentLength
  1197. } = await pdfDocument.getMetadata();
  1198. if (pdfDocument !== this.pdfDocument) {
  1199. return;
  1200. }
  1201. this.documentInfo = info;
  1202. this.metadata = metadata;
  1203. this._contentDispositionFilename = contentDispositionFilename;
  1204. this._contentLength ?? (this._contentLength = contentLength);
  1205. console.log(`PDF ${pdfDocument.fingerprint} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${_pdf.version || "-"}` + `${this.pdfViewer.enableWebGL ? " [WebGL]" : ""})`);
  1206. let pdfTitle;
  1207. const infoTitle = info && info.Title;
  1208. if (infoTitle) {
  1209. pdfTitle = infoTitle;
  1210. }
  1211. const metadataTitle = metadata && metadata.get("dc:title");
  1212. if (metadataTitle) {
  1213. if (metadataTitle !== "Untitled" && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) {
  1214. pdfTitle = metadataTitle;
  1215. }
  1216. }
  1217. if (pdfTitle) {
  1218. this.setTitle(`${pdfTitle} - ${contentDispositionFilename || document.title}`);
  1219. } else if (contentDispositionFilename) {
  1220. this.setTitle(contentDispositionFilename);
  1221. }
  1222. if (info.IsXFAPresent && !info.IsAcroFormPresent) {
  1223. console.warn("Warning: XFA is not supported");
  1224. this._delayedFallback(_pdf.UNSUPPORTED_FEATURES.forms);
  1225. } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderInteractiveForms) {
  1226. console.warn("Warning: Interactive form support is not enabled");
  1227. this._delayedFallback(_pdf.UNSUPPORTED_FEATURES.forms);
  1228. }
  1229. let versionId = "other";
  1230. if (KNOWN_VERSIONS.includes(info.PDFFormatVersion)) {
  1231. versionId = `v${info.PDFFormatVersion.replace(".", "_")}`;
  1232. }
  1233. let generatorId = "other";
  1234. if (info.Producer) {
  1235. const producer = info.Producer.toLowerCase();
  1236. KNOWN_GENERATORS.some(function (generator) {
  1237. if (!producer.includes(generator)) {
  1238. return false;
  1239. }
  1240. generatorId = generator.replace(/[ .-]/g, "_");
  1241. return true;
  1242. });
  1243. }
  1244. let formType = null;
  1245. if (info.IsXFAPresent) {
  1246. formType = "xfa";
  1247. } else if (info.IsAcroFormPresent) {
  1248. formType = "acroform";
  1249. }
  1250. this.externalServices.reportTelemetry({
  1251. type: "documentInfo",
  1252. version: versionId,
  1253. generator: generatorId,
  1254. formType
  1255. });
  1256. this.eventBus.dispatch("metadataloaded", {
  1257. source: this
  1258. });
  1259. },
  1260. async _initializePageLabels(pdfDocument) {
  1261. const labels = await pdfDocument.getPageLabels();
  1262. if (pdfDocument !== this.pdfDocument) {
  1263. return;
  1264. }
  1265. if (!labels || _app_options.AppOptions.get("disablePageLabels")) {
  1266. return;
  1267. }
  1268. const numLabels = labels.length;
  1269. if (numLabels !== this.pagesCount) {
  1270. console.error("The number of Page Labels does not match the number of pages in the document.");
  1271. return;
  1272. }
  1273. let i = 0;
  1274. while (i < numLabels && labels[i] === (i + 1).toString()) {
  1275. i++;
  1276. }
  1277. if (i === numLabels) {
  1278. return;
  1279. }
  1280. const {
  1281. pdfViewer,
  1282. pdfThumbnailViewer,
  1283. toolbar
  1284. } = this;
  1285. pdfViewer.setPageLabels(labels);
  1286. pdfThumbnailViewer.setPageLabels(labels);
  1287. toolbar.setPagesCount(numLabels, true);
  1288. toolbar.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  1289. },
  1290. _initializePdfHistory({
  1291. fingerprint,
  1292. viewOnLoad,
  1293. initialDest = null
  1294. }) {
  1295. if (this.isViewerEmbedded || _app_options.AppOptions.get("disableHistory")) {
  1296. return;
  1297. }
  1298. this.pdfHistory.initialize({
  1299. fingerprint,
  1300. resetHistory: viewOnLoad === ViewOnLoad.INITIAL,
  1301. updateUrl: _app_options.AppOptions.get("historyUpdateUrl")
  1302. });
  1303. if (this.pdfHistory.initialBookmark) {
  1304. this.initialBookmark = this.pdfHistory.initialBookmark;
  1305. this.initialRotation = this.pdfHistory.initialRotation;
  1306. }
  1307. if (initialDest && !this.initialBookmark && viewOnLoad === ViewOnLoad.UNKNOWN) {
  1308. this.initialBookmark = JSON.stringify(initialDest);
  1309. this.pdfHistory.push({
  1310. explicitDest: initialDest,
  1311. pageNumber: null
  1312. });
  1313. }
  1314. },
  1315. async _initializePermissions(pdfDocument) {
  1316. const permissions = await pdfDocument.getPermissions();
  1317. if (pdfDocument !== this.pdfDocument) {
  1318. return;
  1319. }
  1320. if (!permissions || !_app_options.AppOptions.get("enablePermissions")) {
  1321. return;
  1322. }
  1323. if (!permissions.includes(_pdf.PermissionFlag.COPY)) {
  1324. this.appConfig.viewerContainer.classList.add(ENABLE_PERMISSIONS_CLASS);
  1325. }
  1326. },
  1327. _initializeAnnotationStorageCallbacks(pdfDocument) {
  1328. if (pdfDocument !== this.pdfDocument) {
  1329. return;
  1330. }
  1331. const {
  1332. annotationStorage
  1333. } = pdfDocument;
  1334. annotationStorage.onSetModified = function () {
  1335. window.addEventListener("beforeunload", beforeUnload);
  1336. };
  1337. annotationStorage.onResetModified = function () {
  1338. window.removeEventListener("beforeunload", beforeUnload);
  1339. };
  1340. },
  1341. setInitialView(storedHash, {
  1342. rotation,
  1343. sidebarView,
  1344. scrollMode,
  1345. spreadMode
  1346. } = {}) {
  1347. const setRotation = angle => {
  1348. if ((0, _ui_utils.isValidRotation)(angle)) {
  1349. this.pdfViewer.pagesRotation = angle;
  1350. }
  1351. };
  1352. const setViewerModes = (scroll, spread) => {
  1353. if ((0, _ui_utils.isValidScrollMode)(scroll)) {
  1354. this.pdfViewer.scrollMode = scroll;
  1355. }
  1356. if ((0, _ui_utils.isValidSpreadMode)(spread)) {
  1357. this.pdfViewer.spreadMode = spread;
  1358. }
  1359. };
  1360. this.isInitialViewSet = true;
  1361. this.pdfSidebar.setInitialView(sidebarView);
  1362. setViewerModes(scrollMode, spreadMode);
  1363. if (this.initialBookmark) {
  1364. setRotation(this.initialRotation);
  1365. delete this.initialRotation;
  1366. this.pdfLinkService.setHash(this.initialBookmark);
  1367. this.initialBookmark = null;
  1368. } else if (storedHash) {
  1369. setRotation(rotation);
  1370. this.pdfLinkService.setHash(storedHash);
  1371. }
  1372. this.toolbar.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel);
  1373. this.secondaryToolbar.setPageNumber(this.pdfViewer.currentPageNumber);
  1374. if (!this.pdfViewer.currentScaleValue) {
  1375. this.pdfViewer.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  1376. }
  1377. },
  1378. cleanup() {
  1379. if (!this.pdfDocument) {
  1380. return;
  1381. }
  1382. this.pdfViewer.cleanup();
  1383. this.pdfThumbnailViewer.cleanup();
  1384. if (this.pdfViewer.renderer !== _ui_utils.RendererType.SVG) {
  1385. this.pdfDocument.cleanup();
  1386. }
  1387. },
  1388. forceRendering() {
  1389. this.pdfRenderingQueue.printing = !!this.printService;
  1390. this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar.isThumbnailViewVisible;
  1391. this.pdfRenderingQueue.renderHighestPriority();
  1392. },
  1393. beforePrint() {
  1394. this._scriptingInstance?.scripting.dispatchEventInSandbox({
  1395. id: "doc",
  1396. name: "WillPrint"
  1397. });
  1398. if (this.printService) {
  1399. return;
  1400. }
  1401. if (!this.supportsPrinting) {
  1402. this.l10n.get("printing_not_supported", null, "Warning: Printing is not fully supported by this browser.").then(printMessage => {
  1403. this.error(printMessage);
  1404. });
  1405. return;
  1406. }
  1407. if (!this.pdfViewer.pageViewsReady) {
  1408. this.l10n.get("printing_not_ready", null, "Warning: The PDF is not fully loaded for printing.").then(notReadyMessage => {
  1409. window.alert(notReadyMessage);
  1410. });
  1411. return;
  1412. }
  1413. const pagesOverview = this.pdfViewer.getPagesOverview();
  1414. const printContainer = this.appConfig.printContainer;
  1415. const printResolution = _app_options.AppOptions.get("printResolution");
  1416. const optionalContentConfigPromise = this.pdfViewer.optionalContentConfigPromise;
  1417. const printService = PDFPrintServiceFactory.instance.createPrintService(this.pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, this.l10n);
  1418. this.printService = printService;
  1419. this.forceRendering();
  1420. printService.layout();
  1421. this.externalServices.reportTelemetry({
  1422. type: "print"
  1423. });
  1424. },
  1425. afterPrint() {
  1426. this._scriptingInstance?.scripting.dispatchEventInSandbox({
  1427. id: "doc",
  1428. name: "DidPrint"
  1429. });
  1430. if (this.printService) {
  1431. this.printService.destroy();
  1432. this.printService = null;
  1433. if (this.pdfDocument) {
  1434. this.pdfDocument.annotationStorage.resetModified();
  1435. }
  1436. }
  1437. this.forceRendering();
  1438. },
  1439. rotatePages(delta) {
  1440. if (!this.pdfDocument) {
  1441. return;
  1442. }
  1443. const newRotation = (this.pdfViewer.pagesRotation + 360 + delta) % 360;
  1444. this.pdfViewer.pagesRotation = newRotation;
  1445. },
  1446. requestPresentationMode() {
  1447. if (!this.pdfPresentationMode) {
  1448. return;
  1449. }
  1450. this.pdfPresentationMode.request();
  1451. },
  1452. triggerPrinting() {
  1453. if (!this.supportsPrinting) {
  1454. return;
  1455. }
  1456. window.print();
  1457. },
  1458. bindEvents() {
  1459. const {
  1460. eventBus,
  1461. _boundEvents
  1462. } = this;
  1463. _boundEvents.beforePrint = this.beforePrint.bind(this);
  1464. _boundEvents.afterPrint = this.afterPrint.bind(this);
  1465. eventBus._on("resize", webViewerResize);
  1466. eventBus._on("hashchange", webViewerHashchange);
  1467. eventBus._on("beforeprint", _boundEvents.beforePrint);
  1468. eventBus._on("afterprint", _boundEvents.afterPrint);
  1469. eventBus._on("pagerendered", webViewerPageRendered);
  1470. eventBus._on("updateviewarea", webViewerUpdateViewarea);
  1471. eventBus._on("pagechanging", webViewerPageChanging);
  1472. eventBus._on("scalechanging", webViewerScaleChanging);
  1473. eventBus._on("rotationchanging", webViewerRotationChanging);
  1474. eventBus._on("sidebarviewchanged", webViewerSidebarViewChanged);
  1475. eventBus._on("pagemode", webViewerPageMode);
  1476. eventBus._on("namedaction", webViewerNamedAction);
  1477. eventBus._on("presentationmodechanged", webViewerPresentationModeChanged);
  1478. eventBus._on("presentationmode", webViewerPresentationMode);
  1479. eventBus._on("print", webViewerPrint);
  1480. eventBus._on("download", webViewerDownload);
  1481. eventBus._on("save", webViewerSave);
  1482. eventBus._on("firstpage", webViewerFirstPage);
  1483. eventBus._on("lastpage", webViewerLastPage);
  1484. eventBus._on("nextpage", webViewerNextPage);
  1485. eventBus._on("previouspage", webViewerPreviousPage);
  1486. eventBus._on("zoomin", webViewerZoomIn);
  1487. eventBus._on("zoomout", webViewerZoomOut);
  1488. eventBus._on("zoomreset", webViewerZoomReset);
  1489. eventBus._on("pagenumberchanged", webViewerPageNumberChanged);
  1490. eventBus._on("scalechanged", webViewerScaleChanged);
  1491. eventBus._on("rotatecw", webViewerRotateCw);
  1492. eventBus._on("rotateccw", webViewerRotateCcw);
  1493. eventBus._on("optionalcontentconfig", webViewerOptionalContentConfig);
  1494. eventBus._on("switchscrollmode", webViewerSwitchScrollMode);
  1495. eventBus._on("scrollmodechanged", webViewerScrollModeChanged);
  1496. eventBus._on("switchspreadmode", webViewerSwitchSpreadMode);
  1497. eventBus._on("spreadmodechanged", webViewerSpreadModeChanged);
  1498. eventBus._on("documentproperties", webViewerDocumentProperties);
  1499. eventBus._on("find", webViewerFind);
  1500. eventBus._on("findfromurlhash", webViewerFindFromUrlHash);
  1501. eventBus._on("updatefindmatchescount", webViewerUpdateFindMatchesCount);
  1502. eventBus._on("updatefindcontrolstate", webViewerUpdateFindControlState);
  1503. if (_app_options.AppOptions.get("pdfBug")) {
  1504. _boundEvents.reportPageStatsPDFBug = reportPageStatsPDFBug;
  1505. eventBus._on("pagerendered", _boundEvents.reportPageStatsPDFBug);
  1506. eventBus._on("pagechanging", _boundEvents.reportPageStatsPDFBug);
  1507. }
  1508. eventBus._on("fileinputchange", webViewerFileInputChange);
  1509. eventBus._on("openfile", webViewerOpenFile);
  1510. },
  1511. bindWindowEvents() {
  1512. const {
  1513. eventBus,
  1514. _boundEvents
  1515. } = this;
  1516. _boundEvents.windowResize = () => {
  1517. eventBus.dispatch("resize", {
  1518. source: window
  1519. });
  1520. };
  1521. _boundEvents.windowHashChange = () => {
  1522. eventBus.dispatch("hashchange", {
  1523. source: window,
  1524. hash: document.location.hash.substring(1)
  1525. });
  1526. };
  1527. _boundEvents.windowBeforePrint = () => {
  1528. eventBus.dispatch("beforeprint", {
  1529. source: window
  1530. });
  1531. };
  1532. _boundEvents.windowAfterPrint = () => {
  1533. eventBus.dispatch("afterprint", {
  1534. source: window
  1535. });
  1536. };
  1537. _boundEvents.windowUpdateFromSandbox = event => {
  1538. eventBus.dispatch("updatefromsandbox", {
  1539. source: window,
  1540. detail: event.detail
  1541. });
  1542. };
  1543. window.addEventListener("visibilitychange", webViewerVisibilityChange);
  1544. window.addEventListener("wheel", webViewerWheel, {
  1545. passive: false
  1546. });
  1547. window.addEventListener("touchstart", webViewerTouchStart, {
  1548. passive: false
  1549. });
  1550. window.addEventListener("click", webViewerClick);
  1551. window.addEventListener("keydown", webViewerKeyDown);
  1552. window.addEventListener("keyup", webViewerKeyUp);
  1553. window.addEventListener("resize", _boundEvents.windowResize);
  1554. window.addEventListener("hashchange", _boundEvents.windowHashChange);
  1555. window.addEventListener("beforeprint", _boundEvents.windowBeforePrint);
  1556. window.addEventListener("afterprint", _boundEvents.windowAfterPrint);
  1557. window.addEventListener("updatefromsandbox", _boundEvents.windowUpdateFromSandbox);
  1558. },
  1559. unbindEvents() {
  1560. const {
  1561. eventBus,
  1562. _boundEvents
  1563. } = this;
  1564. eventBus._off("resize", webViewerResize);
  1565. eventBus._off("hashchange", webViewerHashchange);
  1566. eventBus._off("beforeprint", _boundEvents.beforePrint);
  1567. eventBus._off("afterprint", _boundEvents.afterPrint);
  1568. eventBus._off("pagerendered", webViewerPageRendered);
  1569. eventBus._off("updateviewarea", webViewerUpdateViewarea);
  1570. eventBus._off("pagechanging", webViewerPageChanging);
  1571. eventBus._off("scalechanging", webViewerScaleChanging);
  1572. eventBus._off("rotationchanging", webViewerRotationChanging);
  1573. eventBus._off("sidebarviewchanged", webViewerSidebarViewChanged);
  1574. eventBus._off("pagemode", webViewerPageMode);
  1575. eventBus._off("namedaction", webViewerNamedAction);
  1576. eventBus._off("presentationmodechanged", webViewerPresentationModeChanged);
  1577. eventBus._off("presentationmode", webViewerPresentationMode);
  1578. eventBus._off("print", webViewerPrint);
  1579. eventBus._off("download", webViewerDownload);
  1580. eventBus._off("save", webViewerSave);
  1581. eventBus._off("firstpage", webViewerFirstPage);
  1582. eventBus._off("lastpage", webViewerLastPage);
  1583. eventBus._off("nextpage", webViewerNextPage);
  1584. eventBus._off("previouspage", webViewerPreviousPage);
  1585. eventBus._off("zoomin", webViewerZoomIn);
  1586. eventBus._off("zoomout", webViewerZoomOut);
  1587. eventBus._off("zoomreset", webViewerZoomReset);
  1588. eventBus._off("pagenumberchanged", webViewerPageNumberChanged);
  1589. eventBus._off("scalechanged", webViewerScaleChanged);
  1590. eventBus._off("rotatecw", webViewerRotateCw);
  1591. eventBus._off("rotateccw", webViewerRotateCcw);
  1592. eventBus._off("optionalcontentconfig", webViewerOptionalContentConfig);
  1593. eventBus._off("switchscrollmode", webViewerSwitchScrollMode);
  1594. eventBus._off("scrollmodechanged", webViewerScrollModeChanged);
  1595. eventBus._off("switchspreadmode", webViewerSwitchSpreadMode);
  1596. eventBus._off("spreadmodechanged", webViewerSpreadModeChanged);
  1597. eventBus._off("documentproperties", webViewerDocumentProperties);
  1598. eventBus._off("find", webViewerFind);
  1599. eventBus._off("findfromurlhash", webViewerFindFromUrlHash);
  1600. eventBus._off("updatefindmatchescount", webViewerUpdateFindMatchesCount);
  1601. eventBus._off("updatefindcontrolstate", webViewerUpdateFindControlState);
  1602. if (_boundEvents.reportPageStatsPDFBug) {
  1603. eventBus._off("pagerendered", _boundEvents.reportPageStatsPDFBug);
  1604. eventBus._off("pagechanging", _boundEvents.reportPageStatsPDFBug);
  1605. _boundEvents.reportPageStatsPDFBug = null;
  1606. }
  1607. eventBus._off("fileinputchange", webViewerFileInputChange);
  1608. eventBus._off("openfile", webViewerOpenFile);
  1609. _boundEvents.beforePrint = null;
  1610. _boundEvents.afterPrint = null;
  1611. },
  1612. unbindWindowEvents() {
  1613. const {
  1614. _boundEvents
  1615. } = this;
  1616. window.removeEventListener("visibilitychange", webViewerVisibilityChange);
  1617. window.removeEventListener("wheel", webViewerWheel, {
  1618. passive: false
  1619. });
  1620. window.removeEventListener("touchstart", webViewerTouchStart, {
  1621. passive: false
  1622. });
  1623. window.removeEventListener("click", webViewerClick);
  1624. window.removeEventListener("keydown", webViewerKeyDown);
  1625. window.removeEventListener("keyup", webViewerKeyUp);
  1626. window.removeEventListener("resize", _boundEvents.windowResize);
  1627. window.removeEventListener("hashchange", _boundEvents.windowHashChange);
  1628. window.removeEventListener("beforeprint", _boundEvents.windowBeforePrint);
  1629. window.removeEventListener("afterprint", _boundEvents.windowAfterPrint);
  1630. window.removeEventListener("updatefromsandbox", _boundEvents.windowUpdateFromSandbox);
  1631. _boundEvents.windowResize = null;
  1632. _boundEvents.windowHashChange = null;
  1633. _boundEvents.windowBeforePrint = null;
  1634. _boundEvents.windowAfterPrint = null;
  1635. _boundEvents.windowUpdateFromSandbox = null;
  1636. },
  1637. accumulateWheelTicks(ticks) {
  1638. if (this._wheelUnusedTicks > 0 && ticks < 0 || this._wheelUnusedTicks < 0 && ticks > 0) {
  1639. this._wheelUnusedTicks = 0;
  1640. }
  1641. this._wheelUnusedTicks += ticks;
  1642. const wholeTicks = Math.sign(this._wheelUnusedTicks) * Math.floor(Math.abs(this._wheelUnusedTicks));
  1643. this._wheelUnusedTicks -= wholeTicks;
  1644. return wholeTicks;
  1645. },
  1646. get scriptingReady() {
  1647. return this._scriptingInstance?.ready || false;
  1648. }
  1649. };
  1650. exports.PDFViewerApplication = PDFViewerApplication;
  1651. let validateFileURL;
  1652. {
  1653. const HOSTED_VIEWER_ORIGINS = ["null", "http://mozilla.github.io", "https://mozilla.github.io"];
  1654. validateFileURL = function (file) {
  1655. if (file === undefined) {
  1656. return;
  1657. }
  1658. try {
  1659. const viewerOrigin = new URL(window.location.href).origin || "null";
  1660. if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) {
  1661. return;
  1662. }
  1663. const {
  1664. origin,
  1665. protocol
  1666. } = new URL(file, window.location.href);
  1667. if (origin !== viewerOrigin && protocol !== "blob:") {
  1668. throw new Error("file origin does not match viewer's");
  1669. }
  1670. } catch (ex) {
  1671. const message = ex && ex.message;
  1672. PDFViewerApplication.l10n.get("loading_error", null, "An error occurred while loading the PDF.").then(loadingErrorMessage => {
  1673. PDFViewerApplication.error(loadingErrorMessage, {
  1674. message
  1675. });
  1676. });
  1677. throw ex;
  1678. }
  1679. };
  1680. }
  1681. async function loadFakeWorker() {
  1682. if (!_pdf.GlobalWorkerOptions.workerSrc) {
  1683. _pdf.GlobalWorkerOptions.workerSrc = _app_options.AppOptions.get("workerSrc");
  1684. }
  1685. return (0, _pdf.loadScript)(_pdf.PDFWorker.getWorkerSrc());
  1686. }
  1687. function loadAndEnablePDFBug(enabledTabs) {
  1688. const appConfig = PDFViewerApplication.appConfig;
  1689. return (0, _pdf.loadScript)(appConfig.debuggerScriptPath).then(function () {
  1690. PDFBug.enable(enabledTabs);
  1691. PDFBug.init({
  1692. OPS: _pdf.OPS
  1693. }, appConfig.mainContainer);
  1694. });
  1695. }
  1696. function reportPageStatsPDFBug({
  1697. pageNumber
  1698. }) {
  1699. if (typeof Stats === "undefined" || !Stats.enabled) {
  1700. return;
  1701. }
  1702. const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  1703. const pageStats = pageView && pageView.pdfPage && pageView.pdfPage.stats;
  1704. if (!pageStats) {
  1705. return;
  1706. }
  1707. Stats.add(pageNumber, pageStats);
  1708. }
  1709. function webViewerInitialized() {
  1710. const appConfig = PDFViewerApplication.appConfig;
  1711. let file;
  1712. const queryString = document.location.search.substring(1);
  1713. const params = (0, _ui_utils.parseQueryString)(queryString);
  1714. file = "file" in params ? params.file : _app_options.AppOptions.get("defaultUrl");
  1715. validateFileURL(file);
  1716. const fileInput = document.createElement("input");
  1717. fileInput.id = appConfig.openFileInputName;
  1718. fileInput.className = "fileInput";
  1719. fileInput.setAttribute("type", "file");
  1720. fileInput.oncontextmenu = _ui_utils.noContextMenuHandler;
  1721. document.body.appendChild(fileInput);
  1722. if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
  1723. appConfig.toolbar.openFile.setAttribute("hidden", "true");
  1724. appConfig.secondaryToolbar.openFileButton.setAttribute("hidden", "true");
  1725. } else {
  1726. fileInput.value = null;
  1727. }
  1728. fileInput.addEventListener("change", function (evt) {
  1729. const files = evt.target.files;
  1730. if (!files || files.length === 0) {
  1731. return;
  1732. }
  1733. PDFViewerApplication.eventBus.dispatch("fileinputchange", {
  1734. source: this,
  1735. fileInput: evt.target
  1736. });
  1737. });
  1738. appConfig.mainContainer.addEventListener("dragover", function (evt) {
  1739. evt.preventDefault();
  1740. evt.dataTransfer.dropEffect = "move";
  1741. });
  1742. appConfig.mainContainer.addEventListener("drop", function (evt) {
  1743. evt.preventDefault();
  1744. const files = evt.dataTransfer.files;
  1745. if (!files || files.length === 0) {
  1746. return;
  1747. }
  1748. PDFViewerApplication.eventBus.dispatch("fileinputchange", {
  1749. source: this,
  1750. fileInput: evt.dataTransfer
  1751. });
  1752. });
  1753. if (!PDFViewerApplication.supportsDocumentFonts) {
  1754. _app_options.AppOptions.set("disableFontFace", true);
  1755. PDFViewerApplication.l10n.get("web_fonts_disabled", null, "Web fonts are disabled: unable to use embedded PDF fonts.").then(msg => {
  1756. console.warn(msg);
  1757. });
  1758. }
  1759. if (!PDFViewerApplication.supportsPrinting) {
  1760. appConfig.toolbar.print.classList.add("hidden");
  1761. appConfig.secondaryToolbar.printButton.classList.add("hidden");
  1762. }
  1763. if (!PDFViewerApplication.supportsFullscreen) {
  1764. appConfig.toolbar.presentationModeButton.classList.add("hidden");
  1765. appConfig.secondaryToolbar.presentationModeButton.classList.add("hidden");
  1766. }
  1767. if (PDFViewerApplication.supportsIntegratedFind) {
  1768. appConfig.toolbar.viewFind.classList.add("hidden");
  1769. }
  1770. appConfig.mainContainer.addEventListener("transitionend", function (evt) {
  1771. if (evt.target === this) {
  1772. PDFViewerApplication.eventBus.dispatch("resize", {
  1773. source: this
  1774. });
  1775. }
  1776. }, true);
  1777. try {
  1778. webViewerOpenFileViaURL(file);
  1779. } catch (reason) {
  1780. PDFViewerApplication.l10n.get("loading_error", null, "An error occurred while loading the PDF.").then(msg => {
  1781. PDFViewerApplication.error(msg, reason);
  1782. });
  1783. }
  1784. }
  1785. let webViewerOpenFileViaURL;
  1786. {
  1787. webViewerOpenFileViaURL = function (file) {
  1788. if (file && file.lastIndexOf("file:", 0) === 0) {
  1789. PDFViewerApplication.setTitleUsingUrl(file);
  1790. const xhr = new XMLHttpRequest();
  1791. xhr.onload = function () {
  1792. PDFViewerApplication.open(new Uint8Array(xhr.response));
  1793. };
  1794. xhr.open("GET", file);
  1795. xhr.responseType = "arraybuffer";
  1796. xhr.send();
  1797. return;
  1798. }
  1799. if (file) {
  1800. PDFViewerApplication.open(file);
  1801. }
  1802. };
  1803. }
  1804. function webViewerResetPermissions() {
  1805. const {
  1806. appConfig
  1807. } = PDFViewerApplication;
  1808. if (!appConfig) {
  1809. return;
  1810. }
  1811. appConfig.viewerContainer.classList.remove(ENABLE_PERMISSIONS_CLASS);
  1812. }
  1813. function webViewerPageRendered({
  1814. pageNumber,
  1815. timestamp,
  1816. error
  1817. }) {
  1818. if (pageNumber === PDFViewerApplication.page) {
  1819. PDFViewerApplication.toolbar.updateLoadingIndicatorState(false);
  1820. }
  1821. if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) {
  1822. const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1);
  1823. const thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(pageNumber - 1);
  1824. if (pageView && thumbnailView) {
  1825. thumbnailView.setImage(pageView);
  1826. }
  1827. }
  1828. if (error) {
  1829. PDFViewerApplication.l10n.get("rendering_error", null, "An error occurred while rendering the page.").then(msg => {
  1830. PDFViewerApplication.error(msg, error);
  1831. });
  1832. }
  1833. PDFViewerApplication.externalServices.reportTelemetry({
  1834. type: "pageInfo",
  1835. timestamp
  1836. });
  1837. PDFViewerApplication.pdfDocument.getStats().then(function (stats) {
  1838. PDFViewerApplication.externalServices.reportTelemetry({
  1839. type: "documentStats",
  1840. stats
  1841. });
  1842. });
  1843. }
  1844. function webViewerPageMode({
  1845. mode
  1846. }) {
  1847. let view;
  1848. switch (mode) {
  1849. case "thumbs":
  1850. view = _ui_utils.SidebarView.THUMBS;
  1851. break;
  1852. case "bookmarks":
  1853. case "outline":
  1854. view = _ui_utils.SidebarView.OUTLINE;
  1855. break;
  1856. case "attachments":
  1857. view = _ui_utils.SidebarView.ATTACHMENTS;
  1858. break;
  1859. case "layers":
  1860. view = _ui_utils.SidebarView.LAYERS;
  1861. break;
  1862. case "none":
  1863. view = _ui_utils.SidebarView.NONE;
  1864. break;
  1865. default:
  1866. console.error('Invalid "pagemode" hash parameter: ' + mode);
  1867. return;
  1868. }
  1869. PDFViewerApplication.pdfSidebar.switchView(view, true);
  1870. }
  1871. function webViewerNamedAction(evt) {
  1872. switch (evt.action) {
  1873. case "GoToPage":
  1874. PDFViewerApplication.appConfig.toolbar.pageNumber.select();
  1875. break;
  1876. case "Find":
  1877. if (!PDFViewerApplication.supportsIntegratedFind) {
  1878. PDFViewerApplication.findBar.toggle();
  1879. }
  1880. break;
  1881. case "Print":
  1882. PDFViewerApplication.triggerPrinting();
  1883. break;
  1884. case "SaveAs":
  1885. webViewerSave();
  1886. break;
  1887. }
  1888. }
  1889. function webViewerPresentationModeChanged(evt) {
  1890. PDFViewerApplication.pdfViewer.presentationModeState = evt.state;
  1891. }
  1892. function webViewerSidebarViewChanged(evt) {
  1893. PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = PDFViewerApplication.pdfSidebar.isThumbnailViewVisible;
  1894. const store = PDFViewerApplication.store;
  1895. if (store && PDFViewerApplication.isInitialViewSet) {
  1896. store.set("sidebarView", evt.view).catch(function () {});
  1897. }
  1898. }
  1899. function webViewerUpdateViewarea(evt) {
  1900. const location = evt.location,
  1901. store = PDFViewerApplication.store;
  1902. if (store && PDFViewerApplication.isInitialViewSet) {
  1903. store.setMultiple({
  1904. page: location.pageNumber,
  1905. zoom: location.scale,
  1906. scrollLeft: location.left,
  1907. scrollTop: location.top,
  1908. rotation: location.rotation
  1909. }).catch(function () {});
  1910. }
  1911. const href = PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  1912. PDFViewerApplication.appConfig.toolbar.viewBookmark.href = href;
  1913. PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href;
  1914. const currentPage = PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1);
  1915. const loading = (currentPage && currentPage.renderingState) !== _pdf_rendering_queue.RenderingStates.FINISHED;
  1916. PDFViewerApplication.toolbar.updateLoadingIndicatorState(loading);
  1917. }
  1918. function webViewerScrollModeChanged(evt) {
  1919. const store = PDFViewerApplication.store;
  1920. if (store && PDFViewerApplication.isInitialViewSet) {
  1921. store.set("scrollMode", evt.mode).catch(function () {});
  1922. }
  1923. }
  1924. function webViewerSpreadModeChanged(evt) {
  1925. const store = PDFViewerApplication.store;
  1926. if (store && PDFViewerApplication.isInitialViewSet) {
  1927. store.set("spreadMode", evt.mode).catch(function () {});
  1928. }
  1929. }
  1930. function webViewerResize() {
  1931. const {
  1932. pdfDocument,
  1933. pdfViewer
  1934. } = PDFViewerApplication;
  1935. if (!pdfDocument) {
  1936. return;
  1937. }
  1938. const currentScaleValue = pdfViewer.currentScaleValue;
  1939. if (currentScaleValue === "auto" || currentScaleValue === "page-fit" || currentScaleValue === "page-width") {
  1940. pdfViewer.currentScaleValue = currentScaleValue;
  1941. }
  1942. pdfViewer.update();
  1943. }
  1944. function webViewerHashchange(evt) {
  1945. const hash = evt.hash;
  1946. if (!hash) {
  1947. return;
  1948. }
  1949. if (!PDFViewerApplication.isInitialViewSet) {
  1950. PDFViewerApplication.initialBookmark = hash;
  1951. } else if (!PDFViewerApplication.pdfHistory.popStateInProgress) {
  1952. PDFViewerApplication.pdfLinkService.setHash(hash);
  1953. }
  1954. }
  1955. let webViewerFileInputChange, webViewerOpenFile;
  1956. {
  1957. webViewerFileInputChange = function (evt) {
  1958. if (PDFViewerApplication.pdfViewer && PDFViewerApplication.pdfViewer.isInPresentationMode) {
  1959. return;
  1960. }
  1961. const file = evt.fileInput.files[0];
  1962. if (!_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) {
  1963. let url = URL.createObjectURL(file);
  1964. if (file.name) {
  1965. url = {
  1966. url,
  1967. originalUrl: file.name
  1968. };
  1969. }
  1970. PDFViewerApplication.open(url);
  1971. } else {
  1972. PDFViewerApplication.setTitleUsingUrl(file.name);
  1973. const fileReader = new FileReader();
  1974. fileReader.onload = function webViewerChangeFileReaderOnload(event) {
  1975. const buffer = event.target.result;
  1976. PDFViewerApplication.open(new Uint8Array(buffer));
  1977. };
  1978. fileReader.readAsArrayBuffer(file);
  1979. }
  1980. const appConfig = PDFViewerApplication.appConfig;
  1981. appConfig.toolbar.viewBookmark.setAttribute("hidden", "true");
  1982. appConfig.secondaryToolbar.viewBookmarkButton.setAttribute("hidden", "true");
  1983. appConfig.toolbar.download.setAttribute("hidden", "true");
  1984. appConfig.secondaryToolbar.downloadButton.setAttribute("hidden", "true");
  1985. };
  1986. webViewerOpenFile = function (evt) {
  1987. const openFileInputName = PDFViewerApplication.appConfig.openFileInputName;
  1988. document.getElementById(openFileInputName).click();
  1989. };
  1990. }
  1991. function webViewerPresentationMode() {
  1992. PDFViewerApplication.requestPresentationMode();
  1993. }
  1994. function webViewerPrint() {
  1995. PDFViewerApplication.triggerPrinting();
  1996. }
  1997. function webViewerDownload() {
  1998. PDFViewerApplication.downloadOrSave({
  1999. sourceEventType: "download"
  2000. });
  2001. }
  2002. function webViewerSave() {
  2003. PDFViewerApplication.downloadOrSave({
  2004. sourceEventType: "save"
  2005. });
  2006. }
  2007. function webViewerFirstPage() {
  2008. if (PDFViewerApplication.pdfDocument) {
  2009. PDFViewerApplication.page = 1;
  2010. }
  2011. }
  2012. function webViewerLastPage() {
  2013. if (PDFViewerApplication.pdfDocument) {
  2014. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  2015. }
  2016. }
  2017. function webViewerNextPage() {
  2018. PDFViewerApplication.pdfViewer.nextPage();
  2019. }
  2020. function webViewerPreviousPage() {
  2021. PDFViewerApplication.pdfViewer.previousPage();
  2022. }
  2023. function webViewerZoomIn() {
  2024. PDFViewerApplication.zoomIn();
  2025. }
  2026. function webViewerZoomOut() {
  2027. PDFViewerApplication.zoomOut();
  2028. }
  2029. function webViewerZoomReset() {
  2030. PDFViewerApplication.zoomReset();
  2031. }
  2032. function webViewerPageNumberChanged(evt) {
  2033. const pdfViewer = PDFViewerApplication.pdfViewer;
  2034. if (evt.value !== "") {
  2035. PDFViewerApplication.pdfLinkService.goToPage(evt.value);
  2036. }
  2037. if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) {
  2038. PDFViewerApplication.toolbar.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  2039. }
  2040. }
  2041. function webViewerScaleChanged(evt) {
  2042. PDFViewerApplication.pdfViewer.currentScaleValue = evt.value;
  2043. }
  2044. function webViewerRotateCw() {
  2045. PDFViewerApplication.rotatePages(90);
  2046. }
  2047. function webViewerRotateCcw() {
  2048. PDFViewerApplication.rotatePages(-90);
  2049. }
  2050. function webViewerOptionalContentConfig(evt) {
  2051. PDFViewerApplication.pdfViewer.optionalContentConfigPromise = evt.promise;
  2052. }
  2053. function webViewerSwitchScrollMode(evt) {
  2054. PDFViewerApplication.pdfViewer.scrollMode = evt.mode;
  2055. }
  2056. function webViewerSwitchSpreadMode(evt) {
  2057. PDFViewerApplication.pdfViewer.spreadMode = evt.mode;
  2058. }
  2059. function webViewerDocumentProperties() {
  2060. PDFViewerApplication.pdfDocumentProperties.open();
  2061. }
  2062. function webViewerFind(evt) {
  2063. PDFViewerApplication.findController.executeCommand("find" + evt.type, {
  2064. query: evt.query,
  2065. phraseSearch: evt.phraseSearch,
  2066. caseSensitive: evt.caseSensitive,
  2067. entireWord: evt.entireWord,
  2068. highlightAll: evt.highlightAll,
  2069. findPrevious: evt.findPrevious
  2070. });
  2071. }
  2072. function webViewerFindFromUrlHash(evt) {
  2073. PDFViewerApplication.findController.executeCommand("find", {
  2074. query: evt.query,
  2075. phraseSearch: evt.phraseSearch,
  2076. caseSensitive: false,
  2077. entireWord: false,
  2078. highlightAll: true,
  2079. findPrevious: false
  2080. });
  2081. }
  2082. function webViewerUpdateFindMatchesCount({
  2083. matchesCount
  2084. }) {
  2085. if (PDFViewerApplication.supportsIntegratedFind) {
  2086. PDFViewerApplication.externalServices.updateFindMatchesCount(matchesCount);
  2087. } else {
  2088. PDFViewerApplication.findBar.updateResultsCount(matchesCount);
  2089. }
  2090. }
  2091. function webViewerUpdateFindControlState({
  2092. state,
  2093. previous,
  2094. matchesCount,
  2095. rawQuery
  2096. }) {
  2097. if (PDFViewerApplication.supportsIntegratedFind) {
  2098. PDFViewerApplication.externalServices.updateFindControlState({
  2099. result: state,
  2100. findPrevious: previous,
  2101. matchesCount,
  2102. rawQuery
  2103. });
  2104. } else {
  2105. PDFViewerApplication.findBar.updateUIState(state, previous, matchesCount);
  2106. }
  2107. }
  2108. function webViewerScaleChanging(evt) {
  2109. PDFViewerApplication.toolbar.setPageScale(evt.presetValue, evt.scale);
  2110. PDFViewerApplication.pdfViewer.update();
  2111. }
  2112. function webViewerRotationChanging(evt) {
  2113. PDFViewerApplication.pdfThumbnailViewer.pagesRotation = evt.pagesRotation;
  2114. PDFViewerApplication.forceRendering();
  2115. PDFViewerApplication.pdfViewer.currentPageNumber = evt.pageNumber;
  2116. }
  2117. function webViewerPageChanging({
  2118. pageNumber,
  2119. pageLabel
  2120. }) {
  2121. PDFViewerApplication.toolbar.setPageNumber(pageNumber, pageLabel);
  2122. PDFViewerApplication.secondaryToolbar.setPageNumber(pageNumber);
  2123. if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) {
  2124. PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(pageNumber);
  2125. }
  2126. }
  2127. function webViewerVisibilityChange(evt) {
  2128. if (document.visibilityState === "visible") {
  2129. setZoomDisabledTimeout();
  2130. }
  2131. }
  2132. let zoomDisabledTimeout = null;
  2133. function setZoomDisabledTimeout() {
  2134. if (zoomDisabledTimeout) {
  2135. clearTimeout(zoomDisabledTimeout);
  2136. }
  2137. zoomDisabledTimeout = setTimeout(function () {
  2138. zoomDisabledTimeout = null;
  2139. }, WHEEL_ZOOM_DISABLED_TIMEOUT);
  2140. }
  2141. function webViewerWheel(evt) {
  2142. const {
  2143. pdfViewer,
  2144. supportedMouseWheelZoomModifierKeys
  2145. } = PDFViewerApplication;
  2146. if (pdfViewer.isInPresentationMode) {
  2147. return;
  2148. }
  2149. if (evt.ctrlKey && supportedMouseWheelZoomModifierKeys.ctrlKey || evt.metaKey && supportedMouseWheelZoomModifierKeys.metaKey) {
  2150. evt.preventDefault();
  2151. if (zoomDisabledTimeout || document.visibilityState === "hidden") {
  2152. return;
  2153. }
  2154. const previousScale = pdfViewer.currentScale;
  2155. const delta = (0, _ui_utils.normalizeWheelEventDirection)(evt);
  2156. let ticks = 0;
  2157. if (evt.deltaMode === WheelEvent.DOM_DELTA_LINE || evt.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
  2158. if (Math.abs(delta) >= 1) {
  2159. ticks = Math.sign(delta);
  2160. } else {
  2161. ticks = PDFViewerApplication.accumulateWheelTicks(delta);
  2162. }
  2163. } else {
  2164. const PIXELS_PER_LINE_SCALE = 30;
  2165. ticks = PDFViewerApplication.accumulateWheelTicks(delta / PIXELS_PER_LINE_SCALE);
  2166. }
  2167. if (ticks < 0) {
  2168. PDFViewerApplication.zoomOut(-ticks);
  2169. } else if (ticks > 0) {
  2170. PDFViewerApplication.zoomIn(ticks);
  2171. }
  2172. const currentScale = pdfViewer.currentScale;
  2173. if (previousScale !== currentScale) {
  2174. const scaleCorrectionFactor = currentScale / previousScale - 1;
  2175. const rect = pdfViewer.container.getBoundingClientRect();
  2176. const dx = evt.clientX - rect.left;
  2177. const dy = evt.clientY - rect.top;
  2178. pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor;
  2179. pdfViewer.container.scrollTop += dy * scaleCorrectionFactor;
  2180. }
  2181. } else {
  2182. setZoomDisabledTimeout();
  2183. }
  2184. }
  2185. function webViewerTouchStart(evt) {
  2186. if (evt.touches.length > 1) {
  2187. evt.preventDefault();
  2188. }
  2189. }
  2190. function webViewerClick(evt) {
  2191. if (PDFViewerApplication.triggerDelayedFallback && PDFViewerApplication.pdfViewer.containsElement(evt.target)) {
  2192. PDFViewerApplication.triggerDelayedFallback();
  2193. }
  2194. if (!PDFViewerApplication.secondaryToolbar.isOpen) {
  2195. return;
  2196. }
  2197. const appConfig = PDFViewerApplication.appConfig;
  2198. if (PDFViewerApplication.pdfViewer.containsElement(evt.target) || appConfig.toolbar.container.contains(evt.target) && evt.target !== appConfig.secondaryToolbar.toggleButton) {
  2199. PDFViewerApplication.secondaryToolbar.close();
  2200. }
  2201. }
  2202. function webViewerKeyUp(evt) {
  2203. if (evt.keyCode === 9) {
  2204. if (PDFViewerApplication.triggerDelayedFallback) {
  2205. PDFViewerApplication.triggerDelayedFallback();
  2206. }
  2207. }
  2208. }
  2209. function webViewerKeyDown(evt) {
  2210. if (PDFViewerApplication.overlayManager.active) {
  2211. return;
  2212. }
  2213. let handled = false,
  2214. ensureViewerFocused = false;
  2215. const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0);
  2216. const pdfViewer = PDFViewerApplication.pdfViewer;
  2217. const isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode;
  2218. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  2219. switch (evt.keyCode) {
  2220. case 70:
  2221. if (!PDFViewerApplication.supportsIntegratedFind && !evt.shiftKey) {
  2222. PDFViewerApplication.findBar.open();
  2223. handled = true;
  2224. }
  2225. break;
  2226. case 71:
  2227. if (!PDFViewerApplication.supportsIntegratedFind) {
  2228. const findState = PDFViewerApplication.findController.state;
  2229. if (findState) {
  2230. PDFViewerApplication.findController.executeCommand("findagain", {
  2231. query: findState.query,
  2232. phraseSearch: findState.phraseSearch,
  2233. caseSensitive: findState.caseSensitive,
  2234. entireWord: findState.entireWord,
  2235. highlightAll: findState.highlightAll,
  2236. findPrevious: cmd === 5 || cmd === 12
  2237. });
  2238. }
  2239. handled = true;
  2240. }
  2241. break;
  2242. case 61:
  2243. case 107:
  2244. case 187:
  2245. case 171:
  2246. if (!isViewerInPresentationMode) {
  2247. PDFViewerApplication.zoomIn();
  2248. }
  2249. handled = true;
  2250. break;
  2251. case 173:
  2252. case 109:
  2253. case 189:
  2254. if (!isViewerInPresentationMode) {
  2255. PDFViewerApplication.zoomOut();
  2256. }
  2257. handled = true;
  2258. break;
  2259. case 48:
  2260. case 96:
  2261. if (!isViewerInPresentationMode) {
  2262. setTimeout(function () {
  2263. PDFViewerApplication.zoomReset();
  2264. });
  2265. handled = false;
  2266. }
  2267. break;
  2268. case 38:
  2269. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  2270. PDFViewerApplication.page = 1;
  2271. handled = true;
  2272. ensureViewerFocused = true;
  2273. }
  2274. break;
  2275. case 40:
  2276. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  2277. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  2278. handled = true;
  2279. ensureViewerFocused = true;
  2280. }
  2281. break;
  2282. }
  2283. }
  2284. const {
  2285. eventBus
  2286. } = PDFViewerApplication;
  2287. if (cmd === 1 || cmd === 8) {
  2288. switch (evt.keyCode) {
  2289. case 83:
  2290. eventBus.dispatch("download", {
  2291. source: window
  2292. });
  2293. handled = true;
  2294. break;
  2295. case 79:
  2296. {
  2297. eventBus.dispatch("openfile", {
  2298. source: window
  2299. });
  2300. handled = true;
  2301. }
  2302. break;
  2303. }
  2304. }
  2305. if (cmd === 3 || cmd === 10) {
  2306. switch (evt.keyCode) {
  2307. case 80:
  2308. PDFViewerApplication.requestPresentationMode();
  2309. handled = true;
  2310. break;
  2311. case 71:
  2312. PDFViewerApplication.appConfig.toolbar.pageNumber.select();
  2313. handled = true;
  2314. break;
  2315. }
  2316. }
  2317. if (handled) {
  2318. if (ensureViewerFocused && !isViewerInPresentationMode) {
  2319. pdfViewer.focus();
  2320. }
  2321. evt.preventDefault();
  2322. return;
  2323. }
  2324. const curElement = (0, _ui_utils.getActiveOrFocusedElement)();
  2325. const curElementTagName = curElement && curElement.tagName.toUpperCase();
  2326. if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElement && curElement.isContentEditable) {
  2327. if (evt.keyCode !== 27) {
  2328. return;
  2329. }
  2330. }
  2331. if (cmd === 0) {
  2332. let turnPage = 0,
  2333. turnOnlyIfPageFit = false;
  2334. switch (evt.keyCode) {
  2335. case 38:
  2336. case 33:
  2337. if (pdfViewer.isVerticalScrollbarEnabled) {
  2338. turnOnlyIfPageFit = true;
  2339. }
  2340. turnPage = -1;
  2341. break;
  2342. case 8:
  2343. if (!isViewerInPresentationMode) {
  2344. turnOnlyIfPageFit = true;
  2345. }
  2346. turnPage = -1;
  2347. break;
  2348. case 37:
  2349. if (pdfViewer.isHorizontalScrollbarEnabled) {
  2350. turnOnlyIfPageFit = true;
  2351. }
  2352. case 75:
  2353. case 80:
  2354. turnPage = -1;
  2355. break;
  2356. case 27:
  2357. if (PDFViewerApplication.secondaryToolbar.isOpen) {
  2358. PDFViewerApplication.secondaryToolbar.close();
  2359. handled = true;
  2360. }
  2361. if (!PDFViewerApplication.supportsIntegratedFind && PDFViewerApplication.findBar.opened) {
  2362. PDFViewerApplication.findBar.close();
  2363. handled = true;
  2364. }
  2365. break;
  2366. case 40:
  2367. case 34:
  2368. if (pdfViewer.isVerticalScrollbarEnabled) {
  2369. turnOnlyIfPageFit = true;
  2370. }
  2371. turnPage = 1;
  2372. break;
  2373. case 13:
  2374. case 32:
  2375. if (!isViewerInPresentationMode) {
  2376. turnOnlyIfPageFit = true;
  2377. }
  2378. turnPage = 1;
  2379. break;
  2380. case 39:
  2381. if (pdfViewer.isHorizontalScrollbarEnabled) {
  2382. turnOnlyIfPageFit = true;
  2383. }
  2384. case 74:
  2385. case 78:
  2386. turnPage = 1;
  2387. break;
  2388. case 36:
  2389. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  2390. PDFViewerApplication.page = 1;
  2391. handled = true;
  2392. ensureViewerFocused = true;
  2393. }
  2394. break;
  2395. case 35:
  2396. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  2397. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  2398. handled = true;
  2399. ensureViewerFocused = true;
  2400. }
  2401. break;
  2402. case 83:
  2403. PDFViewerApplication.pdfCursorTools.switchTool(_pdf_cursor_tools.CursorTool.SELECT);
  2404. break;
  2405. case 72:
  2406. PDFViewerApplication.pdfCursorTools.switchTool(_pdf_cursor_tools.CursorTool.HAND);
  2407. break;
  2408. case 82:
  2409. PDFViewerApplication.rotatePages(90);
  2410. break;
  2411. case 115:
  2412. PDFViewerApplication.pdfSidebar.toggle();
  2413. break;
  2414. }
  2415. if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) {
  2416. if (turnPage > 0) {
  2417. pdfViewer.nextPage();
  2418. } else {
  2419. pdfViewer.previousPage();
  2420. }
  2421. handled = true;
  2422. }
  2423. }
  2424. if (cmd === 4) {
  2425. switch (evt.keyCode) {
  2426. case 13:
  2427. case 32:
  2428. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== "page-fit") {
  2429. break;
  2430. }
  2431. if (PDFViewerApplication.page > 1) {
  2432. PDFViewerApplication.page--;
  2433. }
  2434. handled = true;
  2435. break;
  2436. case 82:
  2437. PDFViewerApplication.rotatePages(-90);
  2438. break;
  2439. }
  2440. }
  2441. if (!handled && !isViewerInPresentationMode) {
  2442. if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== "BUTTON") {
  2443. ensureViewerFocused = true;
  2444. }
  2445. }
  2446. if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
  2447. pdfViewer.focus();
  2448. }
  2449. if (handled) {
  2450. evt.preventDefault();
  2451. }
  2452. }
  2453. function beforeUnload(evt) {
  2454. evt.preventDefault();
  2455. evt.returnValue = "";
  2456. return false;
  2457. }
  2458. function apiPageLayoutToSpreadMode(layout) {
  2459. switch (layout) {
  2460. case "SinglePage":
  2461. case "OneColumn":
  2462. return _ui_utils.SpreadMode.NONE;
  2463. case "TwoColumnLeft":
  2464. case "TwoPageLeft":
  2465. return _ui_utils.SpreadMode.ODD;
  2466. case "TwoColumnRight":
  2467. case "TwoPageRight":
  2468. return _ui_utils.SpreadMode.EVEN;
  2469. }
  2470. return _ui_utils.SpreadMode.NONE;
  2471. }
  2472. function apiPageModeToSidebarView(mode) {
  2473. switch (mode) {
  2474. case "UseNone":
  2475. return _ui_utils.SidebarView.NONE;
  2476. case "UseThumbs":
  2477. return _ui_utils.SidebarView.THUMBS;
  2478. case "UseOutlines":
  2479. return _ui_utils.SidebarView.OUTLINE;
  2480. case "UseAttachments":
  2481. return _ui_utils.SidebarView.ATTACHMENTS;
  2482. case "UseOC":
  2483. return _ui_utils.SidebarView.LAYERS;
  2484. }
  2485. return _ui_utils.SidebarView.NONE;
  2486. }
  2487. const PDFPrintServiceFactory = {
  2488. instance: {
  2489. supportsPrinting: false,
  2490. createPrintService() {
  2491. throw new Error("Not implemented: createPrintService");
  2492. }
  2493. }
  2494. };
  2495. exports.PDFPrintServiceFactory = PDFPrintServiceFactory;