pdf_scripting_manager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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.PDFScriptingManager = void 0;
  27. var _ui_utils = require("./ui_utils.js");
  28. var _pdf = require("../pdf");
  29. class PDFScriptingManager {
  30. constructor({
  31. eventBus,
  32. sandboxBundleSrc = null,
  33. scriptingFactory = null,
  34. docPropertiesLookup = null
  35. }) {
  36. this._pdfDocument = null;
  37. this._pdfViewer = null;
  38. this._closeCapability = null;
  39. this._destroyCapability = null;
  40. this._scripting = null;
  41. this._mouseState = Object.create(null);
  42. this._ready = false;
  43. this._eventBus = eventBus;
  44. this._sandboxBundleSrc = sandboxBundleSrc;
  45. this._scriptingFactory = scriptingFactory;
  46. this._docPropertiesLookup = docPropertiesLookup;
  47. }
  48. setViewer(pdfViewer) {
  49. this._pdfViewer = pdfViewer;
  50. }
  51. async setDocument(pdfDocument) {
  52. if (this._pdfDocument) {
  53. await this._destroyScripting();
  54. }
  55. this._pdfDocument = pdfDocument;
  56. if (!pdfDocument) {
  57. return;
  58. }
  59. const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]);
  60. if (!objects && !docActions) {
  61. await this._destroyScripting();
  62. return;
  63. }
  64. if (pdfDocument !== this._pdfDocument) {
  65. return;
  66. }
  67. try {
  68. this._scripting = this._createScripting();
  69. } catch (error) {
  70. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  71. await this._destroyScripting();
  72. return;
  73. }
  74. this._internalEvents.set("updatefromsandbox", event => {
  75. if (event?.source !== window) {
  76. return;
  77. }
  78. this._updateFromSandbox(event.detail);
  79. });
  80. this._internalEvents.set("dispatcheventinsandbox", event => {
  81. this._scripting?.dispatchEventInSandbox(event.detail);
  82. });
  83. this._internalEvents.set("pagechanging", ({
  84. pageNumber,
  85. previous
  86. }) => {
  87. if (pageNumber === previous) {
  88. return;
  89. }
  90. this._dispatchPageClose(previous);
  91. this._dispatchPageOpen(pageNumber);
  92. });
  93. this._internalEvents.set("pagerendered", ({
  94. pageNumber
  95. }) => {
  96. if (!this._pageOpenPending.has(pageNumber)) {
  97. return;
  98. }
  99. if (pageNumber !== this._pdfViewer.currentPageNumber) {
  100. return;
  101. }
  102. this._dispatchPageOpen(pageNumber);
  103. });
  104. this._internalEvents.set("pagesdestroy", async event => {
  105. await this._dispatchPageClose(this._pdfViewer.currentPageNumber);
  106. await this._scripting?.dispatchEventInSandbox({
  107. id: "doc",
  108. name: "WillClose"
  109. });
  110. this._closeCapability?.resolve();
  111. });
  112. this._domEvents.set("mousedown", event => {
  113. this._mouseState.isDown = true;
  114. });
  115. this._domEvents.set("mouseup", event => {
  116. this._mouseState.isDown = false;
  117. });
  118. for (const [name, listener] of this._internalEvents) {
  119. this._eventBus._on(name, listener);
  120. }
  121. for (const [name, listener] of this._domEvents) {
  122. window.addEventListener(name, listener, true);
  123. }
  124. try {
  125. const docProperties = await this._getDocProperties();
  126. if (pdfDocument !== this._pdfDocument) {
  127. return;
  128. }
  129. await this._scripting.createSandbox({
  130. objects,
  131. calculationOrder,
  132. appInfo: {
  133. platform: navigator.platform,
  134. language: navigator.language
  135. },
  136. docInfo: {
  137. ...docProperties,
  138. actions: docActions
  139. }
  140. });
  141. this._eventBus.dispatch("sandboxcreated", {
  142. source: this
  143. });
  144. } catch (error) {
  145. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  146. await this._destroyScripting();
  147. return;
  148. }
  149. await this._scripting?.dispatchEventInSandbox({
  150. id: "doc",
  151. name: "Open"
  152. });
  153. await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true);
  154. Promise.resolve().then(() => {
  155. if (pdfDocument === this._pdfDocument) {
  156. this._ready = true;
  157. }
  158. });
  159. }
  160. async dispatchWillSave(detail) {
  161. return this._scripting?.dispatchEventInSandbox({
  162. id: "doc",
  163. name: "WillSave"
  164. });
  165. }
  166. async dispatchDidSave(detail) {
  167. return this._scripting?.dispatchEventInSandbox({
  168. id: "doc",
  169. name: "DidSave"
  170. });
  171. }
  172. async dispatchWillPrint(detail) {
  173. return this._scripting?.dispatchEventInSandbox({
  174. id: "doc",
  175. name: "WillPrint"
  176. });
  177. }
  178. async dispatchDidPrint(detail) {
  179. return this._scripting?.dispatchEventInSandbox({
  180. id: "doc",
  181. name: "DidPrint"
  182. });
  183. }
  184. get mouseState() {
  185. return this._mouseState;
  186. }
  187. get destroyPromise() {
  188. return this._destroyCapability?.promise || null;
  189. }
  190. get ready() {
  191. return this._ready;
  192. }
  193. get _internalEvents() {
  194. return (0, _pdf.shadow)(this, "_internalEvents", new Map());
  195. }
  196. get _domEvents() {
  197. return (0, _pdf.shadow)(this, "_domEvents", new Map());
  198. }
  199. get _pageOpenPending() {
  200. return (0, _pdf.shadow)(this, "_pageOpenPending", new Set());
  201. }
  202. get _visitedPages() {
  203. return (0, _pdf.shadow)(this, "_visitedPages", new Map());
  204. }
  205. async _updateFromSandbox(detail) {
  206. const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode;
  207. const {
  208. id,
  209. siblings,
  210. command,
  211. value
  212. } = detail;
  213. if (!id) {
  214. switch (command) {
  215. case "clear":
  216. console.clear();
  217. break;
  218. case "error":
  219. console.error(value);
  220. break;
  221. case "layout":
  222. if (isInPresentationMode) {
  223. return;
  224. }
  225. const modes = (0, _ui_utils.apiPageLayoutToViewerModes)(value);
  226. this._pdfViewer.spreadMode = modes.spreadMode;
  227. break;
  228. case "page-num":
  229. this._pdfViewer.currentPageNumber = value + 1;
  230. break;
  231. case "print":
  232. await this._pdfViewer.pagesPromise;
  233. this._eventBus.dispatch("print", {
  234. source: this
  235. });
  236. break;
  237. case "println":
  238. console.log(value);
  239. break;
  240. case "zoom":
  241. if (isInPresentationMode) {
  242. return;
  243. }
  244. this._pdfViewer.currentScaleValue = value;
  245. break;
  246. case "SaveAs":
  247. this._eventBus.dispatch("download", {
  248. source: this
  249. });
  250. break;
  251. case "FirstPage":
  252. this._pdfViewer.currentPageNumber = 1;
  253. break;
  254. case "LastPage":
  255. this._pdfViewer.currentPageNumber = this._pdfViewer.pagesCount;
  256. break;
  257. case "NextPage":
  258. this._pdfViewer.nextPage();
  259. break;
  260. case "PrevPage":
  261. this._pdfViewer.previousPage();
  262. break;
  263. case "ZoomViewIn":
  264. if (isInPresentationMode) {
  265. return;
  266. }
  267. this._pdfViewer.increaseScale();
  268. break;
  269. case "ZoomViewOut":
  270. if (isInPresentationMode) {
  271. return;
  272. }
  273. this._pdfViewer.decreaseScale();
  274. break;
  275. }
  276. return;
  277. }
  278. if (isInPresentationMode) {
  279. if (detail.focus) {
  280. return;
  281. }
  282. }
  283. delete detail.id;
  284. delete detail.siblings;
  285. const ids = siblings ? [id, ...siblings] : [id];
  286. for (const elementId of ids) {
  287. const element = document.querySelector(`[data-element-id="${elementId}"]`);
  288. if (element) {
  289. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  290. detail
  291. }));
  292. } else {
  293. this._pdfDocument?.annotationStorage.setValue(elementId, detail);
  294. }
  295. }
  296. }
  297. async _dispatchPageOpen(pageNumber, initialize = false) {
  298. const pdfDocument = this._pdfDocument,
  299. visitedPages = this._visitedPages;
  300. if (initialize) {
  301. this._closeCapability = (0, _pdf.createPromiseCapability)();
  302. }
  303. if (!this._closeCapability) {
  304. return;
  305. }
  306. const pageView = this._pdfViewer.getPageView(pageNumber - 1);
  307. if (pageView?.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  308. this._pageOpenPending.add(pageNumber);
  309. return;
  310. }
  311. this._pageOpenPending.delete(pageNumber);
  312. const actionsPromise = (async () => {
  313. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  314. if (pdfDocument !== this._pdfDocument) {
  315. return;
  316. }
  317. await this._scripting?.dispatchEventInSandbox({
  318. id: "page",
  319. name: "PageOpen",
  320. pageNumber,
  321. actions
  322. });
  323. })();
  324. visitedPages.set(pageNumber, actionsPromise);
  325. }
  326. async _dispatchPageClose(pageNumber) {
  327. const pdfDocument = this._pdfDocument,
  328. visitedPages = this._visitedPages;
  329. if (!this._closeCapability) {
  330. return;
  331. }
  332. if (this._pageOpenPending.has(pageNumber)) {
  333. return;
  334. }
  335. const actionsPromise = visitedPages.get(pageNumber);
  336. if (!actionsPromise) {
  337. return;
  338. }
  339. visitedPages.set(pageNumber, null);
  340. await actionsPromise;
  341. if (pdfDocument !== this._pdfDocument) {
  342. return;
  343. }
  344. await this._scripting?.dispatchEventInSandbox({
  345. id: "page",
  346. name: "PageClose",
  347. pageNumber
  348. });
  349. }
  350. async _getDocProperties() {
  351. if (this._docPropertiesLookup) {
  352. return this._docPropertiesLookup(this._pdfDocument);
  353. }
  354. throw new Error("_getDocProperties: Unable to lookup properties.");
  355. }
  356. _createScripting() {
  357. this._destroyCapability = (0, _pdf.createPromiseCapability)();
  358. if (this._scripting) {
  359. throw new Error("_createScripting: Scripting already exists.");
  360. }
  361. if (this._scriptingFactory) {
  362. return this._scriptingFactory.createScripting({
  363. sandboxBundleSrc: this._sandboxBundleSrc
  364. });
  365. }
  366. throw new Error("_createScripting: Cannot create scripting.");
  367. }
  368. async _destroyScripting() {
  369. if (!this._scripting) {
  370. this._pdfDocument = null;
  371. this._destroyCapability?.resolve();
  372. return;
  373. }
  374. if (this._closeCapability) {
  375. await Promise.race([this._closeCapability.promise, new Promise(resolve => {
  376. setTimeout(resolve, 1000);
  377. })]).catch(reason => {});
  378. this._closeCapability = null;
  379. }
  380. this._pdfDocument = null;
  381. try {
  382. await this._scripting.destroySandbox();
  383. } catch (ex) {}
  384. for (const [name, listener] of this._internalEvents) {
  385. this._eventBus._off(name, listener);
  386. }
  387. this._internalEvents.clear();
  388. for (const [name, listener] of this._domEvents) {
  389. window.removeEventListener(name, listener, true);
  390. }
  391. this._domEvents.clear();
  392. this._pageOpenPending.clear();
  393. this._visitedPages.clear();
  394. this._scripting = null;
  395. delete this._mouseState.isDown;
  396. this._ready = false;
  397. this._destroyCapability?.resolve();
  398. }
  399. }
  400. exports.PDFScriptingManager = PDFScriptingManager;