app.js 76 KB

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