office.js 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354
  1. /*
  2. ArozOS Office Suite - shared application framework
  3. ====================================================
  4. Shared by Docs, Sheets and Slides. Provides:
  5. - Document lifecycle: New / Open / Save / Save As in the app's own
  6. Office format (.docx / .xlsx / .pptx), foreign formats (ODF, text),
  7. the JSON envelope the editors hold, file version metadata
  8. - Auto-save, crash-recovery drafts (localStorage), recent documents
  9. - Menubar + statusbar chrome, dialogs, toasts, context menus
  10. - Keyboard shortcut registry, undo/redo bindings
  11. - Light/dark theme (shared across the suite), zoom controls, print
  12. Requires (include before this file):
  13. ../../script/jquery.min.js
  14. ../../script/ao_module.js
  15. ../common/mode.js
  16. ../common/recents.js
  17. ../common/wasm.js
  18. ../common/platform.js
  19. ../common/office.css
  20. Everything that reaches outside the browser tab - file dialogs, reading
  21. and writing documents, session snapshots, AGI calls - goes through
  22. OfficePlatform (common/platform.js), which is what
  23. lets the same source run both as an ArozOS webapp and as the standalone
  24. static-hosting build.
  25. Usage: see Office/common/CONTRACT.md for the full API reference.
  26. */
  27. /* ================= Undo stack ================= */
  28. /*
  29. Generic snapshot-based undo/redo helper.
  30. var undo = new OfficeUndoStack({
  31. limit: 100,
  32. apply: function(state){ ...restore editor from state... }
  33. });
  34. undo.init(initialState);
  35. undo.push(state); // record a new state (call after a change)
  36. undo.pushDebounced(fn, ms); // coalesce rapid changes; fn() returns state
  37. undo.undo(); undo.redo(); // calls apply() with the target state
  38. undo.canUndo(); undo.canRedo();
  39. undo.reset(initialState);
  40. */
  41. function OfficeUndoStack(opts) {
  42. opts = opts || {};
  43. this.limit = opts.limit || 100;
  44. this.applyFn = opts.apply || function () {};
  45. this.stack = [];
  46. this.pos = -1;
  47. this._debTimer = null;
  48. }
  49. OfficeUndoStack.prototype.init = function (state) {
  50. this.stack = [state];
  51. this.pos = 0;
  52. };
  53. OfficeUndoStack.prototype.reset = OfficeUndoStack.prototype.init;
  54. OfficeUndoStack.prototype.push = function (state) {
  55. if (this.pos >= 0) {
  56. var cur = this.stack[this.pos];
  57. if (typeof cur === "string" && typeof state === "string" && cur === state) return;
  58. try {
  59. if (typeof cur === "object" && JSON.stringify(cur) === JSON.stringify(state)) return;
  60. } catch (e) { /* non-serializable state, push anyway */ }
  61. }
  62. this.stack = this.stack.slice(0, this.pos + 1);
  63. this.stack.push(state);
  64. if (this.stack.length > this.limit) this.stack.shift();
  65. this.pos = this.stack.length - 1;
  66. };
  67. OfficeUndoStack.prototype.pushDebounced = function (stateFn, ms) {
  68. var that = this;
  69. clearTimeout(this._debTimer);
  70. this._debTimer = setTimeout(function () {
  71. that.push(stateFn());
  72. }, ms || 400);
  73. };
  74. OfficeUndoStack.prototype.flushDebounced = function (stateFn) {
  75. if (this._debTimer) {
  76. clearTimeout(this._debTimer);
  77. this._debTimer = null;
  78. this.push(stateFn());
  79. }
  80. };
  81. OfficeUndoStack.prototype.canUndo = function () { return this.pos > 0; };
  82. OfficeUndoStack.prototype.canRedo = function () { return this.pos < this.stack.length - 1; };
  83. OfficeUndoStack.prototype.undo = function () {
  84. if (!this.canUndo()) return false;
  85. this.pos--;
  86. this.applyFn(this.stack[this.pos]);
  87. return true;
  88. };
  89. OfficeUndoStack.prototype.redo = function () {
  90. if (!this.canRedo()) return false;
  91. this.pos++;
  92. this.applyFn(this.stack[this.pos]);
  93. return true;
  94. };
  95. /* ================= OfficeApp ================= */
  96. var OfficeApp = (function () {
  97. var cfg = null;
  98. var filepath = null; // virtual path of the open file, null = unsaved
  99. var filename = null; // display name (with extension)
  100. var dirty = false;
  101. var meta = null; // envelope meta of the open document
  102. var zoom = 100;
  103. var shortcuts = {}; // normalized combo -> handler
  104. var statusTimer = null;
  105. var draftTimer = null;
  106. var autosaveTimer = null;
  107. var loadedFromImport = false;
  108. // the file a read-only import came from (a .doc opened in Docs): the
  109. // title shows it until the document is saved somewhere of its own,
  110. // while filename holds the name Save suggests in the app's format
  111. var sourceName = null;
  112. // saving is asynchronous (the app prepares the document, then it
  113. // travels): one write at a time, and an edit made while it is under way
  114. // keeps the document dirty
  115. var editSeq = 0; // bumped by every markDirty
  116. var saveBusy = false;
  117. var queuedSave = null; // {fp, fn, cb} asked for while a save was running
  118. var ENVELOPE_TYPE = "arozos/office";
  119. var GENERATOR = "ArozOS Office/1.0";
  120. var DRAFT_MAX_AGE = 7 * 24 * 3600 * 1000; // prune drafts older than 7 days
  121. var DRAFT_MAX_SIZE = 4 * 1024 * 1024; // skip drafts over 4 MB
  122. var AUTOSAVE_INTERVAL = 25 * 1000;
  123. var RECENT_MAX = 10;
  124. /* ---------- small utils ---------- */
  125. function escapeHtml(t) {
  126. if (t === undefined || t === null) return "";
  127. return String(t).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
  128. .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
  129. }
  130. function basename(p) {
  131. if (!p) return "";
  132. var s = String(p).replace(/\\/g, "/");
  133. return s.substring(s.lastIndexOf("/") + 1);
  134. }
  135. function dirname(p) {
  136. if (!p) return "";
  137. var s = String(p).replace(/\\/g, "/");
  138. return s.substring(0, s.lastIndexOf("/"));
  139. }
  140. function extOf(p) {
  141. var b = basename(p);
  142. var i = b.lastIndexOf(".");
  143. return i < 0 ? "" : b.substring(i).toLowerCase();
  144. }
  145. function stripExt(p) {
  146. var i = String(p).lastIndexOf(".");
  147. return i < 0 ? String(p) : String(p).substring(0, i);
  148. }
  149. function now() { return new Date().getTime(); }
  150. // "meeting-notes" -> "Meeting Notes": template file names become the
  151. // suggested document name, so they should read like one
  152. function titleCase(s) {
  153. return String(s || "").replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim()
  154. .replace(/\b[a-z]/g, function (c) { return c.toUpperCase(); });
  155. }
  156. function lsKey(k) { return "office_" + (cfg ? cfg.appType : "generic") + "_" + k; }
  157. function getSetting(k, def) {
  158. try {
  159. var v = localStorage.getItem(lsKey(k));
  160. return v === null ? def : JSON.parse(v);
  161. } catch (e) { return def; }
  162. }
  163. function setSetting(k, v) {
  164. try { localStorage.setItem(lsKey(k), JSON.stringify(v)); } catch (e) { }
  165. }
  166. /* ---------- host bridge (see common/platform.js) ----------
  167. These stay on OfficeApp because the whole suite already calls them
  168. through it; the implementation - ArozOS virtual file system and AGI
  169. gateway, or the visitor's own device - lives in OfficePlatform. */
  170. function vfsLoad(path, cb, errcb) { OfficePlatform.readText(path, cb, errcb); }
  171. function vfsSave(path, content, cb, errcb) { OfficePlatform.writeText(path, content, cb, errcb); }
  172. function mediaUrl(vpath) { return OfficePlatform.mediaUrl(vpath); }
  173. function blobToSrc(blob, filename, cb, errcb) {
  174. OfficePlatform.blobToSrc(blob, filename, cb, errcb);
  175. }
  176. function agirunLarge(script, params, field, cb, errcb, timeout) {
  177. OfficePlatform.agirunLarge(script, params, field, cb, errcb, timeout);
  178. }
  179. /* ---------- session snapshots ("Restore from previous session") ---------- */
  180. function saveSession() {
  181. if (!cfg) return;
  182. var env;
  183. try { env = buildEnvelopeNoBump(); } catch (e) { return; }
  184. // annotate a COPY of meta - session bookkeeping must not leak into
  185. // the real document file
  186. var m = {};
  187. Object.keys(env.meta || {}).forEach(function (k) { m[k] = env.meta[k]; });
  188. m._sessionAt = now();
  189. m._origin = filepath ? { fp: filepath, fn: filename } : null;
  190. env.meta = m;
  191. OfficePlatform.sessionSave(cfg.appType, JSON.stringify(env));
  192. }
  193. // drop the saved session snapshot so it stops prompting on next launch
  194. function deleteSession() {
  195. if (!cfg) return;
  196. OfficePlatform.sessionDelete(cfg.appType);
  197. }
  198. function trySessionRestore() {
  199. OfficePlatform.sessionLoad(cfg.appType, function (envelope) {
  200. var env = envelope;
  201. if (typeof env === "string") {
  202. try { env = JSON.parse(env); } catch (e) { env = null; }
  203. }
  204. if (!env || env.type !== ENVELOPE_TYPE || env.app !== cfg.appType || !env.body) {
  205. checkDraft();
  206. return;
  207. }
  208. var m = env.meta || {};
  209. var when = m._sessionAt ? new Date(m._sessionAt).toLocaleString() : "an earlier session";
  210. var what = m._origin && m._origin.fn ? escapeHtml(m._origin.fn) : "an unsaved document";
  211. var restore = function () {
  212. var origin = m._origin;
  213. delete m._sessionAt;
  214. delete m._origin;
  215. meta = m;
  216. sourceName = null;
  217. if (origin && origin.fp) {
  218. filepath = origin.fp;
  219. filename = origin.fn;
  220. }
  221. cfg.deserialize(env.body);
  222. markDirty();
  223. updateTitle();
  224. setStatus("Previous session restored - remember to save");
  225. };
  226. dialog({
  227. title: "Restore from previous session?",
  228. body: "You were working on <b>" + what + "</b> (" + escapeHtml(when) + ").<br><br>" +
  229. '<span class="of-dim">Start fresh deletes the saved snapshot.</span>',
  230. dismissable: true,
  231. buttons: [
  232. // keeps the snapshot: dismiss now, may be offered next launch
  233. //{ label: "Start fresh", action: function (close) { close(); checkDraft(); } },
  234. // deletes the snapshot so it stops prompting
  235. {
  236. label: "Start fresh", danger: true,
  237. action: function (close) { close(); deleteSession(); checkDraft(); }
  238. },
  239. {
  240. label: "Restore", primary: true,
  241. action: function (close) { close(); restore(); }
  242. }
  243. ]
  244. });
  245. });
  246. }
  247. /* ---------- envelope ---------- */
  248. function buildEnvelope() {
  249. var m = meta || {};
  250. m.title = stripExt(filename || cfg.defaultFileName);
  251. m.createdAt = m.createdAt || now();
  252. m.modifiedAt = now();
  253. m.revision = (m.revision || 0) + 1;
  254. m.generator = GENERATOR;
  255. meta = m;
  256. return {
  257. type: ENVELOPE_TYPE,
  258. app: cfg.appType,
  259. version: 1,
  260. meta: m,
  261. body: cfg.serialize()
  262. };
  263. }
  264. function parseEnvelope(text) {
  265. var obj = JSON.parse(text);
  266. if (!obj || obj.type !== ENVELOPE_TYPE || obj.app !== cfg.appType) {
  267. throw new Error("Not a valid " + cfg.fileTypeName + " file");
  268. }
  269. return obj;
  270. }
  271. /* ---------- title / status ---------- */
  272. function updateTitle() {
  273. var name = openingName || (!filepath && sourceName) || filename || (cfg.defaultFileName + cfg.extension);
  274. var t = name + (dirty ? " •" : "") + " - " + cfg.appName;
  275. OfficePlatform.setWindowTitle(t);
  276. var $dn = $(".of-docname");
  277. $dn.html((dirty ? '<span class="of-dirty-dot">• </span>' : "") + escapeHtml(name));
  278. // the document's identity only ever changes alongside its title
  279. updateForeignBanner();
  280. }
  281. /* ---------- start-up splash (common/splash.js, when the app has one) ----------
  282. While it shows, status messages and busy messages are what it says;
  283. it goes away when the document is on screen (documentLoaded), when
  284. something needs the person (a dialog), or when something failed. */
  285. function splashActive() {
  286. return !!(window.OfficeSplash && OfficeSplash.active());
  287. }
  288. function splashDone() {
  289. if (!splashActive()) return;
  290. OfficeSplash.done();
  291. showFromTop();
  292. }
  293. /* The document comes out from behind the splash at its beginning. The
  294. window grows and the layout settles for a moment after that (a float
  295. window resizing, pictures and fonts arriving), and any of it can
  296. leave the view scrolled part-way down the first page - so the top is
  297. asked for again until it has settled, unless the person has started
  298. scrolling themselves. */
  299. function showFromTop() {
  300. var $ws = $(".of-workspace");
  301. if (!$ws.length) return;
  302. var touched = false;
  303. var mark = function () { touched = true; };
  304. $ws.one("wheel touchstart keydown mousedown", mark);
  305. var top = function () {
  306. if (touched) return;
  307. $ws.scrollTop(0).scrollLeft(0);
  308. };
  309. top();
  310. requestAnimationFrame(top);
  311. [120, 350, 800].forEach(function (ms) { setTimeout(top, ms); });
  312. setTimeout(function () { $ws.off("wheel touchstart keydown mousedown", mark); }, 900);
  313. }
  314. // the document an app was asked to open is on screen
  315. function documentLoaded() {
  316. splashDone();
  317. }
  318. // say msg on the splash and let it paint before fn does synchronous work
  319. // (laying out a long document); without a splash fn just runs
  320. function splashStep(msg, fn) {
  321. if (!splashActive()) { fn(); return; }
  322. OfficeSplash.status(msg);
  323. // a frame to paint it in - or a moment, where frames do not come (a
  324. // tab or window in the background)
  325. var ran = false;
  326. var go = function () { if (!ran) { ran = true; fn(); } };
  327. requestAnimationFrame(function () { setTimeout(go, 0); });
  328. setTimeout(go, 150);
  329. }
  330. function setStatus(msg, type, timeout) {
  331. if (splashActive()) {
  332. if (type === "error") splashDone();
  333. else OfficeSplash.status(msg);
  334. }
  335. var $m = $(".of-status-msg");
  336. $m.text(msg || "").removeClass("error");
  337. if (type === "error") $m.addClass("error");
  338. clearTimeout(statusTimer);
  339. if (timeout !== 0) {
  340. statusTimer = setTimeout(function () { $m.text(""); }, timeout || 5000);
  341. }
  342. }
  343. function addStatusItem(id, html) {
  344. var $it = $('<span class="of-status-item" data-sid="' + escapeHtml(id) + '"></span>').html(html);
  345. $(".of-status-items").append($it);
  346. return $it;
  347. }
  348. function updateStatusItem(id, html) {
  349. $('.of-status-item[data-sid="' + id + '"]').html(html);
  350. }
  351. /* ---------- dirty / drafts ---------- */
  352. function draftKey() {
  353. return "officeDraft_" + cfg.appType + "_" + (filepath || "untitled");
  354. }
  355. function saveDraft() {
  356. try {
  357. var env = buildEnvelopeNoBump();
  358. var s = JSON.stringify({ t: now(), fp: filepath, fn: filename, env: env });
  359. if (s.length > DRAFT_MAX_SIZE) return;
  360. localStorage.setItem(draftKey(), s);
  361. } catch (e) { }
  362. }
  363. function buildEnvelopeNoBump() {
  364. // snapshot without touching revision/modified metadata
  365. return {
  366. type: ENVELOPE_TYPE, app: cfg.appType, version: 1,
  367. meta: meta || {}, body: cfg.serialize()
  368. };
  369. }
  370. function clearDraft() {
  371. try { localStorage.removeItem(draftKey()); } catch (e) { }
  372. }
  373. function pruneDrafts() {
  374. try {
  375. var kill = [];
  376. for (var i = 0; i < localStorage.length; i++) {
  377. var k = localStorage.key(i);
  378. if (k && k.indexOf("officeDraft_") === 0) {
  379. try {
  380. var d = JSON.parse(localStorage.getItem(k));
  381. if (!d.t || now() - d.t > DRAFT_MAX_AGE) kill.push(k);
  382. } catch (e) { kill.push(k); }
  383. }
  384. }
  385. kill.forEach(function (k) { localStorage.removeItem(k); });
  386. } catch (e) { }
  387. }
  388. function checkDraft() {
  389. var raw = null;
  390. try { raw = localStorage.getItem(draftKey()); } catch (e) { }
  391. if (!raw) return;
  392. var d;
  393. try { d = JSON.parse(raw); } catch (e) { clearDraft(); return; }
  394. if (!d || !d.env || !d.env.body) { clearDraft(); return; }
  395. var when = new Date(d.t).toLocaleString();
  396. confirmDialog("Recover unsaved changes?",
  397. "A recovered version of this document from <b>" + escapeHtml(when) +
  398. "</b> was found. It may contain changes that were never saved.",
  399. "Restore", "Discard",
  400. function (restore) {
  401. if (restore) {
  402. meta = d.env.meta || meta;
  403. cfg.deserialize(d.env.body);
  404. markDirty();
  405. setStatus("Recovered draft restored - remember to save");
  406. } else {
  407. clearDraft();
  408. }
  409. });
  410. }
  411. function markDirty() {
  412. editSeq++;
  413. if (!dirty) { dirty = true; updateTitle(); }
  414. clearTimeout(draftTimer);
  415. draftTimer = setTimeout(saveDraft, 2500);
  416. if (cfg) refreshQat();
  417. }
  418. function markClean() {
  419. dirty = false;
  420. clearTimeout(draftTimer);
  421. clearDraft();
  422. updateTitle();
  423. if (cfg) refreshQat();
  424. }
  425. /* ---------- recent documents ---------- */
  426. /* A recent entry is only useful where the path survives the page: the
  427. standalone build opens File objects the visitor picked, which are gone
  428. on reload, so it keeps no list rather than offering dead entries. */
  429. function getRecents() {
  430. if (!OfficePlatform.tracksRecents()) return [];
  431. return getSetting("recent", []);
  432. }
  433. function addRecent(fp, fn) {
  434. if (!OfficePlatform.tracksRecents()) return;
  435. var list = getRecents().filter(function (r) { return r.fp !== fp; });
  436. list.unshift({ fp: fp, fn: fn, t: now() });
  437. setSetting("recent", list.slice(0, RECENT_MAX));
  438. }
  439. /* ---------- document lifecycle ---------- */
  440. /*
  441. Foreign binary formats (.docx / .xlsx / .pptx / ODF) go through the Go
  442. converters - server side in ArozOS, in the WebAssembly module in a
  443. standalone build made with them. Reading the list through here rather
  444. than off cfg keeps one decision in one place: with no converters they
  445. are neither offered in the Open dialog's filter nor accepted by
  446. openPath.
  447. */
  448. function binaryImporters() {
  449. if (!OfficePlatform.canConvert()) return {};
  450. return cfg.binaryImporters || {};
  451. }
  452. /*
  453. The legacy binary format of the app's kind (cfg.legacyExtensions:
  454. .doc for Docs, .xls for Sheets, .ppt for Slides). Such a file opens
  455. through the platform's documentLoad like the app's own format - the
  456. Go converters turn it into OOXML first, server side in ArozOS, in the
  457. WebAssembly module in a standalone build - but it is an import: the
  458. document is not attached to the old file, and Save asks where to put
  459. it in the app's own format. Like binaryImporters, it needs the
  460. converters.
  461. */
  462. function legacyExtensions() {
  463. if (!OfficePlatform.canConvert()) return [];
  464. return cfg.legacyExtensions || [];
  465. }
  466. function isLegacyExt(ext) { return legacyExtensions().indexOf(ext) >= 0; }
  467. /*
  468. Formats an app reads but never writes (cfg.importFormats - Docs
  469. imports PDF). File > Import lists them, and what one produces is a
  470. new document of the app's own kind, named after the file and
  471. attached to nothing: Save asks where to put the .docx / .xlsx /
  472. .pptx instead of writing over the file it came from, because an
  473. import is not an open.
  474. importFormats: [{
  475. ext: ".pdf", label: "PDF document (.pdf)", icon: "file pdf outline",
  476. needsBackend / needsConvert: as for saveFormats,
  477. load: fn(filepath, filename, done(body), fail(msg), progress(msg))
  478. }]
  479. load converts the file into a body for cfg.deserialize; progress
  480. updates the busy panel the framework shows meanwhile, and
  481. fail("cancelled") gives up quietly (a password prompt dismissed).
  482. */
  483. function importFormats() {
  484. return ((cfg && cfg.importFormats) || []).filter(function (f) {
  485. if (f.needsBackend && !OfficePlatform.hasBackend()) return false;
  486. if (f.needsConvert && !OfficePlatform.canConvert()) return false;
  487. return true;
  488. });
  489. }
  490. function importFormatFor(ext) {
  491. var list = importFormats();
  492. for (var i = 0; i < list.length; i++) {
  493. if (list[i].ext === ext) return list[i];
  494. }
  495. return null;
  496. }
  497. function importDialog(fmt) {
  498. var go = function () {
  499. OfficePlatform.pickOpen({ filter: [fmt.ext.substring(1)], memoryKey: "document" }, function (files) {
  500. importPath(files[0].filepath, files[0].filename, fmt);
  501. });
  502. };
  503. if (dirty) {
  504. confirmDialog("Discard unsaved changes?",
  505. "The current document has unsaved changes that will be lost.",
  506. "Discard", "Cancel", function (yes) { if (yes) go(); });
  507. } else { go(); }
  508. }
  509. function importPath(fp, fn, fmt) {
  510. var name = stripExt(fn) + cfg.extension;
  511. showOpening(name);
  512. showBusy("Importing " + fn + "...");
  513. var settled = false;
  514. fmt.load(fp, fn, function (body) {
  515. if (settled) return;
  516. settled = true;
  517. splashStep("Laying out the pages...", function () {
  518. try {
  519. meta = { createdAt: now(), revision: 0 };
  520. loadedFromImport = true;
  521. openingName = null;
  522. sourceName = null;
  523. filepath = null; // a new document: Save asks where
  524. filename = name;
  525. cfg.deserialize(body);
  526. markClean();
  527. // the source stays in "recent": opening it again imports it again
  528. addRecent(fp, fn);
  529. hideBusy();
  530. setStatus("Imported " + fn + " - use Save to store it as " + cfg.extension);
  531. documentLoaded();
  532. } catch (err) {
  533. hideBusy();
  534. openFailed();
  535. setStatus("Cannot import " + fn + ": " + err.message, "error");
  536. }
  537. });
  538. }, function (msg) {
  539. if (settled) return;
  540. settled = true;
  541. hideBusy();
  542. openFailed();
  543. if (msg === "cancelled") {
  544. setStatus("Import cancelled");
  545. documentLoaded();
  546. } else {
  547. setStatus("Cannot import " + fn + ": " + (msg || "unknown error"), "error");
  548. }
  549. }, function (msg) {
  550. if (!settled) showBusy(msg);
  551. });
  552. }
  553. function loadLegacyEnvelope(env, fp, fn) {
  554. if (!env || env.type !== ENVELOPE_TYPE || env.app !== cfg.appType) {
  555. throw new Error("Not a valid " + cfg.fileTypeName + " file");
  556. }
  557. meta = { createdAt: now(), revision: 0 };
  558. adoptImportedPath(fp, fn);
  559. cfg.deserialize(env.body);
  560. markClean();
  561. // the old file stays in "recent": opening it again imports it again
  562. addRecent(fp, fn);
  563. setStatus(importedStatus(fn));
  564. documentLoaded();
  565. }
  566. function loadNativeEnvelope(env, fp, fn, opts) {
  567. if (!env || env.type !== ENVELOPE_TYPE || env.app !== cfg.appType) {
  568. throw new Error("Not a valid " + cfg.fileTypeName + " file");
  569. }
  570. meta = env.meta || {};
  571. loadedFromImport = false;
  572. openingName = null;
  573. sourceName = null;
  574. /*
  575. A template is a starting point, not a file the person is editing:
  576. the content loads but the document stays unattached, so Ctrl+S
  577. asks where to put it instead of writing back over the template.
  578. The name is kept as a suggestion for that dialog.
  579. */
  580. if (opts && opts.asTemplate) {
  581. var pretty = titleCase(stripExt(fn));
  582. filepath = null;
  583. filename = pretty + cfg.extension;
  584. meta = { createdAt: now(), revision: 0 };
  585. cfg.deserialize(env.body);
  586. markClean();
  587. setStatus("New " + cfg.fileTypeName.toLowerCase() +
  588. " from the " + pretty + " template");
  589. documentLoaded();
  590. return;
  591. }
  592. filepath = fp; filename = fn;
  593. cfg.deserialize(env.body);
  594. markClean();
  595. addRecent(fp, fn);
  596. setStatus("Opened " + fn);
  597. documentLoaded();
  598. checkDraft();
  599. }
  600. function loadNativeText(text, fp, fn, opts) {
  601. loadNativeEnvelope(parseEnvelope(text), fp, fn, opts);
  602. }
  603. /*
  604. A file opened from a foreign format stays attached to that file when
  605. the app declared a writer for its extension (cfg.saveFormats): Save
  606. then writes back in the original format, and only steps up to the
  607. app's own format once the document outgrows it (see doSaveForeign).
  608. With no writer the import is read-only and Save has to become Save As
  609. - which is what every app did before saveFormats existed.
  610. */
  611. function adoptImportedPath(fp, fn) {
  612. loadedFromImport = true;
  613. openingName = null;
  614. sourceName = null;
  615. if (saveFormatFor(extOf(fn))) {
  616. filepath = fp;
  617. filename = fn;
  618. } else {
  619. filepath = null; // read-only import: force Save As on save
  620. filename = stripExt(fn) + cfg.extension;
  621. sourceName = fn;
  622. }
  623. }
  624. function importedStatus(fn) {
  625. return filepath ? ("Opened " + fn) :
  626. ("Imported " + fn + " - use Save to store it as " + cfg.extension);
  627. }
  628. function loadImportText(text, fp, fn) {
  629. var ext = extOf(fn);
  630. var importer = (cfg.importers || {})[ext];
  631. if (!importer) { setStatus("Unsupported file type " + ext, "error"); return; }
  632. meta = { createdAt: now(), revision: 0 };
  633. adoptImportedPath(fp, fn);
  634. importer(text, fn);
  635. dirty = false; updateTitle();
  636. if (filepath) addRecent(filepath, filename);
  637. setStatus(importedStatus(fn));
  638. documentLoaded();
  639. }
  640. var openingName = null; // the file being opened, until it is in
  641. /* The window is titled after the file from the moment it starts to
  642. open - a large document can take a while, and "New Document" in the
  643. title meanwhile says the wrong thing. A failed open goes back. */
  644. function showOpening(fn, opts) {
  645. openingName = (opts && opts.asTemplate) ? titleCase(stripExt(fn)) + cfg.extension : fn;
  646. updateTitle();
  647. }
  648. function openFailed() {
  649. openingName = null;
  650. updateTitle();
  651. }
  652. function openPath(fp, fn, opts) {
  653. fn = fn || basename(fp);
  654. var ext = extOf(fn);
  655. showOpening(fn, opts);
  656. // a template (templates/*.json) is a plain envelope, not an Office
  657. // file: it is read as text in both hosts and needs no conversion
  658. if (opts && opts.asTemplate && ext === ".json") {
  659. setStatus("Opening " + fn + "...", "info", 0);
  660. vfsLoad(fp, function (text) {
  661. splashStep("Preparing " + fn + "...", function () {
  662. try {
  663. loadNativeText(text, fp, fn, opts);
  664. } catch (err) {
  665. openFailed();
  666. setStatus("Cannot open " + fn + ": " + err.message, "error");
  667. }
  668. });
  669. }, function () {
  670. openFailed();
  671. setStatus("Failed to load " + fn, "error");
  672. });
  673. return;
  674. }
  675. // a format the app only imports (a PDF in Docs): a new document
  676. var imp = importFormatFor(ext);
  677. if (imp) {
  678. importPath(fp, fn, imp);
  679. return;
  680. }
  681. // binary foreign formats (e.g. .odt) are handled by the app itself,
  682. // usually through a server-side AGI conversion - no text fetch here
  683. var bi = binaryImporters()[ext];
  684. if (bi) {
  685. meta = { createdAt: now(), revision: 0 };
  686. adoptImportedPath(fp, fn);
  687. dirty = false;
  688. updateTitle();
  689. if (filepath) addRecent(filepath, filename);
  690. bi(fp, fn);
  691. return;
  692. }
  693. if (isLegacyExt(ext)) {
  694. setStatus("Converting " + fn + "...", "info", 0);
  695. OfficePlatform.documentLoad(fp, function (envelope) {
  696. splashStep("Preparing " + fn + "...", function () {
  697. var env = envelope;
  698. if (typeof env === "string") {
  699. try { env = JSON.parse(env); } catch (e) { env = null; }
  700. }
  701. try {
  702. loadLegacyEnvelope(env, fp, fn);
  703. } catch (err) {
  704. openFailed();
  705. setStatus("Cannot open " + fn + ": " + err.message, "error");
  706. }
  707. });
  708. }, function (msg) {
  709. openFailed();
  710. setStatus("Failed to open " + fn + ": " + (msg || "unknown error"), "error");
  711. });
  712. return;
  713. }
  714. setStatus("Opening " + fn + "...", "info", 0);
  715. /* The app's own format: the platform turns the .docx / .xlsx / .pptx
  716. into the envelope - the editor copy the suite embedded when it
  717. saved the file, or an import of the OOXML when another program
  718. wrote it (server side in ArozOS, WebAssembly in the web edition). */
  719. if (ext === cfg.extension) {
  720. OfficePlatform.documentLoad(fp, function (envelope) {
  721. splashStep("Preparing " + fn + "...", function () {
  722. var env = envelope;
  723. if (typeof env === "string") {
  724. try { env = JSON.parse(env); } catch (e) { env = null; }
  725. }
  726. try {
  727. loadNativeEnvelope(env, fp, fn, opts);
  728. } catch (err) {
  729. openFailed();
  730. setStatus("Cannot open " + fn + ": " + err.message, "error");
  731. }
  732. });
  733. }, function (msg) {
  734. openFailed();
  735. setStatus("Failed to open " + fn + ": " + (msg || "unknown error"), "error");
  736. });
  737. return;
  738. }
  739. vfsLoad(fp, function (text) {
  740. splashStep("Preparing " + fn + "...", function () {
  741. try {
  742. loadImportText(text, fp, fn);
  743. } catch (err) {
  744. openFailed();
  745. setStatus("Cannot open " + fn + ": " + err.message, "error");
  746. }
  747. });
  748. }, function () {
  749. openFailed();
  750. setStatus("Failed to load " + fn, "error");
  751. });
  752. }
  753. /*
  754. A host that keeps each document in a window of its own (the desktop
  755. shell: OfficePlatform.prefersNewWindows) opens another document
  756. beside this one once this window holds something - a file, or
  757. unsaved work - the way a desktop app does. An empty untitled window
  758. is simply reused. Elsewhere the document replaces this one.
  759. */
  760. function holdsDocument() { return !!filepath || dirty; }
  761. function openElsewhere(fp, fn) {
  762. if (!OfficePlatform.prefersNewWindows() || !holdsDocument()) return false;
  763. return OfficePlatform.openDocument(fp, fn, { appIcon: cfg.appIcon });
  764. }
  765. function newDocument() {
  766. if (OfficePlatform.prefersNewWindows() && holdsDocument() &&
  767. OfficePlatform.openNewWindow()) {
  768. return;
  769. }
  770. var go = function () {
  771. filepath = null;
  772. filename = null;
  773. sourceName = null;
  774. meta = { createdAt: now(), revision: 0 };
  775. loadedFromImport = false;
  776. cfg.create();
  777. markClean();
  778. setStatus("New " + cfg.fileTypeName.toLowerCase() + " created");
  779. };
  780. if (dirty) {
  781. confirmDialog("Discard unsaved changes?",
  782. "The current document has unsaved changes that will be lost.",
  783. "Discard", "Cancel", function (yes) { if (yes) go(); });
  784. } else { go(); }
  785. }
  786. function openDialog() {
  787. var go = function () {
  788. var filter = [cfg.extension.substring(1)];
  789. (Object.keys(cfg.importers || {})).forEach(function (e) {
  790. filter.push(e.substring(1));
  791. });
  792. (Object.keys(binaryImporters())).forEach(function (e) {
  793. filter.push(e.substring(1));
  794. });
  795. legacyExtensions().forEach(function (e) {
  796. filter.push(e.substring(1));
  797. });
  798. OfficePlatform.pickOpen({ filter: filter, memoryKey: "document" }, function (files) {
  799. if (openElsewhere(files[0].filepath, files[0].filename)) return;
  800. openPath(files[0].filepath, files[0].filename);
  801. });
  802. };
  803. // nothing is discarded when the document goes to a window of its own
  804. if (dirty && !OfficePlatform.prefersNewWindows()) {
  805. confirmDialog("Discard unsaved changes?",
  806. "The current document has unsaved changes that will be lost.",
  807. "Discard", "Cancel", function (yes) { if (yes) go(); });
  808. } else { go(); }
  809. }
  810. /* ---------- foreign save formats (cfg.saveFormats) ---------- */
  811. /*
  812. An app may declare formats it can write besides its own (.docx / .xlsx / .pptx):
  813. saveFormats: [{
  814. ext: ".csv", label: "CSV (.csv)", icon: "file alternate outline",
  815. oneWay: true, // a rendering (PDF):
  816. // never becomes the file
  817. // the document lives in
  818. unsupported: fn -> null | [reason, ...],
  819. save: fn(fp, fn, done, fail(msg))
  820. }]
  821. They drive both Save As (a format picker) and Save (a document opened
  822. from one of these formats writes straight back to it). Apps that
  823. declare none keep the native-format-only behaviour unchanged.
  824. */
  825. /*
  826. Two flags mark a writer that cannot exist everywhere:
  827. needsConvert goes through the Office format converters (.xlsx,
  828. .ods, ...) - present in ArozOS, and in a standalone
  829. build shipped with the WebAssembly module
  830. needsBackend needs a server outright (the real-text PDF renderer)
  831. Filtering here rather than in each app keeps Save As, the
  832. save-back-into-a-foreign-format path and autosave consistent.
  833. */
  834. function saveFormats() {
  835. var list = (cfg && cfg.saveFormats) || [];
  836. return list.filter(function (f) {
  837. if (f.needsBackend && !OfficePlatform.hasBackend()) return false;
  838. if (f.needsConvert && !OfficePlatform.canConvert()) return false;
  839. return true;
  840. });
  841. }
  842. function findSaveFormat(ext, adoptableOnly) {
  843. var list = saveFormats();
  844. for (var i = 0; i < list.length; i++) {
  845. if (list[i].ext !== ext) continue;
  846. return (adoptableOnly && list[i].oneWay) ? null : list[i];
  847. }
  848. return null;
  849. }
  850. // a writer whose output the document can go on living in (excludes PDF)
  851. function saveFormatFor(ext) { return findSaveFormat(ext, true); }
  852. function formatLabel(fmt) { return (fmt && (fmt.label || fmt.ext)) || nativeLabel(); }
  853. // "Word document (.docx)" - what the app's own format is called
  854. function nativeLabel() {
  855. return cfg.nativeLabel || (cfg.fileTypeName + " (" + cfg.extension + ")");
  856. }
  857. function formatReasons(fmt) {
  858. if (!fmt || !fmt.unsupported) return null;
  859. var r;
  860. try { r = fmt.unsupported(); } catch (e) { return null; }
  861. return (r && r.length) ? r : null;
  862. }
  863. /*
  864. A foreign format holds less than the app's own format does, so it may
  865. refuse a document outright instead of silently dropping content. The
  866. reasons come from the app as plain strings - escaped here, never
  867. trusted as markup.
  868. */
  869. function formatBlockedDialog(fmt, reasons) {
  870. var label = formatLabel(fmt);
  871. var list = reasons.map(function (t) {
  872. return "<li>" + escapeHtml(t) + "</li>";
  873. }).join("");
  874. setStatus("Cannot save in " + label + " format", "error");
  875. dialog({
  876. title: "Cannot save as " + label,
  877. body: "<p>This " + escapeHtml(cfg.fileTypeName.toLowerCase()) +
  878. " uses features that " + escapeHtml(label) + " cannot store:</p>" +
  879. "<ul>" + list + "</ul>" +
  880. "<p>Save it as " + escapeHtml(cfg.extension) +
  881. " to keep them, or save a copy in " + escapeHtml(label) + " without them.</p>",
  882. buttons: [
  883. { label: "Cancel" },
  884. {
  885. label: "Save a copy...",
  886. action: function (close) { close(); exportFormat(fmt.ext); }
  887. },
  888. {
  889. label: "Save as " + cfg.extension + "...", primary: true,
  890. action: function (close) { close(); saveAsFormat(null); }
  891. }
  892. ]
  893. });
  894. }
  895. /*
  896. exportFormat writes a copy of the document in one of cfg.saveFormats
  897. and leaves the document where it is: on its own file, as dirty as it
  898. was. It is File > Export for the formats the app writes but does not
  899. edit (exportOnly), and the lossy copy the dialog above offers - so it
  900. asks nothing about what the format cannot hold.
  901. */
  902. function exportFormat(ext) {
  903. var fmt = findSaveFormat(ext, false);
  904. if (!fmt) return;
  905. OfficePlatform.pickSave({
  906. defaultName: stripExt(filename || cfg.defaultFileName) + fmt.ext,
  907. ext: fmt.ext,
  908. memoryKey: "export"
  909. }, function (file) {
  910. if (cfg.onBeforeSave) { try { cfg.onBeforeSave(); } catch (e) { } }
  911. setStatus("Exporting...", "info", 0);
  912. fmt.save(file.filepath, file.filename, function () {
  913. setStatus("Exported " + file.filename);
  914. toast("Exported " + file.filename);
  915. }, function (err) {
  916. setStatus("Export failed: " + err, "error");
  917. toast("Export failed: " + err, "error");
  918. });
  919. });
  920. }
  921. function doSaveForeign(fp, fn, fmt, cb, silent, obs) {
  922. var reasons = formatReasons(fmt);
  923. if (reasons) {
  924. // autosave must never interrupt with a dialog: it skips the write
  925. // and lets the session snapshot be the safety net instead
  926. if (!silent) formatBlockedDialog(fmt, reasons);
  927. return false;
  928. }
  929. if (cfg.onBeforeSave) { try { cfg.onBeforeSave(); } catch (e) { } }
  930. setStatus("Saving...", "info", 0);
  931. if (obs) obs.progress("server");
  932. var seq = editSeq;
  933. saveBusy = true;
  934. fmt.save(fp, fn, function () {
  935. setStatus("Saved " + fn);
  936. // a one-way rendering is a copy, not the document's own file - the
  937. // editor keeps its path and stays dirty
  938. if (!fmt.oneWay) {
  939. filepath = fp; filename = fn;
  940. loadedFromImport = false;
  941. savedClean(seq);
  942. addRecent(fp, fn);
  943. saveSession();
  944. }
  945. finishSave();
  946. if (cb) cb();
  947. }, function (err) {
  948. setStatus("Save failed: " + err, "error");
  949. finishSave();
  950. if (obs) obs.fail(err);
  951. });
  952. return true;
  953. }
  954. // the file on disk has what the document held when the save began: it is
  955. // clean only if nobody edited since
  956. function savedClean(seq) {
  957. if (seq === editSeq) markClean();
  958. else updateTitle();
  959. }
  960. function finishSave() {
  961. saveBusy = false;
  962. if (queuedSave) {
  963. var q = queuedSave;
  964. queuedSave = null;
  965. doSaveTo(q.fp, q.fn, q.cb, false, q.obs);
  966. }
  967. }
  968. /* obs, when given, follows the write: obs.progress(stage, percent) -
  969. "prepare", "compress", "upload", "server" - and obs.fail(message) when
  970. it does not happen (cb only ever reports success) */
  971. function save(cb, obs) {
  972. if (!filepath) { saveAs(cb, obs); return; }
  973. if (!doSaveTo(filepath, filename, cb, false, obs) && obs) obs.fail(null);
  974. }
  975. function saveAs(cb, obs) { saveAsFormat(null, cb, obs); }
  976. /*
  977. `fmt` is a cfg.saveFormats entry, or null for the native format. The
  978. format fixes the extension, so the picker only supplies the name.
  979. */
  980. function saveAsFormat(fmt, cb, obs) {
  981. var ext = fmt ? fmt.ext : cfg.extension;
  982. // ask before making the user pick a filename, not after
  983. var reasons = formatReasons(fmt);
  984. if (reasons) { formatBlockedDialog(fmt, reasons); return; }
  985. var defName = stripExt(filename || cfg.defaultFileName) + ext;
  986. OfficePlatform.pickSave({
  987. defaultName: defName,
  988. ext: ext,
  989. memoryKey: "document",
  990. //A document that has never been saved has no folder of its own, so start
  991. //from wherever this app was last used rather than the hardcoded Desktop
  992. forceOverwrite: !filepath
  993. }, function (file) {
  994. if (!doSaveTo(file.filepath, file.filename, cb, false, obs) && obs) obs.fail(null);
  995. });
  996. }
  997. /*
  998. Write the document into the app's own Office format at fp. Shared by
  999. Save / Save As and by the convert-to-native action, which writes a
  1000. copy without moving the open document onto it - so this deliberately
  1001. touches nothing but the file. Returns false when the envelope could
  1002. not even be built.
  1003. cfg.prepareNative(body) gets a private copy of the body to finish for
  1004. the OOXML writer - render a chart to PNG, turn an SVG into something
  1005. Word can hold - and may return a Promise. What it leaves in the copy
  1006. is both what the .docx / .xlsx / .pptx shows and the editor copy
  1007. embedded in it, so a preparation must only add, never take away.
  1008. */
  1009. function writeNative(fp, done, fail, progress) {
  1010. var env;
  1011. try {
  1012. env = buildEnvelope();
  1013. env.body = JSON.parse(JSON.stringify(env.body));
  1014. } catch (e) { fail(e.message); return false; }
  1015. var prep;
  1016. try { prep = cfg.prepareNative ? cfg.prepareNative(env.body) : null; }
  1017. catch (e) { fail(e.message || "could not prepare the document"); return true; }
  1018. if (progress) progress("prepare");
  1019. Promise.resolve(prep).then(function () {
  1020. OfficePlatform.documentSave(fp, JSON.stringify(env), done, fail, progress);
  1021. }, function (err) {
  1022. fail((err && err.message) ? err.message : "could not prepare the document");
  1023. });
  1024. return true;
  1025. }
  1026. // returns false when the write was declined (format cannot hold the doc)
  1027. function doSaveTo(fp, fn, cb, silent, obs) {
  1028. if (saveBusy) {
  1029. // autosave simply skips a tick; an explicit save runs next
  1030. if (silent) return true;
  1031. queuedSave = { fp: fp, fn: fn, cb: cb, obs: obs };
  1032. if (obs) obs.progress("wait");
  1033. setStatus("Saving...", "info", 0);
  1034. return true;
  1035. }
  1036. var ext = extOf(fn);
  1037. if (ext !== cfg.extension) {
  1038. // one of the app's own foreign formats - including a document
  1039. // opened from one and saved straight back with Ctrl+S
  1040. var fmt = findSaveFormat(ext, false);
  1041. if (fmt) {
  1042. // a writer too expensive to run on a timer (rasterizing
  1043. // charts, seeking videos for a poster frame, refetching every
  1044. // image) stays out of autosave; the caller falls back to the
  1045. // session snapshot, which is what that safety net is for
  1046. if (silent && fmt.noAutosave) return false;
  1047. return doSaveForeign(fp, fn, fmt, cb, silent, obs);
  1048. }
  1049. }
  1050. if (cfg.onBeforeSave) { try { cfg.onBeforeSave(); } catch (e) { } }
  1051. setStatus("Saving...", "info", 0);
  1052. var seq = editSeq;
  1053. saveBusy = true;
  1054. var started = writeNative(fp, function () {
  1055. filepath = fp; filename = fn;
  1056. loadedFromImport = false;
  1057. savedClean(seq);
  1058. addRecent(fp, fn);
  1059. setStatus("Saved " + fn);
  1060. // the file now holds what the snapshot would: drop the snapshot
  1061. // (one tiny request) rather than uploading the document a second
  1062. // time, which doubled every save on a slow link and offered to
  1063. // "restore" a document that was already saved
  1064. deleteSession();
  1065. finishSave();
  1066. if (cb) cb();
  1067. }, function (err) {
  1068. setStatus("Save failed: " + err, "error");
  1069. finishSave();
  1070. if (obs) obs.fail(err);
  1071. }, obs ? obs.progress : null);
  1072. if (!started) saveBusy = false;
  1073. return started;
  1074. }
  1075. /* ---------- foreign-format banner ---------- */
  1076. /*
  1077. A document opened from .docx / .pptx / .csv / ... goes on living in
  1078. that file: Save rewrites it in its own format rather than quietly
  1079. turning it into the app's own format (see doSaveTo). That is the right
  1080. default - somebody who opened a .docx wants a .docx back - but it
  1081. also means every ArozOS Office feature the foreign format cannot hold
  1082. is being dropped on each save, which is worth saying out loud once
  1083. rather than only at the moment content is lost.
  1084. So the editor carries a banner under the toolbar for as long as the
  1085. open file is not native, offering the one-click way out: convert to
  1086. the app's own format. Native documents never see any of this.
  1087. */
  1088. var bannerDismissed = null; // filepath the banner was dismissed for
  1089. // the format the open document currently lives in, or null when that is
  1090. // the app's own format (or nothing on disk yet)
  1091. function foreignFormat() {
  1092. if (!filepath || !filename) return null;
  1093. var ext = extOf(filename);
  1094. if (!ext || ext === cfg.extension) return null;
  1095. return { ext: ext, fmt: findSaveFormat(ext, true) };
  1096. }
  1097. function buildForeignBanner() {
  1098. var $b = $('<div class="of-fmtbanner of-noprint" style="display:none;"></div>');
  1099. $b.append('<i class="exclamation triangle icon"></i>');
  1100. $b.append('<span class="of-fmtbanner-msg"></span>');
  1101. $b.append($('<button type="button" class="of-fmtbanner-btn"></button>')
  1102. .html('<i class="exchange icon"></i>Convert to ' + escapeHtml(cfg.extension))
  1103. .attr("title", "Save a copy as a " + nativeLabel() + " and open it")
  1104. .on("click", convertToNative));
  1105. $b.append($('<button type="button" class="of-fmtbanner-x" title="Dismiss">×</button>')
  1106. .on("click", function () {
  1107. bannerDismissed = filepath;
  1108. $(".of-fmtbanner").hide();
  1109. }));
  1110. return $b;
  1111. }
  1112. function updateForeignBanner() {
  1113. var $b = $(".of-fmtbanner");
  1114. if (!$b.length) return;
  1115. var f = foreignFormat();
  1116. if (!f || bannerDismissed === filepath) { $b.hide(); return; }
  1117. var what = f.fmt ? formatLabel(f.fmt) : (f.ext + " file");
  1118. $b.find(".of-fmtbanner-msg").html(
  1119. "This is a <b>" + escapeHtml(what) + "</b>, not a " +
  1120. escapeHtml(nativeLabel()) + ". " +
  1121. "Anything " + escapeHtml(f.ext) + " cannot store is lost on save.");
  1122. $b.css("display", "");
  1123. }
  1124. /*
  1125. Write the document out in the app's own format and open that copy in a
  1126. window of its own. The editor stays on the original foreign file: the
  1127. converted document is a new file, and which of the two to go on
  1128. working in is the person's call, not ours.
  1129. */
  1130. function convertToNative() {
  1131. var defName = stripExt(filename || cfg.defaultFileName) + cfg.extension;
  1132. OfficePlatform.pickSave({
  1133. defaultName: defName,
  1134. ext: cfg.extension,
  1135. memoryKey: "document"
  1136. }, function (file) {
  1137. if (cfg.onBeforeSave) { try { cfg.onBeforeSave(); } catch (e) { } }
  1138. setStatus("Converting to " + cfg.extension + "...", "info", 0);
  1139. writeNative(file.filepath, function () {
  1140. setStatus("Converted to " + file.filename);
  1141. addRecent(file.filepath, file.filename);
  1142. // the question has been answered for this file either way
  1143. bannerDismissed = filepath;
  1144. updateForeignBanner();
  1145. var opened = OfficePlatform.openDocument(file.filepath, file.filename,
  1146. { appIcon: cfg.appIcon });
  1147. toast(opened ? ("Converted - " + file.filename + " opened in a new window")
  1148. : ("Converted - saved as " + file.filename));
  1149. }, function (err) {
  1150. setStatus("Convert failed: " + err, "error");
  1151. toast("Convert failed: " + err, "error");
  1152. });
  1153. });
  1154. }
  1155. /* ---------- autosave ---------- */
  1156. function autosaveEnabled() { return getSetting("autosave", true); }
  1157. function autosaveTick() {
  1158. // a host with no file system to write back to (the standalone build
  1159. // saves by downloading) must never autosave: the snapshot below is
  1160. // the whole safety net there
  1161. if (dirty && filepath && autosaveEnabled() && OfficePlatform.autosavesToFile()) {
  1162. // a document living in a foreign format is autosaved only while
  1163. // that format can still hold it; when it cannot, doSaveTo's silent
  1164. // mode declines the write rather than interrupting with a dialog,
  1165. // and the session snapshot below protects the work instead
  1166. if (!doSaveTo(filepath, filename, null, true)) saveSession();
  1167. } else if (dirty) {
  1168. // unsaved (or autosave-off) documents still get a session
  1169. // snapshot so "Restore from previous session" can recover them
  1170. saveSession();
  1171. }
  1172. }
  1173. /* ---------- theme ---------- */
  1174. function isDark() {
  1175. try { return localStorage.getItem("office_theme") === "dark"; } catch (e) { return false; }
  1176. }
  1177. function applyTheme() {
  1178. var dark = isDark();
  1179. $("body").toggleClass("dark", dark);
  1180. OfficePlatform.setWindowTheme(dark);
  1181. if (cfg && cfg.onThemeChanged) { try { cfg.onThemeChanged(dark); } catch (e) { } }
  1182. }
  1183. function toggleTheme() {
  1184. try { localStorage.setItem("office_theme", isDark() ? "light" : "dark"); } catch (e) { }
  1185. applyTheme();
  1186. refreshMenuChecks();
  1187. }
  1188. // The host (the desktop's theme toggle, Drive's theme setting) calls
  1189. // this on every app window when its theme changes; Drive also calls it
  1190. // when the window loads, so the app opens in the host's theme
  1191. function followHostTheme(theme) {
  1192. var dark = theme === "dark" || theme === "darkTheme";
  1193. if (dark === isDark()) return;
  1194. try { localStorage.setItem("office_theme", dark ? "dark" : "light"); } catch (e) { }
  1195. applyTheme();
  1196. refreshMenuChecks();
  1197. }
  1198. /* ---------- zoom ---------- */
  1199. var ZOOM_LEVELS = [50, 65, 75, 90, 100, 110, 125, 150, 175, 200];
  1200. function applyZoom(transient) {
  1201. if (cfg.zoomTarget) {
  1202. $(cfg.zoomTarget).css("zoom", zoom / 100);
  1203. }
  1204. $(".of-zoom-val").text(zoom + "%");
  1205. // a transient zoom (a phone fitting the page to its width) is not
  1206. // the person's choice and must not become the next session's zoom
  1207. if (!transient) setSetting("zoom", zoom);
  1208. if (cfg.onZoomChanged) { try { cfg.onZoomChanged(zoom); } catch (e) { } }
  1209. }
  1210. function setZoom(z, opts) {
  1211. zoom = Math.max(25, Math.min(400, Math.round(z)));
  1212. applyZoom(!!(opts && opts.transient));
  1213. }
  1214. /*
  1215. Ctrl/Cmd + wheel zooms the document, not the whole ArozOS desktop.
  1216. The browser's own page zoom owns that gesture, so the listener has to
  1217. be non-passive to be allowed to preventDefault it.
  1218. Deltas are accumulated rather than stepped per event: one mouse notch
  1219. is ~100, but a trackpad pinch arrives as a stream of small deltas
  1220. (Chrome reports those as wheel events with ctrlKey set) and stepping
  1221. on each one would rocket through the zoom levels.
  1222. */
  1223. var WHEEL_ZOOM_STEP = 40;
  1224. var wheelAccum = 0;
  1225. function onWheelZoom(e) {
  1226. if (!e.ctrlKey && !e.metaKey) return;
  1227. e.preventDefault();
  1228. // reversing direction should respond at once rather than first
  1229. // having to work off the leftover from the other direction
  1230. if (wheelAccum !== 0 && (wheelAccum < 0) !== (e.deltaY < 0)) wheelAccum = 0;
  1231. wheelAccum += e.deltaY;
  1232. // at most one level per event, so a single wheel notch (~100) is one
  1233. // step while a stream of small pinch deltas still adds up to one
  1234. if (wheelAccum <= -WHEEL_ZOOM_STEP) { wheelAccum = 0; zoomStep(1); }
  1235. else if (wheelAccum >= WHEEL_ZOOM_STEP) { wheelAccum = 0; zoomStep(-1); }
  1236. }
  1237. function zoomStep(dir) {
  1238. var i;
  1239. if (dir > 0) {
  1240. for (i = 0; i < ZOOM_LEVELS.length; i++) {
  1241. if (ZOOM_LEVELS[i] > zoom) { setZoom(ZOOM_LEVELS[i]); return; }
  1242. }
  1243. setZoom(zoom + 25);
  1244. } else {
  1245. for (i = ZOOM_LEVELS.length - 1; i >= 0; i--) {
  1246. if (ZOOM_LEVELS[i] < zoom) { setZoom(ZOOM_LEVELS[i]); return; }
  1247. }
  1248. setZoom(Math.max(25, zoom - 10));
  1249. }
  1250. }
  1251. /* ---------- keyboard shortcuts ---------- */
  1252. function normalizeCombo(c) {
  1253. var parts = String(c).split("+").map(function (p) { return p.trim(); });
  1254. var mods = { ctrl: false, alt: false, shift: false };
  1255. var key = "";
  1256. parts.forEach(function (p) {
  1257. var l = p.toLowerCase();
  1258. if (l === "ctrl" || l === "cmd" || l === "meta") mods.ctrl = true;
  1259. else if (l === "alt") mods.alt = true;
  1260. else if (l === "shift") mods.shift = true;
  1261. else key = l;
  1262. });
  1263. return (mods.ctrl ? "ctrl+" : "") + (mods.alt ? "alt+" : "") + (mods.shift ? "shift+" : "") + key;
  1264. }
  1265. function comboFromEvent(e) {
  1266. var key = e.key;
  1267. if (!key) return "";
  1268. if (key === " ") key = "space";
  1269. key = key.toLowerCase();
  1270. if (key === "escape") key = "esc";
  1271. return ((e.ctrlKey || e.metaKey) ? "ctrl+" : "") + (e.altKey ? "alt+" : "") +
  1272. (e.shiftKey ? "shift+" : "") + key;
  1273. }
  1274. // Registers through the shared OfficeHotkeys registry when loaded
  1275. // (hotkeys.js); the local map only remains as a standalone fallback.
  1276. // opts (optional) pass straight through: description/group make the
  1277. // binding show up in the Ctrl+/ help dialog, when() gates it.
  1278. function registerShortcut(combo, handler, opts) {
  1279. if (window.OfficeHotkeys) {
  1280. return OfficeHotkeys.register(combo, function (e) {
  1281. closeAllMenus();
  1282. return handler(e);
  1283. }, $.extend({ allowInInput: true, inDialogs: true, group: "General" }, opts || {}));
  1284. }
  1285. shortcuts[normalizeCombo(combo)] = handler;
  1286. }
  1287. function handleKeydown(e) {
  1288. var combo = comboFromEvent(e);
  1289. var h = shortcuts[combo];
  1290. if (h) {
  1291. e.preventDefault();
  1292. e.stopPropagation();
  1293. closeAllMenus();
  1294. h(e);
  1295. return;
  1296. }
  1297. if (combo === "esc") closeAllMenus();
  1298. }
  1299. /* ---------- menus (menubar drops, context menus, floating submenus) ---------- */
  1300. /*
  1301. Submenus are NOT nested in their parent menu element - parents may
  1302. scroll (overflow-y) which would clip them. Instead every submenu is
  1303. a body-level ".of-float-menu" tagged with its depth; opening a menu
  1304. at depth N closes every float menu at depth >= N.
  1305. */
  1306. function closeFloatMenus(minDepth) {
  1307. minDepth = minDepth || 0;
  1308. $(".of-float-menu").each(function () {
  1309. if (($(this).data("depth") || 0) >= minDepth) $(this).remove();
  1310. });
  1311. if (minDepth === 0) $(".of-menu-item.of-has-sub").removeClass("open");
  1312. }
  1313. function closeAllMenus() {
  1314. $(".of-menu").removeClass("open");
  1315. closeFloatMenus(0);
  1316. if (window.OfficeRibbon) OfficeRibbon.closePopups();
  1317. }
  1318. function positionFloatMenu($m, x, y) {
  1319. var w = $m.outerWidth(), h = $m.outerHeight();
  1320. if (x + w > window.innerWidth) x = Math.max(4, window.innerWidth - w - 4);
  1321. if (y + h > window.innerHeight) y = Math.max(4, window.innerHeight - h - 4);
  1322. $m.css({ left: x + "px", top: y + "px" });
  1323. }
  1324. function openFloatSubmenu($it, sub, depth) {
  1325. closeFloatMenus(depth);
  1326. $it.closest(".of-menu-drop, .of-float-menu").find(".of-has-sub").removeClass("open");
  1327. $it.addClass("open");
  1328. var items = (typeof sub === "function") ? sub() : sub;
  1329. var $sm = $('<div class="of-context-menu of-float-menu"></div>').data("depth", depth);
  1330. renderMenuItems($sm, items, depth);
  1331. if (!items || items.length === 0) {
  1332. $sm.append('<div class="of-menu-item disabled"><span style="width:16px;"></span><span class="of-mi-label">(empty)</span></div>');
  1333. }
  1334. $("body").append($sm);
  1335. var r = $it[0].getBoundingClientRect();
  1336. var w = $sm.outerWidth();
  1337. var x = r.right + 2;
  1338. if (x + w > window.innerWidth) x = Math.max(4, r.left - w - 2);
  1339. positionFloatMenu($sm, x, r.top - 4);
  1340. }
  1341. /*
  1342. With foreign writers declared, "Save as" becomes a format picker whose
  1343. first entry is the app's own format; without them it stays the plain
  1344. Save As command it has always been.
  1345. */
  1346. function saveAsMenuItem() {
  1347. var list = saveFormats();
  1348. if (!list.length) {
  1349. return {
  1350. label: "Save as...", icon: "copy outline", key: "Ctrl+Shift+S",
  1351. action: function () { saveAs(); }
  1352. };
  1353. }
  1354. var sub = [
  1355. {
  1356. label: nativeLabel(),
  1357. icon: "save", key: "Ctrl+Shift+S",
  1358. action: function () { saveAsFormat(null); }
  1359. },
  1360. { sep: true }
  1361. ];
  1362. list.forEach(function (f) {
  1363. // hidden: a writer that only exists to save a document back into
  1364. // the file it came from (a second extension for the same format).
  1365. // Save as lists the formats the app edits; a rendering (oneWay,
  1366. // PDF) and a format it only writes (exportOnly: HTML, Markdown)
  1367. // are File > Export's
  1368. if (f.hidden || f.oneWay || f.exportOnly) return;
  1369. sub.push({
  1370. label: formatLabel(f), icon: f.icon || "file outline",
  1371. action: function () { saveAsFormat(f); }
  1372. });
  1373. });
  1374. return { label: "Save as", icon: "copy outline", sub: sub };
  1375. }
  1376. function renderMenuItems($drop, items, depth) {
  1377. depth = depth || 0;
  1378. $drop.empty();
  1379. (items || []).forEach(function (it) {
  1380. if (!it) return;
  1381. if (it.sep) { $drop.append('<div class="of-menu-sep"></div>'); return; }
  1382. var $it = $('<div class="of-menu-item"></div>');
  1383. if (it.checked !== undefined) {
  1384. var on = (typeof it.checked === "function") ? it.checked() : it.checked;
  1385. $it.append('<span class="of-mi-check">' + (on ? "✓" : "") + "</span>");
  1386. } else if (it.svg && window.OfficeIcons && OfficeIcons.has(it.svg)) {
  1387. $it.append(OfficeIcons.get(it.svg, "of-mi-ic"));
  1388. } else if (it.icon) {
  1389. $it.append('<i class="' + escapeHtml(it.icon) + ' icon"></i>');
  1390. } else {
  1391. $it.append('<span style="width:16px;"></span>');
  1392. }
  1393. // it.html: a picture of the choice (a line sample, a swatch) the
  1394. // app builds itself - trusted markup, never user content; the
  1395. // label stays as the tooltip
  1396. if (it.html) {
  1397. $it.append($('<span class="of-mi-label of-mi-html"></span>').html(it.html))
  1398. .attr("title", it.label || "");
  1399. } else {
  1400. $it.append('<span class="of-mi-label">' + escapeHtml(it.label) + "</span>");
  1401. }
  1402. if (it.key) $it.append('<span class="of-mi-key">' + escapeHtml(it.key) + "</span>");
  1403. if (typeof it.enabled === "function" && !it.enabled()) $it.addClass("disabled");
  1404. if (it.sub) {
  1405. $it.addClass("of-has-sub");
  1406. var open = function () { openFloatSubmenu($it, it.sub, depth + 1); };
  1407. $it.on("mouseenter", open);
  1408. $it.on("click", function (ev) { ev.stopPropagation(); open(); });
  1409. } else {
  1410. // hovering a plain item closes any deeper submenu
  1411. $it.on("mouseenter", function () { closeFloatMenus(depth + 1); });
  1412. if (it.action) {
  1413. $it.on("click", function (ev) {
  1414. ev.stopPropagation();
  1415. closeAllMenus();
  1416. it.action();
  1417. });
  1418. }
  1419. }
  1420. $drop.append($it);
  1421. });
  1422. }
  1423. /*
  1424. The title bar, Office style: app icon, the quick access buttons
  1425. (Save, Undo, Redo, the AutoSave switch), then the File menu and the
  1426. ribbon's tabs (common/ribbon.js) - or, for an app that declares no
  1427. ribbon, its classic menus - and the document name on the right.
  1428. It keeps the .of-menubar class: the menu code keys off it.
  1429. */
  1430. function refreshQat() {
  1431. $(".of-qat .of-rb-switch").each(function () {
  1432. var s = $(this).data("sync");
  1433. if (s) s();
  1434. });
  1435. }
  1436. function buildMenubar(menus) {
  1437. var $bar = $('<div class="of-menubar of-titlebar of-noprint"></div>');
  1438. $bar.append('<img class="of-appicon" src="' + escapeHtml(cfg.appIcon || "../img/docs.svg") + '" alt="">');
  1439. // Save, Undo and Redo live in the File and Edit menus (and on
  1440. // their shortcuts); the title bar keeps only the AutoSave switch
  1441. var $qat = $('<div class="of-qat"></div>');
  1442. if (window.OfficeRibbon) {
  1443. $qat.append(OfficeRibbon.toggle({
  1444. label: "AutoSave", cls: "of-autosave",
  1445. title: OfficePlatform.autosavesToFile() ?
  1446. "AutoSave: write changes to the file as you work" :
  1447. "AutoSave: keep a recovery copy as you work",
  1448. get: autosaveEnabled,
  1449. set: function (on) { setSetting("autosave", !!on); }
  1450. }));
  1451. }
  1452. $bar.append($qat);
  1453. $bar.append('<div class="of-tsep of-qatsep"></div>');
  1454. var $menus = $('<div class="of-tabstrip"></div>');
  1455. menus.forEach(function (m) {
  1456. var $m = $('<div class="of-menu" tabindex="-1">' + escapeHtml(m.title) + "</div>");
  1457. var $drop = $('<div class="of-menu-drop"></div>');
  1458. $m.append($drop);
  1459. // contextual menus (e.g. Table) only show when their condition
  1460. // holds; the app re-evaluates via OfficeApp.updateMenus()
  1461. if (m.when) {
  1462. $m.data("when", m.when);
  1463. $m.hide();
  1464. }
  1465. $m.on("click", function (ev) {
  1466. if ($(ev.target).closest(".of-menu-drop").length) return;
  1467. var wasOpen = $m.hasClass("open");
  1468. closeAllMenus();
  1469. if (!wasOpen) {
  1470. renderMenuItems($drop, (typeof m.items === "function") ? m.items() : m.items, 0);
  1471. $m.addClass("open");
  1472. }
  1473. });
  1474. $m.on("mouseenter", function () {
  1475. if ($(".of-menu.open").length && !$m.hasClass("open")) {
  1476. closeAllMenus();
  1477. renderMenuItems($drop, (typeof m.items === "function") ? m.items() : m.items, 0);
  1478. $m.addClass("open");
  1479. }
  1480. });
  1481. $menus.append($m);
  1482. });
  1483. $bar.append($menus);
  1484. if (cfg.ribbon && window.OfficeRibbon) OfficeRibbon.attachStrip($menus);
  1485. $bar.append('<div class="of-docname"></div>');
  1486. // room for an app's own title-bar buttons (Slides' Slideshow)
  1487. $bar.append('<div class="of-titleextras"></div>');
  1488. if (cfg.ribbon && window.OfficeRibbon) {
  1489. var $min = $('<button type="button" class="of-qbtn of-rb-mintoggle" title="Collapse the ribbon"><i class="chevron up icon"></i></button>');
  1490. $min.on("click", function () { OfficeRibbon.setMinimized(!OfficeRibbon.isMinimized()); });
  1491. $bar.append($min);
  1492. }
  1493. // one global closer for menubar drops, context menus and submenus
  1494. $(document).on("mousedown.ofmenu", function (ev) {
  1495. // the ribbon's popups (a folded group, a gallery) close themselves
  1496. if (!$(ev.target).closest(".of-menubar, .of-context-menu, .of-rb-popup, .of-rb-gpop").length) closeAllMenus();
  1497. });
  1498. return $bar;
  1499. }
  1500. function refreshMenuChecks() {
  1501. // menus re-render on open; nothing to do live
  1502. }
  1503. // show/hide conditional menubar menus (menu defs carrying when: fn),
  1504. // and re-read the ribbon's contextual tabs and control states
  1505. function updateMenus() {
  1506. $(".of-menubar .of-menu").each(function () {
  1507. var w = $(this).data("when");
  1508. if (!w) return;
  1509. var on = false;
  1510. try { on = !!w(); } catch (e) { }
  1511. if (!on && $(this).hasClass("open")) closeAllMenus();
  1512. $(this).toggle(on);
  1513. });
  1514. if (cfg && cfg.ribbon && window.OfficeRibbon) OfficeRibbon.refresh();
  1515. if (cfg) refreshQat();
  1516. }
  1517. function standardMenus() {
  1518. var fileItems = function () {
  1519. var items = [
  1520. { label: "New", icon: "file outline", key: "Ctrl+Alt+N", action: newDocument },
  1521. { label: "Open...", icon: "folder open", key: "Ctrl+O", action: openDialog },
  1522. !OfficePlatform.tracksRecents() ? null : {
  1523. label: "Open recent", icon: "history", sub: function () {
  1524. return getRecents().map(function (r) {
  1525. return {
  1526. label: r.fn, action: function () {
  1527. if (openElsewhere(r.fp, r.fn)) return;
  1528. if (dirty) {
  1529. confirmDialog("Discard unsaved changes?",
  1530. "The current document has unsaved changes.",
  1531. "Discard", "Cancel",
  1532. function (yes) { if (yes) openPath(r.fp, r.fn); });
  1533. } else { openPath(r.fp, r.fn); }
  1534. }
  1535. };
  1536. });
  1537. }
  1538. },
  1539. !importFormats().length ? null : {
  1540. label: "Import", icon: "sign-in", sub: function () {
  1541. return importFormats().map(function (f) {
  1542. return { label: f.label, icon: f.icon, action: function () { importDialog(f); } };
  1543. });
  1544. }
  1545. },
  1546. { sep: true },
  1547. { label: "Save", icon: "save", key: "Ctrl+S", action: function () { save(); } },
  1548. saveAsMenuItem(),
  1549. { label: "Auto-save", checked: autosaveEnabled, action: function () { setSetting("autosave", !autosaveEnabled()); } }
  1550. ];
  1551. if (cfg.fileMenuExtras && cfg.fileMenuExtras.length) {
  1552. items.push({ sep: true });
  1553. items = items.concat(cfg.fileMenuExtras);
  1554. }
  1555. items.push({ sep: true });
  1556. items.push({ label: "Print / PDF...", icon: "print", key: "Ctrl+P", action: printDoc });
  1557. return items;
  1558. };
  1559. var editItems = function () {
  1560. var items = [
  1561. {
  1562. label: "Undo", icon: "undo", key: "Ctrl+Z",
  1563. enabled: function () { return !cfg.canUndo || cfg.canUndo(); },
  1564. action: function () { if (cfg.onUndo) cfg.onUndo(); }
  1565. },
  1566. {
  1567. label: "Redo", icon: "redo", key: "Ctrl+Y",
  1568. enabled: function () { return !cfg.canRedo || cfg.canRedo(); },
  1569. action: function () { if (cfg.onRedo) cfg.onRedo(); }
  1570. },
  1571. { sep: true },
  1572. { label: "Cut", icon: "cut", key: "Ctrl+X", action: function () { clipboardAction("cut"); } },
  1573. { label: "Copy", icon: "copy", key: "Ctrl+C", action: function () { clipboardAction("copy"); } },
  1574. { label: "Paste", icon: "paste", key: "Ctrl+V", action: function () { clipboardAction("paste"); } },
  1575. { label: "Clipboard...", icon: "clipboard outline", action: showClipboardPane }
  1576. ];
  1577. if (cfg.editMenuExtras && cfg.editMenuExtras.length) {
  1578. items.push({ sep: true });
  1579. items = items.concat(cfg.editMenuExtras);
  1580. }
  1581. return items;
  1582. };
  1583. var viewItems = function () {
  1584. var items = [
  1585. { label: "Zoom in", icon: "zoom-in", key: "Ctrl+=", action: function () { zoomStep(1); } },
  1586. { label: "Zoom out", icon: "zoom-out", key: "Ctrl+-", action: function () { zoomStep(-1); } },
  1587. { label: "Reset zoom", icon: "expand", key: "Ctrl+0", action: function () { setZoom(100); } },
  1588. { sep: true },
  1589. { label: "Dark theme", checked: isDark, action: toggleTheme }
  1590. ];
  1591. if (cfg.viewMenuExtras && cfg.viewMenuExtras.length) {
  1592. items.push({ sep: true });
  1593. items = items.concat(cfg.viewMenuExtras);
  1594. }
  1595. return items;
  1596. };
  1597. // a ribbon app keeps File and Edit as menus, Google Docs style, and
  1598. // carries the rest (its own menus, View) as ribbon tabs
  1599. var menus = [{ title: "File", items: fileItems }, { title: "Edit", items: editItems }];
  1600. if (cfg.ribbon) return menus;
  1601. (cfg.menus || []).forEach(function (m) { menus.push(m); });
  1602. menus.push({ title: "View", items: viewItems });
  1603. return menus;
  1604. }
  1605. /* ---------- clipboard ---------- */
  1606. function clipboardAction(op) {
  1607. var hook = { cut: cfg.onCut, copy: cfg.onCopy, paste: cfg.onPaste }[op];
  1608. if (hook) { hook(); return; }
  1609. if (op === "paste") {
  1610. if (navigator.clipboard && navigator.clipboard.readText) {
  1611. navigator.clipboard.readText().then(function (t) {
  1612. if (cfg.onPasteText) cfg.onPasteText(t);
  1613. else document.execCommand("insertText", false, t);
  1614. }).catch(function () {
  1615. setStatus("Paste blocked by the browser - use Ctrl+V instead", "error");
  1616. });
  1617. } else {
  1618. setStatus("Paste is not available - use Ctrl+V instead", "error");
  1619. }
  1620. } else {
  1621. document.execCommand(op);
  1622. }
  1623. }
  1624. /* ---------- the Clipboard pane (Home > Clipboard launcher) ----------
  1625. Everything copied or cut in Office in this tab (OfficeClipboard
  1626. keeps it), newest first: click an item to paste it, as Office's
  1627. Clipboard task pane does. An item is put back on the system
  1628. clipboard and pasted by the app's own Paste, so every app pastes it
  1629. the way it pastes anything else. */
  1630. var APP_NAMES = { docs: "Docs", sheets: "Sheets", slides: "Slides" };
  1631. function clipItemView(it) {
  1632. var parsed = it.html ? OfficeClipboard.parse(it.html) : null;
  1633. // another app's object marker is never shown as raw JSON
  1634. var text = OfficeClipboard.isMarker(it.text) || /^\s*\{\s*"app"\s*:/.test(it.text) ?
  1635. (parsed ? parsed.text : "") : (it.text || (parsed ? parsed.text : ""));
  1636. text = String(text || "").replace(/\s+/g, " ").trim();
  1637. var $prev = $('<span class="of-clip-prev"></span>');
  1638. if (parsed && parsed.images.length && !text) {
  1639. $prev.append($('<img alt="">').attr("src", parsed.images[0].src));
  1640. } else if (parsed && parsed.tables.length && !it.text) {
  1641. $prev.text(text.slice(0, 160) || "Table");
  1642. } else {
  1643. $prev.text(text.length > 160 ? text.slice(0, 160) + "..." : (text || "(empty)"));
  1644. }
  1645. return { $prev: $prev, text: text };
  1646. }
  1647. function pasteClipItem(it) {
  1648. OfficeClipboard.writeAsync({ text: it.text, html: it.html, noHistory: true }).then(function () {
  1649. clipboardAction("paste");
  1650. }, function () {
  1651. setStatus("The browser blocked the clipboard - copy it again and press Ctrl+V", "error");
  1652. });
  1653. }
  1654. function showClipboardPane() {
  1655. closeAllMenus();
  1656. if (!window.OfficeClipboard) return;
  1657. var $list = $('<div class="of-clip-list"></div>');
  1658. var d = null;
  1659. var render = function () {
  1660. var items = OfficeClipboard.history();
  1661. $list.empty();
  1662. if (!items.length) {
  1663. $list.append('<div class="of-clip-empty">The clipboard is empty.<br>Copy or cut something in Docs, Sheets or Slides to collect it here.</div>');
  1664. return;
  1665. }
  1666. items.forEach(function (it, i) {
  1667. var v = clipItemView(it);
  1668. var $row = $('<div class="of-clip-item" tabindex="0"></div>').attr("title", "Click to paste");
  1669. $row.append($('<span class="of-clip-app"></span>').text(APP_NAMES[it.app] || "Office"));
  1670. $row.append(v.$prev);
  1671. var $del = $('<button type="button" class="of-clip-del" title="Delete"><i class="close icon"></i></button>');
  1672. $del.on("click", function (e) {
  1673. e.stopPropagation();
  1674. OfficeClipboard.removeFromHistory(i);
  1675. render();
  1676. });
  1677. $row.append($del);
  1678. $row.on("click", function () { d.close(); pasteClipItem(it); });
  1679. $row.on("keydown", function (e) { if (e.key === "Enter") { d.close(); pasteClipItem(it); } });
  1680. $list.append($row);
  1681. });
  1682. };
  1683. var $body = $('<div class="of-clip-pane"></div>')
  1684. .append('<div class="of-clip-hint">Click an item to paste it.</div>')
  1685. .append($list);
  1686. d = dialog({
  1687. title: "Clipboard",
  1688. body: $body,
  1689. buttons: [
  1690. {
  1691. label: "Clear All", action: function () {
  1692. OfficeClipboard.clearHistory();
  1693. render();
  1694. }
  1695. },
  1696. {
  1697. label: "Paste All", action: function (close) {
  1698. // oldest first, the order they were copied in
  1699. var items = OfficeClipboard.history().reverse();
  1700. if (!items.length) return;
  1701. var texts = [], htmls = [];
  1702. items.forEach(function (it) {
  1703. var v = clipItemView(it);
  1704. texts.push(v.text);
  1705. htmls.push(it.html || escapeHtml(it.text).replace(/\n/g, "<br>"));
  1706. });
  1707. close();
  1708. pasteClipItem({ text: texts.join("\n"), html: htmls.join("<br>") });
  1709. }
  1710. },
  1711. { label: "Close", primary: true }
  1712. ]
  1713. });
  1714. render();
  1715. }
  1716. /* ---------- print ---------- */
  1717. function printDoc() {
  1718. closeAllMenus();
  1719. if (cfg.onBeforePrint) { try { cfg.onBeforePrint(); } catch (e) { } }
  1720. setTimeout(function () {
  1721. // the print layout stays up until the dialog is done with it -
  1722. // at once in a browser, later behind a native print panel
  1723. OfficePlatform.print(function () {
  1724. if (cfg.onAfterPrint) { try { cfg.onAfterPrint(); } catch (e) { } }
  1725. });
  1726. }, 60);
  1727. }
  1728. /* ---------- dialogs / toasts / context menu ---------- */
  1729. function dialog(opt) {
  1730. splashDone(); // a question for the person: nothing may cover it
  1731. var $ov = $('<div class="of-dialog-overlay"></div>');
  1732. var $dl = $('<div class="of-dialog"></div>');
  1733. if (opt.wide) $dl.addClass("wide");
  1734. if (opt.title) $dl.append('<div class="of-dialog-title">' + escapeHtml(opt.title) + "</div>");
  1735. var $body = $('<div class="of-dialog-body"></div>');
  1736. if (opt.body instanceof $) $body.append(opt.body);
  1737. else $body.html(opt.body || "");
  1738. $dl.append($body);
  1739. var close = function () { $ov.remove(); $(document).off("keydown.ofdialog"); };
  1740. if (opt.buttons && opt.buttons.length) {
  1741. var $act = $('<div class="of-dialog-actions"></div>');
  1742. opt.buttons.forEach(function (b) {
  1743. var $b = $('<button class="of-btn"></button>').text(b.label);
  1744. if (b.primary) $b.addClass("primary");
  1745. if (b.danger) $b.addClass("danger");
  1746. $b.on("click", function () {
  1747. if (b.action) b.action(close, $body);
  1748. else close();
  1749. });
  1750. $act.append($b);
  1751. });
  1752. $dl.append($act);
  1753. }
  1754. $ov.append($dl);
  1755. // dismissed without a button: opt.onDismiss hears about it
  1756. var dismiss = function () {
  1757. close();
  1758. if (opt.onDismiss) opt.onDismiss();
  1759. };
  1760. $ov.on("mousedown", function (e) { if (e.target === $ov[0] && opt.dismissable !== false) dismiss(); });
  1761. $(document).on("keydown.ofdialog", function (e) {
  1762. if (e.key === "Escape" && opt.dismissable !== false) dismiss();
  1763. });
  1764. $("body").append($ov);
  1765. return { close: close, body: $body };
  1766. }
  1767. function confirmDialog(title, msgHtml, yesLabel, noLabel, cb) {
  1768. dialog({
  1769. title: title,
  1770. body: "<p>" + msgHtml + "</p>",
  1771. dismissable: false,
  1772. buttons: [
  1773. { label: noLabel || "Cancel", action: function (close) { close(); cb(false); } },
  1774. { label: yesLabel || "OK", primary: true, action: function (close) { close(); cb(true); } }
  1775. ]
  1776. });
  1777. }
  1778. function promptDialog(title, label, defVal, cb) {
  1779. var $b = $("<div><label>" + escapeHtml(label) + '</label><input type="text" class="of-prompt-input"></div>');
  1780. $b.find("input").val(defVal === undefined ? "" : defVal);
  1781. var d = dialog({
  1782. title: title, body: $b,
  1783. buttons: [
  1784. { label: "Cancel", action: function (close) { close(); cb(null); } },
  1785. {
  1786. label: "OK", primary: true, action: function (close, $body) {
  1787. var v = $body.find(".of-prompt-input").val();
  1788. close(); cb(v);
  1789. }
  1790. }
  1791. ]
  1792. });
  1793. var $in = d.body.find("input");
  1794. $in.trigger("focus").trigger("select");
  1795. $in.on("keydown", function (e) {
  1796. if (e.key === "Enter") { var v = $in.val(); d.close(); cb(v); }
  1797. });
  1798. return d;
  1799. }
  1800. function toast(msg, type, ms) {
  1801. if (type === "error") splashDone();
  1802. var $h = $(".of-toast-holder");
  1803. if (!$h.length) { $h = $('<div class="of-toast-holder"></div>'); $("body").append($h); }
  1804. var $t = $('<div class="of-toast"></div>').text(msg);
  1805. if (type === "error") $t.addClass("error");
  1806. $h.append($t);
  1807. requestAnimationFrame(function () { $t.addClass("show"); });
  1808. setTimeout(function () {
  1809. $t.removeClass("show");
  1810. setTimeout(function () { $t.remove(); }, 250);
  1811. }, ms || 2600);
  1812. }
  1813. function showContextMenu(x, y, items) {
  1814. closeFloatMenus(0);
  1815. var $cm = $('<div class="of-context-menu of-float-menu"></div>').data("depth", 0);
  1816. renderMenuItems($cm, items, 0);
  1817. $("body").append($cm);
  1818. positionFloatMenu($cm, x, y);
  1819. return { close: function () { closeFloatMenus(0); } };
  1820. }
  1821. function showBusy(msg) {
  1822. // the splash already covers the app and says what is happening
  1823. if (splashActive()) {
  1824. hideBusy();
  1825. OfficeSplash.status(msg || "Working...");
  1826. return;
  1827. }
  1828. // a busy panel already up only changes what it says (a long import
  1829. // reporting its pages), so its spinner does not restart
  1830. var $cur = $(".of-busy-overlay");
  1831. if ($cur.length) {
  1832. $cur.find(".of-busy-msg").text(msg || "Working...");
  1833. return;
  1834. }
  1835. var $o = $('<div class="of-busy-overlay"><div class="of-spinner"></div><div class="of-busy-msg"></div></div>');
  1836. $o.find(".of-busy-msg").text(msg || "Working...");
  1837. $("body").append($o);
  1838. }
  1839. function hideBusy() { $(".of-busy-overlay").remove(); }
  1840. /*
  1841. beginDrag(e, {move(ev), end(ev, cancelled), cursor})
  1842. Call from a pointerdown to own the rest of the gesture. A transparent
  1843. full-window layer goes over everything and takes pointer capture, so
  1844. every move and the release reach the drag however fast the pointer
  1845. travels - even when the dragged element is re-rendered (which drops
  1846. a capture set on the element itself) or the cursor crosses iframes,
  1847. charts or other widgets. The layer is removed on release, cancel, or
  1848. when the window loses focus. Returns a function that ends the drag.
  1849. */
  1850. function beginDrag(e, opts) {
  1851. opts = opts || {};
  1852. var ov = document.createElement("div");
  1853. ov.className = "of-drag-overlay";
  1854. if (opts.cursor) ov.style.cursor = opts.cursor;
  1855. document.body.appendChild(ov);
  1856. var done = false;
  1857. try { ov.setPointerCapture(e.pointerId); } catch (err) { }
  1858. function onMove(ev) {
  1859. ev.preventDefault();
  1860. if (opts.move) opts.move(ev);
  1861. }
  1862. function finish(ev, cancelled) {
  1863. if (done) return;
  1864. done = true;
  1865. ov.removeEventListener("pointermove", onMove);
  1866. ov.removeEventListener("pointerup", onUp);
  1867. ov.removeEventListener("pointercancel", onCancel);
  1868. window.removeEventListener("blur", onCancel);
  1869. if (ov.parentNode) ov.parentNode.removeChild(ov);
  1870. if (opts.end) opts.end(ev || null, !!cancelled);
  1871. }
  1872. function onUp(ev) { finish(ev, false); }
  1873. function onCancel(ev) { finish(ev && ev.type === "pointercancel" ? ev : null, true); }
  1874. ov.addEventListener("pointermove", onMove);
  1875. ov.addEventListener("pointerup", onUp);
  1876. ov.addEventListener("pointercancel", onCancel);
  1877. window.addEventListener("blur", onCancel);
  1878. return function () { finish(null, true); };
  1879. }
  1880. /* showProgress is showBusy's opposite number: a small panel in the
  1881. corner of the editing area for work that takes a while but has no
  1882. reason to hold the document hostage. Exporting is the case it was
  1883. written for - the deck is snapshotted when the export starts, so
  1884. carrying on editing while it runs changes nothing about the file
  1885. that comes out.
  1886. var p = OfficeApp.showProgress({ title: "Exporting PDF",
  1887. anchor: "#slCanvasArea" });
  1888. p.set(done, total, "Exporting 3 of 6 pages");
  1889. p.close();
  1890. anchor is the element to sit in the top-right of; the panel is
  1891. positioned from its box rather than placed inside it, so it does not
  1892. have to care how that element is laid out. */
  1893. function showProgress(o) {
  1894. o = o || {};
  1895. var $p = $('<div class="of-progress-panel of-noprint">' +
  1896. '<div class="of-pp-title"></div>' +
  1897. '<div class="of-pp-msg"></div>' +
  1898. '<div class="of-pp-bar"><div class="of-pp-fill"></div></div>' +
  1899. '</div>');
  1900. $p.find(".of-pp-title").text(o.title || "Working...");
  1901. $("body").append($p);
  1902. function place() {
  1903. var $a = o.anchor ? $(o.anchor) : $();
  1904. var el = $a.length ? $a[0] : null;
  1905. var r = el ? el.getBoundingClientRect() : null;
  1906. if (r && r.width > 0) {
  1907. $p.css({ top: (r.top + 12) + "px", right: (window.innerWidth - r.right + 12) + "px" });
  1908. } else {
  1909. $p.css({ top: "64px", right: "16px" });
  1910. }
  1911. }
  1912. place();
  1913. $(window).on("resize.ofprogress", place);
  1914. var handle = {
  1915. set: function (done, total, msg) {
  1916. var pct = total > 0 ? Math.max(0, Math.min(100, done * 100 / total)) : 0;
  1917. $p.find(".of-pp-fill").css("width", pct + "%");
  1918. if (msg !== undefined) $p.find(".of-pp-msg").text(msg);
  1919. place();
  1920. },
  1921. message: function (msg) { $p.find(".of-pp-msg").text(msg); },
  1922. close: function () {
  1923. $(window).off("resize.ofprogress", place);
  1924. $p.remove();
  1925. }
  1926. };
  1927. return handle;
  1928. }
  1929. /* ---------- statusbar ---------- */
  1930. function buildStatusbar() {
  1931. var $sb = $('<div class="of-statusbar of-noprint"></div>');
  1932. $sb.append('<span class="of-status-msg"></span>');
  1933. $sb.append('<span class="of-status-items"></span>');
  1934. var $z = $('<span class="of-status-zoom"></span>');
  1935. var $minus = $('<button type="button" title="Zoom out">−</button>');
  1936. var $plus = $('<button type="button" title="Zoom in">+</button>');
  1937. var $val = $('<span class="of-zoom-val" title="Reset zoom">100%</span>');
  1938. $minus.on("click", function () { zoomStep(-1); });
  1939. $plus.on("click", function () { zoomStep(1); });
  1940. $val.on("click", function () { setZoom(100); });
  1941. $z.append($minus).append($val).append($plus);
  1942. $sb.append($z);
  1943. return $sb;
  1944. }
  1945. /* ---------- init ---------- */
  1946. function init(config) {
  1947. cfg = config;
  1948. if (!cfg.appType || !cfg.serialize || !cfg.deserialize || !cfg.create) {
  1949. throw new Error("OfficeApp.init: appType, serialize, deserialize and create are required");
  1950. }
  1951. cfg.fileTypeName = cfg.fileTypeName || "Document";
  1952. cfg.defaultFileName = cfg.defaultFileName || "Untitled";
  1953. $("body").addClass("of-app");
  1954. // chrome
  1955. if (cfg.ribbon && window.OfficeRibbon) OfficeRibbon.host();
  1956. var $menubar = buildMenubar(standardMenus());
  1957. $("body").prepend($menubar);
  1958. $("body").append(buildStatusbar());
  1959. if (cfg.ribbon && window.OfficeRibbon && getSetting("ribbonMin", false)) {
  1960. OfficeRibbon.setMinimized(true);
  1961. }
  1962. // the title bar is in the page now: fit its tabs and the panel
  1963. if (cfg.ribbon && window.OfficeRibbon) OfficeRibbon.scheduleFit();
  1964. // the foreign-format banner sits under the whole toolbar strip, so
  1965. // it reads as a note about the document rather than part of the
  1966. // chrome; apps with no toolbar get it straight under the menubar
  1967. var $banner = buildForeignBanner();
  1968. var $tb = $("body > .of-toolbar").last();
  1969. if ($tb.length) $tb.after($banner); else $menubar.after($banner);
  1970. // shortcuts (standard)
  1971. registerShortcut("Ctrl+S", function () { save(); }, { description: "Save" });
  1972. registerShortcut("Ctrl+Shift+S", function () { saveAs(); }, { description: "Save as..." });
  1973. registerShortcut("Ctrl+O", function () { openDialog(); }, { description: "Open..." });
  1974. registerShortcut("Ctrl+Alt+N", function () { newDocument(); }, { description: "New document" });
  1975. registerShortcut("Ctrl+P", function () { printDoc(); }, { description: "Print" });
  1976. registerShortcut("Ctrl+=", function () { zoomStep(1); }, { description: "Zoom in" });
  1977. registerShortcut("Ctrl++", function () { zoomStep(1); });
  1978. registerShortcut("Ctrl+-", function () { zoomStep(-1); }, { description: "Zoom out" });
  1979. registerShortcut("Ctrl+0", function () { setZoom(100); }, { description: "Reset zoom" });
  1980. // non-passive so the browser's own page zoom can be preventDefault-ed
  1981. window.addEventListener("wheel", onWheelZoom, { passive: false });
  1982. if (cfg.onUndo) registerShortcut("Ctrl+Z", function () { cfg.onUndo(); }, { description: "Undo" });
  1983. if (cfg.onRedo) {
  1984. registerShortcut("Ctrl+Y", function () { cfg.onRedo(); }, { description: "Redo" });
  1985. registerShortcut("Ctrl+Shift+Z", function () { cfg.onRedo(); });
  1986. }
  1987. if (window.OfficeHotkeys) {
  1988. registerShortcut("Ctrl+/", function () { OfficeHotkeys.showHelp(); },
  1989. { description: "Keyboard shortcuts help" });
  1990. // Escape falls through (return false) so app-level Escape
  1991. // handlers still run after any open menu is closed
  1992. OfficeHotkeys.register("Escape", function () {
  1993. closeAllMenus();
  1994. return false;
  1995. }, { id: "of.menuclose", allowInInput: true, inDialogs: true });
  1996. } else {
  1997. window.addEventListener("keydown", handleKeydown, true);
  1998. }
  1999. // theme + zoom
  2000. applyTheme();
  2001. window.desktopThemeChanged = followHostTheme;
  2002. zoom = getSetting("zoom", 100);
  2003. applyZoom();
  2004. // housekeeping
  2005. pruneDrafts();
  2006. // load input file (embedded / open-with) or start blank
  2007. meta = { createdAt: now(), revision: 0 };
  2008. var inputs = OfficePlatform.loadInputFiles(cfg.extension);
  2009. if (inputs && inputs.length > 0) {
  2010. cfg.create();
  2011. openPath(inputs[0].filepath, inputs[0].filename,
  2012. { asTemplate: !!inputs[0].asTemplate });
  2013. } else {
  2014. cfg.create();
  2015. markClean();
  2016. splashDone();
  2017. trySessionRestore(); // falls back to checkDraft() itself
  2018. }
  2019. // autosave + unload guard
  2020. autosaveTimer = setInterval(autosaveTick, AUTOSAVE_INTERVAL);
  2021. window.addEventListener("beforeunload", function (e) {
  2022. if (dirty) {
  2023. saveDraft();
  2024. e.preventDefault();
  2025. e.returnValue = "";
  2026. }
  2027. });
  2028. installFloatWindowCloseGuard();
  2029. installStandaloneDropOpen();
  2030. updateTitle();
  2031. // the web edition has no storage behind it - say so once, so "Save
  2032. // downloads a copy" is not a surprise the first time (a desktop
  2033. // shell saves to real files and needs no such warning)
  2034. if (OfficePlatform.mode() === "standalone" && (!inputs || !inputs.length)) {
  2035. setStatus("Web edition - open a " + cfg.extension +
  2036. " from this device, and Save downloads it back", "info", 9000);
  2037. }
  2038. }
  2039. /*
  2040. Standalone build: dropping a document on the window opens it.
  2041. This is the whole point of the web edition - somebody was sent a
  2042. .docx and wants to look at it - so it is worth a drop target even
  2043. though the apps already handle drops of their own.
  2044. It listens in the capture phase but only claims the event when every
  2045. dropped file is one this app can open; anything else (an image being
  2046. dropped into the page, say) falls straight through to the app's own
  2047. handler untouched.
  2048. */
  2049. function installStandaloneDropOpen() {
  2050. if (!OfficePlatform.isStandalone()) return;
  2051. var openable = function (name) {
  2052. var e = extOf(name);
  2053. return e === cfg.extension || !!(cfg.importers || {})[e] || !!binaryImporters()[e] ||
  2054. isLegacyExt(e) || !!importFormatFor(e);
  2055. };
  2056. var claims = function (e) {
  2057. var dt = e.dataTransfer;
  2058. if (!dt || !dt.files || dt.files.length !== 1) return false;
  2059. return openable(dt.files[0].name);
  2060. };
  2061. document.addEventListener("dragover", function (e) {
  2062. if (!claims(e)) return;
  2063. e.preventDefault();
  2064. e.stopPropagation();
  2065. e.dataTransfer.dropEffect = "copy";
  2066. }, true);
  2067. document.addEventListener("drop", function (e) {
  2068. if (!claims(e)) return;
  2069. e.preventDefault();
  2070. e.stopPropagation();
  2071. var file = e.dataTransfer.files[0];
  2072. var go = function () { OfficePlatform.adoptDroppedFile(file, openPath); };
  2073. if (dirty) {
  2074. confirmDialog("Discard unsaved changes?",
  2075. "The current document has unsaved changes that will be lost.",
  2076. "Discard", "Cancel", function (yes) { if (yes) go(); });
  2077. } else { go(); }
  2078. }, true);
  2079. }
  2080. /*
  2081. Ask before a window holding unsaved changes goes away. done() once
  2082. it may close - nothing to lose, saved, or the changes thrown away;
  2083. cancelled() when the person keeps it open. The ArozOS desktop asks
  2084. through ao_module_close (below), a desktop shell through
  2085. OfficeNative.requestClose.
  2086. */
  2087. function requestClose(done, cancelled) {
  2088. cancelled = cancelled || function () { };
  2089. if (!dirty) { done(); return; }
  2090. // with AutoSave on, closing is one more autosave: the document goes
  2091. // back into its file and the window closes - no question to answer.
  2092. // Only when that cannot happen (never saved, a format that cannot
  2093. // hold it, the write failed) does the window ask.
  2094. if (canAutosaveOnClose()) {
  2095. saveWithProgress(save, done, function (err) {
  2096. if (err) toast("Could not save " + (filename || "the document") + ": " + err, "error");
  2097. askBeforeClose(done, cancelled);
  2098. });
  2099. return;
  2100. }
  2101. askBeforeClose(done, cancelled);
  2102. }
  2103. function canAutosaveOnClose() {
  2104. if (!autosaveEnabled() || !filepath || !OfficePlatform.autosavesToFile()) return false;
  2105. var ext = extOf(filename);
  2106. if (ext === cfg.extension) return true;
  2107. // a foreign format: only when it can still hold the document
  2108. var fmt = findSaveFormat(ext, false);
  2109. return !!fmt && !formatReasons(fmt);
  2110. }
  2111. /*
  2112. Run a save (save or saveAs) behind a progress panel: the window is
  2113. about to close, so it holds the screen until the file is written -
  2114. a save that uploads megabytes must not look like a frozen window.
  2115. done() once the file is saved, failed(message) when it was not (a
  2116. null message: declined or cancelled, nothing to report).
  2117. */
  2118. function saveWithProgress(run, done, failed) {
  2119. var ui = null, over = false;
  2120. var stages = {
  2121. wait: [2, "Waiting for the previous save..."],
  2122. prepare: [8, "Preparing the document..."],
  2123. compress: [16, "Compressing..."],
  2124. server: [90, "Writing " + (filename || "the file") + "..."]
  2125. };
  2126. var obs = {
  2127. progress: function (stage, pct) {
  2128. if (over) return;
  2129. if (!ui) ui = showSaveProgress(filename || (cfg.defaultFileName + cfg.extension));
  2130. if (stage === "upload") {
  2131. var p = Math.max(0, Math.min(100, pct || 0));
  2132. ui.set(18 + p * 0.7, "Uploading... " + Math.round(p) + "%", false);
  2133. } else if (stages[stage]) {
  2134. ui.set(stages[stage][0], stages[stage][1], stage === "server" || stage === "wait");
  2135. }
  2136. },
  2137. fail: function (err) {
  2138. if (over) return;
  2139. over = true;
  2140. if (ui) ui.close();
  2141. failed(err);
  2142. }
  2143. };
  2144. run(function () {
  2145. if (over) return;
  2146. over = true;
  2147. if (!ui) { done(); return; }
  2148. ui.set(100, "Saved", false);
  2149. setTimeout(function () { ui.close(); done(); }, 300);
  2150. }, obs);
  2151. }
  2152. function showSaveProgress(name) {
  2153. var $o = $('<div class="of-saveprog-overlay of-noprint" role="dialog" aria-live="polite">' +
  2154. '<div class="of-saveprog"><div class="of-saveprog-title"></div>' +
  2155. '<div class="of-saveprog-bar"><div class="of-saveprog-fill"></div></div>' +
  2156. '<div class="of-saveprog-msg"></div></div></div>');
  2157. $o.find(".of-saveprog-title").text("Saving " + name);
  2158. $("body").append($o);
  2159. return {
  2160. set: function (pct, msg, busy) {
  2161. $o.find(".of-saveprog-fill").css("width", pct + "%");
  2162. $o.find(".of-saveprog-bar").toggleClass("busy", !!busy);
  2163. $o.find(".of-saveprog-msg").text(msg || "");
  2164. },
  2165. close: function () { $o.remove(); }
  2166. };
  2167. }
  2168. function askBeforeClose(done, cancelled) {
  2169. dialog({
  2170. title: "Unsaved changes",
  2171. body: "<b>" + escapeHtml(filename || (cfg.defaultFileName + cfg.extension)) +
  2172. "</b> has unsaved changes. Close it anyway?",
  2173. dismissable: true,
  2174. onDismiss: cancelled,
  2175. buttons: [
  2176. { label: "Cancel", action: function (close) { close(); cancelled(); } },
  2177. {
  2178. label: "Close without saving", danger: true,
  2179. action: function (close) {
  2180. close();
  2181. markClean(); // never re-prompt while the window tears down
  2182. done();
  2183. }
  2184. },
  2185. {
  2186. label: "Save & close", primary: true,
  2187. // only a save that worked closes the window: a failed
  2188. // or cancelled one leaves it open with the changes
  2189. action: function (close) {
  2190. close();
  2191. // a document never saved asks for a file first, and
  2192. // the picker does not report a cancel: release the
  2193. // close request now (a saved file still closes it)
  2194. var asked = !filepath;
  2195. if (asked) cancelled();
  2196. saveWithProgress(save, done, function (err) {
  2197. if (err) toast("Could not save: " + err, "error");
  2198. if (!asked) cancelled();
  2199. });
  2200. }
  2201. }
  2202. ]
  2203. });
  2204. }
  2205. /* The desktop routes a floatWindow's X button through the iframe's
  2206. ao_module_close() (see ao_module.js + desktop.html: it calls
  2207. contentWindow.ao_module_close() when defined). beforeunload does NOT
  2208. fire when the desktop just removes the iframe, so override that hook
  2209. to confirm before discarding unsaved changes. */
  2210. function installFloatWindowCloseGuard() {
  2211. if (typeof window.ao_module_close !== "function") return;
  2212. var reallyClose = function () {
  2213. markClean(); // never re-prompt while the window tears down
  2214. // closed for good (saved, or changes thrown away): its working
  2215. // copies can go now rather than wait for the nightly sweep
  2216. OfficePlatform.releaseWorkdir();
  2217. if (typeof window.ao_module_closeHandler === "function") {
  2218. ao_module_closeHandler();
  2219. }
  2220. };
  2221. window.ao_module_close = function () { requestClose(reallyClose); };
  2222. }
  2223. /* ---------- public API ---------- */
  2224. return {
  2225. init: init,
  2226. // lifecycle
  2227. newDocument: newDocument,
  2228. open: openDialog,
  2229. openPath: openPath,
  2230. save: save,
  2231. saveAs: saveAs,
  2232. exportFormat: exportFormat,
  2233. print: printDoc,
  2234. // ask before the window closes: done() = it may, cancelled() = kept
  2235. requestClose: requestClose,
  2236. markDirty: markDirty,
  2237. isDirty: function () { return dirty; },
  2238. getFilePath: function () { return filepath; },
  2239. getFileName: function () { return filename; },
  2240. getMeta: function () { return meta; },
  2241. wasImported: function () { return loadedFromImport; },
  2242. // ui
  2243. setStatus: setStatus,
  2244. addStatusItem: addStatusItem,
  2245. updateStatusItem: updateStatusItem,
  2246. dialog: dialog,
  2247. confirm: confirmDialog,
  2248. prompt: promptDialog,
  2249. toast: toast,
  2250. showContextMenu: showContextMenu,
  2251. showBusy: showBusy,
  2252. hideBusy: hideBusy,
  2253. documentLoaded: documentLoaded,
  2254. splashStep: splashStep,
  2255. showProgress: showProgress,
  2256. beginDrag: beginDrag,
  2257. closeAllMenus: closeAllMenus,
  2258. updateMenus: updateMenus,
  2259. // features
  2260. registerShortcut: registerShortcut,
  2261. print: printDoc,
  2262. // the Edit commands, for an app's own ribbon (op: cut | copy | paste)
  2263. clipboard: clipboardAction,
  2264. showClipboardPane: showClipboardPane,
  2265. autosaveEnabled: autosaveEnabled,
  2266. setAutosave: function (on) { setSetting("autosave", !!on); refreshQat(); },
  2267. // the title bar's slot for an app's own buttons (right-hand side)
  2268. titleBarSlot: function () { return $(".of-titleextras"); },
  2269. setZoom: setZoom,
  2270. getZoom: function () { return zoom; },
  2271. zoomIn: function () { zoomStep(1); },
  2272. zoomOut: function () { zoomStep(-1); },
  2273. toggleTheme: toggleTheme,
  2274. isDark: isDark,
  2275. // storage
  2276. getSetting: getSetting,
  2277. setSetting: setSetting,
  2278. getRecents: getRecents,
  2279. // host (see common/platform.js)
  2280. hasBackend: function () { return OfficePlatform.hasBackend(); },
  2281. isStandalone: function () { return OfficePlatform.isStandalone(); },
  2282. // vfs / media
  2283. vfsLoad: vfsLoad,
  2284. vfsSave: vfsSave,
  2285. blobToSrc: blobToSrc,
  2286. mediaUrl: mediaUrl,
  2287. agirunLarge: agirunLarge,
  2288. // utils
  2289. escapeHtml: escapeHtml,
  2290. basename: basename,
  2291. dirname: dirname,
  2292. extOf: extOf,
  2293. stripExt: stripExt
  2294. };
  2295. })();