diff --git a/FunGame.Desktop/Controller/LoginController.cs b/FunGame.Desktop/Controller/LoginController.cs index 1feeae9..cb48124 100644 --- a/FunGame.Desktop/Controller/LoginController.cs +++ b/FunGame.Desktop/Controller/LoginController.cs @@ -1,50 +1,193 @@ -using Milimoe.FunGame.Core.Library.Common.Event; -using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.Model; +using Milimoe.FunGame.Core.Api.Transmittal; +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Entity; +using Milimoe.FunGame.Core.Library.Common.Event; +using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Exception; -using Milimoe.FunGame.Core.Controller; +using Milimoe.FunGame.Core.Library.SQLScript.Common; +using Milimoe.FunGame.Core.Library.SQLScript.Entity; +using Milimoe.FunGame.Desktop.Library; +using Milimoe.FunGame.Desktop.Library.Component; +using Milimoe.FunGame.Desktop.UI; namespace Milimoe.FunGame.Desktop.Controller { - public class LoginController : SocketHandlerController + public class LoginController { - private readonly LoginModel LoginModel; + private readonly GeneralForm UIForm; + private readonly DataRequest LoginRequest; + private readonly DataRequest ForgetPasswordRequest; + private readonly DataRequest UpdatePasswordRequest; - public LoginController() + public LoginController(GeneralForm form) { - LoginModel = new LoginModel(); + UIForm = form; + LoginRequest = RunTime.NewLongRunningDataRequest(DataRequestType.RunTime_Login); + ForgetPasswordRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Login_GetFindPasswordVerifyCode); + UpdatePasswordRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Login_UpdatePassword); } - public override void Dispose() + public void Dispose() { - LoginModel.Dispose(); + LoginRequest.Dispose(); + ForgetPasswordRequest.Dispose(); + UpdatePasswordRequest.Dispose(); } - public static async Task LoginAccount(params object[]? objs) + public async Task LoginAccountAsync(string username, string password, string autokey = "") { bool result = false; + string msg = ""; + LoginEventArgs args = new(username, password, autokey); try { - LoginEventArgs LoginEventArgs = new(objs); - if (RunTime.Login?.OnBeforeLoginEvent(LoginEventArgs) == Core.Library.Constant.EventResult.Fail) return false; - - result = await LoginModel.LoginAccountAsync(objs); - - if (result) RunTime.Login?.OnSucceedLoginEvent(LoginEventArgs); - else RunTime.Login?.OnFailedLoginEvent(LoginEventArgs); - RunTime.Login?.OnAfterLoginEvent(LoginEventArgs); + if (OnBeforeLoginEvent(args)) + { + LoginRequest.AddRequestData("username", username); + LoginRequest.AddRequestData("password", password); + LoginRequest.AddRequestData("autokey", autokey); + await LoginRequest.SendRequestAsync(); + if (LoginRequest.Result == RequestResult.Success) + { + Guid key = LoginRequest.GetResult("checkloginkey"); + msg = LoginRequest.GetResult("msg") ?? ""; + if (msg != "") + { + UIForm.ShowMessage(ShowMessageType.Error, msg); + } + else if (key != Guid.Empty) + { + LoginRequest.AddRequestData("checkloginkey", key); + await LoginRequest.SendRequestAsync(); + if (LoginRequest.Result == RequestResult.Success) + { + msg = LoginRequest.GetResult("msg") ?? ""; + if (msg != "") + { + UIForm.ShowMessage(ShowMessageType.Error, msg); + } + else + { + User user = LoginRequest.GetResult("user") ?? Factory.GetUser(); + if (user.Id != 0) + { + // 创建User对象并返回到Main + RunTime.Main?.UpdateUI(MainInvokeType.SetUser, user); + result = true; + } + } + } + } + } + } } catch (Exception e) { RunTime.WritelnSystemInfo(e.GetErrorInfo()); } + if (!result && msg == "") + { + UIForm.ShowMessage(ShowMessageType.Error, "登录失败!"); + } + + OnAfterLoginEvent(result, args); + return result; } - public static string ForgetPassword_CheckVerifyCode(string username, string email, string verifycode = "") => LoginModel.ForgetPassword_CheckVerifyCode(username, email, verifycode); + public async Task ForgetPassword_CheckVerifyCodeAsync(string username, string email, string verifycode) + { + string msg = "无法找回您的密码,请稍后再试。"; - public static string ForgetPassword_UpdatePassword(string username, string password) => LoginModel.ForgetPassword_UpdatePassword(username, password); + try + { + ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_Username, username); + ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_Email, email); + if (verifycode.Trim() == "") + { + // 未发送verifycode,说明需要系统生成一个验证码 + ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, ""); + await ForgetPasswordRequest.SendRequestAsync(); + if (ForgetPasswordRequest.Result == RequestResult.Success) + { + msg = ForgetPasswordRequest.GetResult("msg") ?? msg; + } + else RunTime.WritelnSystemInfo(ForgetPasswordRequest.Error); + } + else + { + // 发送verifycode,需要验证 + ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, verifycode); + await ForgetPasswordRequest.SendRequestAsync(); + if (ForgetPasswordRequest.Result == RequestResult.Success) + { + msg = ForgetPasswordRequest.GetResult("msg") ?? msg; + } + else RunTime.WritelnSystemInfo(ForgetPasswordRequest.Error); + } + } + catch (Exception e) + { + RunTime.WritelnSystemInfo(e.GetErrorInfo()); + } + + return msg; + } + + public async Task ForgetPassword_UpdatePasswordAsync(string username, string password) + { + string msg = "无法更新您的密码,请稍后再试。"; + + try + { + UpdatePasswordRequest.AddRequestData(UserQuery.Column_Username, username); + UpdatePasswordRequest.AddRequestData(UserQuery.Column_Password, password.Encrypt(username)); + await UpdatePasswordRequest.SendRequestAsync(); + if (UpdatePasswordRequest.Result == RequestResult.Success) + { + msg = UpdatePasswordRequest.GetResult("msg") ?? msg; + } + else RunTime.WritelnSystemInfo(UpdatePasswordRequest.Error); + } + catch (Exception e) + { + RunTime.WritelnSystemInfo(e.GetErrorInfo()); + } + + return msg; + } + + private bool OnBeforeLoginEvent(LoginEventArgs LoginEventArgs) + { + if (UIForm.GetType() == typeof(Login)) + { + return ((Login)UIForm).OnBeforeLoginEvent(LoginEventArgs) == EventResult.Success; + } + return true; + } + + private void OnAfterLoginEvent(bool result, LoginEventArgs LoginEventArgs) + { + try + { + if (UIForm.GetType() == typeof(Login)) + { + Login login = (Login)UIForm; + if (result) login.OnSucceedLoginEvent(LoginEventArgs); + else login.OnFailedLoginEvent(LoginEventArgs); + login.OnAfterLoginEvent(LoginEventArgs); + } + else if (UIForm.GetType() == typeof(Main)) + { + if (result) ((Main)UIForm).OnSucceedLoginEvent(LoginEventArgs); + } + } + catch (Exception e) + { + RunTime.WritelnSystemInfo(e.GetErrorInfo()); + } + } } } diff --git a/FunGame.Desktop/Controller/MainController.cs b/FunGame.Desktop/Controller/MainController.cs index 45ca865..7818751 100644 --- a/FunGame.Desktop/Controller/MainController.cs +++ b/FunGame.Desktop/Controller/MainController.cs @@ -1,168 +1,278 @@ -using Milimoe.FunGame.Core.Controller; +using Milimoe.FunGame.Core.Api.Transmittal; +using Milimoe.FunGame.Core.Controller; using Milimoe.FunGame.Core.Entity; -using Milimoe.FunGame.Core.Library.Common.Event; +using Milimoe.FunGame.Core.Library.Common.Network; using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Exception; +using Milimoe.FunGame.Core.Model; using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.Model; using Milimoe.FunGame.Desktop.UI; namespace Milimoe.FunGame.Desktop.Controller { public class MainController : SocketHandlerController { - private MainModel MainModel { get; } - private Main Main { get; } + private readonly Main Main; + private readonly Session Usercfg = RunTime.Session; + private readonly DataRequest ChatRequest; + private readonly DataRequest CreateRoomRequest; + private readonly DataRequest GetRoomPlayerCountRequest; + private readonly DataRequest UpdateRoomRequest; + private readonly DataRequest IntoRoomRequest; + private readonly DataRequest QuitRoomRequest; - private readonly Core.Model.Session Usercfg = RunTime.Session; - - public MainController(Main Main) + public MainController(Main main) : base(RunTime.Socket) { - this.Main = Main; - MainModel = new MainModel(Main); + Main = main; + ChatRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_Chat); + CreateRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_CreateRoom); + GetRoomPlayerCountRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Room_GetRoomPlayerCount); + UpdateRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_UpdateRoom); + IntoRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_IntoRoom); + QuitRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_QuitRoom); + Disposed += MainController_Disposed; } - public override void Dispose() - { - MainModel.Dispose(); - } + #region 公开方法 - public async Task LogOut() + public async Task LogOutAsync() { - bool result = false; - try { - GeneralEventArgs EventArgs = new(); - if (Main.OnBeforeLogoutEvent(EventArgs) == EventResult.Fail) return result; - - if (Usercfg.LoginUser.Id == 0) return result; - - if (Usercfg.InRoom.Roomid != "-1") + // 需要当时登录给的Key发回去,确定是账号本人在操作才允许登出 + if (Usercfg.LoginKey != Guid.Empty) { - string roomid = Usercfg.InRoom.Roomid; - bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser?.Id; - await MainModel.QuitRoom(roomid, isMaster); + DataRequest request = RunTime.NewDataRequest(DataRequestType.RunTime_Logout); + request.AddRequestData("loginkey", Usercfg.LoginKey); + await request.SendRequestAsync(); + if (request.Result == RequestResult.Success) + { + string msg = ""; + Guid key = Guid.Empty; + msg = request.GetResult("msg") ?? ""; + key = request.GetResult("key"); + if (key == Usercfg.LoginKey) + { + Usercfg.LoginKey = Guid.Empty; + Main.UpdateUI(MainInvokeType.LogOut, msg ?? ""); + return true; + } + } } - - result = await MainModel.LogOut(); - - if (result) Main.OnSucceedLogoutEvent(EventArgs); - else Main.OnFailedLogoutEvent(EventArgs); - Main.OnAfterLogoutEvent(EventArgs); + throw new CanNotLogOutException(); } catch (Exception e) { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); + Main.ShowMessage(ShowMessageType.Error, "无法登出您的账号,请联系服务器管理员。", "登出失败", 5); + Main.GetMessage(e.GetErrorInfo()); } - - return result; + return false; } - public async Task UpdateRoom() + public async Task IntoRoomAsync(Room room) { - return await MainModel.UpdateRoom(); - } - - public async Task IntoRoom(Room room) - { - bool result = false; - try { - RoomEventArgs EventArgs = new(room); - if (Main.OnBeforeIntoRoomEvent(EventArgs) == EventResult.Fail) return result; - - result = await MainModel.IntoRoom(room); - - if (result) Main.OnSucceedIntoRoomEvent(EventArgs); - else Main.OnFailedIntoRoomEvent(EventArgs); - Main.OnAfterIntoRoomEvent(EventArgs); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - } - - return result; - } - - public async Task QuitRoom(Room room, bool isMaster) - { - bool result = false; - string roomid = room.Roomid; - - try - { - RoomEventArgs EventArgs = new(room); - if (Main.OnBeforeQuitRoomEvent(EventArgs) == EventResult.Fail) return result; - - result = await MainModel.QuitRoom(roomid, isMaster); - - if (result) Main.OnSucceedQuitRoomEvent(EventArgs); - else Main.OnFailedQuitRoomEvent(EventArgs); - Main.OnAfterQuitRoomEvent(EventArgs); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - } - - return result; - } - - public async Task CreateRoom(string RoomType, string Password = "") - { - string result = ""; - - try - { - RoomEventArgs EventArgs = new(RoomType, Password); - if (Main.OnBeforeCreateRoomEvent(EventArgs) == EventResult.Fail) return result; - - result = await MainModel.CreateRoom(RoomType, Password); - - if (result.Trim() != "") Main.OnSucceedCreateRoomEvent(EventArgs); - else Main.OnFailedCreateRoomEvent(EventArgs); - Main.OnAfterCreateRoomEvent(EventArgs); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - } - - return result; - } - - public async Task GetRoomPlayerCount(string roomid) - { - return await MainModel.GetRoomPlayerCount(roomid); - } - - public bool Chat(string msg) - { - bool result = false; - - try - { - SendTalkEventArgs EventArgs = new(msg); - if (Main.OnBeforeSendTalkEvent(EventArgs) == EventResult.Fail) return result; - - if (msg.Trim() != "") + string rid = room.Roomid; + IntoRoomRequest.AddRequestData("room", rid); + await IntoRoomRequest.SendRequestAsync(); + if (IntoRoomRequest.Result == RequestResult.Success) { - result = MainModel.Chat(msg); + string roomid = IntoRoomRequest.GetResult("roomid") ?? ""; + if (rid == roomid) + { + // 先确认是否是加入的房间,防止服务端返回错误的房间 + if (roomid.Trim() != "" && roomid == "-1") + { + Main.GetMessage($"已连接至公共聊天室。"); + } + else + { + Usercfg.InRoom = room; + } + return true; + } } - - if (result) Main.OnSucceedSendTalkEvent(EventArgs); - else Main.OnFailedSendTalkEvent(EventArgs); - Main.OnAfterSendTalkEvent(EventArgs); + throw new CanNotIntoRoomException(); } catch (Exception e) { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); + Main.GetMessage(e.GetErrorInfo()); + return false; } - + } + + public async Task UpdateRoomAsync() + { + bool result = false; + + try + { + List list = new(); + await UpdateRoomRequest.SendRequestAsync(); + if (UpdateRoomRequest.Result == RequestResult.Success) + { + list = UpdateRoomRequest.GetResult>("roomid") ?? new(); + Main.UpdateUI(MainInvokeType.UpdateRoom, list); + } + else throw new CanNotIntoRoomException(); + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo()); + } + return result; } + + public async Task GetRoomPlayerCountAsync(string roomid) + { + try + { + GetRoomPlayerCountRequest.AddRequestData("roomid", roomid); + await GetRoomPlayerCountRequest.SendRequestAsync(); + return GetRoomPlayerCountRequest.GetResult("count"); + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo()); + return 0; + } + } + + public async Task QuitRoomAsync(string roomid, bool isMaster) + { + bool result = false; + + try + { + QuitRoomRequest.AddRequestData("roomid", roomid); + QuitRoomRequest.AddRequestData("isMaster", isMaster); + await QuitRoomRequest.SendRequestAsync(); + if (QuitRoomRequest.Result == RequestResult.Success) + { + result = QuitRoomRequest.GetResult("result"); + if (result) + { + Usercfg.InRoom = General.HallInstance; + return result; + } + } + throw new CanNotIntoRoomException(); + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo()); + return result; + } + } + + public async Task CreateRoomAsync(string RoomType, string Password = "") + { + string roomid = "-1"; + + try + { + CreateRoomRequest.AddRequestData("roomtype", RoomType); + CreateRoomRequest.AddRequestData("user", Usercfg.LoginUser); + CreateRoomRequest.AddRequestData("password", Password); + await CreateRoomRequest.SendRequestAsync(); + if (CreateRoomRequest.Result == RequestResult.Success) + { + roomid = CreateRoomRequest.GetResult("roomid") ?? "-1"; + } + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo()); + } + + return roomid; + } + + public async Task ChatAsync(string msg) + { + try + { + ChatRequest.AddRequestData("msg", msg); + await ChatRequest.SendRequestAsync(); + if (ChatRequest.Result == RequestResult.Success) + { + return true; + } + throw new CanNotSendTalkException(); + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo()); + return false; + } + } + + public override void SocketHandler(SocketObject SocketObject) + { + try + { + if (SocketObject.SocketType == SocketMessageType.HeartBeat) + { + // 心跳包单独处理 + if ((RunTime.Socket?.Connected ?? false) && Usercfg.LoginUser.Id != 0) + Main.UpdateUI(MainInvokeType.SetGreenAndPing); + } + else if (SocketObject.SocketType == SocketMessageType.ForceLogout) + { + // 服务器强制下线登录 + Guid key = Guid.Empty; + string msg = ""; + if (SocketObject.Length > 0) key = SocketObject.GetParam(0); + if (SocketObject.Length > 1) msg = SocketObject.GetParam(1) ?? ""; + if (key == Usercfg.LoginKey) + { + Usercfg.LoginKey = Guid.Empty; + Main.UpdateUI(MainInvokeType.LogOut, msg ?? ""); + } + } + else if (SocketObject.SocketType == SocketMessageType.Chat) + { + // 收到房间聊天信息 + string user = "", msg = ""; + if (SocketObject.Length > 0) user = SocketObject.GetParam(0) ?? ""; + if (SocketObject.Length > 1) msg = SocketObject.GetParam(1) ?? ""; + if (user != Usercfg.LoginUserName) + { + Main.GetMessage(msg, TimeType.None); + } + } + else if (SocketObject.SocketType == SocketMessageType.UpdateRoomMaster) + { + // 收到房间更换房主的信息 + User user = General.UnknownUserInstance; + Room room = General.HallInstance; + if (SocketObject.Length > 0) user = SocketObject.GetParam(0) ?? General.UnknownUserInstance; + if (SocketObject.Length > 1) room = SocketObject.GetParam(1) ?? General.HallInstance; + if (room.Roomid != "-1" && room.Roomid == Usercfg.InRoom.Roomid) Main.UpdateUI(MainInvokeType.UpdateRoomMaster, room); + } + } + catch (Exception e) + { + RunTime.Controller?.Error(e); + } + } + + #endregion + + #region 私有方法 + + private void MainController_Disposed() + { + ChatRequest.Dispose(); + CreateRoomRequest.Dispose(); + GetRoomPlayerCountRequest.Dispose(); + UpdateRoomRequest.Dispose(); + IntoRoomRequest.Dispose(); + QuitRoomRequest.Dispose(); + } + + #endregion } } diff --git a/FunGame.Desktop/Controller/RegisterController.cs b/FunGame.Desktop/Controller/RegisterController.cs index 904aa51..eb1f0b8 100644 --- a/FunGame.Desktop/Controller/RegisterController.cs +++ b/FunGame.Desktop/Controller/RegisterController.cs @@ -1,39 +1,60 @@ using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.Model; using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Desktop.UI; using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Common.Event; -using Milimoe.FunGame.Core.Controller; +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Desktop.Library.Component; +using Milimoe.FunGame.Core.Api.Transmittal; namespace Milimoe.FunGame.Desktop.Controller { - public class RegisterController : SocketHandlerController + public class RegisterController { private readonly Register Register; - private readonly RegisterModel RegModel; public RegisterController(Register reg) { Register = reg; - RegModel = new RegisterModel(); } - public override void Dispose() - { - RegModel.Dispose(); - } - - public async Task Reg(params object[]? objs) + public async Task RegAsync(string username = "", string password = "", string email = "") { bool result = false; try { - RegisterEventArgs RegEventArgs = new (objs); + password = password.Encrypt(username); + RegisterEventArgs RegEventArgs = new(username, password, email); if (Register.OnBeforeRegEvent(RegEventArgs) == EventResult.Fail) return false; - result = await RegModel.Reg(objs); + DataRequest request = RunTime.NewDataRequest(DataRequestType.Reg_GetRegVerifyCode); + request.AddRequestData("username", username); + request.AddRequestData("password", password); + request.AddRequestData("email", email); + request.AddRequestData("verifycode", ""); + await request.SendRequestAsync(); + if (request.Result == RequestResult.Success) + { + RegInvokeType InvokeType = request.GetResult("type"); + while (true) + { + string verifycode = ShowMessage.InputMessageCancel("请输入注册邮件中的6位数字验证码", "注册验证码", out MessageResult cancel); + if (cancel != MessageResult.Cancel) + { + request.AddRequestData("verifycode", verifycode); + await request.SendRequestAsync(); + if (request.Result == RequestResult.Success) + { + bool success = request.GetResult("success"); + string msg = request.GetResult("msg") ?? ""; + if (msg != "") ShowMessage.Message(msg, "注册结果"); + if (success) return success; + } + } + else break; + } + } if (result) Register.OnSucceedRegEvent(RegEventArgs); else Register.OnFailedRegEvent(RegEventArgs); diff --git a/FunGame.Desktop/Controller/RunTimeController.cs b/FunGame.Desktop/Controller/RunTimeController.cs index e2e0150..1420fb2 100644 --- a/FunGame.Desktop/Controller/RunTimeController.cs +++ b/FunGame.Desktop/Controller/RunTimeController.cs @@ -1,104 +1,28 @@ using Milimoe.FunGame.Core.Api.Transmittal; using Milimoe.FunGame.Core.Library.Common.Event; +using Milimoe.FunGame.Core.Library.Common.Network; using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.Model; using Milimoe.FunGame.Desktop.UI; namespace Milimoe.FunGame.Desktop.Controller { public class RunTimeController : Core.Controller.RunTimeController { - public override bool Connected => RunTimeModel.Connected; + private readonly Main Main; + private readonly Core.Model.Session Usercfg = RunTime.Session; + private readonly LoginController LoginController; - private RunTimeModel RunTimeModel { get; } - private Main Main { get; } - - public RunTimeController(Main Main) + public RunTimeController(Main main) { - this.Main = Main; - RunTimeModel = new RunTimeModel(Main); + Main = main; + LoginController = new(Main); } - public override async Task Connect() + public void Dispose() { - ConnectResult result = ConnectResult.ConnectFailed; - - try - { - ConnectEventArgs EventArgs = new(RunTime.Session.Server_IP, RunTime.Session.Server_Port); - if (Main.OnBeforeConnectEvent(EventArgs) == EventResult.Fail) return ConnectResult.ConnectFailed; - - result = await RunTimeModel.Connect(); - - if (result == ConnectResult.Success) Main.OnSucceedConnectEvent(EventArgs); - else Main.OnFailedConnectEvent(EventArgs); - Main.OnAfterConnectEvent(EventArgs); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - } - - return result; - } - - public override bool Disconnect() - { - bool result = false; - - try - { - if (Main.OnBeforeDisconnectEvent(new GeneralEventArgs()) == EventResult.Fail) return result; - - result = RunTimeModel.Disconnect(); - - if (result) Main.OnSucceedDisconnectEvent(new GeneralEventArgs()); - else Main.OnFailedDisconnectEvent(new GeneralEventArgs()); - Main.OnAfterDisconnectEvent(new GeneralEventArgs()); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - } - - return result; - } - - public override bool Close(Exception? e = null) - { - bool result; - - if (Connected) Disconnect(); - - if (e != null) - { - RunTimeModel.Error(e); - result = true; - } - else result = RunTimeModel.Close(); - - return result; - } - - public override bool Error(Exception e) - { - return Close(e); - } - - public override async Task AutoLogin(string Username, string Password, string AutoKey) - { - try - { - LoginController LoginController = new(); - await LoginController.LoginAccount(Username, Password, AutoKey); - LoginController.Dispose(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - } + LoginController.Dispose(); } public override void WritelnSystemInfo(string msg) @@ -106,10 +30,152 @@ namespace Milimoe.FunGame.Desktop.Controller Main?.GetMessage(msg); } - public override DataRequest NewDataRequest(DataRequestType RequestType) + public override void Error(Exception e) { - DataRequest? request = RunTimeModel?.NewDataRequest(RequestType); - return request is null ? throw new ConnectFailedException() : request; + Main.GetMessage(e.GetErrorInfo(), TimeType.None); + Main.UpdateUI(MainInvokeType.Disconnected); + Main.OnFailedConnectEvent(new ConnectEventArgs(RunTime.Session.Server_IP, RunTime.Session.Server_Port)); + Close(); + } + + public override ConnectResult Connect() + { + if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0) + { + (RunTime.Session.Server_IP, RunTime.Session.Server_Port) = GetServerAddress(); + if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0) + { + Main.ShowMessage(ShowMessageType.Error, "查找可用的服务器失败!"); + return ConnectResult.FindServerFailed; + } + } + try + { + if (Config.FunGame_isRetrying) + { + Main.GetMessage("正在连接服务器,请耐心等待。"); + Config.FunGame_isRetrying = false; + return ConnectResult.CanNotConnect; + } + if (!Config.FunGame_isConnected) + { + Main.CurrentRetryTimes++; + if (Main.CurrentRetryTimes == 0) Main.GetMessage("开始连接服务器...", TimeType.General); + else Main.GetMessage("第" + Main.CurrentRetryTimes + "次重试连接服务器..."); + // 超过重连次数上限 + if (Main.CurrentRetryTimes + 1 > Main.MaxRetryTimes) + { + throw new CanNotConnectException(); + } + // 与服务器建立连接 + Socket?.Close(); + Config.FunGame_isRetrying = true; + _Socket = Socket.Connect(RunTime.Session.Server_IP, RunTime.Session.Server_Port); + if (Socket != null && Socket.Connected) + { + // 设置可复用Socket + RunTime.Socket = Socket; + // 发送连接请求 + DataRequest request = RunTime.NewDataRequest(DataRequestType.RunTime_Connect); + request.SendRequest(); + if (request.Result == RequestResult.Success) + { + bool success = request.GetResult("success"); + string msg = request.GetResult("msg") ?? ""; + if (!success) + { + // 服务器拒绝连接 + if (msg != "") + { + Main.GetMessage(msg); + Main.ShowMessage(ShowMessageType.Error, msg); + } + return ConnectResult.ConnectFailed; + } + else + { + if (msg != "") + { + Main.GetMessage(msg); + } + Guid token = request.GetResult("token"); + string servername = request.GetResult("servername") ?? ""; + string notice = request.GetResult("notice") ?? ""; + Config.FunGame_ServerName = servername; + Config.FunGame_Notice = notice; + Socket!.Token = token; + Usercfg.SocketToken = token; + Main.GetMessage($"已连接服务器:{servername}。\n\n********** 服务器公告 **********\n\n{notice}\n\n"); + // 设置等待登录的黄灯 + Main.UpdateUI(MainInvokeType.WaitLoginAndSetYellow); + Main.GetMessage("连接服务器成功,请登录账号以体验FunGame。"); + Main.UpdateUI(MainInvokeType.Connected); + StartReceiving(); + Task.Run(() => + { + while (true) + { + if (_IsReceiving) + { + break; + } + } + }); + return ConnectResult.Success; + } + } + Config.FunGame_isRetrying = false; + Socket.Close(); + return ConnectResult.ConnectFailed; + } + Socket?.Close(); + Config.FunGame_isRetrying = false; + throw new CanNotConnectException(); + } + else + { + Main.GetMessage("已连接至服务器,请勿重复连接。"); + return ConnectResult.CanNotConnect; + } + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo(), TimeType.None); + Main.UpdateUI(MainInvokeType.SetRed); + Config.FunGame_isRetrying = false; + return ConnectResult.ConnectFailed; + } + } + + public override void AutoLogin(string Username, string Password, string AutoKey) + { + try + { + Core.Api.Utility.TaskUtility.StartAndAwaitTask(async () => await LoginController.LoginAccountAsync(Username, Password, AutoKey)); + } + catch (Exception e) + { + Main.GetMessage(e.GetErrorInfo(), TimeType.None); + } + } + + protected override void SocketHandler_Disconnect(SocketObject ServerMessage) + { + string msg = ""; + if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam(0)!; + Main.GetMessage(msg); + Main.UpdateUI(MainInvokeType.Disconnect); + Close(); + Main.OnSucceedDisconnectEvent(new GeneralEventArgs()); + Main.OnAfterDisconnectEvent(new GeneralEventArgs()); + } + + protected override void SocketHandler_HeartBeat(SocketObject ServerMessage) + { + if (Socket != null && Socket.Connected && Usercfg.LoginUser.Id != 0) + { + Main.UpdateUI(MainInvokeType.SetGreenAndPing); + } } } } diff --git a/FunGame.Desktop/Library/Component/GeneralForm.cs b/FunGame.Desktop/Library/Component/GeneralForm.cs index abe6686..9bc3483 100644 --- a/FunGame.Desktop/Library/Component/GeneralForm.cs +++ b/FunGame.Desktop/Library/Component/GeneralForm.cs @@ -1,4 +1,5 @@ using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Desktop.UI; using Milimoe.FunGame.Desktop.Utility; @@ -13,6 +14,99 @@ namespace Milimoe.FunGame.Desktop.Library.Component InitializeComponent(); } + /// + /// 提供公共方法给Controller发送消息弹窗(这样可以防止跨线程时,弹窗不在最上层) + /// + /// + /// + /// + /// + public MessageResult ShowMessage(ShowMessageType type, string msg, string title = "", int autoclose = 0) + { + MessageResult result = MessageResult.OK; + + void action() + { + if (msg == "") return; + switch (type) + { + case ShowMessageType.General: + result = Library.Component.ShowMessage.Message(msg, title, autoclose); + break; + case ShowMessageType.Tip: + result = Library.Component.ShowMessage.TipMessage(msg, "", autoclose); + break; + case ShowMessageType.Warning: + result = Library.Component.ShowMessage.WarningMessage(msg, "", autoclose); + break; + case ShowMessageType.Error: + result = Library.Component.ShowMessage.ErrorMessage(msg, "", autoclose); + break; + case ShowMessageType.YesNo: + result = Library.Component.ShowMessage.YesNoMessage(msg, title); + break; + case ShowMessageType.OKCancel: + result = Library.Component.ShowMessage.OKCancelMessage(msg, title); + break; + case ShowMessageType.RetryCancel: + result = Library.Component.ShowMessage.RetryCancelMessage(msg, title); + break; + default: + break; + } + }; + InvokeUpdateUI(action); + + return result; + } + + /// + /// 提供公共方法给Controller发送消息弹窗(这样可以防止跨线程时,弹窗不在最上层) + /// + /// + /// + /// + /// + public string ShowInputMessage(string msg, string title) + { + string input = ""; + + void action() + { + if (msg == "") return; + input = Component.ShowMessage.InputMessage(msg, title); + }; + InvokeUpdateUI(action); + + return input; + } + + /// + /// 提供公共方法给Controller发送消息弹窗(这样可以防止跨线程时,弹窗不在最上层) + /// 支持返回点击的按钮,用于判断是否取消输入 + /// + /// + /// + /// + /// + public string ShowInputMessageCancel(string msg, string title, out MessageResult result) + { + MessageResult resultThisMethod = MessageResult.Cancel; + string input = ""; + + void action() + { + if (msg == "") return; + input = Component.ShowMessage.InputMessageCancel(msg, title, out MessageResult resultShowMessage); + resultThisMethod = resultShowMessage; + }; + InvokeUpdateUI(action); + + result = resultThisMethod; + + return input; + } + /// /// 绑定事件,子类需要重写 /// @@ -105,5 +199,16 @@ namespace Milimoe.FunGame.Desktop.Library.Component { BindEvent(); } + + /// + /// 委托更新UI + /// + /// + protected virtual void InvokeUpdateUI(Action action) + { + if (InvokeRequired) Invoke(action); + else action(); + } + } } diff --git a/FunGame.Desktop/Library/Component/ShowMessage.cs b/FunGame.Desktop/Library/Component/ShowMessage.cs index 405666f..40bcc52 100644 --- a/FunGame.Desktop/Library/Component/ShowMessage.cs +++ b/FunGame.Desktop/Library/Component/ShowMessage.cs @@ -158,23 +158,23 @@ namespace Milimoe.FunGame.Desktop.Library.Component return result; } - public static MessageResult TipMessage(string msg, string? title = null, int autoclose = 0) + public static MessageResult TipMessage(string msg, string title = "", int autoclose = 0) { - object[] objs = { title ?? TITLE_TIP, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; + object[] objs = { title == "" ? TITLE_TIP : title, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; MessageResult result = new ShowMessage(objs).MessageResult; return result; } - public static MessageResult WarningMessage(string msg, string? title = null, int autoclose = 0) + public static MessageResult WarningMessage(string msg, string title = "", int autoclose = 0) { - object[] objs = { title ?? TITLE_WARNING, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; + object[] objs = { title == "" ? TITLE_WARNING : title, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; MessageResult result = new ShowMessage(objs).MessageResult; return result; } - public static MessageResult ErrorMessage(string msg, string? title = null, int autoclose = 0) + public static MessageResult ErrorMessage(string msg, string title = "", int autoclose = 0) { - object[] objs = { title ?? TITLE_ERROR, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; + object[] objs = { title == "" ? TITLE_ERROR : title, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; MessageResult result = new ShowMessage(objs).MessageResult; return result; } diff --git a/FunGame.Desktop/Library/Config/Constant.cs b/FunGame.Desktop/Library/Config/Constant.cs index 68a61b6..b7048de 100644 --- a/FunGame.Desktop/Library/Config/Constant.cs +++ b/FunGame.Desktop/Library/Config/Constant.cs @@ -1,5 +1,4 @@ -using System.Text; -using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Core.Library.Constant; namespace Milimoe.FunGame.Desktop.Library { @@ -61,4 +60,17 @@ namespace Milimoe.FunGame.Desktop.Library FunGame_AutoRetryOff }; } + + public enum ShowMessageType + { + General, + Tip, + Warning, + Error, + YesNo, + OKCancel, + RetryCancel, + Input, + InputCancel + } } diff --git a/FunGame.Desktop/Library/Config/RunTime.cs b/FunGame.Desktop/Library/Config/RunTime.cs index b0a05bf..c71acd6 100644 --- a/FunGame.Desktop/Library/Config/RunTime.cs +++ b/FunGame.Desktop/Library/Config/RunTime.cs @@ -32,5 +32,11 @@ namespace Milimoe.FunGame.Desktop.Library DataRequest? request = Controller?.NewDataRequest(RequestType); return request is null ? throw new ConnectFailedException() : request; } + + public static DataRequest NewLongRunningDataRequest(DataRequestType RequestType) + { + DataRequest? request = Controller?.NewLongRunningDataRequest(RequestType); + return request is null ? throw new ConnectFailedException() : request; + } } } diff --git a/FunGame.Desktop/Model/LoginModel.cs b/FunGame.Desktop/Model/LoginModel.cs deleted file mode 100644 index 19412cf..0000000 --- a/FunGame.Desktop/Model/LoginModel.cs +++ /dev/null @@ -1,205 +0,0 @@ -using Milimoe.FunGame.Core.Api.Transmittal; -using Milimoe.FunGame.Core.Api.Utility; -using Milimoe.FunGame.Core.Entity; -using Milimoe.FunGame.Core.Library.Common.Network; -using Milimoe.FunGame.Core.Library.Constant; -using Milimoe.FunGame.Core.Library.Exception; -using Milimoe.FunGame.Core.Library.SQLScript.Common; -using Milimoe.FunGame.Core.Library.SQLScript.Entity; -using Milimoe.FunGame.Core.Model; -using Milimoe.FunGame.Desktop.Library.Component; -using RunTime = Milimoe.FunGame.Desktop.Library.RunTime; - -namespace Milimoe.FunGame.Desktop.Model -{ - /// - /// 请不要越过Controller直接调用Model中的方法。 - /// - public class LoginModel : SocketHandlerModel - { - private static new SocketObject Work; - private static new bool Working = false; - - public LoginModel() : base(RunTime.Socket) - { - - } - - public override void SocketHandler(SocketObject SocketObject) - { - try - { - if (SocketObject.SocketType == SocketMessageType.RunTime_Login || SocketObject.SocketType == SocketMessageType.RunTime_CheckLogin) - { - Work = SocketObject; - Working = false; - } - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - } - - public static async Task LoginAccountAsync(params object[]? objs) - { - try - { - Socket? Socket = RunTime.Socket; - if (Socket != null && objs != null) - { - string username = ""; - string password = ""; - string autokey = ""; - if (objs.Length > 0) username = (string)objs[0]; - if (objs.Length > 1) password = (string)objs[1]; - if (objs.Length > 2) autokey = (string)objs[2]; - password = password.Encrypt(username); - SetWorking(); - if (Socket.Send(SocketMessageType.RunTime_Login, username, password, autokey) == SocketResult.Success) - { - string ErrorMsg = ""; - Guid CheckLoginKey = Guid.Empty; - (CheckLoginKey, ErrorMsg) = await Task.Factory.StartNew(GetCheckLoginKeyAsync); - if (ErrorMsg != null && ErrorMsg.Trim() != "") - { - ShowMessage.ErrorMessage(ErrorMsg, "登录失败"); - return false; - } - SetWorking(); - if (Socket.Send(SocketMessageType.RunTime_CheckLogin, CheckLoginKey) == SocketResult.Success) - { - User user = await Task.Factory.StartNew(GetLoginUserAsync); - // 创建User对象并返回到Main - RunTime.Main?.UpdateUI(MainInvokeType.SetUser, user); - return true; - } - } - } - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - - return false; - } - - public static (Guid, string) GetCheckLoginKeyAsync() - { - Guid key = Guid.Empty; - string? msg = ""; - try - { - WaitForWorkDone(); - // 返回一个确认登录的Key - if (Work.Length > 0) key = Work.GetParam(0); - if (Work.Length > 1) msg = Work.GetParam(1); - if (key != Guid.Empty) - { - RunTime.Session.LoginKey = key; - } - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - msg ??= ""; - return (key, msg); - } - - public static string ForgetPassword_CheckVerifyCode(string username, string email, string verifycode) - { - string msg = "无法找回您的密码,请稍后再试。"; - - try - { - DataRequest request = RunTime.NewDataRequest(DataRequestType.Login_GetFindPasswordVerifyCode); - request.AddRequestData(ForgetVerifyCodes.Column_Username, username); - request.AddRequestData(ForgetVerifyCodes.Column_Email, email); - if (verifycode.Trim() == "") - { - // 未发送verifycode,说明需要系统生成一个验证码 - request.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, ""); - request.SendRequest(); - if (request.Result == RequestResult.Success) - { - msg = request.GetResult("msg") ?? msg; - } - else RunTime.WritelnSystemInfo(request.Error); - } - else - { - // 发送verifycode,需要验证 - request.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, verifycode); - request.SendRequest(); - if (request.Result == RequestResult.Success) - { - msg = request.GetResult("msg") ?? msg; - } - else RunTime.WritelnSystemInfo(request.Error); - } - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - - return msg; - } - - public static string ForgetPassword_UpdatePassword(string username, string password) - { - string msg = "无法更新您的密码,请稍后再试。"; - - try - { - DataRequest request = RunTime.NewDataRequest(DataRequestType.Login_UpdatePassword); - request.AddRequestData(UserQuery.Column_Username, username); - request.AddRequestData(UserQuery.Column_Password, password.Encrypt(username)); - request.SendRequest(); - if (request.Result == RequestResult.Success) - { - msg = request.GetResult("msg") ?? msg; - } - else RunTime.WritelnSystemInfo(request.Error); - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - - return msg; - } - - private static User GetLoginUserAsync() - { - User user = General.UnknownUserInstance; - try - { - WaitForWorkDone(); - // 返回构造User对象的DataSet - if (Work.Length > 0) user = Work.GetParam(0) ?? General.UnknownUserInstance; - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - return user; - } - - private static new void SetWorking() - { - Working = true; - Work = default; - } - - private static new void WaitForWorkDone() - { - while (true) - { - if (!Working) break; - } - } - } -} diff --git a/FunGame.Desktop/Model/MainModel.cs b/FunGame.Desktop/Model/MainModel.cs deleted file mode 100644 index 4a0ffb2..0000000 --- a/FunGame.Desktop/Model/MainModel.cs +++ /dev/null @@ -1,344 +0,0 @@ -using Milimoe.FunGame.Core.Entity; -using Milimoe.FunGame.Core.Library.Common.Network; -using Milimoe.FunGame.Core.Library.Constant; -using Milimoe.FunGame.Core.Library.Exception; -using Milimoe.FunGame.Core.Model; -using Milimoe.FunGame.Desktop.Library.Component; -using Milimoe.FunGame.Desktop.UI; -using RunTime = Milimoe.FunGame.Desktop.Library.RunTime; - -namespace Milimoe.FunGame.Desktop.Model -{ - public class MainModel : SocketHandlerModel - { - private readonly Main Main; - private readonly Session Usercfg = RunTime.Session; - - public MainModel(Main main) : base(RunTime.Socket) - { - Main = main; - } - - #region 公开方法 - - public async Task LogOut() - { - try - { - // 需要当时登录给的Key发回去,确定是账号本人在操作才允许登出 - if (Usercfg.LoginKey != Guid.Empty) - { - SetWorking(); - if (RunTime.Socket?.Send(SocketMessageType.RunTime_Logout, Usercfg.LoginKey) == SocketResult.Success) - { - string msg = ""; - Guid key = Guid.Empty; - (msg, key) = await Task.Factory.StartNew(SocketHandler_LogOut); - if (key == Usercfg.LoginKey) - { - Usercfg.LoginKey = Guid.Empty; - Main.UpdateUI(MainInvokeType.LogOut, msg ?? ""); - return true; - } - } - } - throw new CanNotLogOutException(); - } - catch (Exception e) - { - ShowMessage.ErrorMessage("无法登出您的账号,请联系服务器管理员。", "登出失败", 5); - Main.GetMessage(e.GetErrorInfo()); - } - return false; - } - - public async Task IntoRoom(Room room) - { - try - { - SetWorking(); - if (RunTime.Socket?.Send(SocketMessageType.Main_IntoRoom, room.Roomid) == SocketResult.Success) - { - string roomid = await Task.Factory.StartNew(SocketHandler_IntoRoom); - if (roomid.Trim() != "" && roomid == "-1") - { - Main.GetMessage($"已连接至公共聊天室。"); - } - else - { - Usercfg.InRoom = room; - } - return true; - } - throw new CanNotIntoRoomException(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - return false; - } - } - - public async Task UpdateRoom() - { - try - { - SetWorking(); - if (RunTime.Socket?.Send(SocketMessageType.Main_UpdateRoom) == SocketResult.Success) - { - List list = await Task.Factory.StartNew(SocketHandler_UpdateRoom); - Main.UpdateUI(MainInvokeType.UpdateRoom, list); - return true; - } - throw new GetRoomListException(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - return false; - } - } - - public async Task GetRoomPlayerCount(string roomid) - { - try - { - SetWorking(); - if (RunTime.Socket?.Send(SocketMessageType.Room_GetRoomPlayerCount, roomid) == SocketResult.Success) - { - return await Task.Factory.StartNew(SocketHandler_GetRoomPlayerCount); - } - return 0; - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - return 0; - } - } - - public async Task QuitRoom(string roomid, bool isMaster) - { - bool result = false; - try - { - SetWorking(); - if (RunTime.Socket?.Send(SocketMessageType.Main_QuitRoom, roomid, isMaster) == SocketResult.Success) - { - result = await Task.Factory.StartNew(SocketHandler_QuitRoom); - if (result) - { - Usercfg.InRoom = General.HallInstance; - return result; - } - } - throw new QuitRoomException(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - return result; - } - } - - public async Task CreateRoom(string RoomType, string Password = "") - { - try - { - SetWorking(); - if (RunTime.Socket?.Send(SocketMessageType.Main_CreateRoom, RoomType, Usercfg.LoginUser.Id, Password) == SocketResult.Success) - { - string roomid = await Task.Factory.StartNew(SocketHandler_CreateRoom); - if (roomid.Trim() != "") - { - return roomid; - } - } - throw new CreateRoomException(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - return ""; - } - } - - public bool Chat(string msg) - { - try - { - if (RunTime.Socket?.Send(SocketMessageType.Main_Chat, msg) == SocketResult.Success) - { - return true; - } - throw new CanNotSendTalkException(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - return false; - } - } - - public override void SocketHandler(SocketObject SocketObject) - { - try - { - // 定义接收的通信类型 - SocketMessageType[] SocketMessageTypes = new SocketMessageType[] { SocketMessageType.Main_GetNotice, SocketMessageType.RunTime_Logout, SocketMessageType.Main_IntoRoom, SocketMessageType.Main_QuitRoom, - SocketMessageType.Main_Chat, SocketMessageType.Main_UpdateRoom, SocketMessageType.Main_CreateRoom }; - if (SocketObject.SocketType == SocketMessageType.RunTime_HeartBeat) - { - // 心跳包单独处理 - if ((RunTime.Socket?.Connected ?? false) && Usercfg.LoginUser.Id != 0) - Main.UpdateUI(MainInvokeType.SetGreenAndPing); - } - else if (SocketObject.SocketType == SocketMessageType.RunTime_ForceLogout) - { - // 服务器强制下线登录 - Guid key = Guid.Empty; - string? msg = ""; - if (SocketObject.Length > 0) key = SocketObject.GetParam(0); - if (SocketObject.Length > 1) msg = SocketObject.GetParam(1); - msg ??= ""; - if (key == Usercfg.LoginKey) - { - Usercfg.LoginKey = Guid.Empty; - Main.UpdateUI(MainInvokeType.LogOut, msg ?? ""); - } - } - else if (SocketObject.SocketType == SocketMessageType.Main_Chat) - { - // 收到房间聊天信息 - string? user = "", msg = ""; - if (SocketObject.Length > 0) user = SocketObject.GetParam(0); - if (SocketObject.Length > 1) msg = SocketObject.GetParam(1); - if (user != Usercfg.LoginUserName) - { - Main.GetMessage(msg, TimeType.None); - } - } - else if (SocketObject.SocketType == SocketMessageType.Room_UpdateRoomMaster) - { - // 收到房间更换房主的信息 - User user = General.UnknownUserInstance; - Room room = General.HallInstance; - if (SocketObject.Length > 0) user = SocketObject.GetParam(0) ?? General.UnknownUserInstance; - if (SocketObject.Length > 1) room = SocketObject.GetParam(1) ?? General.HallInstance; - if (room.Roomid != "-1" && room.Roomid == Usercfg.InRoom.Roomid) Main.UpdateUI(MainInvokeType.UpdateRoomMaster, room); - } - else if (SocketMessageTypes.Contains(SocketObject.SocketType)) - { - Work = SocketObject; - Working = false; - } - } - catch (Exception e) - { - RunTime.Controller?.Error(e); - } - } - - #endregion - - #region SocketHandler - - private (string, Guid) SocketHandler_LogOut() - { - string? msg = ""; - Guid key = Guid.Empty; - try - { - WaitForWorkDone(); - // 返回一个Key,如果这个Key是空的,登出失败 - if (Work.Length > 0) key = Work.GetParam(0); - if (Work.Length > 1) msg = Work.GetParam(1); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - } - msg ??= ""; - return (msg, key); - } - - private string SocketHandler_IntoRoom() - { - string? roomid = ""; - try - { - WaitForWorkDone(); - if (Work.Length > 0) roomid = Work.GetParam(0); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - } - roomid ??= ""; - return roomid; - } - - private string SocketHandler_CreateRoom() - { - string? roomid = ""; - try - { - WaitForWorkDone(); - if (Work.Length > 0) roomid = Work.GetParam(0); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - } - roomid ??= ""; - return roomid; - } - - private bool SocketHandler_QuitRoom() - { - bool result = false; - try - { - WaitForWorkDone(); - if (Work.Length > 0) result = Work.GetParam(0); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - } - return result; - } - - private int SocketHandler_GetRoomPlayerCount() - { - int count = 0; - try - { - WaitForWorkDone(); - if (Work.Length > 0) count = Work.GetParam(0); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - } - return count; - } - - private List SocketHandler_UpdateRoom() - { - List list = new(); - try - { - WaitForWorkDone(); - if (Work.Length > 0) list = Work.GetParam>(0) ?? new(); - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo()); - } - return list; - } - - #endregion - } -} diff --git a/FunGame.Desktop/Model/RegisterModel.cs b/FunGame.Desktop/Model/RegisterModel.cs deleted file mode 100644 index 4754dc5..0000000 --- a/FunGame.Desktop/Model/RegisterModel.cs +++ /dev/null @@ -1,123 +0,0 @@ -using Milimoe.FunGame.Core.Api.Utility; -using Milimoe.FunGame.Core.Library.Common.Network; -using Milimoe.FunGame.Core.Library.Constant; -using Milimoe.FunGame.Core.Library.Exception; -using Milimoe.FunGame.Core.Model; -using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.Library.Component; -using RunTime = Milimoe.FunGame.Desktop.Library.RunTime; - -namespace Milimoe.FunGame.Desktop.Model -{ - public class RegisterModel : SocketHandlerModel - { - public RegisterModel() : base(RunTime.Socket) - { - - } - - public override void SocketHandler(SocketObject SocketObject) - { - try - { - if (SocketObject.SocketType == SocketMessageType.RunTime_Reg || SocketObject.SocketType == SocketMessageType.RunTime_CheckReg) - { - Work = SocketObject; - Working = false; - } - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - } - - public async Task Reg(params object[]? objs) - { - try - { - Socket? Socket = RunTime.Socket; - if (Socket != null && objs != null) - { - string username = ""; - string password = ""; - string email = ""; - if (objs.Length > 0) username = (string)objs[0]; - if (objs.Length > 1) password = (string)objs[1]; - password = password.Encrypt(username); - if (objs.Length > 2) email = (string)objs[2]; - SetWorking(); - if (Socket.Send(SocketMessageType.RunTime_Reg, username, email) == SocketResult.Success) - { - RegInvokeType InvokeType = await Task.Factory.StartNew(GetRegInvokeType); - while (true) - { - switch (InvokeType) - { - case RegInvokeType.InputVerifyCode: - string verifycode = ShowMessage.InputMessageCancel("请输入注册邮件中的6位数字验证码", "注册验证码", out MessageResult cancel); - if (cancel != MessageResult.Cancel) - { - SetWorking(); - if (Socket.Send(SocketMessageType.RunTime_CheckReg, username, password, email, verifycode) == SocketResult.Success) - { - bool success = false; - string msg = ""; - (success, msg) = await Task.Factory.StartNew(GetRegResult); - ShowMessage.Message(msg, "注册结果"); - if (success) return success; - } - break; - } - else return false; - case RegInvokeType.DuplicateUserName: - ShowMessage.WarningMessage("此账号名已被注册,请使用其他账号名。"); - return false; - case RegInvokeType.DuplicateEmail: - ShowMessage.WarningMessage("此邮箱已被使用,请使用其他邮箱注册。"); - return false; - } - } - } - } - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - return false; - } - - private RegInvokeType GetRegInvokeType() - { - RegInvokeType type = RegInvokeType.None; - try - { - WaitForWorkDone(); - if (Work.Length > 0) type = Work.GetParam(0); - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - return type; - } - - private (bool, string) GetRegResult() - { - bool success = false; - string? msg = ""; - try - { - WaitForWorkDone(); - if (Work.Length > 0) success = Work.GetParam(0); - if (Work.Length > 1) msg = Work.GetParam(1) ?? ""; - } - catch (Exception e) - { - RunTime.WritelnSystemInfo(e.GetErrorInfo()); - } - return (success, msg); - } - } -} diff --git a/FunGame.Desktop/Model/RunTimeModel.cs b/FunGame.Desktop/Model/RunTimeModel.cs index 50e4e3b..1c54e34 100644 --- a/FunGame.Desktop/Model/RunTimeModel.cs +++ b/FunGame.Desktop/Model/RunTimeModel.cs @@ -1,160 +1,4 @@ -using Milimoe.FunGame.Core.Library.Common.Event; -using Milimoe.FunGame.Core.Library.Common.Network; -using Milimoe.FunGame.Core.Library.Constant; -using Milimoe.FunGame.Core.Library.Exception; -using Milimoe.FunGame.Desktop.Library.Component; -using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.UI; - -namespace Milimoe.FunGame.Desktop.Model +namespace Milimoe.FunGame.Desktop.Model { - /// - /// 与创建关闭Socket相关的方法,使用此类 - /// - public class RunTimeModel : Core.Model.RunTime - { - private readonly Main Main; - private readonly Core.Model.Session Usercfg = RunTime.Session; - - public RunTimeModel(Main main) - { - Main = main; - } - - public override async Task Connect() - { - if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0) - { - (RunTime.Session.Server_IP, RunTime.Session.Server_Port) = GetServerAddress(); - if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0) - { - ShowMessage.ErrorMessage("查找可用的服务器失败!"); - return ConnectResult.FindServerFailed; - } - } - try - { - if (Config.FunGame_isRetrying) - { - Main.GetMessage("正在连接服务器,请耐心等待。"); - Config.FunGame_isRetrying = false; - return ConnectResult.CanNotConnect; - } - if (!Config.FunGame_isConnected) - { - Main.CurrentRetryTimes++; - if (Main.CurrentRetryTimes == 0) Main.GetMessage("开始连接服务器...", TimeType.General); - else Main.GetMessage("第" + Main.CurrentRetryTimes + "次重试连接服务器..."); - // 超过重连次数上限 - if (Main.CurrentRetryTimes + 1 > Main.MaxRetryTimes) - { - throw new CanNotConnectException(); - } - // 与服务器建立连接 - Socket?.Close(); - Config.FunGame_isRetrying = true; - _Socket = Socket.Connect(RunTime.Session.Server_IP, RunTime.Session.Server_Port); - if (Socket != null && Socket.Connected) - { - // 设置可复用Socket - RunTime.Socket = Socket; - // 发送连接请求 - if (Socket.Send(SocketMessageType.RunTime_Connect) == SocketResult.Success) - { - SocketMessageType Result = Receiving(); - if (Result == SocketMessageType.RunTime_Connect) - { - Main.GetMessage("连接服务器成功,请登录账号以体验FunGame。"); - Main.UpdateUI(MainInvokeType.Connected); - StartReceiving(); - await Task.Factory.StartNew(() => - { - while (true) - { - if (_IsReceiving) - { - break; - } - } - }); - return ConnectResult.Success; - } - } - Config.FunGame_isRetrying = false; - Socket.Close(); - return ConnectResult.ConnectFailed; - } - Socket?.Close(); - Config.FunGame_isRetrying = false; - throw new CanNotConnectException(); - } - else - { - Main.GetMessage("已连接至服务器,请勿重复连接。"); - return ConnectResult.CanNotConnect; - } - } - catch (Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - Main.UpdateUI(MainInvokeType.SetRed); - Config.FunGame_isRetrying = false; - return ConnectResult.ConnectFailed; - } - } - - public override void Error(Exception e) - { - Main.GetMessage(e.GetErrorInfo(), TimeType.None); - Main.UpdateUI(MainInvokeType.Disconnected); - Main.OnFailedConnectEvent(new ConnectEventArgs(RunTime.Session.Server_IP, RunTime.Session.Server_Port)); - Close(); - } - - protected override bool SocketHandler_Connect(SocketObject ServerMessage) - { - string msg = ""; - Guid token = Guid.Empty; - if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam(0)!; - string[] strings = msg.Split(';'); - if (strings.Length != 2) - { - // 服务器拒绝连接 - msg = strings[0]; - Main.GetMessage(msg); - ShowMessage.ErrorMessage(msg); - return false; - } - string ServerName = strings[0]; - string ServerNotice = strings[1]; - Config.FunGame_ServerName = ServerName; - Config.FunGame_Notice = ServerNotice; - if (ServerMessage.Parameters.Length > 1) token = ServerMessage.GetParam(1); - Socket!.Token = token; - Usercfg.SocketToken = token; - Main.GetMessage($"已连接服务器:{ServerName}。\n\n********** 服务器公告 **********\n\n{ServerNotice}\n\n"); - // 设置等待登录的黄灯 - Main.UpdateUI(MainInvokeType.WaitLoginAndSetYellow); - return true; - } - - protected override void SocketHandler_Disconnect(SocketObject ServerMessage) - { - string msg = ""; - if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam(0)!; - Main.GetMessage(msg); - Main.UpdateUI(MainInvokeType.Disconnect); - Close(); - Main.OnSucceedDisconnectEvent(new GeneralEventArgs()); - Main.OnAfterDisconnectEvent(new GeneralEventArgs()); - } - - protected override void SocketHandler_HeartBeat(SocketObject ServerMessage) - { - if (Socket != null && Socket.Connected && Usercfg.LoginUser.Id != 0) - { - Main.UpdateUI(MainInvokeType.SetGreenAndPing); - } - } - } + // wait to remove } \ No newline at end of file diff --git a/FunGame.Desktop/UI/Login/ForgetPassword.Designer.cs b/FunGame.Desktop/UI/Login/ForgetPassword.Designer.cs index e1083d8..28b79bd 100644 --- a/FunGame.Desktop/UI/Login/ForgetPassword.Designer.cs +++ b/FunGame.Desktop/UI/Login/ForgetPassword.Designer.cs @@ -48,7 +48,7 @@ namespace Milimoe.FunGame.Desktop.UI Title.Location = new Point(7, 6); Title.Size = new Size(312, 47); Title.TabIndex = 8; - Title.Text = "Find Your Password"; + Title.Text = "Forget Password"; Title.TextAlign = ContentAlignment.MiddleLeft; // // ExitButton diff --git a/FunGame.Desktop/UI/Login/ForgetPassword.cs b/FunGame.Desktop/UI/Login/ForgetPassword.cs index e700677..f7bd1d1 100644 --- a/FunGame.Desktop/UI/Login/ForgetPassword.cs +++ b/FunGame.Desktop/UI/Login/ForgetPassword.cs @@ -1,125 +1,132 @@ -using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Library; -using Milimoe.FunGame.Desktop.Library.Component; namespace Milimoe.FunGame.Desktop.UI { public partial class ForgetPassword { + private readonly LoginController LoginController; + public ForgetPassword() { InitializeComponent(); - } - - protected override void BindEvent() - { - base.BindEvent(); + LoginController = new(this); + Disposed += ForgetPassword_Disposed; } private void FindPassword_Click(object sender, EventArgs e) { - if (RunTime.Socket != null) + TaskUtility.StartAndAwaitTask(async () => { - string username = UsernameText.Text.Trim(); - string email = EmailText.Text.Trim(); - if (username == "" || email == "") + if (RunTime.Socket != null) { - ShowMessage.ErrorMessage("账号或邮箱不能为空!"); - UsernameText.Focus(); - return; - } - - string msg; - bool success = false; - - try - { - // 发送找回密码请求 - msg = LoginController.ForgetPassword_CheckVerifyCode(username, email); - - if (msg.Trim() != "") + string username = UsernameText.Text.Trim(); + string email = EmailText.Text.Trim(); + if (username == "" || email == "") { - // 如果返回一个信息,则停止找回密码 - ShowMessage.ErrorMessage(msg); + ShowMessage(ShowMessageType.Error, "账号或邮箱不能为空!"); + UsernameText.Focus(); + return; } - else + + string msg; + bool success = false; + + try { - while (!success) + // 发送找回密码请求 + msg = await LoginController.ForgetPassword_CheckVerifyCodeAsync(username, email, ""); + + if (msg.Trim() != "") { - string verifycode = ShowMessage.InputMessageCancel("请输入找回密码邮件中的6位数字验证码", "注册验证码", out MessageResult result); - if (result != MessageResult.Cancel) - { - if (verifycode.Trim() != "") - { - msg = LoginController.ForgetPassword_CheckVerifyCode(username, email, verifycode); - if (msg.Trim() != "") - { - ShowMessage.ErrorMessage(msg); - } - else - { - success = true; - break; - } - } - else - { - ShowMessage.WarningMessage("不能输入空值!"); - } - } - else break; + // 如果返回一个信息,则停止找回密码 + ShowMessage(ShowMessageType.Error, msg); } - if (success) + else { - while (true) + while (!success) { - string newpass = ShowMessage.InputMessageCancel("请输入新密码", "设置新密码", out MessageResult result); + string verifycode = ShowInputMessageCancel("请输入找回密码邮件中的6位数字验证码", "注册验证码", out MessageResult result); if (result != MessageResult.Cancel) { - if (newpass.Trim() != "") + if (verifycode.Trim() != "") { - if (newpass.Length < 6 || newpass.Length > 15) // 字节范围 3~12 + msg = await LoginController.ForgetPassword_CheckVerifyCodeAsync(username, email, verifycode); + if (msg.Trim() != "") { - ShowMessage.ErrorMessage("密码长度不符合要求:6~15个字符数"); + ShowMessage(ShowMessageType.Error, msg); } else { - msg = LoginController.ForgetPassword_UpdatePassword(username, newpass); - if (msg.Trim() != "") + success = true; + break; + } + } + else + { + ShowMessage(ShowMessageType.Warning, "不能输入空值!"); + } + } + else break; + } + if (success) + { + while (true) + { + string newpass = ShowInputMessageCancel("请输入新密码", "设置新密码", out MessageResult result); + if (result != MessageResult.Cancel) + { + if (newpass.Trim() != "") + { + if (newpass.Length < 6 || newpass.Length > 15) // 字节范围 3~12 { - ShowMessage.ErrorMessage(msg); + ShowMessage(ShowMessageType.Error, "密码长度不符合要求:6~15个字符数"); } else { - ShowMessage.Message("密码更新成功!请您牢记新的密码。", "找回密码"); - break; + msg = await LoginController.ForgetPassword_UpdatePasswordAsync(username, newpass); + if (msg.Trim() != "") + { + ShowMessage(ShowMessageType.Error, msg); + } + else + { + ShowMessage(ShowMessageType.General, "密码更新成功!请您牢记新的密码。", "找回密码"); + break; + } } } } - } - else - { - if (ShowMessage.OKCancelMessage("确定放弃设置新密码吗?", "找回密码") == MessageResult.OK) + else { - success = false; - break; + if (ShowMessage(ShowMessageType.OKCancel, "确定放弃设置新密码吗?", "找回密码") == MessageResult.OK) + { + success = false; + break; + } } } } - } - if (success) - { - Dispose(); + if (success) + { + Dispose(); + } } } + catch (Exception ex) + { + RunTime.WritelnSystemInfo(ex.GetErrorInfo()); + } } - catch (Exception ex) - { - RunTime.WritelnSystemInfo(ex.GetErrorInfo()); - } - } + }); + } + + private void ForgetPassword_Disposed(object? sender, EventArgs e) + { + LoginController.Dispose(); } } } diff --git a/FunGame.Desktop/UI/Login/ForgetPassword.resx b/FunGame.Desktop/UI/Login/ForgetPassword.resx index 0991239..bcf8b70 100644 --- a/FunGame.Desktop/UI/Login/ForgetPassword.resx +++ b/FunGame.Desktop/UI/Login/ForgetPassword.resx @@ -1,4 +1,64 @@ - + + + diff --git a/FunGame.Desktop/UI/Login/Login.Designer.cs b/FunGame.Desktop/UI/Login/Login.Designer.cs index f50b27c..899738e 100644 --- a/FunGame.Desktop/UI/Login/Login.Designer.cs +++ b/FunGame.Desktop/UI/Login/Login.Designer.cs @@ -28,203 +28,202 @@ /// private void InitializeComponent() { - this.components = new System.ComponentModel.Container(); + components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login)); - this.ExitButton = new Milimoe.FunGame.Desktop.Library.Component.ExitButton(this.components); - this.MinButton = new Milimoe.FunGame.Desktop.Library.Component.MinButton(this.components); - this.Username = new System.Windows.Forms.Label(); - this.Password = new System.Windows.Forms.Label(); - this.UsernameText = new System.Windows.Forms.TextBox(); - this.PasswordText = new System.Windows.Forms.TextBox(); - this.RegButton = new System.Windows.Forms.Button(); - this.GoToLogin = new System.Windows.Forms.Button(); - this.ForgetPassword = new System.Windows.Forms.Button(); - this.FastLogin = new System.Windows.Forms.Button(); - this.TransparentRect = new Milimoe.FunGame.Desktop.Library.Component.TransparentRect(); - this.TransparentRect.SuspendLayout(); - this.SuspendLayout(); + ExitButton = new Library.Component.ExitButton(components); + MinButton = new Library.Component.MinButton(components); + Username = new Label(); + Password = new Label(); + UsernameText = new TextBox(); + PasswordText = new TextBox(); + RegButton = new Button(); + GoToLogin = new Button(); + ForgetPassword = new Button(); + FastLogin = new Button(); + TransparentRect = new Library.Component.TransparentRect(); + TransparentRect.SuspendLayout(); + SuspendLayout(); // // Title // - this.Title.Font = new System.Drawing.Font("LanaPixel", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); - this.Title.Location = new System.Drawing.Point(7, 6); - this.Title.Size = new System.Drawing.Size(387, 47); - this.Title.TabIndex = 8; - this.Title.Text = "Welcome to FunGame!"; - this.Title.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + Title.Font = new Font("LanaPixel", 26.25F, FontStyle.Bold, GraphicsUnit.Point); + Title.Location = new Point(7, 6); + Title.Size = new Size(387, 47); + Title.TabIndex = 8; + Title.Text = "Welcome to FunGame!"; + Title.TextAlign = ContentAlignment.MiddleLeft; // // ExitButton // - this.ExitButton.Anchor = System.Windows.Forms.AnchorStyles.None; - this.ExitButton.BackColor = System.Drawing.Color.White; - this.ExitButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ExitButton.BackgroundImage"))); - this.ExitButton.FlatAppearance.BorderColor = System.Drawing.Color.White; - this.ExitButton.FlatAppearance.BorderSize = 0; - this.ExitButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); - this.ExitButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); - this.ExitButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.ExitButton.Font = new System.Drawing.Font("LanaPixel", 36F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); - this.ExitButton.ForeColor = System.Drawing.Color.Red; - this.ExitButton.Location = new System.Drawing.Point(451, 4); - this.ExitButton.Name = "ExitButton"; - this.ExitButton.RelativeForm = this; - this.ExitButton.Size = new System.Drawing.Size(47, 47); - this.ExitButton.TabIndex = 7; - this.ExitButton.TextAlign = System.Drawing.ContentAlignment.TopLeft; - this.ExitButton.UseVisualStyleBackColor = false; + ExitButton.Anchor = AnchorStyles.None; + ExitButton.BackColor = Color.White; + ExitButton.BackgroundImage = (Image)resources.GetObject("ExitButton.BackgroundImage"); + ExitButton.FlatAppearance.BorderColor = Color.White; + ExitButton.FlatAppearance.BorderSize = 0; + ExitButton.FlatAppearance.MouseDownBackColor = Color.FromArgb(255, 128, 128); + ExitButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 192, 192); + ExitButton.FlatStyle = FlatStyle.Flat; + ExitButton.Font = new Font("LanaPixel", 36F, FontStyle.Bold, GraphicsUnit.Point); + ExitButton.ForeColor = Color.Red; + ExitButton.Location = new Point(451, 4); + ExitButton.Name = "ExitButton"; + ExitButton.RelativeForm = this; + ExitButton.Size = new Size(47, 47); + ExitButton.TabIndex = 7; + ExitButton.TextAlign = ContentAlignment.TopLeft; + ExitButton.UseVisualStyleBackColor = false; // // MinButton // - this.MinButton.Anchor = System.Windows.Forms.AnchorStyles.None; - this.MinButton.BackColor = System.Drawing.Color.White; - this.MinButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("MinButton.BackgroundImage"))); - this.MinButton.FlatAppearance.BorderColor = System.Drawing.Color.White; - this.MinButton.FlatAppearance.BorderSize = 0; - this.MinButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Gray; - this.MinButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.DarkGray; - this.MinButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.MinButton.Font = new System.Drawing.Font("LanaPixel", 36F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); - this.MinButton.ForeColor = System.Drawing.Color.Black; - this.MinButton.Location = new System.Drawing.Point(398, 4); - this.MinButton.Name = "MinButton"; - this.MinButton.RelativeForm = this; - this.MinButton.Size = new System.Drawing.Size(47, 47); - this.MinButton.TabIndex = 6; - this.MinButton.TextAlign = System.Drawing.ContentAlignment.TopLeft; - this.MinButton.UseVisualStyleBackColor = false; + MinButton.Anchor = AnchorStyles.None; + MinButton.BackColor = Color.White; + MinButton.BackgroundImage = (Image)resources.GetObject("MinButton.BackgroundImage"); + MinButton.FlatAppearance.BorderColor = Color.White; + MinButton.FlatAppearance.BorderSize = 0; + MinButton.FlatAppearance.MouseDownBackColor = Color.Gray; + MinButton.FlatAppearance.MouseOverBackColor = Color.DarkGray; + MinButton.FlatStyle = FlatStyle.Flat; + MinButton.Font = new Font("LanaPixel", 36F, FontStyle.Bold, GraphicsUnit.Point); + MinButton.ForeColor = Color.Black; + MinButton.Location = new Point(398, 4); + MinButton.Name = "MinButton"; + MinButton.RelativeForm = this; + MinButton.Size = new Size(47, 47); + MinButton.TabIndex = 6; + MinButton.TextAlign = ContentAlignment.TopLeft; + MinButton.UseVisualStyleBackColor = false; // // Username // - this.Username.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.Username.Location = new System.Drawing.Point(56, 111); - this.Username.Name = "Username"; - this.Username.Size = new System.Drawing.Size(75, 33); - this.Username.TabIndex = 9; - this.Username.Text = "账号"; - this.Username.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + Username.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point); + Username.Location = new Point(56, 111); + Username.Name = "Username"; + Username.Size = new Size(75, 33); + Username.TabIndex = 9; + Username.Text = "账号"; + Username.TextAlign = ContentAlignment.MiddleCenter; // // Password // - this.Password.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.Password.Location = new System.Drawing.Point(56, 144); - this.Password.Name = "Password"; - this.Password.Size = new System.Drawing.Size(75, 33); - this.Password.TabIndex = 10; - this.Password.Text = "密码"; - this.Password.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + Password.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point); + Password.Location = new Point(56, 144); + Password.Name = "Password"; + Password.Size = new Size(75, 33); + Password.TabIndex = 10; + Password.Text = "密码"; + Password.TextAlign = ContentAlignment.MiddleCenter; // // UsernameText // - this.UsernameText.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.UsernameText.Location = new System.Drawing.Point(143, 114); - this.UsernameText.Name = "UsernameText"; - this.UsernameText.Size = new System.Drawing.Size(216, 29); - this.UsernameText.TabIndex = 0; + UsernameText.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point); + UsernameText.Location = new Point(143, 114); + UsernameText.Name = "UsernameText"; + UsernameText.Size = new Size(216, 29); + UsernameText.TabIndex = 0; // // PasswordText // - this.PasswordText.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.PasswordText.Location = new System.Drawing.Point(143, 148); - this.PasswordText.Name = "PasswordText"; - this.PasswordText.PasswordChar = '*'; - this.PasswordText.Size = new System.Drawing.Size(216, 29); - this.PasswordText.TabIndex = 1; + PasswordText.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point); + PasswordText.Location = new Point(143, 148); + PasswordText.Name = "PasswordText"; + PasswordText.PasswordChar = '*'; + PasswordText.Size = new Size(216, 29); + PasswordText.TabIndex = 1; // // RegButton // - this.RegButton.Font = new System.Drawing.Font("LanaPixel", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.RegButton.Location = new System.Drawing.Point(365, 113); - this.RegButton.Name = "RegButton"; - this.RegButton.Size = new System.Drawing.Size(81, 33); - this.RegButton.TabIndex = 4; - this.RegButton.Text = "立即注册"; - this.RegButton.UseVisualStyleBackColor = true; - this.RegButton.Click += new System.EventHandler(this.RegButton_Click); + RegButton.Font = new Font("LanaPixel", 12F, FontStyle.Regular, GraphicsUnit.Point); + RegButton.Location = new Point(365, 113); + RegButton.Name = "RegButton"; + RegButton.Size = new Size(81, 33); + RegButton.TabIndex = 4; + RegButton.Text = "立即注册"; + RegButton.UseVisualStyleBackColor = true; + RegButton.Click += RegButton_Click; // // GoToLogin // - this.GoToLogin.Font = new System.Drawing.Font("LanaPixel", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.GoToLogin.Location = new System.Drawing.Point(277, 216); - this.GoToLogin.Name = "GoToLogin"; - this.GoToLogin.Size = new System.Drawing.Size(128, 42); - this.GoToLogin.TabIndex = 2; - this.GoToLogin.Text = "账号登录"; - this.GoToLogin.UseVisualStyleBackColor = true; - this.GoToLogin.Click += new System.EventHandler(this.GoToLogin_Click); + GoToLogin.Font = new Font("LanaPixel", 18F, FontStyle.Regular, GraphicsUnit.Point); + GoToLogin.Location = new Point(277, 216); + GoToLogin.Name = "GoToLogin"; + GoToLogin.Size = new Size(128, 42); + GoToLogin.TabIndex = 2; + GoToLogin.Text = "账号登录"; + GoToLogin.UseVisualStyleBackColor = true; + GoToLogin.Click += GoToLogin_Click; // // ForgetPassword // - this.ForgetPassword.Font = new System.Drawing.Font("LanaPixel", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.ForgetPassword.Location = new System.Drawing.Point(365, 147); - this.ForgetPassword.Name = "ForgetPassword"; - this.ForgetPassword.Size = new System.Drawing.Size(81, 32); - this.ForgetPassword.TabIndex = 5; - this.ForgetPassword.Text = "找回密码"; - this.ForgetPassword.UseVisualStyleBackColor = true; - this.ForgetPassword.Click += new System.EventHandler(this.ForgetPassword_Click); + ForgetPassword.Font = new Font("LanaPixel", 12F, FontStyle.Regular, GraphicsUnit.Point); + ForgetPassword.Location = new Point(365, 147); + ForgetPassword.Name = "ForgetPassword"; + ForgetPassword.Size = new Size(81, 32); + ForgetPassword.TabIndex = 5; + ForgetPassword.Text = "忘记密码"; + ForgetPassword.UseVisualStyleBackColor = true; + ForgetPassword.Click += ForgetPassword_Click; // // FastLogin // - this.FastLogin.Font = new System.Drawing.Font("LanaPixel", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.FastLogin.Location = new System.Drawing.Point(114, 216); - this.FastLogin.Name = "FastLogin"; - this.FastLogin.Size = new System.Drawing.Size(130, 42); - this.FastLogin.TabIndex = 3; - this.FastLogin.Text = "快捷登录"; - this.FastLogin.UseVisualStyleBackColor = true; - this.FastLogin.Click += new System.EventHandler(this.FastLogin_Click); + FastLogin.Font = new Font("LanaPixel", 18F, FontStyle.Regular, GraphicsUnit.Point); + FastLogin.Location = new Point(114, 216); + FastLogin.Name = "FastLogin"; + FastLogin.Size = new Size(130, 42); + FastLogin.TabIndex = 3; + FastLogin.Text = "快捷登录"; + FastLogin.UseVisualStyleBackColor = true; + FastLogin.Click += FastLogin_Click; // // TransparentRect // - this.TransparentRect.BackColor = System.Drawing.Color.WhiteSmoke; - this.TransparentRect.BorderColor = System.Drawing.Color.WhiteSmoke; - this.TransparentRect.Controls.Add(this.Title); - this.TransparentRect.Controls.Add(this.MinButton); - this.TransparentRect.Controls.Add(this.ExitButton); - this.TransparentRect.Controls.Add(this.FastLogin); - this.TransparentRect.Controls.Add(this.UsernameText); - this.TransparentRect.Controls.Add(this.ForgetPassword); - this.TransparentRect.Controls.Add(this.Username); - this.TransparentRect.Controls.Add(this.GoToLogin); - this.TransparentRect.Controls.Add(this.Password); - this.TransparentRect.Controls.Add(this.RegButton); - this.TransparentRect.Controls.Add(this.PasswordText); - this.TransparentRect.Location = new System.Drawing.Point(0, 0); - this.TransparentRect.Name = "TransparentRect"; - this.TransparentRect.Opacity = 125; - this.TransparentRect.Radius = 20; - this.TransparentRect.ShapeBorderStyle = Milimoe.FunGame.Desktop.Library.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; - this.TransparentRect.Size = new System.Drawing.Size(503, 289); - this.TransparentRect.TabIndex = 11; - this.TransparentRect.TabStop = false; - this.TransparentRect.Controls.SetChildIndex(this.PasswordText, 0); - this.TransparentRect.Controls.SetChildIndex(this.RegButton, 0); - this.TransparentRect.Controls.SetChildIndex(this.Password, 0); - this.TransparentRect.Controls.SetChildIndex(this.GoToLogin, 0); - this.TransparentRect.Controls.SetChildIndex(this.Username, 0); - this.TransparentRect.Controls.SetChildIndex(this.ForgetPassword, 0); - this.TransparentRect.Controls.SetChildIndex(this.UsernameText, 0); - this.TransparentRect.Controls.SetChildIndex(this.FastLogin, 0); - this.TransparentRect.Controls.SetChildIndex(this.ExitButton, 0); - this.TransparentRect.Controls.SetChildIndex(this.MinButton, 0); - this.TransparentRect.Controls.SetChildIndex(this.Title, 0); + TransparentRect.BackColor = Color.WhiteSmoke; + TransparentRect.BorderColor = Color.WhiteSmoke; + TransparentRect.Controls.Add(Title); + TransparentRect.Controls.Add(MinButton); + TransparentRect.Controls.Add(ExitButton); + TransparentRect.Controls.Add(FastLogin); + TransparentRect.Controls.Add(UsernameText); + TransparentRect.Controls.Add(ForgetPassword); + TransparentRect.Controls.Add(Username); + TransparentRect.Controls.Add(GoToLogin); + TransparentRect.Controls.Add(Password); + TransparentRect.Controls.Add(RegButton); + TransparentRect.Controls.Add(PasswordText); + TransparentRect.Location = new Point(0, 0); + TransparentRect.Name = "TransparentRect"; + TransparentRect.Opacity = 125; + TransparentRect.Radius = 20; + TransparentRect.ShapeBorderStyle = Library.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; + TransparentRect.Size = new Size(503, 289); + TransparentRect.TabIndex = 11; + TransparentRect.TabStop = false; + TransparentRect.Controls.SetChildIndex(PasswordText, 0); + TransparentRect.Controls.SetChildIndex(RegButton, 0); + TransparentRect.Controls.SetChildIndex(Password, 0); + TransparentRect.Controls.SetChildIndex(GoToLogin, 0); + TransparentRect.Controls.SetChildIndex(Username, 0); + TransparentRect.Controls.SetChildIndex(ForgetPassword, 0); + TransparentRect.Controls.SetChildIndex(UsernameText, 0); + TransparentRect.Controls.SetChildIndex(FastLogin, 0); + TransparentRect.Controls.SetChildIndex(ExitButton, 0); + TransparentRect.Controls.SetChildIndex(MinButton, 0); + TransparentRect.Controls.SetChildIndex(Title, 0); // // Login // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.WhiteSmoke; - this.ClientSize = new System.Drawing.Size(503, 289); - this.Controls.Add(this.TransparentRect); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.Name = "Login"; - this.Opacity = 0.9D; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "Login"; - this.TransparentRect.ResumeLayout(false); - this.TransparentRect.PerformLayout(); - this.ResumeLayout(false); - + AutoScaleDimensions = new SizeF(7F, 17F); + AutoScaleMode = AutoScaleMode.Font; + BackColor = Color.WhiteSmoke; + ClientSize = new Size(503, 289); + Controls.Add(TransparentRect); + Icon = (Icon)resources.GetObject("$this.Icon"); + Name = "Login"; + Opacity = 0.9D; + StartPosition = FormStartPosition.CenterScreen; + Text = "Login"; + TransparentRect.ResumeLayout(false); + TransparentRect.PerformLayout(); + ResumeLayout(false); } #endregion diff --git a/FunGame.Desktop/UI/Login/Login.cs b/FunGame.Desktop/UI/Login/Login.cs index d276d45..3e2371c 100644 --- a/FunGame.Desktop/UI/Login/Login.cs +++ b/FunGame.Desktop/UI/Login/Login.cs @@ -1,10 +1,10 @@ -using Milimoe.FunGame.Core.Library.Common.Event; +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library.Base; -using Milimoe.FunGame.Desktop.Library.Component; using Milimoe.FunGame.Desktop.Utility; namespace Milimoe.FunGame.Desktop.UI @@ -16,7 +16,7 @@ namespace Milimoe.FunGame.Desktop.UI public Login() { InitializeComponent(); - LoginController = new LoginController(); + LoginController = new(this); } protected override void BindEvent() @@ -29,11 +29,6 @@ namespace Milimoe.FunGame.Desktop.UI SucceedLogin += SucceedLoginEvent; } - private void Login_Disposed(object? sender, EventArgs e) - { - LoginController.Dispose(); - } - private async Task Login_Handler() { try @@ -42,11 +37,11 @@ namespace Milimoe.FunGame.Desktop.UI string password = PasswordText.Text.Trim(); if (username == "" || password == "") { - ShowMessage.ErrorMessage("账号或密码不能为空!"); + ShowMessage(ShowMessageType.Error, "账号或密码不能为空!"); UsernameText.Focus(); return false; } - return await LoginController.LoginAccount(username, password); + return await LoginController.LoginAccountAsync(username, password); } catch (Exception e) { @@ -67,15 +62,27 @@ namespace Milimoe.FunGame.Desktop.UI private void FastLogin_Click(object sender, EventArgs e) { - ShowMessage.TipMessage("与No.16对话即可获得快速登录秘钥,快去试试吧!"); + ShowMessage(ShowMessageType.Tip, "与No.16对话即可获得快速登录秘钥,快去试试吧!"); } - private async void GoToLogin_Click(object sender, EventArgs e) + private void GoToLogin_Click(object sender, EventArgs e) { GoToLogin.Enabled = false; - if (await Login_Handler() == false) GoToLogin.Enabled = true; - else Dispose(); + bool result = false; + TaskUtility.StartAndAwaitTask(async () => + { + result = await Login_Handler(); + }).OnCompleted(() => + { + if (result) Dispose(); + else GoToLogin.Enabled = true; + }); } + private void Login_Disposed(object? sender, EventArgs e) + { + LoginController.Dispose(); + } + private void ForgetPassword_Click(object sender, EventArgs e) { @@ -85,8 +92,7 @@ namespace Milimoe.FunGame.Desktop.UI public EventResult FailedLoginEvent(object sender, LoginEventArgs e) { - if (InvokeRequired) GoToLogin.Invoke(() => GoToLogin.Enabled = true); - else GoToLogin.Enabled = true; + GoToLogin.Enabled = true; RunTime.Main?.OnFailedLoginEvent(e); return EventResult.Success; } diff --git a/FunGame.Desktop/UI/Login/Login.resx b/FunGame.Desktop/UI/Login/Login.resx index 72662bd..0d8b642 100644 --- a/FunGame.Desktop/UI/Login/Login.resx +++ b/FunGame.Desktop/UI/Login/Login.resx @@ -1,4 +1,64 @@ - + + + diff --git a/FunGame.Desktop/UI/Main/Main.cs b/FunGame.Desktop/UI/Main/Main.cs index ac9e443..56313f2 100644 --- a/FunGame.Desktop/UI/Main/Main.cs +++ b/FunGame.Desktop/UI/Main/Main.cs @@ -7,7 +7,6 @@ using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library.Base; -using Milimoe.FunGame.Desktop.Library.Component; using Milimoe.FunGame.Desktop.Utility; namespace Milimoe.FunGame.Desktop.UI @@ -26,7 +25,7 @@ namespace Milimoe.FunGame.Desktop.UI /** * 变量 */ - private Task? MatchFunGame = null; // 匹配线程 + private Task? MatchFunGame = null; // 匹配线程(即将删除) private MainController? MainController = null; private readonly Core.Model.RoomList Rooms = RunTime.RoomList; private readonly Core.Model.Session Usercfg = RunTime.Session; @@ -39,13 +38,13 @@ namespace Milimoe.FunGame.Desktop.UI public Main() { InitializeComponent(); - InitAsync(); + Init(); } /// /// 所有自定义初始化的内容 /// - public async void InitAsync() + public void Init() { RunTime.Main = this; SetButtonEnableIfLogon(false, ClientState.WaitConnect); @@ -55,7 +54,7 @@ namespace Milimoe.FunGame.Desktop.UI // 创建RunTime RunTime.Controller = new RunTimeController(this); // 窗口句柄创建后,进行委托 - await Task.Factory.StartNew(() => + TaskUtility.StartAndAwaitTask(() => { while (true) { @@ -64,7 +63,7 @@ namespace Milimoe.FunGame.Desktop.UI break; } } - if (Config.FunGame_isAutoConnect) RunTime.Controller?.Connect(); + if (Config.FunGame_isAutoConnect) InvokeController_Connect(); }); } @@ -130,7 +129,7 @@ namespace Milimoe.FunGame.Desktop.UI if (MainController != null && Config.FunGame_isAutoConnect) { // 自动连接服务器 - RunTime.Controller?.Connect(); + InvokeController_Connect(); } break; @@ -188,7 +187,7 @@ namespace Milimoe.FunGame.Desktop.UI if (objs[0].GetType() == typeof(string)) { WritelnSystemInfo((string)objs[0]); - ShowMessage.Message((string)objs[0], "退出登录", 5); + ShowMessage(ShowMessageType.General, (string)objs[0], "退出登录", 5); } } break; @@ -250,13 +249,13 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - public void GetMessage(string? msg, TimeType timetype = TimeType.TimeOnly) + public void GetMessage(string msg, TimeType timetype = TimeType.TimeOnly) { void action() { try { - if (msg == null || msg == "") return; + if (msg == "") return; if (timetype != TimeType.None) { WritelnGameInfo(DateTimeUtility.GetDateTimeToString(timetype) + " >> " + msg); @@ -278,16 +277,6 @@ namespace Milimoe.FunGame.Desktop.UI #region 实现 - /// - /// 委托更新UI - /// - /// - private void InvokeUpdateUI(Action action) - { - if (InvokeRequired) Invoke(action); - else action(); - } - /// /// 获取FunGame配置文件设定 /// @@ -484,7 +473,7 @@ namespace Milimoe.FunGame.Desktop.UI else { RoomText.Enabled = false; - ShowMessage.TipMessage("请输入房间号。"); + ShowMessage(ShowMessageType.Tip, "请输入房间号。"); RoomText.Enabled = true; RoomText.Focus(); return false; @@ -505,15 +494,15 @@ namespace Milimoe.FunGame.Desktop.UI { if (MainController != null) { - await MainController.UpdateRoom(); + await MainController.UpdateRoomAsync(); if (CheckRoomIDExist(roomid)) { if (Usercfg.InRoom.Roomid == "-1") { - if (ShowMessage.YesNoMessage("已找到房间 -> [ " + roomid + " ]\n是否加入?", "已找到房间") == MessageResult.Yes) + if (ShowMessage(ShowMessageType.YesNo, "已找到房间 -> [ " + roomid + " ]\n是否加入?", "已找到房间") == MessageResult.Yes) { Room r = GetRoom(roomid); - if (MainController != null && await MainController.IntoRoom(r)) + if (MainController != null && await MainController.IntoRoomAsync(r)) { SetRoomid(r); InRoom(); @@ -524,12 +513,12 @@ namespace Milimoe.FunGame.Desktop.UI } else { - ShowMessage.TipMessage("你需要先退出房间才可以加入新的房间。"); + ShowMessage(ShowMessageType.Tip, "你需要先退出房间才可以加入新的房间。"); return false; } } } - ShowMessage.WarningMessage("未找到此房间!"); + ShowMessage(ShowMessageType.Warning, "未找到此房间!"); return false; } @@ -661,7 +650,7 @@ namespace Milimoe.FunGame.Desktop.UI Logout.Visible = true; UpdateUI(MainInvokeType.SetGreenAndPing); string welcome = $"欢迎回来, {Usercfg.LoginUserName}!"; - ShowMessage.Message(welcome, "登录成功", 5); + ShowMessage(ShowMessageType.General, welcome, "登录成功", 5); WritelnSystemInfo(welcome); } @@ -702,7 +691,7 @@ namespace Milimoe.FunGame.Desktop.UI /// 发送消息实现 /// /// 是否离开焦点 - private async Task SendTalkText_Click(bool isLeave) + private void SendTalkText_Click(bool isLeave) { // 向消息队列发送消息 string text = TalkText.Text; @@ -718,17 +707,23 @@ namespace Milimoe.FunGame.Desktop.UI msg = DateTimeUtility.GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: " + text; } WritelnGameInfo(msg); - if (Usercfg.LoginUser.Id != 0 && !await SwitchTalkMessage(text)) - { - MainController?.Chat(" [ " + Usercfg.LoginUserName + " ] 说: " + text); - } TalkText.Text = ""; if (isLeave) TalkText_Leave(); // 回车不离开焦点 + if (MainController != null && Usercfg.LoginUser.Id != 0 && !SwitchTalkMessage(text)) + { + TaskUtility.StartAndAwaitTask(async () => + { + if (!await MainController.ChatAsync(" [ " + Usercfg.LoginUserName + " ] 说: " + text)) + { + WritelnGameInfo("联网消息发送失败。"); + } + }); + } } else { TalkText.Enabled = false; - ShowMessage.TipMessage("消息不能为空,请重新输入。"); + ShowMessage(ShowMessageType.Tip, "消息不能为空,请重新输入。"); TalkText.Enabled = true; TalkText.Focus(); } @@ -744,26 +739,26 @@ namespace Milimoe.FunGame.Desktop.UI { if (Usercfg.InRoom.Roomid != "-1") { - ShowMessage.WarningMessage("已在房间中,无法创建房间。"); + ShowMessage(ShowMessageType.Warning, "已在房间中,无法创建房间。"); return; } if (MainController != null) { - string roomid = (await MainController.CreateRoom(RoomType, Password)).Trim(); + string roomid = await MainController.CreateRoomAsync(RoomType, Password); if (roomid != "" && roomid != "-1") { - await MainController.UpdateRoom(); + await MainController.UpdateRoomAsync(); Room r = GetRoom(roomid); - await MainController.IntoRoom(r); + await InvokeController_IntoRoom(r); SetRoomid(r); InRoom(); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 创建" + RoomType + "房间"); WritelnGameInfo(">> 创建" + RoomType + "房间成功!房间号: " + roomid); - ShowMessage.Message("创建" + RoomType + "房间成功!\n房间号是 -> [ " + roomid + " ]", "创建成功"); + ShowMessage(ShowMessageType.General, "创建" + RoomType + "房间成功!\n房间号是 -> [ " + roomid + " ]", "创建成功"); return; } } - ShowMessage.Message("创建" + RoomType + "房间失败!", "创建失败"); + ShowMessage(ShowMessageType.General, "创建" + RoomType + "房间失败!", "创建失败"); } /// @@ -796,9 +791,9 @@ namespace Milimoe.FunGame.Desktop.UI if (MainController != null) { // 获取在线的房间列表 - await MainController.UpdateRoom(); + await MainController.UpdateRoomAsync(); // 接入-1号房间聊天室 - await MainController.IntoRoom((Room)Rooms["-1"]!); + await InvokeController_IntoRoom(Rooms["-1"] ?? General.HallInstance); } } @@ -867,10 +862,11 @@ namespace Milimoe.FunGame.Desktop.UI /// private async Task ExitFunGame() { - if (ShowMessage.OKCancelMessage("你确定关闭游戏?", "退出") == (int)MessageResult.OK) + if (ShowMessage(ShowMessageType.OKCancel, "你确定关闭游戏?", "退出") == MessageResult.OK) { - if (MainController != null) await MainController.LogOut(); + if (MainController != null) await LogOut(); RunTime.Controller?.Close(); + RunTime.Controller?.Dispose(); Environment.Exit(0); } } @@ -884,9 +880,9 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void Exit_Click(object sender, EventArgs e) + private void Exit_Click(object sender, EventArgs e) { - await ExitFunGame(); + TaskUtility.StartAndAwaitTask(ExitFunGame); } /// @@ -931,29 +927,29 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void CreateRoom_Click(object sender, EventArgs e) + private void CreateRoom_Click(object sender, EventArgs e) { string password = ""; if (CheckMix.Checked && CheckTeam.Checked) { - ShowMessage.WarningMessage("创建房间不允许同时勾选混战和团队!"); + ShowMessage(ShowMessageType.Warning, "创建房间不允许同时勾选混战和团队!"); return; } if (CheckHasPass.Checked) { - password = ShowMessage.InputMessage("请输入该房间的密码:", "创建密码房间").Trim(); + password = ShowInputMessage("请输入该房间的密码:", "创建密码房间").Trim(); if (password == "" || password.Length > 10) { - ShowMessage.WarningMessage("密码无效!密码不能为空或大于10个字符。"); + ShowMessage(ShowMessageType.Warning, "密码无效!密码不能为空或大于10个字符。"); return; } } if (Config.FunGame_GameMode.Equals("")) { - ShowMessage.WarningMessage("请勾选你要创建的房间类型!"); + ShowMessage(ShowMessageType.Warning, "请勾选你要创建的房间类型!"); return; } - await CreateRoom_Handler(Config.FunGame_GameMode, password); + TaskUtility.StartAndAwaitTask(() => CreateRoom_Handler(Config.FunGame_GameMode, password)); } /// @@ -961,22 +957,25 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void QuitRoom_Click(object sender, EventArgs e) + private void QuitRoom_Click(object sender, EventArgs e) { - if (MainController != null) + string roomid = Usercfg.InRoom.Roomid; + bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser.Id; + bool result = false; + TaskUtility.StartAndAwaitTask(async () => { - string roomid = Usercfg.InRoom.Roomid; - bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser.Id; - if (await MainController.QuitRoom(Usercfg.InRoom, isMaster)) + if (await InvokeController_QuitRoom(Usercfg.InRoom, isMaster)) { WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 离开房间"); WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已离开房间 -> [ " + roomid + " ]"); InMain(); - _ = MainController.UpdateRoom(); - return; + _ = MainController?.UpdateRoomAsync(); + result = true; } - } - ShowMessage.ErrorMessage("无法退出房间!", "退出房间"); + }).OnCompleted(() => + { + if (!result) ShowMessage(ShowMessageType.Error, "无法退出房间!", "退出房间"); + }); } /// @@ -997,7 +996,7 @@ namespace Milimoe.FunGame.Desktop.UI private void CopyRoomID_Click(object sender, EventArgs e) { Clipboard.SetDataObject(Usercfg.InRoom.Roomid); - ShowMessage.TipMessage("已复制房间号到剪贴板"); + ShowMessage(ShowMessageType.Tip, "已复制房间号到剪贴板"); } /// @@ -1005,9 +1004,9 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void QueryRoom_Click(object sender, EventArgs e) + private void QueryRoom_Click(object sender, EventArgs e) { - await JoinRoom(false, RoomText.Text); + TaskUtility.StartAndAwaitTask(async() => await JoinRoom(false, RoomText.Text)); } /// @@ -1015,13 +1014,16 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void Logout_Click(object sender, EventArgs e) + private void Logout_Click(object sender, EventArgs e) { - if (ShowMessage.OKCancelMessage("你确定要退出登录吗?", "退出登录") == MessageResult.OK) + TaskUtility.StartAndAwaitTask(async () => { - if (MainController == null || !await MainController.LogOut()) - ShowMessage.WarningMessage("请求无效:退出登录失败!"); - } + if (ShowMessage(ShowMessageType.OKCancel, "你确定要退出登录吗?", "退出登录") == MessageResult.OK) + { + if (MainController == null || !await LogOut()) + ShowMessage(ShowMessageType.Warning, "请求无效:退出登录失败!"); + } + }); } /// @@ -1034,7 +1036,7 @@ namespace Milimoe.FunGame.Desktop.UI if (MainController != null && Config.FunGame_isConnected) OpenForm.SingleForm(FormType.Login, OpenFormType.Dialog); else - ShowMessage.WarningMessage("请先连接服务器!"); + ShowMessage(ShowMessageType.Warning, "请先连接服务器!"); } /// @@ -1052,11 +1054,11 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void RoomList_MouseDoubleClick(object sender, MouseEventArgs e) + private void RoomList_MouseDoubleClick(object sender, MouseEventArgs e) { if (RoomList.SelectedItem != null) { - await JoinRoom(true, RoomList.SelectedItem.ToString() ?? ""); + TaskUtility.StartAndAwaitTask(async() => await JoinRoom(true, RoomList.SelectedItem.ToString() ?? "")); } } @@ -1065,9 +1067,9 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void SendTalkText_Click(object sender, EventArgs e) + private void SendTalkText_Click(object sender, EventArgs e) { - await SendTalkText_Click(true); + SendTalkText_Click(true); } /// @@ -1122,13 +1124,13 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void RoomText_KeyUp(object sender, KeyEventArgs e) + private void RoomText_KeyUp(object sender, KeyEventArgs e) { RoomText.ForeColor = Color.Black; if (e.KeyCode.Equals(Keys.Enter)) { // 按下回车加入房间 - await JoinRoom(false, RoomText.Text); + TaskUtility.StartAndAwaitTask(async() => await JoinRoom(false, RoomText.Text)); } } @@ -1161,13 +1163,13 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void TalkText_KeyUp(object sender, KeyEventArgs e) + private void TalkText_KeyUp(object sender, KeyEventArgs e) { TalkText.ForeColor = Color.Black; if (e.KeyCode.Equals(Keys.Enter)) { // 按下回车发送 - await SendTalkText_Click(false); + SendTalkText_Click(false); } } @@ -1187,14 +1189,14 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - private async void PresetText_SelectedIndexChanged(object sender, EventArgs e) + private void PresetText_SelectedIndexChanged(object sender, EventArgs e) { // 发送快捷消息并执行功能 if (PresetText.SelectedIndex != 0) { string s = PresetText.SelectedItem.ToString() ?? ""; SendTalkText_Click(s); - await SwitchTalkMessage(s); + SwitchTalkMessage(s); PresetText.SelectedIndex = 0; } } @@ -1223,7 +1225,7 @@ namespace Milimoe.FunGame.Desktop.UI Task.Run(() => { Thread.Sleep(5000); - if (Config.FunGame_isConnected && Config.FunGame_isAutoRetry) RunTime.Controller?.Connect(); // 再次判断是否开启自动重连 + if (Config.FunGame_isConnected && Config.FunGame_isAutoRetry) InvokeController_Connect(); // 再次判断是否开启自动重连 }); GetMessage("连接服务器失败,5秒后自动尝试重连。"); } @@ -1244,7 +1246,7 @@ namespace Milimoe.FunGame.Desktop.UI if (MainController != null && Config.FunGame_isAutoLogin && Config.FunGame_AutoLoginUser != "" && Config.FunGame_AutoLoginPassword != "" && Config.FunGame_AutoLoginKey != "") { // 自动登录 - _ = RunTime.Controller?.AutoLogin(Config.FunGame_AutoLoginUser, Config.FunGame_AutoLoginPassword, Config.FunGame_AutoLoginKey); + RunTime.Controller?.AutoLogin(Config.FunGame_AutoLoginUser, Config.FunGame_AutoLoginPassword, Config.FunGame_AutoLoginKey); } return EventResult.Success; } @@ -1257,7 +1259,7 @@ namespace Milimoe.FunGame.Desktop.UI /// private EventResult SucceedLoginEvent(object sender, GeneralEventArgs e) { - _ = SucceedLoginEvent_Handler(); + TaskUtility.StartAndAwaitTask(SucceedLoginEvent_Handler); return EventResult.Success; } @@ -1287,7 +1289,7 @@ namespace Milimoe.FunGame.Desktop.UI /// 判断快捷消息 /// /// - private async Task SwitchTalkMessage(string s) + private bool SwitchTalkMessage(string s) { switch (s) { @@ -1303,10 +1305,10 @@ namespace Milimoe.FunGame.Desktop.UI GameInfo.Clear(); break; case Constant.FunGame_CreateMix: - await CreateRoom_Handler(GameMode.GameMode_Mix); + TaskUtility.StartAndAwaitTask(() => CreateRoom_Handler(GameMode.GameMode_Mix)); break; case Constant.FunGame_CreateTeam: - await CreateRoom_Handler(GameMode.GameMode_Team); + TaskUtility.StartAndAwaitTask(() => CreateRoom_Handler(GameMode.GameMode_Team)); break; case Constant.FunGame_StartGame: break; @@ -1323,7 +1325,7 @@ namespace Milimoe.FunGame.Desktop.UI { CurrentRetryTimes = -1; Config.FunGame_isAutoRetry = true; - RunTime.Controller?.Connect(); + InvokeController_Connect(); } else WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!"); @@ -1333,24 +1335,31 @@ namespace Milimoe.FunGame.Desktop.UI { CurrentRetryTimes = -1; Config.FunGame_isAutoRetry = true; - RunTime.Controller?.Connect(); + InvokeController_Connect(); } break; case Constant.FunGame_Disconnect: if (Config.FunGame_isConnected && MainController != null) { // 先退出登录再断开连接 - if (MainController != null && await MainController.LogOut()) RunTime.Controller?.Disconnect(); + bool SuccessLogOut = false; + TaskUtility.StartAndAwaitTask(async() => + { + if (await LogOut()) SuccessLogOut = true; + }).OnCompleted(() => + { + if (SuccessLogOut) InvokeController_Disconnect(); + }); } break; case Constant.FunGame_DisconnectWhenNotLogin: if (Config.FunGame_isConnected && MainController != null) { - RunTime.Controller?.Disconnect(); + InvokeController_Disconnect(); } break; case Constant.FunGame_ConnectTo: - string msg = ShowMessage.InputMessage("请输入服务器IP地址和端口号,如: 127.0.0.1:22222。", "连接指定服务器"); + string msg = ShowInputMessage("请输入服务器IP地址和端口号,如: 127.0.0.1:22222。", "连接指定服务器"); if (msg.Equals("")) return true; string[] addr = msg.Split(':'); string ip; @@ -1367,7 +1376,7 @@ namespace Milimoe.FunGame.Desktop.UI } else { - ShowMessage.ErrorMessage("格式错误!\n这不是一个服务器地址。"); + ShowMessage(ShowMessageType.Error, "格式错误!\n这不是一个服务器地址。"); return true; } ErrorIPAddressType ErrorType = NetworkUtility.IsServerAddress(ip, port); @@ -1377,11 +1386,11 @@ namespace Milimoe.FunGame.Desktop.UI RunTime.Session.Server_Port = port; CurrentRetryTimes = -1; Config.FunGame_isAutoRetry = true; - RunTime.Controller?.Connect(); + InvokeController_Connect(); } - else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotIP) ShowMessage.ErrorMessage("这不是一个IP地址!"); - else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotPort) ShowMessage.ErrorMessage("这不是一个端口号!\n正确范围:1~65535"); - else ShowMessage.ErrorMessage("格式错误!\n这不是一个服务器地址。"); + else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotIP) ShowMessage(ShowMessageType.Error, "这不是一个IP地址!"); + else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotPort) ShowMessage(ShowMessageType.Error, "这不是一个端口号!\n正确范围:1~65535"); + else ShowMessage(ShowMessageType.Error, "格式错误!\n这不是一个服务器地址。"); break; default: break; @@ -1390,5 +1399,157 @@ namespace Milimoe.FunGame.Desktop.UI } #endregion + + #region 调用控制器 + + /// + /// 连接服务器,并处理事件 + /// + /// + private void InvokeController_Connect() + { + try + { + ConnectEventArgs EventArgs = new(RunTime.Session.Server_IP, RunTime.Session.Server_Port); + ConnectResult result = ConnectResult.CanNotConnect; + + TaskUtility.StartAndAwaitTask(() => + { + if (OnBeforeConnectEvent(EventArgs) == EventResult.Fail) return; + result = RunTime.Controller?.Connect() ?? result; + EventArgs.ConnectResult = result; + }).OnCompleted(() => + { + if (result == ConnectResult.Success) OnSucceedConnectEvent(EventArgs); + else OnFailedConnectEvent(EventArgs); + OnAfterConnectEvent(EventArgs); + }); + } + catch (Exception e) + { + GetMessage(e.GetErrorInfo(), TimeType.None); + } + } + + /// + /// 断开服务器的连接,并处理事件 + /// + /// + public void InvokeController_Disconnect() + { + try + { + bool result = false; + + TaskUtility.StartAndAwaitTask(() => + { + if (OnBeforeDisconnectEvent(new GeneralEventArgs()) == EventResult.Fail) return; + result = RunTime.Controller?.Disconnect() ?? false; + }).OnCompleted(() => + { + if (result) OnSucceedDisconnectEvent(new GeneralEventArgs()); + else OnFailedDisconnectEvent(new GeneralEventArgs()); + OnAfterDisconnectEvent(new GeneralEventArgs()); + }); + } + catch (Exception e) + { + GetMessage(e.GetErrorInfo(), TimeType.None); + } + } + + /// + /// 进入房间 + /// + /// + /// + public async Task InvokeController_IntoRoom(Room room) + { + bool result = false; + + try + { + RoomEventArgs EventArgs = new(room); + if (OnBeforeIntoRoomEvent(EventArgs) == EventResult.Fail) return result; + + result = MainController is not null && await MainController.IntoRoomAsync(room); + + if (result) OnSucceedIntoRoomEvent(EventArgs); + else OnFailedIntoRoomEvent(EventArgs); + OnAfterIntoRoomEvent(EventArgs); + } + catch (Exception e) + { + GetMessage(e.GetErrorInfo(), TimeType.None); + } + + return result; + } + + /// + /// 退出房间 + /// + /// + /// + public async Task InvokeController_QuitRoom(Room room, bool isMaster) + { + bool result = false; + + try + { + RoomEventArgs EventArgs = new(room); + if (OnBeforeIntoRoomEvent(EventArgs) == EventResult.Fail) return result; + + result = MainController is not null && await MainController.QuitRoomAsync(room.Roomid, isMaster); + + if (result) OnSucceedIntoRoomEvent(EventArgs); + else OnFailedIntoRoomEvent(EventArgs); + OnAfterIntoRoomEvent(EventArgs); + } + catch (Exception e) + { + GetMessage(e.GetErrorInfo(), TimeType.None); + } + + return result; + } + + /// + /// 退出登录 + /// + /// + public async Task LogOut() + { + bool result = false; + + try + { + GeneralEventArgs EventArgs = new(); + if (OnBeforeLogoutEvent(EventArgs) == EventResult.Fail) return result; + + if (Usercfg.LoginUser.Id == 0) return result; + + if (Usercfg.InRoom.Roomid != "-1") + { + string roomid = Usercfg.InRoom.Roomid; + bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser?.Id; + MainController?.QuitRoomAsync(roomid, isMaster); + } + + result = MainController is not null && await MainController.LogOutAsync(); + + if (result) OnSucceedLogoutEvent(EventArgs); + else OnFailedLogoutEvent(EventArgs); + OnAfterLogoutEvent(EventArgs); + } + catch (Exception e) + { + GetMessage(e.GetErrorInfo(), TimeType.None); + } + + return result; + } + + #endregion } } \ No newline at end of file diff --git a/FunGame.Desktop/UI/Register/Register.cs b/FunGame.Desktop/UI/Register/Register.cs index ae30181..cb82268 100644 --- a/FunGame.Desktop/UI/Register/Register.cs +++ b/FunGame.Desktop/UI/Register/Register.cs @@ -5,7 +5,6 @@ using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library.Base; -using Milimoe.FunGame.Desktop.Library.Component; namespace Milimoe.FunGame.Desktop.UI { @@ -14,25 +13,21 @@ namespace Milimoe.FunGame.Desktop.UI public bool CheckReg { get; set; } = false; private readonly RegisterController RegController; + private readonly LoginController LoginController; public Register() { InitializeComponent(); RegController = new RegisterController(this); + LoginController = new(this); } protected override void BindEvent() { base.BindEvent(); - Disposed += Register_Disposed; SucceedReg += SucceedRegEvent; } - private void Register_Disposed(object? sender, EventArgs e) - { - RegController.Dispose(); - } - private async Task Reg_Handler() { try @@ -50,21 +45,21 @@ namespace Milimoe.FunGame.Desktop.UI { if (password != checkpassword) { - ShowMessage.ErrorMessage("两个密码不相同,请重新输入!"); + ShowMessage(ShowMessageType.Error, "两个密码不相同,请重新输入!"); CheckPasswordText.Focus(); return false; } } else { - ShowMessage.ErrorMessage("账号名长度不符合要求:最多6个中文字符或12个英文字符"); + ShowMessage(ShowMessageType.Error, "账号名长度不符合要求:最多6个中文字符或12个英文字符"); UsernameText.Focus(); return false; } } else { - ShowMessage.ErrorMessage("账号名不符合要求:不能包含特殊字符"); + ShowMessage(ShowMessageType.Error, "账号名不符合要求:不能包含特殊字符"); UsernameText.Focus(); return false; } @@ -74,30 +69,30 @@ namespace Milimoe.FunGame.Desktop.UI int length = password.Length; if (length < 6 || length > 15) // 字节范围 3~12 { - ShowMessage.ErrorMessage("密码长度不符合要求:6~15个字符数"); + ShowMessage(ShowMessageType.Error, "密码长度不符合要求:6~15个字符数"); PasswordText.Focus(); return false; } } if (username == "" || password == "" || checkpassword == "") { - ShowMessage.ErrorMessage("请将账号和密码填写完整!"); + ShowMessage(ShowMessageType.Error, "请将账号和密码填写完整!"); UsernameText.Focus(); return false; } if (email == "") { - ShowMessage.ErrorMessage("邮箱不能为空!"); + ShowMessage(ShowMessageType.Error, "邮箱不能为空!"); EmailText.Focus(); return false; } if (!NetworkUtility.IsEmail(email)) { - ShowMessage.ErrorMessage("这不是一个邮箱地址!"); + ShowMessage(ShowMessageType.Error, "这不是一个邮箱地址!"); EmailText.Focus(); return false; } - return await RegController.Reg(username, password, email); + return await RegController.RegAsync(username, password, email); } catch (Exception e) { @@ -120,7 +115,7 @@ namespace Milimoe.FunGame.Desktop.UI { string username = ((RegisterEventArgs)e).Username; string password = ((RegisterEventArgs)e).Password; - _ = LoginController.LoginAccount(username, password); + TaskUtility.StartAndAwaitTask(async () => await LoginController.LoginAccountAsync(username, password)).OnCompleted(LoginController.Dispose); RunTime.Login?.Close(); return EventResult.Success; }