app.js 77 KB

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