Browse Source

Completed NotepadA migration

Toby Chui 3 years ago
parent
commit
58d6c0a196
5 changed files with 271 additions and 172 deletions
  1. 41 16
      web/NotepadA/ace/editor.html
  2. 4 0
      web/NotepadA/backend/newfile.js
  3. 43 15
      web/NotepadA/embedded.html
  4. 162 141
      web/NotepadA/index.html
  5. 21 0
      web/script/ao_module.js

+ 41 - 16
web/NotepadA/ace/editor.html

@@ -42,10 +42,15 @@
 	var lastSave = "";
 	var fontsize = 12;
 	var theme = "github";
+	var editor = undefined;
 
-	var editor;
+	window.onhashchange = function(e){
+		initEditor();
+	}
 
-	if (window.location.hash.length > 0){
+	initEditor();
+	function initEditor(){
+		if (window.location.hash.length > 0){
 		var payload = window.location.hash.substr(1);
 		payload = JSON.parse(decodeURIComponent(payload));
 		filepath = payload.filename;
@@ -58,14 +63,25 @@
 
 		//Load the content of the file
 		$.get("../../media?file=" + filepath, function(fileContent){
-			$("#editor").html(fileContent);
+				$("#editor").html(fileContent);
 
-			//Start the editor
-			StartEditor();
-		});
-	}else{
-		alert("Invalid use of editor!")
+				//Start the editor if not started
+				if (editor == undefined){
+					StartEditor();
+				}
+			});
+		}else{
+			alert("Invalid use of editor!")
+		}
 	}
