index.html 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="apple-mobile-web-app-capable" content="yes" />
  5. <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
  6. <meta charset="UTF-8">
  7. <title>Code Studio</title>
  8. <meta name="theme-color" content="#4b75ff">
  9. <link rel="stylesheet" href="../script/semantic/semantic.min.css">
  10. <link rel="stylesheet" href="CodeStudio.css">
  11. <script src="../script/jquery.min.js"></script>
  12. <script src="../script/semantic/semantic.min.js"></script>
  13. <script src="../script/ao_module.js"></script>
  14. <link data-name="vs/editor/editor.main" rel="stylesheet" href="script/monaco/vs/editor/editor.main.css">
  15. <style>
  16. html{
  17. height:100%;
  18. }
  19. body{
  20. height:100%;
  21. overflow-y:hidden;
  22. padding:1px;
  23. background-color:#292929;
  24. }
  25. #terminals{
  26. position: fixed;
  27. right: 0px;
  28. bottom: 24px;
  29. width: calc(100% - 240px);
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <!-- Main Menu -->
  35. <div class="npa menu">
  36. <div class="item"><img class="ui image" src="img/module_icon.png" style="height:20px;"></img></div>
  37. <div class="item selectable" onclick="initContextMenu('file',this);">File</div>
  38. <div class="item selectable" onclick="initContextMenu('edit',this);">Edit</div>
  39. <div class="item selectable" onclick="initContextMenu('view',this);">View</div>
  40. <div class="item selectable" onclick="initContextMenu('fontsize',this);">Font Size</div>
  41. <div class="item selectable" onclick="initContextMenu('tools',this);">Tools</div>
  42. <div class="item selectable" onclick="initContextMenu('help',this);">Help</div>
  43. </div>
  44. <div id="directoryList" onclick="hideContextMenu();">
  45. <div class="banner">Directory Listing</div>
  46. <div class="title item" onclick="event.preventDefault(); $('#openeditors').stop().finish().slideToggle('fast');"><i class="caret down icon"></i> OPEN EDITORS</div>
  47. <div class="subgroup" id="openeditors">
  48. </div>
  49. <div class="title item" onclick="toggleDirectoryExplorer(this);"><i class="caret down icon"></i><span id="openFolderTitle">NO FOLDER</span></div>
  50. <div class="subgroup" id="directoryExplorer">
  51. </div>
  52. </div>
  53. <div id="codeArea" onclick="hideContextMenu();">
  54. <div id="ca1" class="codeBoard">
  55. <div class="tabs" editorUID="mainEditor" ondrop="TabDrop(event)" ondragover="allowDrop(event)">
  56. </div>
  57. <div class="editor" editorUID="mainEditor" onclick="focusThisEditor(this);"></div>
  58. <div class="editorcover" editorUID="mainEditor" onclick="focusThisEditor(this);"></div>
  59. </div>
  60. <div id="ca2" class="codeBoard splitMode right" style="display:none;">
  61. <div class="tabs" editorUID="subEditor" ondrop="TabDrop(event)" ondragover="allowDrop(event)">
  62. </div>
  63. <div class="editor" editorUID="subEditor" onclick="focusThisEditor(this);"></div>
  64. <div class="editorcover" editorUID="subEditor" onclick="focusThisEditor(this);"></div>
  65. </div>
  66. <div id="terminals" style="display:none;">
  67. <div class="menubar">
  68. <p>TERMINAL</p>
  69. <div style="position: absolute; right: 12px;">
  70. <i style="cursor: pointer;" onclick="restartTerminal();" class="refresh icon"></i>
  71. <i style="cursor: pointer;" onclick="closeTerminal();" class="remove icon"></i>
  72. </div>
  73. </div>
  74. <div class="terminalWindow focused">
  75. <iframe id="initTerminal" src="../wstty/">
  76. </iframe>
  77. </div>
  78. </div>
  79. </div>
  80. <div class="bottommenu">
  81. <div class="item"><i class="exchange icon"></i><span id="pingStatus"></span></div>
  82. <div class="item extrapadding" id="messageField" style="display:none;"><i class="checkmark icon"></i>Connected</div>
  83. <div class="rightpadded">
  84. <div class="item" id="filepath"><i class="code file icon"></i> user:/</div>
  85. <div class="item" id="fileExt">N/A</div>
  86. <div class="item">Code Studio</div>
  87. </div>
  88. </div>
  89. <!-- Context Menu -->
  90. <div id="contextMenu" class="contextMenu">
  91. </div>
  92. <!-- Licnese information -->
  93. <div id="licenseInfo" class="ui modal">
  94. <i class="close icon"></i>
  95. <div class="header">
  96. Code Studio License
  97. </div>
  98. <div class="content">
  99. <div class="description">
  100. <div class="ui header">Copyright 2020-2021 Toby Chui</div>
  101. <p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  102. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  103. <br>
  104. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  105. </p>
  106. </div>
  107. </div>
  108. <div class="actions">
  109. <div class="ui positive right labeled icon button">
  110. OK
  111. <i class="checkmark icon"></i>
  112. </div>
  113. </div>
  114. </div>
  115. <!-- NotepadA Info-->
  116. <div id="aboutnpa" class="ui basic modal">
  117. <div class="ui icon header">
  118. <i class="code icon"></i>
  119. Code Studio Editor
  120. </div>
  121. <div class="content" align="center">
  122. <p>The default code editor for ArozOS 1.0<br>Developed by Toby Chui</p>
  123. </div>
  124. <div class="actions">
  125. <div class="ui green ok inverted button">
  126. <i class="checkmark icon"></i>
  127. OK
  128. </div>
  129. </div>
  130. </div>
  131. <!-- Copy and Paste menu reminder-->
  132. <div id="clipboardReminder" class="ui basic modal">
  133. <div class="ui icon header">
  134. <i id="clipboardReminderIcon" class="archive icon"></i>
  135. Keyboard Only
  136. </div>
  137. <div class="content" style="text-align:center;">
  138. <p id="clipboardReminderText"></p>
  139. </div>
  140. <div class="actions">
  141. <div class="ui green ok inverted button">
  142. <i class="checkmark icon"></i>
  143. OK
  144. </div>
  145. </div>
  146. </div>
  147. <script src="script/monaco/vs/loader.js"></script>
  148. <script>
  149. //Environment Paramters
  150. let editors = []; //List of opened editor
  151. let splitMode = false; //Split the screen into two half
  152. let focusedEditor = "mainEditor"; //The editor currently is focused
  153. let loadedModels = []; //Loaded models. Prevent duplicate loading problem
  154. let focusedFileInfo = [];
  155. let files = ao_module_loadInputFiles(); //Files imported from file system
  156. //Terminal realted
  157. let terminalStartingEndpoint = "../wstty/";
  158. //Initiation functions
  159. initEditor($("#ca1").find(".editor")[0], "mainEditor", files, restoreEditorState);
  160. initEditor($("#ca2").find(".editor")[0],"subEditor");
  161. //Load ready page into the editorCover
  162. $(".editorcover").load("home.html");
  163. //Get the editor by id
  164. function getEditor(uuid){
  165. var resultEditor = undefined;
  166. editors.forEach(thisEditor => {
  167. if (thisEditor.uuid == uuid){
  168. resultEditor = thisEditor;
  169. }
  170. });
  171. return resultEditor;
  172. }
  173. //Restore the previous editor state
  174. function restoreEditorState(editor){
  175. //Load previous state if exists
  176. if (window.location.hash.length > 1){
  177. var stateString = window.location.hash.substr(1);
  178. var oldState = JSON.parse(decodeURIComponent(stateString));
  179. //Load the previous statue opened folder
  180. if (oldState.folder !== undefined){
  181. //Load the previous opened folder
  182. var predictedName = oldState.folder.split("/").pop();
  183. if (oldState.folder.substr(oldState.folder.length -1) == "/"){
  184. var tmp = oldState.folder.split("/");
  185. tmp.pop();
  186. predictedName = tmp.pop();
  187. }
  188. openProjectFolder([{
  189. filename: predictedName,
  190. filepath: oldState.folder
  191. }], false);
  192. }
  193. //Open previous opened files
  194. if (oldState.files !== undefined){
  195. oldState.files.forEach(filepath => {
  196. openFile(filepath, false);
  197. })
  198. }
  199. //Open terminal if it is enabled previously
  200. if (oldState.terminal !== undefined && oldState.terminal == true){
  201. openTerminal();
  202. }
  203. }
  204. }
  205. //Restore previous editor states
  206. function restoreUserPreference(){
  207. getStorage("fontsize",function(fontsize){
  208. setFontSize(fontsize);
  209. });
  210. getStorage("splitmode",function(splitSetting){
  211. if (splitSetting.error !== undefined){
  212. return;
  213. }
  214. splitSetting = splitSetting.trim();
  215. if (splitSetting == "true"){
  216. splitMode = true;
  217. $("#ca1").attr("class","codeBoard splitMode left")
  218. $("#ca2").show();
  219. }else{
  220. splitMode = false;
  221. $("#ca1").attr("class","codeBoard")
  222. $("#ca2").hide();
  223. }
  224. //Update all editor's size
  225. for (var i =0; i < editors.length; i++){
  226. editors[i].editor.layout();
  227. }
  228. });
  229. }
  230. //Check if it is run under vdi mode. If not, establish checkauth ping to keep session alive
  231. if (!ao_module_virtualDesktop){
  232. setInterval(function(){
  233. $.get("../system/auth/checkLogin",function(data){
  234. if (data.error != undefined){
  235. $("#pingStatus").text(data.error);
  236. }else{
  237. var x = Date()
  238. $("#pingStatus").text(x);
  239. }
  240. });
  241. },30000);
  242. }else{
  243. $("#pingStatus").text("Web Desktop Mode");
  244. }
  245. $.get("../system/auth/checkLogin",function(data){
  246. var x = Date()
  247. $("#pingStatus").text(x);
  248. });
  249. //Bind the events of the tab objects
  250. function bindTabItemEvents(){
  251. $(".tabs .item").off("click").on('click',function(evt){
  252. if ($(this).hasClass("selected")){
  253. //This tab is already in focus.
  254. return;
  255. }
  256. //Add focused class to the tab
  257. $(this).parent().find(".item.selected").removeClass("selected");
  258. $(this).addClass("selected");
  259. //Check which editor this tab belongs to
  260. var editorUUID = $(this).parent().parent().find(".editor").attr("editoruid");
  261. var tabUUID = $(this).attr("uuid");
  262. var targetEditor;
  263. for (var i =0; i < editors.length; i++){
  264. if (editors[i].uuid == editorUUID){
  265. targetEditor = editors[i];
  266. }
  267. }
  268. if (typeof targetEditor === undefined){
  269. console.log("Error when loading tab");
  270. return;
  271. }
  272. changeTab(targetEditor,tabUUID);
  273. //Update the selected item in opened editor as well
  274. $("#openeditors .item.selected").removeClass("selected");
  275. $("#openeditors .item").each(function(){
  276. if ($(this).attr("uuid") == tabUUID){
  277. $(this).addClass("selected");
  278. }
  279. });
  280. });
  281. $("#openeditors .item").off("click").on("click",function(evt){
  282. //Update UI to match selected tab
  283. $("#openeditors .item.selected").removeClass('selected');
  284. $(this).addClass("selected");
  285. //Get the target editor UUID
  286. var tabID = $(this).attr("uuid");
  287. var editorUUID = $(this).attr("editorUUID");
  288. var targetEditorObject;
  289. for (var i =0; i < editors.length; i++){
  290. if (editors[i].uuid == editorUUID){
  291. targetEditorObject = editors[i];
  292. }
  293. }
  294. if (typeof targetEditorObject === undefined){
  295. console.log("Error when loading tab");
  296. return;
  297. }
  298. changeTab(targetEditorObject,tabID);
  299. //Also highlight the tab menu as well
  300. $(targetEditorObject.tabsMenu).find(".item.selected").removeClass('selected');
  301. $(targetEditorObject.tabsMenu).find(".item").each(function(){
  302. if ($(this).attr("uuid") == tabID){
  303. $(this).addClass("selected");
  304. }
  305. });
  306. });
  307. $(".tabs .item .closebtn").off("click").on('click',function(evt){
  308. evt.preventDefault();
  309. evt.stopImmediatePropagation();
  310. var tabUUID = $(this).parent().attr("uuid");
  311. var editorUUID = $(this).parent().attr("editorUUID");
  312. closeTabWithUUIDAndEditorID(tabUUID, editorUUID);
  313. });
  314. $("#openeditors .closebtn").off("click").on("click",function(evt){
  315. evt.stopImmediatePropagation();
  316. evt.preventDefault();
  317. var tabUUID = $(this).parent().attr("uuid");
  318. var editorUUID = $(this).parent().attr("editorUUID");
  319. closeTabWithUUIDAndEditorID(tabUUID, editorUUID);
  320. });
  321. }
  322. //Close a tab given the editorUUID and the tabUUID.
  323. function closeTabWithUUIDAndEditorID(tabUUID, editorUUID){
  324. //Find the editor object related to this tab
  325. let targetEditorObject;
  326. for (var i =0; i < editors.length; i++){
  327. if (editors[i].uuid == editorUUID){
  328. targetEditorObject = editors[i];
  329. }
  330. }
  331. if (targetEditorObject === undefined){
  332. console.log("Error when closing tab");
  333. return;
  334. }
  335. //Remove state and models from the editor object
  336. delete targetEditorObject.state[tabUUID];
  337. delete targetEditorObject.model[tabUUID];
  338. //Remove this tab from the list
  339. tabs = JSON.parse(JSON.stringify(targetEditorObject.tabs));
  340. for (var i =0; i < tabs.length; i++){
  341. if (tabUUID == tabs[i].tabUUID){
  342. targetEditorObject.tabs.splice(i,1);
  343. }
  344. }
  345. //Remove the tab objects from DOM
  346. removeTabFromDOMWithUUID(tabUUID);
  347. if (targetEditorObject.tabs.length > 0){
  348. //Switch to the first tab of the editor
  349. var newFocusedTabUUID = targetEditorObject.tabs[0].tabUUID;
  350. changeTab(targetEditorObject, newFocusedTabUUID);
  351. focusTabWithUUID(newFocusedTabUUID);
  352. }else{
  353. //No more tab lefts. Show the editor cover
  354. $(targetEditorObject.tabsMenu).parent().find(".editorcover").show();
  355. $(targetEditorObject.tabsMenu).parent().find(".editorcover").load("home.html");
  356. }
  357. }
  358. function getFocusedTabInfo(){
  359. var focusedEditorObject = getFocusedEditorObject();
  360. var focusedTabUUID = focusedEditorObject.currentTabUUID;
  361. for (var i =0; i < focusedEditorObject.tabs.length; i++){
  362. var thistab = focusedEditorObject.tabs[i];
  363. if (thistab.tabUUID == focusedTabUUID){
  364. //Update the global focused tab info as the current working-on file
  365. focusedFileInfo = thistab;
  366. return thistab;
  367. }
  368. }
  369. }
  370. function getCodeAreaFromEditorUUID(editorUUID){
  371. for (var i =0; i < editors.length; i++){
  372. if (editors[i].uuid == editorUUID){
  373. var tabsMenu = editors[i].tabsMenu;
  374. return $(tabsMenu).parent();
  375. }
  376. }
  377. }
  378. function updateFileStatusDisplay(filepath){
  379. $("#filepath").html(`<i class="code file icon"></i> ${filepath}`);
  380. var ext = filepath.split(".").pop();
  381. $("#fileExt").text(ext.toUpperCase());
  382. }
  383. function getFocusedEditorObject(){
  384. for (var i =0; i < editors.length; i++){
  385. if (editors[i].uuid == focusedEditor){
  386. return editors[i];
  387. }
  388. }
  389. }
  390. function focusThisEditor(object){
  391. var editorUUID = $(object).attr("editorUID");
  392. focusedEditor = editorUUID;
  393. //Update the target file info
  394. var tabInfo = getFocusedTabInfo();
  395. if (tabInfo !== undefined){
  396. updateFileStatusDisplay(tabInfo.filepath);
  397. focusTabWithUUID(tabInfo.tabUUID);
  398. }
  399. }
  400. function focusTabWithUUID(tabUUID){
  401. $(".tabs .item.selected").removeClass("selected");
  402. $(".tabs .item").each(function(){
  403. if ($(this).attr("uuid") == tabUUID){
  404. $(this).addClass("selected");
  405. }
  406. });
  407. $("#openeditors .item.selected").removeClass("selected");
  408. $("#openeditors .item").each(function(){
  409. if ($(this).attr("uuid") == tabUUID){
  410. $(this).addClass("selected");
  411. }
  412. });
  413. }
  414. function removeTabFromDOMWithUUID(tabUUID){
  415. $(".tabs .item").each(function(){
  416. if ($(this).attr("uuid") == tabUUID){
  417. $(this).remove();
  418. }
  419. });
  420. //Remove the tab from OPEN EDITORS
  421. $("#openeditors .item").each(function(){
  422. if ($(this).attr("uuid") == tabUUID){
  423. $(this).remove();
  424. }
  425. });
  426. }
  427. function focusTab(uuid){
  428. $(".tabs .item").each(function(){
  429. if ($(this).attr("uuid") == uuid){
  430. $(this).addClass("selected");
  431. }
  432. });
  433. $("#openeditors .item.selected").removeClass("selected");
  434. $("#openeditors .item").each(function(){
  435. if ($(this).attr("uuid") == uuid){
  436. $(this).addClass("selected");
  437. }
  438. });
  439. }
  440. //Main script section for UI handling
  441. //Load context menu
  442. function initContextMenu(target, object){
  443. if (target == "file"){
  444. //List items in files
  445. $("#contextMenu").html(`
  446. <div class="item">New File
  447. <div class="tips">Ctrl + N</div>
  448. </div>
  449. <div class="divider"></div>
  450. <div class="item" onclick="openFileWithSelector();">Open File
  451. <div class="tips">Ctrl + O</div>
  452. </div>
  453. <div class="item" onclick="openFolderWithSelector();">Open Folder
  454. <div class="tips">Ctrl + Shift + O</div>
  455. </div>
  456. <div class="divider"></div>
  457. <div class="item" onclick="saveCurrentFile();">Save</div>
  458. <div class="item" onclick="saveCurrentFileAs();">Save As</div>
  459. <div class="item" onclick="saveAllFiles();">Save All</div>
  460. <!--<div class="divider"></div>
  461. <div class="item">Preference</div>-->
  462. <div class="divider"></div>
  463. <div class="item" onclick="closeFileCurrentlyFocused();">Close File</div>
  464. <div class="item" onclick="closeAllFiles();">Close All Files</div>
  465. `);
  466. if (ao_module_virtualDesktop){
  467. $("#contextMenu").append(`<div class="item" onclick="hanleUserExit();">Exit</div>`);
  468. }
  469. }else if (target == "edit"){
  470. $("#contextMenu").html(`
  471. <div class="item" onclick="undo();">Undo
  472. <div class="tips">Ctrl + Z</div>
  473. </div>
  474. <div class="item" onclick="redo();">Redo
  475. <div class="tips">Ctrl + Y</div>
  476. </div>
  477. <div class="divider"></div>
  478. <div class="item" onclick="showClipboardReminders(1);">Cut
  479. <div class="tips">Ctrl + X</div>
  480. </div>
  481. <div class="item" onclick="showClipboardReminders(2);">Copy
  482. <div class="tips">Ctrl + C</div>
  483. </div>
  484. <div class="item" onclick="showClipboardReminders(3);">Paste
  485. <div class="tips">Ctrl + V</div>
  486. </div>
  487. <div class="item" onclick="showClipboardReminders(4);">Find
  488. <div class="tips">Ctrl + F</div>
  489. </div>
  490. <div class="item" onclick="showClipboardReminders(5);">Replace
  491. <div class="tips">Ctrl + H</div>
  492. </div>
  493. <div class="divider"></div>
  494. <div class="item" onclick="toggleSplit(true);">Split WorkSpace</div>
  495. <div class="item" onclick="toggleSplit(false);">Merge WorkSpace</div>
  496. `);
  497. }else if (target == "view"){
  498. $("#contextMenu").html(`
  499. <div class="item" onclick="newEditor(); hideContextMenu();">New Editor
  500. <div class="tips"><i class="add icon"></i></div>
  501. </div>
  502. <div class="item" onclick="openInNewTab(); hideContextMenu();">Open in new Tab
  503. <div class="tips"><i class="external icon"></i></div>
  504. </div>
  505. <div class="item" onclick="openInNewFloatWindow(); hideContextMenu();">Open in floatWindow
  506. <div class="tips"><i class="window restore outline icon"></i></div>
  507. </div>
  508. <div class="item" onclick="openFileInFileManager(); hideContextMenu();">Reveal in File Manager
  509. <div class="tips"><i class="folder outline icon"></i></div>
  510. </div>
  511. <div class="item" onclick="openTerminal(); hideContextMenu();">Open Terminal
  512. <div class="tips"><i class="code icon"></i></div>
  513. </div>
  514. <div class="divider"></div>
  515. <div class="item" onclick="downloadFile(); hideContextMenu();">Download
  516. <div class="tips"><i class="download icon"></i></div>
  517. </div>
  518. `);
  519. }else if (target == "fontsize"){
  520. $("#contextMenu").html('');
  521. for (var i = 8; i < 26; i++ ){
  522. $("#contextMenu").append(`<div class="item" style="font-size:${i}px;" onclick="setFontSize(${i});">${i} px</div>`);
  523. }
  524. }else if (target == "tools"){
  525. $("#contextMenu").html('');
  526. $("#contextMenu").html(`
  527. <div class="item" onclick="showColorPicker(); hideContextMenu();">Color Picker
  528. <div class="tips"><i class="eyedropper icon"></i></div>
  529. </div>
  530. <div class="item" onclick="showMobiPreview(); hideContextMenu();">Responsive Design Viewer
  531. <div class="tips"><i class="mobile icon"></i></div>
  532. </div>
  533. `);
  534. }else if (target == "help"){
  535. $("#contextMenu").html(`
  536. <div class="item" onclick="window.open('https://microsoft.github.io/monaco-editor/'); hideContextMenu();">About Monaco Editor</div>
  537. <div class="divider"></div>
  538. <div class="item" onclick="showLicense();">License</div>
  539. <div class="item" onclick="showAboutCodeStudio();">About Code Studio</div>
  540. `);
  541. }
  542. $("#contextMenu").show();
  543. $("#contextMenu").css({
  544. left: $(object).offset().left,
  545. top: "28px"
  546. })
  547. }
  548. function showLicense(){
  549. $("#licenseInfo").modal("show");
  550. hideContextMenu();
  551. }
  552. function showAboutCodeStudio(){
  553. $("#aboutnpa").modal("show");
  554. hideContextMenu();
  555. }
  556. function closeFileCurrentlyFocused(){
  557. var focusedEditor = getFocusedEditorObject();
  558. var editorUUID = focusedEditor.uuid;
  559. var tabsMenu = focusedEditor.tabsMenu;
  560. var focusedTabID = $(tabsMenu).find(".item.selected").attr("uuid");
  561. closeTabWithUUIDAndEditorID(focusedTabID,editorUUID);
  562. hideContextMenu();
  563. }
  564. function closeAllFiles(){
  565. editors.forEach(editor => {
  566. var editorId = editor.uuid;
  567. editor.tabs.forEach(tab => {
  568. closeTabWithUUIDAndEditorID(tab.tabUUID, editorId);
  569. });
  570. });
  571. hideContextMenu();
  572. }
  573. function saveAllFiles(){
  574. //Store the editor object before saveall
  575. let beforeTabInfo = getFocusedTabInfo();
  576. let beforeEditor = getFocusedEditorObject();
  577. //Iterate through all editors and all tabs to save
  578. for (var i = 0; i < editors.length; i++){
  579. var thisEditor = editors[i];
  580. for (var j =0; j < thisEditor.tabs.length; j++){
  581. var tabUUID = thisEditor.tabs[j].tabUUID;
  582. changeTab(thisEditor, tabUUID);
  583. saveCurrentFile();
  584. }
  585. }
  586. //Restore the editor view
  587. changeTab(beforeEditor, beforeTabInfo.tabUUID);
  588. hideContextMenu();
  589. }
  590. function setFontSize(fontsize){
  591. for (var i =0; i < editors.length; i++){
  592. var thisEditor = editors[i].editor;
  593. thisEditor.updateOptions({
  594. fontSize: fontsize
  595. });
  596. }
  597. setStorage("fontsize",fontsize);
  598. hideContextMenu();
  599. }
  600. function toggleSplit(useSplitMode){
  601. if (useSplitMode){
  602. $("#ca1").attr("class","codeBoard splitMode left")
  603. $("#ca2").show();
  604. setStorage("splitmode","true");
  605. }else{
  606. $("#ca1").attr("class","codeBoard")
  607. $("#ca2").hide();
  608. setStorage("splitmode","false");
  609. //Move all tabs from subEditor to main editor
  610. var mainEditor = getEditor("mainEditor");
  611. var subEditor = getEditor("subEditor");
  612. subEditor.tabs.forEach(tab => {
  613. var filepath = tab.filepath;
  614. //Open tab in main editor
  615. openFile(filepath, false, mainEditor);
  616. //Close tab in sub editor
  617. closeTabWithUUIDAndEditorID(tab.tabUUID, "subEditor");
  618. });
  619. }
  620. //Update all editor's size
  621. for (var i =0; i < editors.length; i++){
  622. editors[i].editor.layout();
  623. }
  624. hideContextMenu();
  625. }
  626. //Hide all the context menus
  627. function hideContextMenu(){
  628. $("#contextMenu").hide();
  629. }
  630. //open a file with a new editor by the given filepath
  631. function openFile(filepath, updateHashStatus=true, overrideEditor=undefined){
  632. //Get the focused editor
  633. var targetEditorGroup = undefined;
  634. if (overrideEditor == undefined){
  635. //Do not override editor
  636. for (var i =0; i < editors.length; i++){
  637. if (editors[i].uuid == focusedEditor){
  638. targetEditorGroup = editors[i];
  639. }
  640. }
  641. }else{
  642. //Use override editor
  643. targetEditorGroup = overrideEditor;
  644. }
  645. if (targetEditorGroup === undefined){
  646. alert("Unable to load editor.");
  647. return;
  648. }
  649. //Check if the file is already loaded in this editor
  650. for (var i = 0; i < targetEditorGroup.tabs.length; i++){
  651. var thisTab = targetEditorGroup.tabs[i];
  652. if (thisTab.filepath == filepath){
  653. //Focus this tab
  654. changeTab(targetEditorGroup, thisTab.tabUUID);
  655. return;
  656. }
  657. }
  658. //Get the file
  659. ao_module_agirun("Code Studio/backend/read.agi",{
  660. file: filepath
  661. }, function(filecontent){
  662. //Get the target Opening Editor
  663. let targetOpeningEditor = targetEditorGroup;
  664. if (typeof targetOpeningEditor === undefined){
  665. console.log("Error when trying to get editor info")
  666. return;
  667. }
  668. //Load the editor instances
  669. var editor = targetOpeningEditor.editor;
  670. var editorUUID = targetOpeningEditor.uuid;
  671. var models = targetOpeningEditor.model;
  672. var states = targetOpeningEditor.state;
  673. var currentTabUUID = targetOpeningEditor.currentTabUUID;
  674. var targetTabMenu = targetOpeningEditor.tabsMenu;
  675. //Save the current editor status into the data
  676. var currentState = editor.saveViewState();
  677. var currentModel = editor.getModel();
  678. states[currentTabUUID] = currentState;
  679. models[currentTabUUID] = currentModel;
  680. //Create a tab for this file
  681. var tabUUID = new Date().getTime();
  682. var filename = filepath.split("/").pop();
  683. $(targetTabMenu).find(".item.selected").removeClass("selected");
  684. $(targetTabMenu).append(`<div class="item selected fileTab" title="${filepath}" draggable="true" ondragstart="fileTabDrag(event)" uuid="${tabUUID}" editorUUID="${editorUUID}" filepath="${filepath}"><i class="code file icon"></i> ${filename} <div class="closebtn"><i class="remove icon"></i></i></div></div>`);
  685. //Add this tab into the open editor list
  686. $("#openeditors .item").removeClass("selected");
  687. $("#openeditors").append(`<div class="item selected" uuid="${tabUUID}" editorUUID="${editorUUID}"><div class="closebtn" style="display:inline-block;"><i class="remove icon"></i></div> <i class="code file icon"></i> ${filename} </div>`);
  688. //Update the current tag information
  689. targetOpeningEditor.currentTabUUID = tabUUID
  690. //Push the current tab into the array of tabs
  691. targetOpeningEditor.tabs.push({
  692. filename: filename,
  693. filepath: filepath,
  694. tabUUID: tabUUID,
  695. saveHash: filecontent.hashCode()
  696. });
  697. //Update title if nonVDI or update floatWindow title if under fdi
  698. if (ao_module_virtualDesktop){
  699. ao_module_setWindowTitle("Code Studio - " + filename);
  700. }else{
  701. document.title = "Code Studio - " + filename;
  702. }
  703. //Check if model is loaded before
  704. var model;
  705. if (loadedModels[filepath] === undefined){
  706. let ext = filepath.split(".").pop();
  707. let language = undefined; //Auto detect
  708. if (ext == "agi"){
  709. language = "javascript"
  710. }
  711. //Set the editor value and do model auto lanuage detection
  712. model = monaco.editor.createModel(
  713. filecontent,
  714. language,
  715. monaco.Uri.file("../media?file=" + encodeURIComponent(filepath))
  716. )
  717. loadedModels[filepath] = model;
  718. }else{
  719. //Load the already loaded model
  720. model = loadedModels[filepath];
  721. }
  722. editor.setModel(model)
  723. //Bind tab events
  724. bindTabItemEvents();
  725. //Update file info tab
  726. var tabInfo = getFocusedTabInfo();
  727. updateFileStatusDisplay(tabInfo.filepath);
  728. //Hide the editorCover
  729. var ca = getCodeAreaFromEditorUUID(editorUUID);
  730. $(ca).find(".editorcover").hide();
  731. //monaco.editor.colorize(filecontent, "javascript").then(html => ca[0].innerHTML = html);
  732. //Write the opened filelist to window hash
  733. if (updateHashStatus){
  734. var currentState = getHashObject();
  735. currentState["files"] = getOpenedFiles();
  736. console.log(currentState);
  737. writeHashObject(currentState);
  738. }
  739. //Finally, focus on the newly opened tab
  740. focusTabWithUUID(tabUUID);
  741. });
  742. }
  743. function hash(s){
  744. return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
  745. }
  746. //Open fileSelector
  747. function openFileWithSelector(){
  748. ao_module_openFileSelector(externalFileLoader, "user:/Document", "file",true);
  749. hideContextMenu();
  750. }
  751. //Open folderSelector
  752. function openFolderWithSelector(){
  753. ao_module_openFileSelector(openProjectFolder, "user:/Document", "folder");
  754. hideContextMenu();
  755. }
  756. //Handle fileSelector return value
  757. function externalFileLoader(filedata){
  758. if (filedata.length > 0){
  759. for (var i=0; i < filedata.length; i++){
  760. filepath = filedata[i].filepath;
  761. openFile(filepath);
  762. }
  763. }
  764. }
  765. function openProjectFolder(filedata, rewriteHash=true){
  766. for (var i=0; i < filedata.length; i++){
  767. folderpath = filedata[i].filepath;
  768. foldername = filedata[i].filename;
  769. //Load this as the folder
  770. $("#openFolderTitle").text(foldername.toUpperCase());
  771. $("#directoryExplorer").html("");
  772. $.get("../system/file_system/listDir?dir=" + encodeURIComponent(folderpath),function(data){
  773. var folders = [];
  774. var files = [];
  775. if (data === null){
  776. data = [];
  777. }
  778. for (var i =0; i < data.length; i++){
  779. var filename = data[i].Filename;
  780. var ext = filename.split(".").pop();
  781. var icon = ao_module_utils.getIconFromExt(ext);
  782. var filepath = data[i].Filepath;
  783. if (data[i].IsDir){
  784. icon = "folder";
  785. folders.push(`
  786. <div class="folderObjectWrapper">
  787. <div class="item" title="${filepath}" style="overflow:hidden;" onclick="listfolder(this);">
  788. <div class="showmore" style="display:inline-block;"><i class="caret right icon"></i></div>
  789. <i class="${icon} icon"></i> ${filename}
  790. </div>
  791. </div>
  792. `);
  793. }else{
  794. files.push(`
  795. <div class="item" title="${filepath}" draggable="true" ondragstart="directoryFileDrag(event)" filepath="${filepath}" filename="${filename}" style="overflow:hidden;" onclick="openFileViaDirectoryExplorer(this, event);">
  796. <i class="${icon} icon"></i> ${filename}
  797. </div>
  798. `);
  799. }
  800. }
  801. $("#directoryExplorer").append(folders.join(""));
  802. $("#directoryExplorer").append(files.join(""));
  803. });
  804. if (rewriteHash){
  805. var currentState = getHashObject();
  806. currentState["folder"] = foldername;
  807. writeHashObject(currentState);
  808. }
  809. }
  810. }
  811. function listfolder(folder){
  812. var folderPath = $(folder).attr("title");
  813. //Check if the folder is already list. If yes, toggle the list
  814. if ($(folder).parent().find(".dirlist").length == 0){
  815. //Folder is not listed. Load from file system
  816. $(folder).parent().append(`<div class="dirlist"></div>`);
  817. $(folder).find(".showmore i").attr("class","caret down icon");
  818. var targetListObject = $(folder).parent().find(".dirlist");
  819. $.get("../system/file_system/listDir?dir=" + encodeURIComponent(folderPath),function(data){
  820. var folders = [];
  821. var files = [];
  822. if (data === null){
  823. data = [];
  824. }
  825. for (var i =0; i < data.length; i++){
  826. var filename = data[i].Filename;
  827. var ext = filename.split(".").pop();
  828. var icon = ao_module_utils.getIconFromExt(ext);
  829. var filepath = data[i].Filepath;
  830. if (data[i].IsDir){
  831. icon = "folder";
  832. folders.push(`
  833. <div class="folderObjectWrapper">
  834. <div class="subitem" title="${filepath}" style="overflow:hidden;" onclick="listfolder(this);">
  835. <div class="showmore" style="display:inline-block;"><i class="caret right icon"></i></div>
  836. <i class="${icon} icon"></i> ${filename}
  837. </div>
  838. </div>
  839. `);
  840. }else{
  841. files.push(`
  842. <div class="subitem" title="${filepath}" style="overflow:hidden;" onclick="openFileViaDirectoryExplorer(this,event);">
  843. <i class="${icon} icon"></i> ${filename}
  844. </div>
  845. `);
  846. }
  847. }
  848. //Push the items into the list
  849. $(targetListObject).append(folders.join(""));
  850. $(targetListObject).append(files.join(""));
  851. });
  852. }else{
  853. //Folder is already listed. Toggle show of filelist
  854. if ($(folder).find(".caret.down.icon").length > 0){
  855. //Folder list visiable. Hide it
  856. $(folder).parent().find(".dirlist").slideUp('fast');
  857. $(folder).find(".showmore i").attr("class","caret right icon");
  858. }else{
  859. //Folder list hidden. Show it
  860. $(folder).parent().find(".dirlist").slideDown('fast');
  861. $(folder).find(".showmore i").attr("class","caret down icon");
  862. }
  863. }
  864. }
  865. function openFileViaDirectoryExplorer(object, event){
  866. var filepath = $(object).attr('title');
  867. openFile(filepath);
  868. }
  869. function toggleDirectoryExplorer(btn){
  870. if ($(btn).find("i").hasClass("right")){
  871. $(btn).find("i").attr("class","caret down icon");
  872. $("#directoryExplorer").slideDown('fast');
  873. }else{
  874. $(btn).find("i").attr("class","caret right icon");
  875. $("#directoryExplorer").slideUp('fast');
  876. }
  877. }
  878. //Initiate an editor with the given uuid and targetDOM
  879. function initEditor(targetDOM, editorUUID, loadPendingFiles = [], callback=undefined){
  880. require.config({ paths: { 'vs': 'script/monaco/vs' }});
  881. window.GlobalEnvironment = { getWorkerUrl: () => proxy };
  882. let proxy = URL.createObjectURL(new Blob([`
  883. self.GlobalEnvironment = {
  884. baseUrl: 'script/monaco/'
  885. };
  886. importScripts('script/monaco/vs/base/worker/workerMain.js');
  887. `], { type: 'text/javascript' }));
  888. require(["vs/editor/editor.main"], function () {
  889. let editor = monaco.editor.create(targetDOM, {
  890. value: "",
  891. language: 'javascript',
  892. automaticLayout: true,
  893. theme: 'vs-dark'
  894. });
  895. //Bind save event for this editor
  896. editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function() {
  897. let thisEditor = editor;
  898. //Save this editor text to the current editor focused tab folder
  899. var tabInfo = getFocusedTabInfo();
  900. var filepath = tabInfo.filepath;
  901. var content = thisEditor.getValue();
  902. //console.log(filepath, content);
  903. saveContentToFile(tabInfo.tabUUID, filepath, content, function(data){
  904. if (data.error !== undefined){
  905. alert(data.error);
  906. }else{
  907. //OK
  908. console.log("File saved");
  909. msgbox("save","File Saved")
  910. }
  911. });
  912. });
  913. editors.push({
  914. uuid: editorUUID,
  915. tabsMenu: $(targetDOM).parent().find(".tabs"),
  916. editor: editor,
  917. currentTabUUID: "default",
  918. model: [],
  919. state: [],
  920. tabs: []
  921. });
  922. //Check if there are load pending files. If yes, load them into this editor
  923. if (loadPendingFiles !== null && loadPendingFiles.length > 0){
  924. for (var i =0; i < loadPendingFiles.length; i++){
  925. openFile(loadPendingFiles[i].filepath);
  926. }
  927. }
  928. //Initialize user settings
  929. restoreUserPreference();
  930. //Perform callback with editor object if required
  931. if (callback !== undefined){
  932. callback(editor);
  933. }
  934. });
  935. }
  936. /*
  937. Terminal Function Related
  938. */
  939. function terminalInit(){
  940. $(".ui.dropdown").dropdown();
  941. }
  942. var codeAreaBottomOffset = 0;
  943. function openTerminal(){
  944. //Open WsTTY on the editor
  945. codeAreaBottomOffset = 300;
  946. $("#terminals").show();
  947. updateCodeAreaSize();
  948. hideContextMenu();
  949. updateStatusHash("terminal",true);
  950. }
  951. function closeTerminal(){
  952. codeAreaBottomOffset = 0;
  953. $("#terminals").hide();
  954. updateCodeAreaSize();
  955. updateStatusHash("terminal",false);
  956. }
  957. function restartTerminal(){
  958. $("#terminals").find(".terminalWindow.focused").find("iframe").attr("src","");
  959. setTimeout(function(){
  960. $("#terminals").find(".terminalWindow.focused").find("iframe").attr("src",terminalStartingEndpoint);
  961. }, 1000);
  962. }
  963. $(window).on("resize", function(data){
  964. updateCodeAreaSize();
  965. });
  966. updateCodeAreaSize();
  967. function updateCodeAreaSize(){
  968. $("#codeArea").css({
  969. "height":window.innerHeight - 52 - codeAreaBottomOffset
  970. });
  971. editors.forEach(editor => {
  972. editor.editor.layout();
  973. })
  974. }
  975. function openFileInFileManager(){
  976. var tabInfo = getFocusedTabInfo();
  977. var filepath = tabInfo.filepath;
  978. var fileinfo = filepath.split("/");
  979. var filename = fileinfo.pop();
  980. var dirname = fileinfo.join("/");
  981. ao_module_openPath(dirname, filename);
  982. }
  983. function getHashObject(){
  984. if (window.location.hash.length > 1){
  985. var stateString = window.location.hash.substr(1);
  986. var currentState = JSON.parse(decodeURIComponent(stateString));
  987. return currentState
  988. }else{
  989. return {};
  990. }
  991. }
  992. function writeHashObject(newStateObject){
  993. window.location.hash = JSON.stringify(newStateObject);
  994. }
  995. function updateStatusHash(key, value){
  996. var currentState = getHashObject();
  997. currentState[key] = value;
  998. writeHashObject(currentState);
  999. }
  1000. function getOpenedFiles(){
  1001. var openedFilepaths = [];
  1002. editors.forEach(editor => {
  1003. editor.tabs.forEach(tab => {
  1004. if (!openedFilepaths.includes(tab.filepath)){
  1005. openedFilepaths.push(tab.filepath);
  1006. }
  1007. })
  1008. });
  1009. return openedFilepaths;
  1010. }
  1011. function changeTab(editorObject, targettabUUID) {
  1012. //Move focus to the selected editor
  1013. focusedEditor = editorObject.uuid;
  1014. //Get the basic information for the editor object
  1015. var editor = editorObject.editor;
  1016. var models = editorObject.model;
  1017. var states = editorObject.state;
  1018. var currentTabUUID = editorObject.currentTabUUID;
  1019. //save the current editor states
  1020. var currentState = editor.saveViewState();
  1021. var currentModel = editor.getModel();
  1022. states[currentTabUUID] = currentState;
  1023. models[currentTabUUID] = currentModel;
  1024. //Update the current Tab UUID
  1025. editorObject.currentTabUUID = targettabUUID;
  1026. //Load the content from the given uuid tab
  1027. editor.setModel(models[targettabUUID]);
  1028. editor.restoreViewState(states[targettabUUID]);
  1029. editor.focus();
  1030. //Update the target file info
  1031. var tabInfo = getFocusedTabInfo();
  1032. updateFileStatusDisplay(tabInfo.filepath);
  1033. //Update title if nonVDI or update floatWindow title if under fdi
  1034. if (ao_module_virtualDesktop){
  1035. ao_module_setWindowTitle("Code Studio - " + tabInfo.filename);
  1036. }else{
  1037. document.title = "Code Studio - " + tabInfo.filename
  1038. }
  1039. //Focus this tab
  1040. focusTabWithUUID(targettabUUID);
  1041. }
  1042. //Show clipboard reminders
  1043. function showClipboardReminders(rt){
  1044. var reminderText = "This function is keyboard shortcut only.";
  1045. var iconClass = "keyboard icon";
  1046. if (rt == 1){
  1047. reminderText = "Use the keyboard shortcut Ctrl + X to cut text from the editor.";
  1048. iconClass = "cut icon";
  1049. }else if (rt == 2){
  1050. reminderText = "Use the keyboard shortcut Ctrl + C for copying text from the editor";
  1051. iconClass = "copy icon";
  1052. }else if (rt == 3){
  1053. reminderText = "Use the keyboard shortcut Ctrl + V for pasting to editor.";
  1054. iconClass = "paste icon";
  1055. }else if (rt == 4){
  1056. reminderText = "Press Ctrl + F on the editor to start searching.";
  1057. iconClass = "search icon";
  1058. }else if (rt == 5){
  1059. reminderText = "Press Ctrl + H on the editor to start replacing text.";
  1060. iconClass = "sync alternate icon";
  1061. }
  1062. $("#clipboardReminderText").text(reminderText);
  1063. $("#clipboardReminderIcon").attr("class",iconClass)
  1064. $('#clipboardReminder').modal('show');
  1065. hideContextMenu();
  1066. }
  1067. //Editor function binding
  1068. function undo(){
  1069. editorObject = getFocusedEditorObject();
  1070. editorObject.editor.trigger('aaa','undo','aaa');
  1071. editorObject.editor.focus();
  1072. }
  1073. function redo(){
  1074. editorObject = getFocusedEditorObject();
  1075. editorObject.editor.trigger('aaa','redo','aaa');
  1076. editorObject.editor.focus();
  1077. }
  1078. //Save current file as a new file
  1079. function saveCurrentFileAs(){
  1080. var tabInfo = getFocusedTabInfo();
  1081. var filepath = tabInfo.filepath;
  1082. var fileinfo = filepath.split("/");
  1083. var filename = fileinfo.pop();
  1084. var dirname = fileinfo.join("/") + "/";
  1085. ao_module_openFileSelector(writeToSaveAsFile, dirname, "new",false,{
  1086. defaultName: filename
  1087. });
  1088. hideContextMenu();
  1089. }
  1090. function writeToSaveAsFile(filedata){
  1091. for (var i=0; i < filedata.length; i++){
  1092. var filename = filedata[i].filename;
  1093. var filepath = filedata[i].filepath;
  1094. var content = getFocusedEditorObject().editor.getValue();
  1095. //Write to this filepath
  1096. syscall("writeFile",{"filepath":filepath, "content":content}, function(data){
  1097. if (data.error !== undefined){
  1098. alert(data.error);
  1099. }else{
  1100. //OK
  1101. console.log("File saved");
  1102. msgbox("save","File Saved")
  1103. }
  1104. });
  1105. //Handle only one file write
  1106. return
  1107. }
  1108. }
  1109. function saveCurrentFile(){
  1110. var tabInfo = getFocusedTabInfo();
  1111. var focusedEditor = getFocusedEditorObject();
  1112. var filepath = tabInfo.filepath;
  1113. var content = focusedEditor.editor.getValue();
  1114. saveContentToFile(tabInfo.tabUUID, filepath, content, function(data){
  1115. if (data.error !== undefined){
  1116. alert(data.error);
  1117. }else{
  1118. //OK
  1119. console.log("File saved");
  1120. msgbox("save","File Saved")
  1121. }
  1122. });
  1123. hideContextMenu();
  1124. }
  1125. function getAllOpenedTabs(){
  1126. var results = [];
  1127. editors.forEach(editor => {
  1128. let thisEditor = editor;
  1129. editor.tabs.forEach(tab => {
  1130. let thisTab = tab;
  1131. results.push({
  1132. editor: thisEditor,
  1133. tab: thisTab
  1134. })
  1135. })
  1136. });
  1137. return results;
  1138. }
  1139. function saveContentToFile(tabUUID, filepath, content, callback=undefined){
  1140. syscall("writeFile",{"filepath":filepath, "content":content}, function(data){
  1141. if (callback !== undefined){
  1142. callback(data);
  1143. }
  1144. var contextHash = content.hashCode();
  1145. //Update all the tabs that contains this filepath
  1146. for (var i =0; i < editors.length; i++){
  1147. var thisEditor = editors[i];
  1148. for (var j =0; j < thisEditor.tabs.length; j++){
  1149. var thisTab = thisEditor.tabs[j];
  1150. if (thisTab.tabUUID == tabUUID){
  1151. thisTab.saveHash = contextHash;
  1152. }
  1153. }
  1154. }
  1155. });
  1156. }
  1157. function msgbox(icon, message){
  1158. $("#messageField").html(`<i class="${icon} icon"></i> ${message}`);
  1159. $("#messageField").stop().finish().hide().fadeIn('fast').delay(5000).fadeOut('fast');
  1160. }
  1161. function setStorage(key, value){
  1162. syscall("store",{opr:"set",key:key,value:value});
  1163. /*
  1164. $.post("./store",{opr: "set", key: key, value: value}).done(function(data){
  1165. if (data.error !== undefined){
  1166. console.log(data);
  1167. }
  1168. });
  1169. */
  1170. }
  1171. function getStorage(key, callback){
  1172. syscall("store",{opr:"get",key:key}, callback);
  1173. //$.post("./store",{opr: "get", key: key}).done(callback);
  1174. }
  1175. function showColorPicker(){
  1176. ao_module_newfw({
  1177. url: "Code Studio/tools/colorpicker/index.html",
  1178. width: 365,
  1179. height: 200,
  1180. appicon: "Code Studio/img/module_icon.png",
  1181. title: "Color Picker"
  1182. });
  1183. }
  1184. function showMobiPreview(){
  1185. var currentFileData = getCurrentFocusedFileData();
  1186. if (currentFileData == null){
  1187. //No opened files
  1188. alert("No editing file found!")
  1189. return;
  1190. }
  1191. //Encode the filedata
  1192. var fd = encodeURIComponent(JSON.stringify([currentFileData]));
  1193. ao_module_newfw({
  1194. url: "Code Studio/tools/mobipreview/index.html#" + fd,
  1195. width: 350,
  1196. height: 625,
  1197. appicon: "Code Studio/img/module_icon.png",
  1198. title: "Responsive Design Viewer"
  1199. });
  1200. }
  1201. function openInNewTab(){
  1202. //Open the editor in new tab
  1203. var currentFileData = getCurrentFocusedFileData();
  1204. if (currentFileData == null){
  1205. //No opened files
  1206. return;
  1207. }
  1208. //Encode the filedata
  1209. var fd = encodeURIComponent(JSON.stringify([currentFileData]));
  1210. window.open("./index.html#" + fd);
  1211. }
  1212. function openInNewFloatWindow(){
  1213. //Open the editor in new tab
  1214. var currentFileData = getCurrentFocusedFileData();
  1215. if (currentFileData == null){
  1216. //No opened files
  1217. return;
  1218. }
  1219. //Encode the filedata
  1220. var fd = encodeURIComponent(JSON.stringify([currentFileData]));
  1221. ao_module_newfw({
  1222. url: "Code Studio/index.html#" + fd,
  1223. width: 890,
  1224. height: 625,
  1225. appicon: "Code Studio/img/module_icon.png",
  1226. title: "Code Studio"
  1227. });
  1228. }
  1229. function newEditor(){
  1230. ao_module_newfw({
  1231. url: "Code Studio/index.html",
  1232. width: 890,
  1233. height: 625,
  1234. appicon: "Code Studio/img/module_icon.png",
  1235. title: "Code Studio"
  1236. });
  1237. }
  1238. function downloadFile(){
  1239. var currentFileData = getCurrentFocusedFileData();
  1240. if (currentFileData == null){
  1241. //No opened files
  1242. alert("No file selected")
  1243. return;
  1244. }
  1245. window.open("../../../media/download/?file=" + currentFileData.filepath);
  1246. }
  1247. function getCurrentFocusedFileData(){
  1248. var currentEditor = getFocusedEditorObject();
  1249. var focusedTabUUID = currentEditor.currentTabUUID;
  1250. for (var i = 0; i < currentEditor.tabs.length; i++){
  1251. if (currentEditor.tabs[i].tabUUID == focusedTabUUID){
  1252. //This is the tab we are looking for!
  1253. return {
  1254. filepath: currentEditor.tabs[i].filepath,
  1255. filename: currentEditor.tabs[i].filename
  1256. }
  1257. }
  1258. }
  1259. return null;
  1260. }
  1261. function hanleUserExit(){
  1262. //Check if there are opened files
  1263. var openedTabs = getAllOpenedTabs();
  1264. if (openedTabs.length > 0){
  1265. if (confirm("Some files might not be saved. Confirm exit?")){
  1266. ao_module_close();
  1267. }
  1268. }else{
  1269. ao_module_close();
  1270. }
  1271. }
  1272. //Hashcode function for comparing save stated
  1273. String.prototype.hashCode = function() {
  1274. var hash = 0;
  1275. if (this.length == 0) {
  1276. return hash;
  1277. }
  1278. for (var i = 0; i < this.length; i++) {
  1279. var char = this.charCodeAt(i);
  1280. hash = ((hash<<5)-hash)+char;
  1281. hash = hash & hash; // Convert to 32bit integer
  1282. }
  1283. return hash;
  1284. }
  1285. //Call to the system core with AJGI script
  1286. function syscall(scriptName, data, callback=undefined){
  1287. $.ajax({
  1288. url: "../system/ajgi/interface?script=Code Studio/backend/" + scriptName + ".agi",
  1289. method: "POST",
  1290. data: data,
  1291. success: function(data){
  1292. if (callback !== undefined){
  1293. callback(data);
  1294. }
  1295. }
  1296. })
  1297. }
  1298. //Drag events for fileTabs
  1299. function allowDrop(ev) {
  1300. ev.preventDefault();
  1301. }
  1302. //Drag file from directory explorer to editor tabs
  1303. function directoryFileDrag(ev){
  1304. var tabFilepath = $(ev.target).attr("filepath");
  1305. var tabFilename = $(ev.target).attr("filename");
  1306. var uuid = Date.now(); //Generate a new UUID for this
  1307. ev.dataTransfer.setData("uuid", uuid);
  1308. ev.dataTransfer.setData("filename", tabFilename);
  1309. ev.dataTransfer.setData("filepath", tabFilepath);
  1310. }
  1311. //Drag tab from one editor top to another
  1312. function fileTabDrag(ev) {
  1313. var tabUUID = $(ev.target).attr("uuid");
  1314. var tabFilepath = $(ev.target).attr("filepath");
  1315. var tabFilename = $(ev.target).text();
  1316. ev.dataTransfer.setData("uuid", tabUUID);
  1317. ev.dataTransfer.setData("filename", tabFilename);
  1318. ev.dataTransfer.setData("filepath", tabFilepath);
  1319. }
  1320. function TabDrop(ev) {
  1321. if ($(ev.target).hasClass("tabs") == false){
  1322. return;
  1323. }
  1324. ev.preventDefault();
  1325. //Get the file information
  1326. var tabUUID = ev.dataTransfer.getData("uuid");
  1327. var tabFilename = ev.dataTransfer.getData("filename");
  1328. var tabFilepath = ev.dataTransfer.getData("filepath");
  1329. if (tabFilename == "" || tabFilepath == ""){
  1330. return;
  1331. }
  1332. //Get the target dropping editor
  1333. var targetEditor = getEditor($(ev.target).attr("editoruid"));
  1334. if (targetEditor == undefined){
  1335. console.log("Editor with given ID not found");
  1336. return
  1337. }
  1338. //Open the file in the given editor
  1339. openFile(tabFilepath, true, targetEditor);
  1340. console.log(targetEditor, tabUUID, tabFilename, tabFilepath);
  1341. }
  1342. </script>
  1343. </body>
  1344. </html>