app.js 74 KB

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