firefoxcom.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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.FirefoxCom = exports.DownloadManager = void 0;
  27. require("../extensions/firefox/tools/l10n.js");
  28. var _app = require("./app.js");
  29. var _pdf = require("../pdf");
  30. var _preferences = require("./preferences.js");
  31. var _ui_utils = require("./ui_utils.js");
  32. var _l10n_utils = require("./l10n_utils.js");
  33. {
  34. throw new Error('Module "./firefoxcom.js" shall not be used outside MOZCENTRAL builds.');
  35. }
  36. class FirefoxCom {
  37. static requestSync(action, data) {
  38. const request = document.createTextNode("");
  39. document.documentElement.append(request);
  40. const sender = document.createEvent("CustomEvent");
  41. sender.initCustomEvent("pdf.js.message", true, false, {
  42. action,
  43. data,
  44. sync: true
  45. });
  46. request.dispatchEvent(sender);
  47. const response = sender.detail.response;
  48. request.remove();
  49. return response;
  50. }
  51. static requestAsync(action, data) {
  52. return new Promise(resolve => {
  53. this.request(action, data, resolve);
  54. });
  55. }
  56. static request(action, data, callback = null) {
  57. const request = document.createTextNode("");
  58. if (callback) {
  59. request.addEventListener("pdf.js.response", event => {
  60. const response = event.detail.response;
  61. event.target.remove();
  62. callback(response);
  63. }, {
  64. once: true
  65. });
  66. }
  67. document.documentElement.append(request);
  68. const sender = document.createEvent("CustomEvent");
  69. sender.initCustomEvent("pdf.js.message", true, false, {
  70. action,
  71. data,
  72. sync: false,
  73. responseExpected: !!callback
  74. });
  75. request.dispatchEvent(sender);
  76. }
  77. }
  78. exports.FirefoxCom = FirefoxCom;
  79. class DownloadManager {
  80. constructor() {
  81. this._openBlobUrls = new WeakMap();
  82. }
  83. downloadUrl(url, filename) {
  84. FirefoxCom.request("download", {
  85. originalUrl: url,
  86. filename
  87. });
  88. }
  89. downloadData(data, filename, contentType) {
  90. const blobUrl = URL.createObjectURL(new Blob([data], {
  91. type: contentType
  92. }));
  93. FirefoxCom.request("download", {
  94. blobUrl,
  95. originalUrl: blobUrl,
  96. filename,
  97. isAttachment: true
  98. });
  99. }
  100. openOrDownloadData(element, data, filename) {
  101. const isPdfData = (0, _pdf.isPdfFile)(filename);
  102. const contentType = isPdfData ? "application/pdf" : "";
  103. if (isPdfData) {
  104. let blobUrl = this._openBlobUrls.get(element);
  105. if (!blobUrl) {
  106. blobUrl = URL.createObjectURL(new Blob([data], {
  107. type: contentType
  108. }));
  109. this._openBlobUrls.set(element, blobUrl);
  110. }
  111. const viewerUrl = blobUrl + "#filename=" + encodeURIComponent(filename);
  112. try {
  113. window.open(viewerUrl);
  114. return true;
  115. } catch (ex) {
  116. console.error(`openOrDownloadData: ${ex}`);
  117. URL.revokeObjectURL(blobUrl);
  118. this._openBlobUrls.delete(element);
  119. }
  120. }
  121. this.downloadData(data, filename, contentType);
  122. return false;
  123. }
  124. download(blob, url, filename) {
  125. const blobUrl = URL.createObjectURL(blob);
  126. FirefoxCom.request("download", {
  127. blobUrl,
  128. originalUrl: url,
  129. filename
  130. });
  131. }
  132. }
  133. exports.DownloadManager = DownloadManager;
  134. class FirefoxPreferences extends _preferences.BasePreferences {
  135. async _writeToStorage(prefObj) {
  136. return FirefoxCom.requestAsync("setPreferences", prefObj);
  137. }
  138. async _readFromStorage(prefObj) {
  139. const prefStr = await FirefoxCom.requestAsync("getPreferences", prefObj);
  140. return JSON.parse(prefStr);
  141. }
  142. }
  143. class MozL10n {
  144. constructor(mozL10n) {
  145. this.mozL10n = mozL10n;
  146. }
  147. async getLanguage() {
  148. return this.mozL10n.getLanguage();
  149. }
  150. async getDirection() {
  151. return this.mozL10n.getDirection();
  152. }
  153. async get(key, args = null, fallback = (0, _l10n_utils.getL10nFallback)(key, args)) {
  154. return this.mozL10n.get(key, args, fallback);
  155. }
  156. async translate(element) {
  157. this.mozL10n.translate(element);
  158. }
  159. }
  160. (function listenFindEvents() {
  161. const events = ["find", "findagain", "findhighlightallchange", "findcasesensitivitychange", "findentirewordchange", "findbarclose", "finddiacriticmatchingchange"];
  162. const findLen = "find".length;
  163. const handleEvent = function ({
  164. type,
  165. detail
  166. }) {
  167. if (!_app.PDFViewerApplication.initialized) {
  168. return;
  169. }
  170. if (type === "findbarclose") {
  171. _app.PDFViewerApplication.eventBus.dispatch(type, {
  172. source: window
  173. });
  174. return;
  175. }
  176. _app.PDFViewerApplication.eventBus.dispatch("find", {
  177. source: window,
  178. type: type.substring(findLen),
  179. query: detail.query,
  180. phraseSearch: true,
  181. caseSensitive: !!detail.caseSensitive,
  182. entireWord: !!detail.entireWord,
  183. highlightAll: !!detail.highlightAll,
  184. findPrevious: !!detail.findPrevious,
  185. matchDiacritics: !!detail.matchDiacritics
  186. });
  187. };
  188. for (const event of events) {
  189. window.addEventListener(event, handleEvent);
  190. }
  191. })();
  192. (function listenZoomEvents() {
  193. const events = ["zoomin", "zoomout", "zoomreset"];
  194. const handleEvent = function ({
  195. type,
  196. detail
  197. }) {
  198. if (!_app.PDFViewerApplication.initialized) {
  199. return;
  200. }
  201. if (type === "zoomreset" && _app.PDFViewerApplication.pdfViewer.currentScaleValue === _ui_utils.DEFAULT_SCALE_VALUE) {
  202. return;
  203. }
  204. _app.PDFViewerApplication.eventBus.dispatch(type, {
  205. source: window
  206. });
  207. };
  208. for (const event of events) {
  209. window.addEventListener(event, handleEvent);
  210. }
  211. })();
  212. (function listenSaveEvent() {
  213. const handleEvent = function ({
  214. type,
  215. detail
  216. }) {
  217. if (!_app.PDFViewerApplication.initialized) {
  218. return;
  219. }
  220. _app.PDFViewerApplication.eventBus.dispatch("download", {
  221. source: window
  222. });
  223. };
  224. window.addEventListener("save", handleEvent);
  225. })();
  226. (function listenEditingEvent() {
  227. const handleEvent = function ({
  228. detail
  229. }) {
  230. if (!_app.PDFViewerApplication.initialized) {
  231. return;
  232. }
  233. _app.PDFViewerApplication.eventBus.dispatch("editingaction", {
  234. source: window,
  235. name: detail.name
  236. });
  237. };
  238. window.addEventListener("editingaction", handleEvent);
  239. })();
  240. class FirefoxComDataRangeTransport extends _pdf.PDFDataRangeTransport {
  241. requestDataRange(begin, end) {
  242. FirefoxCom.request("requestDataRange", {
  243. begin,
  244. end
  245. });
  246. }
  247. abort() {
  248. FirefoxCom.requestSync("abortLoading", null);
  249. }
  250. }
  251. class FirefoxScripting {
  252. static async createSandbox(data) {
  253. const success = await FirefoxCom.requestAsync("createSandbox", data);
  254. if (!success) {
  255. throw new Error("Cannot create sandbox.");
  256. }
  257. }
  258. static async dispatchEventInSandbox(event) {
  259. FirefoxCom.request("dispatchEventInSandbox", event);
  260. }
  261. static async destroySandbox() {
  262. FirefoxCom.request("destroySandbox", null);
  263. }
  264. }
  265. class FirefoxExternalServices extends _app.DefaultExternalServices {
  266. static updateFindControlState(data) {
  267. FirefoxCom.request("updateFindControlState", data);
  268. }
  269. static updateFindMatchesCount(data) {
  270. FirefoxCom.request("updateFindMatchesCount", data);
  271. }
  272. static initPassiveLoading(callbacks) {
  273. let pdfDataRangeTransport;
  274. window.addEventListener("message", function windowMessage(e) {
  275. if (e.source !== null) {
  276. console.warn("Rejected untrusted message from " + e.origin);
  277. return;
  278. }
  279. const args = e.data;
  280. if (typeof args !== "object" || !("pdfjsLoadAction" in args)) {
  281. return;
  282. }
  283. switch (args.pdfjsLoadAction) {
  284. case "supportsRangedLoading":
  285. if (args.done && !args.data) {
  286. callbacks.onError();
  287. break;
  288. }
  289. pdfDataRangeTransport = new FirefoxComDataRangeTransport(args.length, args.data, args.done, args.filename);
  290. callbacks.onOpenWithTransport(args.pdfUrl, args.length, pdfDataRangeTransport);
  291. break;
  292. case "range":
  293. pdfDataRangeTransport.onDataRange(args.begin, args.chunk);
  294. break;
  295. case "rangeProgress":
  296. pdfDataRangeTransport.onDataProgress(args.loaded);
  297. break;
  298. case "progressiveRead":
  299. pdfDataRangeTransport.onDataProgressiveRead(args.chunk);
  300. pdfDataRangeTransport.onDataProgress(args.loaded, args.total);
  301. break;
  302. case "progressiveDone":
  303. pdfDataRangeTransport?.onDataProgressiveDone();
  304. break;
  305. case "progress":
  306. callbacks.onProgress(args.loaded, args.total);
  307. break;
  308. case "complete":
  309. if (!args.data) {
  310. callbacks.onError(args.errorCode);
  311. break;
  312. }
  313. callbacks.onOpenWithData(args.data, args.filename);
  314. break;
  315. }
  316. });
  317. FirefoxCom.requestSync("initPassiveLoading", null);
  318. }
  319. static reportTelemetry(data) {
  320. FirefoxCom.request("reportTelemetry", JSON.stringify(data));
  321. }
  322. static createDownloadManager(options) {
  323. return new DownloadManager();
  324. }
  325. static createPreferences() {
  326. return new FirefoxPreferences();
  327. }
  328. static updateEditorStates(data) {
  329. FirefoxCom.request("updateEditorStates", data);
  330. }
  331. static createL10n(options) {
  332. const mozL10n = document.mozL10n;
  333. return new MozL10n(mozL10n);
  334. }
  335. static createScripting(options) {
  336. return FirefoxScripting;
  337. }
  338. static get supportsIntegratedFind() {
  339. const support = FirefoxCom.requestSync("supportsIntegratedFind");
  340. return (0, _pdf.shadow)(this, "supportsIntegratedFind", support);
  341. }
  342. static get supportsDocumentFonts() {
  343. const support = FirefoxCom.requestSync("supportsDocumentFonts");
  344. return (0, _pdf.shadow)(this, "supportsDocumentFonts", support);
  345. }
  346. static get supportedMouseWheelZoomModifierKeys() {
  347. const support = FirefoxCom.requestSync("supportedMouseWheelZoomModifierKeys");
  348. return (0, _pdf.shadow)(this, "supportedMouseWheelZoomModifierKeys", support);
  349. }
  350. static get isInAutomation() {
  351. const isInAutomation = FirefoxCom.requestSync("isInAutomation");
  352. return (0, _pdf.shadow)(this, "isInAutomation", isInAutomation);
  353. }
  354. }
  355. _app.PDFViewerApplication.externalServices = FirefoxExternalServices;
  356. document.mozL10n.setExternalLocalizerServices({
  357. getLocale() {
  358. return FirefoxCom.requestSync("getLocale", null);
  359. },
  360. getStrings(key) {
  361. return FirefoxCom.requestSync("getStrings", null);
  362. }
  363. });