This commit is contained in:
2026-01-30 21:55:35 +08:00
commit 5b5684cd43
10 changed files with 1568 additions and 0 deletions

58
.gitignore vendored Normal file
View File

@@ -0,0 +1,58 @@
# Build output
bin/
obj/
# IDE files
.vs/
*.suo
*.user
*.sln.docstates
# Cosmos specific files
*.vmdk
*.iso
*.img
# Log files
*.log
# Temporary files
*.tmp
*.temp
# OS generated files
Thumbs.db
.DS_Store
# Package manager files
packages/
.nuget/
# Environment variables
.env
# Test results
TestResults/
coverage/
# Documentation
*.rst
# Backup files
*.bak
*.old
# Misc
*.swp
*~
.project
.classpath
.c9/
.settings/
# Debug files
*.pdb
*.mdb
# Release files
*.release

30
CMLeonOS.csproj Normal file
View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<!--<RuntimeIdentifier>cosmos</RuntimeIdentifier>-->
<Platform>cosmos</Platform>
<SupportsX86Intrinsics>false</SupportsX86Intrinsics>
<SelfContained>True</SelfContained>
<Platforms>AnyCPU;x64</Platforms>
<Configurations>Debug;Release;Release (Fixed)</Configurations>
</PropertyGroup>
<PropertyGroup>
<EnableGDB>False</EnableGDB>
<StartCosmosGDB>False</StartCosmosGDB>
<VisualStudioDebugPort>Pipe: Cosmos\Serial</VisualStudioDebugPort>
<CosmosDebugPort>Serial: COM1</CosmosDebugPort>
<Launch>VMware</Launch>
<Profile>VMware</Profile>
<Description>Use VMware Player or Workstation to deploy and debug.</Description>
<PxeInterface>192.168.0.8</PxeInterface>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Cosmos.Build" Version="0-*" NoWarn="NU1604" />
<PackageReference Include="Cosmos.Debug.Kernel" Version="0-*" NoWarn="NU1604" />
<PackageReference Include="Cosmos.System2" Version="0-*" NoWarn="NU1604" />
</ItemGroup>
</Project>

24
CMLeonOS.sln Normal file
View File

@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CMLeonOS", "CMLeonOS.csproj", "{6C1B2895-8108-62B7-CBCE-014DEA155AB7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6C1B2895-8108-62B7-CBCE-014DEA155AB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C1B2895-8108-62B7-CBCE-014DEA155AB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C1B2895-8108-62B7-CBCE-014DEA155AB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C1B2895-8108-62B7-CBCE-014DEA155AB7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AE8E1CEA-FDF5-449C-9B1D-477E510A120A}
EndGlobalSection
EndGlobal

158
CUI.cs Normal file
View File

@@ -0,0 +1,158 @@
using System;
namespace CMLeonOS
{
public class CUI
{
private string title;
private string status;
private ConsoleColor backgroundColor;
private ConsoleColor textColor;
public CUI(string title = "CMLeonOS")
{
this.title = title;
this.status = "Ready";
this.backgroundColor = ConsoleColor.Black;
this.textColor = ConsoleColor.White;
}
public void SetTitle(string title)
{
this.title = title;
}
public void SetStatus(string status)
{
this.status = status;
}
public void SetBackgroundColor(ConsoleColor color)
{
this.backgroundColor = color;
}
public void SetTextColor(ConsoleColor color)
{
this.textColor = color;
}
public void Render()
{
Console.BackgroundColor = backgroundColor;
Console.ForegroundColor = textColor;
Console.Clear();
RenderTopBar();
// 重置颜色
Console.ResetColor();
}
public void RenderBottomBar()
{
// 渲染底栏
RenderBottomBarImpl();
}
private void RenderTopBar()
{
// 简化顶栏渲染确保在Cosmos环境中正确显示
Console.ForegroundColor = textColor;
Console.BackgroundColor = backgroundColor;
// 使用固定长度的顶栏,避免宽度计算问题
string topBar = new string('─', 80); // 假设标准宽度为80
Console.WriteLine(topBar);
// 居中显示标题和状态
string titleLine = $"{title.PadRight(60)}{status}";
if (titleLine.Length > 80)
{
titleLine = titleLine.Substring(0, 80);
}
Console.WriteLine(titleLine);
Console.WriteLine(topBar);
Console.ResetColor();
}
private void RenderBottomBarImpl()
{
// 简化底栏渲染确保在Cosmos环境中正确显示
Console.ForegroundColor = textColor;
Console.BackgroundColor = backgroundColor;
// 使用固定长度的底栏,避免宽度计算问题
string bottomBar = new string('─', 80); // 假设标准宽度为80
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(bottomBar);
// 显示帮助信息和时间
string timeText = DateTime.Now.ToShortTimeString();
string bottomLine = $"Press help for available commands{(new string(' ', 80 - 35 - timeText.Length))}{timeText}";
if (bottomLine.Length > 80)
{
bottomLine = bottomLine.Substring(0, 80);
}
Console.WriteLine(bottomLine);
Console.WriteLine(bottomBar);
Console.ResetColor();
}
public void ShowMessage(string message)
{
Console.WriteLine(message);
}
public void ShowError(string error)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: {error}");
Console.ResetColor();
}
public void ShowSuccess(string message)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Success: {message}");
Console.ResetColor();
}
public string Prompt(string promptText)
{
Console.Write($"{promptText}: ");
return Console.ReadLine();
}
public void Clear()
{
Console.Clear();
Render();
}
}
}

