firefoxcom.js 11 KB

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