platform.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. /*
  2. OfficePlatform - the host abstraction for the ArozOS Office Suite
  3. ================================================================
  4. Every place the suite reaches outside the browser tab goes through this
  5. file, so the same source runs in two hosts:
  6. "arozos" the ArozOS desktop. Files live in the virtual file
  7. system, dialogs are the desktop's file selector, and the
  8. heavy format conversions run server side in the AGI
  9. backends (mod/office).
  10. "standalone" a plain static web server with no ArozOS behind it
  11. (the "ArozOS Office Web" build). Documents are read from
  12. the visitor's device or from a relative URL next to the
  13. page, opened and saved by the same Go code compiled to
  14. WebAssembly (common/wasm.js), and saving hands the file
  15. back as a download.
  16. "native" the standalone build inside a desktop shell (ArozOS
  17. Office for macOS, apps/ArozOS Office Mac) that answers
  18. OfficeNative (common/native.js). The same WebAssembly
  19. converters, but files are real files: system Open and
  20. Save dialogs, Save writes back in place, and autosave
  21. and the recent list work as they do in ArozOS.
  22. Documents are .docx / .xlsx / .pptx in every host: documentLoad turns
  23. the file into the editor envelope and documentSave writes the envelope
  24. back as the file (mod/office native.go - the OOXML plus the editor's own
  25. copy embedded in the package).
  26. Two separate capability questions, deliberately not one:
  27. hasBackend() is there an ArozOS server? Gate anything that needs
  28. storage, an AGI script or a user account on this.
  29. canConvert() does this build carry the Office format code (mod/office)?
  30. True in ArozOS, and true in the standalone build, which
  31. always ships it as WebAssembly (src/wasm/office): it is
  32. what opens and saves every document there.
  33. Run a conversion through convertIn / convertOut rather than reaching for
  34. either host's mechanism: they take one descriptor naming the AGI script
  35. and the wasm converter, and pick the right one.
  36. The mode comes from common/mode.js (window.OFFICE_STANDALONE), which the
  37. web-viewer generator rewrites in its output tree, and the native host is
  38. the standalone build when a shell is answering (OfficeNative.available).
  39. Nothing else in the suite should test either: ask OfficePlatform instead.
  40. Load order: mode.js, native.js, recents.js, wasm.js, platform.js,
  41. office.js.
  42. Path shapes in standalone mode
  43. ------------------------------
  44. "local:/<name>" a File the visitor picked - held in a registry for
  45. the lifetime of the page
  46. "device:/<name>" a save target: writing to it downloads the file
  47. "recent:/<id>" a document kept in this browser by OfficeRecents
  48. (IndexedDB), which is what ?recent=<id> opens
  49. anything else a relative URL served next to the page (read only),
  50. which is how ?open= and ?template= work (a template
  51. is a plain envelope JSON file, templates/*.json)
  52. and in native mode, besides those:
  53. "native:/<handle>/<name>" a file on disk the person picked, opened
  54. from Finder or dropped on the window. The shell
  55. keeps the handle across relaunches, so ?open= with
  56. one reopens the file itself
  57. Query parameters the home page uses (see home/home.js):
  58. ?open=<relative path> open that document
  59. ?template=<relative path> start a new unsaved document from it
  60. ?recent=<id> reopen one of this browser's recent documents
  61. ?request=<share link> (standalone) open a public ArozOS share,
  62. optionally with &name=<file name>
  63. Requires: jquery, ../common/mode.js, ../common/wasm.js (standalone),
  64. (for ?request=) ../common/share.js and (in ArozOS mode)
  65. ../../script/ao_module.js
  66. */
  67. var OfficePlatform = (function () {
  68. "use strict";
  69. var STANDALONE = (typeof window.OFFICE_STANDALONE !== "undefined") &&
  70. !!window.OFFICE_STANDALONE;
  71. /* ---------- small helpers (duplicated from OfficeApp: this file loads
  72. first, and they are three lines each) ---------- */
  73. function basename(p) {
  74. var s = String(p || "").replace(/\\/g, "/");
  75. var q = s.indexOf("?");
  76. if (q >= 0) s = s.substring(0, q);
  77. return s.substring(s.lastIndexOf("/") + 1);
  78. }
  79. function stripExt(p) {
  80. var i = String(p).lastIndexOf(".");
  81. return i < 0 ? String(p) : String(p).substring(0, i);
  82. }
  83. function now() { return new Date().getTime(); }
  84. function extOf(name) {
  85. var s = basename(name);
  86. var i = s.lastIndexOf(".");
  87. return i < 0 ? "" : s.substring(i).toLowerCase();
  88. }
  89. /* The suite's own formats, by extension: which app lives in each, the
  90. WebAssembly converter that opens and saves it, and its MIME type. */
  91. var NATIVE = {
  92. ".docx": { app: "document", wasm: "documentFile",
  93. mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
  94. ".xlsx": { app: "spreadsheet", wasm: "spreadsheetFile",
  95. mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
  96. ".pptx": { app: "presentation", wasm: "presentationFile",
  97. mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation" }
  98. };
  99. /* The Office 97-2003 formats open through the same converter as the
  100. app's own format (office.ReadNativeFile converts them first); they are
  101. never saved, so documentSave never sees one. */
  102. var LEGACY = {
  103. ".doc": ".docx", ".dot": ".docx",
  104. ".xls": ".xlsx", ".xlt": ".xlsx",
  105. ".ppt": ".pptx", ".pot": ".pptx", ".pps": ".pptx"
  106. };
  107. function nativeOf(name) {
  108. var ext = extOf(name);
  109. return NATIVE[ext] || NATIVE[LEGACY[ext]] || null;
  110. }
  111. function extForApp(app) {
  112. for (var e in NATIVE) if (NATIVE[e].app === app) return e;
  113. return "";
  114. }
  115. /* gzip a string with the browser's own CompressionStream; cb(null) where
  116. there is none (the payload then goes uncompressed) */
  117. function gzipText(text, cb) {
  118. if (typeof CompressionStream !== "function" || typeof Response !== "function" ||
  119. typeof Blob !== "function") {
  120. cb(null);
  121. return;
  122. }
  123. try {
  124. var stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"));
  125. new Response(stream).blob().then(function (b) { cb(b); }, function () { cb(null); });
  126. } catch (e) { cb(null); }
  127. }
  128. function status(msg, type) {
  129. if (window.OfficeApp && OfficeApp.setStatus) OfficeApp.setStatus(msg, type);
  130. }
  131. function toast(msg, type) {
  132. if (window.OfficeApp && OfficeApp.toast) OfficeApp.toast(msg, type);
  133. else status(msg, type);
  134. }
  135. /*
  136. This page's path relative to the ArozOS web root ("Office/docs/
  137. index.html"), which is the form newFloatWindow wants. ao_root is the
  138. way back up to that root ("../../"), so the same number of trailing
  139. path segments is the way back down to here - and the app keeps
  140. working if the whole desktop is served from a sub-path.
  141. */
  142. function pagePath() {
  143. var parts = String(window.location.pathname).split("/")
  144. .filter(function (s) { return s.length > 0; });
  145. var up = (String(typeof ao_root === "string" ? ao_root : "").match(/\.\.\//g) || []).length;
  146. if (up > 0 && parts.length > up + 1) parts = parts.slice(parts.length - up - 1);
  147. return parts.join("/");
  148. }
  149. // a path relative to this page ("../img/docs.svg") in the same web-root
  150. // relative form ("Office/img/docs.svg")
  151. function pageRelative(rel) {
  152. var dir = pagePath().split("/");
  153. dir.pop();
  154. String(rel || "").split("/").forEach(function (seg) {
  155. if (!seg || seg === ".") return;
  156. if (seg === "..") { dir.pop(); return; }
  157. dir.push(seg);
  158. });
  159. return dir.join("/");
  160. }
  161. /* ================================================================
  162. ArozOS host
  163. ================================================================ */
  164. /* Working copies (pictures of the open documents, pictures dropped in
  165. before a save, oversized request payloads) live under tmp:/, which
  166. ArozOS empties nightly of anything a day old. Each editor window has
  167. its own folders, named by INSTANCE, and deletes them when it closes;
  168. see common/backend/document.agi. */
  169. var WORKDIR = "tmp:/.appdata/Office";
  170. var TMPDIR = WORKDIR + "/tmp";
  171. var INSTANCE = (Date.now().toString(36) +
  172. Math.random().toString(36).substring(2, 10)).replace(/[^a-z0-9]/g, "");
  173. var UPLOADS = WORKDIR + "/uploads/" + INSTANCE;
  174. // well inside the sweep's day, and throttled background timers still
  175. // manage it
  176. var KEEPALIVE_MS = 2 * 60 * 60 * 1000;
  177. var DOCUMENT_BACKEND = "Office/common/backend/document.agi";
  178. // only tiny blobs stay inline: an inline picture is base64 in the body,
  179. // which rides along on every save (pictures do not gzip), while an
  180. // uploaded one is a link the server reads - sent once, however often
  181. // the document is saved
  182. var DATAURL_MAX = 32 * 1024;
  183. var POST_INLINE_MAX = 4 * 1024 * 1024; // stay well clear of the 10 MB form cap
  184. // past this a payload is gzipped and uploaded rather than form-posted:
  185. // a urlencoded JSON body is roughly twice its own size, a gzipped one a
  186. // fifth of it, and the upload is one extra round trip
  187. var COMPRESS_MIN = 64 * 1024;
  188. var workdirReady = false;
  189. var keepAliveTimer = null;
  190. var workdirReleased = false;
  191. /* An open window keeps its working copies from the nightly sweep, and
  192. lets them go when it closes - unless it closes with unsaved changes:
  193. the draft kept in this browser still links them, and the sweep will
  194. take them a day later. */
  195. function startKeepAlive() {
  196. if (keepAliveTimer || typeof ao_module_agirun !== "function") return;
  197. keepAliveTimer = setInterval(function () {
  198. ao_module_agirun(DOCUMENT_BACKEND, { action: "touch", instance: INSTANCE },
  199. function () { }, function () { });
  200. }, KEEPALIVE_MS);
  201. window.addEventListener("pagehide", function () {
  202. if (window.OfficeApp && OfficeApp.isDirty && OfficeApp.isDirty()) return;
  203. releaseWorkdir();
  204. });
  205. }
  206. /* The vpath behind a media?file= link, or "" */
  207. function linkVpath(src) {
  208. var m = /media\?file=([^&"'\s)]+)/.exec(String(src || ""));
  209. if (!m) return "";
  210. try { return decodeURIComponent(m[1]); } catch (e) { return ""; }
  211. }
  212. /* A link into another window's working copies - a picture copied from
  213. there. That window deletes its folders when it closes, so the picture
  214. has to become this window's own. */
  215. function isForeignWorkingCopy(src) {
  216. var vp = linkVpath(src);
  217. return vp.indexOf(WORKDIR + "/") === 0 && vp.indexOf("/" + INSTANCE + "/") < 0;
  218. }
  219. function releaseWorkdir() {
  220. if (workdirReleased || !keepAliveTimer) return;
  221. workdirReleased = true;
  222. clearInterval(keepAliveTimer);
  223. var url = (typeof ao_root === "string" ? ao_root : "../../") +
  224. "system/ajgi/interface?script=" + DOCUMENT_BACKEND;
  225. var form = new URLSearchParams({ action: "release", instance: INSTANCE });
  226. // a closing page cannot wait for an answer: a beacon still goes out
  227. try {
  228. if (navigator.sendBeacon && navigator.sendBeacon(url, form)) return;
  229. } catch (e) { }
  230. try { fetch(url, { method: "POST", body: form, keepalive: true, credentials: "same-origin" }); } catch (e) { }
  231. }
  232. var arozos = {
  233. name: "arozos",
  234. hasBackend: true,
  235. tracksRecents: true,
  236. autosavesToFile: true,
  237. // the office AGI lib is there whenever the host is
  238. canConvert: function () { return true; },
  239. /* One conversion to or from a foreign format (ODF), whichever
  240. direction. In this host both are an AGI call; spec.wasm is
  241. ignored. */
  242. convertIn: function (spec, srcRef, cb, errcb) {
  243. arozos.agirun(spec.agi, { action: spec.action, src: srcRef },
  244. function (data) {
  245. if (!data || data.error) {
  246. errcb((data && data.error) || "no response");
  247. return;
  248. }
  249. cb(data.body);
  250. },
  251. function () { errcb("cannot reach the ArozOS backend"); }, 120000);
  252. },
  253. convertOut: function (spec, destRef, bodyJson, cb, errcb) {
  254. arozos.agirunLarge(spec.agi, {
  255. action: spec.action, dest: destRef, data: bodyJson
  256. }, "data", function (data) {
  257. // the pptx writer reports its media sidecar zip by vpath
  258. cb({ mediaZip: data && data.mediaZip ? basename(data.mediaZip) : null });
  259. }, errcb, 180000);
  260. },
  261. prepareWorkdir: function (cb, errcb) {
  262. if (workdirReady) { cb(); return; }
  263. ao_module_agirun(DOCUMENT_BACKEND, { action: "prepare", instance: INSTANCE }, function (data) {
  264. if (data && data.error) { if (errcb) errcb(data.error); return; }
  265. workdirReady = true;
  266. startKeepAlive();
  267. cb();
  268. }, function () {
  269. if (errcb) errcb("connection error");
  270. });
  271. },
  272. releaseWorkdir: function () { releaseWorkdir(); },
  273. agirun: function (script, params, cb, errcb, timeout) {
  274. ao_module_agirun(script, params, cb, errcb, timeout);
  275. },
  276. /* ---------- large AGI payloads ----------
  277. The AGI gateway reads its POST parameters with Go's r.ParseForm,
  278. which caps an application/x-www-form-urlencoded body at 10 MB.
  279. Past that the parse fails, EVERY parameter silently disappears and
  280. the still-uploading socket gets reset (the browser reports a plain
  281. network error). So a payload of any size worth mentioning is
  282. uploaded as a file through the system upload endpoint instead
  283. (streamed to disk server side rather than held in RAM) and handed
  284. to the script as a vpath in <field>File.
  285. That is also what makes a save cheap on a slow link: the upload is
  286. gzipped (CompressionStream) - a document body shrinks to a fifth
  287. or less, where urlencoding would have doubled it. The backend
  288. reads the file with office.readPayload, which gunzips it, and
  289. deletes it. Small payloads are simply posted.
  290. progress(stage, percent), when given, follows the request:
  291. "compress", "upload" (with the percent sent) and "server" (the
  292. script is running), so a long save can show where it is. */
  293. agirunLarge: function (script, params, field, cb, errcb, timeout, progress) {
  294. timeout = timeout || 0;
  295. errcb = errcb || function () { };
  296. progress = progress || function () { };
  297. var payload = params[field];
  298. var post = function (p) {
  299. progress("server");
  300. ao_module_agirun(script, p, function (data) {
  301. if (data && data.error) { errcb(data.error); return; }
  302. cb(data);
  303. }, function () { errcb("connection error"); }, timeout);
  304. };
  305. if (typeof payload !== "string" || payload.length <= COMPRESS_MIN ||
  306. typeof ao_module_uploadFile !== "function") {
  307. post(params);
  308. return;
  309. }
  310. var upload = function (blob, name) {
  311. arozos.prepareWorkdir(function () {
  312. var file;
  313. try {
  314. file = new File([blob], name, { type: blob.type || "application/octet-stream" });
  315. } catch (e) { post(params); return; }
  316. progress("upload", 0);
  317. ao_module_uploadFile(file, TMPDIR, function (resp) {
  318. if (typeof resp === "string" && resp.indexOf('"error"') >= 0) {
  319. errcb("upload failed: " + resp);
  320. return;
  321. }
  322. // hand over the vpath instead of the payload itself
  323. var p = {};
  324. Object.keys(params).forEach(function (k) {
  325. if (k !== field) p[k] = params[k];
  326. });
  327. p[field + "File"] = TMPDIR + "/" + name;
  328. post(p);
  329. }, function (pct) { progress("upload", pct); }, function () {
  330. errcb("upload failed - the document is too large to send");
  331. });
  332. }, function () { post(params); });
  333. };
  334. var stem = "post-" + Date.now().toString(36) + "-" +
  335. Math.random().toString(36).substring(2, 8);
  336. progress("compress");
  337. gzipText(payload, function (gz) {
  338. if (gz) { upload(gz, stem + ".json.gz"); return; }
  339. if (payload.length <= POST_INLINE_MAX) { post(params); return; }
  340. upload(new Blob([payload], { type: "application/json" }), stem + ".json");
  341. });
  342. },
  343. pickOpen: function (opts, cb) {
  344. try {
  345. ao_module_openFileSelector(function (files) {
  346. if (files && files.length > 0) cb(files);
  347. }, opts.startDir || "user:/Desktop", "file", !!opts.multiple, {
  348. filter: opts.filter,
  349. path_memory_key: opts.memoryKey || "document"
  350. });
  351. } catch (e) {
  352. toast("File selector is not available here", "error");
  353. }
  354. },
  355. pickSave: function (opts, cb) {
  356. try {
  357. ao_module_openFileSelector(function (files) {
  358. if (!files || !files.length) return;
  359. var fp = files[0].filepath, fn = files[0].filename;
  360. if (opts.ext && fn.toLowerCase().lastIndexOf(opts.ext.toLowerCase()) !==
  361. fn.length - opts.ext.length) {
  362. fp += opts.ext;
  363. fn += opts.ext;
  364. }
  365. cb({ filepath: fp, filename: fn });
  366. }, opts.startDir || "user:/Desktop", "new", false, {
  367. defaultName: opts.defaultName,
  368. path_memory_key: opts.memoryKey || "document",
  369. // a document that has never been saved has no folder of
  370. // its own, so start from wherever this app was last used
  371. force_path_overwrite: !!opts.forceOverwrite
  372. });
  373. } catch (e) {
  374. toast("File selector is not available here", "error");
  375. }
  376. },
  377. readText: function (path, cb, errcb) {
  378. // a template or a document published as a web asset is fetched
  379. // over HTTP in both hosts; only a vpath goes through the VFS
  380. if (!isVpath(path)) { readWebText(path, cb, errcb); return; }
  381. $.ajax({
  382. url: ao_root + "media?file=" + encodeURIComponent(path) + "&nocache=" + now(),
  383. dataType: "text",
  384. success: function (data) { cb(data); },
  385. error: function (xhr) { if (errcb) errcb(xhr); }
  386. });
  387. },
  388. // a file the client converts itself (a PDF Docs imports)
  389. readBytes: function (path, cb, errcb) {
  390. errcb = errcb || function () { };
  391. if (!isVpath(path)) { readWebBytes(path, cb, errcb); return; }
  392. var xhr = new XMLHttpRequest();
  393. xhr.open("GET", ao_root + "media?file=" + encodeURIComponent(path) + "&nocache=" + now());
  394. xhr.responseType = "arraybuffer";
  395. xhr.onload = function () {
  396. if (xhr.status >= 200 && xhr.status < 300 && xhr.response) cb(new Uint8Array(xhr.response));
  397. else errcb("HTTP " + xhr.status);
  398. };
  399. xhr.onerror = function () { errcb("cannot reach the ArozOS backend"); };
  400. xhr.send();
  401. },
  402. writeText: function (path, content, cb, errcb) {
  403. arozos.agirunLarge("Office/common/backend/filesaver.agi", {
  404. filepath: path,
  405. content: content
  406. }, "content", function () {
  407. if (cb) cb();
  408. }, function (msg) {
  409. if (errcb) errcb(msg);
  410. });
  411. },
  412. /* Write bytes the client produced (the Slides PDF renderer is the
  413. one that needs this: only the browser knows how the text laid
  414. out). Base64 rides the same oversized-payload path every export
  415. uses, and the backend decodes it with office.writeBinaryFile. */
  416. writeBytes: function (path, bytes, cb, errcb) {
  417. var b64;
  418. try { b64 = bytesToBase64(bytes); }
  419. catch (e) { if (errcb) errcb("could not encode the file"); return; }
  420. arozos.agirunLarge("Office/common/backend/binsaver.agi", {
  421. filepath: path,
  422. content: b64
  423. }, "content", function () {
  424. if (cb) cb();
  425. }, function (msg) {
  426. if (errcb) errcb(msg);
  427. });
  428. },
  429. /* The suite's own open and save: a .docx / .xlsx / .pptx in the
  430. user's storage becomes the editor envelope and back
  431. (common/backend/document.agi -> office.loadDocument /
  432. office.saveDocument). Pictures stay links both ways - the server
  433. reads and extracts them, so they never cross the network as
  434. base64. */
  435. documentLoad: function (path, cb, errcb) {
  436. if (!isVpath(path)) {
  437. errcb("open documents from your ArozOS storage");
  438. return;
  439. }
  440. arozos.agirun(DOCUMENT_BACKEND, { action: "load", filepath: path, instance: INSTANCE }, function (data) {
  441. if (!data || data.error) {
  442. errcb((data && data.error) || "no response");
  443. return;
  444. }
  445. startKeepAlive();
  446. cb(data.envelope);
  447. }, function () { errcb("cannot reach the ArozOS backend"); }, 120000);
  448. },
  449. documentSave: function (path, envelopeJson, cb, errcb, progress) {
  450. arozos.agirunLarge(DOCUMENT_BACKEND, {
  451. action: "save", filepath: path, content: envelopeJson
  452. }, "content", function () { cb(); }, errcb, 180000, progress);
  453. },
  454. sessionSave: function (app, envelopeJson, cb, errcb) {
  455. arozos.agirunLarge(DOCUMENT_BACKEND, {
  456. action: "session-save", app: app, content: envelopeJson
  457. }, "content", cb || function () { }, errcb || function () { }, 60000);
  458. },
  459. sessionLoad: function (app, cb) {
  460. arozos.agirun(DOCUMENT_BACKEND, { action: "session-load", app: app, instance: INSTANCE },
  461. function (data) {
  462. if (data && data.envelope) startKeepAlive();
  463. cb(data && data.envelope);
  464. },
  465. function () { cb(null); }, 60000);
  466. },
  467. sessionDelete: function (app) {
  468. arozos.agirun(DOCUMENT_BACKEND, { action: "session-delete", app: app },
  469. function () { }, function () { }, 60000);
  470. },
  471. // page-relative form matching what office.loadDocument writes; the
  472. // server reads the file behind it at save time
  473. mediaUrl: function (vpath) {
  474. return "../../media?file=" + encodeURIComponent(vpath);
  475. },
  476. /* Turn a Blob/File into a document-storable src string. Small blobs
  477. stay inline data URLs; anything bigger is streamed to the Office
  478. working directory through the system upload endpoint and
  479. referenced by a media?file= link (the server reads it into the
  480. file at save time). */
  481. blobToSrc: function (blob, filename, cb, errcb) {
  482. if (blob.size <= DATAURL_MAX) {
  483. readAsDataURL(blob, cb, errcb || function (msg) { status(msg, "error"); });
  484. return;
  485. }
  486. arozos.cacheBlob(blob, filename, cb, errcb);
  487. },
  488. /* The same, whatever the size: a render the editor makes for saving
  489. (a chart as PNG, a video's poster frame) is uploaded once and
  490. linked, so it is not sent again with every save. */
  491. cacheBlob: function (blob, filename, cb, errcb) {
  492. errcb = errcb || function (msg) { status(msg, "error"); };
  493. var asDataURL = function (failMsg) {
  494. // inline fallback only for small payloads - big base64 blobs
  495. // would make every save carry them
  496. if (blob.size > 8 * 1024 * 1024) {
  497. errcb(failMsg || "File is too large to embed without an ArozOS backend");
  498. return;
  499. }
  500. readAsDataURL(blob, cb, errcb);
  501. };
  502. if (typeof ao_module_uploadFile !== "function") { asDataURL(); return; }
  503. arozos.prepareWorkdir(function () {
  504. var safe = String(filename || "media").replace(/[^a-zA-Z0-9._-]/g, "_").substring(0, 80);
  505. var name = Date.now().toString(36) + "-" + safe;
  506. var file;
  507. try {
  508. file = new File([blob], name, { type: blob.type || "application/octet-stream" });
  509. } catch (e) { asDataURL(); return; }
  510. ao_module_uploadFile(file, UPLOADS,
  511. function (resp) {
  512. if (typeof resp === "string" && resp.indexOf('"error"') >= 0) {
  513. errcb("Upload failed: " + resp);
  514. return;
  515. }
  516. cb(arozos.mediaUrl(UPLOADS + "/" + name));
  517. },
  518. undefined,
  519. function () { asDataURL("Upload failed and the file is too large to embed"); });
  520. }, function () { asDataURL(); });
  521. },
  522. /* A pasted picture that links into another window's working copies
  523. is copied into this window's own (cb gets the new src, or the old
  524. one when the copy fails - it still works while that window is
  525. open). Anything else is returned as it is. */
  526. adoptSrc: function (src, cb) {
  527. if (!isForeignWorkingCopy(src) || typeof fetch !== "function") { cb(src); return; }
  528. var name = linkVpath(src).split("/").pop() || "picture.png";
  529. fetch(src, { credentials: "same-origin" }).then(function (r) {
  530. if (!r.ok) throw new Error("HTTP " + r.status);
  531. return r.blob();
  532. }).then(function (blob) {
  533. arozos.cacheBlob(blob, name, cb, function () { cb(src); });
  534. }).catch(function () { cb(src); });
  535. },
  536. isForeignWorkingCopy: isForeignWorkingCopy,
  537. loadInputFiles: function (ext) {
  538. // a ?template= / ?open= / ?recent= link is answered the same way
  539. // in both hosts; otherwise ask the desktop what it opened us with
  540. var entry = entryPointFiles(ext);
  541. if (entry) return entry;
  542. try { return ao_module_loadInputFiles(); } catch (e) { return null; }
  543. },
  544. /* Open a document in a second window of this same app - the desktop
  545. launches another floatWindow, a plain browser tab another tab. The
  546. file is handed over the same way the desktop hands one to an
  547. opened-with app: the hash carries the input file list. */
  548. openDocument: function (filepath, filename, opts) {
  549. opts = opts || {};
  550. var hash = "#" + encodeURIComponent(JSON.stringify(
  551. [{ filepath: filepath, filename: filename }]));
  552. try {
  553. ao_module_newfw({
  554. url: pagePath() + hash,
  555. title: filename,
  556. appicon: opts.appIcon ? pageRelative(opts.appIcon) : undefined,
  557. width: opts.width || 1080,
  558. height: opts.height || 700
  559. });
  560. return true;
  561. } catch (e) { return false; }
  562. },
  563. setWindowTitle: function (t) {
  564. try { ao_module_setWindowTitle(t); } catch (e) { document.title = t; }
  565. },
  566. setWindowTheme: function (dark) {
  567. try { ao_module_setWindowTheme(dark ? "dark" : "white"); } catch (e) { }
  568. }
  569. };
  570. /* ================================================================
  571. Standalone host (static hosting, no server)
  572. ================================================================ */
  573. // blobs may be inlined generously here - nothing has to survive a POST
  574. var STANDALONE_INLINE_MAX = 24 * 1024 * 1024;
  575. var SESSION_MAX = 4 * 1024 * 1024; // localStorage is ~5 MB per origin
  576. var localFiles = {}; // "local:/<name>" -> File
  577. var sharedFiles = {}; // "share:/<name>" -> preview URL
  578. function readAsDataURL(blob, cb, errcb) {
  579. var reader = new FileReader();
  580. reader.onload = function () { cb(reader.result); };
  581. reader.onerror = function () { errcb("Could not read the file"); };
  582. reader.readAsDataURL(blob);
  583. }
  584. function readAsText(blob, cb, errcb) {
  585. var reader = new FileReader();
  586. reader.onload = function () { cb(reader.result); };
  587. reader.onerror = function () { errcb("Could not read the file"); };
  588. reader.readAsText(blob);
  589. }
  590. function readAsBytes(blob, cb, errcb) {
  591. var reader = new FileReader();
  592. reader.onload = function () { cb(new Uint8Array(reader.result)); };
  593. reader.onerror = function () { errcb("Could not read the file"); };
  594. reader.readAsArrayBuffer(blob);
  595. }
  596. /* Fetch a document served next to the page. Only relative paths are
  597. accepted: a document is meant to sit in the viewer's own folder, and
  598. refusing absolute URLs keeps ?open= from being turned into a fetch of
  599. somewhere else. */
  600. function fetchRelative(url, responseType, cb, errcb) {
  601. if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url) || url.indexOf("//") === 0) {
  602. errcb("only documents served next to this page can be opened by link");
  603. return;
  604. }
  605. var xhr = new XMLHttpRequest();
  606. xhr.open("GET", url, true);
  607. if (responseType) xhr.responseType = responseType;
  608. xhr.onload = function () {
  609. if (xhr.status >= 200 && xhr.status < 300) {
  610. cb(responseType === "arraybuffer" ? new Uint8Array(xhr.response) : xhr.responseText);
  611. } else {
  612. errcb("HTTP " + xhr.status);
  613. }
  614. };
  615. xhr.onerror = function () { errcb("network error"); };
  616. xhr.send();
  617. }
  618. /* base64 in chunks: String.fromCharCode.apply on a multi-megabyte
  619. array blows the argument limit */
  620. function bytesToBase64(bytes) {
  621. var arr = (bytes instanceof Uint8Array) ? bytes : new Uint8Array(bytes);
  622. var CHUNK = 0x8000;
  623. var parts = [];
  624. for (var i = 0; i < arr.length; i += CHUNK) {
  625. parts.push(String.fromCharCode.apply(null, arr.subarray(i, i + CHUNK)));
  626. }
  627. return btoa(parts.join(""));
  628. }
  629. function download(bytesOrText, filename, mime) {
  630. var blob = (bytesOrText instanceof Uint8Array)
  631. ? new Blob([bytesOrText], { type: mime || "application/octet-stream" })
  632. : new Blob([bytesOrText], { type: (mime || "text/plain") + ";charset=utf-8" });
  633. var url = URL.createObjectURL(blob);
  634. var a = document.createElement("a");
  635. a.href = url;
  636. a.download = filename || "document";
  637. document.body.appendChild(a);
  638. a.click();
  639. document.body.removeChild(a);
  640. setTimeout(function () { URL.revokeObjectURL(url); }, 8000);
  641. }
  642. function acceptFromFilter(filter) {
  643. if (!filter || !filter.length) return "";
  644. return filter.map(function (e) {
  645. return e.charAt(0) === "." ? e : ("." + e);
  646. }).join(",");
  647. }
  648. function sessionKey(app) {
  649. return "officeSession_" + String(app || "app").replace(/[^a-zA-Z0-9_-]/g, "");
  650. }
  651. // a server-only feature reached in standalone mode: say so once, plainly
  652. function noBackend(what) {
  653. toast((what || "That") + " needs an ArozOS server - this is the " +
  654. "standalone web edition", "error");
  655. }
  656. var NO_CONVERTER = "this build has no converter for that format";
  657. var NO_WASM = "this build was made without the Office format code, so it cannot open or save documents";
  658. var RECENT_PREFIX = "recent:/";
  659. var SHARE_PREFIX = "share:/";
  660. /*
  661. A virtual path names something a host owns - "user:/Desktop/a.docx" in
  662. ArozOS, "local:/", "device:/" and "recent:/" in the browser. Anything
  663. else is a plain relative URL served by whatever web server is in front
  664. of the suite, and is read over HTTP. That is what lets templates/
  665. work identically whether or not there is an ArozOS behind the page.
  666. */
  667. function isVpath(p) {
  668. return /^[a-zA-Z][a-zA-Z0-9_+.-]*:\//.test(String(p || ""));
  669. }
  670. /*
  671. Entry points a link (or the home page) can use to point an app at
  672. something, in either host:
  673. ?open=<relative path> open a document published next to the app
  674. ?template=<relative path> start a NEW unsaved document from it, so
  675. Save asks for a name instead of writing
  676. back over the template
  677. ?recent=<id> reopen a document this browser kept
  678. (OfficeRecents)
  679. Relative paths only - fetchRelative refuses anything with a scheme, so
  680. none of these can be turned into a fetch of another site.
  681. The one deliberate exception, standalone only:
  682. ?request=<share link>[&name=<file name>]
  683. open a document from a public ArozOS
  684. share. OfficeShare.parse only accepts a
  685. share path and rewrites it to that
  686. server's preview endpoint, so this is
  687. not a general fetch either. The home
  688. page normally takes these links itself
  689. (it can tell which app a document is
  690. for) and only falls back to sending one
  691. here when it cannot keep the file.
  692. ext is the calling app's own extension; a share link does not carry
  693. the file name, and the document is only opened as one when the name
  694. says it is.
  695. */
  696. function entryPointFiles(ext) {
  697. var q = window.location.search || "";
  698. var param = function (name) {
  699. var m = new RegExp("[?&]" + name + "=([^&]+)").exec(q);
  700. if (!m) return null;
  701. try { return decodeURIComponent(m[1]) || null; } catch (e) { return null; }
  702. };
  703. var recent = param("recent");
  704. if (recent) {
  705. var name = "";
  706. if (window.OfficeRecents) {
  707. OfficeRecents.index().forEach(function (e) {
  708. if (e.id === recent) name = e.name;
  709. });
  710. }
  711. if (!name) return null; // gone from this browser: start blank
  712. return [{ filepath: RECENT_PREFIX + recent, filename: name }];
  713. }
  714. var tpl = param("template");
  715. if (tpl) return [{ filepath: tpl, filename: basename(tpl), asTemplate: true }];
  716. var request = param("request");
  717. if (request && STANDALONE && window.OfficeShare) {
  718. var info;
  719. try { info = OfficeShare.parse(request); }
  720. catch (e) { toast(e.message, "error"); return null; }
  721. var app = NATIVE[ext] ? NATIVE[ext].app : "";
  722. var shareName = OfficeShare.fileName(app, [param("name"), info.nameHint]);
  723. var sharePath = SHARE_PREFIX + shareName;
  724. sharedFiles[sharePath] = info.previewUrl;
  725. return [{ filepath: sharePath, filename: shareName }];
  726. }
  727. var open = param("open");
  728. if (open) return [{ filepath: open, filename: basename(open) }];
  729. return null;
  730. }
  731. /*
  732. The name a document should be written out under. Normally that is the
  733. last path segment - but a document reopened from the recent list has
  734. the path "recent:/<id>", and an id is not a filename: saving one has
  735. to produce "My Report.docx", not "mtm6gu3c-bn7mpk". The recent index
  736. is the only thing that knows, so ask it.
  737. */
  738. function saveName(path) {
  739. if (String(path).indexOf(RECENT_PREFIX) === 0 && window.OfficeRecents) {
  740. var id = String(path).substring(RECENT_PREFIX.length);
  741. var found = "";
  742. OfficeRecents.index().forEach(function (e) {
  743. if (e.id === id) found = e.name;
  744. });
  745. if (found) return found;
  746. }
  747. return basename(path);
  748. }
  749. // read bytes for a path no host owns: a relative URL, or this browser's
  750. // own recent-document store
  751. function readWebBytes(path, cb, errcb) {
  752. if (path.indexOf(RECENT_PREFIX) === 0) {
  753. if (!window.OfficeRecents) { errcb("recent documents are not available here"); return; }
  754. OfficeRecents.load(path.substring(RECENT_PREFIX.length), cb, errcb);
  755. return;
  756. }
  757. if (sharedFiles[path]) {
  758. OfficeShare.fetch(sharedFiles[path], function (bytes) { cb(bytes); }, errcb);
  759. return;
  760. }
  761. fetchRelative(path, "arraybuffer", cb, errcb);
  762. }
  763. function readWebText(path, cb, errcb) {
  764. if (path.indexOf(RECENT_PREFIX) === 0) {
  765. readWebBytes(path, function (bytes) {
  766. cb(new TextDecoder("utf-8").decode(bytes));
  767. }, errcb);
  768. return;
  769. }
  770. fetchRelative(path, "", cb, errcb);
  771. }
  772. // Templates live in the site's own templates/ folder and are scaffolds,
  773. // not the visitor's documents: opening one must not push it into the
  774. // recent list, and Save must ask for a name rather than overwrite it.
  775. function isTemplatePath(path) {
  776. return /(^|\/)templates\//.test(String(path || ""));
  777. }
  778. /*
  779. Keep a copy of the document in this browser so the home page can
  780. offer it again after a reload. Best-effort throughout: recents are a
  781. convenience, and a full quota or a private window must never break
  782. opening or saving.
  783. */
  784. function keepRecent(name, bytes) {
  785. if (!name || !bytes || !window.OfficeRecents || !OfficeRecents.supported()) return;
  786. var app = nativeOf(name) ? nativeOf(name).app : "";
  787. var dot = name.lastIndexOf(".");
  788. OfficeRecents.remember({
  789. name: name,
  790. app: app,
  791. ext: dot < 0 ? "" : name.substring(dot).toLowerCase(),
  792. bytes: bytes
  793. }, function () { }, function () { /* over quota or unavailable: skip */ });
  794. }
  795. var standalone = {
  796. name: "standalone",
  797. hasBackend: false,
  798. // recents point at File objects that die with the page, and autosave
  799. // would mean a download every 25 seconds
  800. tracksRecents: false,
  801. autosavesToFile: false,
  802. // the build ships the WebAssembly module (generate.go always adds it)
  803. canConvert: function () {
  804. return !!(window.OfficeWasm && OfficeWasm.available());
  805. },
  806. /* The converters are the same Go code the AGI backends run, compiled
  807. to WebAssembly (src/wasm/office). The module is a few MB, so it is
  808. fetched the first time a document is opened or saved, not at page
  809. load - the caller's busy overlay covers the wait. */
  810. convertIn: function (spec, srcRef, cb, errcb) {
  811. if (!spec.wasm) { errcb(NO_CONVERTER); return; }
  812. standalone.readBytes(srcRef, function (bytesIn) {
  813. OfficeWasm.runImport(spec.wasm, bytesIn, cb, errcb);
  814. }, function (msg) { errcb("could not read the file: " + msg); });
  815. },
  816. convertOut: function (spec, destRef, bodyJson, cb, errcb) {
  817. if (!spec.wasm) { errcb(NO_CONVERTER); return; }
  818. OfficeWasm.runExport(spec.wasm, bodyJson, function (res) {
  819. var name = saveName(destRef);
  820. try {
  821. download(res.data, name, "application/octet-stream");
  822. } catch (e) {
  823. errcb(e.message || "download failed");
  824. return;
  825. }
  826. cb({ mediaZip: null });
  827. }, errcb);
  828. },
  829. prepareWorkdir: function (cb) { cb(); },
  830. releaseWorkdir: function () { },
  831. adoptSrc: function (src, cb) { cb(src); },
  832. isForeignWorkingCopy: function () { return false; },
  833. agirun: function (script, params, cb, errcb) {
  834. if (errcb) errcb("no ArozOS backend in the standalone web edition");
  835. },
  836. agirunLarge: function (script, params, field, cb, errcb) {
  837. if (errcb) errcb("no ArozOS backend in the standalone web edition");
  838. },
  839. pickOpen: function (opts, cb) {
  840. var input = document.createElement("input");
  841. input.type = "file";
  842. if (opts.multiple) input.multiple = true;
  843. var accept = acceptFromFilter(opts.filter);
  844. if (accept) input.accept = accept;
  845. input.style.display = "none";
  846. document.body.appendChild(input);
  847. input.addEventListener("change", function () {
  848. var picked = Array.prototype.slice.call(input.files || []);
  849. document.body.removeChild(input);
  850. if (!picked.length) return;
  851. cb(picked.map(function (f) {
  852. var p = "local:/" + f.name;
  853. localFiles[p] = f;
  854. return { filepath: p, filename: f.name, file: f };
  855. }));
  856. });
  857. input.click();
  858. },
  859. /*
  860. There is no file system to browse, so "where to save" is just a
  861. name: the write itself is a browser download into whatever the
  862. visitor's browser calls its downloads folder.
  863. */
  864. pickSave: function (opts, cb) {
  865. var def = opts.defaultName || "document";
  866. var ask = function (label, defVal, done) {
  867. if (window.OfficeApp && OfficeApp.prompt) OfficeApp.prompt("Download as", label, defVal, done);
  868. else done(window.prompt(label, defVal));
  869. };
  870. ask("File name", def, function (name) {
  871. if (!name) return;
  872. name = String(name).replace(/[\\/:*?"<>|]/g, "_").trim();
  873. if (!name) return;
  874. if (opts.ext && name.toLowerCase().lastIndexOf(opts.ext.toLowerCase()) !==
  875. name.length - opts.ext.length) {
  876. name += opts.ext;
  877. }
  878. cb({ filepath: "device:/" + name, filename: name });
  879. });
  880. },
  881. readText: function (path, cb, errcb) {
  882. errcb = errcb || function () { };
  883. var f = localFiles[path];
  884. if (f) { readAsText(f, cb, errcb); return; }
  885. readWebText(path, cb, errcb);
  886. },
  887. readBytes: function (path, cb, errcb) {
  888. errcb = errcb || function () { };
  889. var f = localFiles[path];
  890. if (f) { readAsBytes(f, cb, errcb); return; }
  891. readWebBytes(path, cb, errcb);
  892. },
  893. writeText: function (path, content, cb, errcb) {
  894. try {
  895. download(content, saveName(path), "text/plain");
  896. if (cb) cb();
  897. } catch (e) {
  898. if (errcb) errcb(e.message || "download failed");
  899. }
  900. },
  901. writeBytes: function (path, bytes, cb, errcb) {
  902. try {
  903. download(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes),
  904. saveName(path), "application/octet-stream");
  905. if (cb) cb();
  906. } catch (e) {
  907. if (errcb) errcb(e.message || "download failed");
  908. }
  909. },
  910. /* The suite's own open and save, run by the WebAssembly module: the
  911. file's bytes become the envelope (pictures inline as data URLs -
  912. there is no file system to link into) and the envelope becomes the
  913. file, handed over as a download. Both keep a copy in this
  914. browser's recent documents. */
  915. documentLoad: function (path, cb, errcb) {
  916. var name = saveName(path);
  917. var nat = nativeOf(name);
  918. if (!nat) { errcb("not a .docx, .xlsx or .pptx file"); return; }
  919. if (!standalone.canConvert()) { errcb(NO_WASM); return; }
  920. standalone.readBytes(path, function (bytes) {
  921. OfficeWasm.runImport(nat.wasm, bytes, function (envelope) {
  922. // opening a document is what puts it in "recently opened";
  923. // reopening one already there only moves it up the list
  924. if (String(path).indexOf(RECENT_PREFIX) === 0) {
  925. if (window.OfficeRecents) OfficeRecents.touch(path.substring(RECENT_PREFIX.length));
  926. } else if (!isTemplatePath(path)) {
  927. keepRecent(name, bytes);
  928. }
  929. cb(envelope);
  930. }, errcb);
  931. }, function (msg) { errcb("could not read the file: " + msg); });
  932. },
  933. documentSave: function (path, envelopeJson, cb, errcb, progress) {
  934. if (progress) progress("server");
  935. var name = saveName(path);
  936. var nat = nativeOf(name);
  937. if (!nat) { errcb("documents are saved as .docx, .xlsx or .pptx"); return; }
  938. if (!standalone.canConvert()) { errcb(NO_WASM); return; }
  939. OfficeWasm.runExport(nat.wasm, envelopeJson, function (res) {
  940. try {
  941. download(res.data, name, nat.mime);
  942. } catch (e) {
  943. errcb(e.message || "download failed");
  944. return;
  945. }
  946. // a saved document is the one most worth having in recents: the
  947. // download leaves the browser's hands, this copy does not
  948. keepRecent(name, res.data);
  949. cb();
  950. }, errcb);
  951. },
  952. /* The session snapshot is the crash net, so it stays inside the
  953. browser: localStorage, skipped when the document outgrows the
  954. per-origin quota (the plain draft in OfficeApp does the same). */
  955. sessionSave: function (app, envelopeJson, cb) {
  956. try {
  957. if (envelopeJson.length <= SESSION_MAX) {
  958. localStorage.setItem(sessionKey(app), envelopeJson);
  959. }
  960. } catch (e) { /* quota or private mode: the draft still covers us */ }
  961. if (cb) cb();
  962. },
  963. sessionLoad: function (app, cb) {
  964. var raw = null;
  965. try { raw = localStorage.getItem(sessionKey(app)); } catch (e) { }
  966. cb(raw);
  967. },
  968. sessionDelete: function (app) {
  969. try { localStorage.removeItem(sessionKey(app)); } catch (e) { }
  970. },
  971. mediaUrl: function () {
  972. // nothing to link to: the storage pickers are hidden in this mode
  973. return "";
  974. },
  975. blobToSrc: function (blob, filename, cb, errcb) {
  976. standalone.cacheBlob(blob, filename, cb, errcb);
  977. },
  978. // nowhere to upload to: a render made for saving stays inline
  979. cacheBlob: function (blob, filename, cb, errcb) {
  980. errcb = errcb || function (msg) { status(msg, "error"); };
  981. if (blob.size > STANDALONE_INLINE_MAX) {
  982. errcb("File is too large for the standalone web edition (max " +
  983. Math.round(STANDALONE_INLINE_MAX / 1048576) + " MB)");
  984. return;
  985. }
  986. readAsDataURL(blob, cb, errcb);
  987. },
  988. loadInputFiles: entryPointFiles,
  989. setWindowTitle: function (t) { document.title = t; },
  990. setWindowTheme: function () { },
  991. /* Saving here is a download, so there is no path a second window
  992. could be pointed at - the caller says so instead. */
  993. openDocument: function () { return false; },
  994. /* A File that arrived by drag and drop rather than through a picker:
  995. register it the same way pickOpen does, then hand the caller the
  996. path it now answers to. */
  997. adoptDroppedFile: function (file, cb) {
  998. var p = "local:/" + file.name;
  999. localFiles[p] = file;
  1000. cb(p, file.name);
  1001. }
  1002. };
  1003. /* ================================================================
  1004. Native host (the standalone build inside a desktop shell)
  1005. ================================================================ */
  1006. /*
  1007. Everything the web edition does still holds here - the converters
  1008. are the same WebAssembly module, templates are fetched next to the
  1009. page, the crash snapshot stays in localStorage - except that files
  1010. are real files: the pickers are the system's own dialogs, and a
  1011. "native:/<handle>/<name>" path survives a reload and a relaunch, so
  1012. Save writes back in place and autosave and recents come back.
  1013. The shell keeps its own recent list (the home page and the system's
  1014. Open Recent menu read it): it notes a document whenever one is read
  1015. or written, so nothing here has to.
  1016. */
  1017. function isNativePath(p) {
  1018. return !!(window.OfficeNative && OfficeNative.isNativePath(p));
  1019. }
  1020. function nativeFail(errcb) {
  1021. return function (e) { if (errcb) errcb((e && e.message) || String(e)); };
  1022. }
  1023. function nativeReadBytes(path, cb, errcb) {
  1024. if (!isNativePath(path)) { standalone.readBytes(path, cb, errcb); return; }
  1025. OfficeNative.read(path).then(cb, nativeFail(errcb));
  1026. }
  1027. /* Write to a file the person chose. A path that is no file on disk (a
  1028. template, a shared link, a dropped file the shell could not place)
  1029. has nowhere to be written back to, so the Save dialog asks where -
  1030. what the web edition's download stands in for. A cancelled dialog is
  1031. reported as a failure: the caller is waiting for one or the other. */
  1032. function nativeWrite(path, data, cb, errcb) {
  1033. var fail = nativeFail(errcb);
  1034. var put = function (target) {
  1035. OfficeNative.write(target, data).then(function () { if (cb) cb(); }, fail);
  1036. };
  1037. if (isNativePath(path)) { put(path); return; }
  1038. var name = saveName(path);
  1039. OfficeNative.pickSave({ name: name, ext: extOf(name) }).then(function (f) {
  1040. if (f) put(f.path);
  1041. else fail(new Error("cancelled"));
  1042. }, fail);
  1043. }
  1044. // what the shell shows for this window: the dot in the close button and
  1045. // the file behind the title's proxy icon
  1046. function nativeWindowState() {
  1047. var app = window.OfficeApp;
  1048. return {
  1049. edited: !!(app && app.isDirty && app.isDirty()),
  1050. path: (app && app.getFilePath && app.getFilePath()) || ""
  1051. };
  1052. }
  1053. var nativeShell = {
  1054. name: "native",
  1055. hasBackend: false,
  1056. tracksRecents: true,
  1057. autosavesToFile: true,
  1058. // a desktop app opens another document in a window of its own
  1059. prefersNewWindows: true,
  1060. canConvert: standalone.canConvert,
  1061. convertIn: function (spec, srcRef, cb, errcb) {
  1062. if (!spec.wasm) { errcb(NO_CONVERTER); return; }
  1063. nativeReadBytes(srcRef, function (bytesIn) {
  1064. OfficeWasm.runImport(spec.wasm, bytesIn, cb, errcb);
  1065. }, function (msg) { errcb("could not read the file: " + msg); });
  1066. },
  1067. convertOut: function (spec, destRef, bodyJson, cb, errcb) {
  1068. if (!spec.wasm) { errcb(NO_CONVERTER); return; }
  1069. OfficeWasm.runExport(spec.wasm, bodyJson, function (res) {
  1070. nativeWrite(destRef, res.data, function () { cb({ mediaZip: null }); }, errcb);
  1071. }, errcb);
  1072. },
  1073. prepareWorkdir: standalone.prepareWorkdir,
  1074. releaseWorkdir: standalone.releaseWorkdir,
  1075. agirun: standalone.agirun,
  1076. agirunLarge: standalone.agirunLarge,
  1077. pickOpen: function (opts, cb) {
  1078. OfficeNative.pickOpen({ exts: opts.filter, multiple: !!opts.multiple }).then(function (files) {
  1079. if (!files.length) return;
  1080. cb(files.map(function (f) { return { filepath: f.path, filename: f.name }; }));
  1081. }, function (e) { toast("Could not show the Open dialog: " + e.message, "error"); });
  1082. },
  1083. pickSave: function (opts, cb) {
  1084. OfficeNative.pickSave({
  1085. name: opts.defaultName || "document",
  1086. ext: opts.ext || "",
  1087. near: nativeWindowState().path
  1088. }).then(function (f) {
  1089. if (f) cb({ filepath: f.path, filename: f.name });
  1090. }, function (e) { toast("Could not show the Save dialog: " + e.message, "error"); });
  1091. },
  1092. readText: function (path, cb, errcb) {
  1093. errcb = errcb || function () { };
  1094. if (!isNativePath(path)) { standalone.readText(path, cb, errcb); return; }
  1095. nativeReadBytes(path, function (bytes) {
  1096. cb(new TextDecoder("utf-8").decode(bytes));
  1097. }, errcb);
  1098. },
  1099. readBytes: function (path, cb, errcb) {
  1100. nativeReadBytes(path, cb, errcb || function () { });
  1101. },
  1102. writeText: function (path, content, cb, errcb) {
  1103. nativeWrite(path, String(content), cb, errcb);
  1104. },
  1105. writeBytes: function (path, bytes, cb, errcb) {
  1106. nativeWrite(path, bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), cb, errcb);
  1107. },
  1108. documentLoad: function (path, cb, errcb) {
  1109. var nat = nativeOf(saveName(path));
  1110. if (!nat) { errcb("not a .docx, .xlsx or .pptx file"); return; }
  1111. if (!nativeShell.canConvert()) { errcb(NO_WASM); return; }
  1112. nativeReadBytes(path, function (bytes) {
  1113. OfficeWasm.runImport(nat.wasm, bytes, cb, errcb);
  1114. }, function (msg) { errcb("could not read the file: " + msg); });
  1115. },
  1116. documentSave: function (path, envelopeJson, cb, errcb, progress) {
  1117. if (progress) progress("server");
  1118. var nat = nativeOf(saveName(path));
  1119. if (!nat) { errcb("documents are saved as .docx, .xlsx or .pptx"); return; }
  1120. if (!nativeShell.canConvert()) { errcb(NO_WASM); return; }
  1121. OfficeWasm.runExport(nat.wasm, envelopeJson, function (res) {
  1122. nativeWrite(path, res.data, cb, errcb);
  1123. }, errcb);
  1124. },
  1125. sessionSave: standalone.sessionSave,
  1126. sessionLoad: standalone.sessionLoad,
  1127. sessionDelete: standalone.sessionDelete,
  1128. // pictures stay inline, as in the web edition: there is no server
  1129. // to link them to, and the file on disk carries them anyway
  1130. mediaUrl: standalone.mediaUrl,
  1131. blobToSrc: standalone.blobToSrc,
  1132. cacheBlob: standalone.cacheBlob,
  1133. adoptSrc: standalone.adoptSrc,
  1134. isForeignWorkingCopy: standalone.isForeignWorkingCopy,
  1135. loadInputFiles: entryPointFiles,
  1136. openDocument: function (filepath) {
  1137. if (!isNativePath(filepath)) return false;
  1138. OfficeNative.openWindow({ path: filepath });
  1139. return true;
  1140. },
  1141. // a new, empty document of this app in a window of its own
  1142. openNewWindow: function () {
  1143. OfficeNative.openWindow({ url: window.location.pathname });
  1144. return true;
  1145. },
  1146. // the system print panel is asynchronous: done once it is finished
  1147. // with the page, so the app keeps its print layout up until then
  1148. print: function (done) {
  1149. OfficeNative.print().then(done, done);
  1150. },
  1151. setWindowTitle: function (t) {
  1152. // the shell shows "edited" as the dot in the close button
  1153. document.title = String(t).replace(" •", "");
  1154. OfficeNative.windowInfo(nativeWindowState());
  1155. },
  1156. setWindowTheme: function (dark) { OfficeNative.setTheme(dark); },
  1157. // the shell opens dropped documents itself (with their real path);
  1158. // a File that still reaches the page is held like the web edition's
  1159. adoptDroppedFile: standalone.adoptDroppedFile
  1160. };
  1161. /* ================================================================
  1162. Chosen host
  1163. ================================================================ */
  1164. var host = !STANDALONE ? arozos :
  1165. (window.OfficeNative && OfficeNative.available()) ? nativeShell : standalone;
  1166. // Uniform "this needs a server" guard for the apps' menu entries: they
  1167. // gate on hasBackend() so the item is absent rather than failing late.
  1168. function requireBackend(what) {
  1169. if (host.hasBackend) return true;
  1170. noBackend(what);
  1171. return false;
  1172. }
  1173. /* The matching guard for the Office interchange formats. A standalone
  1174. build made without -wasm has no converters at all, which is a
  1175. different thing from having no server - so it says so differently. */
  1176. function requireConvert(what) {
  1177. if (host.canConvert()) return true;
  1178. toast((what || "That") + " needs the Office format converters, which " +
  1179. "this build does not include", "error");
  1180. return false;
  1181. }
  1182. return {
  1183. mode: function () { return host.name; },
  1184. isStandalone: function () { return !host.hasBackend; },
  1185. hasBackend: function () { return host.hasBackend; },
  1186. canConvert: function () { return host.canConvert(); },
  1187. tracksRecents: function () { return host.tracksRecents; },
  1188. autosavesToFile: function () { return host.autosavesToFile; },
  1189. requireBackend: requireBackend,
  1190. requireConvert: requireConvert,
  1191. /* Foreign formats (ODF), whichever host is running.
  1192. spec = { agi: "<backend .agi path>", action: "<agi action>",
  1193. wasm: "<converter name from src/wasm/office>" }
  1194. convertIn -> cb(bodyJsonString)
  1195. convertOut -> cb({mediaZip: <name or null>}) */
  1196. convertIn: function (spec, srcRef, cb, errcb) {
  1197. host.convertIn(spec, srcRef, cb, errcb || function () { });
  1198. },
  1199. convertOut: function (spec, destRef, bodyJson, cb, errcb) {
  1200. host.convertOut(spec, destRef, bodyJson, cb, errcb || function () { });
  1201. },
  1202. pickOpen: function (o, cb) { host.pickOpen(o || {}, cb); },
  1203. pickSave: function (o, cb) { host.pickSave(o || {}, cb); },
  1204. readText: function (p, cb, errcb) { host.readText(p, cb, errcb); },
  1205. // a file's bytes, as a Uint8Array (a PDF the client converts itself)
  1206. readBytes: function (p, cb, errcb) { host.readBytes(p, cb, errcb || function () { }); },
  1207. writeText: function (p, c, cb, errcb) { host.writeText(p, c, cb, errcb); },
  1208. // a file the client rendered itself (the Slides PDF); bytes is a
  1209. // Uint8Array, and the standalone host turns it into a download
  1210. writeBytes: function (p, b, cb, errcb) { host.writeBytes(p, b, cb, errcb); },
  1211. // the suite's own .docx / .xlsx / .pptx: file <-> envelope JSON
  1212. documentLoad: function (p, cb, errcb) { host.documentLoad(p, cb, errcb || function () { }); },
  1213. documentSave: function (p, j, cb, errcb, progress) { host.documentSave(p, j, cb, errcb || function () { }, progress); },
  1214. nativeExtension: extForApp,
  1215. sessionSave: function (a, j, cb, errcb) { host.sessionSave(a, j, cb, errcb); },
  1216. sessionLoad: function (a, cb) { host.sessionLoad(a, cb); },
  1217. sessionDelete: function (a) { host.sessionDelete(a); },
  1218. agirun: function (s, p, cb, errcb, t) { host.agirun(s, p, cb, errcb, t); },
  1219. agirunLarge: function (s, p, f, cb, errcb, t, progress) { host.agirunLarge(s, p, f, cb, errcb, t, progress); },
  1220. prepareWorkdir: function (cb, errcb) { host.prepareWorkdir(cb, errcb); },
  1221. // the window is closing for good: drop its working copies
  1222. releaseWorkdir: function () { host.releaseWorkdir(); },
  1223. // a pasted picture from another window becomes this window's own
  1224. adoptSrc: function (src, cb) { host.adoptSrc(src, cb); },
  1225. isForeignWorkingCopy: function (src) { return host.isForeignWorkingCopy(src); },
  1226. mediaUrl: function (v) { return host.mediaUrl(v); },
  1227. blobToSrc: function (b, n, cb, errcb) { host.blobToSrc(b, n, cb, errcb); },
  1228. // a render made for saving (chart PNG, poster frame): a link in
  1229. // ArozOS, so later saves do not carry it again
  1230. cacheBlob: function (b, n, cb, errcb) { host.cacheBlob(b, n, cb, errcb); },
  1231. // ext: the calling app's native extension, which names a document
  1232. // opened from a share link that did not say what it is called
  1233. loadInputFiles: function (ext) { return host.loadInputFiles(ext); },
  1234. // open a document in a second window of this app; false = this host
  1235. // has nowhere to open it from (the standalone build saves by download)
  1236. openDocument: function (fp, fn, o) { return !!host.openDocument(fp, fn, o || {}); },
  1237. // true where another document belongs in a window of its own rather
  1238. // than in place of this one (a desktop app, not a browser tab)
  1239. prefersNewWindows: function () { return !!host.prefersNewWindows; },
  1240. // a new, empty document of this app in another window; false = this
  1241. // host has no such thing, so the caller starts one in place
  1242. openNewWindow: function () { return !!(host.openNewWindow && host.openNewWindow()); },
  1243. // print the page; done() once the print dialog is finished with it,
  1244. // which the browser's window.print() already is when it returns
  1245. print: function (done) {
  1246. done = done || function () { };
  1247. if (host.print) { host.print(done); return; }
  1248. window.print();
  1249. done();
  1250. },
  1251. adoptDroppedFile: function (f, cb) {
  1252. if (host.adoptDroppedFile) host.adoptDroppedFile(f, cb);
  1253. },
  1254. setWindowTitle: function (t) { host.setWindowTitle(t); },
  1255. setWindowTheme: function (d) { host.setWindowTheme(d); }
  1256. };
  1257. })();