301
Editor.cs Normal file
View File

@@ -0,0 +1,301 @@
using System;
using System.Collections.Generic;
namespace CMLeonOS
{
// 简单的代码编辑器类
// 支持基本的文本编辑功能,如输入、删除、移动光标等
// 支持文件的加载和保存
public class Editor
{
private string fileName; // 要编辑的文件名
private List<string> lines; // 文件内容的行列表
private int currentLine; // 当前光标所在行
private int currentColumn; // 当前光标所在列
private bool isRunning; // 编辑器是否正在运行
private FileSystem fileSystem; // 文件系统实例,用于读写文件
// 构造函数
// 参数fileName - 要编辑的文件名
// 参数fs - 文件系统实例
public Editor(string fileName, FileSystem fs)
{
this.fileName = fileName;
this.fileSystem = fs;
this.lines = new List<string>();
this.currentLine = 0;
this.currentColumn = 0;
this.isRunning = true;
LoadFile();
}
// 运行编辑器
// 主循环:渲染界面 -> 处理输入 -> 重复
public void Run()
{
while (isRunning)
{
Render();
HandleInput();
}
}
// 加载文件内容
private void LoadFile()
{
try
{
// 尝试从文件系统读取文件内容
string content = fileSystem.ReadFile(fileName);
if (!string.IsNullOrEmpty(content))
{
// 分割内容为行
string[] fileLines = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (string line in fileLines)
{
lines.Add(line);
}
}
else
{
// 文件不存在或为空,创建新文件
lines.Add("");
}
}
catch
{
// 文件不存在,创建新文件
lines.Add("");
}
}
// 保存文件内容
private void SaveFile()
{
try
{
// 简化实现,避免可能导致栈损坏的操作
string content = "";
for (int i = 0; i < lines.Count; i++)
{
content += lines[i];
if (i < lines.Count - 1)
{
content += "\n";
}
}
// 直接使用CreateFile因为它会覆盖现有文件
try
{
fileSystem.CreateFile(fileName, content);
Console.WriteLine($"File saved: {fileName}");
}
catch (Exception ex)
{
Console.WriteLine($"Error saving file: {ex.Message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in SaveFile: {ex.Message}");
}
}
// 渲染编辑器界面
private void Render()
{
Console.Clear();
// 显示标题栏
Console.WriteLine($"CMLeonOS Editor - {fileName}");
Console.WriteLine("--------------------------------");
Console.WriteLine("Commands: Esc = Exit");
Console.WriteLine();
// 显示文件内容(限制显示行数,避免超出控制台高度)
int maxVisibleLines = 15; // 假设控制台高度为25行留10行给其他内容
int startLine = Math.Max(0, currentLine - maxVisibleLines / 2);
int endLine = Math.Min(lines.Count, startLine + maxVisibleLines);
for (int i = startLine; i < endLine; i++)
{
string line = lines[i];
Console.WriteLine($"{i + 1}: {line}");
}
// 显示光标位置
Console.WriteLine();
Console.WriteLine($"Cursor: Line {currentLine + 1}, Column {currentColumn + 1}");
Console.WriteLine($"Lines: {lines.Count}");
// 计算光标位置,确保不超出控制台高度
int consoleHeight = 25; // 假设控制台高度为25行
int titleLines = 4; // 标题栏占用的行数
int visibleLines = endLine - startLine;
int cursorY = titleLines + (currentLine - startLine);
// 确保光标Y位置在有效范围内
cursorY = Math.Max(titleLines, Math.Min(cursorY, consoleHeight - 5)); // 留5行给状态信息
// 设置光标位置
try
{
Console.SetCursorPosition(currentColumn + 4, cursorY);
}
catch
{
// 如果设置光标位置失败,忽略错误
}
}
// 处理用户输入
private void HandleInput()
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.Escape:
// 显示保存确认弹窗
ShowSaveConfirmation();
break;
case ConsoleKey.Backspace:
// 删除字符
if (currentColumn > 0)
{
string line = lines[currentLine];
line = line.Remove(currentColumn - 1, 1);
lines[currentLine] = line;
currentColumn--;
}
else if (currentLine > 0)
{
// 如果在行首,合并到上一行
string previousLine = lines[currentLine - 1];
string lineText = lines[currentLine];
lines.RemoveAt(currentLine);
currentLine--;
currentColumn = previousLine.Length;
lines[currentLine] = previousLine + lineText;
}
break;
case ConsoleKey.Enter:
// 插入换行
string currentLineText = lines[currentLine];
string firstPart = currentLineText.Substring(0, currentColumn);
string secondPart = currentLineText.Substring(currentColumn);
lines[currentLine] = firstPart;
lines.Insert(currentLine + 1, secondPart);
currentLine++;
currentColumn = 0;
break;
case ConsoleKey.LeftArrow:
// 左移光标
if (currentColumn > 0)
{
currentColumn--;
}
break;
case ConsoleKey.RightArrow:
// 右移光标
if (currentColumn < lines[currentLine].Length)
{
currentColumn++;
}
break;
case ConsoleKey.UpArrow:
// 上移光标
if (currentLine > 0)
{
currentLine--;
currentColumn = Math.Min(currentColumn, lines[currentLine].Length);
}
break;
case ConsoleKey.DownArrow:
// 下移光标
if (currentLine < lines.Count - 1)
{
currentLine++;
currentColumn = Math.Min(currentColumn, lines[currentLine].Length);
}
break;
default:
// 输入字符
if (char.IsLetterOrDigit(keyInfo.KeyChar) || char.IsPunctuation(keyInfo.KeyChar) || char.IsSymbol(keyInfo.KeyChar) || keyInfo.KeyChar == ' ')
{
string line = lines[currentLine];
line = line.Insert(currentColumn, keyInfo.KeyChar.ToString());
lines[currentLine] = line;
currentColumn++;
}
break;
}
}
// 显示保存确认弹窗
private void ShowSaveConfirmation()
{
// 简化版本避免使用可能在Cosmos中不支持的功能
Console.Clear();
// 显示灰色背景的确认弹窗
Console.BackgroundColor = ConsoleColor.DarkGray;
Console.ForegroundColor = ConsoleColor.White;
// 简单的弹窗显示
Console.WriteLine("+----------------------------+");
Console.WriteLine("| Save File? |");
Console.WriteLine("+----------------------------+");
Console.WriteLine("| Do you want to save the |");
Console.WriteLine("| changes? |");
Console.WriteLine("+----------------------------+");
Console.WriteLine("| Y = Yes, N = No |");
Console.WriteLine("+----------------------------+");
// 等待用户输入
while (true)
{
ConsoleKeyInfo keyInfo;
try
{
keyInfo = Console.ReadKey(true);
}
catch
{
// 如果ReadKey失败直接退出
Console.ResetColor();
Console.Clear();
isRunning = false;
return;
}
if (keyInfo.Key == ConsoleKey.Y)
{
// 保存文件
try
{
SaveFile();
}
catch
{
Console.WriteLine("Error saving file");
}
Console.ResetColor();
Console.Clear();
isRunning = false;
break;
}
else if (keyInfo.Key == ConsoleKey.N)
{
// 不保存文件
Console.ResetColor();
Console.Clear();
isRunning = false;
break;
}
}
}
}
}

