diff --git a/.gitignore b/.gitignore index 47549623..440ce7a0 100644 --- a/.gitignore +++ b/.gitignore @@ -207,3 +207,7 @@ $RECYCLE.BIN/ # Windows shortcuts *.lnk + +# IDE FIles +/.idea/ +*.iml diff --git a/Interop/TranslationProvider.cs b/Interop/TranslationProvider.cs index 63281d47..c2198c1e 100644 --- a/Interop/TranslationProvider.cs +++ b/Interop/TranslationProvider.cs @@ -26,7 +26,7 @@ public string GetLanguage(string langID) { return language[langID]; } - catch (Exception e) + catch (Exception) { throw new Exception($"{langID} is not a known language-phrase"); } @@ -118,8 +118,8 @@ private void FillToEnglishDefaults() language.Add("FoundInOff", "Found in offset {0} with length {1}"); language.Add("FoundNothing", "Found nothing"); language.Add("ReplacedOff", "Replaced in offset {0}"); - language.Add("ReplacedOcc", "Replaced {0} occurences in {1} documents"); - language.Add("OccFound", "occurences found"); + language.Add("ReplacedOcc", "Replaced {0} occurrences in {1} documents"); + language.Add("OccFound", "occurrences found"); language.Add("EmptyPatt", "Empty search pattern"); language.Add("NoValidRegex", "No valid regex pattern"); language.Add("FailedCheck", "Failed to check"); @@ -149,7 +149,7 @@ private void FillToEnglishDefaults() language.Add("CloseAll", "Close all"); language.Add("Build", "Build"); language.Add("CopyPlugin", "Copy Plugins"); - language.Add("SendRCon", "Senc RCon commands"); + language.Add("SendRCon", "Send RCon commands"); language.Add("Config", "Configuration"); language.Add("Edit", "Edit"); language.Add("Undo", "Undo"); @@ -166,8 +166,8 @@ private void FillToEnglishDefaults() language.Add("Tools", "Tools"); language.Add("Options", "Options"); language.Add("ParsedIncDir", "Parsed from include directory"); - language.Add("OldAPIWeb", "Old API webside"); - language.Add("NewAPIWeb", "New API webside"); + language.Add("OldAPIWeb", "Old API website"); + language.Add("NewAPIWeb", "New API website"); language.Add("Reformatter", "Syntax reformatter"); language.Add("ReformatCurr", "Reformat current"); language.Add("ReformatAll", "Reformat all"); @@ -206,7 +206,7 @@ private void FillToEnglishDefaults() language.Add("PeopleInv", "People involved"); language.Add("Preview", "Preview"); language.Add("NewFile", "New file"); - language.Add("ConfigWrongPars", "The config was not able to parse a sourcepawn definiton."); + language.Add("ConfigWrongPars", "The config was not able to parse a sourcepawn definition."); language.Add("NoName", "no name"); language.Add("PosLen", "(pos: {0} - len: {1})"); language.Add("InheritedFrom", "inherited from"); @@ -264,7 +264,7 @@ private void FillToEnglishDefaults() language.Add("OpenIncRec", "Open Includes Recursively"); language.Add("AutoUpdate", "Search automatically for updates"); language.Add("ShowToolbar", "Show toolbar"); - language.Add("DynamicISAC", "Dynamic Autocompletition/Intellisense"); + language.Add("DynamicISAC", "Dynamic Autocomplete/Intellisense"); language.Add("DarkTheme", "Dark theme"); language.Add("ThemeColor", "Theme Color"); language.Add("LanguageStr", "Language"); @@ -272,7 +272,7 @@ private void FillToEnglishDefaults() language.Add("FontSize", "Font size"); language.Add("ScrollSpeed", "Scroll speed"); language.Add("WordWrap", "Word wrap"); - language.Add("AggIndentation", "Agressive Indentation"); + language.Add("AggIndentation", "Aggressive Indentation"); language.Add("ReformatAfterSem", "Reformatting line after semicolon"); language.Add("TabsToSpace", "Replace tabs with spaces"); language.Add("AutoCloseBrack", "Auto close brackets"); @@ -281,7 +281,7 @@ private void FillToEnglishDefaults() language.Add("ShowTabs", "Show tabs"); language.Add("IndentationSize", "Indentation size"); language.Add("FontFamily", "Font"); - language.Add("SyntaxHigh", "Syntaxhighlighting"); + language.Add("SyntaxHigh", "Syntax Highlighting"); language.Add("HighDeprecat", "Highlight deprecated (<1.7) syntax"); language.Add("Compile", "Compile"); language.Add("AutoSaveMin", "Auto save (min)"); diff --git a/Program.cs b/Program.cs index 12dfd327..2a61fce8 100644 --- a/Program.cs +++ b/Program.cs @@ -21,12 +21,12 @@ public static class Program public static OptionsControl OptionsObject; public static TranslationProvider Translations; public static Config[] Configs; - public static int SelectedConfig = 0; + public static int SelectedConfig; public static UpdateInfo UpdateStatus; - public static bool RCCKMade = false; - public static DiscordRpcClient discordClient = new DiscordRpcClient("692110664948514836"); + public static bool RCCKMade; + public static readonly DiscordRpcClient discordClient = new DiscordRpcClient("692110664948514836"); public static Timestamps discordTime = Timestamps.Now; [STAThread] @@ -46,134 +46,136 @@ public static void Main(string[] args) } }); bool mutexReserved; - using (Mutex appMutex = new Mutex(true, "SpeditGlobalMutex", out mutexReserved)) + using (new Mutex(true, "SpeditGlobalMutex", out mutexReserved)) { - if (mutexReserved) - { - bool ProgramIsNew = false; + if (mutexReserved) + { #if !DEBUG - try - { + try + { #endif - SplashScreen splashScreen = new SplashScreen("Resources/Icon256x.png"); - splashScreen.Show(false, true); - Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + SplashScreen splashScreen = new SplashScreen("Resources/Icon256x.png"); + splashScreen.Show(false, true); + Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new NullReferenceException(); #if !DEBUG - ProfileOptimization.SetProfileRoot(Environment.CurrentDirectory); - ProfileOptimization.StartProfile("Startup.Profile"); + ProfileOptimization.SetProfileRoot(Environment.CurrentDirectory); + ProfileOptimization.StartProfile("Startup.Profile"); #endif - UpdateStatus = new UpdateInfo(); - OptionsObject = OptionsControlIOObject.Load(out ProgramIsNew); - Translations = new TranslationProvider(); - Translations.LoadLanguage(OptionsObject.Language, true); - for (int i = 0; i < args.Length; ++i) - { - if (args[i].ToLowerInvariant() == "-rcck") //ReCreateCryptoKey - { - OptionsObject.ReCreateCryptoKey(); - MakeRCCKAlert(); - } - } - Configs = ConfigLoader.Load(); - for (int i = 0; i < Configs.Length; ++i) - { - if (Configs[i].Name == OptionsObject.Program_SelectedConfig) - { - Program.SelectedConfig = i; - break; - } - } - if (!OptionsObject.Program_UseHardwareAcceleration) - { - RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly; - } + UpdateStatus = new UpdateInfo(); + OptionsObject = OptionsControlIOObject.Load(out var ProgramIsNew); + Translations = new TranslationProvider(); + Translations.LoadLanguage(OptionsObject.Language, true); + for (int i = 0; i < args.Length; ++i) + { + if (args[i].ToLowerInvariant() == "-rcck") //ReCreateCryptoKey + { + OptionsObject.ReCreateCryptoKey(); + MakeRCCKAlert(); + } + } + Configs = ConfigLoader.Load(); + for (int i = 0; i < Configs.Length; ++i) + { + if (Configs[i].Name == OptionsObject.Program_SelectedConfig) + { + Program.SelectedConfig = i; + break; + } + } + if (!OptionsObject.Program_UseHardwareAcceleration) + { + RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly; + } #if !DEBUG - if (ProgramIsNew) - { - if (Translations.AvailableLanguageIDs.Length > 0) - { - splashScreen.Close(new TimeSpan(0, 0, 1)); - var languageWindow = new UI.Interop.LanguageChooserWindow(Translations.AvailableLanguageIDs, Translations.AvailableLanguages); - languageWindow.ShowDialog(); - string potentialSelectedLanguageID = languageWindow.SelectedID; - if (!string.IsNullOrWhiteSpace(potentialSelectedLanguageID)) - { - OptionsObject.Language = potentialSelectedLanguageID; - Translations.LoadLanguage(potentialSelectedLanguageID); - } - splashScreen.Show(false, true); - } - } + if (ProgramIsNew) + { + if (Translations.AvailableLanguageIDs.Length > 0) + { + splashScreen.Close(new TimeSpan(0, 0, 1)); + var languageWindow = new UI.Interop.LanguageChooserWindow(Translations.AvailableLanguageIDs, Translations.AvailableLanguages); + languageWindow.ShowDialog(); + string potentialSelectedLanguageID = languageWindow.SelectedID; + if (!string.IsNullOrWhiteSpace(potentialSelectedLanguageID)) + { + OptionsObject.Language = potentialSelectedLanguageID; + Translations.LoadLanguage(potentialSelectedLanguageID); + } + splashScreen.Show(false, true); + } + } #endif - MainWindow = new MainWindow(splashScreen); - PipeInteropServer pipeServer = new PipeInteropServer(MainWindow); - pipeServer.Start(); + MainWindow = new MainWindow(splashScreen); + PipeInteropServer pipeServer = new PipeInteropServer(MainWindow); + pipeServer.Start(); #if !DEBUG - } - catch (Exception e) - { - File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT LOADING")); - MessageBox.Show("An error occured while loading." + Environment.NewLine + "A crash report was written in the editor-directory.", - "Error while Loading", - MessageBoxButton.OK, - MessageBoxImage.Error); - Environment.Exit(Environment.ExitCode); - } + } + catch (Exception e) + { + File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT LOADING")); + MessageBox.Show("An error occured while loading." + Environment.NewLine + "A crash report was written in the editor-directory.", + "Error while Loading", + MessageBoxButton.OK, + MessageBoxImage.Error); + Environment.Exit(Environment.ExitCode); + } #endif - Application app = new Application(); + Application app = new Application(); #if !DEBUG - try - { - if (OptionsObject.Program_CheckForUpdates) - { - UpdateCheck.Check(true); - } + try + { + if (OptionsObject.Program_CheckForUpdates) + { + UpdateCheck.Check(true); + } #endif - app.Startup += App_Startup; - app.Run(MainWindow); - OptionsControlIOObject.Save(); + app.Startup += App_Startup; + app.Run(MainWindow); + OptionsControlIOObject.Save(); #if !DEBUG - } - catch (Exception e) - { - File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT MAIN")); - MessageBox.Show("An error occured." + Environment.NewLine + "A crash report was written in the editor-directory.", - "Error", - MessageBoxButton.OK, - MessageBoxImage.Error); - Environment.Exit(Environment.ExitCode); - } + } + catch (Exception e) + { + File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT MAIN")); + MessageBox.Show("An error occured." + Environment.NewLine + "A crash report was written in the editor-directory.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error); + Environment.Exit(Environment.ExitCode); + } #endif - } - else - { - try - { - StringBuilder sBuilder = new StringBuilder(); - bool addedFiles = false; - for (int i = 0; i < args.Length; ++i) - { - if (!string.IsNullOrWhiteSpace(args[i])) - { - FileInfo fInfo = new FileInfo(args[i]); - if (fInfo.Exists) - { - string ext = fInfo.Extension.ToLowerInvariant().Trim(new char[] { '.', ' ' }); - if (ext == "sp" || ext == "inc" || ext == "txt" || ext == "smx") - { - addedFiles = true; - sBuilder.Append(fInfo.FullName); - if ((i + 1) != args.Length) - { sBuilder.Append("|"); } - } - } - } - } - if (addedFiles) - { PipeInteropClient.ConnectToMasterPipeAndSendData(sBuilder.ToString()); } - } - catch (Exception) { } //dont fuck the user up with irrelevant data - } + } + else + { + try + { + StringBuilder sBuilder = new StringBuilder(); + bool addedFiles = false; + for (int i = 0; i < args.Length; ++i) + { + if (!string.IsNullOrWhiteSpace(args[i])) + { + FileInfo fInfo = new FileInfo(args[i]); + if (fInfo.Exists) + { + string ext = fInfo.Extension.ToLowerInvariant().Trim(new char[] { '.', ' ' }); + if (ext == "sp" || ext == "inc" || ext == "txt" || ext == "smx") + { + addedFiles = true; + sBuilder.Append(fInfo.FullName); + if ((i + 1) != args.Length) + { sBuilder.Append("|"); } + } + } + } + } + if (addedFiles) + { PipeInteropClient.ConnectToMasterPipeAndSendData(sBuilder.ToString()); } + } + catch (Exception) + { + // ignored + } //dont fuck the user up with irrelevant data + } } } @@ -203,8 +205,7 @@ public static void ClearUpdateFiles() private static void App_Startup(object sender, StartupEventArgs e) { - - Tuple appStyle = MahApps.Metro.ThemeManager.DetectAppStyle(Application.Current); + MahApps.Metro.ThemeManager.DetectAppStyle(Application.Current); MahApps.Metro.ThemeManager.ChangeAppStyle(Application.Current, MahApps.Metro.ThemeManager.GetAccent("Green"), MahApps.Metro.ThemeManager.GetAppTheme("BaseDark")); // or appStyle.Item1 @@ -220,11 +221,10 @@ private static string BuildExceptionString(Exception e, string SectionName) outString.AppendLine("64 bit mode: " + ((Environment.Is64BitProcess) ? "TRUE" : "FALSE")); outString.AppendLine("Dir: " + Environment.CurrentDirectory); outString.AppendLine("Working Set: " + (Environment.WorkingSet / 1024).ToString() + " kb"); - outString.AppendLine("Installed UI Culture: " + System.Globalization.CultureInfo.InstalledUICulture ?? "null"); - outString.AppendLine("Current UI Culture: " + System.Globalization.CultureInfo.CurrentUICulture ?? "null"); - outString.AppendLine("Current Culture: " + System.Globalization.CultureInfo.CurrentCulture ?? "null"); + outString.AppendLine("Installed UI Culture: " + System.Globalization.CultureInfo.InstalledUICulture); + outString.AppendLine("Current UI Culture: " + System.Globalization.CultureInfo.CurrentUICulture); + outString.AppendLine("Current Culture: " + System.Globalization.CultureInfo.CurrentCulture); outString.AppendLine(); - Exception current = e; int eNumber = 1; for (; ; ) { @@ -246,12 +246,12 @@ private static string BuildExceptionString(Exception e, string SectionName) if (e.TargetSite != null) { outString.AppendLine("Targetsite Name:"); - outString.AppendLine(e.TargetSite.Name ?? "null"); + outString.AppendLine(e.TargetSite.Name); } e = e.InnerException; eNumber++; } - return (eNumber - 1).ToString() + Environment.NewLine + outString.ToString(); + return (eNumber - 1) + Environment.NewLine + outString; } } } diff --git a/UI/Components/EditorElement.xaml.cs b/UI/Components/EditorElement.xaml.cs index a4021cfb..641f5c70 100644 --- a/UI/Components/EditorElement.xaml.cs +++ b/UI/Components/EditorElement.xaml.cs @@ -532,6 +532,7 @@ public async void Close(bool ForcedToSave = false, bool CheckSavings = true) } } Parent = null; //to prevent a ring depency which disables the GC from work + Program.MainWindow.UpdateWindowTitle(); } private void editor_TextChanged(object sender, EventArgs e) diff --git a/UI/MainWindow.xaml.cs b/UI/MainWindow.xaml.cs index 81628541..a01d308c 100644 --- a/UI/MainWindow.xaml.cs +++ b/UI/MainWindow.xaml.cs @@ -1,5 +1,4 @@ using MahApps.Metro; -using MahApps.Metro.Controls; using Spedit.UI.Components; using System; using System.Collections.Generic; @@ -9,28 +8,30 @@ using System.Windows; using System.Windows.Controls; using System.ComponentModel; +using System.Diagnostics; using System.Windows.Media.Animation; using System.Windows.Threading; using DiscordRPC; +using Spedit.Interop.Updater; using Xceed.Wpf.AvalonDock.Layout; -using Spedit.Interop.Updater; //not delete! +// using Spedit.Interop.Updater; //not delete! ? namespace Spedit.UI { /// /// Interaction logic for MainWindow.xaml /// - public partial class MainWindow : MetroWindow + public partial class MainWindow { - public List EditorsReferences = new List(); + public readonly List EditorsReferences = new List(); - Storyboard BlendOverEffect; - Storyboard FadeFindReplaceGridIn; - Storyboard FadeFindReplaceGridOut; - Storyboard EnableServerAnim; - Storyboard DisableServerAnim; + readonly Storyboard BlendOverEffect; + readonly Storyboard FadeFindReplaceGridIn; + readonly Storyboard FadeFindReplaceGridOut; + readonly Storyboard EnableServerAnim; + readonly Storyboard DisableServerAnim; - private bool FullyInitialized = false; + private readonly bool FullyInitialized; public MainWindow() { @@ -55,12 +56,12 @@ public MainWindow(SplashScreen sc) { Win_ToolBar.Height = double.NaN; } - this.MetroDialogOptions.AnimateHide = this.MetroDialogOptions.AnimateShow = false; - BlendOverEffect = (Storyboard)this.Resources["BlendOverEffect"]; - FadeFindReplaceGridIn = (Storyboard)this.Resources["FadeFindReplaceGridIn"]; - FadeFindReplaceGridOut = (Storyboard)this.Resources["FadeFindReplaceGridOut"]; - EnableServerAnim = (Storyboard)this.Resources["EnableServerAnim"]; - DisableServerAnim = (Storyboard)this.Resources["DisableServerAnim"]; + MetroDialogOptions.AnimateHide = MetroDialogOptions.AnimateShow = false; + BlendOverEffect = (Storyboard)Resources["BlendOverEffect"]; + FadeFindReplaceGridIn = (Storyboard)Resources["FadeFindReplaceGridIn"]; + FadeFindReplaceGridOut = (Storyboard)Resources["FadeFindReplaceGridOut"]; + EnableServerAnim = (Storyboard)Resources["EnableServerAnim"]; + DisableServerAnim = (Storyboard)Resources["DisableServerAnim"]; ChangeObjectBrowserToDirectory(Program.OptionsObject.Program_ObjectBrowserDirectory); Language_Translate(true); #if DEBUG @@ -68,9 +69,9 @@ public MainWindow(SplashScreen sc) #endif if (Program.OptionsObject.LastOpenFiles != null) { - for (int i = 0; i < Program.OptionsObject.LastOpenFiles.Length; ++i) + foreach (var file in Program.OptionsObject.LastOpenFiles) { - TryLoadSourceFile(Program.OptionsObject.LastOpenFiles[i], false, true, false); + TryLoadSourceFile(file, false); } } string[] args = Environment.GetCommandLineArgs(); @@ -91,7 +92,7 @@ public bool TryLoadSourceFile(string filePath, bool UseBlendoverEffect = true, b FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { - string extension = fileInfo.Extension.ToLowerInvariant().Trim(new char[] { '.', ' ' }); + string extension = fileInfo.Extension.ToLowerInvariant().Trim('.', ' '); if (extension == "sp" || extension == "inc" || extension == "txt" || extension == "cfg" || extension == "ini") { string finalPath = fileInfo.FullName; @@ -106,14 +107,14 @@ public bool TryLoadSourceFile(string filePath, bool UseBlendoverEffect = true, b EditorElement[] editors = GetAllEditorElements(); if (editors != null) { - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - if (editors[i].FullFilePath == finalPath) + if (editor.FullFilePath == finalPath) { - if (SelectMe) - { - editors[i].Parent.IsSelected = true; - } + if (SelectMe) + { + editor.Parent.IsSelected = true; + } return true; } } @@ -135,18 +136,20 @@ public bool TryLoadSourceFile(string filePath, bool UseBlendoverEffect = true, b { fileName = fileName + ".inc"; } - fileName = System.IO.Path.Combine(fileInfo.DirectoryName, fileName); + fileName = Path.Combine(fileInfo.DirectoryName ?? throw new NullReferenceException(), fileName); TryLoadSourceFile(fileName, false, Program.OptionsObject.Program_OpenIncludesRecursively); } - catch (Exception) { } + catch (Exception) + { + // ignored + } } } } } else if (extension == "smx") { - LayoutDocument layoutDocument = new LayoutDocument(); - layoutDocument.Title = "DASM: " + fileInfo.Name; + LayoutDocument layoutDocument = new LayoutDocument {Title = "DASM: " + fileInfo.Name}; DASMElement dasmElement = new DASMElement(fileInfo); layoutDocument.Content = dasmElement; DockingPane.Children.Add(layoutDocument); @@ -161,14 +164,12 @@ public bool TryLoadSourceFile(string filePath, bool UseBlendoverEffect = true, b return false; } - public void AddEditorElement(string filePath, string name, bool SelectMe) + private void AddEditorElement(string filePath, string name, bool SelectMe) { - LayoutDocument layoutDocument = new LayoutDocument(); - layoutDocument.Title = name; + LayoutDocument layoutDocument = new LayoutDocument {Title = name}; layoutDocument.Closing += layoutDocument_Closing; layoutDocument.ToolTip = filePath; - EditorElement editor = new EditorElement(filePath); - editor.Parent = layoutDocument; + EditorElement editor = new EditorElement(filePath) {Parent = layoutDocument}; layoutDocument.Content = editor; EditorsReferences.Add(editor); DockingPane.Children.Add(layoutDocument); @@ -200,72 +201,53 @@ private void DockingManager_ActiveContentChanged(object sender, EventArgs e) private void DockingManager_DocumentClosing(object sender, Xceed.Wpf.AvalonDock.DocumentClosingEventArgs e) { - if (e.Document.Content is EditorElement) - { - ((EditorElement)e.Document.Content).Close(); - } + (e.Document.Content as EditorElement)?.Close(); UpdateWindowTitle(); } - private void layoutDocument_Closing(object sender, System.ComponentModel.CancelEventArgs e) + private void layoutDocument_Closing(object sender, CancelEventArgs e) { e.Cancel = true; } - private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) + private void MetroWindow_Closing(object sender, CancelEventArgs e) { - if (backgroundParserThread != null) - { - backgroundParserThread.Abort(); - } - if (parseDistributorTimer != null) - { - parseDistributorTimer.Stop(); - } - if (ServerCheckThread != null) - { - ServerCheckThread.Abort(); //a join would not work, so we have to be..forcefully... - } + backgroundParserThread?.Abort(); + parseDistributorTimer?.Stop(); + ServerCheckThread?.Abort(); //a join would not work, so we have to be..forcefully... List lastOpenFiles = new List(); EditorElement[] editors = GetAllEditorElements(); bool? SaveUnsaved = null; if (editors != null) - { - for (int i = 0; i < editors.Length; ++i) - { - if (File.Exists(editors[i].FullFilePath)) - { - lastOpenFiles.Add(editors[i].FullFilePath); - if (editors[i].NeedsSave) - { - if (SaveUnsaved == null) - { + { + foreach (var editor in editors) + { + if (File.Exists(editor.FullFilePath)) + { + lastOpenFiles.Add(editor.FullFilePath); + if (editor.NeedsSave) + { + if (SaveUnsaved == null) + { var result = MessageBox.Show(this, Program.Translations.GetLanguage("SavingUFiles"), Program.Translations.GetLanguage("Saving"), MessageBoxButton.YesNo, MessageBoxImage.Question); - if (result == MessageBoxResult.Yes) - { - SaveUnsaved = true; - } - else - { - SaveUnsaved = false; - } - } - if (SaveUnsaved.Value) - { - editors[i].Close(true, true); - } - else - { - editors[i].Close(false, false); - } - } - else - { - editors[i].Close(false, false); - } - } - } - } + SaveUnsaved = result == MessageBoxResult.Yes; + } + if (SaveUnsaved.Value) + { + editor.Close(true); + } + else + { + editor.Close(false, false); + } + } + else + { + editor.Close(false, false); + } + } + } + } Program.OptionsObject.LastOpenFiles = lastOpenFiles.ToArray(); #if !DEBUG if (Program.UpdateStatus.IsAvailable) @@ -281,8 +263,9 @@ private void MetroWindow_Drop(object sender, DragEventArgs e) if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); - this.Activate(); - this.Focus(); + Activate(); + Focus(); + Debug.Assert(files != null, nameof(files) + " != null"); for (int i = 0; i < files.Length; ++i) { TryLoadSourceFile(files[i], (i == 0), true, (i == 0)); @@ -290,10 +273,10 @@ private void MetroWindow_Drop(object sender, DragEventArgs e) } } - public static void ProcessUITasks() + private static void ProcessUITasks() { DispatcherFrame frame = new DispatcherFrame(); - Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(object parameter) + Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate { frame.Continue = false; return null; @@ -314,17 +297,17 @@ private void ErrorResultGrid_SelectionChanged(object sender, SelectionChangedEve { return; } - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - if (editors[i].FullFilePath == fileName) + if (editor.FullFilePath == fileName) { - ((LayoutDocument)editors[i].Parent).IsSelected = true; + editor.Parent.IsSelected = true; int line = GetLineInteger(row.line); - if (line > 0 && line <= editors[i].editor.LineCount) + if (line > 0 && line <= editor.editor.LineCount) { - var lineObj = editors[i].editor.Document.Lines[line - 1]; - editors[i].editor.ScrollToLine(line - 1); - editors[i].editor.Select(lineObj.Offset, lineObj.Length); + var lineObj = editor.editor.Document.Lines[line - 1]; + editor.editor.ScrollToLine(line - 1); + editor.editor.Select(lineObj.Offset, lineObj.Length); } } } @@ -343,7 +326,7 @@ private void EditorObjectBrowserGridRow_WidthChanged(object sender, EventArgs e) } } - private void UpdateWindowTitle() + public void UpdateWindowTitle() { EditorElement ee = GetCurrentEditorElement(); string outString; @@ -368,7 +351,7 @@ private void UpdateWindowTitle() { outString = $"{outString} ({Program.Translations.GetLanguage("ServerRunning")})"; } - this.Title = outString; + Title = outString; } private int GetLineInteger(string lineStr) @@ -385,8 +368,8 @@ private int GetLineInteger(string lineStr) break; } } - int line; - if (int.TryParse(lineStr.Substring(0, end + 1), out line)) + + if (int.TryParse(lineStr.Substring(0, end + 1), out var line)) { return line; } diff --git a/UI/MainWindowBackgroundParser.cs b/UI/MainWindowBackgroundParser.cs index 83f8ec02..6addf8c2 100644 --- a/UI/MainWindowBackgroundParser.cs +++ b/UI/MainWindowBackgroundParser.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Diagnostics; using SourcepawnCondenser; using SourcepawnCondenser.SourcemodDefinition; using System.Threading; @@ -13,14 +10,14 @@ namespace Spedit.UI { public partial class MainWindow { - public ulong currentSMDefUID = 0; + private ulong currentSMDefUID; Thread backgroundParserThread; - SMDefinition currentSMDef = null; + SMDefinition currentSMDef; System.Timers.Timer parseDistributorTimer; - public void StartBackgroundParserThread() + private void StartBackgroundParserThread() { - backgroundParserThread = new Thread(new ThreadStart(BackgroundParser_Worker)); + backgroundParserThread = new Thread(BackgroundParser_Worker); backgroundParserThread.Start(); parseDistributorTimer = new System.Timers.Timer(500.0); parseDistributorTimer.Elapsed += ParseDistributorTimer_Elapsed; @@ -32,18 +29,21 @@ private void ParseDistributorTimer_Elapsed(object sender, ElapsedEventArgs args) if (currentSMDefUID == 0) { return; } EditorElement[] ee = null; EditorElement ce = null; - this.Dispatcher.Invoke(() => + Dispatcher?.Invoke(() => { ee = GetAllEditorElements(); ce = GetCurrentEditorElement(); }); if (ee == null || ce == null) { return; } //this can happen! + + Debug.Assert(ee != null, nameof(ee) + " != null"); foreach (var e in ee) { - if (e.LastSMDefUpdateUID < currentSMDefUID) //wants an update of the SMDefintion + if (e.LastSMDefUpdateUID < currentSMDefUID) //wants an update of the SMDefinition { if (e == ce) { + Debug.Assert(ce != null, nameof(ce) + " != null"); if (ce.ISAC_Open) { continue; @@ -54,10 +54,10 @@ private void ParseDistributorTimer_Elapsed(object sender, ElapsedEventArgs args) } } } - - public SMFunction[] currentSMFunctions; - public ACNode[] currentACNodes; - public ISNode[] currentISNodes; + + private SMFunction[] currentSMFunctions; + private ACNode[] currentACNodes; + private ISNode[] currentISNodes; private void BackgroundParser_Worker() { @@ -75,8 +75,7 @@ private void BackgroundParser_Worker() FileInfo fInfo = new FileInfo(ee[i].FullFilePath); if (fInfo.Extension.Trim('.').ToLowerInvariant() == "inc") { - var condenser = new Condenser(File.ReadAllText(fInfo.FullName), fInfo.Name); - definitions[i] = ((new Condenser(File.ReadAllText(fInfo.FullName), fInfo.Name)).Condense()); + definitions[i] = (new Condenser(File.ReadAllText(fInfo.FullName), fInfo.Name).Condense()); } } currentSMDef = (Program.Configs[Program.SelectedConfig].GetSMDef()).ProduceTemporaryExpandedDefinition(definitions); @@ -88,6 +87,7 @@ private void BackgroundParser_Worker() } Thread.Sleep(5000); } + // ReSharper disable once FunctionNeverReturns } } } diff --git a/UI/MainWindowCommands.cs b/UI/MainWindowCommands.cs index 9760549b..3927929b 100644 --- a/UI/MainWindowCommands.cs +++ b/UI/MainWindowCommands.cs @@ -1,10 +1,10 @@ -using MahApps.Metro.Controls.Dialogs; +using System.Diagnostics; +using MahApps.Metro.Controls.Dialogs; using Microsoft.Win32; using Spedit.UI.Components; using Spedit.UI.Windows; using Spedit.Utils.SPSyntaxTidy; using System.Text; -using System.Threading.Tasks; using Lysis; using System.IO; @@ -12,21 +12,15 @@ namespace Spedit.UI { public partial class MainWindow { - public EditorElement GetCurrentEditorElement() + private EditorElement GetCurrentEditorElement() { EditorElement outElement = null; - if (DockingPane.SelectedContent != null) + if (DockingPane.SelectedContent?.Content != null) { - if (DockingPane.SelectedContent.Content != null) + var possElement = DockingManager.ActiveContent; + if (possElement is EditorElement element) { - var possElement = DockingManager.ActiveContent; - if (possElement != null) - { - if (possElement is EditorElement) - { - outElement = (EditorElement)possElement; - } - } + outElement = element; } } return outElement; @@ -34,11 +28,7 @@ public EditorElement GetCurrentEditorElement() public EditorElement[] GetAllEditorElements() { - if (this.EditorsReferences.Count < 1) - { - return null; - } - return this.EditorsReferences.ToArray(); + return EditorsReferences.Count < 1 ? null : EditorsReferences.ToArray(); } private void Command_New() @@ -85,17 +75,20 @@ private void Command_SaveAs() EditorElement ee = GetCurrentEditorElement(); if (ee != null) { - SaveFileDialog sfd = new SaveFileDialog() { AddExtension = true, Filter = @"Sourcepawn Files (*.sp *.inc)|*.sp;*.inc|All Files (*.*)|*.*", OverwritePrompt = true, Title = Program.Translations.GetLanguage("SaveFileAs") }; - sfd.FileName = ee.Parent.Title.Trim(new char[] { '*' }); + SaveFileDialog sfd = new SaveFileDialog + { + AddExtension = true, + Filter = @"Sourcepawn Files (*.sp *.inc)|*.sp;*.inc|All Files (*.*)|*.*", + OverwritePrompt = true, + Title = Program.Translations.GetLanguage("SaveFileAs"), + FileName = ee.Parent.Title.Trim('*') + }; var result = sfd.ShowDialog(this); - if (result.Value) + if (result.Value && !string.IsNullOrWhiteSpace(sfd.FileName)) { - if (!string.IsNullOrWhiteSpace(sfd.FileName)) - { - ee.FullFilePath = sfd.FileName; - ee.Save(true); - BlendOverEffect.Begin(); - } + ee.FullFilePath = sfd.FileName; + ee.Save(true); + BlendOverEffect.Begin(); } } } @@ -109,10 +102,11 @@ private void Command_SaveAll() } if (editors.Length > 0) { - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - editors[i].Save(); + editor.Save(); } + BlendOverEffect.Begin(); } } @@ -120,10 +114,7 @@ private void Command_SaveAll() private void Command_Close() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.Close(); - } + ee?.Close(); } private async void Command_CloseAll() @@ -136,9 +127,9 @@ private async void Command_CloseAll() if (editors.Length > 0) { bool UnsavedEditorsExisting = false; - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - UnsavedEditorsExisting |= editors[i].NeedsSave; + UnsavedEditorsExisting |= editor.NeedsSave; } bool ForceSave = false; if (UnsavedEditorsExisting) @@ -147,9 +138,9 @@ private async void Command_CloseAll() for (int i = 0; i < editors.Length; ++i) { if (i == 0) - { str.Append(editors[i].Parent.Title.Trim(new char[] { '*' })); } + { str.Append(editors[i].Parent.Title.Trim('*')); } else - { str.AppendLine(editors[i].Parent.Title.Trim(new char[] { '*' })); } + { str.AppendLine(editors[i].Parent.Title.Trim('*')); } } var Result = await this.ShowMessageAsync(Program.Translations.GetLanguage("SaveFollow"), str.ToString(), MessageDialogStyle.AffirmativeAndNegative, this.MetroDialogOptions); if (Result == MessageDialogResult.Affirmative) @@ -157,9 +148,9 @@ private async void Command_CloseAll() ForceSave = true; } } - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - editors[i].Close(ForceSave, ForceSave); + editor.Close(ForceSave, ForceSave); } } } @@ -191,42 +182,30 @@ private void Command_Redo() private void Command_Cut() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.editor.Cut(); - } + ee?.editor.Cut(); } private void Command_Copy() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.editor.Copy(); - } + ee?.editor.Copy(); } private void Command_Paste() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.editor.Paste(); - } + ee?.editor.Paste(); } private void Command_FlushFoldingState(bool state) { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) + if (ee?.foldingManager != null) { - if (ee.foldingManager != null) + var foldings = ee.foldingManager.AllFoldings; + foreach (var folding in foldings) { - var foldings = ee.foldingManager.AllFoldings; - foreach (var folding in foldings) - { - folding.IsFolded = state; - } + folding.IsFolded = state; } } } @@ -234,44 +213,26 @@ private void Command_FlushFoldingState(bool state) private void Command_JumpTo() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.ToggleJumpGrid(); - } + ee?.ToggleJumpGrid(); } private void Command_SelectAll() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.editor.SelectAll(); - } + ee?.editor.SelectAll(); } private void Command_ToggleCommentLine() { EditorElement ee = GetCurrentEditorElement(); - if (ee != null) - { - ee.ToggleCommentOnLine(); - } - } + ee?.ToggleCommentOnLine(); + } private void Command_TidyCode(bool All) { - EditorElement[] editors; - if (All) - { - editors = GetAllEditorElements(); - } - else - { - editors = new EditorElement[] { GetCurrentEditorElement() }; - } - for (int i = 0; i < editors.Length; ++i) + var editors = All ? GetAllEditorElements() : new[] { GetCurrentEditorElement() }; + foreach (var ee in editors) { - EditorElement ee = editors[i]; if (ee != null) { ee.editor.Document.BeginUpdate(); @@ -284,30 +245,30 @@ private void Command_TidyCode(bool All) private async void Command_Decompile(MainWindow win) { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Filter = "Sourcepawn Plugins (*.smx)|*.smx"; - ofd.Title = Program.Translations.GetLanguage("ChDecomp"); + OpenFileDialog ofd = new OpenFileDialog + { + Filter = "Sourcepawn Plugins (*.smx)|*.smx", Title = Program.Translations.GetLanguage("ChDecomp") + }; var result = ofd.ShowDialog(); - if (result.Value) + + Debug.Assert(result != null, nameof(result) + " != null"); + if (result.Value && !string.IsNullOrWhiteSpace(ofd.FileName)) { - if (!string.IsNullOrWhiteSpace(ofd.FileName)) + FileInfo fInfo = new FileInfo(ofd.FileName); + if (fInfo.Exists) { - FileInfo fInfo = new FileInfo(ofd.FileName); - if (fInfo.Exists) + ProgressDialogController task = null; + if (win != null) + { + task = await this.ShowProgressAsync(Program.Translations.GetLanguage("Decompiling"), fInfo.FullName, false, this.MetroDialogOptions); + MainWindow.ProcessUITasks(); + } + string destFile = fInfo.FullName + ".sp"; + File.WriteAllText(destFile, LysisDecompiler.Analyze(fInfo), Encoding.UTF8); + TryLoadSourceFile(destFile, true, false); + if (task != null) { - ProgressDialogController task = null; - if (win != null) - { - task = await this.ShowProgressAsync(Program.Translations.GetLanguage("Decompiling"), fInfo.FullName, false, this.MetroDialogOptions); - MainWindow.ProcessUITasks(); - } - string destFile = fInfo.FullName + ".sp"; - File.WriteAllText(destFile, LysisDecompiler.Analyze(fInfo), Encoding.UTF8); - TryLoadSourceFile(destFile, true, false); - if (task != null) - { - await task.CloseAsync(); - } + await task.CloseAsync(); } } } diff --git a/UI/MainWindowConfigHandler.cs b/UI/MainWindowConfigHandler.cs index 8439348e..ee816c5f 100644 --- a/UI/MainWindowConfigHandler.cs +++ b/UI/MainWindowConfigHandler.cs @@ -12,8 +12,10 @@ public void FillConfigMenu() ConfigMenu.Items.Clear(); for (int i = 0; i < Program.Configs.Length; ++i) { - MenuItem item = new MenuItem() { Header = Program.Configs[i].Name, IsCheckable = true }; - item.IsChecked = (i == Program.SelectedConfig); + MenuItem item = new MenuItem + { + Header = Program.Configs[i].Name, IsCheckable = true, IsChecked = (i == Program.SelectedConfig) + }; item.Click += item_Click; ConfigMenu.Items.Add(item); } @@ -35,12 +37,6 @@ private void item_Click(object sender, RoutedEventArgs e) ChangeConfig(name); } - private void ConfigSelected(object sender, RoutedEventArgs e) - { - MenuItem item = (MenuItem)sender; - string Name = (string)item.Header; - } - public void ChangeConfig(int index) { if (index < 0 || index >= Program.Configs.Length) @@ -48,25 +44,26 @@ public void ChangeConfig(int index) return; } Program.Configs[index].LoadSMDef(); - string Name = Program.Configs[index].Name; + string name = Program.Configs[index].Name; for (int i = 0; i < ConfigMenu.Items.Count - 2; ++i) { - ((MenuItem)ConfigMenu.Items[i]).IsChecked = (Name == (string)(((MenuItem)ConfigMenu.Items[i]).Header)); + ((MenuItem)ConfigMenu.Items[i]).IsChecked = (name == (string)(((MenuItem)ConfigMenu.Items[i]).Header)); } Program.SelectedConfig = index; Program.OptionsObject.Program_SelectedConfig = Program.Configs[Program.SelectedConfig].Name; EditorElement[] editors = GetAllEditorElements(); if (editors != null) - { - for (int i = 0; i < editors.Length; ++i) - { - editors[i].LoadAutoCompletes(); - editors[i].editor.SyntaxHighlighting = new AeonEditorHighlighting(); - editors[i].InvalidateVisual(); - } - } + { + foreach (var editor in editors) + { + editor.LoadAutoCompletes(); + editor.editor.SyntaxHighlighting = new AeonEditorHighlighting(); + editor.InvalidateVisual(); + } + } } - public void ChangeConfig(string name) + + private void ChangeConfig(string name) { for (int i = 0; i < Program.Configs.Length; ++i) { diff --git a/UI/MainWindowFindReplaceHandler.cs b/UI/MainWindowFindReplaceHandler.cs index 330d7855..25fcde3c 100644 --- a/UI/MainWindowFindReplaceHandler.cs +++ b/UI/MainWindowFindReplaceHandler.cs @@ -1,18 +1,18 @@ using Spedit.UI.Components; using System; +using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Input; -using Xceed.Wpf.AvalonDock.Layout; namespace Spedit.UI { public partial class MainWindow { - bool IsSearchFieldOpen = false; + bool IsSearchFieldOpen; - public void ToggleSearchField() + private void ToggleSearchField() { EditorElement ee = GetCurrentEditorElement(); if (IsSearchFieldOpen) @@ -114,7 +114,7 @@ private void ReplaceBoxKeyUp(object sender, KeyEventArgs e) } private void FindReplaceGrid_KeyDown(object sender, KeyEventArgs e) { - if (e.Key == System.Windows.Input.Key.Escape) + if (e.Key == Key.Escape) { ToggleSearchField(); } @@ -122,8 +122,7 @@ private void FindReplaceGrid_KeyDown(object sender, KeyEventArgs e) private void Search() { - int editorIndex = 0; - EditorElement[] editors = GetEditorElementsForFRAction(out editorIndex); + EditorElement[] editors = GetEditorElementsForFRAction(out var editorIndex); if (editors == null) { return; } if (editors.Length < 1) { return; } if (editors[0] == null) { return; } @@ -145,14 +144,9 @@ private void Search() } else if (i == (editors.Length + editorIndex)) { - if (startFileCaretOffset == 0) - { - searchText = string.Empty; - } - else - { - searchText = editors[index].editor.Text.Substring(0, startFileCaretOffset); - } + searchText = startFileCaretOffset == 0 ? + string.Empty : + editors[index].editor.Text.Substring(0, startFileCaretOffset); } else { @@ -161,20 +155,17 @@ private void Search() if (!string.IsNullOrWhiteSpace(searchText)) { Match m = regex.Match(searchText); - if (m != null) //can this happen? + if (m.Success) //can this happen? { - if (m.Success) - { - foundOccurence = true; - ((LayoutDocument)editors[index].Parent).IsSelected = true; - editors[index].editor.CaretOffset = m.Index + addToOffset + m.Length; - editors[index].editor.Select(m.Index + addToOffset, m.Length); - var location = editors[index].editor.Document.GetLocation(m.Index + addToOffset); - editors[index].editor.ScrollTo(location.Line, location.Column); - //FindResultBlock.Text = "Found in offset " + (m.Index + addToOffset).ToString() + " with length " + m.Length.ToString(); - FindResultBlock.Text = string.Format(Program.Translations.GetLanguage("FoundInOff"), m.Index + addToOffset, m.Length); - break; - } + foundOccurence = true; + editors[index].Parent.IsSelected = true; + editors[index].editor.CaretOffset = m.Index + addToOffset + m.Length; + editors[index].editor.Select(m.Index + addToOffset, m.Length); + var location = editors[index].editor.Document.GetLocation(m.Index + addToOffset); + editors[index].editor.ScrollTo(location.Line, location.Column); + //FindResultBlock.Text = "Found in offset " + (m.Index + addToOffset).ToString() + " with length " + m.Length.ToString(); + FindResultBlock.Text = string.Format(Program.Translations.GetLanguage("FoundInOff"), m.Index + addToOffset, m.Length); + break; } } } @@ -186,8 +177,7 @@ private void Search() private void Replace() { - int editorIndex = 0; - EditorElement[] editors = GetEditorElementsForFRAction(out editorIndex); + EditorElement[] editors = GetEditorElementsForFRAction(out var editorIndex); if (editors == null) { return; } if (editors.Length < 1) { return; } if (editors[0] == null) { return; } @@ -210,14 +200,9 @@ private void Replace() } else if (i == (editors.Length + editorIndex)) { - if (startFileCaretOffset == 0) - { - searchText = string.Empty; - } - else - { - searchText = editors[index].editor.Text.Substring(0, startFileCaretOffset); - } + searchText = startFileCaretOffset == 0 ? + string.Empty : + editors[index].editor.Text.Substring(0, startFileCaretOffset); } else { @@ -226,21 +211,18 @@ private void Replace() if (!string.IsNullOrWhiteSpace(searchText)) { Match m = regex.Match(searchText); - if (m != null) + if (m.Success) { - if (m.Success) - { - foundOccurence = true; - ((LayoutDocument)editors[index].Parent).IsSelected = true; - string result = m.Result(replaceString); - editors[index].editor.Document.Replace(m.Index + addToOffset, m.Length, result); - editors[index].editor.CaretOffset = m.Index + addToOffset + result.Length; - editors[index].editor.Select(m.Index + addToOffset, result.Length); - var location = editors[index].editor.Document.GetLocation(m.Index + addToOffset); - editors[index].editor.ScrollTo(location.Line, location.Column); - FindResultBlock.Text = string.Format(Program.Translations.GetLanguage("ReplacedOff"), MinHeight + addToOffset); - break; - } + foundOccurence = true; + editors[index].Parent.IsSelected = true; + string result = m.Result(replaceString); + editors[index].editor.Document.Replace(m.Index + addToOffset, m.Length, result); + editors[index].editor.CaretOffset = m.Index + addToOffset + result.Length; + editors[index].editor.Select(m.Index + addToOffset, result.Length); + var location = editors[index].editor.Document.GetLocation(m.Index + addToOffset); + editors[index].editor.ScrollTo(location.Line, location.Column); + FindResultBlock.Text = string.Format(Program.Translations.GetLanguage("ReplacedOff"), MinHeight + addToOffset); + break; } } } @@ -252,31 +234,27 @@ private void Replace() private void ReplaceAll() { - int editorIndex = 0; - EditorElement[] editors = GetEditorElementsForFRAction(out editorIndex); + EditorElement[] editors = GetEditorElementsForFRAction(out _); if (editors == null) { return; } if (editors.Length < 1) { return; } if (editors[0] == null) { return; } Regex regex = GetSearchRegex(); if (regex == null) { return; } - int count = 0; - int fileCount = 0; + string replaceString = ReplaceBox.Text; - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - MatchCollection mc = regex.Matches(editors[i].editor.Text); + MatchCollection mc = regex.Matches(editor.editor.Text); if (mc.Count > 0) { - fileCount++; - count += mc.Count; - editors[i].editor.BeginChange(); + editor.editor.BeginChange(); for (int j = mc.Count - 1; j >= 0; --j) { string replace = mc[j].Result(replaceString); - editors[i].editor.Document.Replace(mc[j].Index, mc[j].Length, replace); + editor.editor.Document.Replace(mc[j].Index, mc[j].Length, replace); } - editors[i].editor.EndChange(); - editors[i].NeedsSave = true; + editor.editor.EndChange(); + editor.NeedsSave = true; } } //FindResultBlock.Text = "Replaced " + count.ToString() + " occurences in " + fileCount.ToString() + " documents"; @@ -285,17 +263,16 @@ private void ReplaceAll() private void Count() { - int editorIndex = 0; - EditorElement[] editors = GetEditorElementsForFRAction(out editorIndex); + EditorElement[] editors = GetEditorElementsForFRAction(out _); if (editors == null) { return; } if (editors.Length < 1) { return; } if (editors[0] == null) { return; } Regex regex = GetSearchRegex(); if (regex == null) { return; } int count = 0; - for (int i = 0; i < editors.Length; ++i) + foreach (var editor in editors) { - MatchCollection mc = regex.Matches(editors[i].editor.Text); + MatchCollection mc = regex.Matches(editor.editor.Text); count += mc.Count; } FindResultBlock.Text = count.ToString() + Program.Translations.GetLanguage("OccFound"); @@ -311,60 +288,70 @@ private Regex GetSearchRegex() } Regex regex; RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant; + Debug.Assert(CCBox.IsChecked != null, "CCBox.IsChecked != null"); + Debug.Assert(NSearch_RButton.IsChecked != null, "NSearch_RButton.IsChecked != null"); + + if (!CCBox.IsChecked.Value) { regexOptions |= RegexOptions.IgnoreCase; } + if (NSearch_RButton.IsChecked.Value) { regex = new Regex(Regex.Escape(findString), regexOptions); } - else if (WSearch_RButton.IsChecked.Value) - { - regex = new Regex("\\b" + Regex.Escape(findString) + "\\b", regexOptions); - } - else if (ASearch_RButton.IsChecked.Value) - { - findString = findString.Replace("\\t", "\t").Replace("\\r", "\r").Replace("\\n", "\n"); - Regex rx = new Regex(@"\\[uUxX]([0-9A-F]{4})"); - findString = rx.Replace(findString, delegate(Match match) { return ((char)Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); }); - regex = new Regex(Regex.Escape(findString), regexOptions); - } - else //if (RSearch_RButton.IsChecked.Value) + else { - regexOptions |= RegexOptions.Multiline; - if (MLRBox.IsChecked.Value) - { regexOptions |= RegexOptions.Singleline; } //paradox, isn't it? ^^ - try + Debug.Assert(WSearch_RButton.IsChecked != null, "WSearch_RButton.IsChecked != null"); + if (WSearch_RButton.IsChecked.Value) + { + regex = new Regex("\\b" + Regex.Escape(findString) + "\\b", regexOptions); + } + else { - regex = new Regex(findString, regexOptions); + Debug.Assert(ASearch_RButton.IsChecked != null, "ASearch_RButton.IsChecked != null"); + if (ASearch_RButton.IsChecked.Value) + { + findString = findString.Replace("\\t", "\t").Replace("\\r", "\r").Replace("\\n", "\n"); + Regex rx = new Regex(@"\\[uUxX]([0-9A-F]{4})"); + findString = rx.Replace(findString, + match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString()); + regex = new Regex(Regex.Escape(findString), regexOptions); + } + else //if (RSearch_RButton.IsChecked.Value) + { + regexOptions |= RegexOptions.Multiline; + Debug.Assert(MLRBox.IsChecked != null, "MLRBox.IsChecked != null"); + if (MLRBox.IsChecked.Value) + { regexOptions |= RegexOptions.Singleline; } //paradox, isn't it? ^^ + try + { + regex = new Regex(findString, regexOptions); + } + catch (Exception) { FindResultBlock.Text = Program.Translations.GetLanguage("NoValidRegex"); return null; } + } } - catch (Exception) { FindResultBlock.Text = Program.Translations.GetLanguage("NoValidRegex"); return null; } } + return regex; } private EditorElement[] GetEditorElementsForFRAction(out int editorIndex) { int editorStartIndex = 0; - EditorElement[] editors = null; + EditorElement[] editors; if (FindDestinies.SelectedIndex == 0) - { editors = new EditorElement[] { GetCurrentEditorElement() }; } + { editors = new[] { GetCurrentEditorElement() }; } else { editors = GetAllEditorElements(); - if (DockingPane.SelectedContent != null) + object checkElement = DockingPane.SelectedContent?.Content; + if (checkElement is EditorElement) { - object checkElement = DockingPane.SelectedContent.Content; - if (checkElement != null) + for (int i = 0; i < editors.Length; ++i) { - if (checkElement is EditorElement) + if (editors[i] == checkElement) { - for (int i = 0; i < editors.Length; ++i) - { - if (editors[i] == checkElement) - { - editorStartIndex = i; - } - } + editorStartIndex = i; } } } diff --git a/UI/MainWindowMenuHandler.cs b/UI/MainWindowMenuHandler.cs index b8c5d70b..fdbeaa2b 100644 --- a/UI/MainWindowMenuHandler.cs +++ b/UI/MainWindowMenuHandler.cs @@ -1,5 +1,4 @@ -using MahApps.Metro.Controls; -using MahApps.Metro.Controls.Dialogs; +using MahApps.Metro.Controls.Dialogs; using Spedit.Interop.Updater; using Spedit.UI.Components; using Spedit.UI.Windows; @@ -11,7 +10,7 @@ namespace Spedit.UI { - public partial class MainWindow : MetroWindow + public partial class MainWindow { private void FileMenu_Open(object sender, RoutedEventArgs e) { @@ -69,11 +68,11 @@ private void EditMenu_Open(object sender, RoutedEventArgs e) MenuItem menu = (MenuItem)sender; if (ee == null) { - for (int i = 0; i < menu.Items.Count; ++i) + foreach (var item in menu.Items) { - if (menu.Items[i] is MenuItem) + if (item is MenuItem menuItem) { - ((MenuItem)menu.Items[i]).IsEnabled = false; + menuItem.IsEnabled = false; } } } @@ -249,7 +248,7 @@ private void UpdateCheck_Click(object sender, RoutedEventArgs e) } else { - this.ShowMessageAsync(Program.Translations.GetLanguage("VersUpToDate"), string.Format(Program.Translations.GetLanguage("VersionYour"), Assembly.GetEntryAssembly().GetName().Version.ToString()) + this.ShowMessageAsync(Program.Translations.GetLanguage("VersUpToDate"), string.Format(Program.Translations.GetLanguage("VersionYour"), Assembly.GetEntryAssembly()?.GetName().Version) , MessageDialogStyle.Affirmative, this.MetroDialogOptions); } } @@ -264,7 +263,7 @@ private void MenuButton_Compile(object sender, RoutedEventArgs e) } else { - Compile_SPScripts(true); + Compile_SPScripts(); } } @@ -273,7 +272,7 @@ private void MenuButton_Action(object sender, RoutedEventArgs e) int selected = CActionButton.SelectedIndex; if (selected == 0) { - Copy_Plugins(false); + Copy_Plugins(); } else if (selected == 1) { diff --git a/UI/MainWindowObjectBrowser.cs b/UI/MainWindowObjectBrowser.cs index 7baca1bb..8ca3e238 100644 --- a/UI/MainWindowObjectBrowser.cs +++ b/UI/MainWindowObjectBrowser.cs @@ -1,7 +1,4 @@ -using MahApps.Metro.Controls; -using MahApps.Metro.Controls.Dialogs; -using Spedit.UI.Components; -using Spedit.Utils; +using Spedit.UI.Components; using System; using System.Collections.Generic; using System.Diagnostics; @@ -9,35 +6,34 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Media.Imaging; -using System.Collections.ObjectModel; namespace Spedit.UI { - public partial class MainWindow : MetroWindow + public partial class MainWindow { private string CurrentObjectBrowserDirectory = string.Empty; private void TreeViewOBItem_Expanded(object sender, RoutedEventArgs e) { object source = e.Source; - if (source is TreeViewItem) + if (!(source is TreeViewItem)) { - TreeViewItem item = (TreeViewItem)source; - ObjectBrowserTag itemInfo = (ObjectBrowserTag)item.Tag; - if (itemInfo.Kind == ObjectBrowserItemKind.Directory) + return; + } + TreeViewItem item = (TreeViewItem)source; + ObjectBrowserTag itemInfo = (ObjectBrowserTag)item.Tag; + if (itemInfo.Kind != ObjectBrowserItemKind.Directory || !Directory.Exists(itemInfo.Value)) + { + return; + } + + Debug.Assert(Dispatcher != null, nameof(Dispatcher) + " != null"); + using (Dispatcher.DisableProcessing()) + { + item.Items.Clear(); + List newItems = BuildDirectoryItems(itemInfo.Value); + foreach (var i in newItems) { - if (!Directory.Exists(itemInfo.Value)) - { - return; - } - using (var dd = Dispatcher.DisableProcessing()) - { - item.Items.Clear(); - List newItems = BuildDirectoryItems(itemInfo.Value); - foreach (var i in newItems) - { - item.Items.Add(i); - } - } + item.Items.Add(i); } } } @@ -59,9 +55,8 @@ private void TreeViewOBItemParentDir_DoubleClicked(object sender, RoutedEventArg private void TreeViewOBItemFile_DoubleClicked(object sender, RoutedEventArgs e) { - if (sender is TreeViewItem) + if (sender is TreeViewItem item) { - TreeViewItem item = (TreeViewItem)sender; ObjectBrowserTag itemInfo = (ObjectBrowserTag)item.Tag; if (itemInfo.Kind == ObjectBrowserItemKind.File) { @@ -72,7 +67,7 @@ private void TreeViewOBItemFile_DoubleClicked(object sender, RoutedEventArgs e) private void ListViewOBItem_SelectFile(object sender, RoutedEventArgs e) { - if (sender is ListViewItem) + if (sender is ListViewItem item) { EditorElement ee = GetCurrentEditorElement(); if (ee != null) @@ -80,31 +75,30 @@ private void ListViewOBItem_SelectFile(object sender, RoutedEventArgs e) FileInfo fInfo = new FileInfo(ee.FullFilePath); ChangeObjectBrowserToDirectory(fInfo.DirectoryName); } - ((ListViewItem)sender).IsSelected = false; + item.IsSelected = false; ObjectBrowserButtonHolder.SelectedIndex = -1; } } private void ListViewOBItem_SelectConfig(object sender, RoutedEventArgs e) { - if (sender is ListViewItem) + if (sender is ListViewItem item) { var cc = Program.Configs[Program.SelectedConfig]; if (cc.SMDirectories.Length > 0) { ChangeObjectBrowserToDirectory(cc.SMDirectories[0]); } - ((ListViewItem)sender).IsSelected = false; + item.IsSelected = false; ObjectBrowserButtonHolder.SelectedIndex = -1; } } private void ListViewOBItem_SelectOBItem(object sender, RoutedEventArgs e) { - if (sender is ListViewItem) + if (sender is ListViewItem viewItem) { object objectBrowserSelectedItem = ObjectBrowser.SelectedItem; - if (objectBrowserSelectedItem is TreeViewItem) + if (objectBrowserSelectedItem is TreeViewItem item) { - TreeViewItem item = (TreeViewItem)objectBrowserSelectedItem; ObjectBrowserTag itemInfo = (ObjectBrowserTag)item.Tag; if (itemInfo.Kind == ObjectBrowserItemKind.Directory) { @@ -125,7 +119,7 @@ private void ListViewOBItem_SelectOBItem(object sender, RoutedEventArgs e) ChangeObjectBrowserToDrives(); } } - ((ListViewItem)sender).IsSelected = false; + viewItem.IsSelected = false; ObjectBrowserButtonHolder.SelectedIndex = -1; } } @@ -160,7 +154,8 @@ private void ChangeObjectBrowserToDirectory(string dir) CurrentObjectBrowserDirectory = dir; Program.OptionsObject.Program_ObjectBrowserDirectory = CurrentObjectBrowserDirectory; - using (var dd = Dispatcher.DisableProcessing()) + Debug.Assert(Dispatcher != null, nameof(Dispatcher) + " != null"); + using (Dispatcher.DisableProcessing()) { ObjectBrowserDirBlock.Text = dir; ObjectBrowser.Items.Clear(); @@ -182,7 +177,8 @@ private void ChangeObjectBrowserToDrives() { Program.OptionsObject.Program_ObjectBrowserDirectory = "0:"; DriveInfo[] drives = DriveInfo.GetDrives(); - using (var dd = Dispatcher.DisableProcessing()) + Debug.Assert(Dispatcher != null, nameof(Dispatcher) + " != null"); + using (Dispatcher.DisableProcessing()) { ObjectBrowserDirBlock.Text = string.Empty; ObjectBrowser.Items.Clear(); @@ -190,16 +186,13 @@ private void ChangeObjectBrowserToDrives() { if (dInfo.IsReady && (dInfo.DriveType == DriveType.Fixed || dInfo.DriveType == DriveType.Removable)) { - if (dInfo.RootDirectory != null) + var tvi = new TreeViewItem() { - var tvi = new TreeViewItem() - { - Header = BuildTreeViewItemContent(dInfo.Name, "iconmonstr-folder-13-16.png"), - Tag = new ObjectBrowserTag() { Kind = ObjectBrowserItemKind.Directory, Value = dInfo.RootDirectory.FullName } - }; - tvi.Items.Add("..."); - ObjectBrowser.Items.Add(tvi); - } + Header = BuildTreeViewItemContent(dInfo.Name, "iconmonstr-folder-13-16.png"), + Tag = new ObjectBrowserTag() { Kind = ObjectBrowserItemKind.Directory, Value = dInfo.RootDirectory.FullName } + }; + tvi.Items.Add("..."); + ObjectBrowser.Items.Add(tvi); } } } @@ -269,16 +262,13 @@ private List BuildDirectoryItems(string dir) private object BuildTreeViewItemContent(string headerString, string iconFile) { - StackPanel stack = new StackPanel(); - stack.Orientation = Orientation.Horizontal; + StackPanel stack = new StackPanel {Orientation = Orientation.Horizontal}; Image image = new Image(); string uriPath = $"/Spedit;component/Resources/{iconFile}"; image.Source = new BitmapImage(new Uri(uriPath, UriKind.Relative)); image.Width = 16; image.Height = 16; - TextBlock lbl = new TextBlock(); - lbl.Text = headerString; - lbl.Margin = new Thickness(2.0, 0.0, 0.0, 0.0); + TextBlock lbl = new TextBlock {Text = headerString, Margin = new Thickness(2.0, 0.0, 0.0, 0.0)}; stack.Children.Add(image); stack.Children.Add(lbl); return stack; diff --git a/UI/MainWindowSPCompiler.cs b/UI/MainWindowSPCompiler.cs index 6aeb7c79..7e3b0612 100644 --- a/UI/MainWindowSPCompiler.cs +++ b/UI/MainWindowSPCompiler.cs @@ -1,5 +1,4 @@ -using MahApps.Metro.Controls; -using MahApps.Metro.Controls.Dialogs; +using MahApps.Metro.Controls.Dialogs; using Spedit.UI.Components; using Spedit.Utils; using System; @@ -13,13 +12,13 @@ namespace Spedit.UI { - public partial class MainWindow : MetroWindow + public partial class MainWindow { - private List compiledFiles = new List(); - private List nonUploadedFiles = new List(); - private List compiledFileNames = new List(); + private readonly List compiledFiles = new List(); + private readonly List nonUploadedFiles = new List(); + private readonly List compiledFileNames = new List(); - private bool InCompiling = false; + private bool InCompiling; private async void Compile_SPScripts(bool All = true) { if (InCompiling) { return; } @@ -52,11 +51,12 @@ private async void Compile_SPScripts(bool All = true) InCompiling = false; return; } - for (int i = 0; i < editors.Length; ++i) + foreach (var t in editors) { - if (editors[i].CompileBox.IsChecked.Value) + var compileBoxIsChecked = t.CompileBox.IsChecked; + if (compileBoxIsChecked != null && compileBoxIsChecked.Value) { - filesToCompile.Add(editors[i].FullFilePath); + filesToCompile.Add(t.FullFilePath); } } } @@ -86,9 +86,6 @@ private async void Compile_SPScripts(bool All = true) progressTask.SetProgress(0.0); StringBuilder stringOutput = new StringBuilder(); Regex errorFilterRegex = new Regex(@"^(?.+?)\((?[0-9]+(\s*--\s*[0-9]+)?)\)\s*:\s*(?[a-zA-Z]+\s+([a-zA-Z]+\s+)?[0-9]+)\s*:(?
.+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Multiline); - string destinationFileName = null; - FileInfo fileInfo = null; - string outFile = null; for (int i = 0; i < compileCount; ++i) { if (!InCompiling) //pressed escape @@ -98,20 +95,20 @@ private async void Compile_SPScripts(bool All = true) } string file = filesToCompile[i]; progressTask.SetMessage(file); - MainWindow.ProcessUITasks(); - fileInfo = new FileInfo(file); + ProcessUITasks(); + var fileInfo = new FileInfo(file); stringOutput.AppendLine(fileInfo.Name); if (fileInfo.Exists) { using (Process process = new Process()) { - process.StartInfo.WorkingDirectory = fileInfo.DirectoryName; + process.StartInfo.WorkingDirectory = fileInfo.DirectoryName ?? throw new NullReferenceException(); process.StartInfo.UseShellExecute = true; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = spCompInfo.FullName; - destinationFileName = ShortenScriptFileName(fileInfo.Name) + ".smx"; - outFile = Path.Combine(fileInfo.DirectoryName, destinationFileName); + var destinationFileName = ShortenScriptFileName(fileInfo.Name) + ".smx"; + var outFile = Path.Combine(fileInfo.DirectoryName, destinationFileName); if (File.Exists(outFile)) { File.Delete(outFile); } string errorFile = Environment.CurrentDirectory + @"\sourcepawn\errorfiles\error_" + Environment.TickCount.ToString() + "_" + file.GetHashCode().ToString("X") + "_" + i.ToString() + ".txt"; if (File.Exists(errorFile)) { File.Delete(errorFile); } @@ -122,15 +119,14 @@ private async void Compile_SPScripts(bool All = true) includeDirectories.Append(" -i=\"" + dir + "\""); } - string includeStr = string.Empty; - includeStr = includeDirectories.ToString(); + var includeStr = includeDirectories.ToString(); process.StartInfo.Arguments = "\"" + fileInfo.FullName + "\" -o=\"" + outFile + "\" -e=\"" + errorFile + "\"" + includeStr + " -O=" + c.OptimizeLevel.ToString() + " -v=" + c.VerboseLevel.ToString(); - progressTask.SetProgress((((double)(i + 1)) - 0.5d) / ((double)compileCount)); + progressTask.SetProgress((i + 1 - 0.5d) / compileCount); string execResult = ExecuteCommandLine(c.PreCmd, fileInfo.DirectoryName, c.CopyDirectory, fileInfo.FullName, fileInfo.Name, outFile, destinationFileName); if (!string.IsNullOrWhiteSpace(execResult)) { - stringOutput.AppendLine(execResult.Trim(new char[] { '\n', '\r' })); + stringOutput.AppendLine(execResult.Trim('\n', '\r')); } MainWindow.ProcessUITasks(); try @@ -151,7 +147,7 @@ private async void Compile_SPScripts(bool All = true) if (File.Exists(errorFile)) { string errorStr = File.ReadAllText(errorFile); - stringOutput.AppendLine(errorStr.Trim(new char[] { '\n', '\r' } )); + stringOutput.AppendLine(errorStr.Trim('\n', '\r')); MatchCollection mc = errorFilterRegex.Matches(errorStr); for (int j = 0; j < mc.Count; ++j) { @@ -175,11 +171,11 @@ private async void Compile_SPScripts(bool All = true) string execResult_Post = ExecuteCommandLine(c.PostCmd, fileInfo.DirectoryName, c.CopyDirectory, fileInfo.FullName, fileInfo.Name, outFile, destinationFileName); if (!string.IsNullOrWhiteSpace(execResult_Post)) { - stringOutput.AppendLine(execResult_Post.Trim(new char[] { '\n', '\r' })); + stringOutput.AppendLine(execResult_Post.Trim('\n', '\r')); } stringOutput.AppendLine(); - progressTask.SetProgress(((double)(i + 1)) / ((double)compileCount)); - MainWindow.ProcessUITasks(); + progressTask.SetProgress(((double)(i + 1)) / compileCount); + ProcessUITasks(); } } } @@ -206,7 +202,7 @@ private async void Compile_SPScripts(bool All = true) InCompiling = false; } - public void Copy_Plugins(bool OvertakeOutString = false) + private void Copy_Plugins(bool OvertakeOutString = false) { if (compiledFiles.Count > 0) { @@ -216,29 +212,29 @@ public void Copy_Plugins(bool OvertakeOutString = false) if (!string.IsNullOrWhiteSpace(c.CopyDirectory)) { StringBuilder stringOutput = new StringBuilder(); - for (int i = 0; i < compiledFiles.Count; ++i) + foreach (var file in compiledFiles) { try { - FileInfo destFile = new FileInfo(compiledFiles[i]); + FileInfo destFile = new FileInfo(file); if (destFile.Exists) { string destinationFileName = destFile.Name; string copyFileDestination = Path.Combine(c.CopyDirectory, destinationFileName); - File.Copy(compiledFiles[i], copyFileDestination, true); + File.Copy(file, copyFileDestination, true); nonUploadedFiles.Add(copyFileDestination); - stringOutput.AppendLine($"{Program.Translations.GetLanguage("Copied")}: " + compiledFiles[i]); + stringOutput.AppendLine($"{Program.Translations.GetLanguage("Copied")}: " + file); ++copyCount; if (c.DeleteAfterCopy) { - File.Delete(compiledFiles[i]); - stringOutput.AppendLine($"{Program.Translations.GetLanguage("Deleted")}: " + compiledFiles[i]); + File.Delete(file); + stringOutput.AppendLine($"{Program.Translations.GetLanguage("Deleted")}: " + file); } } } catch (Exception) { - stringOutput.AppendLine($"{Program.Translations.GetLanguage("FailCopy")}: " + compiledFiles[i]); + stringOutput.AppendLine($"{Program.Translations.GetLanguage("FailCopy")}: " + file); } } if (copyCount == 0) @@ -261,7 +257,7 @@ public void Copy_Plugins(bool OvertakeOutString = false) } } - public void FTPUpload_Plugins() + private void FTPUpload_Plugins() { if (nonUploadedFiles.Count <= 0) { @@ -276,30 +272,32 @@ public void FTPUpload_Plugins() try { FTP ftp = new FTP(c.FTPHost, c.FTPUser, c.FTPPassword); - for (int i = 0; i < nonUploadedFiles.Count; ++i) + foreach (var file in nonUploadedFiles) { - FileInfo fileInfo = new FileInfo(nonUploadedFiles[i]); - if (fileInfo.Exists) + FileInfo fileInfo = new FileInfo(file); + if (!fileInfo.Exists) { - string uploadDir; - if (string.IsNullOrWhiteSpace(c.FTPDir)) - { - uploadDir = fileInfo.Name; - } - else - { - uploadDir = c.FTPDir.TrimEnd(new char[] { '/' }) + "/" + fileInfo.Name; - } - try - { - ftp.upload(uploadDir, nonUploadedFiles[i]); - stringOutput.AppendLine($"{Program.Translations.GetLanguage("Uploaded")}: " + nonUploadedFiles[i]); - } - catch (Exception e) - { - stringOutput.AppendLine(string.Format(Program.Translations.GetLanguage("ErrorUploadFile"), nonUploadedFiles[i], uploadDir)); - stringOutput.AppendLine($"{Program.Translations.GetLanguage("Details")}: " + e.Message); - } + continue; + } + + string uploadDir; + if (string.IsNullOrWhiteSpace(c.FTPDir)) + { + uploadDir = fileInfo.Name; + } + else + { + uploadDir = c.FTPDir.TrimEnd('/') + "/" + fileInfo.Name; + } + try + { + ftp.upload(uploadDir, file); + stringOutput.AppendLine($"{Program.Translations.GetLanguage("Uploaded")}: " + file); + } + catch (Exception e) + { + stringOutput.AppendLine(string.Format(Program.Translations.GetLanguage("ErrorUploadFile"), file, uploadDir)); + stringOutput.AppendLine($"{Program.Translations.GetLanguage("Details")}: " + e.Message); } } } @@ -316,11 +314,11 @@ public void FTPUpload_Plugins() } } - public bool ServerIsRunning = false; - public Process ServerProcess; - public Thread ServerCheckThread; + private bool ServerIsRunning; + private Process ServerProcess; + private Thread ServerCheckThread; - public void Server_Start() + private void Server_Start() { if (ServerIsRunning) { return; } @@ -337,21 +335,22 @@ public void Server_Start() } try { - ServerProcess = new Process(); - ServerProcess.StartInfo.UseShellExecute = true; - ServerProcess.StartInfo.FileName = serverExec.FullName; - ServerProcess.StartInfo.WorkingDirectory = serverExec.DirectoryName; - ServerProcess.StartInfo.Arguments = c.ServerArgs; - ServerCheckThread = new Thread(new ThreadStart(ProcessCheckWorker)); + ServerProcess = new Process + { + StartInfo = + { + UseShellExecute = true, + FileName = serverExec.FullName, + WorkingDirectory = serverExec.DirectoryName ?? throw new NullReferenceException(), + Arguments = c.ServerArgs + } + }; + ServerCheckThread = new Thread(ProcessCheckWorker); ServerCheckThread.Start(); } catch (Exception) { - if (ServerProcess != null) - { - ServerProcess.Dispose(); - } - return; + ServerProcess?.Dispose(); } } @@ -367,7 +366,7 @@ private void ProcessCheckWorker() return; } ServerIsRunning = true; - Program.MainWindow.Dispatcher.Invoke(() => + Program.MainWindow.Dispatcher?.Invoke(() => { EnableServerAnim.Begin(); UpdateWindowTitle(); @@ -375,7 +374,7 @@ private void ProcessCheckWorker() ServerProcess.WaitForExit(); ServerProcess.Dispose(); ServerIsRunning = false; - Program.MainWindow.Dispatcher.Invoke(() => + Program.MainWindow.Dispatcher?.Invoke(() => { if (Program.MainWindow.IsLoaded) { @@ -404,7 +403,7 @@ private string ExecuteCommandLine(string code, string directory, string copyDir, } string batchFile = (new FileInfo(Path.Combine("sourcepawn\\temp\\", Environment.TickCount.ToString() + "_" + ((uint)code.GetHashCode() ^ (uint)directory.GetHashCode()).ToString() + "_temp.bat"))).FullName; File.WriteAllText(batchFile, code); - string result = null; + string result; using (Process process = new Process()) { process.StartInfo.UseShellExecute = false; diff --git a/UI/MainWindowServerQuery.cs b/UI/MainWindowServerQuery.cs index 48a3522d..13f6c6c8 100644 --- a/UI/MainWindowServerQuery.cs +++ b/UI/MainWindowServerQuery.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Text; using System.Windows; using System.Threading.Tasks; @@ -11,7 +9,7 @@ namespace Spedit.UI { public partial class MainWindow { - public void Server_Query() + private void Server_Query() { Config c = Program.Configs[Program.SelectedConfig]; if (string.IsNullOrWhiteSpace(c.RConIP) || string.IsNullOrWhiteSpace(c.RConCommands)) @@ -30,18 +28,18 @@ public void Server_Query() stringOutput.AppendLine(serverInfo.Name); using (var rcon = server.GetControl(c.RConPassword)) { - string[] cmds = ReplaceRconCMDVaraibles(c.RConCommands).Split('\n'); - for (int i = 0; i < cmds.Length; ++i) + string[] cmds = ReplaceRconCMDVariables(c.RConCommands).Split('\n'); + foreach (var cmd in cmds) { - Task t = Task.Run(() => - { - string command = (cmds[i].Trim(new char[] { '\r' })).Trim(); - if (!string.IsNullOrWhiteSpace(command)) - { - stringOutput.AppendLine(rcon.SendCommand(command)); - } - }); - t.Wait(); + Task t = Task.Run(() => + { + string command = (cmd.Trim('\r')).Trim(); + if (!string.IsNullOrWhiteSpace(command)) + { + stringOutput.AppendLine(rcon.SendCommand(command)); + } + }); + t.Wait(); } } } @@ -58,39 +56,39 @@ public void Server_Query() } } - private string ReplaceRconCMDVaraibles(string input) + private string ReplaceRconCMDVariables(string input) { if (compiledFileNames.Count < 1) { return input; } - if (input.IndexOf("{plugins_reload}") >= 0) + if (input.IndexOf("{plugins_reload}", StringComparison.Ordinal) >= 0) { StringBuilder replacement = new StringBuilder(); replacement.AppendLine(); - for (int i = 0; i < compiledFileNames.Count; ++i) + foreach (var fileName in compiledFileNames) { - replacement.Append("sm plugins reload " + StripSMXPostFix(compiledFileNames[i]) + ";"); + replacement.Append("sm plugins reload " + StripSMXPostFix(fileName) + ";"); } replacement.AppendLine(); input = input.Replace("{plugins_reload}", replacement.ToString()); } - if (input.IndexOf("{plugins_load}") >= 0) + if (input.IndexOf("{plugins_load}", StringComparison.Ordinal) >= 0) { StringBuilder replacement = new StringBuilder(); replacement.AppendLine(); - for (int i = 0; i < compiledFileNames.Count; ++i) + foreach (var fileName in compiledFileNames) { - replacement.Append("sm plugins load " + StripSMXPostFix(compiledFileNames[i]) + ";"); + replacement.Append("sm plugins load " + StripSMXPostFix(fileName) + ";"); } replacement.AppendLine(); input = input.Replace("{plugins_load}", replacement.ToString()); } - if (input.IndexOf("{plugins_unload}") >= 0) + if (input.IndexOf("{plugins_unload}", StringComparison.Ordinal) >= 0) { StringBuilder replacement = new StringBuilder(); replacement.AppendLine(); - for (int i = 0; i < compiledFileNames.Count; ++i) + foreach (var fileName in compiledFileNames) { - replacement.Append("sm plugins unload " + StripSMXPostFix(compiledFileNames[i]) + ";"); + replacement.Append("sm plugins unload " + StripSMXPostFix(fileName) + ";"); } replacement.AppendLine(); input = input.Replace("{plugins_unload}", replacement.ToString()); diff --git a/UI/MainWindowTranslations.cs b/UI/MainWindowTranslations.cs index 6b3d25b9..54d98126 100644 --- a/UI/MainWindowTranslations.cs +++ b/UI/MainWindowTranslations.cs @@ -1,19 +1,10 @@ -using MahApps.Metro.Controls; -using MahApps.Metro.Controls.Dialogs; -using Spedit.UI.Components; -using Spedit.Utils; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Text; -using System.Threading; +using Spedit.UI.Components; using System.Windows.Controls; using System.Collections.ObjectModel; namespace Spedit.UI { - public partial class MainWindow : MetroWindow + public partial class MainWindow { public void Language_Translate(bool Initial = false) { @@ -30,12 +21,9 @@ public void Language_Translate(bool Initial = false) EditorElement[] ee = GetAllEditorElements(); if (ee != null) { - for (int i = 0; i < ee.Length; ++i) + foreach (var t in ee) { - if (ee[i] != null) - { - ee[i].Language_Translate(); - } + t?.Language_Translate(); } } } diff --git a/UI/STheme/STheme.xaml b/UI/STheme/STheme.xaml index 8c2c375a..c7c97f23 100644 --- a/UI/STheme/STheme.xaml +++ b/UI/STheme/STheme.xaml @@ -17,10 +17,8 @@