app.js 76 KB

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