280
FileSystem.cs Normal file
View File

@@ -0,0 +1,280 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace CMLeonOS
{
public class FileSystem
{
private string currentDirectory;
public FileSystem()
{
currentDirectory = @"0:\";
}
public string CurrentDirectory
{
get { return currentDirectory; }
}
public void ChangeDirectory(string path)
{
if (string.IsNullOrEmpty(path))
{
currentDirectory = @"0:\";
return;
}
string fullPath = GetFullPath(path);
try
{
if (Directory.Exists(fullPath))
{
currentDirectory = fullPath;
}
else
{
Console.WriteLine($"Directory not found: {path}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error changing directory: {ex.Message}");
}
}
public void MakeDirectory(string path)
{
string fullPath = GetFullPath(path);
try
{
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
Console.WriteLine($"Directory created: {path}");
}
else
{
Console.WriteLine($"Directory already exists: {path}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error creating directory: {ex.Message}");
}
}
public void ListFiles(string path = ".")
{
string fullPath = GetFullPath(path);
try
{
if (Directory.Exists(fullPath))
{
// 列出当前目录下的文件和子目录
Console.WriteLine($"Contents of {path}:");
// 列出子目录
try
{
var dirs = Directory.GetDirectories(fullPath);
foreach (var dir in dirs)
{
// 使用Path.GetFileName获取目录名避免Substring可能导致的问题
string dirName = Path.GetFileName(dir);
Console.WriteLine($"[DIR] {dirName}");
}
}
catch
{
// 可能没有权限或其他错误
}
// 列出文件
try
{
var files = Directory.GetFiles(fullPath);
foreach (var file in files)
{
// 使用Path.GetFileName获取文件名避免Substring可能导致的问题
string fileName = Path.GetFileName(file);
Console.WriteLine($"[FILE] {fileName}");
}
}
catch
{
// 可能没有权限或其他错误
}
}
else
{
Console.WriteLine($"Directory not found: {path}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error listing files: {ex.Message}");
}
}
public void CreateFile(string path, string content = "")
{
string fullPath = GetFullPath(path);
try
{
// 创建或覆盖文件
File.WriteAllText(fullPath, content);
Console.WriteLine($"File created: {path}");
}
catch (Exception ex)
{
Console.WriteLine($"Error creating file: {ex.Message}");
}
}
public void WriteFile(string path, string content)
{
string fullPath = GetFullPath(path);
try
{
if (File.Exists(fullPath))
{
File.WriteAllText(fullPath, content);
Console.WriteLine($"File written: {path}");
}
else
{
Console.WriteLine($"File not found: {path}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error writing file: {ex.Message}");
}
}
public string ReadFile(string path)
{
string fullPath = GetFullPath(path);
try
{
if (File.Exists(fullPath))
{
return File.ReadAllText(fullPath);
}
else
{
Console.WriteLine($"File not found: {path}");
return "";
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading file: {ex.Message}");
return "";
}
}
public void DeleteFile(string path)
{
string fullPath = GetFullPath(path);
try
{
if (File.Exists(fullPath))
{
File.Delete(fullPath);
Console.WriteLine($"File deleted: {path}");
}
else
{
Console.WriteLine($"File not found: {path}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting file: {ex.Message}");
}
}
public void DeleteDirectory(string path)
{
string fullPath = GetFullPath(path);
try
{
if (Directory.Exists(fullPath))
{
try
{
// 尝试删除目录
Directory.Delete(fullPath);
Console.WriteLine($"Directory deleted: {path}");
}
catch
{
// 目录可能不为空
Console.WriteLine($"Directory not empty: {path}");
}
}
else
{
Console.WriteLine($"Directory not found: {path}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting directory: {ex.Message}");
}
}
private string GetFullPath(string path)
{
if (path.StartsWith(@"0:\"))
{
return path;
}
else if (path == ".")
{
return currentDirectory;
}
else if (path == "..")
{
if (currentDirectory == @"0:\")
{
return @"0:\";
}
else
{
int lastSlash = currentDirectory.LastIndexOf('\\');
if (lastSlash == 2) // 0:\
{
return @"0:\";
}
else
{
return currentDirectory.Substring(0, lastSlash);
}
}
}
else
{
if (currentDirectory == @"0:\")
{
return $@"0:\{path}";
}
else
{
return $@"{currentDirectory}\{path}";
}
}
}
}
}

100
Kernel.cs Normal file
View File

@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Sys = Cosmos.System;
namespace CMLeonOS
{
public class Kernel : Sys.Kernel
{
// 创建全局CosmosVFS实例
Sys.FileSystem.CosmosVFS fs = new Sys.FileSystem.CosmosVFS();
private Shell shell;
private UserSystem userSystem;
protected override void BeforeRun()
{
Console.Clear();
Console.WriteLine(@" ____ __ __ _ ___ ____ ");
Console.WriteLine(@" / ___| \/ | | ___ ___ _ __ / _ \/ ___| ");
Console.WriteLine(@" | | | |\/| | | / _ \/ _ \| '_ \| | | \___ \ ");
Console.WriteLine(@" | |___| | | | |__| __/ (_) | | | | |_| |___) |");
Console.WriteLine(@" \____|_| |_|_____\___|\___/|_| |_|__/|____/ ");
Console.WriteLine();
Console.WriteLine("CMLeonOS Test Project");
Console.WriteLine("By LeonOS 2 Developement Team");
// 注册VFS
try
{
Sys.FileSystem.VFS.VFSManager.RegisterVFS(fs);
Console.WriteLine("VFS initialized successfully");
// 显示可用空间
var available_space = fs.GetAvailableFreeSpace(@"0:\");
Console.WriteLine("Available Free Space: " + available_space + " bytes");
// 显示文件系统类型
var fs_type = fs.GetFileSystemType(@"0:\");
Console.WriteLine("File System Type: " + fs_type);
// 删除默认示例文件和文件夹
try
{
// 删除示例文件
if (System.IO.File.Exists(@"0:\example.txt"))
{
System.IO.File.Delete(@"0:\example.txt");
Console.WriteLine("Deleted example.txt");
}
// 删除示例文件夹
if (System.IO.Directory.Exists(@"0:\example"))
{
System.IO.Directory.Delete(@"0:\example", true);
Console.WriteLine("Deleted example directory");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting example files: {ex.Message}");
}
// 初始化用户系统
userSystem = new UserSystem();
// 第一次启动,设置管理员密码
if (!userSystem.IsPasswordSet)
{
userSystem.SetAdminPassword();
}
// 后续启动,需要登录
else
{
// 循环直到登录成功
while (!userSystem.Login())
{
// 登录失败,继续尝试
}
}
// 登录成功后初始化Shell
shell = new Shell();
}
catch (Exception ex)
{
Console.WriteLine($"Error initializing system: {ex.Message}");
}
}
protected override void Run()
{
if (shell != null)
{
shell.Run();
}
}
}
}

439
Shell.cs Normal file
View File

@@ -0,0 +1,439 @@
using System;
using System.Collections.Generic;
using Sys = Cosmos.System;
namespace CMLeonOS
{
public class Shell
{
private string prompt = "/";
private List<string> commandHistory = new List<string>();
private FileSystem fileSystem;
private UserSystem userSystem;
public Shell()
{
fileSystem = new FileSystem();
userSystem = new UserSystem();
}
public void Run()
{
while (true)
{
Console.Write(prompt);
var input = Console.ReadLine();
commandHistory.Add(input);
var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 0)
{
var command = parts[0].ToLower();
var args = parts.Length > 1 ? string.Join(" ", parts, 1, parts.Length - 1) : "";
ProcessCommand(command, args);
}
}
}
private void ProcessCommand(string command, string args)
{
switch (command)
{
case "echo":
ProcessEcho(args);
break;
case "clear":
case "cls":
Console.Clear();
break;
case "restart":
Console.WriteLine("Restarting system...");
Sys.Power.Reboot();
break;
case "shutdown":
Console.WriteLine("Shutting down system...");
Sys.Power.Shutdown();
break;
case "help":
Console.WriteLine("Available commands:");
Console.WriteLine(" echo <text> - Display text (supports \\n for newline)");
Console.WriteLine(" clear/cls - Clear the screen");
Console.WriteLine(" restart - Restart the system");
Console.WriteLine(" shutdown - Shutdown the system");
Console.WriteLine(" time - Display current time");
Console.WriteLine(" date - Display current date");
Console.WriteLine(" prompt <text> - Change command prompt");
Console.WriteLine(" calc <expr> - Simple calculator");
Console.WriteLine(" history - Show command history");
Console.WriteLine(" background <hex> - Change background color");
Console.WriteLine(" cuitest - Test CUI framework");
Console.WriteLine(" edit <file> - Simple code editor");
Console.WriteLine(" ls <dir> - List files and directories");
Console.WriteLine(" cd <dir> - Change directory");
Console.WriteLine(" pwd - Show current directory");
Console.WriteLine(" mkdir <dir> - Create directory");
Console.WriteLine(" rm <file> - Remove file");
Console.WriteLine(" rmdir <dir> - Remove directory");
Console.WriteLine(" cat <file> - Display file content");
Console.WriteLine(" echo <text> > <file> - Write text to file");
Console.WriteLine(" cpass - Change password");
Console.WriteLine(" version - Show OS version");
Console.WriteLine(" about - Show about information");
Console.WriteLine(" help - Show this help message");
break;
case "time":
Console.WriteLine(DateTime.Now.ToString());
break;
case "date":
Console.WriteLine(DateTime.Now.ToShortDateString());
break;
case "prompt":
ChangePrompt(args);
break;
case "calc":
Calculate(args);
break;
case "history":
ShowHistory();
break;
case "background":
ChangeBackground(args);
break;
case "cuitest":
TestCUI();
break;
case "edit":
EditFile(args);
break;
case "ls":
fileSystem.ListFiles(args);
break;
case "cd":
fileSystem.ChangeDirectory(args);
break;
case "pwd":
Console.WriteLine(fileSystem.CurrentDirectory);
break;
case "mkdir":
if (string.IsNullOrEmpty(args))
{
Console.WriteLine("Error: Please specify a directory name");
}
else
{
fileSystem.MakeDirectory(args);
}
break;
case "rm":
if (string.IsNullOrEmpty(args))
{
Console.WriteLine("Error: Please specify a file name");
}
else
{
fileSystem.DeleteFile(args);
}
break;
case "rmdir":
if (string.IsNullOrEmpty(args))
{
Console.WriteLine("Error: Please specify a directory name");
}
else
{
fileSystem.DeleteDirectory(args);
}
break;
case "cat":
if (string.IsNullOrEmpty(args))
{
Console.WriteLine("Error: Please specify a file name");
}
else
{
Console.WriteLine(fileSystem.ReadFile(args));
}
break;
case "version":
Console.WriteLine("CMLeonOS v1.0");
break;
case "about":
Console.WriteLine("CMLeonOS Test Project");
Console.WriteLine("By LeonOS 2 Developement Team");
Console.WriteLine("A simple operating system built with Cosmos");
break;
case "cpass":
userSystem.ChangePassword();
break;
default:
Console.WriteLine($"Unknown command: {command}");
break;
}
}
private void ProcessEcho(string args)
{
// 支持基本的转义字符
var processedArgs = args.Replace("\\n", "\n");
Console.WriteLine(processedArgs);
}
private void ChangePrompt(string args)
{
if (!string.IsNullOrEmpty(args))
{
prompt = args;
}
else
{
prompt = "/";
}
}
private void Calculate(string expression)
{
try
{
// 简单的计算器,只支持加减乘除
var parts = expression.Split(' ');
if (parts.Length == 3)
{
double num1 = double.Parse(parts[0]);
string op = parts[1];
double num2 = double.Parse(parts[2]);
double result = 0;
switch (op)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0)
{
result = num1 / num2;
}
else
{
Console.WriteLine("Error: Division by zero");
return;
}
break;
default:
Console.WriteLine("Error: Invalid operator. Use +, -, *, /");
return;
}
Console.WriteLine($"Result: {result}");
}
else
{
Console.WriteLine("Error: Invalid expression. Use format: calc <num> <op> <num>");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
private void ShowHistory()
{
for (int i = 0; i < commandHistory.Count; i++)
{
Console.WriteLine($"{i + 1}: {commandHistory[i]}");
}
}
private void ChangeBackground(string hexColor)
{
try
{
// 移除#前缀(如果有)
hexColor = hexColor.TrimStart('#');
// 解析16进制颜色代码
if (hexColor.Length == 6)
{
int r = Convert.ToInt32(hexColor.Substring(0, 2), 16);
int g = Convert.ToInt32(hexColor.Substring(2, 2), 16);
int b = Convert.ToInt32(hexColor.Substring(4, 2), 16);
// 简单的颜色映射将RGB值映射到最接近的ConsoleColor
ConsoleColor color = GetClosestConsoleColor(r, g, b);
Console.BackgroundColor = color;
Console.Clear();
Console.WriteLine($"Background color changed to: #{hexColor}");
}
else
{
Console.WriteLine("Error: Invalid hex color format. Use format: #RRGGBB or RRGGBB");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error changing background color: {ex.Message}");
}
}
private ConsoleColor GetClosestConsoleColor(int r, int g, int b)
{
// 简单的颜色映射逻辑
// 将RGB值映射到最接近的ConsoleColor
ConsoleColor[] colors = new ConsoleColor[]
{
ConsoleColor.Black,
ConsoleColor.DarkBlue,
ConsoleColor.DarkGreen,
ConsoleColor.DarkCyan,
ConsoleColor.DarkRed,
ConsoleColor.DarkMagenta,
ConsoleColor.DarkYellow,
ConsoleColor.Gray,
ConsoleColor.DarkGray,
ConsoleColor.Blue,
ConsoleColor.Green,
ConsoleColor.Cyan,
ConsoleColor.Red,
ConsoleColor.Magenta,
ConsoleColor.Yellow,
ConsoleColor.White
};
ConsoleColor closestColor = ConsoleColor.Black;
double smallestDistance = double.MaxValue;
foreach (ConsoleColor color in colors)
{
// 为每个ConsoleColor计算RGB值
// 这里使用简单的映射,实际效果可能不是很准确
int cr, cg, cb;
GetRGBFromConsoleColor(color, out cr, out cg, out cb);
// 计算欧几里得距离
double distance = Math.Sqrt(Math.Pow(r - cr, 2) + Math.Pow(g - cg, 2) + Math.Pow(b - cb, 2));
if (distance < smallestDistance)
{
smallestDistance = distance;
closestColor = color;
}
}
return closestColor;
}
private void GetRGBFromConsoleColor(ConsoleColor color, out int r, out int g, out int b)
{
// 简单的ConsoleColor到RGB的映射
switch (color)
{
case ConsoleColor.Black:
r = 0; g = 0; b = 0; break;
case ConsoleColor.DarkBlue:
r = 0; g = 0; b = 128; break;
case ConsoleColor.DarkGreen:
r = 0; g = 128; b = 0; break;
case ConsoleColor.DarkCyan:
r = 0; g = 128; b = 128; break;
case ConsoleColor.DarkRed:
r = 128; g = 0; b = 0; break;
case ConsoleColor.DarkMagenta:
r = 128; g = 0; b = 128; break;
case ConsoleColor.DarkYellow:
r = 128; g = 128; b = 0; break;
case ConsoleColor.Gray:
r = 192; g = 192; b = 192; break;
case ConsoleColor.DarkGray:
r = 128; g = 128; b = 128; break;
case ConsoleColor.Blue:
r = 0; g = 0; b = 255; break;
case ConsoleColor.Green:
r = 0; g = 255; b = 0; break;
case ConsoleColor.Cyan:
r = 0; g = 255; b = 255; break;
case ConsoleColor.Red:
r = 255; g = 0; b = 0; break;
case ConsoleColor.Magenta:
r = 255; g = 0; b = 255; break;
case ConsoleColor.Yellow:
r = 255; g = 255; b = 0; break;
case ConsoleColor.White:
r = 255; g = 255; b = 255; break;
default:
r = 0; g = 0; b = 0; break;
}
}
private void TestCUI()
{
// 创建CUI实例
var cui = new CUI("CMLeonOS CUI Test");
// 设置状态
cui.SetStatus("Testing CUI...");
// 渲染CUI界面只渲染顶栏
cui.Render();
// 显示测试消息
Console.WriteLine();
Console.WriteLine("CUI Framework Test");
Console.WriteLine("-------------------");
Console.WriteLine("Testing CUI functionality...");
Console.WriteLine();
// 测试不同类型的消息
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Success: Success message test");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: Error message test");
Console.ResetColor();
Console.WriteLine("Normal message test");
Console.WriteLine();
// 测试用户输入
Console.Write("Enter your name: ");
var input = Console.ReadLine();
Console.WriteLine();
Console.WriteLine($"Hello, {input}!");
Console.WriteLine();
// 渲染底栏
cui.RenderBottomBar();
// 等待用户按任意键返回
Console.WriteLine();
Console.WriteLine("Press any key to return to shell...");
Console.ReadKey(true);
// 重置控制台
Console.Clear();
}
private void EditFile(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
Console.WriteLine("Error: Please specify a file name");
return;
}
try
{
var editor = new Editor(fileName, fileSystem);
editor.Run();
}
catch (Exception ex)
{
Console.WriteLine($"Error starting editor: {ex.Message}");
}
}
}
}

172
UserSystem.cs Normal file
View File

@@ -0,0 +1,172 @@
using System;
using System.IO;
namespace CMLeonOS
{
public class UserSystem
{
private string adminPasswordFilePath = @"0:\admin_password.txt";
private bool isPasswordSet = false;
public UserSystem()
{
CheckPasswordStatus();
}
private void CheckPasswordStatus()
{
try
{
isPasswordSet = File.Exists(adminPasswordFilePath);
}
catch
{
isPasswordSet = false;
}
}
public bool IsPasswordSet
{
get { return isPasswordSet; }
}
public void SetAdminPassword()
{
Console.WriteLine("====================================");
Console.WriteLine(" First Time Setup");
Console.WriteLine("====================================");
Console.WriteLine("Please set a password for admin user:");
string password = ReadPassword();
Console.WriteLine("Please confirm your password:");
string confirmPassword = ReadPassword();
if (password == confirmPassword)
{
try
{
// 简单存储密码(实际应用中应使用加密)
File.WriteAllText(adminPasswordFilePath, password);
Console.WriteLine("Password set successfully!");
isPasswordSet = true;
}
catch (Exception ex)
{
Console.WriteLine($"Error setting password: {ex.Message}");
}
}
else
{
Console.WriteLine("Passwords do not match. Please try again.");
SetAdminPassword();
}
}
public bool Login()
{
Console.WriteLine("====================================");
Console.WriteLine(" System Login");
Console.WriteLine("====================================");
Console.WriteLine("Username: admin");
Console.WriteLine("Password:");
string password = ReadPassword();
try
{
string storedPassword = File.ReadAllText(adminPasswordFilePath);
if (password == storedPassword)
{
Console.WriteLine("Login successful!");
return true;
}
else
{
Console.WriteLine("Invalid password. Please try again.");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error during login: {ex.Message}");
return false;
}
}
private string ReadPassword()
{
string password = "";
while (true)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else if (keyInfo.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password = password.Substring(0, password.Length - 1);
// 简化退格处理只修改password字符串
// 在Cosmos中Console.Write("\b \b")可能不被支持
}
}
else
{
password += keyInfo.KeyChar;
Console.Write("*");
}
}
return password;
}
public bool ChangePassword()
{
Console.WriteLine("====================================");
Console.WriteLine(" Change Password");
Console.WriteLine("====================================");
// 验证当前密码
Console.WriteLine("Please enter your current password:");
string currentPassword = ReadPassword();
try
{
string storedPassword = File.ReadAllText(adminPasswordFilePath);
if (currentPassword != storedPassword)
{
Console.WriteLine("Current password is incorrect.");
return false;
}
// 设置新密码
Console.WriteLine("Please enter your new password:");
string newPassword = ReadPassword();
Console.WriteLine("Please confirm your new password:");
string confirmPassword = ReadPassword();
if (newPassword == confirmPassword)
{
// 存储新密码
File.WriteAllText(adminPasswordFilePath, newPassword);
Console.WriteLine("Password changed successfully!");
return true;
}
else
{
Console.WriteLine("New passwords do not match.");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error changing password: {ex.Message}");
return false;
}
}
}
}

6
global.json Normal file
View File

@@ -0,0 +1,6 @@
{
"sdk": {
"version": "6.0.419",
"rollForward": "latestMinor"
}
}