+	
+
+	document.addEventListener("mousedown", function(event) {
+		//When click on this document, focus this
+		if (parent.ao_module_virtualDesktop){
+			parent.ao_module_focus();
+		}
+	}, true);
 
 	function StartEditor(){
 		//Init editor
@@ -106,9 +122,8 @@
 	function Print() {
 		try {
 			var printWindow = window.open("", "", "height=400,width=800");
-			printWindow.document.write("<html><head><title>NotepadA Print Window</title>");
+			printWindow.document.write(`<html><head><title>${filename}  ${new Date().toLocaleString()}</title>`);
 			printWindow.document.write("</head><xmp>");
-			printWindow.document.write("filename: " + filename + " \nprint-time: " + new Date().toLocaleString() + "\n");
 			printWindow.document.write(editor.getSession().getDocument().getValue());
 			printWindow.document.write("</xmp></html>");
 			printWindow.document.close();
@@ -121,6 +136,20 @@
 	//Absolute path is used for saving. So no need to worry about the relative path over php issues
 	function Save(){
 		code = editor.getValue();
+		parent.ao_module_agirun(parent.moduleRootPath + "backend/filesaver.js", {
+			filepath: filepath,
+			content: code
+		}, function(data){
+			if (data.error == undefined){
+				//Finish writting to the file
+				console.log("%c[NotepadA] " + filename + " -> Saved!","color:#1265ea");
+				lastSave = code;
+			}else{
+				console.log(data);
+			}
+		})
+
+		/*
 		$.post("../writeCode.php", { filename: filepath, content: code })
 		  .done(function( data ) {
 			if (data.includes("ERROR") == false){
@@ -130,6 +159,7 @@
 				console.log(data);
 			}
 		  });
+		  */
 	}
 	
 	function getDocWidth(){
@@ -161,12 +191,7 @@
 	}
 	
 	function openInNewTab(){
-		if (filename.substring(0,14) == "/media/storage"){
-			window.open("../SystemAOB/functions/extDiskAccess.php?file=" + filename);
-		}else{
-			window.open(filename.replace("../",""));
-		}
-		
+		window.open("../../media?file=" + filepath);
 	}
 	
 	function getSelectedText(){

+ 4 - 0
web/NotepadA/backend/newfile.js

@@ -0,0 +1,4 @@
+requirelib("filelib");
+filelib.mkdir("user:/Document/NotepadA");
+filelib.writeFile("user:/Document/NotepadA/" + tmpid, "");
+sendJSONResp(JSON.stringify("user:/Document/NotepadA/" + tmpid));

+ 43 - 15
web/NotepadA/embedded.php → web/NotepadA/embedded.html

@@ -1,28 +1,55 @@
 <html>
 <head>
-<?php
-include_once '../auth.php';
-?>
+	<style>
+		body{
+			background-color: white;
+		}
+	</style>
 </head>
 <body>
 Initializing Environment...<br>
-This window should close automatically. If not, click <a onClick="ao_module_close();">here</a>.
-<?php
-$filepath = "";
-$filename = "";
-if (isset($_GET['filepath'])){
-	$filepath = str_replace("./","",str_replace("../","",str_replace("\\","/",$_GET['filepath'])));
-}
-if (isset($_GET['filename'])){
-	$filename = $_GET['filename'];
-}
-?>
 <script src="../script/jquery.min.js"></script>
 <script src="../script/ao_module.js"></script>
 <script>
 //Try its best to hide this window
-ao_module_setGlassEffectMode();
 ao_module_setWindowTitle("NotepadA Initializing...");
+
+var inputFiles = ao_module_loadInputFiles();
+if (inputFiles != null){
+	console.log(inputFiles);
+	let targetOpeningInstances = ao_module_getInstanceByPath("NotepadA/index.html")
+	if (targetOpeningInstances == null){
+		//Open the file in new NotepadA windows
+		let encodedFileObject = encodeURIComponent(JSON.stringify(inputFiles));
+		var url = "NotepadA/index.html#" + encodedFileObject;
+		var title = "NotepadA";
+		ao_module_newfw({
+			url: url,
+			width: 1080,
+			height: 580,
+			title: title,
+			appicon: "NotepadA/img/small_icon.png",
+		});
+
+		setTimeout(function(){
+			ao_module_close();
+		}, 300);
+	}else{
+		//Make the running NotepadA instance to open those files
+		inputFiles.forEach(function(file){
+			console.log($(targetOpeningInstances).find("iframe")[0].contentWindow.newEditor(file.filepath));
+		});
+		
+		setTimeout(function(){
+			ao_module_close();
+		}, 300);
+	}
+
+
+	
+}
+
+/*
 var instances = ao_module_getProcessID("NotepadA");
 var filepath = "<?php echo $filepath;?>";
 var filename = "<?php echo $filename;?>";
@@ -46,6 +73,7 @@ function remove(array, element) {
     const index = array.indexOf(element);
     array.splice(index, 1);
 }
+*/
 </script>
 </body>
 </html>

+ 162 - 141
web/NotepadA/index.html

@@ -200,29 +200,11 @@
 </div>
 <div id="aboutus" class="middleFloat" style="display:none;">
 	<h3>📝 NotepadA ArOZ Online In-System Text Editor</h3>
-	<p>Author: Toby Chui 2017-2019</p>
+	<p>Author: Toby Chui 2017-2021</p>
 	<hr>
-	<p>This web based text editor for ArOZ Online System are made possible by the ace editor, jQuery and ArOZ Project. Part of the system are licensed under BSD License or MIT license. Please refer to the individual license information under the library folder. <br><br>For the rest of the system and interface, all codes are CopyRight Toby Chui feat. IMUS Laboratory and licnesed under IMUS license (which is something similar to MIT license but with some extra licensing information about hardware). Developed under ArOZ Online System for experimental purpose.<br><br>
-Visit <a href="https://github.com/tobychui">https://github.com/tobychui</a> for more information.</p>
+	<p>This web based text editor for ArOZ Online System are made possible by the ace editor, jQuery and ArOZ Project. Part of the system are licensed under BSD License. Please refer to the individual license information under the library folder. <br><br><br>
+ 	Developed for ArOZ Online Beta and migrated to ArozOS</p>
 	<hr>
-	<p>MIT License<p>
-	<p style="font-size:70%;">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:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-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.</p>
 	<p>BSD License<p>
 	<p style="font-size:70%;">All rights reserved.
 Redistribution and use in source and binary forms, with or without
@@ -287,7 +269,6 @@ var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator
 var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
 var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox')
 var lastSelectedMenuItem = "";
-var username = loadStorage("ArOZusername");
 var fontsize = 12;
 var VDI = ao_module_virtualDesktop;
 var openedFilePath = [];
@@ -298,7 +279,7 @@ var currentTabWidth = 0;
 var mainCodingWindow = true;
 var functionList = {
 	File: ["📄 New","📂 Open File","Run in FloatWindow","Open current directory","Reload","💾 Save","💾 Save As","Close All Tabs","🖨 Print","Exit"],
-	Edit: ["⤺ Undo","⤻ Redo","Open in New Tab","Insert Special Characters"],
+	Edit: ["⤺ Undo","⤻ Redo","Open in New Tab"],
 	Search:["Find / Replace"],
 	Theme:["ambiance","chaos","chrome","clouds","clouds_midnight","cobalt","crimson_editor","dawn","dracula","dreamweaver","eclipse","github","gob","gruvbox","idle_fingers","iplastic","katzenmilch","kr_theme","kuroir","merbivore","merbivore_soft","mono_industrial","monokai","pastel_on_dark","solarized_dark","solarized_light","sqlserver","terminal","textmate","tomorrow","tomorrow_night","tomorrow_night_blue","tomorrow_night_bright","tomorrow_night_eighties","twilight","vibrant_ink","xcode"],
 	Font_Size:["8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25"],
@@ -308,69 +289,122 @@ var functionList = {
 //Init functions
 adjustCodeAreaHeight();
 bindListener();
-initTheme();
-initFontSize();
-initNotepadA();
-reloadAllTabs();
-loadAllSpecialCharacter();
+init();
+
+//Start all NotepadA services
+function init(){
+	initTheme(function(){
+		initFontSize(function(){
+			initNotepadA(function(){
+				reloadAllTabs();
+				loadAllSpecialCharacter();
+			});
+		});
+	});
+}
 
 //Init notepadA. If there are previos stored page, load them into the environment. Or otherwise, just open a blank page.
-function initNotepadA(){
-	if (!ao_module_virtualDesktop){
-		$(".topbar").prepend('<div class="npalogo" style="display:inline;"><a href="../index.php">◀️</a> | NotepadA</div>');
-		$(".topbar").css("padding-left","0px");
+function initNotepadA(callback=undefined){
+	//Load input file from ao_module
+	inFiles = ao_module_loadInputFiles();
+	if (inFiles == null){
+		dragIn = "";
+	}else{
+		dragIn = [];
+		inFiles.forEach(function(file){
+			dragIn.push(file.filepath); 
+		});
 	}
-	
-	//ao_module_setWindowSize(1080,600);
-	if (loadStorage("NotepadA_" + username + "_sessionFiles") != ""){
-		var pages = JSON.parse(loadStorage("NotepadA_" + username + "_sessionFiles"));
-		for (var i =0; i < pages.length;i++){
-			let page = pages[i];
-			newEditor(page);
-		}
-		if (dragIn != ""){
-			//If there is a file dragin, and it hasn't been opened, open it
-			if (pages.indexOf(dragIn) == -1){
-				newEditor(dragIn);
+
+	loadStorage("sessionFiles", function(sessionFiles){
+		if (sessionFiles == ""){
+			//No previous opened files
+			if (dragIn != ""){
+				//If there is a file dragin, open it as well.
+				dragIn.forEach(function(openingFile){
+					newEditor(openingFile);
+				})
 			}else{
-				focusTab($($(".fileTab")[pages.indexOf(dragIn)]).attr("tabid"));
+				newTab();
 			}
-			//alert(dragIn);
-		}
-	}else{
-		if (dragIn != ""){
-			//If there is a file dragin, open it as well.
-			newEditor(dragIn);
 		}else{
-			newTab();
-		}
-	}
-	setTimeout(function(){
-		setInterval(function(){
-			var tabid = getFocusedTab();
-			if (tabid.length == 0){
-				return;
+			//There are perviously opened files
+			var pages = JSON.parse(sessionFiles);
+			for (var i =0; i < pages.length;i++){
+				let page = pages[i];
+				newEditor(page);
 			}
-			var tab = findTabWithAttr("framematch",tabid[0]);
-			var saved = checkTabSaved(tabid[0]);
-			if (saved != previousSavedState){
-				previousSavedState = saved;
-				if (saved){
-					ao_module_setWindowTitle("NotepadA   	 📝 " + tab.attr("filename").replace("../../","/aor/"));
-					document.title = "NotepadA   	 📝 " + tab.attr("filename").replace("../../","/aor/");
-				}else{
-					ao_module_setWindowTitle("NotepadA   	 *💾 📝 " + tab.attr("filename").replace("../../","/aor/"));
-					document.title = "NotepadA   	 *💾 📝 " + tab.attr("filename").replace("../../","/aor/");
-				}
+
+			if (dragIn != ""){
+				//If there is a file dragin, and it hasn't been opened, open it
+				dragIn.forEach(function(filepath){
+					if (pages.indexOf(filepath) == -1){
+						newEditor(filepath);
+					}else{
+						focusTab($($(".fileTab")[pages.indexOf(filepath)]).attr("tabid"));
+					}
+				})
 			}
-			
-			
-		},1000);
-	},500);
+		}
+
+		setTimeout(function(){
+			setInterval(function(){
+				var tabid = getFocusedTab();
+				if (tabid.length == 0){
+					return;
+				}
+				var tab = findTabWithAttr("framematch",tabid[0]);
+				var saved = checkTabSaved(tabid[0]);
+				if (saved != previousSavedState){
+					previousSavedState = saved;
+					if (saved){
+						ao_module_setWindowTitle("NotepadA   	 📝 " + tab.attr("filename").replace("../../","/aor/"));
+						document.title = "NotepadA   	 📝 " + tab.attr("filename").replace("../../","/aor/");
+					}else{
+						ao_module_setWindowTitle("NotepadA   	 *💾 📝 " + tab.attr("filename").replace("../../","/aor/"));
+						document.title = "NotepadA   	 *💾 📝 " + tab.attr("filename").replace("../../","/aor/");
+					}
+				}
+				
+				
+			},1000);
+		},500);
+		
+		toggleFileTabsList();
+
+		if (callback != undefined){
+			callback();
+		}
+		
+	})
+}
+
+function initTheme(callback=undefined){
+	loadStorage("NotepadA_theme", function(data){
+		if (data != ""){
+			theme = data;
+		}
+		console.log("NotepadA Theme Loaded: " + theme)
+		if (callback != undefined){
+			callback();
+		}
+	});
+}
+
+function initFontSize(callback=undefined){
+	loadStorage("NotepadA_fontsize", function(data){
+		if (data != ""){
+			fontsize = data;
+		}
+		if (callback != undefined){
+			callback();
+		}
+	});
+
 	
-	toggleFileTabsList();
 }
 
+
 //Add a new editor window to the editor (?) -->ALL FILE PATH PASSED IN MUST BE FROM AOR OR /media/storage*
 function newEditor(filepath){
      if (openedFilePath.includes(filepath)){
@@ -403,48 +437,63 @@ function newEditor(filepath){
 	if (openedFilePath.indexOf(filepath) == -1){
 		openedFilePath.push(filepath);
 	}
-	setStorage("NotepadA_" + username + "_sessionFiles",JSON.stringify(openedFilePath));
+	setStorage("sessionFiles",JSON.stringify(openedFilePath));
 }
 
 function newTab(){
 	let tabid = Math.round((new Date()).getTime());
-	let filepath = 'NotepadA/tmp/newfile_' + tabid;
-	var tab = '<div class="fileTab" tabid="'+tabid+'" framematch="ca'+tabid+'" filename="../../'+filepath+'">\
+	let fileID = 'newfile_' + tabid;
+
+	ao_module_agirun(moduleRootPath + "backend/newfile.js", {
+		tmpid: fileID
+	}, function(data){
+		if (data.error == undefined){
+            //Finish writting to the new file. Open the new file in new tab
+            var tab = '<div class="fileTab" tabid="'+tabid+'" framematch="ca'+tabid+'" filename="' + data + '">\
 					loading... <div class="closeBtn">⨯</div>\
 					</div>';
-	var frame = '<div style=""><iframe id="ca'+tabid+'" class="editor" src="ace/editor.php?theme='+theme+'&filename=../../'+filepath+'&fontsize=' + fontsize + '" width="100%" frameBorder="0"></iframe></div>';
-	$("#tabs").append(tab);
-	$("#codeArea").append(frame);
-	updateFrameAttr('ca' + tabid);
-	setTimeout(function(){focusTab(tabid + "");},100);
-	if (openedFilePath.indexOf(filepath) == -1){
-		openedFilePath.push(filepath);
-	}
-	setStorage("NotepadA_" + username + "_sessionFiles",JSON.stringify(openedFilePath));
+			let payload = {
+				"theme": theme,
+				"filename": data,
+				"fontsize": fontsize,
+				"timestamp": Date.now() //Add this to make sure browser dont cache resp
+			}
+			let encodedPayload = encodeURIComponent(JSON.stringify(payload))
+			var frame = '<div style=""><iframe id="ca'+tabid+'" class="editor" src="ace/editor.html#' + encodedPayload + '" width="100%" frameBorder="0"></iframe></div>';
+			$("#tabs").append(tab);
+			$("#codeArea").append(frame);
+			updateFrameAttr('ca' + tabid);
+			setTimeout(function(){focusTab(tabid + "");},100);
+			if (openedFilePath.indexOf(data) == -1){
+				openedFilePath.push(data);
+			}
+			setStorage("sessionFiles",JSON.stringify(openedFilePath));
+        }else{
+           alert("Create tmp file failed");
+        }
+	})
+
+	
 }
 
 function saveToDirectory(){
     var targetPath = currentSaveAsPath;
-    if (targetPath.includes("/media/storage") == false){
-        //If it is not starting from the media root, stat with aor.
-        //Remove the "/" at the front of the path
-        targetPath = "../" + targetPath.substr(1);
-    }
     var newfilename = $("#saveAsFilename").val();
     var framematch = getFocusedTab()[0];
     var editorContent = $("#" + framematch)[0].contentWindow.getEditorContenet();
-    $.post( "writeCode.php", { filename: targetPath + newfilename, content: editorContent }).done(function( data ) {
-        if (data.includes("ERROR") == false){
+
+	ao_module_agirun(moduleRootPath + "backend/filesaver.js", {
+		filepath: targetPath + newfilename,
+		content: editorContent
+	}, function(data){
+		if (data.error == undefined){
             //Finish writting to the new file. Open the new file in new tab
-            if (targetPath.includes("/media/storage")==false && targetPath.includes("../")){
-                targetPath = targetPath.replace("../","");
-            }
             newEditor(targetPath + newfilename);
             $("#saveAsSelectionMenu").hide();
         }else{
             console.log(data);
         }
-      });
+	})
 }
 
 function changeSaveAsPath(object){
@@ -738,7 +787,16 @@ function reloadTab(tabID){
 	var object = findTabWithAttr("tabid",tabID);
 	var filename = $(object).attr("filename");
 	var codeAreaID = $(object).attr("framematch");
-	$("#" + codeAreaID).attr("src","ace/editor.php?theme=" + theme + "&fontsize="+fontsize+"&filename=" + filename);
+	let payload = {
+		"theme": theme,
+		"filename": filename,
+		"fontsize": fontsize,
+		"timestamp": Date.now() //Add this to make sure browser dont cache resp
+	}
+	let encodedPayload = encodeURIComponent(JSON.stringify(payload))
+	console.log($("#" + codeAreaID));
+	$("#" + codeAreaID).attr("src","ace/editor.html#" + encodedPayload);
+	$("#" + codeAreaID)[0].contentWindow.location.reload();
 }
 
 function launchFocusedTabSearchBox(){
@@ -799,6 +857,7 @@ function handleFileMenu(itemText){
 				url: url,
 				width: 1080,
 				height: 580,
+				title: title,
 				appicon: "NotepadA/img/small_icon.png",
 			});
 
@@ -882,12 +941,7 @@ function handleFileMenu(itemText){
 			$("#" + id)[0].contentWindow.Print();
 			break;
 		case 9:
-			if (VDI){
-				window.location.href = "../SystemAOB/functions/killProcess.php"
-			}else{
-				window.location.href = "../index.php"
-			}
-			break;
+			ao_module_close();
 	}
 }
 
@@ -898,16 +952,6 @@ function handleAboutMenu(itemText){
 	}
 }
 
-function newfw(src,windowname,icon,uid,sizex,sizey,posx = undefined,posy = undefined,fixsize = undefined,tran = undefined, parentUID=undefined, callbackFunct=undefined){
-	//Example
-	//newEmbededWindow('Memo/index.php','Memo','sticky note outline','memoEmbedded',475,700);
-	if (!VDI){
-		window.open("../" + src);
-		return;
-	}
-	parent.newEmbededWindow(src,windowname,icon,uid,sizex,sizey,posx,posy,fixsize,tran,parentUID,callbackFunct);
-}
-
 function getFocusedTab(){
 	result = [];
 	$(".fileTab").each(function(){
@@ -962,38 +1006,15 @@ function checkIfAllTabSaved(){
 	return allSaved;
 }
 
-
-function initTheme(){
-	if (loadStorage("NotepadA_theme") != ""){
-		theme = loadStorage("NotepadA_theme");
-	}
-}
-
-function initFontSize(){
-	if (loadStorage("NotepadA_fontsize") != ""){
-		fontsize = loadStorage("NotepadA_fontsize");
-	}
-}
-
 function setStorage(configName,configValue){
 	//localStorage.setItem(name, value);
-	/*
-	$.ajax({
-	  type: 'POST',
-	  url: "../SystemAOB/functions/user/userGlobalConfig.php",
-	  data: {module: "NotepadA",name:configName,value:configValue},
-	  success: function(data){},
-	  async:true
-	});
-	*/
 	ao_module_storage.setStorage("NotepadA", configName, configValue);
 	return true;
 }
 
-function loadStorage(configName){
+function loadStorage(configName, callback){
 	var result = "";
-	ao_module_storage.loadStorage("NotepadA", configName);
-	return result;
+	ao_module_storage.loadStorage("NotepadA", configName, callback);
 }
 
 function removeTab(tabid){
@@ -1029,7 +1050,7 @@ function removeTab(tabid){
 		//There is no more tab left, create a new tab instead
 		setTimeout(function(){ newTab("untitled"); }, 100);
 	}
-	setStorage("NotepadA_" + username + "_sessionFiles",JSON.stringify(openedFilePath));
+	setStorage("sessionFiles",JSON.stringify(openedFilePath));
 	toggleFileTabsList();
 }
 

+ 21 - 0
web/script/ao_module.js

@@ -173,6 +173,27 @@ function ao_module_makeSingleInstance(){
     return false
 }
 
+//Use for cross frame communication, example: 
+//let targetOpeningInstances = ao_module_getInstanceByPath("NotepadA/index.html")
+function ao_module_getInstanceByPath(matchingPath){
+    let targetInstance = "";
+    $(window.parent.document).find(".floatWindow").each(function(){
+        if ($(this).attr("windowid") == ao_module_windowID){
+            return
+        }
+        let thisfwPath = $(this).find("iframe").attr('src').split("#").shift();
+        if (thisfwPath == matchingPath){
+            targetInstance = $(this).attr("windowid");
+        }
+    });
+
+    if (targetInstance == ""){
+        return null;
+    }
+        
+    return parent.getFloatWindowByID(targetInstance);
+}
+
 
 //Close the current window
 function ao_module_close(){