firefoxcom.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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"];
  170. const handleEvent = function ({
  171. type,
  172. detail
  173. }) {
  174. if (!_app.PDFViewerApplication.initialized) {
  175. return;
  176. }
  177. if (type === "findbarclose") {
  178. _app.PDFViewerApplication.eventBus.dispatch(type, {
  179. source: window
  180. });
  181. return;
  182. }
  183. _app.PDFViewerApplication.eventBus.dispatch("find", {
  184. source: window,
  185. type: type.substring("find".length),
  186. query: detail.query,
  187. phraseSearch: true,
  188. caseSensitive: !!detail.caseSensitive,
  189. entireWord: !!detail.entireWord,
  190. highlightAll: !!detail.highlightAll,
  191. findPrevious: !!detail.findPrevious
  192. });
  193. };
  194. for (const event of events) {
  195. window.addEventListener(event, handleEvent);
  196. }
  197. })();
  198. (function listenZoomEvents() {
  199. const events = ["zoomin", "zoomout", "zoomreset"];
  200. const handleEvent = function ({
  201. type,
  202. detail
  203. }) {
  204. if (!_app.PDFViewerApplication.initialized) {
  205. return;
  206. }
  207. if (type === "zoomreset" && _app.PDFViewerApplication.pdfViewer.currentScaleValue === _ui_utils.DEFAULT_SCALE_VALUE) {
  208. return;
  209. }
  210. _app.PDFViewerApplication.eventBus.dispatch(type, {
  211. source: window
  212. });
  213. };
  214. for (const event of events) {
  215. window.addEventListener(event, handleEvent);
  216. }
  217. })();
  218. (function listenSaveEvent() {
  219. const handleEvent = function ({
  220. type,
  221. detail
  222. }) {
  223. if (!_app.PDFViewerApplication.initialized) {
  224. return;
  225. }
  226. _app.PDFViewerApplication.eventBus.dispatch(type, {
  227. source: window
  228. });
  229. };
  230. window.addEventListener("save", handleEvent);
  231. })();
  232. class FirefoxComDataRangeTransport extends _pdf.PDFDataRangeTransport {
  233. requestDataRange(begin, end) {
  234. FirefoxCom.request("requestDataRange", {
  235. begin,
  236. end
  237. });
  238. }
  239. abort() {
  240. FirefoxCom.requestSync("abortLoading", null);
  241. }
  242. }
  243. class FirefoxScripting {
  244. static async createSandbox(data) {
  245. const success = await FirefoxCom.requestAsync("createSandbox", data);
  246. if (!success) {
  247. throw new Error("Cannot create sandbox.");
  248. }
  249. }
  250. static async dispatchEventInSandbox(event) {
  251. FirefoxCom.request("dispatchEventInSandbox", event);
  252. }
  253. static async destroySandbox() {
  254. FirefoxCom.request("destroySandbox", null);
  255. }
  256. }
  257. class FirefoxExternalServices extends _app.DefaultExternalServices {
  258. static updateFindControlState(data) {
  259. FirefoxCom.request("updateFindControlState", data);
  260. }
  261. static updateFindMatchesCount(data) {
  262. FirefoxCom.request("updateFindMatchesCount", data);
  263. }
  264. static initPassiveLoading(callbacks) {
  265. let pdfDataRangeTransport;
  266. window.addEventListener("message", function windowMessage(e) {
  267. if (e.source !== null) {
  268. console.warn("Rejected untrusted message from " + e.origin);
  269. return;
  270. }
  271. const args = e.data;
  272. if (typeof args !== "object" || !("pdfjsLoadAction" in args)) {
  273. return;
  274. }
  275. switch (args.pdfjsLoadAction) {
  276. case "supportsRangedLoading":
  277. pdfDataRangeTransport = new FirefoxComDataRangeTransport(args.length, args.data, args.done, args.filename);
  278. callbacks.onOpenWithTransport(args.pdfUrl, args.length, pdfDataRangeTransport);
  279. break;
  280. case "range":
  281. pdfDataRangeTransport.onDataRange(args.begin, args.chunk);
  282. break;
  283. case "rangeProgress":
  284. pdfDataRangeTransport.onDataProgress(args.loaded);
  285. break;
  286. case "progressiveRead":
  287. pdfDataRangeTransport.onDataProgressiveRead(args.chunk);
  288. pdfDataRangeTransport.onDataProgress(args.loaded, args.total);
  289. break;
  290. case "progressiveDone":
  291. if (pdfDataRangeTransport) {
  292. pdfDataRangeTransport.onDataProgressiveDone();
  293. }
  294. break;
  295. case "progress":
  296. callbacks.onProgress(args.loaded, args.total);
  297. break;
  298. case "complete":
  299. if (!args.data) {
  300. callbacks.onError(args.errorCode);
  301. break;
  302. }
  303. callbacks.onOpenWithData(args.data, args.filename);
  304. break;
  305. }
  306. });
  307. FirefoxCom.requestSync("initPassiveLoading", null);
  308. }
  309. static async fallback(data) {
  310. return FirefoxCom.requestAsync("fallback", data);
  311. }
  312. static reportTelemetry(data) {
  313. FirefoxCom.request("reportTelemetry", JSON.stringify(data));
  314. }
  315. static createDownloadManager(options) {
  316. return new DownloadManager();
  317. }
  318. static createPreferences() {
  319. return new FirefoxPreferences();
  320. }
  321. static createL10n(options) {
  322. const mozL10n = document.mozL10n;
  323. return new MozL10n(mozL10n);
  324. }
  325. static createScripting(options) {
  326. return FirefoxScripting;
  327. }
  328. static get supportsIntegratedFind() {
  329. const support = FirefoxCom.requestSync("supportsIntegratedFind");
  330. return (0, _pdf.shadow)(this, "supportsIntegratedFind", support);
  331. }
  332. static get supportsDocumentFonts() {
  333. const support = FirefoxCom.requestSync("supportsDocumentFonts");
  334. return (0, _pdf.shadow)(this, "supportsDocumentFonts", support);
  335. }
  336. static get supportedMouseWheelZoomModifierKeys() {
  337. const support = FirefoxCom.requestSync("supportedMouseWheelZoomModifierKeys");
  338. return (0, _pdf.shadow)(this, "supportedMouseWheelZoomModifierKeys", support);
  339. }
  340. static get isInAutomation() {
  341. const isInAutomation = FirefoxCom.requestSync("isInAutomation");
  342. return (0, _pdf.shadow)(this, "isInAutomation", isInAutomation);
  343. }
  344. }
  345. _app.PDFViewerApplication.externalServices = FirefoxExternalServices;
  346. document.mozL10n.setExternalLocalizerServices({
  347. getLocale() {
  348. return FirefoxCom.requestSync("getLocale", null);
  349. },
  350. getStrings(key) {
  351. return FirefoxCom.requestSync("getStrings", key);
  352. }
  353. });