native.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. OfficeNative - the bridge to a native desktop shell
  3. ===================================================
  4. A desktop shell (apps/ArozOS Office Mac: a Cocoa window around a
  5. WKWebView, serving the standalone build from 127.0.0.1) runs the suite
  6. as a real desktop application. It announces itself by defining
  7. window.OFFICE_NATIVE before any page script runs:
  8. { platform: "macos", version: "1.0.0",
  9. token: "<per-launch secret>", window: <window id> }
  10. and answers on the page's own origin under /__native/. Every request
  11. carries the token (X-Office-Token) and the window it comes from
  12. (X-Office-Window); the shell refuses anything else, so another page or
  13. program on this machine cannot drive it.
  14. Files are capabilities, not paths. The page never names a file on disk:
  15. the shell hands out "native:/<handle>/<name>" for a file the person
  16. picked in a system dialog, opened from Finder or dropped on a window,
  17. and only those can be read or written. Script that a hostile document
  18. managed to run in the editor still could not reach anything else.
  19. Endpoints (JSON in and out unless noted; errors are {error} with a
  20. non-2xx status):
  21. POST pick-open {exts:[".docx"], multiple} -> {files:[{path,name}]}
  22. POST pick-save {name, ext, near} -> {path,name} | {cancelled:true}
  23. GET file?path=<p> -> the file's bytes
  24. PUT file?path=<p> <- the file's bytes, written atomically
  25. POST recents -> {items:[{path,name,app,ext,folder,at}]}
  26. POST recents/forget {path}
  27. POST window {action, ...} where action is
  28. open {path} or {url}: another window
  29. close this window, now (the page has agreed)
  30. close-cancelled the person kept the window
  31. info {edited, path, seq}: close-button dot,
  32. proxy icon (the newest seq wins)
  33. theme {theme: "light" | "dark" | "system"}
  34. print the system print panel (answers when done)
  35. reveal {path}: show the file in Finder
  36. The shell calls into the page through two functions:
  37. OfficeNative.requestClose() the window's close button. true = close
  38. now; false = the page is asking the
  39. person and will answer with close or
  40. close-cancelled
  41. OfficeNative.menu(name) an item of the system menu bar that the
  42. page carries out (save, saveAs, print,
  43. undo, redo)
  44. Without a shell (ArozOS, the web edition) available() is false and
  45. nothing here does anything: platform.js only picks its native host
  46. when it is true.
  47. Load order: mode.js, native.js, ... platform.js.
  48. */
  49. var OfficeNative = (function () {
  50. "use strict";
  51. var cfg = window.OFFICE_NATIVE || null;
  52. var PREFIX = "native:/";
  53. var BASE = "/__native/";
  54. function available() {
  55. return !!(cfg && typeof cfg.token === "string" && cfg.token.length > 0 &&
  56. typeof window.fetch === "function");
  57. }
  58. function isNativePath(p) { return String(p || "").indexOf(PREFIX) === 0; }
  59. /* ---------- transport ---------- */
  60. function headers(extra) {
  61. var h = {
  62. "X-Office-Token": cfg.token,
  63. "X-Office-Window": String(cfg.window || 0)
  64. };
  65. Object.keys(extra || {}).forEach(function (k) { h[k] = extra[k]; });
  66. return h;
  67. }
  68. function failure(res) {
  69. return res.text().then(function (t) {
  70. var msg = "HTTP " + res.status;
  71. try {
  72. var o = JSON.parse(t);
  73. if (o && o.error) msg = o.error;
  74. } catch (e) { if (t) msg = t; }
  75. throw new Error(msg);
  76. });
  77. }
  78. function call(endpoint, payload) {
  79. if (!available()) return Promise.reject(new Error("no native shell"));
  80. return fetch(BASE + endpoint, {
  81. method: "POST",
  82. headers: headers({ "Content-Type": "application/json" }),
  83. body: JSON.stringify(payload || {}),
  84. cache: "no-store"
  85. }).then(function (res) {
  86. if (!res.ok) return failure(res);
  87. return res.json();
  88. });
  89. }
  90. function fileUrl(path) { return BASE + "file?path=" + encodeURIComponent(path); }
  91. // ".docx" and "docx" both appear in the suite's filters
  92. function normExts(list) {
  93. return (list || []).map(function (e) {
  94. e = String(e).toLowerCase();
  95. return e.charAt(0) === "." ? e : "." + e;
  96. });
  97. }
  98. /* ---------- files ---------- */
  99. function read(path) {
  100. if (!available()) return Promise.reject(new Error("no native shell"));
  101. return fetch(fileUrl(path), { headers: headers(), cache: "no-store" }).then(function (res) {
  102. if (!res.ok) return failure(res);
  103. return res.arrayBuffer();
  104. }).then(function (buf) { return new Uint8Array(buf); });
  105. }
  106. // data: a Uint8Array, or a string (written as UTF-8)
  107. function write(path, data) {
  108. if (!available()) return Promise.reject(new Error("no native shell"));
  109. return fetch(fileUrl(path), {
  110. method: "PUT",
  111. headers: headers({ "Content-Type": "application/octet-stream" }),
  112. body: data,
  113. cache: "no-store"
  114. }).then(function (res) {
  115. if (!res.ok) return failure(res);
  116. return res.json();
  117. });
  118. }
  119. // -> [{path, name}], empty when the person cancelled
  120. function pickOpen(opts) {
  121. opts = opts || {};
  122. return call("pick-open", {
  123. exts: normExts(opts.exts),
  124. multiple: !!opts.multiple
  125. }).then(function (r) { return (r && r.files) || []; });
  126. }
  127. // -> {path, name}, or null when the person cancelled. near: a native
  128. // path whose folder the dialog starts in
  129. function pickSave(opts) {
  130. opts = opts || {};
  131. return call("pick-save", {
  132. name: opts.name || "",
  133. ext: opts.ext || "",
  134. near: isNativePath(opts.near) ? opts.near : ""
  135. }).then(function (r) { return (r && r.path) ? r : null; });
  136. }
  137. function recents() {
  138. return call("recents").then(function (r) { return (r && r.items) || []; });
  139. }
  140. function forgetRecent(path) { return call("recents/forget", { path: path }); }
  141. /* ---------- the window ---------- */
  142. function windowAction(action, extra) {
  143. var p = extra || {};
  144. p.action = action;
  145. return call("window", p);
  146. }
  147. // {path: native path} opens that document; {url: page path} opens a page
  148. function openWindow(target) {
  149. target = target || {};
  150. return windowAction("open", { path: target.path || "", url: target.url || "" });
  151. }
  152. function closeWindow() { return windowAction("close"); }
  153. /* Each update is its own request, and requests can overtake each
  154. other: seq orders them (the shell keeps the newest), and it grows
  155. across page loads in the window too. */
  156. var infoCount = 0;
  157. function windowInfo(info) {
  158. info = info || {};
  159. infoCount = (infoCount + 1) % 1000;
  160. return windowAction("info", {
  161. edited: !!info.edited,
  162. path: isNativePath(info.path) ? info.path : "",
  163. seq: Date.now() * 1000 + infoCount
  164. });
  165. }
  166. // dark: true / false, or null to follow the system
  167. function setTheme(dark) {
  168. return windowAction("theme", { theme: dark === null ? "system" : (dark ? "dark" : "light") });
  169. }
  170. // resolves once the print panel is finished with the page
  171. function print() { return windowAction("print"); }
  172. function reveal(path) { return windowAction("reveal", { path: path }); }
  173. /* ---------- the shell calling in ---------- */
  174. var closing = false;
  175. function requestClose() {
  176. var app = window.OfficeApp;
  177. if (!app || typeof app.requestClose !== "function") return true;
  178. if (typeof app.isDirty === "function" && !app.isDirty()) return true;
  179. // the close button again while the question is up: keep asking once
  180. if (closing) return false;
  181. closing = true;
  182. app.requestClose(function () {
  183. closing = false;
  184. closeWindow();
  185. }, function () {
  186. closing = false;
  187. windowAction("close-cancelled");
  188. });
  189. return false;
  190. }
  191. /* A key combination the page's own shortcuts answer (OfficeHotkeys),
  192. for menu items whose command lives in the app rather than in
  193. OfficeApp: the same handler runs whether the person pressed the keys
  194. or picked the menu item. Falls back to the browser's command when no
  195. handler claimed it (a plain text field's own undo). */
  196. function sendKey(key, shift, fallback) {
  197. var target = document.activeElement || document.body;
  198. var ev;
  199. try {
  200. ev = new KeyboardEvent("keydown", {
  201. key: key, code: "Key" + key.toUpperCase(), metaKey: true,
  202. shiftKey: !!shift, bubbles: true, cancelable: true
  203. });
  204. } catch (e) { return false; }
  205. if (target.dispatchEvent(ev) && fallback) {
  206. try { document.execCommand(fallback); } catch (e) { }
  207. }
  208. return true;
  209. }
  210. function menu(name) {
  211. var app = window.OfficeApp;
  212. switch (name) {
  213. case "save":
  214. if (app && app.save) { app.save(); return true; }
  215. return false;
  216. case "saveAs":
  217. if (app && app.saveAs) { app.saveAs(); return true; }
  218. return false;
  219. case "print":
  220. if (app && app.print) { app.print(); return true; }
  221. window.print();
  222. return true;
  223. case "undo":
  224. return sendKey("z", false, "undo");
  225. case "redo":
  226. return sendKey("z", true, "redo");
  227. }
  228. return false;
  229. }
  230. /* window.print() does nothing in a WKWebView: hand it to the shell's
  231. print panel. OfficeApp prints through OfficePlatform.print, which
  232. waits for the panel; this only catches a direct call. */
  233. if (available()) {
  234. window.print = function () { print(); };
  235. }
  236. return {
  237. available: available,
  238. platform: function () { return cfg ? cfg.platform || "" : ""; },
  239. isNativePath: isNativePath,
  240. read: read,
  241. write: write,
  242. pickOpen: pickOpen,
  243. pickSave: pickSave,
  244. recents: recents,
  245. forgetRecent: forgetRecent,
  246. openWindow: openWindow,
  247. closeWindow: closeWindow,
  248. windowInfo: windowInfo,
  249. setTheme: setTheme,
  250. print: print,
  251. reveal: reveal,
  252. requestClose: requestClose,
  253. menu: menu
  254. };
  255. })();