pdf_scripting_manager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PDFScriptingManager = void 0;
  27. var _pdf = require("../pdf");
  28. var _ui_utils = require("./ui_utils.js");
  29. var _pdf_rendering_queue = require("./pdf_rendering_queue.js");
  30. class PDFScriptingManager {
  31. constructor({
  32. eventBus,
  33. sandboxBundleSrc = null,
  34. scriptingFactory = null,
  35. docPropertiesLookup = null
  36. }) {
  37. this._pdfDocument = null;
  38. this._pdfViewer = null;
  39. this._closeCapability = null;
  40. this._destroyCapability = null;
  41. this._scripting = null;
  42. this._mouseState = Object.create(null);
  43. this._pageEventsReady = false;
  44. this._ready = false;
  45. this._eventBus = eventBus;
  46. this._sandboxBundleSrc = sandboxBundleSrc;
  47. this._scriptingFactory = scriptingFactory;
  48. this._docPropertiesLookup = docPropertiesLookup;
  49. }
  50. setViewer(pdfViewer) {
  51. this._pdfViewer = pdfViewer;
  52. }
  53. async setDocument(pdfDocument) {
  54. if (this._pdfDocument) {
  55. await this._destroyScripting();
  56. }
  57. this._pdfDocument = pdfDocument;
  58. if (!pdfDocument) {
  59. return;
  60. }
  61. const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]);
  62. if (!objects && !docActions) {
  63. await this._destroyScripting();
  64. return;
  65. }
  66. if (pdfDocument !== this._pdfDocument) {
  67. return;
  68. }
  69. this._scripting = this._createScripting();
  70. this._internalEvents.set("updatefromsandbox", event => {
  71. if (event?.source !== window) {
  72. return;
  73. }
  74. this._updateFromSandbox(event.detail);
  75. });
  76. this._internalEvents.set("dispatcheventinsandbox", event => {
  77. this._scripting?.dispatchEventInSandbox(event.detail);
  78. });
  79. this._internalEvents.set("pagechanging", ({
  80. pageNumber,
  81. previous
  82. }) => {
  83. if (pageNumber === previous) {
  84. return;
  85. }
  86. this._dispatchPageClose(previous);
  87. this._dispatchPageOpen(pageNumber);
  88. });
  89. this._internalEvents.set("pagerendered", ({
  90. pageNumber
  91. }) => {
  92. if (!this._pageOpenPending.has(pageNumber)) {
  93. return;
  94. }
  95. if (pageNumber !== this._pdfViewer.currentPageNumber) {
  96. return;
  97. }
  98. this._dispatchPageOpen(pageNumber);
  99. });
  100. this._internalEvents.set("pagesdestroy", async event => {
  101. await this._dispatchPageClose(this._pdfViewer.currentPageNumber);
  102. await this._scripting?.dispatchEventInSandbox({
  103. id: "doc",
  104. name: "WillClose"
  105. });
  106. this._closeCapability?.resolve();
  107. });
  108. this._domEvents.set("mousedown", event => {
  109. this._mouseState.isDown = true;
  110. });
  111. this._domEvents.set("mouseup", event => {
  112. this._mouseState.isDown = false;
  113. });
  114. for (const [name, listener] of this._internalEvents) {
  115. this._eventBus._on(name, listener);
  116. }
  117. for (const [name, listener] of this._domEvents) {
  118. window.addEventListener(name, listener);
  119. }
  120. try {
  121. const docProperties = await this._getDocProperties();
  122. if (pdfDocument !== this._pdfDocument) {
  123. return;
  124. }
  125. await this._scripting.createSandbox({
  126. objects,
  127. calculationOrder,
  128. appInfo: {
  129. platform: navigator.platform,
  130. language: navigator.language
  131. },
  132. docInfo: { ...docProperties,
  133. actions: docActions
  134. }
  135. });
  136. this._eventBus.dispatch("sandboxcreated", {
  137. source: this
  138. });
  139. } catch (error) {
  140. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  141. await this._destroyScripting();
  142. return;
  143. }
  144. await this._scripting?.dispatchEventInSandbox({
  145. id: "doc",
  146. name: "Open"
  147. });
  148. await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true);
  149. Promise.resolve().then(() => {
  150. if (pdfDocument === this._pdfDocument) {
  151. this._ready = true;
  152. }
  153. });
  154. }
  155. async dispatchWillSave(detail) {
  156. return this._scripting?.dispatchEventInSandbox({
  157. id: "doc",
  158. name: "WillSave"
  159. });
  160. }
  161. async dispatchDidSave(detail) {
  162. return this._scripting?.dispatchEventInSandbox({
  163. id: "doc",
  164. name: "DidSave"
  165. });
  166. }
  167. async dispatchWillPrint(detail) {
  168. return this._scripting?.dispatchEventInSandbox({
  169. id: "doc",
  170. name: "WillPrint"
  171. });
  172. }
  173. async dispatchDidPrint(detail) {
  174. return this._scripting?.dispatchEventInSandbox({
  175. id: "doc",
  176. name: "DidPrint"
  177. });
  178. }
  179. get mouseState() {
  180. return this._mouseState;
  181. }
  182. get destroyPromise() {
  183. return this._destroyCapability?.promise || null;
  184. }
  185. get ready() {
  186. return this._ready;
  187. }
  188. get _internalEvents() {
  189. return (0, _pdf.shadow)(this, "_internalEvents", new Map());
  190. }
  191. get _domEvents() {
  192. return (0, _pdf.shadow)(this, "_domEvents", new Map());
  193. }
  194. get _pageOpenPending() {
  195. return (0, _pdf.shadow)(this, "_pageOpenPending", new Set());
  196. }
  197. get _visitedPages() {
  198. return (0, _pdf.shadow)(this, "_visitedPages", new Map());
  199. }
  200. async _updateFromSandbox(detail) {
  201. const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode;
  202. const {
  203. id,
  204. siblings,
  205. command,
  206. value
  207. } = detail;
  208. if (!id) {
  209. switch (command) {
  210. case "clear":
  211. console.clear();
  212. break;
  213. case "error":
  214. console.error(value);
  215. break;
  216. case "layout":
  217. this._pdfViewer.spreadMode = (0, _ui_utils.apiPageLayoutToSpreadMode)(value);
  218. break;
  219. case "page-num":
  220. this._pdfViewer.currentPageNumber = value + 1;
  221. break;
  222. case "print":
  223. await this._pdfViewer.pagesPromise;
  224. this._eventBus.dispatch("print", {
  225. source: this
  226. });
  227. break;
  228. case "println":
  229. console.log(value);
  230. break;
  231. case "zoom":
  232. if (isInPresentationMode) {
  233. return;
  234. }
  235. this._pdfViewer.currentScaleValue = value;
  236. break;
  237. }
  238. return;
  239. }
  240. if (isInPresentationMode) {
  241. if (detail.focus) {
  242. return;
  243. }
  244. }
  245. delete detail.id;
  246. delete detail.siblings;
  247. const ids = siblings ? [id, ...siblings] : [id];
  248. for (const elementId of ids) {
  249. const element = document.getElementById(elementId);
  250. if (element) {
  251. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  252. detail
  253. }));
  254. } else {
  255. this._pdfDocument?.annotationStorage.setValue(elementId, detail);
  256. }
  257. }
  258. }
  259. async _dispatchPageOpen(pageNumber, initialize = false) {
  260. const pdfDocument = this._pdfDocument,
  261. visitedPages = this._visitedPages;
  262. if (initialize) {
  263. this._closeCapability = (0, _pdf.createPromiseCapability)();
  264. this._pageEventsReady = true;
  265. }
  266. if (!this._pageEventsReady) {
  267. return;
  268. }
  269. const pageView = this._pdfViewer.getPageView(pageNumber - 1);
  270. if (pageView?.renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) {
  271. this._pageOpenPending.add(pageNumber);
  272. return;
  273. }
  274. this._pageOpenPending.delete(pageNumber);
  275. const actionsPromise = (async () => {
  276. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  277. if (pdfDocument !== this._pdfDocument) {
  278. return;
  279. }
  280. await this._scripting?.dispatchEventInSandbox({
  281. id: "page",
  282. name: "PageOpen",
  283. pageNumber,
  284. actions
  285. });
  286. })();
  287. visitedPages.set(pageNumber, actionsPromise);
  288. }
  289. async _dispatchPageClose(pageNumber) {
  290. const pdfDocument = this._pdfDocument,
  291. visitedPages = this._visitedPages;
  292. if (!this._pageEventsReady) {
  293. return;
  294. }
  295. if (this._pageOpenPending.has(pageNumber)) {
  296. return;
  297. }
  298. const actionsPromise = visitedPages.get(pageNumber);
  299. if (!actionsPromise) {
  300. return;
  301. }
  302. visitedPages.set(pageNumber, null);
  303. await actionsPromise;
  304. if (pdfDocument !== this._pdfDocument) {
  305. return;
  306. }
  307. await this._scripting?.dispatchEventInSandbox({
  308. id: "page",
  309. name: "PageClose",
  310. pageNumber
  311. });
  312. }
  313. async _getDocProperties() {
  314. if (this._docPropertiesLookup) {
  315. return this._docPropertiesLookup(this._pdfDocument);
  316. }
  317. throw new Error("_getDocProperties: Unable to lookup properties.");
  318. }
  319. _createScripting() {
  320. this._destroyCapability = (0, _pdf.createPromiseCapability)();
  321. if (this._scripting) {
  322. throw new Error("_createScripting: Scripting already exists.");
  323. }
  324. if (this._scriptingFactory) {
  325. return this._scriptingFactory.createScripting({
  326. sandboxBundleSrc: this._sandboxBundleSrc
  327. });
  328. }
  329. throw new Error("_createScripting: Cannot create scripting.");
  330. }
  331. async _destroyScripting() {
  332. if (!this._scripting) {
  333. this._pdfDocument = null;
  334. this._destroyCapability?.resolve();
  335. return;
  336. }
  337. if (this._closeCapability) {
  338. await Promise.race([this._closeCapability.promise, new Promise(resolve => {
  339. setTimeout(resolve, 1000);
  340. })]).catch(reason => {});
  341. this._closeCapability = null;
  342. }
  343. this._pdfDocument = null;
  344. try {
  345. await this._scripting.destroySandbox();
  346. } catch (ex) {}
  347. for (const [name, listener] of this._internalEvents) {
  348. this._eventBus._off(name, listener);
  349. }
  350. this._internalEvents.clear();
  351. for (const [name, listener] of this._domEvents) {
  352. window.removeEventListener(name, listener);
  353. }
  354. this._domEvents.clear();
  355. this._pageOpenPending.clear();
  356. this._visitedPages.clear();
  357. this._scripting = null;
  358. delete this._mouseState.isDown;
  359. this._pageEventsReady = false;
  360. this._ready = false;
  361. this._destroyCapability?.resolve();
  362. }
  363. }
  364. exports.PDFScriptingManager = PDFScriptingManager;