editor.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. /*
  2. Code Studio — editor core
  3. Monaco instances, editor groups, tabs and file IO. The workbench
  4. chrome around it lives in workbench.js.
  5. */
  6. /* ═══════════════════════════════════════════════════════════════════
  7. Environment
  8. ═══════════════════════════════════════════════════════════════════ */
  9. let editors = []; //All editor groups currently on screen
  10. let focusedEditor = "mainEditor"; //uuid of the focused editor group
  11. let loadedModels = []; //filepath -> monaco model, avoids duplicates
  12. let focusedFileInfo = [];
  13. let currentProjectFolder = null; //Virtual path of the opened project folder
  14. let selectedFolderItem = null; //Item the folder context menu acts on
  15. let selectedTabInfo = null; //Tab the tab context menu acts on
  16. let untitledCounter = 0;
  17. let editorGroupCounter = 1;
  18. //Hashcode used to tell a modified buffer from a saved one
  19. String.prototype.hashCode = function() {
  20. var hash = 0;
  21. if (this.length == 0) return hash;
  22. for (var i = 0; i < this.length; i++) {
  23. hash = ((hash << 5) - hash) + this.charCodeAt(i);
  24. hash = hash & hash;
  25. }
  26. return hash;
  27. }
  28. /* ═══════════════════════════════════════════════════════════════════
  29. Editor group lifecycle
  30. ═══════════════════════════════════════════════════════════════════ */
  31. function getEditor(uuid){
  32. for (var i = 0; i < editors.length; i++){
  33. if (editors[i].uuid == uuid) return editors[i];
  34. }
  35. return undefined;
  36. }
  37. function getFocusedEditorObject(){
  38. var editorObject = getEditor(focusedEditor);
  39. if (editorObject === undefined && editors.length > 0) editorObject = editors[0];
  40. return editorObject;
  41. }
  42. /*
  43. The AMD loader turns a module id into a relative URL and lets the browser
  44. resolve it against the document URL. Anchoring it to the loader <script>
  45. tag's own (already absolute) URL instead keeps Monaco's lazy language loads
  46. working regardless of what the page URL looks like later on.
  47. */
  48. function monacoRootPath(){
  49. var loaderScript = document.querySelector('script[src*="monaco/vs/loader.js"]');
  50. if (loaderScript && loaderScript.src){
  51. return loaderScript.src.substring(0, loaderScript.src.lastIndexOf("/"));
  52. }
  53. return "script/monaco/vs";
  54. }
  55. function initEditor(targetDOM, editorUUID, loadPendingFiles = [], callback = undefined){
  56. //One loader configuration is enough, even when more editor groups are added
  57. if (!window.csMonacoConfigured){
  58. window.csMonacoConfigured = true;
  59. require.config({ paths: { 'vs': monacoRootPath() }});
  60. }
  61. window.GlobalEnvironment = { getWorkerUrl: () => proxy };
  62. let proxy = URL.createObjectURL(new Blob([`
  63. self.GlobalEnvironment = {
  64. baseUrl: 'script/monaco/'
  65. };
  66. importScripts('script/monaco/vs/base/worker/workerMain.js');
  67. `], { type: 'text/javascript' }));
  68. require(["vs/editor/editor.main"], function () {
  69. defineMonacoThemes();
  70. let editor = monaco.editor.create(targetDOM, {
  71. value: "",
  72. language: 'javascript',
  73. automaticLayout: true,
  74. theme: CS_THEMES[CS_PREF.theme].monaco,
  75. fontSize: CS_PREF.fontSize,
  76. minimap: { enabled: CS_PREF.minimap },
  77. wordWrap: CS_PREF.wordWrap ? "on" : "off",
  78. lineNumbers: CS_PREF.lineNumbers ? "on" : "off",
  79. scrollBeyondLastLine: false,
  80. renderLineHighlight: "all",
  81. smoothScrolling: true
  82. });
  83. editors.push({
  84. uuid: editorUUID,
  85. tabsMenu: $(targetDOM).parent().find(".tabs"),
  86. editor: editor,
  87. currentTabUUID: "default",
  88. model: [],
  89. state: [],
  90. tabs: []
  91. });
  92. bindEditorEvents(editor, editorUUID);
  93. //Load any file passed in from the file manager
  94. if (loadPendingFiles !== null && loadPendingFiles.length > 0){
  95. for (var i = 0; i < loadPendingFiles.length; i++){
  96. openFile(loadPendingFiles[i].filepath);
  97. }
  98. }
  99. if (callback !== undefined) callback(editor);
  100. });
  101. }
  102. function bindEditorEvents(editor, editorUUID){
  103. //Mark the tab dirty as soon as the buffer differs from the saved content
  104. editor.onDidChangeModelContent(function(){
  105. var editorObject = getEditor(editorUUID);
  106. if (!editorObject) return;
  107. var currentTab = editorObject.tabs.find(function(tab){
  108. return tab.tabUUID == editorObject.currentTabUUID;
  109. });
  110. if (!currentTab) return;
  111. markTabUnsaved(currentTab.tabUUID, editor.getValue().hashCode() !== currentTab.saveHash);
  112. });
  113. editor.onDidChangeCursorPosition(function(event){
  114. if (focusedEditor == editorUUID) updateCursorStatus(event.position);
  115. });
  116. editor.onDidFocusEditorText(function(){
  117. focusedEditor = editorUUID;
  118. updateLanguageStatus(editor.getModel());
  119. });
  120. //Ctrl+S — save the file behind the focused tab
  121. editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function(){
  122. focusedEditor = editorUUID;
  123. saveCurrentFile();
  124. });
  125. //Diagnostics are global to Monaco, so only ever subscribe once
  126. if (!window.csMarkerListenerBound && monaco.editor.onDidChangeMarkers){
  127. window.csMarkerListenerBound = true;
  128. monaco.editor.onDidChangeMarkers(function(){ refreshProblems(); });
  129. }
  130. }
  131. //Add a second (or third …) editor group beside the current one
  132. function splitEditor(){
  133. editorGroupCounter++;
  134. var groupUUID = "editor" + editorGroupCounter;
  135. var groupID = "ca" + editorGroupCounter;
  136. $("#codeArea").append(
  137. '<div id="' + groupID + '" class="codeBoard">' +
  138. '<div class="tabs" editorUID="' + groupUUID + '" ondrop="TabDrop(event)" ondragover="allowDrop(event)"></div>' +
  139. '<div class="editor" editorUID="' + groupUUID + '" onclick="focusThisEditor(this);"></div>' +
  140. '<div class="editorcover" editorUID="' + groupUUID + '" onclick="focusThisEditor(this);"></div>' +
  141. '</div>');
  142. initEditor($("#" + groupID).find(".editor")[0], groupUUID, [], function(){
  143. focusedEditor = groupUUID;
  144. $("#" + groupID).find(".editorcover").html(
  145. '<div class="welcome"><h1>Editor group ' + editorGroupCounter + '</h1>' +
  146. '<div class="tagline">Drag a tab here, or open a file from the explorer.</div></div>');
  147. relayoutEditors();
  148. });
  149. }
  150. function closeEditorGroup(editorUUID){
  151. if (editors.length <= 1) return; //never close the last group
  152. var editorObject = getEditor(editorUUID);
  153. if (!editorObject) return;
  154. editorObject.tabs.slice().forEach(function(tab){
  155. closeTabWithUUIDAndEditorID(tab.tabUUID, editorUUID);
  156. });
  157. try { editorObject.editor.dispose(); } catch(e){ /* already disposed */ }
  158. $(editorObject.tabsMenu).parent().remove();
  159. editors = editors.filter(function(entry){ return entry.uuid != editorUUID; });
  160. focusedEditor = editors[0].uuid;
  161. relayoutEditors();
  162. }
  163. /* ═══════════════════════════════════════════════════════════════════
  164. Session state (window hash)
  165. ═══════════════════════════════════════════════════════════════════ */
  166. /*
  167. The opened folder and files are mirrored into the window hash so a browser
  168. reload restores the session.
  169. Under the web desktop the app runs inside a floatWindow whose URL belongs to
  170. the desktop: writing to location.hash there makes the host re-navigate the
  171. frame, which reloads the editor and aborts whatever Monaco was lazily
  172. loading at that moment (the "[object Event]" loader error). So in that mode
  173. the state is only kept in memory — the desktop restores windows itself.
  174. */
  175. let csSessionState = null; //In-memory mirror of the session state
  176. function getHashObject(){
  177. if (csSessionState !== null) return csSessionState;
  178. csSessionState = {};
  179. if (window.location.hash.length > 1){
  180. try {
  181. var parsed = JSON.parse(decodeURIComponent(window.location.hash.substr(1)));
  182. //An array is a launch payload (the files to open), not a state object
  183. if (parsed && typeof parsed === "object" && !Array.isArray(parsed)){
  184. csSessionState = parsed;
  185. }
  186. } catch(e){ /* not a state object — start from an empty one */ }
  187. }
  188. return csSessionState;
  189. }
  190. function writeHashObject(newStateObject){
  191. csSessionState = newStateObject;
  192. if (ao_module_virtualDesktop) return;
  193. window.location.hash = JSON.stringify(newStateObject);
  194. }
  195. function updateStatusHash(key, value){
  196. var currentState = getHashObject();
  197. currentState[key] = value;
  198. writeHashObject(currentState);
  199. }
  200. function getOpenedFiles(){
  201. var openedFilepaths = [];
  202. editors.forEach(function(entry){
  203. entry.tabs.forEach(function(tab){
  204. if (tab.filepath && openedFilepaths.indexOf(tab.filepath) === -1){
  205. openedFilepaths.push(tab.filepath);
  206. }
  207. });
  208. });
  209. return openedFilepaths;
  210. }
  211. function restoreEditorState(editor){
  212. var oldState = getHashObject();
  213. if (oldState.folder !== undefined){
  214. var predictedName = oldState.folder.split("/").pop();
  215. if (oldState.folder.substr(oldState.folder.length - 1) == "/"){
  216. var parts = oldState.folder.split("/");
  217. parts.pop();
  218. predictedName = parts.pop();
  219. }
  220. //The hash already carries the tabs of this session, so the stored
  221. //workspace state must not open a second, older set on top of them
  222. var hashHasFiles = (oldState.files !== undefined && oldState.files.length > 0);
  223. openProjectFolder([{ filename: predictedName, filepath: oldState.folder }], false, !hashHasFiles);
  224. }
  225. if (oldState.files !== undefined){
  226. oldState.files.forEach(function(filepath){ openFile(filepath, false); });
  227. }
  228. }
  229. /* ═══════════════════════════════════════════════════════════════════
  230. Tabs
  231. ═══════════════════════════════════════════════════════════════════ */
  232. function fileIconMarkup(filename, isError){
  233. if (isError) return '<i class="times circle icon" style="color:var(--err);"></i>';
  234. var ext = filename.split(".").pop().toLowerCase();
  235. var icon = ao_module_utils.getIconFromExt(ext);
  236. return '<i class="' + icon + ' icon ' + getFileIconClass(ext) + '"></i>';
  237. }
  238. function appendTabToDOM(editorObject, tab, isError){
  239. var editorUUID = editorObject.uuid;
  240. var icon = fileIconMarkup(tab.filename, isError);
  241. var pathAttr = tab.filepath ? tab.filepath : "";
  242. $(editorObject.tabsMenu).find(".item.selected").removeClass("selected");
  243. $(editorObject.tabsMenu).append(
  244. '<div class="item selected fileTab" title="' + escapeHTMLText(pathAttr || tab.filename) + '" draggable="true" ' +
  245. 'ondragstart="fileTabDrag(event)" uuid="' + tab.tabUUID + '" editorUUID="' + editorUUID + '" ' +
  246. 'filepath="' + escapeHTMLText(pathAttr) + '">' +
  247. icon +
  248. '<span class="tabFilename">' + escapeHTMLText(tab.filename) + '</span>' +
  249. '<div class="closebtn"><i class="times icon"></i></div>' +
  250. '</div>');
  251. $("#openeditors .row").removeClass("selected");
  252. $("#openeditors").append(
  253. '<div class="row selected" uuid="' + tab.tabUUID + '" editorUUID="' + editorUUID + '" ' +
  254. 'title="' + escapeHTMLText(pathAttr || tab.filename) + '">' +
  255. '<span class="rowbtn closebtn"><i class="times icon"></i></span>' +
  256. icon +
  257. '<span class="name tabFilename">' + escapeHTMLText(tab.filename) + '</span>' +
  258. '</div>');
  259. editorObject.currentTabUUID = tab.tabUUID;
  260. editorObject.tabs.push(tab);
  261. }
  262. function bindTabItemEvents(){
  263. $(".tabs .item").off("click").on("click", function(){
  264. if ($(this).hasClass("selected")) return;
  265. var editorUUID = $(this).attr("editorUUID");
  266. var targetEditor = getEditor(editorUUID);
  267. if (targetEditor === undefined) return;
  268. focusedEditor = editorUUID;
  269. changeTab(targetEditor, $(this).attr("uuid"));
  270. });
  271. $("#openeditors .row").off("click").on("click", function(){
  272. var tabUUID = $(this).attr("uuid");
  273. var editorUUID = $(this).attr("editorUUID");
  274. var targetEditor = getEditor(editorUUID);
  275. if (targetEditor === undefined) return;
  276. focusedEditor = editorUUID;
  277. changeTab(targetEditor, tabUUID);
  278. });
  279. $(".tabs .item .closebtn, #openeditors .row .closebtn").off("click").on("click", function(event){
  280. event.preventDefault();
  281. event.stopImmediatePropagation();
  282. var holder = $(this).closest(".item, .row");
  283. closeTabWithUUIDAndEditorID(holder.attr("uuid"), holder.attr("editorUUID"));
  284. });
  285. //A dirty tab shows a dot; hovering it turns the dot back into a close cross
  286. $(".tabs .item.dirty").off("mouseenter mouseleave").on("mouseenter", function(){
  287. $(this).find(".closebtn i").attr("class", "times icon");
  288. }).on("mouseleave", function(){
  289. if ($(this).hasClass("dirty")) $(this).find(".closebtn i").attr("class", "circle icon");
  290. });
  291. bindTabContextMenu();
  292. }
  293. function focusTabWithUUID(tabUUID){
  294. $(".tabs .item").removeClass("selected");
  295. $('.tabs .item[uuid="' + tabUUID + '"]').addClass("selected");
  296. $("#openeditors .row").removeClass("selected");
  297. $('#openeditors .row[uuid="' + tabUUID + '"]').addClass("selected");
  298. }
  299. //Kept for API compatibility with the previous version
  300. function focusTab(uuid){ focusTabWithUUID(uuid); }
  301. function removeTabFromDOMWithUUID(tabUUID){
  302. $('.tabs .item[uuid="' + tabUUID + '"]').remove();
  303. $('#openeditors .row[uuid="' + tabUUID + '"]').remove();
  304. }
  305. function getFocusedTabInfo(){
  306. var editorObject = getFocusedEditorObject();
  307. if (!editorObject) return undefined;
  308. for (var i = 0; i < editorObject.tabs.length; i++){
  309. if (editorObject.tabs[i].tabUUID == editorObject.currentTabUUID){
  310. focusedFileInfo = editorObject.tabs[i];
  311. return editorObject.tabs[i];
  312. }
  313. }
  314. return undefined;
  315. }
  316. function getCodeAreaFromEditorUUID(editorUUID){
  317. var editorObject = getEditor(editorUUID);
  318. if (!editorObject) return $();
  319. return $(editorObject.tabsMenu).parent();
  320. }
  321. function focusThisEditor(object){
  322. focusedEditor = $(object).attr("editorUID");
  323. var tabInfo = getFocusedTabInfo();
  324. if (tabInfo !== undefined){
  325. updateFileStatusDisplay(tabInfo.filepath || tabInfo.filename);
  326. focusTabWithUUID(tabInfo.tabUUID);
  327. }
  328. }
  329. function changeTab(editorObject, targettabUUID){
  330. focusedEditor = editorObject.uuid;
  331. var editor = editorObject.editor;
  332. var models = editorObject.model;
  333. var states = editorObject.state;
  334. //Stash the outgoing tab's view state
  335. states[editorObject.currentTabUUID] = editor.saveViewState();
  336. models[editorObject.currentTabUUID] = editor.getModel();
  337. editorObject.currentTabUUID = targettabUUID;
  338. var targetTab = editorObject.tabs.find(function(tab){ return tab.tabUUID == targettabUUID; });
  339. var codeArea = getCodeAreaFromEditorUUID(editorObject.uuid);
  340. if (targetTab && targetTab.error){
  341. $(codeArea).find(".editorcover")
  342. .html(buildErrorCoverHTML(targetTab.filepath, targettabUUID, editorObject.uuid)).show();
  343. } else {
  344. $(codeArea).find(".editorcover").hide();
  345. if (models[targettabUUID]) editor.setModel(models[targettabUUID]);
  346. if (states[targettabUUID]) editor.restoreViewState(states[targettabUUID]);
  347. editor.focus();
  348. updateLanguageStatus(editor.getModel());
  349. updateCursorStatus(editor.getPosition());
  350. }
  351. var tabInfo = getFocusedTabInfo();
  352. if (tabInfo){
  353. updateFileStatusDisplay(tabInfo.filepath || tabInfo.filename);
  354. refreshWindowTitle();
  355. }
  356. focusTabWithUUID(targettabUUID);
  357. scheduleProjectSessionSave();
  358. }
  359. function closeTabWithUUIDAndEditorID(tabUUID, editorUUID){
  360. var editorObject = getEditor(editorUUID);
  361. if (editorObject === undefined) return;
  362. delete editorObject.state[tabUUID];
  363. delete editorObject.model[tabUUID];
  364. editorObject.tabs = editorObject.tabs.filter(function(tab){ return tab.tabUUID != tabUUID; });
  365. removeTabFromDOMWithUUID(tabUUID);
  366. var currentState = getHashObject();
  367. currentState["files"] = getOpenedFiles();
  368. writeHashObject(currentState);
  369. scheduleProjectSessionSave();
  370. if (editorObject.tabs.length > 0){
  371. var newFocusedTabUUID = editorObject.tabs[editorObject.tabs.length - 1].tabUUID;
  372. changeTab(editorObject, newFocusedTabUUID);
  373. } else {
  374. var codeArea = getCodeAreaFromEditorUUID(editorUUID);
  375. $(codeArea).find(".editorcover").show();
  376. if (editors.length > 1){
  377. closeEditorGroup(editorUUID);
  378. } else {
  379. renderWelcomeScreen();
  380. updateFileStatusDisplay(null);
  381. refreshWindowTitle();
  382. }
  383. }
  384. }
  385. function markTabUnsaved(tabUUID, unsaved){
  386. var tab = $('.tabs .item[uuid="' + tabUUID + '"]');
  387. tab.toggleClass("dirty", unsaved);
  388. tab.find(".closebtn i").attr("class", unsaved ? "circle icon" : "times icon");
  389. $('#openeditors .row[uuid="' + tabUUID + '"]').toggleClass("unsaved", unsaved);
  390. }
  391. function getAllOpenedTabs(){
  392. var results = [];
  393. editors.forEach(function(entry){
  394. entry.tabs.forEach(function(tab){ results.push({ editor: entry, tab: tab }); });
  395. });
  396. return results;
  397. }
  398. /* ═══════════════════════════════════════════════════════════════════
  399. Opening files
  400. ═══════════════════════════════════════════════════════════════════ */
  401. function buildErrorCoverHTML(filepath, tabUUID, editorUUID){
  402. return '<div class="errorcover">' +
  403. '<i class="times circle icon" style="font-size:3em;color:var(--err);"></i>' +
  404. '<div class="headline">File or folder no longer exists</div>' +
  405. '<div class="path">' + escapeHTMLText(filepath) + '</div>' +
  406. '<button class="btn" onclick="closeTabWithUUIDAndEditorID(\'' + tabUUID + '\',\'' + editorUUID + '\')">Close File</button>' +
  407. '</div>';
  408. }
  409. function openFile(filepath, updateHashStatus = true, overrideEditor = undefined){
  410. var targetEditorGroup = overrideEditor || getFocusedEditorObject();
  411. if (targetEditorGroup === undefined){
  412. alert("Unable to load editor.");
  413. return;
  414. }
  415. //Already open in this group? Just focus it
  416. for (var i = 0; i < targetEditorGroup.tabs.length; i++){
  417. if (targetEditorGroup.tabs[i].filepath == filepath){
  418. changeTab(targetEditorGroup, targetEditorGroup.tabs[i].tabUUID);
  419. return;
  420. }
  421. }
  422. ao_module_agirun("Code Studio/backend/read.agi", { file: filepath }, function(filecontent){
  423. var filename = filepath.split("/").pop();
  424. //Missing file — show a placeholder tab instead of a broken model
  425. if (typeof filecontent === "object" && filecontent.error){
  426. var errorTab = { filename: filename, filepath: filepath, tabUUID: newTabUUID(), saveHash: 0, error: true };
  427. appendTabToDOM(targetEditorGroup, errorTab, true);
  428. $(getCodeAreaFromEditorUUID(targetEditorGroup.uuid)).find(".editorcover")
  429. .html(buildErrorCoverHTML(filepath, errorTab.tabUUID, targetEditorGroup.uuid)).show();
  430. bindTabItemEvents();
  431. focusTabWithUUID(errorTab.tabUUID);
  432. csLog("err", "Cannot open " + filepath);
  433. return;
  434. }
  435. var editor = targetEditorGroup.editor;
  436. //Stash the outgoing view state before swapping models
  437. targetEditorGroup.state[targetEditorGroup.currentTabUUID] = editor.saveViewState();
  438. targetEditorGroup.model[targetEditorGroup.currentTabUUID] = editor.getModel();
  439. var tab = { filename: filename, filepath: filepath, tabUUID: newTabUUID(), saveHash: filecontent.hashCode() };
  440. appendTabToDOM(targetEditorGroup, tab, false);
  441. var model = loadedModels[filepath];
  442. if (model === undefined || model.isDisposed()){
  443. model = monaco.editor.createModel(
  444. filecontent,
  445. languageForFilename(filename),
  446. monaco.Uri.file("../media?file=" + encodeURIComponent(filepath))
  447. );
  448. loadedModels[filepath] = model;
  449. }
  450. targetEditorGroup.model[tab.tabUUID] = model;
  451. editor.setModel(model);
  452. $(getCodeAreaFromEditorUUID(targetEditorGroup.uuid)).find(".editorcover").hide();
  453. bindTabItemEvents();
  454. focusTabWithUUID(tab.tabUUID);
  455. updateFileStatusDisplay(filepath);
  456. updateLanguageStatus(model);
  457. refreshWindowTitle();
  458. if (updateHashStatus){
  459. var currentState = getHashObject();
  460. currentState["files"] = getOpenedFiles();
  461. writeHashObject(currentState);
  462. }
  463. scheduleProjectSessionSave();
  464. refreshGitDecorations();
  465. });
  466. }
  467. //Resolve the Monaco language from the file name, so the mode never depends on
  468. //how the model URI happens to be spelled. Returns undefined for unknown types,
  469. //which leaves the model as plain text.
  470. function languageForFilename(filename){
  471. var ext = "." + filename.split(".").pop().toLowerCase();
  472. if (ext == ".agi") return "javascript"; //AGI scripts are JavaScript
  473. var languages = monaco.languages.getLanguages();
  474. for (var i = 0; i < languages.length; i++){
  475. var extensions = languages[i].extensions || [];
  476. if (extensions.indexOf(ext) !== -1) return languages[i].id;
  477. }
  478. return undefined;
  479. }
  480. function newTabUUID(){
  481. //Timestamp based, with a counter so two tabs opened in the same millisecond differ
  482. untitledCounter++;
  483. return String(new Date().getTime()) + untitledCounter;
  484. }
  485. function newUntitledFile(){
  486. var editorObject = getFocusedEditorObject();
  487. if (!editorObject){
  488. alert("The editor is still starting up, please try again in a moment.");
  489. return;
  490. }
  491. var filename = "Untitled-" + (editorObject.tabs.filter(function(t){ return t.untitled; }).length + 1);
  492. var tab = { filename: filename, filepath: null, tabUUID: newTabUUID(), saveHash: "".hashCode(), untitled: true };
  493. editorObject.state[editorObject.currentTabUUID] = editorObject.editor.saveViewState();
  494. editorObject.model[editorObject.currentTabUUID] = editorObject.editor.getModel();
  495. appendTabToDOM(editorObject, tab, false);
  496. var model = monaco.editor.createModel("", "plaintext");
  497. editorObject.model[tab.tabUUID] = model;
  498. editorObject.editor.setModel(model);
  499. $(getCodeAreaFromEditorUUID(editorObject.uuid)).find(".editorcover").hide();
  500. bindTabItemEvents();
  501. focusTabWithUUID(tab.tabUUID);
  502. updateFileStatusDisplay(null);
  503. updateLanguageStatus(model);
  504. editorObject.editor.focus();
  505. }
  506. //Open a read-only, in-memory document — used for diffs and generated reports
  507. function openVirtualDocument(title, content, language){
  508. var editorObject = getFocusedEditorObject();
  509. if (!editorObject) return;
  510. var tab = { filename: title, filepath: null, tabUUID: newTabUUID(), saveHash: content.hashCode(), virtual: true };
  511. editorObject.state[editorObject.currentTabUUID] = editorObject.editor.saveViewState();
  512. editorObject.model[editorObject.currentTabUUID] = editorObject.editor.getModel();
  513. appendTabToDOM(editorObject, tab, false);
  514. var model = monaco.editor.createModel(content, language || "plaintext");
  515. editorObject.model[tab.tabUUID] = model;
  516. editorObject.editor.setModel(model);
  517. $(getCodeAreaFromEditorUUID(editorObject.uuid)).find(".editorcover").hide();
  518. bindTabItemEvents();
  519. focusTabWithUUID(tab.tabUUID);
  520. updateLanguageStatus(model);
  521. updateFileStatusDisplay(null);
  522. }
  523. function openFileWithSelector(){
  524. ao_module_openFileSelector(externalFileLoader, "user:/Desktop", "file", true);
  525. }
  526. function openFolderWithSelector(){
  527. ao_module_openFileSelector(openProjectFolder, "user:/Desktop", "folder");
  528. }
  529. function externalFileLoader(filedata){
  530. for (var i = 0; i < filedata.length; i++){
  531. openFile(filedata[i].filepath);
  532. }
  533. }
  534. /* ═══════════════════════════════════════════════════════════════════
  535. Saving
  536. ═══════════════════════════════════════════════════════════════════ */
  537. function saveCurrentFile(){
  538. var tabInfo = getFocusedTabInfo();
  539. if (!tabInfo){
  540. setStatusMessage("info circle", "Nothing to save");
  541. return;
  542. }
  543. if (tabInfo.untitled || !tabInfo.filepath){
  544. saveCurrentFileAs();
  545. return;
  546. }
  547. var content = getFocusedEditorObject().editor.getValue();
  548. saveContentToFile(tabInfo.tabUUID, tabInfo.filepath, content, function(data){
  549. if (data && data.error !== undefined){
  550. alert(data.error);
  551. csLog("err", "Save failed: " + data.error);
  552. } else {
  553. setStatusMessage("save", "Saved " + tabInfo.filename);
  554. csLog("ok", "Saved " + tabInfo.filepath);
  555. refreshGitDecorations();
  556. }
  557. });
  558. }
  559. function saveCurrentFileAs(){
  560. var tabInfo = getFocusedTabInfo();
  561. if (!tabInfo) return;
  562. var dirname = currentProjectFolder || "user:/Desktop/";
  563. var filename = tabInfo.filename;
  564. if (tabInfo.filepath){
  565. var parts = tabInfo.filepath.split("/");
  566. filename = parts.pop();
  567. dirname = parts.join("/") + "/";
  568. }
  569. ao_module_openFileSelector(writeToSaveAsFile, dirname, "new", false, { defaultName: filename });
  570. }
  571. function writeToSaveAsFile(filedata){
  572. if (!filedata || filedata.length == 0) return;
  573. var filepath = filedata[0].filepath;
  574. var filename = filedata[0].filename || filepath.split("/").pop();
  575. var tabInfo = getFocusedTabInfo();
  576. var content = getFocusedEditorObject().editor.getValue();
  577. syscall("writeFile", { filepath: filepath, content: content }, function(data){
  578. if (data && data.error !== undefined){
  579. alert(data.error);
  580. return;
  581. }
  582. //Re-point the tab at its new home
  583. if (tabInfo){
  584. tabInfo.filepath = filepath;
  585. tabInfo.filename = filename;
  586. tabInfo.untitled = false;
  587. tabInfo.saveHash = content.hashCode();
  588. $('.tabs .item[uuid="' + tabInfo.tabUUID + '"]').attr("filepath", filepath).attr("title", filepath);
  589. $('.tabs .item[uuid="' + tabInfo.tabUUID + '"] .tabFilename, #openeditors .row[uuid="' + tabInfo.tabUUID + '"] .tabFilename').text(filename);
  590. markTabUnsaved(tabInfo.tabUUID, false);
  591. updateFileStatusDisplay(filepath);
  592. }
  593. setStatusMessage("save", "Saved " + filename);
  594. csLog("ok", "Saved as " + filepath);
  595. refreshFolderTree();
  596. });
  597. }
  598. function saveAllFiles(){
  599. var beforeEditor = getFocusedEditorObject();
  600. var beforeTabInfo = getFocusedTabInfo();
  601. editors.forEach(function(entry){
  602. entry.tabs.forEach(function(tab){
  603. if (!tab.filepath || tab.error) return;
  604. var model = (entry.currentTabUUID == tab.tabUUID) ?
  605. entry.editor.getModel() : entry.model[tab.tabUUID];
  606. if (!model) return;
  607. var content = model.getValue();
  608. if (content.hashCode() === tab.saveHash) return; //unchanged
  609. saveContentToFile(tab.tabUUID, tab.filepath, content);
  610. });
  611. });
  612. if (beforeEditor && beforeTabInfo) changeTab(beforeEditor, beforeTabInfo.tabUUID);
  613. setStatusMessage("save", "All files saved");
  614. }
  615. function saveContentToFile(tabUUID, filepath, content, callback = undefined){
  616. syscall("writeFile", { filepath: filepath, content: content }, function(data){
  617. if (callback !== undefined) callback(data);
  618. var contentHash = content.hashCode();
  619. editors.forEach(function(entry){
  620. entry.tabs.forEach(function(tab){
  621. if (tab.tabUUID == tabUUID){
  622. tab.saveHash = contentHash;
  623. markTabUnsaved(tabUUID, false);
  624. }
  625. });
  626. });
  627. });
  628. }
  629. /* ═══════════════════════════════════════════════════════════════════
  630. Closing
  631. ═══════════════════════════════════════════════════════════════════ */
  632. function closeFileCurrentlyFocused(){
  633. var editorObject = getFocusedEditorObject();
  634. if (!editorObject) return;
  635. closeTabWithUUIDAndEditorID(editorObject.currentTabUUID, editorObject.uuid);
  636. }
  637. function closeAllFiles(){
  638. editors.slice().forEach(function(entry){
  639. entry.tabs.slice().forEach(function(tab){
  640. closeTabWithUUIDAndEditorID(tab.tabUUID, entry.uuid);
  641. });
  642. });
  643. }
  644. function closeTabsRight(){
  645. var editorObject = getFocusedEditorObject();
  646. if (!editorObject) return;
  647. closeTabsRelativeTo(editorObject, editorObject.currentTabUUID, "right");
  648. }
  649. function closeTabsLeft(){
  650. var editorObject = getFocusedEditorObject();
  651. if (!editorObject) return;
  652. closeTabsRelativeTo(editorObject, editorObject.currentTabUUID, "left");
  653. }
  654. function closeTabsRelativeTo(editorObject, anchorTabUUID, direction){
  655. var reached = false;
  656. var toClose = [];
  657. editorObject.tabs.forEach(function(tab){
  658. if (tab.tabUUID == anchorTabUUID){ reached = true; return; }
  659. if (direction == "right" && reached) toClose.push(tab.tabUUID);
  660. if (direction == "left" && !reached) toClose.push(tab.tabUUID);
  661. });
  662. toClose.forEach(function(tabUUID){ closeTabWithUUIDAndEditorID(tabUUID, editorObject.uuid); });
  663. if (editorObject.tabs.length > 0) changeTab(editorObject, anchorTabUUID);
  664. }
  665. function closeAllFilesWithConfirm(){
  666. var hasUnsaved = false;
  667. editors.forEach(function(entry){
  668. entry.tabs.forEach(function(tab){
  669. var model = entry.model[tab.tabUUID];
  670. if (model && model.getValue().hashCode() !== tab.saveHash) hasUnsaved = true;
  671. });
  672. });
  673. if (hasUnsaved && !confirm("Some files have unsaved changes. Close anyway?")) return;
  674. closeAllFiles();
  675. }
  676. function hanleUserExit(){
  677. if (getAllOpenedTabs().length > 0){
  678. if (confirm("Some files might not be saved. Confirm exit?")) ao_module_close();
  679. } else {
  680. ao_module_close();
  681. }
  682. }
  683. /* ═══════════════════════════════════════════════════════════════════
  684. Editor actions bound to the menus
  685. ═══════════════════════════════════════════════════════════════════ */
  686. function undo(){
  687. var editorObject = getFocusedEditorObject();
  688. if (!editorObject) return;
  689. editorObject.editor.trigger("codestudio", "undo", null);
  690. editorObject.editor.focus();
  691. }
  692. function redo(){
  693. var editorObject = getFocusedEditorObject();
  694. if (!editorObject) return;
  695. editorObject.editor.trigger("codestudio", "redo", null);
  696. editorObject.editor.focus();
  697. }
  698. //Clipboard actions still need a real user gesture in some browsers, so fall
  699. //back to a reminder dialog when the browser refuses the programmatic call.
  700. function showClipboardReminders(rt){
  701. var editorObject = getFocusedEditorObject();
  702. var monacoEditor = editorObject ? editorObject.editor : null;
  703. var actionMap = {
  704. 1: { action: "editor.action.clipboardCutAction", icon: "cut icon", hint: "Use the keyboard shortcut Ctrl + X to cut text from the editor." },
  705. 2: { action: "editor.action.clipboardCopyAction", icon: "copy icon", hint: "Use the keyboard shortcut Ctrl + C for copying text from the editor." },
  706. 3: { action: "editor.action.clipboardPasteAction", icon: "paste icon", hint: "Use the keyboard shortcut Ctrl + V for pasting to editor." },
  707. 4: { action: "actions.find", icon: "search icon", hint: "Press Ctrl + F on the editor to start searching." },
  708. 5: { action: "editor.action.startFindReplaceAction", icon: "sync alternate icon", hint: "Press Ctrl + H on the editor to start replacing text." }
  709. };
  710. var entry = actionMap[rt];
  711. if (!entry) return;
  712. function showFallback(){
  713. $("#clipboardReminderText").text(entry.hint);
  714. $("#clipboardReminderIcon").attr("class", entry.icon);
  715. $("#clipboardReminder").modal("show");
  716. }
  717. if (!monacoEditor){ showFallback(); return; }
  718. if (rt == 3 && navigator.clipboard && navigator.clipboard.readText){
  719. navigator.clipboard.readText().then(function(text){
  720. monacoEditor.focus();
  721. var selection = monacoEditor.getSelection();
  722. monacoEditor.executeEdits("paste", [{
  723. range: new monaco.Range(selection.startLineNumber, selection.startColumn,
  724. selection.endLineNumber, selection.endColumn),
  725. text: text,
  726. forceMoveMarkers: true
  727. }]);
  728. }).catch(showFallback);
  729. return;
  730. }
  731. try {
  732. monacoEditor.focus();
  733. monacoEditor.trigger("keyboard", entry.action, null);
  734. } catch(e){
  735. showFallback();
  736. }
  737. }
  738. /* ═══════════════════════════════════════════════════════════════════
  739. Status display helpers
  740. ═══════════════════════════════════════════════════════════════════ */
  741. function updateFileStatusDisplay(filepath){
  742. $("#sbPath").text(filepath ? filepath : "No file opened");
  743. refreshWindowTitle();
  744. }
  745. //"about.html — my-website", or just the project name when nothing is open
  746. function currentContextTitle(){
  747. var projectName = currentProjectFolder ?
  748. currentProjectFolder.split("/").filter(Boolean).pop() : null;
  749. var tabInfo = getFocusedTabInfo();
  750. var filename = tabInfo ? tabInfo.filename : null;
  751. if (filename && projectName) return filename + " — " + projectName;
  752. if (filename) return filename;
  753. if (projectName) return projectName;
  754. return "ArozOS Code Studio";
  755. }
  756. /*
  757. Where the context text goes depends on the host: the web desktop already
  758. draws a title bar for the floatWindow, so it is written there and the
  759. in-page title bar is hidden (see adaptChromeToHost).
  760. */
  761. function refreshWindowTitle(){
  762. var context = currentContextTitle();
  763. $("#titleContext").text(context);
  764. if (ao_module_virtualDesktop){
  765. ao_module_setWindowTitle(context);
  766. } else {
  767. document.title = (context == "ArozOS Code Studio") ? "Code Studio" : ("Code Studio - " + context);
  768. }
  769. }
  770. //Kept so older call sites keep working — the title is derived from the state
  771. function setWindowTitle(){ refreshWindowTitle(); }
  772. /* ═══════════════════════════════════════════════════════════════════
  773. External integrations
  774. ═══════════════════════════════════════════════════════════════════ */
  775. function getCurrentFocusedFileData(){
  776. var editorObject = getFocusedEditorObject();
  777. if (!editorObject) return null;
  778. for (var i = 0; i < editorObject.tabs.length; i++){
  779. var tab = editorObject.tabs[i];
  780. if (tab.tabUUID == editorObject.currentTabUUID && tab.filepath){
  781. return { filepath: tab.filepath, filename: tab.filename };
  782. }
  783. }
  784. return null;
  785. }
  786. function openFileInFileManager(){
  787. var fileData = getCurrentFocusedFileData();
  788. if (fileData == null) return;
  789. var parts = fileData.filepath.split("/");
  790. var filename = parts.pop();
  791. ao_module_openPath(parts.join("/"), filename);
  792. }
  793. function downloadFile(){
  794. var fileData = getCurrentFocusedFileData();
  795. if (fileData == null){
  796. alert("No file selected");
  797. return;
  798. }
  799. window.open("../../../media/download/?file=" + encodeURIComponent(fileData.filepath));
  800. }
  801. function openInNewTab(){
  802. var fileData = getCurrentFocusedFileData();
  803. if (fileData == null) return;
  804. window.open("./index.html#" + encodeURIComponent(JSON.stringify([fileData])));
  805. }
  806. function openInNewFloatWindow(){
  807. var fileData = getCurrentFocusedFileData();
  808. if (fileData == null) return;
  809. ao_module_newfw({
  810. url: "Code Studio/index.html#" + encodeURIComponent(JSON.stringify([fileData])),
  811. width: 1024,
  812. height: 720,
  813. appicon: "Code Studio/img/module_icon.png",
  814. title: "Code Studio"
  815. });
  816. }
  817. function newEditor(){
  818. ao_module_newfw({
  819. url: "Code Studio/index.html",
  820. width: 1024,
  821. height: 720,
  822. appicon: "Code Studio/img/module_icon.png",
  823. title: "Code Studio"
  824. });
  825. }
  826. //Legacy entry points — the tool system now handles both launch modes
  827. function showColorPicker(){ openTool("colorpicker"); }
  828. function showMobiPreview(){ openTool("mobipreview"); }
  829. function showCompareTool(launchPayload = undefined){ openTool("compare", undefined, launchPayload); }
  830. function compareCurrentProjectFolder(){
  831. if (!currentProjectFolder){
  832. alert("No project folder is open. Use File > Open Folder first.");
  833. return;
  834. }
  835. openTool("compare", undefined, { type: "folder", left: currentProjectFolder, right: "" });
  836. }
  837. function compareCurrentFile(){
  838. var fileData = getCurrentFocusedFileData();
  839. if (fileData == null){
  840. alert("No editing file found!");
  841. return;
  842. }
  843. openTool("compare", undefined, { type: "pick", left: fileData.filepath, right: "" });
  844. }
  845. function showLicense(){ $("#licenseInfo").modal("show"); }
  846. function showAboutCodeStudio(){ $("#aboutnpa").modal("show"); }
  847. /* ═══════════════════════════════════════════════════════════════════
  848. Backend plumbing
  849. ═══════════════════════════════════════════════════════════════════ */
  850. function syscall(scriptName, data, callback = undefined){
  851. $.ajax({
  852. url: "../system/ajgi/interface?script=Code Studio/backend/" + scriptName + ".agi",
  853. method: "POST",
  854. data: data,
  855. success: function(response){
  856. if (callback !== undefined) callback(response);
  857. },
  858. error: function(){
  859. if (callback !== undefined) callback({ error: "Backend call failed: " + scriptName });
  860. }
  861. });
  862. }
  863. function setStorage(key, value){ syscall("store", { opr: "set", key: key, value: value }); }
  864. function getStorage(key, callback){ syscall("store", { opr: "get", key: key }, callback); }
  865. /* ═══════════════════════════════════════════════════════════════════
  866. Tab drag and drop
  867. ═══════════════════════════════════════════════════════════════════ */
  868. function allowDrop(event){ event.preventDefault(); }
  869. function fileTabDrag(event){
  870. var tab = $(event.target).closest(".item");
  871. event.dataTransfer.setData("uuid", tab.attr("uuid"));
  872. event.dataTransfer.setData("filename", tab.find(".tabFilename").text());
  873. event.dataTransfer.setData("filepath", tab.attr("filepath"));
  874. event.dataTransfer.setData("sourceEditorUUID", tab.attr("editorUUID"));
  875. event.dataTransfer.effectAllowed = "move";
  876. }
  877. function directoryFileDrag(event){
  878. var source = $(event.target).closest("[data-path]");
  879. event.dataTransfer.setData("uuid", new Date().getTime());
  880. event.dataTransfer.setData("filename", source.data("name"));
  881. event.dataTransfer.setData("filepath", source.data("path"));
  882. event.dataTransfer.effectAllowed = "move";
  883. }
  884. function TabDrop(event){
  885. if (!$(event.target).hasClass("tabs")) return;
  886. event.preventDefault();
  887. var tabUUID = event.dataTransfer.getData("uuid");
  888. var tabFilepath = event.dataTransfer.getData("filepath");
  889. var sourceEditorUUID = event.dataTransfer.getData("sourceEditorUUID");
  890. if (!tabFilepath) return;
  891. var targetEditor = getEditor($(event.target).attr("editoruid"));
  892. if (targetEditor == undefined) return;
  893. if (sourceEditorUUID && sourceEditorUUID !== targetEditor.uuid){
  894. closeTabWithUUIDAndEditorID(tabUUID, sourceEditorUUID);
  895. }
  896. openFile(tabFilepath, true, targetEditor);
  897. }
  898. /* ═══════════════════════════════════════════════════════════════════
  899. Tab context menu
  900. ═══════════════════════════════════════════════════════════════════ */
  901. function bindTabContextMenu(){
  902. $(".tabs .item").off("contextmenu").on("contextmenu", function(event){
  903. event.preventDefault();
  904. event.stopPropagation();
  905. selectedTabInfo = {
  906. tabUUID: $(this).attr("uuid"),
  907. editorUUID: $(this).attr("editorUUID"),
  908. filepath: $(this).attr("filepath"),
  909. element: this
  910. };
  911. var items = [
  912. { label: "Close", action: "closeCurrentTab()" },
  913. { label: "Close Others", action: "closeOtherTabs()" },
  914. { label: "Close to the Right", action: "closeTabsToTheRight()" },
  915. { label: "Close to the Left", action: "closeTabsToTheLeft()" },
  916. { divider: true },
  917. { label: "Close All", action: "closeAllTabsInEditor()" },
  918. { divider: true },
  919. { label: "Split Editor Group", action: "splitEditor()" },
  920. { label: "Copy Path", action: "copyFilePathFromTab()" },
  921. { label: "Reveal in File Manager", action: "revealTabInFileManager()" }
  922. ];
  923. showFloatingMenu("#tabContextMenu", items, event.clientX, event.clientY);
  924. });
  925. }
  926. //Shared renderer for the two right-click menus
  927. function showFloatingMenu(selector, items, x, y){
  928. var menu = $(selector);
  929. menu.html(renderMenu(items)).css({ left: 0, top: 0 }).show();
  930. var left = x, top = y;
  931. if (left + menu.outerWidth() > window.innerWidth - 6) left = window.innerWidth - menu.outerWidth() - 6;
  932. if (top + menu.outerHeight() > window.innerHeight - 6) top = Math.max(6, y - menu.outerHeight());
  933. menu.css({ left: left + "px", top: top + "px" });
  934. /*
  935. Dismiss on the next press *outside* the menu. A blanket mousedown
  936. handler would hide the menu between mousedown and mouseup, so the
  937. browser would never generate a click on the item under the cursor and
  938. the entry would silently do nothing.
  939. */
  940. setTimeout(function(){
  941. $(document).off("mousedown.csmenu").on("mousedown.csmenu", function(event){
  942. if ($(event.target).closest(".menupanel").length > 0) return;
  943. dismissAllMenus();
  944. });
  945. }, 0);
  946. }
  947. function hideTabContextMenu(){ $("#tabContextMenu").hide(); }
  948. function closeCurrentTab(){
  949. if (!selectedTabInfo) return;
  950. closeTabWithUUIDAndEditorID(selectedTabInfo.tabUUID, selectedTabInfo.editorUUID);
  951. }
  952. function closeOtherTabs(){
  953. if (!selectedTabInfo) return;
  954. var editorObject = getEditor(selectedTabInfo.editorUUID);
  955. if (!editorObject) return;
  956. var anchor = selectedTabInfo.tabUUID;
  957. editorObject.tabs.slice().forEach(function(tab){
  958. if (tab.tabUUID != anchor) closeTabWithUUIDAndEditorID(tab.tabUUID, editorObject.uuid);
  959. });
  960. changeTab(editorObject, anchor);
  961. }
  962. function closeTabsToTheRight(){
  963. if (!selectedTabInfo) return;
  964. var editorObject = getEditor(selectedTabInfo.editorUUID);
  965. if (editorObject) closeTabsRelativeTo(editorObject, selectedTabInfo.tabUUID, "right");
  966. }
  967. function closeTabsToTheLeft(){
  968. if (!selectedTabInfo) return;
  969. var editorObject = getEditor(selectedTabInfo.editorUUID);
  970. if (editorObject) closeTabsRelativeTo(editorObject, selectedTabInfo.tabUUID, "left");
  971. }
  972. function closeAllTabsInEditor(){
  973. if (!selectedTabInfo) return;
  974. var editorObject = getEditor(selectedTabInfo.editorUUID);
  975. if (!editorObject) return;
  976. editorObject.tabs.slice().forEach(function(tab){
  977. closeTabWithUUIDAndEditorID(tab.tabUUID, editorObject.uuid);
  978. });
  979. }
  980. function copyFilePathFromTab(){
  981. if (!selectedTabInfo || !selectedTabInfo.filepath) return;
  982. var filepath = selectedTabInfo.filepath;
  983. copyToClipboard(filepath, function(copied){
  984. if (copied){
  985. setStatusMessage("copy", "Path copied to clipboard");
  986. } else {
  987. prompt("Copy the path below:", filepath);
  988. }
  989. });
  990. }
  991. function revealTabInFileManager(){
  992. if (!selectedTabInfo || !selectedTabInfo.filepath) return;
  993. var parts = selectedTabInfo.filepath.split("/");
  994. var filename = parts.pop();
  995. ao_module_openPath(parts.join("/"), filename);
  996. }
  997. /*
  998. navigator.clipboard only exists in a secure context (https or localhost), so
  999. an ArozOS host reached over plain http on the LAN always needs the textarea
  1000. fallback. The async path can also reject when the document is not focused,
  1001. which is why the fallback runs again on failure.
  1002. */
  1003. function copyToClipboard(text, onDone){
  1004. function fallback(){
  1005. var textarea = document.createElement("textarea");
  1006. textarea.value = text;
  1007. textarea.style.position = "fixed";
  1008. textarea.style.opacity = "0";
  1009. document.body.appendChild(textarea);
  1010. textarea.focus();
  1011. textarea.select();
  1012. var copied = false;
  1013. try { copied = document.execCommand("copy"); } catch(e){ copied = false; }
  1014. document.body.removeChild(textarea);
  1015. if (onDone) onDone(copied);
  1016. }
  1017. if (navigator.clipboard && navigator.clipboard.writeText){
  1018. navigator.clipboard.writeText(text).then(function(){
  1019. if (onDone) onDone(true);
  1020. }).catch(fallback);
  1021. return;
  1022. }
  1023. fallback();
  1024. }