firefoxcom.js 11 KB

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