Reduce code duplication for gui and cli input/command handling.

This commit is contained in:
UnknownShadow200 2016-06-07 09:24:45 +10:00
parent 3178fc14ee
commit e69600fd95
6 changed files with 109 additions and 145 deletions

74
GUI/Handlers.cs Normal file
View File

@ -0,0 +1,74 @@
/*
Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCGalaxy)
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.opensource.org/licenses/ecl2.php
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.Threading;
namespace MCGalaxy.Gui {
public static class Handlers {
public static void HandleChat(string text, Action<string> output) {
if (text != null) text = text.Trim();
if (String.IsNullOrEmpty(text)) return;
if (Chat.HandleModes(null, text)) return;
Player.GlobalMessage("Console [&a" + Server.ZallState + Server.DefaultColor + "]:&f " + text);
Server.IRC.Say("Console [&a" + Server.ZallState + "%S]: " + text);
Server.s.Log("(Console): " + text, true);
output("<CONSOLE>: " + text);
}
public static Thread HandleCommand(string text, Action<string> output) {
if (text != null) text = text.Trim();
if (String.IsNullOrEmpty(text)) {
output("CONSOLE: Whitespace commands are not allowed."); return null;
}
if (text[0] == '/' && text.Length > 1)
text = text.Substring(1);
int sep = text.IndexOf(' ');
string name = "", args = "";
if (sep >= 0) {
name = text.Substring(0, sep);
args = text.Substring(sep + 1);
} else {
name = text;
}
if (Server.Check(name, args)) { Server.cancelcommand = false; return null; }
Command cmd = Command.all.Find(name);
if (cmd == null) { output("CONSOLE: No such command."); return null; }
Thread thread = new Thread(
() =>
{
try {
cmd.Use(null, args);
output("CONSOLE: USED /" + text);
Server.s.Log("(Console) used /" + text, true);
} catch (Exception ex) {
Server.ErrorLog(ex);
output("CONSOLE: Failed command");
}
});
thread.Name = "MCG_ConsoleCommand";
thread.IsBackground = true;
thread.Start();
return thread;
}
}
}

View File

@ -35,8 +35,7 @@ namespace MCGalaxy.Gui
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public static void GlobalExHandler(object sender, UnhandledExceptionEventArgs e)
{
public static void GlobalExHandler(object sender, UnhandledExceptionEventArgs e) {
Exception ex = (Exception)e.ExceptionObject;
Server.ErrorLog(ex);
Thread.Sleep(500);
@ -45,8 +44,7 @@ namespace MCGalaxy.Gui
App.ExitProgram(true);
}
public static void ThreadExHandler(object sender, ThreadExceptionEventArgs e)
{
public static void ThreadExHandler(object sender, ThreadExceptionEventArgs e) {
Exception ex = e.Exception;
Server.ErrorLog(ex);
Thread.Sleep(500);
@ -57,18 +55,17 @@ namespace MCGalaxy.Gui
static bool useConsole, useHighQualityGui;
[STAThread]
public static void Main(string[] args)
{
public static void Main(string[] args) {
startTime = DateTime.Now;
if (Process.GetProcessesByName("MCGalaxy").Length != 1)
{
foreach (Process pr in Process.GetProcessesByName("MCGalaxy"))
{
if (pr.MainModule.BaseAddress == Process.GetCurrentProcess().MainModule.BaseAddress)
if (pr.Id != Process.GetCurrentProcess().Id)
pr.Kill();
Process[] duplicates = Process.GetProcessesByName("MCGalaxy");
if (duplicates.Length != 1) {
Process proc = Process.GetCurrentProcess();
foreach (Process pr in duplicates) {
if (pr.MainModule.BaseAddress == proc.MainModule.BaseAddress)
if (pr.Id != proc.Id) pr.Kill();
}
}
Logger.Init();
AppDomain.CurrentDomain.UnhandledException += GlobalExHandler;
Application.ThreadException += ThreadExHandler;
@ -133,60 +130,16 @@ namespace MCGalaxy.Gui
Console.WriteLine();
}
public static void handleComm()
{
string s, msg;
while (true)
{
try
{
string sentCmd = String.Empty, sentMsg = String.Empty;
s = Console.ReadLine().Trim(); // Make sure we have no whitespace!
if (s.Length < 1) continue;
if (s[0] == '/') s = s.Remove(0, 1);
else goto talk;
if (s.IndexOf(' ') != -1)
{
sentCmd = s.Substring(0, s.IndexOf(' '));
sentMsg = s.Substring(s.IndexOf(' ') + 1);
}
else if (s != String.Empty) sentCmd = s;
else goto talk;
try
{
if (Server.Check(sentCmd, sentMsg)) { Server.cancelcommand = false; continue; }
Command cmd = Command.all.Find(sentCmd);
if (cmd != null)
{
cmd.Use(null, sentMsg);
Console.WriteLine("CONSOLE: USED /" + sentCmd + " " + sentMsg);
Server.s.Log("(Console) used /" + sentCmd + " " + sentMsg, true);
if (sentCmd.ToLower() != "restart")
continue;
break;
}
else
{
Console.WriteLine("CONSOLE: Unknown command.");
continue;
}
}
catch (Exception e)
{
Server.ErrorLog(e);
Console.WriteLine("CONSOLE: Failed command.");
continue;
}
talk:
if (!Chat.HandleModes(null, s)) {
msg = String.Format("{0}Console [&a{1}{0}]: &f{2}", Server.DefaultColor, Server.ZallState, s);
Player.GlobalMessage(msg);
Server.IRC.Say("Console [&a" + Server.ZallState + "%S]: " + s);
WriteToConsole(msg);
Server.s.Log("(Console): " + msg, true);
public static void handleComm() {
while (true) {
try {
string s = Console.ReadLine().Trim(); // Make sure we have no whitespace!
if (s.Length > 0 && s[0] == '/') {
s = s.Remove(0, 1);
Thread t = Handlers.HandleCommand(s, Console.WriteLine);
if (s.CaselessEq("restart")) { t.Join(); break; }
} else {
Handlers.HandleChat(s, WriteToConsole);
}
} catch (Exception ex) {
Server.ErrorLog(ex);

View File

@ -422,87 +422,23 @@ namespace MCGalaxy.Gui
}
}
private void txtInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
string text = txtInput.Text.Trim();
if (String.IsNullOrEmpty(text)) return;
if (MCGalaxy.Chat.HandleModes(null, text))
return;
Player.GlobalMessage("Console [&a" + Server.ZallState + Server.DefaultColor + "]:&f " + text);
Server.IRC.Say("Console [&a" + Server.ZallState + "%S]: " + text);
WriteLine("<CONSOLE> " + text);
Server.s.Log("(Console): " + text, true);
txtInput.Clear();
}
}
private void txtCommands_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Enter)
return;
string sentCmd, sentMsg = "";
void txtInput_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode != Keys.Enter) return;
e.Handled = true;
e.SuppressKeyPress = true;
Handlers.HandleChat(txtInput.Text, WriteLine);
txtInput.Clear();
}
if (txtCommands.Text == null || txtCommands.Text.Trim() == "")
{
newCommand("CONSOLE: Whitespace commands are not allowed.");
txtCommands.Clear();
return;
}
if (txtCommands.Text[0] == '/' && txtCommands.Text.Length > 1)
txtCommands.Text = txtCommands.Text.Substring(1);
if (txtCommands.Text.IndexOf(' ') != -1)
{
sentCmd = txtCommands.Text.Split(' ')[0];
sentMsg = txtCommands.Text.Substring(txtCommands.Text.IndexOf(' ') + 1);
}
else if (txtCommands.Text != "")
{
sentCmd = txtCommands.Text;
}
else
{
return;
}
Thread cmdThread = new Thread(() =>
{
try
{
Command commandcmd = Command.all.Find(sentCmd);
if (commandcmd == null)
{
Server.s.Log("No such command!");
return;
}
commandcmd.Use(null, sentMsg);
newCommand("CONSOLE: USED /" + sentCmd + " " + sentMsg);
Server.s.Log("(Console) used /" + sentCmd + " " + sentMsg, true);
}
catch (Exception ex)
{
Server.ErrorLog(ex);
newCommand("CONSOLE: Failed command.");
}
});
cmdThread.Name = "MCG_ConsoleCommand";
cmdThread.Start();
void txtCommands_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode != Keys.Enter) return;
e.Handled = true;
e.SuppressKeyPress = true;
Handlers.HandleCommand(txtCommands.Text, newCommand);
txtCommands.Clear();
}
private void btnClose_Click_1(object sender, EventArgs e)
{
Close();
}
void btnClose_Click_1(object sender, EventArgs e) { Close(); }
public void newCommand(string p)
{

View File

@ -1332,6 +1332,7 @@ return;
}
}));
thread.Name = "MCG_Command";
thread.IsBackground = true;
thread.Start();
}
}

View File

@ -49,6 +49,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="GUI\Formatter.cs" />
<Compile Include="GUI\Handlers.cs" />
<Compile Include="GUI\LevelSettings.cs" />
<Compile Include="GUI\PlayerCollection.cs" />
<Compile Include="GUI\Program.cs" />

View File

@ -205,9 +205,8 @@ namespace MCGalaxy.Gui
} else {
saveAll(false);
Application.Exit();
if (usingConsole) {
Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
}
if (usingConsole)
Process.GetCurrentProcess().Kill();
Environment.Exit(0);
}
})).Start();