pdf_scripting_manager.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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: { ...docProperties,
  137. actions: docActions
  138. }
  139. });
  140. this._eventBus.dispatch("sandboxcreated", {
  141. source: this
  142. });
  143. } catch (error) {
  144. console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
  145. await this._destroyScripting();
  146. return;
  147. }
  148. await this._scripting?.dispatchEventInSandbox({
  149. id: "doc",
  150. name: "Open"
  151. });
  152. await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true);
  153. Promise.resolve().then(() => {
  154. if (pdfDocument === this._pdfDocument) {
  155. this._ready = true;
  156. }
  157. });
  158. }
  159. async dispatchWillSave(detail) {
  160. return this._scripting?.dispatchEventInSandbox({
  161. id: "doc",
  162. name: "WillSave"
  163. });
  164. }
  165. async dispatchDidSave(detail) {
  166. return this._scripting?.dispatchEventInSandbox({
  167. id: "doc",
  168. name: "DidSave"
  169. });
  170. }
  171. async dispatchWillPrint(detail) {
  172. return this._scripting?.dispatchEventInSandbox({
  173. id: "doc",
  174. name: "WillPrint"
  175. });
  176. }
  177. async dispatchDidPrint(detail) {
  178. return this._scripting?.dispatchEventInSandbox({
  179. id: "doc",
  180. name: "DidPrint"
  181. });
  182. }
  183. get mouseState() {
  184. return this._mouseState;
  185. }
  186. get destroyPromise() {
  187. return this._destroyCapability?.promise || null;
  188. }
  189. get ready() {
  190. return this._ready;
  191. }
  192. get _internalEvents() {
  193. return (0, _pdf.shadow)(this, "_internalEvents", new Map());
  194. }
  195. get _domEvents() {
  196. return (0, _pdf.shadow)(this, "_domEvents", new Map());
  197. }
  198. get _pageOpenPending() {
  199. return (0, _pdf.shadow)(this, "_pageOpenPending", new Set());
  200. }
  201. get _visitedPages() {
  202. return (0, _pdf.shadow)(this, "_visitedPages", new Map());
  203. }
  204. async _updateFromSandbox(detail) {
  205. const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode;
  206. const {
  207. id,
  208. siblings,
  209. command,
  210. value
  211. } = detail;
  212. if (!id) {
  213. switch (command) {
  214. case "clear":
  215. console.clear();
  216. break;
  217. case "error":
  218. console.error(value);
  219. break;
  220. case "layout":
  221. if (isInPresentationMode) {
  222. return;
  223. }
  224. const modes = (0, _ui_utils.apiPageLayoutToViewerModes)(value);
  225. this._pdfViewer.spreadMode = modes.spreadMode;
  226. break;
  227. case "page-num":
  228. this._pdfViewer.currentPageNumber = value + 1;
  229. break;
  230. case "print":
  231. await this._pdfViewer.pagesPromise;
  232. this._eventBus.dispatch("print", {
  233. source: this
  234. });
  235. break;
  236. case "println":
  237. console.log(value);
  238. break;
  239. case "zoom":
  240. if (isInPresentationMode) {
  241. return;
  242. }
  243. this._pdfViewer.currentScaleValue = value;
  244. break;
  245. case "SaveAs":
  246. this._eventBus.dispatch("download", {
  247. source: this
  248. });
  249. break;
  250. case "FirstPage":
  251. this._pdfViewer.currentPageNumber = 1;
  252. break;
  253. case "LastPage":
  254. this._pdfViewer.currentPageNumber = this._pdfViewer.pagesCount;
  255. break;
  256. case "NextPage":
  257. this._pdfViewer.nextPage();
  258. break;
  259. case "PrevPage":
  260. this._pdfViewer.previousPage();
  261. break;
  262. case "ZoomViewIn":
  263. if (isInPresentationMode) {
  264. return;
  265. }
  266. this._pdfViewer.increaseScale();
  267. break;
  268. case "ZoomViewOut":
  269. if (isInPresentationMode) {
  270. return;
  271. }
  272. this._pdfViewer.decreaseScale();
  273. break;
  274. }
  275. return;
  276. }
  277. if (isInPresentationMode) {
  278. if (detail.focus) {
  279. return;
  280. }
  281. }
  282. delete detail.id;
  283. delete detail.siblings;
  284. const ids = siblings ? [id, ...siblings] : [id];
  285. for (const elementId of ids) {
  286. const element = document.querySelector(`[data-element-id="${elementId}"]`);
  287. if (element) {
  288. element.dispatchEvent(new CustomEvent("updatefromsandbox", {
  289. detail
  290. }));
  291. } else {
  292. this._pdfDocument?.annotationStorage.setValue(elementId, detail);
  293. }
  294. }
  295. }
  296. async _dispatchPageOpen(pageNumber, initialize = false) {
  297. const pdfDocument = this._pdfDocument,
  298. visitedPages = this._visitedPages;
  299. if (initialize) {
  300. this._closeCapability = (0, _pdf.createPromiseCapability)();
  301. }
  302. if (!this._closeCapability) {
  303. return;
  304. }
  305. const pageView = this._pdfViewer.getPageView(pageNumber - 1);
  306. if (pageView?.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  307. this._pageOpenPending.add(pageNumber);
  308. return;
  309. }
  310. this._pageOpenPending.delete(pageNumber);
  311. const actionsPromise = (async () => {
  312. const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null);
  313. if (pdfDocument !== this._pdfDocument) {
  314. return;
  315. }
  316. await this._scripting?.dispatchEventInSandbox({
  317. id: "page",
  318. name: "PageOpen",
  319. pageNumber,
  320. actions
  321. });
  322. })();
  323. visitedPages.set(pageNumber, actionsPromise);
  324. }
  325. async _dispatchPageClose(pageNumber) {
  326. const pdfDocument = this._pdfDocument,
  327. visitedPages = this._visitedPages;
  328. if (!this._closeCapability) {
  329. return;
  330. }
  331. if (this._pageOpenPending.has(pageNumber)) {
  332. return;
  333. }
  334. const actionsPromise = visitedPages.get(pageNumber);
  335. if (!actionsPromise) {
  336. return;
  337. }
  338. visitedPages.set(pageNumber, null);
  339. await actionsPromise;
  340. if (pdfDocument !== this._pdfDocument) {
  341. return;
  342. }
  343. await this._scripting?.dispatchEventInSandbox({
  344. id: "page",
  345. name: "PageClose",
  346. pageNumber
  347. });
  348. }
  349. async _getDocProperties() {
  350. if (this._docPropertiesLookup) {
  351. return this._docPropertiesLookup(this._pdfDocument);
  352. }
  353. throw new Error("_getDocProperties: Unable to lookup properties.");
  354. }
  355. _createScripting() {
  356. this._destroyCapability = (0, _pdf.createPromiseCapability)();
  357. if (this._scripting) {
  358. throw new Error("_createScripting: Scripting already exists.");
  359. }
  360. if (this._scriptingFactory) {
  361. return this._scriptingFactory.createScripting({
  362. sandboxBundleSrc: this._sandboxBundleSrc
  363. });
  364. }
  365. throw new Error("_createScripting: Cannot create scripting.");
  366. }
  367. async _destroyScripting() {
  368. if (!this._scripting) {
  369. this._pdfDocument = null;
  370. this._destroyCapability?.resolve();
  371. return;
  372. }
  373. if (this._closeCapability) {
  374. await Promise.race([this._closeCapability.promise, new Promise(resolve => {
  375. setTimeout(resolve, 1000);
  376. })]).catch(reason => {});
  377. this._closeCapability = null;
  378. }
  379. this._pdfDocument = null;
  380. try {
  381. await this._scripting.destroySandbox();
  382. } catch (ex) {}
  383. for (const [name, listener] of this._internalEvents) {
  384. this._eventBus._off(name, listener);
  385. }
  386. this._internalEvents.clear();
  387. for (const [name, listener] of this._domEvents) {
  388. window.removeEventListener(name, listener, true);
  389. }
  390. this._domEvents.clear();
  391. this._pageOpenPending.clear();
  392. this._visitedPages.clear();
  393. this._scripting = null;
  394. delete this._mouseState.isDown;
  395. this._ready = false;
  396. this._destroyCapability?.resolve();
  397. }
  398. }
  399. exports.PDFScriptingManager = PDFScriptingManager;