diff --git a/CustomControls/ComboBoxCustomSearch.cs b/CustomControls/ComboBoxCustomSearch.cs index 72f6a9df..ad8b3c10 100644 --- a/CustomControls/ComboBoxCustomSearch.cs +++ b/CustomControls/ComboBoxCustomSearch.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -29,91 +29,89 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Linq; using System.Windows.Forms; -namespace CustomControls +namespace CustomControls; +// Parts of the code from (C): https://social.msdn.microsoft.com/Forums/en-US/4ebaaed0-cd29-4663-9a43-973729d66cea/autocomplete-combobox-match-any-part-of-string-not-only-beginning-string?forum=winforms + +/// +/// A implementation auto-completing case-insensitively items containing the typed text. +/// Implements the +/// +/// +public class ComboBoxCustomSearch : ComboBox { - // Parts of the code from (C): https://social.msdn.microsoft.com/Forums/en-US/4ebaaed0-cd29-4663-9a43-973729d66cea/autocomplete-combobox-match-any-part-of-string-not-only-beginning-string?forum=winforms + private IList collectionList; /// - /// A implementation auto-completing case-insensitively items containing the typed text. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public class ComboBoxCustomSearch : ComboBox + public ComboBoxCustomSearch() { - private IList collectionList; + collectionList = new List(); + } - /// - /// Initializes a new instance of the class. - /// - public ComboBoxCustomSearch() - { - collectionList = new List(); - } + // ReSharper disable four times InconsistentNaming, WinApi constant.. + // ReSharper disable four times IdentifierTypo, WinApi constant.. + private const int CB_ADDSTRING = 0x143; + private const int CB_DELETESTRING = 0x144; + private const int CB_INSERTSTRING = 0x14A; + private const int CB_RESETCONTENT = 0x14B; - // ReSharper disable four times InconsistentNaming, WinApi constant.. - // ReSharper disable four times IdentifierTypo, WinApi constant.. - private const int CB_ADDSTRING = 0x143; - private const int CB_DELETESTRING = 0x144; - private const int CB_INSERTSTRING = 0x14A; - private const int CB_RESETCONTENT = 0x14B; - - /// - /// Processes Windows messages. - /// - /// The message to process. - protected override void WndProc(ref Message m) + /// + /// Processes Windows messages. + /// + /// The message to process. + protected override void WndProc(ref Message m) + { + if (m.Msg is CB_ADDSTRING or CB_DELETESTRING or CB_INSERTSTRING or CB_RESETCONTENT) { - if (m.Msg is CB_ADDSTRING or CB_DELETESTRING or CB_INSERTSTRING or CB_RESETCONTENT) + if (!filtering) { - if (!filtering) - { - collectionList = Items.OfType().ToList(); - } + collectionList = Items.OfType().ToList(); } - base.WndProc(ref m); } + base.WndProc(ref m); + } - /// - /// A flag indicting whether the combo box is being filtered. - /// - private bool filtering; - - /// - /// A flag indicating whether has been called once. - /// - private bool controlCreated; - - /// - /// Raises the event. - /// - /// An that contains the event data. - protected override void OnTextUpdate(EventArgs e) - { - filtering = true; - IList Values = collectionList - .Where(x => (x.ToString() ?? "").Contains(Text, StringComparison.OrdinalIgnoreCase)) - .ToList(); + /// + /// A flag indicting whether the combo box is being filtered. + /// + private bool filtering; - Items.Clear(); - Items.AddRange(Text != string.Empty ? Values.ToArray() : collectionList.ToArray()); + /// + /// A flag indicating whether has been called once. + /// + private bool controlCreated; - SelectionStart = Text.Length; - DroppedDown = true; - filtering = false; - } + /// + /// Raises the event. + /// + /// An that contains the event data. + protected override void OnTextUpdate(EventArgs e) + { + filtering = true; + IList Values = collectionList + .Where(x => (x.ToString() ?? "").Contains(Text, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + Items.Clear(); + Items.AddRange(Text != string.Empty ? Values.ToArray() : collectionList.ToArray()); + + SelectionStart = Text.Length; + DroppedDown = true; + filtering = false; + } - /// - /// Raises the method. - /// - protected override void OnCreateControl() + /// + /// Raises the method. + /// + protected override void OnCreateControl() + { + base.OnCreateControl(); + if (!controlCreated) { - base.OnCreateControl(); - if (!controlCreated) - { - collectionList = Items.OfType().ToList(); - controlCreated = true; - } + collectionList = Items.OfType().ToList(); + controlCreated = true; } } -} +} \ No newline at end of file diff --git a/CustomControls/CustomControls.csproj b/CustomControls/CustomControls.csproj index 4d0d169d..8a4e44cf 100644 --- a/CustomControls/CustomControls.csproj +++ b/CustomControls/CustomControls.csproj @@ -1,38 +1,38 @@ - - true - net6.0-windows - - Library - - VPKSoft - ScriptNotepad Custom Controls - CustomControls - Custom controls for the ScriptNotepad software. - Copyright © VPKSoft 2021 - MIT - https://www.vpksoft.net/2015-03-31-13-33-28/scriptnotepad - ScriptNotepad_icon.png - - https://github.com/VPKSoft/ScriptNotepad - git - custom control winforms - See: https://github.com/VPKSoft/ScriptNotepad - + + true + net6.0-windows + + Library + + VPKSoft + ScriptNotepad Custom Controls + CustomControls + Custom controls for the ScriptNotepad software. + Copyright © VPKSoft 2022 + MIT + https://www.vpksoft.net/2015-03-31-13-33-28/scriptnotepad + ScriptNotepad_icon.png + + https://github.com/VPKSoft/ScriptNotepad + git + custom control winforms + See: https://github.com/VPKSoft/ScriptNotepad + - - C:\Files\GitHub\ScriptNotepad\CustomControls\CustomControls.xml - + + C:\Files\GitHub\ScriptNotepad\CustomControls\CustomControls.xml + - - C:\Files\GitHub\ScriptNotepad\CustomControls\CustomControls.xml - + + C:\Files\GitHub\ScriptNotepad\CustomControls\CustomControls.xml + - - - True - - - + + + True + + + diff --git a/CustomControls/ImageButton.cs b/CustomControls/ImageButton.cs index a0565394..8b620100 100644 --- a/CustomControls/ImageButton.cs +++ b/CustomControls/ImageButton.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -29,67 +29,66 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Drawing; using System.Windows.Forms; -namespace CustomControls +namespace CustomControls; + +/// +/// A custom button control with an image and a label. +/// Implements the +/// +/// +[DefaultEvent(nameof(Click))] +public partial class ImageButton : UserControl { /// - /// A custom button control with an image and a label. - /// Implements the + /// Initializes a new instance of the class. /// - /// - [DefaultEvent(nameof(Click))] - public partial class ImageButton : UserControl + public ImageButton() { - /// - /// Initializes a new instance of the class. - /// - public ImageButton() - { - InitializeComponent(); - } + InitializeComponent(); + } - /// - /// Gets or sets the button image. - /// - /// The button image. - [Category("Appearance")] - [Description("The button image.")] - public Image ButtonImage { get => pnImage.BackgroundImage; set => pnImage.BackgroundImage = value; } + /// + /// Gets or sets the button image. + /// + /// The button image. + [Category("Appearance")] + [Description("The button image.")] + public Image ButtonImage { get => pnImage.BackgroundImage; set => pnImage.BackgroundImage = value; } - /// - /// Gets or sets the button image layout. - /// - /// The button image layout. - [Category("Appearance")] - [Description("The button image layout.")] - public ImageLayout ButtonImageLayout { get => pnImage.BackgroundImageLayout; set => pnImage.BackgroundImageLayout = value; } + /// + /// Gets or sets the button image layout. + /// + /// The button image layout. + [Category("Appearance")] + [Description("The button image layout.")] + public ImageLayout ButtonImageLayout { get => pnImage.BackgroundImageLayout; set => pnImage.BackgroundImageLayout = value; } - /// - /// Gets or sets the text associated with this control. - /// - /// The text. - [Category("Appearance")] - [Description("The text associated with this control.")] - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] - [EditorBrowsable(EditorBrowsableState.Always)] - public override string Text { get => lbButtonText.Text; set => lbButtonText.Text = value; } + /// + /// Gets or sets the text associated with this control. + /// + /// The text. + [Category("Appearance")] + [Description("The text associated with this control.")] + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] + [EditorBrowsable(EditorBrowsableState.Always)] + public override string Text { get => lbButtonText.Text; set => lbButtonText.Text = value; } - /// - /// Occurs when the control is clicked. - /// - [Category("Behaviour")] - [Description("The text associated with this control.")] - // ReSharper disable once InconsistentNaming - public new EventHandler Click; + /// + /// Occurs when the control is clicked. + /// + [Category("Behaviour")] + [Description("The text associated with this control.")] + // ReSharper disable once InconsistentNaming + public new EventHandler Click; - /// - /// Delegates the event to the base control. - /// - /// The sender. - /// The instance containing the event data. - private void DelegateClick(object sender, EventArgs e) - { - Click?.Invoke(this, EventArgs.Empty); - } + /// + /// Delegates the event to the base control. + /// + /// The sender. + /// The instance containing the event data. + private void DelegateClick(object sender, EventArgs e) + { + Click?.Invoke(this, EventArgs.Empty); } -} +} \ No newline at end of file diff --git a/InstallerBaseWixSharp/Files/Dialogs/ProgressDialog.cs b/InstallerBaseWixSharp/Files/Dialogs/ProgressDialog.cs index ceaccabc..2482f9bf 100644 --- a/InstallerBaseWixSharp/Files/Dialogs/ProgressDialog.cs +++ b/InstallerBaseWixSharp/Files/Dialogs/ProgressDialog.cs @@ -48,7 +48,7 @@ public ProgressDialog() InitializeComponent(); dialogText.MakeTransparentOn(banner); - showWaitPromptTimer = new System.Windows.Forms.Timer { Interval = 4000 }; + showWaitPromptTimer = new System.Windows.Forms.Timer { Interval = 4000, }; showWaitPromptTimer.Tick += (s, e) => { waitPrompt.Visible = true; diff --git a/InstallerBaseWixSharp/Files/Localization/TabDeliLocalization/TabDeliLocalization.cs b/InstallerBaseWixSharp/Files/Localization/TabDeliLocalization/TabDeliLocalization.cs index 1af597f9..35dc1d71 100644 --- a/InstallerBaseWixSharp/Files/Localization/TabDeliLocalization/TabDeliLocalization.cs +++ b/InstallerBaseWixSharp/Files/Localization/TabDeliLocalization/TabDeliLocalization.cs @@ -167,7 +167,7 @@ public void GetLocalizedTexts(string fileContents) { continue; } - LocalizationTexts.Add(new LocalizationTextContainer { MessageName = delimited[0], Message = delimited[1], CultureName = locale}); + LocalizationTexts.Add(new LocalizationTextContainer { MessageName = delimited[0], Message = delimited[1], CultureName = locale, }); } } } diff --git a/InstallerBaseWixSharp/Files/PInvoke/ProcessExtensions.cs b/InstallerBaseWixSharp/Files/PInvoke/ProcessExtensions.cs index e71dec53..9af6a2c1 100644 --- a/InstallerBaseWixSharp/Files/PInvoke/ProcessExtensions.cs +++ b/InstallerBaseWixSharp/Files/PInvoke/ProcessExtensions.cs @@ -111,7 +111,7 @@ private enum SW SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, - SW_MAX = 10 + SW_MAX = 10, } private enum WTS_CONNECTSTATE_CLASS @@ -125,7 +125,7 @@ private enum WTS_CONNECTSTATE_CLASS WTSListen, WTSReset, WTSDown, - WTSInit + WTSInit, } [StructLayout(LayoutKind.Sequential)] @@ -171,7 +171,7 @@ private struct STARTUPINFO private enum TOKEN_TYPE { TokenPrimary = 1, - TokenImpersonation = 2 + TokenImpersonation = 2, } [StructLayout(LayoutKind.Sequential)] diff --git a/InstallerBaseWixSharp/Program.cs b/InstallerBaseWixSharp/Program.cs index f8c31bc5..56b52402 100644 --- a/InstallerBaseWixSharp/Program.cs +++ b/InstallerBaseWixSharp/Program.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -83,7 +83,7 @@ string OutputFile() // get the executable file name and the version from it.. // ReSharper disable three times StringLiteralTypo new ExeFileShortcut(AppName, $"[INSTALLDIR]{Executable}", "") { - WorkingDirectory = "[INSTALLDIR]", IconFile = ApplicationIcon + WorkingDirectory = "[INSTALLDIR]", IconFile = ApplicationIcon, }), #if InstallLocalAppData new Dir($@"%LocalAppDataFolder%\{AppName}", diff --git a/InstallerBaseWixSharp/Registry/RegistryFileAssociation.cs b/InstallerBaseWixSharp/Registry/RegistryFileAssociation.cs index 2193b1dd..d2b1ade1 100644 --- a/InstallerBaseWixSharp/Registry/RegistryFileAssociation.cs +++ b/InstallerBaseWixSharp/Registry/RegistryFileAssociation.cs @@ -719,7 +719,7 @@ public enum HChangeNotifyFlags /// but should return as soon as the notification process has begun. /// As this flag modifies other data-type flags, it cannot by used by itself. /// - SHCNF_FLUSHNOWAIT = 0x2000 + SHCNF_FLUSHNOWAIT = 0x2000, } #endregion } diff --git a/PluginTemplate/SamplePlugin.cs b/PluginTemplate/SamplePlugin.cs index c406d740..d361d64c 100644 --- a/PluginTemplate/SamplePlugin.cs +++ b/PluginTemplate/SamplePlugin.cs @@ -35,503 +35,502 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using static ScriptNotepadPluginBase.Types.DelegateTypes; -namespace PluginTemplate +namespace PluginTemplate; + +/// +/// An interface to wright plug-ins for ScriptNotepad software. +/// +/// +public class SamplePlugin : ScriptNotepadPlugin, IScriptNotepadPlugin { /// - /// An interface to wright plug-ins for ScriptNotepad software. + /// Occurs when the plug-in requests the active document of the ScriptNotepad. + /// + public event OnRequestActiveDocument RequestActiveDocument = null; + + /// + /// Occurs when the plug-in requests for all the open documents of the ScriptNotepad. + /// + public event OnRequestAllDocuments RequestAllDocuments; + + /// + /// Occurs when an exception occurred within the plug-in so the hosting + /// software (ScriptNotepad) can log it and possibly take necessary actions + /// for the plug-in (i.e. disable it). + /// + public event OnPluginException PluginException; + + /// + /// A field to save the event to unsubscribe it in the Dispose method. /// - /// - public class SamplePlugin : ScriptNotepadPlugin, IScriptNotepadPlugin + private OnRequestActiveDocument onRequestActiveDocument; + + /// + /// A field to save the event to unsubscribe it in the Dispose method. + /// + private OnRequestAllDocuments onRequestAllDocuments; + + /// + /// A field to save the event to report an exception which happened within the plugin library. + /// + private OnPluginException onPluginException; + + /// + /// A menu strip given by the main software (ScriptNotepad) for a plug-in to construct it's own menu. + /// + private ToolStripMenuItem pluginMenuStrip = null; + + /// + /// Gets the name of the plug-in (i.e. "My Awesome Plug-in). + /// + public string PluginName { - /// - /// Occurs when the plug-in requests the active document of the ScriptNotepad. - /// - public event OnRequestActiveDocument RequestActiveDocument = null; - - /// - /// Occurs when the plug-in requests for all the open documents of the ScriptNotepad. - /// - public event OnRequestAllDocuments RequestAllDocuments; - - /// - /// Occurs when an exception occurred within the plug-in so the hosting - /// software (ScriptNotepad) can log it and possibly take necessary actions - /// for the plug-in (i.e. disable it). - /// - public event OnPluginException PluginException; - - /// - /// A field to save the event to unsubscribe it in the Dispose method. - /// - private OnRequestActiveDocument onRequestActiveDocument; - - /// - /// A field to save the event to unsubscribe it in the Dispose method. - /// - private OnRequestAllDocuments onRequestAllDocuments; - - /// - /// A field to save the event to report an exception which happened within the plugin library. - /// - private OnPluginException onPluginException; - - /// - /// A menu strip given by the main software (ScriptNotepad) for a plug-in to construct it's own menu. - /// - private ToolStripMenuItem pluginMenuStrip = null; - - /// - /// Gets the name of the plug-in (i.e. "My Awesome Plug-in). - /// - public string PluginName - { - get => "SamplePlugin"; - } + get => "SamplePlugin"; + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - // unsubscribe the event handlers.. - RequestActiveDocument -= onRequestActiveDocument; - RequestAllDocuments -= onRequestAllDocuments; - PluginException -= onPluginException; - // END: unsubscribe the event handlers.. + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + // unsubscribe the event handlers.. + RequestActiveDocument -= onRequestActiveDocument; + RequestAllDocuments -= onRequestAllDocuments; + PluginException -= onPluginException; + // END: unsubscribe the event handlers.. - // leave no references to the host program (ScriptNotepad).. - ScriptNotepadMainForm = null; + // leave no references to the host program (ScriptNotepad).. + ScriptNotepadMainForm = null; - // leave no references to the host program (ScriptNotepad).. - ScriptNotepadMainMenu = null; + // leave no references to the host program (ScriptNotepad).. + ScriptNotepadMainMenu = null; - // dispose of the menu constructed by this plug-in.. - DisposeMenu(); + // dispose of the menu constructed by this plug-in.. + DisposeMenu(); - // set the initialization flag.. - Initialized = false; - } + // set the initialization flag.. + Initialized = false; + } - /// - /// Gets or sets the name of the session. - /// - public string SessionName { get; set; } - - /// - /// The description of this plug-in. - /// - public string PluginDescription { get; set; } = "Sample plug-in by VPKSoft"; - - /// - /// A list containing messages for localization. Please do fill at least the en-US localization. - /// - public List<(string MessageName, string Message, string CultureName)> LocalizationTexts { get; set; } = - new List<(string MessageName, string Message, string CultureName)>(); - - /// - /// The main form of the hosting software (ScriptNotepad). - /// - public Form ScriptNotepadMainForm { get; set; } = null; - - // set the culture to current UI culture.. - private string _Locale = CultureInfo.CurrentUICulture.Name; - - /// - /// Gets or sets the current locale for the plug-in. - /// - public string Locale - { - get => _Locale; - set - { - _Locale = value; - // and some localization here.. - PluginDescription = GetMessage("plgDescription", "Sample plug-in by VPKSoft", value); + /// + /// Gets or sets the name of the session. + /// + public string SessionName { get; set; } - // the about menu for this plug-in has been constructed.. - if (Initialized) - { - // ..localize the about menu constructed by this plug-in.. - pluginAboutMenu.Text = GetMessage("txtAbout", "About", value); - pluginCauseException.Text = GetMessage("txtCauseException", "Cause an exception", value); - } - } - } + /// + /// The description of this plug-in. + /// + public string PluginDescription { get; set; } = "Sample plug-in by VPKSoft"; - /// - /// Gets or sets the tool strip menu item the plug-in constructed. - /// - public ToolStripMenuItem PluginMenu { get; set; } - - /// - /// A drop down menu item for the . - /// - ToolStripMenuItem pluginMainMenu; - - /// - /// A menu item to cause an non-handled exception on purpose. - /// - ToolStripMenuItem pluginCauseException; - - /// - /// A menu item to cause an handled exception on purpose. - /// - ToolStripMenuItem pluginCauseHandledException; - /// - /// A menu item to append a modified ROT-13 algorithm to either selected text or the whole document. - /// - ToolStripMenuItem pluginROT13; - - /// - /// A menu item to revert a modified ROT-13 algorithm to either selected text or the whole document. - /// - ToolStripMenuItem pluginUnROT13; - - /// - /// A drop down menu item for the . - /// - ToolStripMenuItem pluginAboutMenu; - - /// - /// The rot13 text doubled so there is no need to start counting indices. - /// - private string rot13Text = - "abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ0123456789!\"#¤%&/()=?`@£${[]}|<>½ " + "abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ0123456789!\"#¤%&/()=?`@£${[]}|<>½"; - - private const int rotAmount = 13; - - /// - /// Performs a modified ROT-13 algorithm on a single character. - /// - /// A character to mess with the ROT-13 algorithm. - /// System.Char. - private char GetRot(char toRot) - { - int chIndex = rot13Text.IndexOf(toRot); - if (chIndex == -1) - { - return toRot; - } + /// + /// A list containing messages for localization. Please do fill at least the en-US localization. + /// + public List<(string MessageName, string Message, string CultureName)> LocalizationTexts { get; set; } = + new List<(string MessageName, string Message, string CultureName)>(); - chIndex += rotAmount; - return (rot13Text)[chIndex]; - } + /// + /// The main form of the hosting software (ScriptNotepad). + /// + public Form ScriptNotepadMainForm { get; set; } = null; - /// - /// Reverses the modified ROT-13 algorithm on a single character. - /// - /// A character to "decrypt" with the ROT-13 algorithm. - /// System.Char. - private char GetUnRot(char toUnRot) + // set the culture to current UI culture.. + private string _Locale = CultureInfo.CurrentUICulture.Name; + + /// + /// Gets or sets the current locale for the plug-in. + /// + public string Locale + { + get => _Locale; + set { - int chIndex = rot13Text.LastIndexOf(toUnRot); - if (chIndex == -1) + _Locale = value; + // and some localization here.. + PluginDescription = GetMessage("plgDescription", "Sample plug-in by VPKSoft", value); + + // the about menu for this plug-in has been constructed.. + if (Initialized) { - return toUnRot; + // ..localize the about menu constructed by this plug-in.. + pluginAboutMenu.Text = GetMessage("txtAbout", "About", value); + pluginCauseException.Text = GetMessage("txtCauseException", "Cause an exception", value); } + } + } - chIndex -= rotAmount; - return (rot13Text)[chIndex]; + /// + /// Gets or sets the tool strip menu item the plug-in constructed. + /// + public ToolStripMenuItem PluginMenu { get; set; } + + /// + /// A drop down menu item for the . + /// + ToolStripMenuItem pluginMainMenu; + + /// + /// A menu item to cause an non-handled exception on purpose. + /// + ToolStripMenuItem pluginCauseException; + + /// + /// A menu item to cause an handled exception on purpose. + /// + ToolStripMenuItem pluginCauseHandledException; + /// + /// A menu item to append a modified ROT-13 algorithm to either selected text or the whole document. + /// + ToolStripMenuItem pluginROT13; + + /// + /// A menu item to revert a modified ROT-13 algorithm to either selected text or the whole document. + /// + ToolStripMenuItem pluginUnROT13; + + /// + /// A drop down menu item for the . + /// + ToolStripMenuItem pluginAboutMenu; + + /// + /// The rot13 text doubled so there is no need to start counting indices. + /// + private string rot13Text = + "abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ0123456789!\"#¤%&/()=?`@£${[]}|<>½ " + "abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ0123456789!\"#¤%&/()=?`@£${[]}|<>½"; + + private const int rotAmount = 13; + + /// + /// Performs a modified ROT-13 algorithm on a single character. + /// + /// A character to mess with the ROT-13 algorithm. + /// System.Char. + private char GetRot(char toRot) + { + int chIndex = rot13Text.IndexOf(toRot); + if (chIndex == -1) + { + return toRot; } - /// - /// Additional initialization method for the plug-in. - /// - /// The event provided by the hosting software (ScriptNotepad) to request for the active document within the software. - /// The event provided by the hosting software (ScriptNotepad) to request for all open documents within the software. - /// The event provided by the hosting software (ScriptNotepad) for error reporting. - /// The which is the main menu of the hosting software (ScriptNotepad). - /// The which is the plug-in menu in the hosting software (ScriptNotepad). - /// The name of the current session in the hosting software (ScriptNotepad). - /// A reference to the main form of the hosting software (ScriptNotepad). - public void Initialize(OnRequestActiveDocument onRequestActiveDocument, - OnRequestAllDocuments onRequestAllDocuments, - OnPluginException onPluginException, - MenuStrip mainMenu, - ToolStripMenuItem pluginMenuStrip, - string sessionName, - Form scriptNotepadMainForm) + chIndex += rotAmount; + return (rot13Text)[chIndex]; + } + + /// + /// Reverses the modified ROT-13 algorithm on a single character. + /// + /// A character to "decrypt" with the ROT-13 algorithm. + /// System.Char. + private char GetUnRot(char toUnRot) + { + int chIndex = rot13Text.LastIndexOf(toUnRot); + if (chIndex == -1) { - // save the given delegates so they can be unsubscribed on disposal.. - this.onRequestActiveDocument = onRequestActiveDocument; - this.onRequestAllDocuments = onRequestAllDocuments; - this.onPluginException = onPluginException; + return toUnRot; + } - // save the main form of the ScriptNotepad software.. - ScriptNotepadMainForm = scriptNotepadMainForm; + chIndex -= rotAmount; + return (rot13Text)[chIndex]; + } + + /// + /// Additional initialization method for the plug-in. + /// + /// The event provided by the hosting software (ScriptNotepad) to request for the active document within the software. + /// The event provided by the hosting software (ScriptNotepad) to request for all open documents within the software. + /// The event provided by the hosting software (ScriptNotepad) for error reporting. + /// The which is the main menu of the hosting software (ScriptNotepad). + /// The which is the plug-in menu in the hosting software (ScriptNotepad). + /// The name of the current session in the hosting software (ScriptNotepad). + /// A reference to the main form of the hosting software (ScriptNotepad). + public void Initialize(OnRequestActiveDocument onRequestActiveDocument, + OnRequestAllDocuments onRequestAllDocuments, + OnPluginException onPluginException, + MenuStrip mainMenu, + ToolStripMenuItem pluginMenuStrip, + string sessionName, + Form scriptNotepadMainForm) + { + // save the given delegates so they can be unsubscribed on disposal.. + this.onRequestActiveDocument = onRequestActiveDocument; + this.onRequestAllDocuments = onRequestAllDocuments; + this.onPluginException = onPluginException; - // save the plug-in menu string of the ScriptNotepad software.. - this.pluginMenuStrip = pluginMenuStrip; + // save the main form of the ScriptNotepad software.. + ScriptNotepadMainForm = scriptNotepadMainForm; - // save the name of the current session of the ScriptNotepad software.. - SessionName = sessionName; + // save the plug-in menu string of the ScriptNotepad software.. + this.pluginMenuStrip = pluginMenuStrip; - // subscribe the event handlers.. - RequestActiveDocument += onRequestActiveDocument; - RequestAllDocuments += onRequestAllDocuments; - PluginException += onPluginException; - // END: subscribe the event handlers.. + // save the name of the current session of the ScriptNotepad software.. + SessionName = sessionName; - // save the hosting process (ScriptNotepad) main menu to a property.. - ScriptNotepadMainMenu = mainMenu; + // subscribe the event handlers.. + RequestActiveDocument += onRequestActiveDocument; + RequestAllDocuments += onRequestAllDocuments; + PluginException += onPluginException; + // END: subscribe the event handlers.. - // create a menu for the plug-in.. - pluginMainMenu = new ToolStripMenuItem() { Text = PluginName, Tag = this }; - pluginMenuStrip.DropDownItems.Add(pluginMainMenu); + // save the hosting process (ScriptNotepad) main menu to a property.. + ScriptNotepadMainMenu = mainMenu; - pluginAboutMenu = new ToolStripMenuItem() { Text = GetMessage("txtAbout", "About", Locale), Tag = this }; - pluginMainMenu.DropDownItems.Add(pluginAboutMenu); + // create a menu for the plug-in.. + pluginMainMenu = new ToolStripMenuItem() { Text = PluginName, Tag = this, }; + pluginMenuStrip.DropDownItems.Add(pluginMainMenu); - pluginCauseException = new ToolStripMenuItem() { Text = GetMessage("txtCauseException", "Cause an exception", Locale), Tag = this }; - pluginMainMenu.DropDownItems.Add(pluginCauseException); + pluginAboutMenu = new ToolStripMenuItem() { Text = GetMessage("txtAbout", "About", Locale), Tag = this, }; + pluginMainMenu.DropDownItems.Add(pluginAboutMenu); - pluginCauseHandledException = new ToolStripMenuItem() { Text = GetMessage("txtCauseHandledException", "Cause a handled exception", Locale), Tag = this }; - pluginMainMenu.DropDownItems.Add(pluginCauseHandledException); + pluginCauseException = new ToolStripMenuItem() { Text = GetMessage("txtCauseException", "Cause an exception", Locale), Tag = this, }; + pluginMainMenu.DropDownItems.Add(pluginCauseException); - pluginROT13 = new ToolStripMenuItem() { Text = GetMessage("txtModifiedROT13", "Modified ROT-13", Locale), Tag = this }; - pluginMainMenu.DropDownItems.Add(pluginROT13); + pluginCauseHandledException = new ToolStripMenuItem() { Text = GetMessage("txtCauseHandledException", "Cause a handled exception", Locale), Tag = this, }; + pluginMainMenu.DropDownItems.Add(pluginCauseHandledException); - pluginUnROT13 = new ToolStripMenuItem() { Text = GetMessage("txtModifiedUnROT13", "Decrypt modified ROT-13", Locale), Tag = this }; - pluginMainMenu.DropDownItems.Add(pluginUnROT13); + pluginROT13 = new ToolStripMenuItem() { Text = GetMessage("txtModifiedROT13", "Modified ROT-13", Locale), Tag = this, }; + pluginMainMenu.DropDownItems.Add(pluginROT13); - // subscribe events for the menu created by the plug-in.. - pluginAboutMenu.Click += PluginAboutMenu_Click; - pluginCauseException.Click += PluginCauseException_Click; - pluginCauseHandledException.Click += PluginCauseHandledException_Click; - pluginROT13.Click += PluginROT13_Click; - pluginUnROT13.Click += PluginUnROT13_Click; - // END: subscribe events for the menu created by the plug-in.. + pluginUnROT13 = new ToolStripMenuItem() { Text = GetMessage("txtModifiedUnROT13", "Decrypt modified ROT-13", Locale), Tag = this, }; + pluginMainMenu.DropDownItems.Add(pluginUnROT13); - // set the initialization flag.. - Initialized = true; + // subscribe events for the menu created by the plug-in.. + pluginAboutMenu.Click += PluginAboutMenu_Click; + pluginCauseException.Click += PluginCauseException_Click; + pluginCauseHandledException.Click += PluginCauseHandledException_Click; + pluginROT13.Click += PluginROT13_Click; + pluginUnROT13.Click += PluginUnROT13_Click; + // END: subscribe events for the menu created by the plug-in.. - // write extra initialization code here if required.. - } + // set the initialization flag.. + Initialized = true; - /// - /// A user clicked the append ROT-13 "decryption" algorithm from the plugin menu. - /// - /// The source of the event. - /// The instance containing the event data. - private void PluginUnROT13_Click(object sender, System.EventArgs e) + // write extra initialization code here if required.. + } + + /// + /// A user clicked the append ROT-13 "decryption" algorithm from the plugin menu. + /// + /// The source of the event. + /// The instance containing the event data. + private void PluginUnROT13_Click(object sender, System.EventArgs e) + { + try // try as the hosting software might ban the plugin in case of a total crash.. { - try // try as the hosting software might ban the plugin in case of a total crash.. + // initialize a new event arguments to request the active document on the hosting software (ScriptNotepad).. + RequestScintillaDocumentEventArgs args = new RequestScintillaDocumentEventArgs() {AllDocuments = false, }; + + // request the active Scintilla document from the hosting software (ScriptNotepad).. + RequestActiveDocument?.Invoke(this, args); + + // check that the event invocation returned any documents.. + if (args.Documents.Count > 0) { - // initialize a new event arguments to request the active document on the hosting software (ScriptNotepad).. - RequestScintillaDocumentEventArgs args = new RequestScintillaDocumentEventArgs() {AllDocuments = false}; + // get the first document as only the active document was requested.. + var scintilla = args.Documents[0].Scintilla; + + // detect the text to to either selection or the whole text of the scintilla.. + string text = scintilla.SelectedText.Length > 0 ? scintilla.SelectedText : scintilla.Text; - // request the active Scintilla document from the hosting software (ScriptNotepad).. - RequestActiveDocument?.Invoke(this, args); + // introduce a new variable for the ROT-13 text.. + string newText = ""; - // check that the event invocation returned any documents.. - if (args.Documents.Count > 0) + // loop through the text and "decrypt" it with the modified ROT-13 "algorithm".. + foreach (var t in text) { - // get the first document as only the active document was requested.. - var scintilla = args.Documents[0].Scintilla; - - // detect the text to to either selection or the whole text of the scintilla.. - string text = scintilla.SelectedText.Length > 0 ? scintilla.SelectedText : scintilla.Text; - - // introduce a new variable for the ROT-13 text.. - string newText = ""; - - // loop through the text and "decrypt" it with the modified ROT-13 "algorithm".. - foreach (var t in text) - { - // set the new text as we go.. - newText += GetUnRot(t); - } - - // if the text was in selection.. - if (scintilla.SelectedText.Length > 0) - { - // ..save the range of the selection.. - int selStart = scintilla.SelectionStart; - int selEnd = scintilla.SelectionEnd; - - // replace the selection.. - scintilla.ReplaceSelection(newText); - - // set the selection range back to it's original state.. - scintilla.SelectionStart = selStart; - scintilla.SelectionEnd = selEnd; - } - // the whole text was "encrypted".. - else - { - scintilla.Text = newText; - } + // set the new text as we go.. + newText += GetUnRot(t); } - } - // an exception occurred.. - catch (Exception ex) - { - // ..report the exception to the hosting software (ScriptNotepad) for logging.. - onPluginException?.Invoke(this, new PluginExceptionEventArgs {Exception = ex, PluginModuleName = PluginName}); - } - } - /// - /// A user clicked the append ROT-13 "encryption" algorithm from the plugin menu. - /// - /// The source of the event. - /// The instance containing the event data. - private void PluginROT13_Click(object sender, System.EventArgs e) - { - try // try as the hosting software might ban the plugin in case of a total crash.. - { - // initialize a new event arguments to request the active document on the hosting software (ScriptNotepad).. - RequestScintillaDocumentEventArgs args = new RequestScintillaDocumentEventArgs() {AllDocuments = false}; + // if the text was in selection.. + if (scintilla.SelectedText.Length > 0) + { + // ..save the range of the selection.. + int selStart = scintilla.SelectionStart; + int selEnd = scintilla.SelectionEnd; - // request the active Scintilla document from the hosting software (ScriptNotepad).. - RequestActiveDocument?.Invoke(this, args); + // replace the selection.. + scintilla.ReplaceSelection(newText); - // check that the event invocation returned any documents.. - if (args.Documents.Count > 0) + // set the selection range back to it's original state.. + scintilla.SelectionStart = selStart; + scintilla.SelectionEnd = selEnd; + } + // the whole text was "encrypted".. + else { - // get the first document as only the active document was requested.. - var scintilla = args.Documents[0].Scintilla; - - // detect the text to to either selection or the whole text of the scintilla.. - string text = scintilla.SelectedText.Length > 0 ? scintilla.SelectedText : scintilla.Text; - - // introduce a new variable for the ROT-13 text.. - string newText = ""; - - // loop through the text and "encrypt" it with the modified ROT-13 "algorithm".. - foreach (var t in text) - { - // set the new text as we go.. - newText += GetRot(t); - } - - // if the text was in selection.. - if (scintilla.SelectedText.Length > 0) - { - // ..save the range of the selection.. - int selStart = scintilla.SelectionStart; - int selEnd = scintilla.SelectionEnd; - - // replace the selection.. - scintilla.ReplaceSelection(newText); - - // set the selection range back to it's original state.. - scintilla.SelectionStart = selStart; - scintilla.SelectionEnd = selEnd; - } - else - { - // the whole text was "encrypted".. - scintilla.Text = newText; - } + scintilla.Text = newText; } } - // an exception occurred.. - catch (Exception ex) - { - // ..report the exception to the hosting software (ScriptNotepad) for logging.. - onPluginException?.Invoke(this, new PluginExceptionEventArgs {Exception = ex, PluginModuleName = PluginName}); - } } - - // cause an intentional unhandled crash (for testing the ban mechanism).. - private void PluginCauseException_Click(object sender, System.EventArgs e) + // an exception occurred.. + catch (Exception ex) { - // fool the code check.. - int i = 5 / int.Parse("0"); // this will cause an exception.. + // ..report the exception to the hosting software (ScriptNotepad) for logging.. + onPluginException?.Invoke(this, new PluginExceptionEventArgs {Exception = ex, PluginModuleName = PluginName, }); } + } - // cause an intentional handled exception (for testing the logging mechanism).. - private void PluginCauseHandledException_Click(object sender, EventArgs e) + /// + /// A user clicked the append ROT-13 "encryption" algorithm from the plugin menu. + /// + /// The source of the event. + /// The instance containing the event data. + private void PluginROT13_Click(object sender, System.EventArgs e) + { + try // try as the hosting software might ban the plugin in case of a total crash.. { - try - { - // fool the code check.. - int i = 5 / int.Parse("0"); // this will cause an exception.. - } - // an exception occurred.. - catch (Exception ex) + // initialize a new event arguments to request the active document on the hosting software (ScriptNotepad).. + RequestScintillaDocumentEventArgs args = new RequestScintillaDocumentEventArgs() {AllDocuments = false, }; + + // request the active Scintilla document from the hosting software (ScriptNotepad).. + RequestActiveDocument?.Invoke(this, args); + + // check that the event invocation returned any documents.. + if (args.Documents.Count > 0) { - // ..report the exception to the hosting software (ScriptNotepad) for logging.. - onPluginException?.Invoke(this, new PluginExceptionEventArgs {Exception = ex, PluginModuleName = PluginName}); + // get the first document as only the active document was requested.. + var scintilla = args.Documents[0].Scintilla; + + // detect the text to to either selection or the whole text of the scintilla.. + string text = scintilla.SelectedText.Length > 0 ? scintilla.SelectedText : scintilla.Text; + + // introduce a new variable for the ROT-13 text.. + string newText = ""; + + // loop through the text and "encrypt" it with the modified ROT-13 "algorithm".. + foreach (var t in text) + { + // set the new text as we go.. + newText += GetRot(t); + } + + // if the text was in selection.. + if (scintilla.SelectedText.Length > 0) + { + // ..save the range of the selection.. + int selStart = scintilla.SelectionStart; + int selEnd = scintilla.SelectionEnd; + + // replace the selection.. + scintilla.ReplaceSelection(newText); + + // set the selection range back to it's original state.. + scintilla.SelectionStart = selStart; + scintilla.SelectionEnd = selEnd; + } + else + { + // the whole text was "encrypted".. + scintilla.Text = newText; + } } } - - /// - /// Handles the Click event of the pluginAboutMenu control. - /// - /// The source of the event. - /// The instance containing the event data. - private void PluginAboutMenu_Click(object sender, System.EventArgs e) + // an exception occurred.. + catch (Exception ex) { - // display the about dialog for this plug-in from a self-created menu item click.. - AbountDialog(); + // ..report the exception to the hosting software (ScriptNotepad) for logging.. + onPluginException?.Invoke(this, new PluginExceptionEventArgs {Exception = ex, PluginModuleName = PluginName, }); } + } - /// - /// This method is called by the hosting software (ScriptNotepad) if documents in the software have been changed. - /// - public void NotifyDocumentChanged() - { - RequestScintillaDocumentEventArgs args = new RequestScintillaDocumentEventArgs() { AllDocuments = false }; - RequestActiveDocument?.Invoke(this, args); - } + // cause an intentional unhandled crash (for testing the ban mechanism).. + private void PluginCauseException_Click(object sender, System.EventArgs e) + { + // fool the code check.. + int i = 5 / int.Parse("0"); // this will cause an exception.. + } - /// - /// The basic constructor for the plug-in. - /// - public SamplePlugin() + // cause an intentional handled exception (for testing the logging mechanism).. + private void PluginCauseHandledException_Click(object sender, EventArgs e) + { + try { - GetLocalizedTexts(Properties.Resources.tab_deli_localization); - PluginDescription = GetMessage("plgDescription", "Sample plug-in by VPKSoft", Locale); - // write extra initialization code here if required.. + // fool the code check.. + int i = 5 / int.Parse("0"); // this will cause an exception.. } - - /// - /// Displays the about dialog for this plug-in. - /// - public void AbountDialog() + // an exception occurred.. + catch (Exception ex) { - // display the about dialog for the plug-in.. - new FormPluginAbout( - ScriptNotepadMainForm, // the hosting software main form (ScriptNotepad).. - Assembly.GetAssembly(GetType()), // get the assembly (this) the about dialog should use.. - "MIT", // give a name for the license.. - "https://raw.githubusercontent.com/VPKSoft/ScriptNotepadPluginBase/master/LICENSE", // give a link to the license.. - Locale, // give the current locale for the dialog.. - Properties.Resources.VPKSoft, // give an icon for the dialog.. - PluginName, // give this plug-in name for the dialog.. - Properties.Resources.VPKSoftLogo_App); // give a logo banner for the dialog.. + // ..report the exception to the hosting software (ScriptNotepad) for logging.. + onPluginException?.Invoke(this, new PluginExceptionEventArgs {Exception = ex, PluginModuleName = PluginName, }); } + } - /// - /// Disposes the menu created by the plug-in. - /// - public void DisposeMenu() + /// + /// Handles the Click event of the pluginAboutMenu control. + /// + /// The source of the event. + /// The instance containing the event data. + private void PluginAboutMenu_Click(object sender, System.EventArgs e) + { + // display the about dialog for this plug-in from a self-created menu item click.. + AbountDialog(); + } + + /// + /// This method is called by the hosting software (ScriptNotepad) if documents in the software have been changed. + /// + public void NotifyDocumentChanged() + { + RequestScintillaDocumentEventArgs args = new RequestScintillaDocumentEventArgs() { AllDocuments = false, }; + RequestActiveDocument?.Invoke(this, args); + } + + /// + /// The basic constructor for the plug-in. + /// + public SamplePlugin() + { + GetLocalizedTexts(Properties.Resources.tab_deli_localization); + PluginDescription = GetMessage("plgDescription", "Sample plug-in by VPKSoft", Locale); + // write extra initialization code here if required.. + } + + /// + /// Displays the about dialog for this plug-in. + /// + public void AbountDialog() + { + // display the about dialog for the plug-in.. + new FormPluginAbout( + ScriptNotepadMainForm, // the hosting software main form (ScriptNotepad).. + Assembly.GetAssembly(GetType()), // get the assembly (this) the about dialog should use.. + "MIT", // give a name for the license.. + "https://raw.githubusercontent.com/VPKSoft/ScriptNotepadPluginBase/master/LICENSE", // give a link to the license.. + Locale, // give the current locale for the dialog.. + Properties.Resources.VPKSoft, // give an icon for the dialog.. + PluginName, // give this plug-in name for the dialog.. + Properties.Resources.VPKSoftLogo_App); // give a logo banner for the dialog.. + } + + /// + /// Disposes the menu created by the plug-in. + /// + public void DisposeMenu() + { + // the Dispose method or this method may be called before the Initialize method (!), + // so check the Initialized field.. + if (Initialized) { - // the Dispose method or this method may be called before the Initialize method (!), - // so check the Initialized field.. - if (Initialized) - { - // remove the menu constructed by the plug-in from the hosting - // program's (ScriptNotepad) menu for plug-ins.. - pluginMenuStrip.DropDownItems.Remove(pluginMainMenu); + // remove the menu constructed by the plug-in from the hosting + // program's (ScriptNotepad) menu for plug-ins.. + pluginMenuStrip.DropDownItems.Remove(pluginMainMenu); - // unsubscribe the events.. - pluginAboutMenu.Click -= PluginAboutMenu_Click; - pluginCauseException.Click -= PluginCauseException_Click; - pluginROT13.Click -= PluginROT13_Click; - pluginUnROT13.Click -= PluginUnROT13_Click; + // unsubscribe the events.. + pluginAboutMenu.Click -= PluginAboutMenu_Click; + pluginCauseException.Click -= PluginCauseException_Click; + pluginROT13.Click -= PluginROT13_Click; + pluginUnROT13.Click -= PluginUnROT13_Click; - using (pluginMainMenu) - { - // dispose of the menu created for the plug-in.. - }; + using (pluginMainMenu) + { + // dispose of the menu created for the plug-in.. + }; - // leave no references to the host program's (ScriptNotepad) menu.. - pluginMenuStrip = null; - } + // leave no references to the host program's (ScriptNotepad) menu.. + pluginMenuStrip = null; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Database/DirectAccess/CheckFluentMigrator.cs b/ScriptNotepad/Database/DirectAccess/CheckFluentMigrator.cs index 1458b41d..f89b8109 100644 --- a/ScriptNotepad/Database/DirectAccess/CheckFluentMigrator.cs +++ b/ScriptNotepad/Database/DirectAccess/CheckFluentMigrator.cs @@ -1,34 +1,33 @@ using System.Data.SQLite; -namespace ScriptNotepad.Database.DirectAccess +namespace ScriptNotepad.Database.DirectAccess; + +/// +/// A class to create the VersionInfo table in case the code-first database already exists. +/// +internal class CheckFluentMigrator { /// - /// A class to create the VersionInfo table in case the code-first database already exists. + /// Marks the first database migration as done. /// - internal class CheckFluentMigrator + /// The connection string fot the SQLite database table. + public static void MarkMigration(string connectionString) { - /// - /// Marks the first database migration as done. - /// - /// The connection string fot the SQLite database table. - public static void MarkMigration(string connectionString) - { - using var connection = new SQLiteConnection(connectionString); + using var connection = new SQLiteConnection(connectionString); - connection.Open(); + connection.Open(); - using SQLiteCommand command = new SQLiteCommand( - "CREATE TABLE IF NOT EXISTS VersionInfo (Version INTEGER NOT NULL, AppliedOn DATETIME, Description TEXT);", - connection); + using SQLiteCommand command = new SQLiteCommand( + "CREATE TABLE IF NOT EXISTS VersionInfo (Version INTEGER NOT NULL, AppliedOn DATETIME, Description TEXT);", + connection); - command.ExecuteNonQuery(); + command.ExecuteNonQuery(); - command.CommandText = string.Join(Environment.NewLine, - "INSERT INTO VersionInfo (Version, AppliedOn, Description)", - // ReSharper disable once StringLiteralTypo, this is a function name in the SQLite.. - "SELECT 20210101103253, strftime('%Y-%m-%dT%H:%M:%S','now'), 'InitialMigration'", - "WHERE NOT EXISTS(SELECT * FROM VersionInfo WHERE Version = 20210101103253)"); - command.ExecuteNonQuery(); - } + command.CommandText = string.Join(Environment.NewLine, + "INSERT INTO VersionInfo (Version, AppliedOn, Description)", + // ReSharper disable once StringLiteralTypo, this is a function name in the SQLite.. + "SELECT 20220101103253, strftime('%Y-%m-%dT%H:%M:%S','now'), 'InitialMigration'", + "WHERE NOT EXISTS(SELECT * FROM VersionInfo WHERE Version = 20220101103253)"); + command.ExecuteNonQuery(); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Context/ScriptNotepadDbContext.cs b/ScriptNotepad/Database/Entity/Context/ScriptNotepadDbContext.cs index 7e649a90..997559fb 100644 --- a/ScriptNotepad/Database/Entity/Context/ScriptNotepadDbContext.cs +++ b/ScriptNotepad/Database/Entity/Context/ScriptNotepadDbContext.cs @@ -28,169 +28,168 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Entities; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Database.Entity.Context +namespace ScriptNotepad.Database.Entity.Context; + +/// +/// The database context for the ScriptNotepad . +/// Implements the +/// +/// +public class ScriptNotepadDbContext: DbContext { + private static string ConnectionString { get; set; } = "ScriptNotepadEntityCore.sqlite"; + /// - /// The database context for the ScriptNotepad . - /// Implements the + /// Initializes a new instance of the class. /// - /// - public class ScriptNotepadDbContext: DbContext + public ScriptNotepadDbContext() { - private static string ConnectionString { get; set; } = "ScriptNotepadEntityCore.sqlite"; - - /// - /// Initializes a new instance of the class. - /// - public ScriptNotepadDbContext() - { - ConnectionString ??= "ScriptNotepadEntityCore.sqlite"; - } + ConnectionString ??= "ScriptNotepadEntityCore.sqlite"; + } - /// - /// Initializes a new instance of the class. - /// - /// The connection string for a SQLite database. - public ScriptNotepadDbContext(string connectionString) - { - ScriptNotepadDbContext.ConnectionString = connectionString; - } - - /// - /// - /// Override this method to configure the database (and other options) to be used for this context. - /// This method is called for each instance of the context that is created. - /// The base implementation does nothing. - /// - /// - /// In situations where an instance of may or may not have been passed - /// to the constructor, you can use to determine if - /// the options have already been set, and skip some or all of the logic in - /// . - /// - /// - /// A builder used to create or modify options for this context. Databases (and other extensions) - /// typically define extension methods on this object that allow you to configure the context. - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + /// + /// Initializes a new instance of the class. + /// + /// The connection string for a SQLite database. + public ScriptNotepadDbContext(string connectionString) + { + ScriptNotepadDbContext.ConnectionString = connectionString; + } + + /// + /// + /// Override this method to configure the database (and other options) to be used for this context. + /// This method is called for each instance of the context that is created. + /// The base implementation does nothing. + /// + /// + /// In situations where an instance of may or may not have been passed + /// to the constructor, you can use to determine if + /// the options have already been set, and skip some or all of the logic in + /// . + /// + /// + /// A builder used to create or modify options for this context. Databases (and other extensions) + /// typically define extension methods on this object that allow you to configure the context. + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlite(ConnectionString); + base.OnConfiguring(optionsBuilder); + } + + /// + /// A static property to hold the created with the method. + /// + /// The database context. + public static ScriptNotepadDbContext DbContext { get; set; } + + /// + /// Initializes the database context. + /// + /// The connection string to initialize the underlying SQLite database connection. + /// true if the operation was successful, false otherwise. + public static bool InitializeDbContext(string connectionString) + { + try { - optionsBuilder.UseSqlite(ConnectionString); - base.OnConfiguring(optionsBuilder); + DbContext = new ScriptNotepadDbContext(connectionString); + DbContextInitialized = true; + return true; } - - /// - /// A static property to hold the created with the method. - /// - /// The database context. - public static ScriptNotepadDbContext DbContext { get; set; } - - /// - /// Initializes the database context. - /// - /// The connection string to initialize the underlying SQLite database connection. - /// true if the operation was successful, false otherwise. - public static bool InitializeDbContext(string connectionString) + catch (Exception ex) // report the exception and return false.. { - try - { - DbContext = new ScriptNotepadDbContext(connectionString); - DbContextInitialized = true; - return true; - } - catch (Exception ex) // report the exception and return false.. - { - DbContext = null; - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - DbContextInitialized = false; - return false; - } + DbContext = null; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + DbContextInitialized = false; + return false; } + } - /// - /// Gets or sets a value indicating whether the database context is initialized. - /// - /// true if the database is context initialized; otherwise, false. - internal static bool DbContextInitialized { get; set; } - - /// - /// Releases the database context. - /// - /// if set to true a the context is requested to save the changes before disposing of the context. - /// A value indicating whether to force the instance immediately to be garbage-collected. - /// true if the operation was successful, false otherwise. - public static bool ReleaseDbContext(bool save = true, bool forceGarbageCollection = false) + /// + /// Gets or sets a value indicating whether the database context is initialized. + /// + /// true if the database is context initialized; otherwise, false. + internal static bool DbContextInitialized { get; set; } + + /// + /// Releases the database context. + /// + /// if set to true a the context is requested to save the changes before disposing of the context. + /// A value indicating whether to force the instance immediately to be garbage-collected. + /// true if the operation was successful, false otherwise. + public static bool ReleaseDbContext(bool save = true, bool forceGarbageCollection = false) + { + try { - try + if (DbContext != null) // null check.. { - if (DbContext != null) // null check.. + using (DbContext) // dispose of the context.. { - using (DbContext) // dispose of the context.. + if (save) // ..if set to save, then save.. { - if (save) // ..if set to save, then save.. - { - DbContext.SaveChanges(); - } - - DbContext = null; // set to null.. + DbContext.SaveChanges(); } - if (forceGarbageCollection) - { - GC.Collect(); - GC.WaitForPendingFinalizers(); - } + DbContext = null; // set to null.. } - DbContextInitialized = false; - - return true; - } - catch (Exception ex) // report the exception and return false.. - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - DbContextInitialized = false; - return false; + if (forceGarbageCollection) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } } - } - /// - /// Gets or sets instances in the database. - /// - public DbSet FileSaves { get; set; } - - /// - /// Gets or sets the file sessions used with other entity instances. - /// - public DbSet FileSessions { get; set; } - - /// - /// Gets or sets instances in the database. - /// - public DbSet MiscellaneousTextEntries { get; set; } - - /// - /// Gets or sets the instances in the database. - /// - public DbSet Plugins { get; set; } - - /// - /// Gets or sets the instances in the database. - /// - public DbSet RecentFiles { get; set; } - - /// - /// Gets or sets the instances in the database. - /// - public DbSet CodeSnippets { get; set; } - - /// - /// Gets or sets the instances in the database. - /// - public DbSet SearchAndReplaceHistories { get; set; } - - /// - /// Gets or sets the instances in the database. - /// - /// The instances in the database. - public DbSet MiscellaneousParameters { get; set; } + DbContextInitialized = false; + + return true; + } + catch (Exception ex) // report the exception and return false.. + { + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + DbContextInitialized = false; + return false; + } } -} + + /// + /// Gets or sets instances in the database. + /// + public DbSet FileSaves { get; set; } + + /// + /// Gets or sets the file sessions used with other entity instances. + /// + public DbSet FileSessions { get; set; } + + /// + /// Gets or sets instances in the database. + /// + public DbSet MiscellaneousTextEntries { get; set; } + + /// + /// Gets or sets the instances in the database. + /// + public DbSet Plugins { get; set; } + + /// + /// Gets or sets the instances in the database. + /// + public DbSet RecentFiles { get; set; } + + /// + /// Gets or sets the instances in the database. + /// + public DbSet CodeSnippets { get; set; } + + /// + /// Gets or sets the instances in the database. + /// + public DbSet SearchAndReplaceHistories { get; set; } + + /// + /// Gets or sets the instances in the database. + /// + /// The instances in the database. + public DbSet MiscellaneousParameters { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Entities/CodeSnippet.cs b/ScriptNotepad/Database/Entity/Entities/CodeSnippet.cs index b3d8b6b6..aa202a98 100644 --- a/ScriptNotepad/Database/Entity/Entities/CodeSnippet.cs +++ b/ScriptNotepad/Database/Entity/Entities/CodeSnippet.cs @@ -29,54 +29,53 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.ComponentModel.DataAnnotations.Schema; using ScriptNotepad.Database.Entity.Enumerations; -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class for storing code snippets into the database. +/// Implements the +/// +/// +[Table("CodeSnippets")] +public class CodeSnippet: IEntity { /// - /// A class for storing code snippets into the database. - /// Implements the + /// Gets or sets the identifier for the entity. /// - /// - [Table("CodeSnippets")] - public class CodeSnippet: IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } + public int Id { get; set; } - /// - /// Gets or sets the script's contents. - /// - public string? ScriptContents { get; set; } + /// + /// Gets or sets the script's contents. + /// + public string? ScriptContents { get; set; } - /// - /// Gets or sets the name of the script. - /// - public string ScriptName { get; set; } = string.Empty; + /// + /// Gets or sets the name of the script. + /// + public string ScriptName { get; set; } = string.Empty; - /// - /// Gets or sets the date and time when the script was previously modified. - /// - public DateTime Modified { get; set; } + /// + /// Gets or sets the date and time when the script was previously modified. + /// + public DateTime Modified { get; set; } - /// - /// Gets or sets the language type of the script snippet. - /// - public CodeSnippetLanguage ScriptLanguage { get; set; } + /// + /// Gets or sets the language type of the script snippet. + /// + public CodeSnippetLanguage ScriptLanguage { get; set; } - /// - /// Gets or sets the type of the script text manipulation. - /// - public ScriptSnippetType ScriptTextManipulationType { get; set; } + /// + /// Gets or sets the type of the script text manipulation. + /// + public ScriptSnippetType ScriptTextManipulationType { get; set; } - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return ScriptName; - } + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return ScriptName; } } diff --git a/ScriptNotepad/Database/Entity/Entities/FileSave.cs b/ScriptNotepad/Database/Entity/Entities/FileSave.cs index b126637c..aa154df4 100644 --- a/ScriptNotepad/Database/Entity/Entities/FileSave.cs +++ b/ScriptNotepad/Database/Entity/Entities/FileSave.cs @@ -29,131 +29,130 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #nullable enable -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class representing a single file save entry in the database. +/// Implements the +/// Implements the +/// +/// +/// +[Table("FileSaves")] +public class FileSave: IEntity { /// - /// A class representing a single file save entry in the database. - /// Implements the - /// Implements the - /// - /// - /// - [Table("FileSaves")] - public class FileSave: IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } - - /// - /// Gets or sets the session identifier. - /// - /// The session identifier. - public int SessionId { get; set; } - - /// - /// Gets or sets a string representing the encoding of the file save. - /// - public string EncodingAsString { get; set; } = "utf-8;65001;True;False;False"; - - /// - /// Gets or sets a value indicating whether the file exists in the file system. - /// - public bool ExistsInFileSystem { get; set; } - - /// - /// Gets or sets the full file name with path. - /// - public string FileNameFull { get; set; } = string.Empty; - - /// - /// Gets or sets the file name without path. - /// - public string FileName { get; set; } = string.Empty; - - /// - /// Gets or sets the full path for the file. - /// - public string? FilePath { get; set; } - - /// - /// Gets or sets the value indicating when the file was modified in the file system. - /// - public DateTime FileSystemModified { get; set; } - - /// - /// Gets or sets the value indicating when the file was saved to the file system by the software. - /// - public DateTime FileSystemSaved { get; set; } - - /// - /// Gets or sets the value indicating when the file was modified in the database. - /// - public DateTime DatabaseModified { get; set; } = DateTime.MinValue; - - /// - /// Gets or sets the lexer number with the ScintillaNET. - /// - public LexerEnumerations.LexerType LexerType { get; set; } - - /// - /// Gets or sets a value indicating whether to use the file system to store the contents of the file instead of a database BLOB. - /// - public bool? UseFileSystemOnContents { get; set; } - - /// - /// Gets or sets the location of the temporary file save in case the file changes are cached into the file system. - /// - public string? TemporaryFileSaveName { get; set; } - - /// - /// Gets or sets the file contents. - /// - public byte[]? FileContents { get; set; } - - /// - /// Gets or sets the visibility order (in a tabbed control). - /// - public int VisibilityOrder { get; set; } - - /// - /// Gets or sets a value indicating whether the file is activated in the tab control. - /// - public bool IsActive { get; set; } - - /// - /// Gets or sets a value indicating whether this entry is a history entry. - /// - public bool IsHistory { get; set; } = false; - - /// - /// Gets or sets the current position (cursor / caret) of the file. - /// - public int CurrentCaretPosition { get; set; } - - /// - /// Gets or sets a value indicating whether to use spell check with this document. - /// - public bool UseSpellChecking { get; set; } - - /// - /// Gets or sets the editor zoom value in percentage. - /// - public int EditorZoomPercentage { get; set; } - - /// - /// Gets or sets the value containing the document folding data. - /// - /// The value containing the document folding data. - public string FoldSave { get; set; } = string.Empty; - - /// - /// Gets or sets the session the belongs to. - /// - [ForeignKey(nameof(SessionId))] - public virtual FileSession? Session { get; set; } - } + /// Gets or sets the identifier for the entity. + /// + public int Id { get; set; } + + /// + /// Gets or sets the session identifier. + /// + /// The session identifier. + public int SessionId { get; set; } + + /// + /// Gets or sets a string representing the encoding of the file save. + /// + public string EncodingAsString { get; set; } = "utf-8;65001;True;False;False"; + + /// + /// Gets or sets a value indicating whether the file exists in the file system. + /// + public bool ExistsInFileSystem { get; set; } + + /// + /// Gets or sets the full file name with path. + /// + public string FileNameFull { get; set; } = string.Empty; + + /// + /// Gets or sets the file name without path. + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Gets or sets the full path for the file. + /// + public string? FilePath { get; set; } + + /// + /// Gets or sets the value indicating when the file was modified in the file system. + /// + public DateTime FileSystemModified { get; set; } + + /// + /// Gets or sets the value indicating when the file was saved to the file system by the software. + /// + public DateTime FileSystemSaved { get; set; } + + /// + /// Gets or sets the value indicating when the file was modified in the database. + /// + public DateTime DatabaseModified { get; set; } = DateTime.MinValue; + + /// + /// Gets or sets the lexer number with the ScintillaNET. + /// + public LexerEnumerations.LexerType LexerType { get; set; } + + /// + /// Gets or sets a value indicating whether to use the file system to store the contents of the file instead of a database BLOB. + /// + public bool? UseFileSystemOnContents { get; set; } + + /// + /// Gets or sets the location of the temporary file save in case the file changes are cached into the file system. + /// + public string? TemporaryFileSaveName { get; set; } + + /// + /// Gets or sets the file contents. + /// + public byte[]? FileContents { get; set; } + + /// + /// Gets or sets the visibility order (in a tabbed control). + /// + public int VisibilityOrder { get; set; } + + /// + /// Gets or sets a value indicating whether the file is activated in the tab control. + /// + public bool IsActive { get; set; } + + /// + /// Gets or sets a value indicating whether this entry is a history entry. + /// + public bool IsHistory { get; set; } = false; + + /// + /// Gets or sets the current position (cursor / caret) of the file. + /// + public int CurrentCaretPosition { get; set; } + + /// + /// Gets or sets a value indicating whether to use spell check with this document. + /// + public bool UseSpellChecking { get; set; } + + /// + /// Gets or sets the editor zoom value in percentage. + /// + public int EditorZoomPercentage { get; set; } + + /// + /// Gets or sets the value containing the document folding data. + /// + /// The value containing the document folding data. + public string FoldSave { get; set; } = string.Empty; + + /// + /// Gets or sets the session the belongs to. + /// + [ForeignKey(nameof(SessionId))] + public virtual FileSession? Session { get; set; } } #nullable restore \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Entities/FileSession.cs b/ScriptNotepad/Database/Entity/Entities/FileSession.cs index 5475716b..3494eeb9 100644 --- a/ScriptNotepad/Database/Entity/Entities/FileSession.cs +++ b/ScriptNotepad/Database/Entity/Entities/FileSession.cs @@ -28,42 +28,41 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.ComponentModel.DataAnnotations.Schema; -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class for storing session(s) into the database. +/// +[Table("FileSessions")] +public class FileSession: IEntity { /// - /// A class for storing session(s) into the database. + /// Gets or sets the identifier for the entity. /// - [Table("FileSessions")] - public class FileSession: IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } + public int Id { get; set; } - /// - /// Gets or sets the name of a session. - /// - public string? SessionName { get; set; } + /// + /// Gets or sets the name of a session. + /// + public string? SessionName { get; set; } - /// - /// Gets or sets the temporary file path in case the file system is used to cache the contents - /// of the entities belonging to the session. - /// - public string? TemporaryFilePath { get; set; } + /// + /// Gets or sets the temporary file path in case the file system is used to cache the contents + /// of the entities belonging to the session. + /// + public string? TemporaryFilePath { get; set; } - /// - /// Gets or sets a value indicating whether to use the file system to store the contents of the file instead of a database BLOB. - /// - public bool UseFileSystemOnContents { get; set; } + /// + /// Gets or sets a value indicating whether to use the file system to store the contents of the file instead of a database BLOB. + /// + public bool UseFileSystemOnContents { get; set; } - /// - /// Returns a that represents this instance. - /// - public override string? ToString() - { - return SessionName; - } + /// + /// Returns a that represents this instance. + /// + public override string? ToString() + { + return SessionName; } } diff --git a/ScriptNotepad/Database/Entity/Entities/MiscellaneousParameter.cs b/ScriptNotepad/Database/Entity/Entities/MiscellaneousParameter.cs index 790a6ee4..75626927 100644 --- a/ScriptNotepad/Database/Entity/Entities/MiscellaneousParameter.cs +++ b/ScriptNotepad/Database/Entity/Entities/MiscellaneousParameter.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,34 +28,33 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #nullable enable -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class for miscellaneous entries, I.e. history data entered into database. +/// Implements the +/// +/// +[Table("MiscellaneousParameters")] +public class MiscellaneousParameter: IEntity { /// - /// A class for miscellaneous entries, I.e. history data entered into database. - /// Implements the + /// Gets or sets the identifier for the entity. + /// + /// The identifier. + public int Id { get; set; } + + /// + /// Gets or sets the when the entry was added to the database. + /// + /// The when the entry was added to the database. + public DateTime Added { get; set; } + + /// + /// Gets or sets the value. /// - /// - [Table("MiscellaneousParameters")] - public class MiscellaneousParameter: IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - /// The identifier. - public int Id { get; set; } - - /// - /// Gets or sets the when the entry was added to the database. - /// - /// The when the entry was added to the database. - public DateTime Added { get; set; } - - /// - /// Gets or sets the value. - /// - /// The value. - public string Value { get; set; } = string.Empty; - } + /// The value. + public string Value { get; set; } = string.Empty; } #nullable restore diff --git a/ScriptNotepad/Database/Entity/Entities/MiscellaneousTextEntry.cs b/ScriptNotepad/Database/Entity/Entities/MiscellaneousTextEntry.cs index acbe2453..3cda33e7 100644 --- a/ScriptNotepad/Database/Entity/Entities/MiscellaneousTextEntry.cs +++ b/ScriptNotepad/Database/Entity/Entities/MiscellaneousTextEntry.cs @@ -29,56 +29,55 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #nullable enable -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class for storing miscellaneous text data into the database. +/// Implements the +/// +/// +[Table("MiscellaneousTextEntries")] +public class MiscellaneousTextEntry: IEntity { /// - /// A class for storing miscellaneous text data into the database. - /// Implements the + /// Gets or sets the identifier for the entity. /// - /// - [Table("MiscellaneousTextEntries")] - public class MiscellaneousTextEntry: IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } + public int Id { get; set; } - /// - /// Gets or sets the session identifier. - /// - /// The session identifier. - public int SessionId { get; set; } + /// + /// Gets or sets the session identifier. + /// + /// The session identifier. + public int SessionId { get; set; } - /// - /// Gets or sets the text value. - /// - public string TextValue { get; set; } = string.Empty; + /// + /// Gets or sets the text value. + /// + public string TextValue { get; set; } = string.Empty; - /// - /// Gets or sets the type of the text. - /// - public MiscellaneousTextType TextType { get; set; } + /// + /// Gets or sets the type of the text. + /// + public MiscellaneousTextType TextType { get; set; } - /// - /// Gets or sets the added date and time when the entry was added or updated to the database. - /// - public DateTime Added { get; set; } + /// + /// Gets or sets the added date and time when the entry was added or updated to the database. + /// + public DateTime Added { get; set; } - /// - /// Gets or sets the this miscellaneous text data belongs to. - /// - [ForeignKey(nameof(SessionId))] - public virtual FileSession? Session { get; set; } + /// + /// Gets or sets the this miscellaneous text data belongs to. + /// + [ForeignKey(nameof(SessionId))] + public virtual FileSession? Session { get; set; } - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return TextValue; - } + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return TextValue; } } diff --git a/ScriptNotepad/Database/Entity/Entities/Plugin.cs b/ScriptNotepad/Database/Entity/Entities/Plugin.cs index d4e27687..0b79d779 100644 --- a/ScriptNotepad/Database/Entity/Entities/Plugin.cs +++ b/ScriptNotepad/Database/Entity/Entities/Plugin.cs @@ -28,105 +28,104 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #nullable enable -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class to store plug-in data into the database. +/// Implements the +/// Implements the +/// +/// +/// +[Table("Plugins")] +public class Plugin : IEntity { /// - /// A class to store plug-in data into the database. - /// Implements the - /// Implements the + /// Gets or sets the identifier for the entity. /// - /// - /// - [Table("Plugins")] - public class Plugin : IEntity + public int Id { get; set; } + + /// + /// Gets or sets the full file name with path of the plug-in assembly. + /// + public string FileNameFull { get; set; } = string.Empty; + + /// + /// Gets or sets the full file name without path of the plug-in assembly. + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Gets or sets the full path of the plug-in assembly. + /// + public string FilePath { get; set; } = string.Empty; + + /// + /// Gets or sets the name of the plug-in. + /// + public string PluginName { get; set; } = string.Empty; + + /// + /// Gets or sets the version of the plug-in assembly. + /// + public string PluginVersion { get; set; } = string.Empty; + + /// + /// Gets or sets the description of the plug-in. + /// + public string PluginDescription { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether the plug-in is active. + /// + public bool IsActive { get; set; } + + /// + /// Gets or sets the exception count the plug-in has reported via an event. + /// + public int ExceptionCount { get; set; } + + /// + /// Gets or sets the amount of failed load attempts for the plug-in. + /// + public int LoadFailures { get; set; } + + /// + /// Gets or sets the amount of how many times the plug-in has crashed the entire software. + /// + public int ApplicationCrashes { get; set; } + + /// + /// Gets or sets the sort order for the plug-in during the load process. + /// + public int SortOrder { get; set; } + + /// + /// Gets or sets the rating for the plug-in (0-100). + /// + public int Rating { get; set; } = 50; + + /// + /// Gets or sets the date and time when the plug-in was installed. + /// + public DateTime PluginInstalled { get; set; } + + /// + /// Gets or sets the date and time when the plug-in was updated. + /// + public DateTime PluginUpdated { get; set; } + + /// + /// Gets or sets a flag indicating if the plug-in is pending for deletion from the plug-ins folder on application restart. + /// + public bool PendingDeletion { get; set; } + + /// + /// Returns a that represents this instance. + /// + public override string ToString() { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } - - /// - /// Gets or sets the full file name with path of the plug-in assembly. - /// - public string FileNameFull { get; set; } = string.Empty; - - /// - /// Gets or sets the full file name without path of the plug-in assembly. - /// - public string FileName { get; set; } = string.Empty; - - /// - /// Gets or sets the full path of the plug-in assembly. - /// - public string FilePath { get; set; } = string.Empty; - - /// - /// Gets or sets the name of the plug-in. - /// - public string PluginName { get; set; } = string.Empty; - - /// - /// Gets or sets the version of the plug-in assembly. - /// - public string PluginVersion { get; set; } = string.Empty; - - /// - /// Gets or sets the description of the plug-in. - /// - public string PluginDescription { get; set; } = string.Empty; - - /// - /// Gets or sets a value indicating whether the plug-in is active. - /// - public bool IsActive { get; set; } - - /// - /// Gets or sets the exception count the plug-in has reported via an event. - /// - public int ExceptionCount { get; set; } - - /// - /// Gets or sets the amount of failed load attempts for the plug-in. - /// - public int LoadFailures { get; set; } - - /// - /// Gets or sets the amount of how many times the plug-in has crashed the entire software. - /// - public int ApplicationCrashes { get; set; } - - /// - /// Gets or sets the sort order for the plug-in during the load process. - /// - public int SortOrder { get; set; } - - /// - /// Gets or sets the rating for the plug-in (0-100). - /// - public int Rating { get; set; } = 50; - - /// - /// Gets or sets the date and time when the plug-in was installed. - /// - public DateTime PluginInstalled { get; set; } - - /// - /// Gets or sets the date and time when the plug-in was updated. - /// - public DateTime PluginUpdated { get; set; } - - /// - /// Gets or sets a flag indicating if the plug-in is pending for deletion from the plug-ins folder on application restart. - /// - public bool PendingDeletion { get; set; } - - /// - /// Returns a that represents this instance. - /// - public override string ToString() - { - return PluginName + " / " + PluginDescription; - } + return PluginName + " / " + PluginDescription; } } diff --git a/ScriptNotepad/Database/Entity/Entities/RecentFile.cs b/ScriptNotepad/Database/Entity/Entities/RecentFile.cs index d0cce6af..8e3b6037 100644 --- a/ScriptNotepad/Database/Entity/Entities/RecentFile.cs +++ b/ScriptNotepad/Database/Entity/Entities/RecentFile.cs @@ -28,65 +28,64 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.ComponentModel.DataAnnotations.Schema; -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class for storing recent file data into the database. +/// Implements the +/// +/// +[Table("RecentFiles")] +public class RecentFile: IEntity { /// - /// A class for storing recent file data into the database. - /// Implements the + /// Gets or sets the identifier for the entity. /// - /// - [Table("RecentFiles")] - public class RecentFile: IEntity + public int Id { get; set; } + + /// + /// Gets or sets the session identifier. + /// + /// The session identifier. + public int SessionId { get; set; } + + /// + /// Gets or sets the full file name with path. + /// + public string FileNameFull { get; set; } = string.Empty; + + /// + /// Gets or sets the file name without path. + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Gets or sets the full path for the file. + /// + public string? FilePath { get; set; } + + /// + /// Gets or sets the date and time when the file was closed in the editor. + /// + public DateTime ClosedDateTime { get; set; } + + /// + /// Gets or sets the session the recent file belongs to. + /// + [ForeignKey(nameof(SessionId))] + public virtual FileSession? Session { get; set; } + + /// + /// Gets or sets a string representing the encoding of the file save. + /// + public string EncodingAsString { get; set; } = "utf-8;65001;True;False;False"; + + /// + /// Returns a that represents this instance. + /// + public override string ToString() { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } - - /// - /// Gets or sets the session identifier. - /// - /// The session identifier. - public int SessionId { get; set; } - - /// - /// Gets or sets the full file name with path. - /// - public string FileNameFull { get; set; } = string.Empty; - - /// - /// Gets or sets the file name without path. - /// - public string FileName { get; set; } = string.Empty; - - /// - /// Gets or sets the full path for the file. - /// - public string? FilePath { get; set; } - - /// - /// Gets or sets the date and time when the file was closed in the editor. - /// - public DateTime ClosedDateTime { get; set; } - - /// - /// Gets or sets the session the recent file belongs to. - /// - [ForeignKey(nameof(SessionId))] - public virtual FileSession? Session { get; set; } - - /// - /// Gets or sets a string representing the encoding of the file save. - /// - public string EncodingAsString { get; set; } = "utf-8;65001;True;False;False"; - - /// - /// Returns a that represents this instance. - /// - public override string ToString() - { - return FileNameFull; - } + return FileNameFull; } } diff --git a/ScriptNotepad/Database/Entity/Entities/SearchAndReplaceHistory.cs b/ScriptNotepad/Database/Entity/Entities/SearchAndReplaceHistory.cs index ad85d312..6a3e9553 100644 --- a/ScriptNotepad/Database/Entity/Entities/SearchAndReplaceHistory.cs +++ b/ScriptNotepad/Database/Entity/Entities/SearchAndReplaceHistory.cs @@ -29,66 +29,65 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #nullable enable -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class to store search or replace history into the database. +/// Implements the +/// +/// +[Table("SearchAndReplaceHistories")] +public class SearchAndReplaceHistory : IEntity { /// - /// A class to store search or replace history into the database. - /// Implements the + /// Gets or sets the identifier for the entity. + /// + /// The identifier. + public int Id { get; set; } + + /// + /// Gets or sets the session identifier. + /// + /// The session identifier. + public int SessionId { get; set; } + + /// + /// Gets or sets the search or replace text. + /// + public string SearchOrReplaceText { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether search or replace was case sensitive. + /// + public bool CaseSensitive { get; set; } + + /// + /// Gets or sets the type of the search. + /// + public SearchAndReplaceSearchType SearchAndReplaceSearchType { get; set; } + + /// + /// Gets or sets the type of the search or replace. + /// + public SearchAndReplaceType SearchAndReplaceType { get; set; } + + /// + /// Gets or sets the added date and time when the entry was added to the database or created. + /// + public DateTime Added { get; set; } + + /// + /// Gets or sets the session the search or replace history entry belongs to. + /// + [ForeignKey(nameof(SessionId))] + public virtual FileSession? Session { get; set; } + + /// + /// Returns a that represents this instance. /// - /// - [Table("SearchAndReplaceHistories")] - public class SearchAndReplaceHistory : IEntity + /// A that represents this instance. + public override string ToString() { - /// - /// Gets or sets the identifier for the entity. - /// - /// The identifier. - public int Id { get; set; } - - /// - /// Gets or sets the session identifier. - /// - /// The session identifier. - public int SessionId { get; set; } - - /// - /// Gets or sets the search or replace text. - /// - public string SearchOrReplaceText { get; set; } = string.Empty; - - /// - /// Gets or sets a value indicating whether search or replace was case sensitive. - /// - public bool CaseSensitive { get; set; } - - /// - /// Gets or sets the type of the search. - /// - public SearchAndReplaceSearchType SearchAndReplaceSearchType { get; set; } - - /// - /// Gets or sets the type of the search or replace. - /// - public SearchAndReplaceType SearchAndReplaceType { get; set; } - - /// - /// Gets or sets the added date and time when the entry was added to the database or created. - /// - public DateTime Added { get; set; } - - /// - /// Gets or sets the session the search or replace history entry belongs to. - /// - [ForeignKey(nameof(SessionId))] - public virtual FileSession? Session { get; set; } - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return SearchOrReplaceText; - } + return SearchOrReplaceText; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Entities/SoftwareLicense.cs b/ScriptNotepad/Database/Entity/Entities/SoftwareLicense.cs index b4f15a99..25455942 100644 --- a/ScriptNotepad/Database/Entity/Entities/SoftwareLicense.cs +++ b/ScriptNotepad/Database/Entity/Entities/SoftwareLicense.cs @@ -28,31 +28,30 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #nullable enable -namespace ScriptNotepad.Database.Entity.Entities +namespace ScriptNotepad.Database.Entity.Entities; + +/// +/// A class to save the license of the software to the database. +/// Implements the +/// +[Table("SoftwareLicenses")] +public class SoftwareLicense: IEntity { /// - /// A class to save the license of the software to the database. - /// Implements the + /// Gets or sets the identifier for the entity. /// - [Table("SoftwareLicenses")] - public class SoftwareLicense: IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - public int Id { get; set; } - - /// - /// Gets or sets the license text. - /// - public string LicenseText { get; set; } = string.Empty; - - /// - /// Gets or sets the license SPDX identifier. - /// See: https://spdx.org/licenses/ - /// - public string LicenseSpdxIdentifier { get; set; } = string.Empty; - } + public int Id { get; set; } + + /// + /// Gets or sets the license text. + /// + public string LicenseText { get; set; } = string.Empty; + + /// + /// Gets or sets the license SPDX identifier. + /// See: https://spdx.org/licenses/ + /// + public string LicenseSpdxIdentifier { get; set; } = string.Empty; } #nullable restore \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Enumerations/CodeSnippetLanguage.cs b/ScriptNotepad/Database/Entity/Enumerations/CodeSnippetLanguage.cs index d5aaf45d..95af79ee 100644 --- a/ScriptNotepad/Database/Entity/Enumerations/CodeSnippetLanguage.cs +++ b/ScriptNotepad/Database/Entity/Enumerations/CodeSnippetLanguage.cs @@ -24,16 +24,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.Database.Entity.Enumerations +namespace ScriptNotepad.Database.Entity.Enumerations; + +/// +/// An enumeration for a code snippet language. +/// +public enum CodeSnippetLanguage { /// - /// An enumeration for a code snippet language. + /// The C# programming language. /// - public enum CodeSnippetLanguage - { - /// - /// The C# programming language. - /// - Cs, - } -} + Cs, +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Enumerations/MiscellaneousTextType.cs b/ScriptNotepad/Database/Entity/Enumerations/MiscellaneousTextType.cs index c1684ddc..4a4a802b 100644 --- a/ScriptNotepad/Database/Entity/Enumerations/MiscellaneousTextType.cs +++ b/ScriptNotepad/Database/Entity/Enumerations/MiscellaneousTextType.cs @@ -26,26 +26,25 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Entities; -namespace ScriptNotepad.Database.Entity.Enumerations +namespace ScriptNotepad.Database.Entity.Enumerations; + +/// +/// An enumeration for the type. +/// +public enum MiscellaneousTextType { /// - /// An enumeration for the type. + /// Indicates a path/directory in the file system. + /// + Path = 0, + + /// + /// Indicates a file extension list delimited with semicolon (;); I.e. *.txt;*.cs. + /// + FileExtensionList = 1, + + /// + /// The regular expression sorting within the custom sort dialog. /// - public enum MiscellaneousTextType - { - /// - /// Indicates a path/directory in the file system. - /// - Path = 0, - - /// - /// Indicates a file extension list delimited with semicolon (;); I.e. *.txt;*.cs. - /// - FileExtensionList = 1, - - /// - /// The regular expression sorting within the custom sort dialog. - /// - RegexSorting = 2, - } + RegexSorting = 2, } \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Enumerations/ScriptSnippetType.cs b/ScriptNotepad/Database/Entity/Enumerations/ScriptSnippetType.cs index 7253276a..bc2fb37a 100644 --- a/ScriptNotepad/Database/Entity/Enumerations/ScriptSnippetType.cs +++ b/ScriptNotepad/Database/Entity/Enumerations/ScriptSnippetType.cs @@ -24,21 +24,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.Database.Entity.Enumerations +namespace ScriptNotepad.Database.Entity.Enumerations; + +/// +/// An enumeration for the script snippet text manipulation type. +/// +public enum ScriptSnippetType { /// - /// An enumeration for the script snippet text manipulation type. + /// The text is manipulated as a single string. /// - public enum ScriptSnippetType - { - /// - /// The text is manipulated as a single string. - /// - Text, + Text, - /// - /// The text is manipulated as a collection of lines. - /// - Lines, - } -} + /// + /// The text is manipulated as a collection of lines. + /// + Lines, +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceSearchType.cs b/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceSearchType.cs index 11d8f8a2..364547e6 100644 --- a/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceSearchType.cs +++ b/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceSearchType.cs @@ -24,37 +24,36 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.Database.Entity.Enumerations +namespace ScriptNotepad.Database.Entity.Enumerations; + +/// +/// An enumeration for a text search type. +/// +[Flags] +public enum SearchAndReplaceSearchType { /// - /// An enumeration for a text search type. + /// A normal text search. + /// + Normal = 1, + + /// + /// An extended text search. + /// + Extended = 2, + + /// + /// A text search using regular expressions. + /// + RegularExpression = 4, + + /// + /// The simple text search with some additional extended formatting possibilities. + /// + SimpleExtended = 8, + + /// + /// All the possibilities combined. /// - [Flags] - public enum SearchAndReplaceSearchType - { - /// - /// A normal text search. - /// - Normal = 1, - - /// - /// An extended text search. - /// - Extended = 2, - - /// - /// A text search using regular expressions. - /// - RegularExpression = 4, - - /// - /// The simple text search with some additional extended formatting possibilities. - /// - SimpleExtended = 8, - - /// - /// All the possibilities combined. - /// - All = Normal | Extended | RegularExpression | SimpleExtended, - } -} + All = Normal | Extended | RegularExpression | SimpleExtended, +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceType.cs b/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceType.cs index 1f8b33cf..0a2c71b7 100644 --- a/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceType.cs +++ b/ScriptNotepad/Database/Entity/Enumerations/SearchAndReplaceType.cs @@ -24,21 +24,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.Database.Entity.Enumerations +namespace ScriptNotepad.Database.Entity.Enumerations; + +/// +/// An enumeration for a type of a search. +/// +public enum SearchAndReplaceType { /// - /// An enumeration for a type of a search. + /// The type of the search and replace history is search. /// - public enum SearchAndReplaceType - { - /// - /// The type of the search and replace history is search. - /// - Search, + Search, - /// - /// The type of the search and replace history is replace. - /// - Replace, - } -} + /// + /// The type of the search and replace history is replace. + /// + Replace, +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/IEntity.cs b/ScriptNotepad/Database/Entity/IEntity.cs index 758a4573..e26d6d69 100644 --- a/ScriptNotepad/Database/Entity/IEntity.cs +++ b/ScriptNotepad/Database/Entity/IEntity.cs @@ -24,16 +24,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.Database.Entity +namespace ScriptNotepad.Database.Entity; + +/// +/// An interface for an entity. +/// +interface IEntity { /// - /// An interface for an entity. + /// Gets or sets the identifier for the entity. /// - interface IEntity - { - /// - /// Gets or sets the identifier for the entity. - /// - int Id { get; set; } - } -} + int Id { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Entity/Migrations/01_InitialMigration.cs b/ScriptNotepad/Database/Entity/Migrations/01_InitialMigration.cs index 55144d36..86cf3674 100644 --- a/ScriptNotepad/Database/Entity/Migrations/01_InitialMigration.cs +++ b/ScriptNotepad/Database/Entity/Migrations/01_InitialMigration.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -36,7 +36,7 @@ namespace ScriptNotepad.Database.Entity.Migrations /// Implements the /// /// - [Migration(2021_0101_10_32_53)] + [Migration(2022_0101_10_32_53)] public class InitialMigration: Migration { /// diff --git a/ScriptNotepad/Database/Entity/Migrations/02_FoldSave.cs b/ScriptNotepad/Database/Entity/Migrations/02_FoldSave.cs index e8b44c65..d8b6e3f6 100644 --- a/ScriptNotepad/Database/Entity/Migrations/02_FoldSave.cs +++ b/ScriptNotepad/Database/Entity/Migrations/02_FoldSave.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -34,7 +34,7 @@ namespace ScriptNotepad.Database.Entity.Migrations /// Implements the /// /// - [Migration(2021_0325_17_17_49)] + [Migration(2022_0325_17_17_49)] public class FoldSave: Migration { /// diff --git a/ScriptNotepad/Database/Entity/Migrations/03_FixEmptySession.cs b/ScriptNotepad/Database/Entity/Migrations/03_FixEmptySession.cs index 01deac9a..61c0ceab 100644 --- a/ScriptNotepad/Database/Entity/Migrations/03_FixEmptySession.cs +++ b/ScriptNotepad/Database/Entity/Migrations/03_FixEmptySession.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -34,7 +34,7 @@ namespace ScriptNotepad.Database.Entity.Migrations /// Implements the /// /// - [Migration(2021_0609_21_15_38)] + [Migration(2022_0609_21_15_38)] public class FixEmptySession : Migration { /// diff --git a/ScriptNotepad/Database/Entity/Migrations/ExecuteDatabaseMigrate.cs b/ScriptNotepad/Database/Entity/Migrations/ExecuteDatabaseMigrate.cs index 01fb5fff..d617a2a9 100644 --- a/ScriptNotepad/Database/Entity/Migrations/ExecuteDatabaseMigrate.cs +++ b/ScriptNotepad/Database/Entity/Migrations/ExecuteDatabaseMigrate.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,75 +28,74 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using Microsoft.Extensions.DependencyInjection; // This sample (C): https://fluentmigrator.github.io/articles/quickstart.html?tabs=runner-in-process -namespace ScriptNotepad.Database.Entity.Migrations +namespace ScriptNotepad.Database.Entity.Migrations; + +/// +/// A class to run the database migrations. +/// +public static class ExecuteDatabaseMigrate { /// - /// A class to run the database migrations. + /// Migrates the database changes with the specified connection string. /// - public static class ExecuteDatabaseMigrate + /// The SQLite connection string. + public static void Migrate(string connectionString) { - /// - /// Migrates the database changes with the specified connection string. - /// - /// The SQLite connection string. - public static void Migrate(string connectionString) - { - ConnectionString = connectionString; + ConnectionString = connectionString; - var serviceProvider = CreateServices(); + var serviceProvider = CreateServices(); - // Put the database update into a scope to ensure - // that all resources will be disposed. - using var scope = serviceProvider.CreateScope(); - UpdateDatabase(scope.ServiceProvider); - } + // Put the database update into a scope to ensure + // that all resources will be disposed. + using var scope = serviceProvider.CreateScope(); + UpdateDatabase(scope.ServiceProvider); + } - /// - /// Gets or sets the name for the default session in the database. - /// - /// The name for the default session in the database. - public static string DefaultSessionName { get; set; } = @"Default"; + /// + /// Gets or sets the name for the default session in the database. + /// + /// The name for the default session in the database. + public static string DefaultSessionName { get; set; } = @"Default"; - /// - /// Gets or sets the SQLite database connection string. - /// - /// The the SQLite database connection string. - private static string ConnectionString { get; set; } + /// + /// Gets or sets the SQLite database connection string. + /// + /// The the SQLite database connection string. + private static string ConnectionString { get; set; } - /// - /// Configure the dependency injection services - /// - private static IServiceProvider CreateServices() - { - return new ServiceCollection() - // ReSharper disable once CommentTypo - // Add common FluentMigrator services - .AddFluentMigratorCore() - .ConfigureRunner(rb => rb - // ReSharper disable once CommentTypo - // Add SQLite support to FluentMigrator - .AddSQLite() - // Set the connection string - .WithGlobalConnectionString(ConnectionString) - // Define the assembly containing the migrations - .ScanIn(typeof(InitialMigration).Assembly).For.Migrations()) + /// + /// Configure the dependency injection services + /// + private static IServiceProvider CreateServices() + { + return new ServiceCollection() + // ReSharper disable once CommentTypo + // Add common FluentMigrator services + .AddFluentMigratorCore() + .ConfigureRunner(rb => rb // ReSharper disable once CommentTypo - // Enable logging to console in the FluentMigrator way - .AddLogging(lb => lb.AddFluentMigratorConsole()) - // Build the service provider - .BuildServiceProvider(false); - } + // Add SQLite support to FluentMigrator + .AddSQLite() + // Set the connection string + .WithGlobalConnectionString(ConnectionString) + // Define the assembly containing the migrations + .ScanIn(typeof(InitialMigration).Assembly).For.Migrations()) + // ReSharper disable once CommentTypo + // Enable logging to console in the FluentMigrator way + .AddLogging(lb => lb.AddFluentMigratorConsole()) + // Build the service provider + .BuildServiceProvider(false); + } - /// - /// Update the database - /// - private static void UpdateDatabase(IServiceProvider serviceProvider) - { - // Instantiate the runner - var runner = serviceProvider.GetRequiredService(); + /// + /// Update the database + /// + private static void UpdateDatabase(IServiceProvider serviceProvider) + { + // Instantiate the runner + var runner = serviceProvider.GetRequiredService(); - // Execute the migrations - runner.MigrateUp(); - } + // Execute the migrations + runner.MigrateUp(); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Database/Helpers/DatabaseUtilities.cs b/ScriptNotepad/Database/Helpers/DatabaseUtilities.cs index 65024723..0aec7c47 100644 --- a/ScriptNotepad/Database/Helpers/DatabaseUtilities.cs +++ b/ScriptNotepad/Database/Helpers/DatabaseUtilities.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,29 +28,28 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Context; using ScriptNotepad.Database.Entity.Entities; -namespace ScriptNotepad.Database.Helpers +namespace ScriptNotepad.Database.Helpers; + +/// +/// Some database utilities for the . +/// +public static class DatabaseUtilities { /// - /// Some database utilities for the . + /// Sets the miscellaneous parameter to the database. /// - public static class DatabaseUtilities + /// The database context. + /// The value to set. + /// true if the value is already set, false otherwise. + public static bool SetMiscellaneousParameter(this ScriptNotepadDbContext context, string value) { - /// - /// Sets the miscellaneous parameter to the database. - /// - /// The database context. - /// The value to set. - /// true if the value is already set, false otherwise. - public static bool SetMiscellaneousParameter(this ScriptNotepadDbContext context, string value) + if (!context.MiscellaneousParameters.Any(f => f.Value.Equals(value, StringComparison.Ordinal))) { - if (!context.MiscellaneousParameters.Any(f => f.Value.Equals(value, StringComparison.Ordinal))) - { - return true; - } - - context.MiscellaneousParameters.Add(new MiscellaneousParameter {Added = DateTime.Now, Value = value}); - context.SaveChanges(); - return false; + return true; } + + context.MiscellaneousParameters.Add(new MiscellaneousParameter {Added = DateTime.Now, Value = value, }); + context.SaveChanges(); + return false; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/DialogForms/FormDialogQueryEncoding.cs b/ScriptNotepad/DialogForms/FormDialogQueryEncoding.cs index 6c502051..3fe9203e 100644 --- a/ScriptNotepad/DialogForms/FormDialogQueryEncoding.cs +++ b/ScriptNotepad/DialogForms/FormDialogQueryEncoding.cs @@ -28,173 +28,172 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using VPKSoft.LangLib; -namespace ScriptNotepad.DialogForms +namespace ScriptNotepad.DialogForms; + +/// +/// A dialog to query for an encoding to a file while opening a file. +/// +/// +public partial class FormDialogQueryEncoding : DBLangEngineWinforms { /// - /// A dialog to query for an encoding to a file while opening a file. + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogQueryEncoding : DBLangEngineWinforms + public FormDialogQueryEncoding() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogQueryEncoding() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - // create a new instance of the CharacterSetComboBuilder class.. - CharacterSetComboBuilder = new CharacterSetComboBuilder(cmbCharacterSet, cmbEncoding, tbFilterEncodings, false, "encoding"); + // create a new instance of the CharacterSetComboBuilder class.. + CharacterSetComboBuilder = new CharacterSetComboBuilder(cmbCharacterSet, cmbEncoding, tbFilterEncodings, false, "encoding"); - Encoding = CharacterSetComboBuilder.CurrentEncoding; + Encoding = CharacterSetComboBuilder.CurrentEncoding; - // subscribe the encoding selected event.. - CharacterSetComboBuilder.EncodingSelected += CharacterSetComboBuilder_EncodingSelected; + // subscribe the encoding selected event.. + CharacterSetComboBuilder.EncodingSelected += CharacterSetComboBuilder_EncodingSelected; - // translate the tool tips.. - ttMain.SetToolTip(btUTF8, - DBLangEngine.GetMessage("msgUTF8Encoding", "Set to Unicode (UTF8)|Set the selected encoding to UTF8 via a button click")); + // translate the tool tips.. + ttMain.SetToolTip(btUTF8, + DBLangEngine.GetMessage("msgUTF8Encoding", "Set to Unicode (UTF8)|Set the selected encoding to UTF8 via a button click")); - // translate the tool tips.. - ttMain.SetToolTip(btSystemDefaultEncoding, - DBLangEngine.GetMessage("msgSysDefaultEncoding", "Set to system default|Set the selected encoding to system's default encoding via a button click")); - } + // translate the tool tips.. + ttMain.SetToolTip(btSystemDefaultEncoding, + DBLangEngine.GetMessage("msgSysDefaultEncoding", "Set to system default|Set the selected encoding to system's default encoding via a button click")); + } - /// - /// Displays a new instance of this dialog. - /// - /// In case of Unicode (UTF8, Unicode or UTF32) whether to use the Unicode byte order mark. - /// In case of Unicode (UTF8, Unicode or UTF32) whether to fail on invalid characters. - /// An if the user accepted the dialog; otherwise null. - public static Encoding Execute(out bool unicodeBom, out bool unicodeFailInvalidCharacters) + /// + /// Displays a new instance of this dialog. + /// + /// In case of Unicode (UTF8, Unicode or UTF32) whether to use the Unicode byte order mark. + /// In case of Unicode (UTF8, Unicode or UTF32) whether to fail on invalid characters. + /// An if the user accepted the dialog; otherwise null. + public static Encoding Execute(out bool unicodeBom, out bool unicodeFailInvalidCharacters) + { + // create a new instance of this dialog.. + FormDialogQueryEncoding form = new FormDialogQueryEncoding(); + + // show the dialog and if the dialog result was OK.. + if (form.ShowDialog() == DialogResult.OK) { - // create a new instance of this dialog.. - FormDialogQueryEncoding form = new FormDialogQueryEncoding(); + unicodeBom = form.cbUseUnicodeBOM.Checked && form.cbUseUnicodeBOM.Enabled; + unicodeFailInvalidCharacters = form.cbUnicodeFailInvalidCharacters.Checked && + form.cbUnicodeFailInvalidCharacters.Enabled; - // show the dialog and if the dialog result was OK.. - if (form.ShowDialog() == DialogResult.OK) + if (form.Encoding is UTF8Encoding) { - unicodeBom = form.cbUseUnicodeBOM.Checked && form.cbUseUnicodeBOM.Enabled; - unicodeFailInvalidCharacters = form.cbUnicodeFailInvalidCharacters.Checked && - form.cbUnicodeFailInvalidCharacters.Enabled; - - if (form.Encoding is UTF8Encoding) - { - return new UTF8Encoding(unicodeBom, unicodeFailInvalidCharacters); - } - - if (form.Encoding is UnicodeEncoding) - { - return new UnicodeEncoding(form.Encoding.CodePage == 1201, unicodeBom, - unicodeFailInvalidCharacters); - } - - if (form.Encoding is UTF32Encoding) - { - return new UTF32Encoding(form.Encoding.CodePage == 12001, unicodeBom, - unicodeFailInvalidCharacters); - } + return new UTF8Encoding(unicodeBom, unicodeFailInvalidCharacters); + } - // ..so return the encoding.. - return form.Encoding; + if (form.Encoding is UnicodeEncoding) + { + return new UnicodeEncoding(form.Encoding.CodePage == 1201, unicodeBom, + unicodeFailInvalidCharacters); } - // .. so return null.. - unicodeBom = false; - unicodeFailInvalidCharacters = false; - return null; - } + if (form.Encoding is UTF32Encoding) + { + return new UTF32Encoding(form.Encoding.CodePage == 12001, unicodeBom, + unicodeFailInvalidCharacters); + } - // this event is fired when the encoding is changed from the corresponding combo box.. - private void CharacterSetComboBuilder_EncodingSelected(object sender, OnEncodingSelectedEventArgs e) - { - // save the changed value.. - Encoding = e.Encoding; + // ..so return the encoding.. + return form.Encoding; } - private Encoding encoding; + // .. so return null.. + unicodeBom = false; + unicodeFailInvalidCharacters = false; + return null; + } - /// - /// Gets or sets the encoding a user selected from the dialog. - /// - private Encoding Encoding - { - get => encoding; + // this event is fired when the encoding is changed from the corresponding combo box.. + private void CharacterSetComboBuilder_EncodingSelected(object sender, OnEncodingSelectedEventArgs e) + { + // save the changed value.. + Encoding = e.Encoding; + } - set - { - encoding = value; - btOK.Enabled = value != null; - } - } + private Encoding encoding; - /// - /// Gets or sets the character set combo box builder. - /// - private CharacterSetComboBuilder CharacterSetComboBuilder { get; set; } + /// + /// Gets or sets the encoding a user selected from the dialog. + /// + private Encoding Encoding + { + get => encoding; - // dispose of all the resourced used.. - private void FormDialogQueryEncoding_FormClosing(object sender, FormClosingEventArgs e) + set { - using (CharacterSetComboBuilder) - { - // unsubscribe the encoding selected event.. - CharacterSetComboBuilder.EncodingSelected -= CharacterSetComboBuilder_EncodingSelected; - } + encoding = value; + btOK.Enabled = value != null; } + } - private void btDefaultEncodings_Click(object sender, System.EventArgs e) - { - // select the encoding based on which button the user clicked.. - CharacterSetComboBuilder.SelectItemByEncoding(sender.Equals(btUTF8) ? Encoding.UTF8 : Encoding.Default, false); - } + /// + /// Gets or sets the character set combo box builder. + /// + private CharacterSetComboBuilder CharacterSetComboBuilder { get; set; } - private void FormDialogQueryEncoding_Shown(object sender, System.EventArgs e) + // dispose of all the resourced used.. + private void FormDialogQueryEncoding_FormClosing(object sender, FormClosingEventArgs e) + { + using (CharacterSetComboBuilder) { - tbFilterEncodings.Focus(); + // unsubscribe the encoding selected event.. + CharacterSetComboBuilder.EncodingSelected -= CharacterSetComboBuilder_EncodingSelected; } + } - private void cmbCharacterSet_SelectedIndexChanged(object sender, System.EventArgs e) - { - cbUseUnicodeBOM.Enabled = false; - cbUnicodeFailInvalidCharacters.Enabled = false; + private void btDefaultEncodings_Click(object sender, System.EventArgs e) + { + // select the encoding based on which button the user clicked.. + CharacterSetComboBuilder.SelectItemByEncoding(sender.Equals(btUTF8) ? Encoding.UTF8 : Encoding.Default, false); + } + + private void FormDialogQueryEncoding_Shown(object sender, System.EventArgs e) + { + tbFilterEncodings.Focus(); + } - tbFilterEncodings.Focus(); + private void cmbCharacterSet_SelectedIndexChanged(object sender, System.EventArgs e) + { + cbUseUnicodeBOM.Enabled = false; + cbUnicodeFailInvalidCharacters.Enabled = false; + + tbFilterEncodings.Focus(); - // the lower combo box on the dialog.. - if (sender.Equals(cmbEncoding)) + // the lower combo box on the dialog.. + if (sender.Equals(cmbEncoding)) + { + ComboBox combo = (ComboBox) sender; + if (combo.SelectedItem != null) { - ComboBox combo = (ComboBox) sender; - if (combo.SelectedItem != null) + var item = (CharacterSetComboItem) combo.SelectedItem; + if (item.Encoding.CodePage == 65001 || // UTF8.. + item.Encoding.CodePage == 1200 || // Unicode Little Endian.. + item.Encoding.CodePage == 1201 || // Unicode Big Endian.. + item.Encoding.CodePage == 12000 || // UTF32 Little Endian.. + item.Encoding.CodePage == 12001) // UTF32 Big Endian.. { - var item = (CharacterSetComboItem) combo.SelectedItem; - if (item.Encoding.CodePage == 65001 || // UTF8.. - item.Encoding.CodePage == 1200 || // Unicode Little Endian.. - item.Encoding.CodePage == 1201 || // Unicode Big Endian.. - item.Encoding.CodePage == 12000 || // UTF32 Little Endian.. - item.Encoding.CodePage == 12001) // UTF32 Big Endian.. - { - cbUseUnicodeBOM.Enabled = true; - cbUnicodeFailInvalidCharacters.Enabled = true; - } + cbUseUnicodeBOM.Enabled = true; + cbUnicodeFailInvalidCharacters.Enabled = true; } } } + } - private void pbClearFilterText_Click(object sender, System.EventArgs e) - { - tbFilterEncodings.Text = string.Empty; - } + private void pbClearFilterText_Click(object sender, System.EventArgs e) + { + tbFilterEncodings.Text = string.Empty; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/DialogForms/FormDialogQueryJumpLocation.cs b/ScriptNotepad/DialogForms/FormDialogQueryJumpLocation.cs index 6fdb53aa..13caff8b 100644 --- a/ScriptNotepad/DialogForms/FormDialogQueryJumpLocation.cs +++ b/ScriptNotepad/DialogForms/FormDialogQueryJumpLocation.cs @@ -28,77 +28,76 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using VPKSoft.LangLib; -namespace ScriptNotepad.DialogForms +namespace ScriptNotepad.DialogForms; + +/// +/// A simple goto dialog for the . +/// Implements the +/// +/// +public partial class FormDialogQueryJumpLocation : DBLangEngineWinforms { /// - /// A simple goto dialog for the . - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogQueryJumpLocation : DBLangEngineWinforms + public FormDialogQueryJumpLocation() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogQueryJumpLocation() + InitializeComponent(); + + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + + if (Utils.ShouldLocalize() != null) { - InitializeComponent(); + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + private Scintilla Scintilla { get; set; } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + /// + /// Displays the goto dialog with a specified instance. + /// + /// The Scintilla instance to use with the dialog. + public static void Execute(Scintilla scintilla) + { + if (1 >= scintilla.Lines.Count) + { + return; } - private Scintilla Scintilla { get; set; } - - /// - /// Displays the goto dialog with a specified instance. - /// - /// The Scintilla instance to use with the dialog. - public static void Execute(Scintilla scintilla) + var form = new FormDialogQueryJumpLocation { - if (1 >= scintilla.Lines.Count) + Scintilla = scintilla, + nudGoto = { - return; - } - - var form = new FormDialogQueryJumpLocation + Minimum = 1, + Maximum = scintilla.Lines.Count, + Value = scintilla.LineFromPosition(scintilla.CurrentPosition), + }, + lbEnterLineNumber = { - Scintilla = scintilla, - nudGoto = - { - Minimum = 1, - Maximum = scintilla.Lines.Count, - Value = scintilla.LineFromPosition(scintilla.CurrentPosition) - }, - lbEnterLineNumber = - { - Text = DBLangEngine.GetStatMessage("msgEnterALineNumber", - "Enter a line number ({0} - {1}):|A message for a label describing an input control to select a line number", - 1, scintilla.Lines.Count) - } - }; - form.ShowDialog(); - } + Text = DBLangEngine.GetStatMessage("msgEnterALineNumber", + "Enter a line number ({0} - {1}):|A message for a label describing an input control to select a line number", + 1, scintilla.Lines.Count), + }, + }; + form.ShowDialog(); + } - // occurs when a user selects a line number to jump to.. - private void BtGo_Click(object sender, EventArgs e) - { - Scintilla.GotoPosition(Scintilla.Lines[(int) nudGoto.Value - 1].Position); - DialogResult = DialogResult.OK; - } + // occurs when a user selects a line number to jump to.. + private void BtGo_Click(object sender, EventArgs e) + { + Scintilla.GotoPosition(Scintilla.Lines[(int) nudGoto.Value - 1].Position); + DialogResult = DialogResult.OK; + } - // occurs when a user selects a line number to jump to.. - private void FormDialogQueryJumpLocation_Shown(object sender, EventArgs e) - { - nudGoto.Select(0, nudGoto.Text.Length); - } + // occurs when a user selects a line number to jump to.. + private void FormDialogQueryJumpLocation_Shown(object sender, EventArgs e) + { + nudGoto.Select(0, nudGoto.Text.Length); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/DialogForms/FormDialogQueryNumber.cs b/ScriptNotepad/DialogForms/FormDialogQueryNumber.cs index 687cdf29..1f4c47ce 100644 --- a/ScriptNotepad/DialogForms/FormDialogQueryNumber.cs +++ b/ScriptNotepad/DialogForms/FormDialogQueryNumber.cs @@ -28,162 +28,161 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using VPKSoft.LangLib; -namespace ScriptNotepad.DialogForms +namespace ScriptNotepad.DialogForms; + +/// +/// A dialog to query one or two numbers from the user. +/// Implements the +/// +/// +public partial class FormDialogQueryNumber : DBLangEngineWinforms { /// - /// A dialog to query one or two numbers from the user. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogQueryNumber : DBLangEngineWinforms + public FormDialogQueryNumber() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogQueryNumber() - { - InitializeComponent(); - - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + InitializeComponent(); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - } - - /// - /// Displays the dialog with given range values and initial values. - /// - /// The type of the T. - /// The start value for the first . - /// The minimum value for the first . - /// The maximum value for the first . - /// The start value for the second . - /// The minimum value for the second . - /// The maximum value for the second . - /// The title to of the dialog. - /// A text for the label to describe the value requested from the user. - /// System.ValueTuple<T, T>. - public static (T, T) Execute(int startValue, int startValueMin, int startValueMax, int endValue, - int endValueMin, - int endValueMax, string title, string valueDescription) + if (Utils.ShouldLocalize() != null) { - // create a new dialog and set the parameter values for it.. - FormDialogQueryNumber dialog = new FormDialogQueryNumber - { - nudValueStart = {Maximum = startValueMax, Minimum = startValueMin, Value = startValue}, - nudValueEnd = {Maximum = endValueMax, Minimum = endValueMin, Value = endValue}, - Text = title, - lbFunctionDescription = {Text = valueDescription} - }; - - // if only one value is requested, disable the other NumericUpDown.. - if (endValue == -1 && endValueMin == -1 && endValueMax == -1) - { - dialog.nudValueStart.Size = new Size(dialog.nudValueEnd.Right - dialog.nudValueStart.Left, - dialog.nudValueStart.Height); - dialog.lbDelimiter.Visible = false; - dialog.nudValueEnd.Visible = false; - } - - // if the user accepted the input, return the values.. - if (dialog.ShowDialog() == DialogResult.OK) - { - var v1 = (T) Convert.ChangeType(dialog.nudValueStart.Value, typeof(T)); - var v2 = (T) Convert.ChangeType(dialog.nudValueEnd.Value, typeof(T)); - return (v1, v2); - } - - // user didn't accept the input so return default.. - return default; + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - /// - /// Displays the dialog with given range values and initial values. - /// - /// The type of the T. - /// The minimum value for the first . - /// The maximum value for the first . - /// The minimum value for the second . - /// The maximum value for the second . - /// The title to of the dialog. - /// A text for the label to describe the value requested from the user. - /// System.ValueTuple<T, T>. - public static (T, T) Execute(int startValueMin, int startValueMax, - int endValueMin, - int endValueMax, string title, string valueDescription) - { - return Execute(startValueMin, startValueMin, startValueMax, endValueMin, endValueMin, endValueMax, title, - valueDescription); - } + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } - /// - /// Displays the dialog with given range values and initial values. - /// - /// The type of the T. - /// The maximum value for the first . - /// The maximum value for the second . - /// The title to of the dialog. - /// A text for the label to describe the value requested from the user. - /// System.ValueTuple<T, T>. - public static (T, T) ExecuteStartValueZero(int startValueMax, - int endValueMax, string title, string valueDescription) + /// + /// Displays the dialog with given range values and initial values. + /// + /// The type of the T. + /// The start value for the first . + /// The minimum value for the first . + /// The maximum value for the first . + /// The start value for the second . + /// The minimum value for the second . + /// The maximum value for the second . + /// The title to of the dialog. + /// A text for the label to describe the value requested from the user. + /// System.ValueTuple<T, T>. + public static (T, T) Execute(int startValue, int startValueMin, int startValueMax, int endValue, + int endValueMin, + int endValueMax, string title, string valueDescription) + { + // create a new dialog and set the parameter values for it.. + FormDialogQueryNumber dialog = new FormDialogQueryNumber { - return Execute(0, 0, startValueMax, 0, 0, endValueMax, title, - valueDescription); - } - - /// - /// Displays the dialog with given range values and initial values. - /// - /// The type of the T. - /// The start value for the first . - /// The minimum value for the first . - /// The maximum value for the first . - /// The title to of the dialog. - /// A text for the label to describe the value requested from the user. - /// T. - public static T Execute(int startValue, int startValueMin, int startValueMax, - string title, string valueDescription) + nudValueStart = {Maximum = startValueMax, Minimum = startValueMin, Value = startValue, }, + nudValueEnd = {Maximum = endValueMax, Minimum = endValueMin, Value = endValue, }, + Text = title, + lbFunctionDescription = {Text = valueDescription, }, + }; + + // if only one value is requested, disable the other NumericUpDown.. + if (endValue == -1 && endValueMin == -1 && endValueMax == -1) { - return Execute(startValue, startValueMin, startValueMax, -1, -1, -1, title, - valueDescription).Item1; + dialog.nudValueStart.Size = new Size(dialog.nudValueEnd.Right - dialog.nudValueStart.Left, + dialog.nudValueStart.Height); + dialog.lbDelimiter.Visible = false; + dialog.nudValueEnd.Visible = false; } - /// - /// Displays the dialog with given range values and initial values. - /// - /// The type of the T. - /// The minimum value for the first . - /// The maximum value for the first . - /// The title to of the dialog. - /// A text for the label to describe the value requested from the user. - /// T. - public static T Execute(int startValueMin, int startValueMax, - string title, string valueDescription) + // if the user accepted the input, return the values.. + if (dialog.ShowDialog() == DialogResult.OK) { - return Execute(startValueMin, startValueMin, startValueMax, -1, -1, -1, title, - valueDescription).Item1; + var v1 = (T) Convert.ChangeType(dialog.nudValueStart.Value, typeof(T)); + var v2 = (T) Convert.ChangeType(dialog.nudValueEnd.Value, typeof(T)); + return (v1, v2); } - /// - /// Displays the dialog with given range values and initial values. - /// - /// The type of the T. - /// The maximum value for the first . - /// The title to of the dialog. - /// A text for the label to describe the value requested from the user. - /// T. - public static T Execute(int startValueMax, - string title, string valueDescription) - { - return Execute(0, 0, startValueMax, -1, -1, -1, title, - valueDescription).Item1; - } + // user didn't accept the input so return default.. + return default; + } + + /// + /// Displays the dialog with given range values and initial values. + /// + /// The type of the T. + /// The minimum value for the first . + /// The maximum value for the first . + /// The minimum value for the second . + /// The maximum value for the second . + /// The title to of the dialog. + /// A text for the label to describe the value requested from the user. + /// System.ValueTuple<T, T>. + public static (T, T) Execute(int startValueMin, int startValueMax, + int endValueMin, + int endValueMax, string title, string valueDescription) + { + return Execute(startValueMin, startValueMin, startValueMax, endValueMin, endValueMin, endValueMax, title, + valueDescription); + } + + /// + /// Displays the dialog with given range values and initial values. + /// + /// The type of the T. + /// The maximum value for the first . + /// The maximum value for the second . + /// The title to of the dialog. + /// A text for the label to describe the value requested from the user. + /// System.ValueTuple<T, T>. + public static (T, T) ExecuteStartValueZero(int startValueMax, + int endValueMax, string title, string valueDescription) + { + return Execute(0, 0, startValueMax, 0, 0, endValueMax, title, + valueDescription); + } + + /// + /// Displays the dialog with given range values and initial values. + /// + /// The type of the T. + /// The start value for the first . + /// The minimum value for the first . + /// The maximum value for the first . + /// The title to of the dialog. + /// A text for the label to describe the value requested from the user. + /// T. + public static T Execute(int startValue, int startValueMin, int startValueMax, + string title, string valueDescription) + { + return Execute(startValue, startValueMin, startValueMax, -1, -1, -1, title, + valueDescription).Item1; + } + + /// + /// Displays the dialog with given range values and initial values. + /// + /// The type of the T. + /// The minimum value for the first . + /// The maximum value for the first . + /// The title to of the dialog. + /// A text for the label to describe the value requested from the user. + /// T. + public static T Execute(int startValueMin, int startValueMax, + string title, string valueDescription) + { + return Execute(startValueMin, startValueMin, startValueMax, -1, -1, -1, title, + valueDescription).Item1; + } + + /// + /// Displays the dialog with given range values and initial values. + /// + /// The type of the T. + /// The maximum value for the first . + /// The title to of the dialog. + /// A text for the label to describe the value requested from the user. + /// T. + public static T Execute(int startValueMax, + string title, string valueDescription) + { + return Execute(0, 0, startValueMax, -1, -1, -1, title, + valueDescription).Item1; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/DialogForms/FormDialogRenameNewFile.cs b/ScriptNotepad/DialogForms/FormDialogRenameNewFile.cs index 19588b04..9d2aadc4 100644 --- a/ScriptNotepad/DialogForms/FormDialogRenameNewFile.cs +++ b/ScriptNotepad/DialogForms/FormDialogRenameNewFile.cs @@ -28,102 +28,101 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.ScintillaTabbedTextControl; -namespace ScriptNotepad.DialogForms +namespace ScriptNotepad.DialogForms; + +/// +/// A dialog to rename new files (files which aren't saved to the file system). +/// Implements the +/// +/// +public partial class FormDialogRenameNewFile : DBLangEngineWinforms { /// - /// A dialog to rename new files (files which aren't saved to the file system). - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogRenameNewFile : DBLangEngineWinforms + public FormDialogRenameNewFile() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogRenameNewFile() + InitializeComponent(); + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + + if (Utils.ShouldLocalize() != null) { - InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } + + /// + /// Gets or sets the control. + /// + private ScintillaTabbedTextControl TabbedTextControl { get; set; } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + /// + /// Shows the form as a modal dialog box with the specified owner. + /// + /// Any object that implements that represents the top-level window that will own the modal dialog box. + /// An instance of the control in which the current new document should be renamed. + /// A new file name for a new file if successful; otherwise null. + /// The form specified in the parameter is the same as the form being shown. + /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). + public static string ShowDialog(IWin32Window owner, ScintillaTabbedTextControl tabbedTextControl) + { + if (tabbedTextControl.CurrentDocument == null) + { + return null; } - /// - /// Gets or sets the control. - /// - private ScintillaTabbedTextControl TabbedTextControl { get; set; } - - /// - /// Shows the form as a modal dialog box with the specified owner. - /// - /// Any object that implements that represents the top-level window that will own the modal dialog box. - /// An instance of the control in which the current new document should be renamed. - /// A new file name for a new file if successful; otherwise null. - /// The form specified in the parameter is the same as the form being shown. - /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). - public static string ShowDialog(IWin32Window owner, ScintillaTabbedTextControl tabbedTextControl) + using (var dialog = new FormDialogRenameNewFile()) { - if (tabbedTextControl.CurrentDocument == null) + dialog.TabbedTextControl = tabbedTextControl; + dialog.tbCurrentName.Text = tabbedTextControl.CurrentDocument.FileName; + dialog.tbNewName.Text = tabbedTextControl.CurrentDocument.FileName; + if (dialog.ShowDialog(owner) == DialogResult.OK) { - return null; + return dialog.tbNewName.Text; } + } - using (var dialog = new FormDialogRenameNewFile()) - { - dialog.TabbedTextControl = tabbedTextControl; - dialog.tbCurrentName.Text = tabbedTextControl.CurrentDocument.FileName; - dialog.tbNewName.Text = tabbedTextControl.CurrentDocument.FileName; - if (dialog.ShowDialog(owner) == DialogResult.OK) - { - return dialog.tbNewName.Text; - } - } + return null; + } - return null; - } + // a text is changed with the new file name text box, so do validation.. + private void TbNewName_TextChanged(object sender, EventArgs e) + { + bool enableOk = true; + var newText = ((TextBox) sender).Text; - // a text is changed with the new file name text box, so do validation.. - private void TbNewName_TextChanged(object sender, EventArgs e) + // first validate the file name.. + if (newText.Trim() != string.Empty && // empty string is not allowed.. + newText.IndexOfAny(Path.GetInvalidFileNameChars()) == -1 && // no invalid path characters are allowed.. + Path.GetFileName(newText) == newText) // not paths allowed with the unsaved file.. { - bool enableOk = true; - var newText = ((TextBox) sender).Text; - - // first validate the file name.. - if (newText.Trim() != string.Empty && // empty string is not allowed.. - newText.IndexOfAny(Path.GetInvalidFileNameChars()) == -1 && // no invalid path characters are allowed.. - Path.GetFileName(newText) == newText) // not paths allowed with the unsaved file.. + // now validate that the file doesn't already "exist".. + foreach (var document in TabbedTextControl.Documents) { - // now validate that the file doesn't already "exist".. - foreach (var document in TabbedTextControl.Documents) + if (document.FileName.Equals(newText, StringComparison.InvariantCultureIgnoreCase)) { - if (document.FileName.Equals(newText, StringComparison.InvariantCultureIgnoreCase)) - { - enableOk = false; // a file with the name exists, so disable the button.. - break; - } + enableOk = false; // a file with the name exists, so disable the button.. + break; } } - else - { - enableOk = false; // validation failed.. - } - - // set the OK button's enabled state.. - btOK.Enabled = enableOk; } - - // focus to the right control.. - private void FormDialogRenameNewFile_Shown(object sender, EventArgs e) + else { - tbNewName.Focus(); - tbNewName.SelectAll(); + enableOk = false; // validation failed.. } + + // set the OK button's enabled state.. + btOK.Enabled = enableOk; + } + + // focus to the right control.. + private void FormDialogRenameNewFile_Shown(object sender, EventArgs e) + { + tbNewName.Focus(); + tbNewName.SelectAll(); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/DialogForms/FormDialogScriptLoad.cs b/ScriptNotepad/DialogForms/FormDialogScriptLoad.cs index 96202278..4c405c8c 100644 --- a/ScriptNotepad/DialogForms/FormDialogScriptLoad.cs +++ b/ScriptNotepad/DialogForms/FormDialogScriptLoad.cs @@ -35,217 +35,216 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.MessageBoxExtended; using VPKSoft.PosLib; -namespace ScriptNotepad.DialogForms +namespace ScriptNotepad.DialogForms; + +/// +/// A form for user to select saved script snippets from the database. +/// +/// +public partial class FormDialogScriptLoad : DBLangEngineWinforms { + private IEnumerable codeSnippets; + + // a field to hold localized name for a script template for manipulating Scintilla contents as text.. + readonly string defaultNameScriptTemplateText = string.Empty; + + // a field to hold localized name for a script template for manipulating Scintilla contents as lines.. + readonly string defaultNameScriptTemplateLines = string.Empty; + /// - /// A form for user to select saved script snippets from the database. + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogScriptLoad : DBLangEngineWinforms + public FormDialogScriptLoad() { - private IEnumerable codeSnippets; + // Add this form to be positioned.. + PositionForms.Add(this); - // a field to hold localized name for a script template for manipulating Scintilla contents as text.. - readonly string defaultNameScriptTemplateText = string.Empty; + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - // a field to hold localized name for a script template for manipulating Scintilla contents as lines.. - readonly string defaultNameScriptTemplateLines = string.Empty; + InitializeComponent(); - /// - /// Initializes a new instance of the class. - /// - public FormDialogScriptLoad() - { - // Add this form to be positioned.. - PositionForms.Add(this); + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - InitializeComponent(); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + // get the code snippets in the database.. + codeSnippets = ScriptNotepadDbContext.DbContext.CodeSnippets.ToArray(); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + // localize the script type default names.. + defaultNameScriptTemplateText = + DBLangEngine.GetMessage("msgDefaultScriptSnippetText", "A text script snippet|As in a script for manipulating Scintilla contents as text"); - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + defaultNameScriptTemplateLines = + DBLangEngine.GetMessage("msgDefaultScriptSnippetLines", "A line script snippet|As in a script for manipulating Scintilla contents as lines"); - // get the code snippets in the database.. - codeSnippets = ScriptNotepadDbContext.DbContext.CodeSnippets.ToArray(); + // localize the currently supported script types.. + cmbScriptType.Items.Clear(); + cmbScriptType.Items.Add( + DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text") + ); - // localize the script type default names.. - defaultNameScriptTemplateText = - DBLangEngine.GetMessage("msgDefaultScriptSnippetText", "A text script snippet|As in a script for manipulating Scintilla contents as text"); + cmbScriptType.Items.Add( + DBLangEngine.GetMessage("msgScriptTypeLines", "Script lines|As in the C# script type should be handling the Scintilla's contents as lines") + ); - defaultNameScriptTemplateLines = - DBLangEngine.GetMessage("msgDefaultScriptSnippetLines", "A line script snippet|As in a script for manipulating Scintilla contents as lines"); + cmbScriptType.SelectedIndex = 0; - // localize the currently supported script types.. - cmbScriptType.Items.Clear(); - cmbScriptType.Items.Add( - DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text") - ); + cmbScriptType.SelectedItem = + DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text"); - cmbScriptType.Items.Add( - DBLangEngine.GetMessage("msgScriptTypeLines", "Script lines|As in the C# script type should be handling the Scintilla's contents as lines") - ); + // set the OK button's state based on the value if any script is selected from the script list box.. + btOK.Enabled = lbScriptList.SelectedIndex != -1; + } - cmbScriptType.SelectedIndex = 0; + /// + /// Shows this dialog for a user to select a script. + /// + /// A flag indicating if the dialog will be shown in manage mode. + /// An instance for the class if user accepted the dialog; otherwise null. + public static CodeSnippet Execute(bool manage) + { + // create a new instance of the FormDialogScriptLoad.. + FormDialogScriptLoad formDialogScriptLoad = new FormDialogScriptLoad + { + btCancel = {Visible = !manage, }, btOK = {Visible = !manage, }, btClose = {Visible = manage, }, + }; - cmbScriptType.SelectedItem = - DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text"); + // set the button visibility based on the manage flag.. - // set the OK button's state based on the value if any script is selected from the script list box.. - btOK.Enabled = lbScriptList.SelectedIndex != -1; + // if the manage flag is set only one button returning DialogResult.Cancel value is used.. + if (manage) + { + // ..so do set reset the dialog's default buttons.. + formDialogScriptLoad.AcceptButton = formDialogScriptLoad.btClose; + formDialogScriptLoad.CancelButton = formDialogScriptLoad.btClose; } - /// - /// Shows this dialog for a user to select a script. - /// - /// A flag indicating if the dialog will be shown in manage mode. - /// An instance for the class if user accepted the dialog; otherwise null. - public static CodeSnippet Execute(bool manage) + // show the dialog.. + if (formDialogScriptLoad.ShowDialog() == DialogResult.OK) { - // create a new instance of the FormDialogScriptLoad.. - FormDialogScriptLoad formDialogScriptLoad = new FormDialogScriptLoad - { - btCancel = {Visible = !manage}, btOK = {Visible = !manage}, btClose = {Visible = manage} - }; - - // set the button visibility based on the manage flag.. - - // if the manage flag is set only one button returning DialogResult.Cancel value is used.. - if (manage) - { - // ..so do set reset the dialog's default buttons.. - formDialogScriptLoad.AcceptButton = formDialogScriptLoad.btClose; - formDialogScriptLoad.CancelButton = formDialogScriptLoad.btClose; - } - - // show the dialog.. - if (formDialogScriptLoad.ShowDialog() == DialogResult.OK) - { - // if the OK button was selected then return the selected CODE_SNIPPETS class instance.. - return (CodeSnippet)formDialogScriptLoad.lbScriptList.SelectedItem; - } - else - { - // user canceled the dialog so do return null.. - return null; - } + // if the OK button was selected then return the selected CODE_SNIPPETS class instance.. + return (CodeSnippet)formDialogScriptLoad.lbScriptList.SelectedItem; } - - /// - /// Filters the list box contents based on the script type and a possible search string. - /// - /// The type of the script. - /// The text for filtering the snippets by their names. - private void FilterSnippets(ScriptSnippetType type, string filterText) + else { - // select the snipped based on the given parameter values.. - IEnumerable selectedSnippets = - codeSnippets.Where( - f => f.ScriptTextManipulationType == type && - (filterText.Trim() == string.Empty || f.ScriptName.ToLowerInvariant().Contains(filterText.ToLowerInvariant()))); - - // list the script snippets to the list box.. - ListScriptSnippets(selectedSnippets); + // user canceled the dialog so do return null.. + return null; } + } - /// - /// Filters the list box contents based on the script type and a possible search string. - /// - /// The snippets. - private void ListScriptSnippets(IEnumerable snippets) - { - // clear the previous contents from the list box.. - lbScriptList.Items.Clear(); + /// + /// Filters the list box contents based on the script type and a possible search string. + /// + /// The type of the script. + /// The text for filtering the snippets by their names. + private void FilterSnippets(ScriptSnippetType type, string filterText) + { + // select the snipped based on the given parameter values.. + IEnumerable selectedSnippets = + codeSnippets.Where( + f => f.ScriptTextManipulationType == type && + (filterText.Trim() == string.Empty || f.ScriptName.ToLowerInvariant().Contains(filterText.ToLowerInvariant()))); + + // list the script snippets to the list box.. + ListScriptSnippets(selectedSnippets); + } - // list the code snippets to the list box.. - foreach (var codeSnippet in snippets) - { - lbScriptList.Items.Add(codeSnippet); - } - } + /// + /// Filters the list box contents based on the script type and a possible search string. + /// + /// The snippets. + private void ListScriptSnippets(IEnumerable snippets) + { + // clear the previous contents from the list box.. + lbScriptList.Items.Clear(); - // common handler for both the filter type combo box and the search text box changed event.. - private void common_ScriptChanged(object sender, EventArgs e) + // list the code snippets to the list box.. + foreach (var codeSnippet in snippets) { - // filter the list box contents based on the given filters.. - FilterSnippets((ScriptSnippetType)cmbScriptType.SelectedIndex, tbFilter.Text); + lbScriptList.Items.Add(codeSnippet); } + } - private void lbScriptList_SelectedIndexChanged(object sender, EventArgs e) - { - // set the OK button's state based on the value if any script is selected from the script list box.. - btOK.Enabled = lbScriptList.SelectedIndex != -1; - } + // common handler for both the filter type combo box and the search text box changed event.. + private void common_ScriptChanged(object sender, EventArgs e) + { + // filter the list box contents based on the given filters.. + FilterSnippets((ScriptSnippetType)cmbScriptType.SelectedIndex, tbFilter.Text); + } - /// - /// Determines whether script is possible to be deleted from the database i.e. not a "reserved" name. - /// - /// Name of the script to check. - /// - /// True if the script with a given name is possible to be deleted from the database; otherwise false. - /// - private bool IsScriptPossibleToDelete(string scriptName) - { - return !((scriptName == defaultNameScriptTemplateText || // a localized template name for text will not do.. - scriptName == defaultNameScriptTemplateLines || // a localized template name for lines will not do.. - scriptName == "Simple line ending change script" || // a non-localized database template for lines will not do.. - scriptName == "Simple replace script" || - scriptName == "Simple XML manipulation script")); // a non-localized database template for text will not do.. - } + private void lbScriptList_SelectedIndexChanged(object sender, EventArgs e) + { + // set the OK button's state based on the value if any script is selected from the script list box.. + btOK.Enabled = lbScriptList.SelectedIndex != -1; + } - // a user wishes to delete scripts from the database.. - private void btDeleteScript_Click(object sender, EventArgs e) - { - // display a confirmation dialog.. - if (MessageBoxExtended.Show( + /// + /// Determines whether script is possible to be deleted from the database i.e. not a "reserved" name. + /// + /// Name of the script to check. + /// + /// True if the script with a given name is possible to be deleted from the database; otherwise false. + /// + private bool IsScriptPossibleToDelete(string scriptName) + { + return !((scriptName == defaultNameScriptTemplateText || // a localized template name for text will not do.. + scriptName == defaultNameScriptTemplateLines || // a localized template name for lines will not do.. + scriptName == "Simple line ending change script" || // a non-localized database template for lines will not do.. + scriptName == "Simple replace script" || + scriptName == "Simple XML manipulation script")); // a non-localized database template for text will not do.. + } + + // a user wishes to delete scripts from the database.. + private void btDeleteScript_Click(object sender, EventArgs e) + { + // display a confirmation dialog.. + if (MessageBoxExtended.Show( DBLangEngine.GetMessage("msgDeleteScriptConfirm", "Delete selected script snippet(s)?|A confirmation question whether to delete selected script snippets from the database"), DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog"), MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question) == DialogResultExtended.Yes) + { + bool deleted = false; // a flag indicating if any scripts were actually deleted.. + + // loop though the selected items in the list box.. + foreach (var item in lbScriptList.SelectedItems) { - bool deleted = false; // a flag indicating if any scripts were actually deleted.. + // assume that an item in the list box is a CODE_SNIPPETS class instance.. + var snippet = (CodeSnippet)item; - // loop though the selected items in the list box.. - foreach (var item in lbScriptList.SelectedItems) + // check if the script's name is valid for deletion.. + if (IsScriptPossibleToDelete(snippet.ScriptName)) { - // assume that an item in the list box is a CODE_SNIPPETS class instance.. - var snippet = (CodeSnippet)item; - - // check if the script's name is valid for deletion.. - if (IsScriptPossibleToDelete(snippet.ScriptName)) + // some boolean algebra to determine if anything was actually delete from the database.. + try + { + ScriptNotepadDbContext.DbContext.CodeSnippets.Remove(snippet); + deleted = true; + } + catch (Exception ex) { - // some boolean algebra to determine if anything was actually delete from the database.. - try - { - ScriptNotepadDbContext.DbContext.CodeSnippets.Remove(snippet); - deleted = true; - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } + ExceptionLogger.LogError(ex); } } + } - if (deleted) // only refresh the list if some deletions were made.. - { - ScriptNotepadDbContext.DbContext.SaveChanges(); + if (deleted) // only refresh the list if some deletions were made.. + { + ScriptNotepadDbContext.DbContext.SaveChanges(); - // get the remaining code snippets in the database.. - codeSnippets = ScriptNotepadDbContext.DbContext.CodeSnippets.ToArray(); + // get the remaining code snippets in the database.. + codeSnippets = ScriptNotepadDbContext.DbContext.CodeSnippets.ToArray(); - // filter the list box contents based on the given filters.. - FilterSnippets((ScriptSnippetType)cmbScriptType.SelectedIndex, tbFilter.Text); - } + // filter the list box contents based on the given filters.. + FilterSnippets((ScriptSnippetType)cmbScriptType.SelectedIndex, tbFilter.Text); } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/DialogForms/FormDialogSelectFileTab.cs b/ScriptNotepad/DialogForms/FormDialogSelectFileTab.cs index d3f505ed..69d42468 100644 --- a/ScriptNotepad/DialogForms/FormDialogSelectFileTab.cs +++ b/ScriptNotepad/DialogForms/FormDialogSelectFileTab.cs @@ -32,281 +32,280 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.ScintillaTabbedTextControl; -namespace ScriptNotepad.DialogForms +namespace ScriptNotepad.DialogForms; + +/// +/// A dialog to select a tab from the tabbed control. +/// Implements the +/// +/// +public partial class FormDialogSelectFileTab : DBLangEngineWinforms { /// - /// A dialog to select a tab from the tabbed control. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogSelectFileTab : DBLangEngineWinforms + public FormDialogSelectFileTab() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogSelectFileTab() - { - InitializeComponent(); - - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + InitializeComponent(); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - // a list of image keys and ScintillaTabbedDocument class instances to display on the dialog.. - private List<(string imageKey, ScintillaTabbedDocument document)> OpenDocuments { get; } = - new List<(string imageKey, ScintillaTabbedDocument document)>(); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } - /// - /// Gets the cached images for file types. - /// - private static ImageList CachedImages { get; } = new ImageList(); + // a list of image keys and ScintillaTabbedDocument class instances to display on the dialog.. + private List<(string imageKey, ScintillaTabbedDocument document)> OpenDocuments { get; } = + new List<(string imageKey, ScintillaTabbedDocument document)>(); - // the ScintillaTabbedTextControl class instance given via the ShowDialog(...) method.. - private ScintillaTabbedTextControl scintillaTabbedTextControl; + /// + /// Gets the cached images for file types. + /// + private static ImageList CachedImages { get; } = new ImageList(); - /// - /// Shows the form as a modal dialog box for user to select an opened file within a a control. - /// - /// An instance to a instance to select a tab from. - /// One of the values. - public static DialogResult ShowDialog(ScintillaTabbedTextControl scintillaTabbedTextControl) - { - var form = new FormDialogSelectFileTab(); + // the ScintillaTabbedTextControl class instance given via the ShowDialog(...) method.. + private ScintillaTabbedTextControl scintillaTabbedTextControl; + + /// + /// Shows the form as a modal dialog box for user to select an opened file within a a control. + /// + /// An instance to a instance to select a tab from. + /// One of the values. + public static DialogResult ShowDialog(ScintillaTabbedTextControl scintillaTabbedTextControl) + { + var form = new FormDialogSelectFileTab(); - form.dgvOpenFiles.SuspendLayout(); + form.dgvOpenFiles.SuspendLayout(); - form.scintillaTabbedTextControl = scintillaTabbedTextControl; + form.scintillaTabbedTextControl = scintillaTabbedTextControl; - foreach (var scintillaTabbedDocument in scintillaTabbedTextControl.Documents) + foreach (var scintillaTabbedDocument in scintillaTabbedTextControl.Documents) + { + var iconForFile = SystemIcons.WinLogo; + + if (!CachedImages.Images.ContainsKey(":unknown:")) { - var iconForFile = SystemIcons.WinLogo; + iconForFile.ToBitmap(); + CachedImages.Images.Add(":unknown:", iconForFile); + } - if (!CachedImages.Images.ContainsKey(":unknown:")) + try + { + if (File.Exists(scintillaTabbedDocument.FileName)) { - iconForFile.ToBitmap(); - CachedImages.Images.Add(":unknown:", iconForFile); - } + FileInfo fileInfo = new FileInfo(scintillaTabbedDocument.FileName); - try - { - if (File.Exists(scintillaTabbedDocument.FileName)) + // Check to see if the image collection contains an image + // for this extension, using the extension as a key. + if (!CachedImages.Images.ContainsKey(fileInfo.Extension)) { - FileInfo fileInfo = new FileInfo(scintillaTabbedDocument.FileName); - - // Check to see if the image collection contains an image - // for this extension, using the extension as a key. - if (!CachedImages.Images.ContainsKey(fileInfo.Extension)) + // If not, add the image to the image list. + iconForFile = Icon.ExtractAssociatedIcon(fileInfo.FullName); + if (iconForFile != null) { - // If not, add the image to the image list. - iconForFile = Icon.ExtractAssociatedIcon(fileInfo.FullName); - if (iconForFile != null) - { - CachedImages.Images.Add(fileInfo.Extension, iconForFile); - } + CachedImages.Images.Add(fileInfo.Extension, iconForFile); } - - form.OpenDocuments.Add((fileInfo.Extension, scintillaTabbedDocument)); - form.dgvOpenFiles.Rows.Add(CachedImages.Images[fileInfo.Extension], fileInfo.FullName); - } - else - { - form.OpenDocuments.Add((":unknown:", scintillaTabbedDocument)); - form.dgvOpenFiles.Rows.Add(CachedImages.Images[":unknown:"], scintillaTabbedDocument.FileName); } + + form.OpenDocuments.Add((fileInfo.Extension, scintillaTabbedDocument)); + form.dgvOpenFiles.Rows.Add(CachedImages.Images[fileInfo.Extension], fileInfo.FullName); } - catch (Exception ex) + else { - // log the exception.. - ExceptionLogger.LogError(ex); + form.OpenDocuments.Add((":unknown:", scintillaTabbedDocument)); + form.dgvOpenFiles.Rows.Add(CachedImages.Images[":unknown:"], scintillaTabbedDocument.FileName); } } - form.dgvOpenFiles.ResumeLayout(); - - return form.ShowDialog(); + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + } } + form.dgvOpenFiles.ResumeLayout(); + + return form.ShowDialog(); + } - /// - /// Filters the open tab list with a given filter text. - /// - /// The string to be used for the filtering. - private void RefreshTabs(string filterText) + /// + /// Filters the open tab list with a given filter text. + /// + /// The string to be used for the filtering. + private void RefreshTabs(string filterText) + { + dgvOpenFiles.SuspendLayout(); + dgvOpenFiles.Rows.Clear(); + foreach (var document in OpenDocuments) { - dgvOpenFiles.SuspendLayout(); - dgvOpenFiles.Rows.Clear(); - foreach (var document in OpenDocuments) + if (filterText.Trim() == string.Empty || document.document.FileName.IndexOf(filterText, StringComparison.InvariantCultureIgnoreCase) >= 0) { - if (filterText.Trim() == string.Empty || document.document.FileName.IndexOf(filterText, StringComparison.InvariantCultureIgnoreCase) >= 0) - { - dgvOpenFiles.Rows.Add(CachedImages.Images[document.imageKey], document.document.FileName); - } + dgvOpenFiles.Rows.Add(CachedImages.Images[document.imageKey], document.document.FileName); } - dgvOpenFiles.ResumeLayout(); } + dgvOpenFiles.ResumeLayout(); + } - /// - /// Gets a value indicating if the user selected a valid file entry from the dialog and if successful, selects the tab from the . - /// - /// true if the tab was successfully selected, false otherwise. - private bool DialogOk() + /// + /// Gets a value indicating if the user selected a valid file entry from the dialog and if successful, selects the tab from the . + /// + /// true if the tab was successfully selected, false otherwise. + private bool DialogOk() + { + var row = dgvOpenFiles.CurrentRow; + if (row != null) { - var row = dgvOpenFiles.CurrentRow; - if (row != null) + var fileName = row.Cells[colFileName.Index].Value.ToString(); + var index = scintillaTabbedTextControl.Documents.FindIndex(f => f.FileName == fileName); + if (index != -1) { - var fileName = row.Cells[colFileName.Index].Value.ToString(); - var index = scintillaTabbedTextControl.Documents.FindIndex(f => f.FileName == fileName); - if (index != -1) - { - scintillaTabbedTextControl.ActivateDocument(index); - return true; - } + scintillaTabbedTextControl.ActivateDocument(index); + return true; } + } + return false; + } + + /// + /// Changes the selection of the instance in case of the given key is or value. + /// + /// A enumeration value. + /// A control to focus after the selection change. Set the value to null to not to change the focus. + /// true if the selection was successfully changed, false otherwise. + private bool MoveSelection(Keys keys, Control focusControl) + { + if (keys != Keys.Up && keys != Keys.Down) + { return false; } - /// - /// Changes the selection of the instance in case of the given key is or value. - /// - /// A enumeration value. - /// A control to focus after the selection change. Set the value to null to not to change the focus. - /// true if the selection was successfully changed, false otherwise. - private bool MoveSelection(Keys keys, Control focusControl) + if (dgvOpenFiles.Rows.Count > 0) { - if (keys != Keys.Up && keys != Keys.Down) - { - return false; - } + int rowIndex = dgvOpenFiles.CurrentRow?.Index ?? -1; - if (dgvOpenFiles.Rows.Count > 0) + if (keys == Keys.Down) { - int rowIndex = dgvOpenFiles.CurrentRow?.Index ?? -1; - - if (keys == Keys.Down) + rowIndex++; + if (rowIndex >= dgvOpenFiles.Rows.Count) { - rowIndex++; - if (rowIndex >= dgvOpenFiles.Rows.Count) - { - rowIndex = 0; - } + rowIndex = 0; + } - dgvOpenFiles.CurrentCell = dgvOpenFiles.Rows[rowIndex].Cells[0]; + dgvOpenFiles.CurrentCell = dgvOpenFiles.Rows[rowIndex].Cells[0]; - dgvOpenFiles.FirstDisplayedScrollingRowIndex = rowIndex; + dgvOpenFiles.FirstDisplayedScrollingRowIndex = rowIndex; - focusControl?.Focus(); - return true; - } + focusControl?.Focus(); + return true; + } - if (keys == Keys.Up) + if (keys == Keys.Up) + { + rowIndex--; + if (rowIndex < 0) { - rowIndex--; - if (rowIndex < 0) - { - rowIndex = dgvOpenFiles.Rows.Count - 1; - } + rowIndex = dgvOpenFiles.Rows.Count - 1; + } - dgvOpenFiles.CurrentCell = dgvOpenFiles.Rows[rowIndex].Cells[0]; + dgvOpenFiles.CurrentCell = dgvOpenFiles.Rows[rowIndex].Cells[0]; - dgvOpenFiles.FirstDisplayedScrollingRowIndex = rowIndex; + dgvOpenFiles.FirstDisplayedScrollingRowIndex = rowIndex; - focusControl?.Focus(); - return true; - } + focusControl?.Focus(); + return true; } - - return false; } - // the keyboard handler for everything else than the filter text box.. - private void FormDialogSelectFileTab_KeyDown(object sender, KeyEventArgs e) + return false; + } + + // the keyboard handler for everything else than the filter text box.. + private void FormDialogSelectFileTab_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Escape) { - if (e.KeyCode == Keys.Escape) - { - e.SuppressKeyPress = true; - DialogResult = DialogResult.Cancel; - } + e.SuppressKeyPress = true; + DialogResult = DialogResult.Cancel; + } - if (e.KeyCode == Keys.Return) + if (e.KeyCode == Keys.Return) + { + e.SuppressKeyPress = true; + if (DialogOk()) { - e.SuppressKeyPress = true; - if (DialogOk()) - { - DialogResult = DialogResult.OK; - } - return; + DialogResult = DialogResult.OK; } + return; + } - if (MoveSelection(e.KeyCode, null)) - { - e.SuppressKeyPress = true; - return; - } + if (MoveSelection(e.KeyCode, null)) + { + e.SuppressKeyPress = true; + return; + } - // delegate normal key presses to the filter open tabs text box.. - if (char.IsLetterOrDigit((char)e.KeyValue) || KeySendList.HasKey(e.KeyCode) && !tbFilterFiles.Focused) - { - tbFilterFiles.SelectAll(); - tbFilterFiles.Focus(); - char key = (char)e.KeyValue; + // delegate normal key presses to the filter open tabs text box.. + if (char.IsLetterOrDigit((char)e.KeyValue) || KeySendList.HasKey(e.KeyCode) && !tbFilterFiles.Focused) + { + tbFilterFiles.SelectAll(); + tbFilterFiles.Focus(); + char key = (char)e.KeyValue; - SendKeys.Send( - char.IsLetterOrDigit(key) ? key.ToString().ToLower() : KeySendList.GetKeyString(e.KeyCode)); + SendKeys.Send( + char.IsLetterOrDigit(key) ? key.ToString().ToLower() : KeySendList.GetKeyString(e.KeyCode)); - e.SuppressKeyPress = true; - } + e.SuppressKeyPress = true; } + } + + // filters the open tab list when the text with the filtered text box changes.. + private void TbFilterFiles_TextChanged(object sender, EventArgs e) + { + var textBox = (TextBox) sender; + RefreshTabs(textBox.Text); + } - // filters the open tab list when the text with the filtered text box changes.. - private void TbFilterFiles_TextChanged(object sender, EventArgs e) + // the keyboard handler for the filter text box.. + private void TbFilterFiles_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Escape) { - var textBox = (TextBox) sender; - RefreshTabs(textBox.Text); + e.SuppressKeyPress = true; + DialogResult = DialogResult.Cancel; } - // the keyboard handler for the filter text box.. - private void TbFilterFiles_KeyDown(object sender, KeyEventArgs e) + if (e.KeyCode == Keys.Return) { - if (e.KeyCode == Keys.Escape) - { - e.SuppressKeyPress = true; - DialogResult = DialogResult.Cancel; - } - - if (e.KeyCode == Keys.Return) + e.SuppressKeyPress = true; + if (DialogOk()) { - e.SuppressKeyPress = true; - if (DialogOk()) - { - DialogResult = DialogResult.OK; - } - return; + DialogResult = DialogResult.OK; } + return; + } - if (MoveSelection(e.KeyCode, tbFilterFiles)) - { - e.SuppressKeyPress = true; - } + if (MoveSelection(e.KeyCode, tbFilterFiles)) + { + e.SuppressKeyPress = true; } + } - // a user clicked an open tab file entry within the list of open tabs, so handle the click.. - private void DgvOpenFiles_CellClick(object sender, DataGridViewCellEventArgs e) + // a user clicked an open tab file entry within the list of open tabs, so handle the click.. + private void DgvOpenFiles_CellClick(object sender, DataGridViewCellEventArgs e) + { + // ..validate the index.. + if (e.RowIndex >= 0 && e.RowIndex < dgvOpenFiles.RowCount) { - // ..validate the index.. - if (e.RowIndex >= 0 && e.RowIndex < dgvOpenFiles.RowCount) + // ..check if a valid entry was clicked.. + if (DialogOk()) { - // ..check if a valid entry was clicked.. - if (DialogOk()) - { - DialogResult = DialogResult.OK; - } + DialogResult = DialogResult.OK; } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/EntityHelpers/DataHolders/DataHolderIndexer.cs b/ScriptNotepad/Editor/EntityHelpers/DataHolders/DataHolderIndexer.cs index 5f138d95..7122c0b4 100644 --- a/ScriptNotepad/Editor/EntityHelpers/DataHolders/DataHolderIndexer.cs +++ b/ScriptNotepad/Editor/EntityHelpers/DataHolders/DataHolderIndexer.cs @@ -1,44 +1,43 @@ using System.Collections.Generic; -namespace ScriptNotepad.Editor.EntityHelpers.DataHolders +namespace ScriptNotepad.Editor.EntityHelpers.DataHolders; + +/// +/// A class to hold a get indexer for type of . +/// +/// The class which is to be indexed. +public class DataHolderIndexer where T: class { /// - /// A class to hold a get indexer for type of . + /// Gets the values for the this indexer. /// - /// The class which is to be indexed. - public class DataHolderIndexer where T: class - { - /// - /// Gets the values for the this indexer. - /// - /// The values for the this indexer. - private Dictionary Values { get; } = new(); + /// The values for the this indexer. + private Dictionary Values { get; } = new(); - /// - /// Gets the with the specified key. - /// - /// The key. - /// The instance with the specified key. - public T this[int key] + /// + /// Gets the with the specified key. + /// + /// The key. + /// The instance with the specified key. + public T this[int key] + { + get { - get + if (!Values.ContainsKey(key)) { - if (!Values.ContainsKey(key)) - { - Values.Add(key, Activator.CreateInstance()); - } - - return Values[key]; + Values.Add(key, Activator.CreateInstance()); } - } - /// - /// Removes the instance with a specified key. - /// - /// The key. - public void Remove(int key) - { - Values.Remove(key); + return Values[key]; } } -} + + /// + /// Removes the instance with a specified key. + /// + /// The key. + public void Remove(int key) + { + Values.Remove(key); + } +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/EntityHelpers/DataHolders/FileSaveData.cs b/ScriptNotepad/Editor/EntityHelpers/DataHolders/FileSaveData.cs index 36b1855f..93c0b9be 100644 --- a/ScriptNotepad/Editor/EntityHelpers/DataHolders/FileSaveData.cs +++ b/ScriptNotepad/Editor/EntityHelpers/DataHolders/FileSaveData.cs @@ -2,49 +2,48 @@ using ScriptNotepad.Database.Entity.Entities; using ScriptNotepad.UtilityClasses.LinesAndBinary; -namespace ScriptNotepad.Editor.EntityHelpers.DataHolders +namespace ScriptNotepad.Editor.EntityHelpers.DataHolders; + +/// +/// Additional data for the entity. +/// +public class FileSaveData { /// - /// Additional data for the entity. + /// Gets or sets the value if the property has been set once. + /// + public bool PreviousDbModifiedIsSet { get; set; } + + /// + /// Gets or sets the value indicating when the file was modified in the database. + /// + public DateTime PreviousDbModified { get; set; } = DateTime.MinValue; + + /// + /// Gets or sets a value indicating whether the user should be queried of to reload the changed document from the file system. + /// + public bool ShouldQueryDiskReload { get; set; } = true; + + /// + /// Gets or sets the previous encodings of the file save for undo possibility. + /// Redo possibility does not exist. + /// + public List PreviousEncodings { get; set; } = new(); + + /// + /// A text describing the file line ending type(s) of the document. + /// + public string FileEndingText { get; set; } = string.Empty; + + /// + /// Gets or sets the file line types and their descriptions. + /// + /// The file line types and their descriptions. + public IEnumerable> FileLineTypesInternal { get; set; } = + new List>(); + + /// + /// Gets or sets the value indicating when the file was modified in the database. /// - public class FileSaveData - { - /// - /// Gets or sets the value if the property has been set once. - /// - public bool PreviousDbModifiedIsSet { get; set; } - - /// - /// Gets or sets the value indicating when the file was modified in the database. - /// - public DateTime PreviousDbModified { get; set; } = DateTime.MinValue; - - /// - /// Gets or sets a value indicating whether the user should be queried of to reload the changed document from the file system. - /// - public bool ShouldQueryDiskReload { get; set; } = true; - - /// - /// Gets or sets the previous encodings of the file save for undo possibility. - /// Redo possibility does not exist. - /// - public List PreviousEncodings { get; set; } = new(); - - /// - /// A text describing the file line ending type(s) of the document. - /// - public string FileEndingText { get; set; } = string.Empty; - - /// - /// Gets or sets the file line types and their descriptions. - /// - /// The file line types and their descriptions. - public IEnumerable> FileLineTypesInternal { get; set; } = - new List>(); - - /// - /// Gets or sets the value indicating when the file was modified in the database. - /// - public DateTime DbModified { get; set; } = DateTime.MinValue; - } -} + public DateTime DbModified { get; set; } = DateTime.MinValue; +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/EntityHelpers/FileSaveHelper.cs b/ScriptNotepad/Editor/EntityHelpers/FileSaveHelper.cs index ab7b4dd6..f3190436 100644 --- a/ScriptNotepad/Editor/EntityHelpers/FileSaveHelper.cs +++ b/ScriptNotepad/Editor/EntityHelpers/FileSaveHelper.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -34,406 +34,405 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.LinesAndBinary; using VPKSoft.LangLib; -namespace ScriptNotepad.Editor.EntityHelpers +namespace ScriptNotepad.Editor.EntityHelpers; + +/// +/// Helper methods for the entity. +/// +public static class FileSaveHelper { /// - /// Helper methods for the entity. + /// Gets the data indexer fot the instances. + /// + /// The data indexer fot the instances. + public static DataHolderIndexer DataIndexer { get; } = new(); + + /// + /// Gets the encoding of the file save. /// - public static class FileSaveHelper + /// The instance. + /// The encoding used in the file save. + public static Encoding GetEncoding(this FileSave fileSave) { - /// - /// Gets the data indexer fot the instances. - /// - /// The data indexer fot the instances. - public static DataHolderIndexer DataIndexer { get; } = new(); - - /// - /// Gets the encoding of the file save. - /// - /// The instance. - /// The encoding used in the file save. - public static Encoding GetEncoding(this FileSave fileSave) - { - return EncodingData.EncodingFromString(fileSave.EncodingAsString); - } + return EncodingData.EncodingFromString(fileSave.EncodingAsString); + } - /// - /// Sets the encoding for the file save. - /// - /// The instance. - /// The encoding. - public static void SetEncoding(this FileSave fileSave, Encoding encoding) - { - fileSave.EncodingAsString = EncodingData.EncodingToString(encoding); - } + /// + /// Sets the encoding for the file save. + /// + /// The instance. + /// The encoding. + public static void SetEncoding(this FileSave fileSave, Encoding encoding) + { + fileSave.EncodingAsString = EncodingData.EncodingToString(encoding); + } + + /// + /// Restores the previous time stamp for the property value. + /// + /// The instance. + public static void PopPreviousDbModified(this FileSave fileSave) + { + fileSave.DatabaseModified = fileSave.GetPreviousDbModified(); + } - /// - /// Restores the previous time stamp for the property value. - /// - /// The instance. - public static void PopPreviousDbModified(this FileSave fileSave) + /// + /// Sets the random file name for this instance to to be used as a file system cache for changed file contents. The must be true for this to work. + /// + /// The instance. + /// System.String. + public static string? SetRandomFile(this FileSave fileSave) + { + if (fileSave.TemporaryFileSaveName == null && fileSave.UseFileSystemOnContents == true) { - fileSave.DatabaseModified = fileSave.GetPreviousDbModified(); + fileSave.Session ??= new FileSession(); + fileSave.Session.SetRandomPath(); + fileSave.TemporaryFileSaveName = Path.Combine(fileSave.Session.TemporaryFilePath ?? string.Empty, + Path.GetRandomFileName()); } - - /// - /// Sets the random file name for this instance to to be used as a file system cache for changed file contents. The must be true for this to work. - /// - /// The instance. - /// System.String. - public static string? SetRandomFile(this FileSave fileSave) + else if (!fileSave.UseFileSystemOnContents == false) { - if (fileSave.TemporaryFileSaveName == null && fileSave.UseFileSystemOnContents == true) - { - fileSave.Session ??= new FileSession(); - fileSave.Session.SetRandomPath(); - fileSave.TemporaryFileSaveName = Path.Combine(fileSave.Session.TemporaryFilePath ?? string.Empty, - Path.GetRandomFileName()); - } - else if (!fileSave.UseFileSystemOnContents == false) - { - fileSave.TemporaryFileSaveName = null; - } - - return fileSave.TemporaryFileSaveName; + fileSave.TemporaryFileSaveName = null; } - /// - /// Sets the file contents of this class instance. - /// The contents are either saved to the file system or to the database depending on the property value. - /// - /// The instance. - /// The file contents. - /// A value indicating whether to commit the changes to the - /// database or to the file system cache depending on the property value. - /// A value indicating whether to override existing copy of the file in the file system. - /// A value indicating whether the file contents have been changed. - /// true if the operation was successful, false otherwise. - public static bool SetFileContents(this FileSave fileSave, byte[] fileContents, bool commit, - bool saveToFileSystem, - bool contentChanged) + return fileSave.TemporaryFileSaveName; + } + + /// + /// Sets the file contents of this class instance. + /// The contents are either saved to the file system or to the database depending on the property value. + /// + /// The instance. + /// The file contents. + /// A value indicating whether to commit the changes to the + /// database or to the file system cache depending on the property value. + /// A value indicating whether to override existing copy of the file in the file system. + /// A value indicating whether the file contents have been changed. + /// true if the operation was successful, false otherwise. + public static bool SetFileContents(this FileSave fileSave, byte[] fileContents, bool commit, + bool saveToFileSystem, + bool contentChanged) + { + try { - try - { - fileSave.FileContents = fileContents; + fileSave.FileContents = fileContents; - if (fileSave.UseFileSystemOnContents == true) + if (fileSave.UseFileSystemOnContents == true) + { + if (commit && !saveToFileSystem) { - if (commit && !saveToFileSystem) + var randomFile = fileSave.SetRandomFile(); + if (randomFile != null) { - var randomFile = fileSave.SetRandomFile(); - if (randomFile != null) - { - File.WriteAllBytes(randomFile, fileContents); - } + File.WriteAllBytes(randomFile, fileContents); } + } - if (saveToFileSystem) + if (saveToFileSystem) + { + var randomFile = fileSave.SetRandomFile(); + if (randomFile != null) { - var randomFile = fileSave.SetRandomFile(); - if (randomFile != null) - { - File.WriteAllBytes(randomFile, fileContents); - } - - if (fileSave.ExistsInFileSystem) - { - File.WriteAllBytes(fileSave.FileNameFull, fileContents); - fileSave.FileSystemSaved = DateTime.Now; - } + File.WriteAllBytes(randomFile, fileContents); } - } - else - { - fileSave.FileContents = fileContents; - } - if (contentChanged) - { - fileSave.DatabaseModified = DateTime.Now; + if (fileSave.ExistsInFileSystem) + { + File.WriteAllBytes(fileSave.FileNameFull, fileContents); + fileSave.FileSystemSaved = DateTime.Now; + } } - - return true; } - catch (Exception ex) + else { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return false; + fileSave.FileContents = fileContents; } - } - - /// - /// Gets the cached file contents of this class instance. - /// - /// The instance. - /// A byte array with the file contents. - public static byte[]? GetFileContents(this FileSave fileSave) - { - try - { - if (fileSave.UseFileSystemOnContents == true && fileSave.TemporaryFileSaveName != null) - { - return File.ReadAllBytes(fileSave.TemporaryFileSaveName); - } - return fileSave.FileContents; - } - catch (Exception ex) + if (contentChanged) { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return null; + fileSave.DatabaseModified = DateTime.Now; } - } - - /// - /// Undoes the encoding change. - /// - /// The instance. - public static void UndoEncodingChange(this FileSave fileSave) - { - // only if there exists a previous encoding.. - if (DataIndexer[fileSave.Id].PreviousEncodings.Count > 0) - { - // get the last index of the list.. - int idx = DataIndexer[fileSave.Id].PreviousEncodings.Count - 1; - - // set the previous encoding value.. - fileSave.SetEncoding(DataIndexer[fileSave.Id].PreviousEncodings[idx]); - // remove the last encoding from the list.. - DataIndexer[fileSave.Id].PreviousEncodings.RemoveAt(idx); - } + return true; } - - /// - /// Resets the previous database modified property, so it can be set again. - /// - /// The instance. - public static void ResetPreviousDbModified(this FileSave fileSave) + catch (Exception ex) { - DataIndexer[fileSave.Id].PreviousDbModifiedIsSet = false; - DataIndexer[fileSave.Id].PreviousDbModified = DateTime.MinValue; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return false; } + } - /// - /// Sets the value indicating when the file was previously modified in the database. - /// - /// The instance. - /// The to set as previously modified time. - public static void SetPreviousDbModified(this FileSave fileSave, DateTime value) + /// + /// Gets the cached file contents of this class instance. + /// + /// The instance. + /// A byte array with the file contents. + public static byte[]? GetFileContents(this FileSave fileSave) + { + try { - if (DataIndexer[fileSave.Id].PreviousDbModified.CompareTo(value) != 0 && !DataIndexer[fileSave.Id].PreviousDbModifiedIsSet) + if (fileSave.UseFileSystemOnContents == true && fileSave.TemporaryFileSaveName != null) { - DataIndexer[fileSave.Id].PreviousDbModifiedIsSet = true; - DataIndexer[fileSave.Id].PreviousDbModified = value; + return File.ReadAllBytes(fileSave.TemporaryFileSaveName); } - } - /// - /// Gets the value indicating when the file was previously modified in the database. - /// - /// The instance. - public static DateTime GetPreviousDbModified(this FileSave fileSave) + return fileSave.FileContents; + } + catch (Exception ex) { - return DataIndexer[fileSave.Id].PreviousDbModified; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return null; } + } - /// - /// Gets the file contents as a memory stream. - /// - /// The instance. - /// The file contents as a memory stream. - public static MemoryStream GetFileContentsAsMemoryStream(this FileSave fileSave) + /// + /// Undoes the encoding change. + /// + /// The instance. + public static void UndoEncodingChange(this FileSave fileSave) + { + // only if there exists a previous encoding.. + if (DataIndexer[fileSave.Id].PreviousEncodings.Count > 0) { - var fileContents = fileSave.GetFileContents(); - if (fileContents == null || fileContents.Length == 0) - { - return new MemoryStream(); - } + // get the last index of the list.. + int idx = DataIndexer[fileSave.Id].PreviousEncodings.Count - 1; - return new MemoryStream(fileContents); + // set the previous encoding value.. + fileSave.SetEncoding(DataIndexer[fileSave.Id].PreviousEncodings[idx]); + + // remove the last encoding from the list.. + DataIndexer[fileSave.Id].PreviousEncodings.RemoveAt(idx); } + } + + /// + /// Resets the previous database modified property, so it can be set again. + /// + /// The instance. + public static void ResetPreviousDbModified(this FileSave fileSave) + { + DataIndexer[fileSave.Id].PreviousDbModifiedIsSet = false; + DataIndexer[fileSave.Id].PreviousDbModified = DateTime.MinValue; + } - /// - /// Gets the file contents as a memory stream. - /// - /// The instance. - /// The file's contents in a memory stream. - /// The file contents as a memory stream. - public static void SetFileContentsAsMemoryStream(this FileSave fileSave, MemoryStream value) + /// + /// Sets the value indicating when the file was previously modified in the database. + /// + /// The instance. + /// The to set as previously modified time. + public static void SetPreviousDbModified(this FileSave fileSave, DateTime value) + { + if (DataIndexer[fileSave.Id].PreviousDbModified.CompareTo(value) != 0 && !DataIndexer[fileSave.Id].PreviousDbModifiedIsSet) { - fileSave.SetFileContents(value.ToArray(), true, false, false); + DataIndexer[fileSave.Id].PreviousDbModifiedIsSet = true; + DataIndexer[fileSave.Id].PreviousDbModified = value; } + } - /// - /// Gets a value indicating whether the user should be queried of to reload the changed document from the file system. - /// - /// The instance. - /// The value indicating whether the user should be queried of to reload the changed document from the file system. - public static bool GetShouldQueryDiskReload(this FileSave fileSave) + /// + /// Gets the value indicating when the file was previously modified in the database. + /// + /// The instance. + public static DateTime GetPreviousDbModified(this FileSave fileSave) + { + return DataIndexer[fileSave.Id].PreviousDbModified; + } + + /// + /// Gets the file contents as a memory stream. + /// + /// The instance. + /// The file contents as a memory stream. + public static MemoryStream GetFileContentsAsMemoryStream(this FileSave fileSave) + { + var fileContents = fileSave.GetFileContents(); + if (fileContents == null || fileContents.Length == 0) { - var fileSysModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; + return new MemoryStream(); + } - // get the last time the file was written into.. - DateTime dtUpdated = fileSysModified; + return new MemoryStream(fileContents); + } - // get the result to be returned.. - bool result = DataIndexer[fileSave.Id].ShouldQueryDiskReload && dtUpdated > fileSave.FileSystemModified; + /// + /// Gets the file contents as a memory stream. + /// + /// The instance. + /// The file's contents in a memory stream. + /// The file contents as a memory stream. + public static void SetFileContentsAsMemoryStream(this FileSave fileSave, MemoryStream value) + { + fileSave.SetFileContents(value.ToArray(), true, false, false); + } - return result; - } + /// + /// Gets a value indicating whether the user should be queried of to reload the changed document from the file system. + /// + /// The instance. + /// The value indicating whether the user should be queried of to reload the changed document from the file system. + public static bool GetShouldQueryDiskReload(this FileSave fileSave) + { + var fileSysModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; - /// - /// Sets a value indicating whether the user should be queried of to reload the changed document from the file system. - /// - /// The instance. - /// The value indicating whether the user should be queried of to reload the changed document from the file system. - public static void SetShouldQueryDiskReload(this FileSave fileSave, bool value) - { - DataIndexer[fileSave.Id].ShouldQueryDiskReload = value; - } + // get the last time the file was written into.. + DateTime dtUpdated = fileSysModified; - /// - /// Gets a value indicating whether a software should query the user if the deleted file should be kept in the editor. - /// - /// The instance. - /// A value indicating whether a software should query the user if the deleted file should be kept in the editor. - public static bool ShouldQueryKeepFile(this FileSave fileSave) - { - return fileSave.ExistsInFileSystem && !File.Exists(fileSave.FileNameFull); - } + // get the result to be returned.. + bool result = DataIndexer[fileSave.Id].ShouldQueryDiskReload && dtUpdated > fileSave.FileSystemModified; - /// - /// Gets a value indicating whether a software should query the user if a file reappeared in the file system should be reloaded. - /// - /// The instance. - /// A value indicating whether a software should query the user if a file reappeared in the file system should be reloaded. - public static bool ShouldQueryFileReappeared(this FileSave fileSave) - { - return !fileSave.ExistsInFileSystem && File.Exists(fileSave.FileNameFull); - } + return result; + } - /// - /// Gets a value indicating whether the document is changed in the editor versus the file system. - /// - /// The instance. - /// A value indicating whether the document is changed in the editor versus the file system. - public static bool IsChangedInEditor(this FileSave fileSave) - { - return fileSave.ExistsInFileSystem && fileSave.DatabaseModified > fileSave.FileSystemModified; - } + /// + /// Sets a value indicating whether the user should be queried of to reload the changed document from the file system. + /// + /// The instance. + /// The value indicating whether the user should be queried of to reload the changed document from the file system. + public static void SetShouldQueryDiskReload(this FileSave fileSave, bool value) + { + DataIndexer[fileSave.Id].ShouldQueryDiskReload = value; + } - /// - /// Adds a previous encoding to the collection for undo possibility. - /// - /// The instance. - /// The encoding to add. - public static void AddPreviousEncoding(this FileSave fileSave, Encoding encoding) - { - DataIndexer[fileSave.Id].PreviousEncodings.Add(encoding); - } + /// + /// Gets a value indicating whether a software should query the user if the deleted file should be kept in the editor. + /// + /// The instance. + /// A value indicating whether a software should query the user if the deleted file should be kept in the editor. + public static bool ShouldQueryKeepFile(this FileSave fileSave) + { + return fileSave.ExistsInFileSystem && !File.Exists(fileSave.FileNameFull); + } - /// - /// Clears the previous encodings data from the . - /// - /// The instance. - public static void ClearPreviousEncodings(this FileSave fileSave) - { - DataIndexer[fileSave.Id].PreviousEncodings.Clear(); - } + /// + /// Gets a value indicating whether a software should query the user if a file reappeared in the file system should be reloaded. + /// + /// The instance. + /// A value indicating whether a software should query the user if a file reappeared in the file system should be reloaded. + public static bool ShouldQueryFileReappeared(this FileSave fileSave) + { + return !fileSave.ExistsInFileSystem && File.Exists(fileSave.FileNameFull); + } - /// - /// Gets the file line types and their descriptions. - /// - /// The instance. - /// File line types and their descriptions. - public static IEnumerable> GetFileLineTypes(this FileSave fileSave) - { - if (fileSave.FileContents == null) - { - var fileLineTypes = - ScriptNotepad.UtilityClasses.LinesAndBinary.FileLineType.GetFileLineTypes(fileSave.FileContents); + /// + /// Gets a value indicating whether the document is changed in the editor versus the file system. + /// + /// The instance. + /// A value indicating whether the document is changed in the editor versus the file system. + public static bool IsChangedInEditor(this FileSave fileSave) + { + return fileSave.ExistsInFileSystem && fileSave.DatabaseModified > fileSave.FileSystemModified; + } - var lineTypesInternal = fileLineTypes as KeyValuePair[] ?? - fileLineTypes.ToArray(); + /// + /// Adds a previous encoding to the collection for undo possibility. + /// + /// The instance. + /// The encoding to add. + public static void AddPreviousEncoding(this FileSave fileSave, Encoding encoding) + { + DataIndexer[fileSave.Id].PreviousEncodings.Add(encoding); + } - DataIndexer[fileSave.Id].FileLineTypesInternal = lineTypesInternal; + /// + /// Clears the previous encodings data from the . + /// + /// The instance. + public static void ClearPreviousEncodings(this FileSave fileSave) + { + DataIndexer[fileSave.Id].PreviousEncodings.Clear(); + } - return lineTypesInternal; - } + /// + /// Gets the file line types and their descriptions. + /// + /// The instance. + /// File line types and their descriptions. + public static IEnumerable> GetFileLineTypes(this FileSave fileSave) + { + if (fileSave.FileContents == null) + { + var fileLineTypes = + ScriptNotepad.UtilityClasses.LinesAndBinary.FileLineType.GetFileLineTypes(fileSave.FileContents); + + var lineTypesInternal = fileLineTypes as KeyValuePair[] ?? + fileLineTypes.ToArray(); + + DataIndexer[fileSave.Id].FileLineTypesInternal = lineTypesInternal; - return DataIndexer[fileSave.Id].FileLineTypesInternal; + return lineTypesInternal; } - /// - /// Gets the type of the file line ending. - /// - /// The instance. - /// The type of the file line ending. - public static FileLineTypes GetFileLineType(this FileSave fileSave) - { - List> typesList = - new(fileSave.GetFileLineTypes().ToArray()); + return DataIndexer[fileSave.Id].FileLineTypesInternal; + } - if (typesList.Count == 0 || - typesList.Count == 1 && typesList[0].Key.HasFlag(FileLineTypes.Mixed)) - { - return FileLineTypes.CRLF; - } + /// + /// Gets the type of the file line ending. + /// + /// The instance. + /// The type of the file line ending. + public static FileLineTypes GetFileLineType(this FileSave fileSave) + { + List> typesList = + new(fileSave.GetFileLineTypes().ToArray()); - if (typesList.Count == 1) - { - return typesList[0].Key; - } + if (typesList.Count == 0 || + typesList.Count == 1 && typesList[0].Key.HasFlag(FileLineTypes.Mixed)) + { + return FileLineTypes.CRLF; + } - return typesList.FirstOrDefault().Key; + if (typesList.Count == 1) + { + return typesList[0].Key; } - /// - /// Gets the text describing the file line ending type(s) of the document. - /// - /// The instance. - /// The text describing the file line ending type(s) of the document. - public static string FileLineEndingText(this FileSave fileSave) + return typesList.FirstOrDefault().Key; + } + + /// + /// Gets the text describing the file line ending type(s) of the document. + /// + /// The instance. + /// The text describing the file line ending type(s) of the document. + public static string FileLineEndingText(this FileSave fileSave) + { + if (string.IsNullOrEmpty(DataIndexer[fileSave.Id].FileEndingText)) { - if (string.IsNullOrEmpty(DataIndexer[fileSave.Id].FileEndingText)) - { - DataIndexer[fileSave.Id].FileEndingText = DBLangEngine.GetStatMessage("msgLineEndingShort", - "LE: |A short message indicating a file line ending type value(s) as a concatenated text"); + DataIndexer[fileSave.Id].FileEndingText = DBLangEngine.GetStatMessage("msgLineEndingShort", + "LE: |A short message indicating a file line ending type value(s) as a concatenated text"); - var fileLineTypes = fileSave.GetFileLineTypes(); + var fileLineTypes = fileSave.GetFileLineTypes(); - string endAppend = string.Empty; + string endAppend = string.Empty; - foreach (var fileLineType in fileLineTypes) + foreach (var fileLineType in fileLineTypes) + { + if (!fileLineType.Key.HasFlag(FileLineTypes.Mixed)) { - if (!fileLineType.Key.HasFlag(FileLineTypes.Mixed)) - { - DataIndexer[fileSave.Id].FileEndingText += fileLineType.Value + ", "; - } - else - { - endAppend = $" ({fileLineType.Value})"; - } - - DataIndexer[fileSave.Id].FileEndingText = - DataIndexer[fileSave.Id].FileEndingText.TrimEnd(',', ' ') + endAppend; + DataIndexer[fileSave.Id].FileEndingText += fileLineType.Value + ", "; + } + else + { + endAppend = $" ({fileLineType.Value})"; } - } - return DataIndexer[fileSave.Id].FileEndingText; + DataIndexer[fileSave.Id].FileEndingText = + DataIndexer[fileSave.Id].FileEndingText.TrimEnd(',', ' ') + endAppend; + } } - /// - /// Sets the database modified property value along with the property value. - /// - /// The file save. - /// The value. - public static void SetDatabaseModified(this FileSave fileSave, DateTime value) - { - fileSave.SetPreviousDbModified(fileSave.DatabaseModified); - fileSave.DatabaseModified = value; - } + return DataIndexer[fileSave.Id].FileEndingText; + } + + /// + /// Sets the database modified property value along with the property value. + /// + /// The file save. + /// The value. + public static void SetDatabaseModified(this FileSave fileSave, DateTime value) + { + fileSave.SetPreviousDbModified(fileSave.DatabaseModified); + fileSave.DatabaseModified = value; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/EntityHelpers/FileSessionHelper.cs b/ScriptNotepad/Editor/EntityHelpers/FileSessionHelper.cs index 912e1542..83764953 100644 --- a/ScriptNotepad/Editor/EntityHelpers/FileSessionHelper.cs +++ b/ScriptNotepad/Editor/EntityHelpers/FileSessionHelper.cs @@ -1,44 +1,43 @@ #nullable enable using ScriptNotepad.Database.Entity.Entities; -namespace ScriptNotepad.Editor.EntityHelpers +namespace ScriptNotepad.Editor.EntityHelpers; + +/// +/// Helper methods for the entity. +/// +public static class FileSessionHelper { /// - /// Helper methods for the entity. + /// Generates, creates and sets a random path for the property in case the property value is null. /// - public static class FileSessionHelper + /// The instance. + /// The generated or already existing path for temporary files for the session. + public static string? SetRandomPath(this FileSession fileSession) { - /// - /// Generates, creates and sets a random path for the property in case the property value is null. - /// - /// The instance. - /// The generated or already existing path for temporary files for the session. - public static string? SetRandomPath(this FileSession fileSession) + if (fileSession.TemporaryFilePath == null && fileSession.UseFileSystemOnContents) { - if (fileSession.TemporaryFilePath == null && fileSession.UseFileSystemOnContents) + var path = Path.Combine(ApplicationDataDirectory, Path.GetRandomFileName()); + if (!Directory.Exists(path)) { - var path = Path.Combine(ApplicationDataDirectory, Path.GetRandomFileName()); - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - fileSession.TemporaryFilePath = path; - - return path; + Directory.CreateDirectory(path); } - if (!fileSession.UseFileSystemOnContents) - { - fileSession.TemporaryFilePath = null; - } + fileSession.TemporaryFilePath = path; - return fileSession.TemporaryFilePath; + return path; } - /// - /// Gets or sets the application data directory for caching files in case the property is set to true. - /// - public static string ApplicationDataDirectory { get; set; } = string.Empty; + if (!fileSession.UseFileSystemOnContents) + { + fileSession.TemporaryFilePath = null; + } + + return fileSession.TemporaryFilePath; } -} + + /// + /// Gets or sets the application data directory for caching files in case the property is set to true. + /// + public static string ApplicationDataDirectory { get; set; } = string.Empty; +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/EntityHelpers/RecentFileHelper.cs b/ScriptNotepad/Editor/EntityHelpers/RecentFileHelper.cs index c237cb56..135ca1ed 100644 --- a/ScriptNotepad/Editor/EntityHelpers/RecentFileHelper.cs +++ b/ScriptNotepad/Editor/EntityHelpers/RecentFileHelper.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -31,82 +31,81 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.Encodings; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Editor.EntityHelpers +namespace ScriptNotepad.Editor.EntityHelpers; + +/// +/// Helper methods for the entity. +/// +public static class RecentFileHelper { /// - /// Helper methods for the entity. + /// Gets the encoding of the recent file. /// - public static class RecentFileHelper + /// The instance. + public static Encoding GetEncoding(this RecentFile recentFile) { - /// - /// Gets the encoding of the recent file. - /// - /// The instance. - public static Encoding GetEncoding(this RecentFile recentFile) - { - return EncodingData.EncodingFromString(recentFile.EncodingAsString) ?? Encoding.UTF8; - } + return EncodingData.EncodingFromString(recentFile.EncodingAsString) ?? Encoding.UTF8; + } - /// - /// Gets the encoding of the recent file. - /// - /// The instance. - /// The encoding to set for the recent file. - public static void SetEncoding(this RecentFile recentFile, Encoding value) - { - recentFile.EncodingAsString = EncodingData.EncodingToString(value); - } + /// + /// Gets the encoding of the recent file. + /// + /// The instance. + /// The encoding to set for the recent file. + public static void SetEncoding(this RecentFile recentFile, Encoding value) + { + recentFile.EncodingAsString = EncodingData.EncodingToString(value); + } - /// - /// Gets a value indicating whether a snapshot of the file in question exists in the database. - /// - /// The instance. - /// The entities to compare the specified to. - public static bool ExistsInDatabase(this RecentFile recentFile, DbSet fileSaves) - { - return fileSaves.Count(f => f.FileNameFull == recentFile.FileNameFull && f.Session.SessionName == recentFile.Session.SessionName && f.IsHistory) > 0; - } + /// + /// Gets a value indicating whether a snapshot of the file in question exists in the database. + /// + /// The instance. + /// The entities to compare the specified to. + public static bool ExistsInDatabase(this RecentFile recentFile, DbSet fileSaves) + { + return fileSaves.Count(f => f.FileNameFull == recentFile.FileNameFull && f.Session.SessionName == recentFile.Session.SessionName && f.IsHistory) > 0; + } - /// - /// Adds or updates a entity into the database. - /// - /// The entity to use for a recent file data. - /// true if the operation was successful, false otherwise. - public static bool AddOrUpdateRecentFile(FileSave fileSave) + /// + /// Adds or updates a entity into the database. + /// + /// The entity to use for a recent file data. + /// true if the operation was successful, false otherwise. + public static bool AddOrUpdateRecentFile(FileSave fileSave) + { + try { - try - { - var dbContext = ScriptNotepadDbContext.DbContext; - var recentFile = dbContext.RecentFiles.FirstOrDefault(f => - f.FileNameFull == fileSave.FileNameFull && f.Session.SessionName == fileSave.Session.SessionName); - - if (recentFile != null) - { - recentFile.ClosedDateTime = DateTime.Now; - recentFile.SetEncoding(fileSave.GetEncoding()); - } - else - { - dbContext.RecentFiles.Add(new RecentFile - { - FileNameFull = fileSave.FileNameFull, - Session = fileSave.Session, - EncodingAsString = EncodingData.EncodingToString(fileSave.GetEncoding()), - ClosedDateTime = DateTime.Now, - FileName = fileSave.FileName, - FilePath = fileSave.FilePath, - }); - } + var dbContext = ScriptNotepadDbContext.DbContext; + var recentFile = dbContext.RecentFiles.FirstOrDefault(f => + f.FileNameFull == fileSave.FileNameFull && f.Session.SessionName == fileSave.Session.SessionName); - dbContext.SaveChanges(); - return true; + if (recentFile != null) + { + recentFile.ClosedDateTime = DateTime.Now; + recentFile.SetEncoding(fileSave.GetEncoding()); } - catch (Exception ex) + else { - // log the exception.. - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return false; + dbContext.RecentFiles.Add(new RecentFile + { + FileNameFull = fileSave.FileNameFull, + Session = fileSave.Session, + EncodingAsString = EncodingData.EncodingToString(fileSave.GetEncoding()), + ClosedDateTime = DateTime.Now, + FileName = fileSave.FileName, + FilePath = fileSave.FilePath, + }); } + + dbContext.SaveChanges(); + return true; + } + catch (Exception ex) + { + // log the exception.. + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return false; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/AssemblyVersion.cs b/ScriptNotepad/Editor/Utility/AssemblyVersion.cs index 6c19d0cf..7e0ee51d 100644 --- a/ScriptNotepad/Editor/Utility/AssemblyVersion.cs +++ b/ScriptNotepad/Editor/Utility/AssemblyVersion.cs @@ -28,75 +28,74 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Entities; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Editor.Utility +namespace ScriptNotepad.Editor.Utility; + +/// +/// A class to help to deal with versions. +/// Implements the +/// +/// +public class AssemblyVersion: ErrorHandlingBase { /// - /// A class to help to deal with versions. - /// Implements the + /// Gets a version string from a given . /// - /// - public class AssemblyVersion: ErrorHandlingBase + /// The assembly to set the version from. + public static string VersionStringFromAssembly(Assembly assembly) { - /// - /// Gets a version string from a given . - /// - /// The assembly to set the version from. - public static string VersionStringFromAssembly(Assembly assembly) + try { - try - { - // return the version from the given assembly.. - return assembly.GetName().Version.ToString(); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - - // return a default value.. - return "1.0.0.0"; - } + // return the version from the given assembly.. + return assembly.GetName().Version.ToString(); } - - /// - /// Sets the from a given assembly. - /// - /// The plugin which version to update. - /// The assembly to set the version from. - public static void VersionFromAssembly(Plugin plugin, Assembly assembly) + catch (Exception ex) { - // get the plug-in version from the given assembly.. - plugin.PluginVersion = VersionStringFromAssembly(assembly); + // log the exception.. + ExceptionLogAction?.Invoke(ex); + + // return a default value.. + return "1.0.0.0"; } + } - /// - /// Sets the property if the given assembly version is larger than the previous . - /// - /// The plugin which update state to check. - /// The assembly which version to compare to the current one. - public static void SetPluginUpdated(Plugin plugin, Assembly assembly) + /// + /// Sets the from a given assembly. + /// + /// The plugin which version to update. + /// The assembly to set the version from. + public static void VersionFromAssembly(Plugin plugin, Assembly assembly) + { + // get the plug-in version from the given assembly.. + plugin.PluginVersion = VersionStringFromAssembly(assembly); + } + + /// + /// Sets the property if the given assembly version is larger than the previous . + /// + /// The plugin which update state to check. + /// The assembly which version to compare to the current one. + public static void SetPluginUpdated(Plugin plugin, Assembly assembly) + { + try { - try - { - Version newVersion = assembly.GetName().Version; // get the assembly version.. - Version previousVersion = new Version(plugin.PluginVersion); // get the previous version.. + Version newVersion = assembly.GetName().Version; // get the assembly version.. + Version previousVersion = new Version(plugin.PluginVersion); // get the previous version.. - // update the version whether required or not.. - VersionFromAssembly(plugin, assembly); + // update the version whether required or not.. + VersionFromAssembly(plugin, assembly); - // if the new version is larger than the previous one.. - if (newVersion > previousVersion) - { - // ..set a new time for the PLUGIN_UPDATED property.. - plugin.PluginUpdated = DateTime.Now; - } - } - catch (Exception ex) + // if the new version is larger than the previous one.. + if (newVersion > previousVersion) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + // ..set a new time for the PLUGIN_UPDATED property.. + plugin.PluginUpdated = DateTime.Now; } } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/DocumentReload.cs b/ScriptNotepad/Editor/Utility/DocumentReload.cs index 61c33f4d..2ef2e5ec 100644 --- a/ScriptNotepad/Editor/Utility/DocumentReload.cs +++ b/ScriptNotepad/Editor/Utility/DocumentReload.cs @@ -30,78 +30,77 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.StreamHelpers; using VPKSoft.ScintillaTabbedTextControl; -namespace ScriptNotepad.Editor.Utility +namespace ScriptNotepad.Editor.Utility; + +/// +/// A helper class to reload a document from the file system. +/// +public static class DocumentReload { /// - /// A helper class to reload a document from the file system. + /// Reloads the contents of the document from the disk. /// - public static class DocumentReload + /// An instance to a class. + /// A ScintillaTabbedDocument to which contents should also be updated. + /// True if the operation was successful; otherwise false. + public static bool ReloadFromDisk(this FileSave fileSave, ScintillaTabbedDocument document) { - /// - /// Reloads the contents of the document from the disk. - /// - /// An instance to a class. - /// A ScintillaTabbedDocument to which contents should also be updated. - /// True if the operation was successful; otherwise false. - public static bool ReloadFromDisk(this FileSave fileSave, ScintillaTabbedDocument document) + try { - try + // can't reload what doesn't exist.. + if (File.Exists(fileSave.FileNameFull)) { - // can't reload what doesn't exist.. - if (File.Exists(fileSave.FileNameFull)) + // read the file contents from the file.. + using (FileStream fileStream = new FileStream(fileSave.FileNameFull, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { - // read the file contents from the file.. - using (FileStream fileStream = new FileStream(fileSave.FileNameFull, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - // create a byte buffer the contain all the bytes if the file with an assumption - // no one wishes to open massive binary files.. - byte[] fileContents = new byte[fileStream.Length]; - - // read the file contents to the buffer.. - fileStream.Read(fileContents, 0, (int)fileStream.Length); + // create a byte buffer the contain all the bytes if the file with an assumption + // no one wishes to open massive binary files.. + byte[] fileContents = new byte[fileStream.Length]; - // set the file system's modified flag.. - fileSave.FileSystemModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; + // read the file contents to the buffer.. + fileStream.Read(fileContents, 0, (int)fileStream.Length); - fileSave.SetDatabaseModified(fileSave.FileSystemModified); // set the other DateTime flags to indicate the same.. - fileSave.FileSystemSaved = fileSave.FileSystemModified; // set the other DateTime flags to indicate the same.. - fileSave.ResetPreviousDbModified(); + // set the file system's modified flag.. + fileSave.FileSystemModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; + fileSave.SetDatabaseModified(fileSave.FileSystemModified); // set the other DateTime flags to indicate the same.. + fileSave.FileSystemSaved = fileSave.FileSystemModified; // set the other DateTime flags to indicate the same.. + fileSave.ResetPreviousDbModified(); - // create a new memory stream to hold the file contents.. - MemoryStream memoryStream = new MemoryStream(fileContents); - document.Scintilla.Text = StreamStringHelpers.MemoryStreamToText(memoryStream, fileSave.GetEncoding()); + // create a new memory stream to hold the file contents.. + MemoryStream memoryStream = new MemoryStream(fileContents); - // a reload doesn't need to be undone.. - document.Scintilla.EmptyUndoBuffer(); + document.Scintilla.Text = StreamStringHelpers.MemoryStreamToText(memoryStream, fileSave.GetEncoding()); - fileSave.SetFileContentsAsMemoryStream(memoryStream); + // a reload doesn't need to be undone.. + document.Scintilla.EmptyUndoBuffer(); - // set the saved position of the document's caret.. - if (fileSave.CurrentCaretPosition > 0 && fileSave.CurrentCaretPosition < document.Scintilla.TextLength) - { - document.Scintilla.CurrentPosition = fileSave.CurrentCaretPosition; - document.Scintilla.SelectionStart = fileSave.CurrentCaretPosition; - document.Scintilla.SelectionEnd = fileSave.CurrentCaretPosition; - document.Scintilla.ScrollCaret(); - } + fileSave.SetFileContentsAsMemoryStream(memoryStream); + // set the saved position of the document's caret.. + if (fileSave.CurrentCaretPosition > 0 && fileSave.CurrentCaretPosition < document.Scintilla.TextLength) + { + document.Scintilla.CurrentPosition = fileSave.CurrentCaretPosition; + document.Scintilla.SelectionStart = fileSave.CurrentCaretPosition; + document.Scintilla.SelectionEnd = fileSave.CurrentCaretPosition; + document.Scintilla.ScrollCaret(); } - return true; // success.. - } - else - { - return false; // the file didn't exists, so fail.. + } + return true; // success.. } - catch (Exception ex) + else { - // log the exception.. - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - - return false; // an exception occurred, so fail.. + return false; // the file didn't exists, so fail.. } } + catch (Exception ex) + { + // log the exception.. + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + + return false; // an exception occurred, so fail.. + } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/ModelHelpers/FileHistoryHelper.cs b/ScriptNotepad/Editor/Utility/ModelHelpers/FileHistoryHelper.cs index 39a07bd0..2db301d1 100644 --- a/ScriptNotepad/Editor/Utility/ModelHelpers/FileHistoryHelper.cs +++ b/ScriptNotepad/Editor/Utility/ModelHelpers/FileHistoryHelper.cs @@ -29,107 +29,106 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Entities; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Editor.Utility.ModelHelpers +namespace ScriptNotepad.Editor.Utility.ModelHelpers; + +/// +/// A class to help with file history and excess history cleanup. +/// Implements the +/// +/// +public class FileHistoryHelper: ErrorHandlingBase { /// - /// A class to help with file history and excess history cleanup. - /// Implements the + /// Cleans up the closed (history) files from a given session with a given maximum amount to keep. /// - /// - public class FileHistoryHelper: ErrorHandlingBase + /// The maximum number of file history to keep per session. + /// The session + /// true a tuple containing the value whether the clean up was successful and the amount of records deleted. + public static (bool success, int count) CleanUpHistoryFiles(int keepMaximum, FileSession session) { - /// - /// Cleans up the closed (history) files from a given session with a given maximum amount to keep. - /// - /// The maximum number of file history to keep per session. - /// The session - /// true a tuple containing the value whether the clean up was successful and the amount of records deleted. - public static (bool success, int count) CleanUpHistoryFiles(int keepMaximum, FileSession session) + try { - try - { - var dbContext = ScriptNotepadDbContext.DbContext; - var deleteSavesIds = dbContext.FileSaves - .Where(f => f.Session.SessionName == session.SessionName && f.IsHistory) - .Select(f => new {id = f.Id, modified = f.DatabaseModified}); - - var deleteAmount = deleteSavesIds.Count() - keepMaximum; + var dbContext = ScriptNotepadDbContext.DbContext; + var deleteSavesIds = dbContext.FileSaves + .Where(f => f.Session.SessionName == session.SessionName && f.IsHistory) + .Select(f => new {id = f.Id, modified = f.DatabaseModified, }); - if (deleteAmount > 0) - { - deleteSavesIds = deleteSavesIds.Take(deleteAmount); + var deleteAmount = deleteSavesIds.Count() - keepMaximum; - var deleted = dbContext.FileSaves.Count(f => deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id)); + if (deleteAmount > 0) + { + deleteSavesIds = deleteSavesIds.Take(deleteAmount); - dbContext.FileSaves.RemoveRange( - dbContext.FileSaves.Where(f => - deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id))); + var deleted = dbContext.FileSaves.Count(f => deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id)); - dbContext.SaveChanges(); + dbContext.FileSaves.RemoveRange( + dbContext.FileSaves.Where(f => + deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id))); - return (true, deleted); - } + dbContext.SaveChanges(); - return (true, 0); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return (false, 0); + return (true, deleted); } - } - /// - /// Cleanups the recent file list by removing older entries from the list by a given number to keep. - /// - /// The maximum number of recent files to keep per session. - /// The session from which to clean the recent file from. - /// true a tuple containing the value whether the clean up was successful and the amount of records deleted. - public static (bool success, int count) CleanupHistoryList(int keepMaximum, FileSession session) // one could probably make this a bit more complicated.. + return (true, 0); + } + catch (Exception ex) { - try - { - var dbContext = ScriptNotepadDbContext.DbContext; + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return (false, 0); + } + } - session = - dbContext.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName); + /// + /// Cleanups the recent file list by removing older entries from the list by a given number to keep. + /// + /// The maximum number of recent files to keep per session. + /// The session from which to clean the recent file from. + /// true a tuple containing the value whether the clean up was successful and the amount of records deleted. + public static (bool success, int count) CleanupHistoryList(int keepMaximum, FileSession session) // one could probably make this a bit more complicated.. + { + try + { + var dbContext = ScriptNotepadDbContext.DbContext; - var closedCount = - dbContext.FileSaves.Count(f => f.IsHistory && f.Session.SessionName == session.SessionName); + session = + dbContext.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName); - var removeFiles = dbContext.FileSaves - .Where(f => !f.IsHistory && f.Session.SessionName == session.SessionName) - .Select(f => f.FileNameFull); + var closedCount = + dbContext.FileSaves.Count(f => f.IsHistory && f.Session.SessionName == session.SessionName); - dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles.Where(f => - f.Session.SessionName == session.SessionName && removeFiles.Contains(f.FileNameFull))); + var removeFiles = dbContext.FileSaves + .Where(f => !f.IsHistory && f.Session.SessionName == session.SessionName) + .Select(f => f.FileNameFull); - var historyRemoveCount = closedCount - keepMaximum; + dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles.Where(f => + f.Session.SessionName == session.SessionName && removeFiles.Contains(f.FileNameFull))); - if (historyRemoveCount > 0) - { - var deleted = dbContext.RecentFiles - .OrderByDescending(f => f.ClosedDateTime) - .Take(historyRemoveCount).Count(); + var historyRemoveCount = closedCount - keepMaximum; - dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles - .OrderByDescending(f => f.ClosedDateTime) - .Take(historyRemoveCount)); + if (historyRemoveCount > 0) + { + var deleted = dbContext.RecentFiles + .OrderByDescending(f => f.ClosedDateTime) + .Take(historyRemoveCount).Count(); - dbContext.SaveChanges(); + dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles + .OrderByDescending(f => f.ClosedDateTime) + .Take(historyRemoveCount)); - return (true, deleted); - } + dbContext.SaveChanges(); - return (true, 0); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return (false, 0); + return (true, deleted); } + + return (true, 0); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return (false, 0); } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/ModelHelpers/FileSaveHelper.cs b/ScriptNotepad/Editor/Utility/ModelHelpers/FileSaveHelper.cs index 9070d1c8..c85df1b1 100644 --- a/ScriptNotepad/Editor/Utility/ModelHelpers/FileSaveHelper.cs +++ b/ScriptNotepad/Editor/Utility/ModelHelpers/FileSaveHelper.cs @@ -30,155 +30,154 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Editor.EntityHelpers; using VPKSoft.ScintillaTabbedTextControl; -namespace ScriptNotepad.Editor.Utility.ModelHelpers +namespace ScriptNotepad.Editor.Utility.ModelHelpers; + +/// +/// A class to help with entities. +/// +public static class FileSaveHelper { /// - /// A class to help with entities. + /// Adds the or update file. /// - public static class FileSaveHelper + /// A class instance to be added or updated into the database. + /// An instance to a ScintillaTabbedDocument class. + /// A value indicating whether to commit the changes to the + /// database or to the file system cache depending on the setting. + /// A value indicating whether to override existing copy of the file in the file system. + /// A value indicating whether the file contents have been changed. + /// An instance to a modified class. + public static FileSave AddOrUpdateFile(this FileSave fileSave, ScintillaTabbedDocument document, bool commit, + bool saveToFileSystem, bool contentChanged) { - /// - /// Adds the or update file. - /// - /// A class instance to be added or updated into the database. - /// An instance to a ScintillaTabbedDocument class. - /// A value indicating whether to commit the changes to the - /// database or to the file system cache depending on the setting. - /// A value indicating whether to override existing copy of the file in the file system. - /// A value indicating whether the file contents have been changed. - /// An instance to a modified class. - public static FileSave AddOrUpdateFile(this FileSave fileSave, ScintillaTabbedDocument document, bool commit, - bool saveToFileSystem, bool contentChanged) + fileSave.SetFileContents(fileSave.GetEncoding().GetBytes(document.Scintilla.Text), commit, saveToFileSystem, contentChanged); + fileSave.CurrentCaretPosition = document.Scintilla.CurrentPosition; + fileSave.FilePath = Path.GetDirectoryName(fileSave.FileNameFull); + ScriptNotepadDbContext.DbContext.SaveChanges(); + + if (!ScriptNotepadDbContext.DbContext.FileSaves.Any(f => f.Id == fileSave.Id)) { - fileSave.SetFileContents(fileSave.GetEncoding().GetBytes(document.Scintilla.Text), commit, saveToFileSystem, contentChanged); - fileSave.CurrentCaretPosition = document.Scintilla.CurrentPosition; - fileSave.FilePath = Path.GetDirectoryName(fileSave.FileNameFull); - ScriptNotepadDbContext.DbContext.SaveChanges(); + return ScriptNotepadDbContext.DbContext.FileSaves.Add(fileSave).Entity; + } - if (!ScriptNotepadDbContext.DbContext.FileSaves.Any(f => f.Id == fileSave.Id)) - { - return ScriptNotepadDbContext.DbContext.FileSaves.Add(fileSave).Entity; - } + return ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Id == fileSave.Id); + } - return ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Id == fileSave.Id); - } + /// + /// Sets the contents of the class instance. + /// + /// The file save of which contents to set. + /// The contents as a string. + /// A value indicating whether to commit the changes to the + /// database or to the file system cache depending on the setting. + /// A value indicating whether to override existing copy of the file in the file system. + /// A value indicating whether the file contents have been changed. + /// An instance to a modified class. + public static FileSave SetContents(this FileSave fileSave, string contents, bool commit, + bool saveToFileSystem, bool contentChanged) + { + fileSave.SetFileContents(fileSave.GetEncoding().GetBytes(contents), commit, saveToFileSystem, contentChanged); - /// - /// Sets the contents of the class instance. - /// - /// The file save of which contents to set. - /// The contents as a string. - /// A value indicating whether to commit the changes to the - /// database or to the file system cache depending on the setting. - /// A value indicating whether to override existing copy of the file in the file system. - /// A value indicating whether the file contents have been changed. - /// An instance to a modified class. - public static FileSave SetContents(this FileSave fileSave, string contents, bool commit, - bool saveToFileSystem, bool contentChanged) - { - fileSave.SetFileContents(fileSave.GetEncoding().GetBytes(contents), commit, saveToFileSystem, contentChanged); + return fileSave; + } - return fileSave; - } + /// + /// Adds the or update file. + /// + /// The file save. + /// An instance to a modified class. + public static FileSave AddOrUpdateFile(this FileSave fileSave) + { + ScriptNotepadDbContext.DbContext.SaveChanges(); + return ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Id == fileSave.Id); + } - /// - /// Adds the or update file. - /// - /// The file save. - /// An instance to a modified class. - public static FileSave AddOrUpdateFile(this FileSave fileSave) - { - ScriptNotepadDbContext.DbContext.SaveChanges(); - return ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Id == fileSave.Id); - } + /// + /// Updates the file data of the class instance with a given full file name. + /// + /// The file save. + /// The full file name. + /// An instance to a modified class. + public static FileSave UpdateFileData(this FileSave fileSave, string fileNameFull) + { + fileSave.FileName = Path.GetFileName(fileNameFull); + fileSave.FileNameFull = fileNameFull; + fileSave.FilePath = Path.GetDirectoryName(fileNameFull); + return fileSave; + } - /// - /// Updates the file data of the class instance with a given full file name. - /// - /// The file save. - /// The full file name. - /// An instance to a modified class. - public static FileSave UpdateFileData(this FileSave fileSave, string fileNameFull) - { - fileSave.FileName = Path.GetFileName(fileNameFull); - fileSave.FileNameFull = fileNameFull; - fileSave.FilePath = Path.GetDirectoryName(fileNameFull); - return fileSave; - } + /// + /// Adds the or update file. + /// + /// A class instance to be added or updated into the database. + /// An instance to a ScintillaTabbedDocument class. + /// if set to true the file is to be considered as a closed/history file. + /// Name of the session the file belongs to. + /// The encoding of the file. + /// A value indicating whether to commit the changes to the + /// database or to the file system cache depending on the setting. + /// A value indicating whether to override existing copy of the file in the file system. + /// A value indicating whether the file contents have been changed. + /// An instance to a modified class. + public static FileSave AddOrUpdateFile(this FileSave fileSave, ScintillaTabbedDocument document, bool isHistory, + string sessionName, Encoding encoding, bool commit, + bool saveToFileSystem, bool contentChanged) + { + fileSave.SetFileContents(fileSave.GetEncoding().GetBytes(document.Scintilla.Text), commit, saveToFileSystem, contentChanged); + fileSave.CurrentCaretPosition = document.Scintilla.CurrentPosition; + fileSave.FilePath = Path.GetDirectoryName(fileSave.FileNameFull); + fileSave.IsHistory = isHistory; + fileSave.Session = + ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => f.SessionName == sessionName); - /// - /// Adds the or update file. - /// - /// A class instance to be added or updated into the database. - /// An instance to a ScintillaTabbedDocument class. - /// if set to true the file is to be considered as a closed/history file. - /// Name of the session the file belongs to. - /// The encoding of the file. - /// A value indicating whether to commit the changes to the - /// database or to the file system cache depending on the setting. - /// A value indicating whether to override existing copy of the file in the file system. - /// A value indicating whether the file contents have been changed. - /// An instance to a modified class. - public static FileSave AddOrUpdateFile(this FileSave fileSave, ScintillaTabbedDocument document, bool isHistory, - string sessionName, Encoding encoding, bool commit, - bool saveToFileSystem, bool contentChanged) - { - fileSave.SetFileContents(fileSave.GetEncoding().GetBytes(document.Scintilla.Text), commit, saveToFileSystem, contentChanged); - fileSave.CurrentCaretPosition = document.Scintilla.CurrentPosition; - fileSave.FilePath = Path.GetDirectoryName(fileSave.FileNameFull); - fileSave.IsHistory = isHistory; - fileSave.Session = - ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => f.SessionName == sessionName); + fileSave.SetEncoding(encoding); - fileSave.SetEncoding(encoding); + ScriptNotepadDbContext.DbContext.SaveChanges(); + return ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Id == fileSave.Id); + } - ScriptNotepadDbContext.DbContext.SaveChanges(); - return ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Id == fileSave.Id); - } + // An instance to a class generated from the class instance. - // An instance to a class generated from the class instance. - - /// - /// Creates a entity from a given document. - /// - /// The document to create a file save from. - /// The encoding of the file save. - /// The file session. - /// if set to true the resulting instance is marked as a history file. - /// An instance to a modified class. - public static FileSave CreateFromTabbedDocument(ScintillaTabbedDocument document, Encoding encoding, - FileSession fileSession, bool isHistory = false) + /// + /// Creates a entity from a given document. + /// + /// The document to create a file save from. + /// The encoding of the file save. + /// The file session. + /// if set to true the resulting instance is marked as a history file. + /// An instance to a modified class. + public static FileSave CreateFromTabbedDocument(ScintillaTabbedDocument document, Encoding encoding, + FileSession fileSession, bool isHistory = false) + { + var fileSave = new FileSave { - var fileSave = new FileSave - { - ExistsInFileSystem = File.Exists(document.FileName), - FileNameFull = document.FileName, - FileName = Path.GetFileName(document.FileName), - FilePath = Path.GetDirectoryName(document.FileName), - FileSystemModified = File.Exists(document.FileName) - ? new FileInfo(document.FileName).LastWriteTime - : DateTime.MinValue, - LexerType = document.LexerType, - VisibilityOrder = (int) document.FileTabButton.Tag, - Session = ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => - f.SessionName == fileSession.SessionName), - IsActive = document.FileTabButton.IsActive, - IsHistory = isHistory, - CurrentCaretPosition = document.Scintilla.CurrentPosition, - UseSpellChecking = true, - EditorZoomPercentage = document.ZoomPercentage, - UseFileSystemOnContents = fileSession.UseFileSystemOnContents, - }; - - fileSave.SetDatabaseModified(DateTime.Now); - - fileSave.SetEncoding(encoding); - - fileSave.SetFileContents(encoding.GetBytes(document.Scintilla.Text), true, false, true); - - ScriptNotepadDbContext.DbContext.FileSaves.Add(fileSave); - ScriptNotepadDbContext.DbContext.SaveChanges(); - return fileSave; - } + ExistsInFileSystem = File.Exists(document.FileName), + FileNameFull = document.FileName, + FileName = Path.GetFileName(document.FileName), + FilePath = Path.GetDirectoryName(document.FileName), + FileSystemModified = File.Exists(document.FileName) + ? new FileInfo(document.FileName).LastWriteTime + : DateTime.MinValue, + LexerType = document.LexerType, + VisibilityOrder = (int) document.FileTabButton.Tag, + Session = ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => + f.SessionName == fileSession.SessionName), + IsActive = document.FileTabButton.IsActive, + IsHistory = isHistory, + CurrentCaretPosition = document.Scintilla.CurrentPosition, + UseSpellChecking = true, + EditorZoomPercentage = document.ZoomPercentage, + UseFileSystemOnContents = fileSession.UseFileSystemOnContents, + }; + + fileSave.SetDatabaseModified(DateTime.Now); + + fileSave.SetEncoding(encoding); + + fileSave.SetFileContents(encoding.GetBytes(document.Scintilla.Text), true, false, true); + + ScriptNotepadDbContext.DbContext.FileSaves.Add(fileSave); + ScriptNotepadDbContext.DbContext.SaveChanges(); + return fileSave; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/ModelHelpers/FileSessionHelper.cs b/ScriptNotepad/Editor/Utility/ModelHelpers/FileSessionHelper.cs index 4732e12a..58572895 100644 --- a/ScriptNotepad/Editor/Utility/ModelHelpers/FileSessionHelper.cs +++ b/ScriptNotepad/Editor/Utility/ModelHelpers/FileSessionHelper.cs @@ -29,46 +29,45 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Entities; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Editor.Utility.ModelHelpers +namespace ScriptNotepad.Editor.Utility.ModelHelpers; + +/// +/// A class to help with entities. +/// Implements the +/// +/// +public class FileSessionHelper: ErrorHandlingBase { /// - /// A class to help with entities. - /// Implements the + /// Deletes the entire session from the database context. /// - /// - public class FileSessionHelper: ErrorHandlingBase + /// The session to delete. + /// true if the operation was successful, false otherwise. + public static bool DeleteEntireSession(FileSession session) { - /// - /// Deletes the entire session from the database context. - /// - /// The session to delete. - /// true if the operation was successful, false otherwise. - public static bool DeleteEntireSession(FileSession session) + try { - try - { - var context = ScriptNotepadDbContext.DbContext; + var context = ScriptNotepadDbContext.DbContext; - context.FileSaves.RemoveRange(context.FileSaves.Where(f => f.Session.SessionName == session.SessionName)); - context.MiscellaneousTextEntries.RemoveRange(context.MiscellaneousTextEntries.Where(f => f.Session.SessionName == session.SessionName)); - context.RecentFiles.RemoveRange(context.RecentFiles.Where(f => f.Session.SessionName == session.SessionName)); + context.FileSaves.RemoveRange(context.FileSaves.Where(f => f.Session.SessionName == session.SessionName)); + context.MiscellaneousTextEntries.RemoveRange(context.MiscellaneousTextEntries.Where(f => f.Session.SessionName == session.SessionName)); + context.RecentFiles.RemoveRange(context.RecentFiles.Where(f => f.Session.SessionName == session.SessionName)); - session = context.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName); + session = context.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName); - if (session != null) - { - context.FileSessions.Remove(session); - } - - context.SaveChanges(); - return true; // success.. - } - catch (Exception ex) + if (session != null) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; // failure.. + context.FileSessions.Remove(session); } + + context.SaveChanges(); + return true; // success.. + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; // failure.. } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/ModelHelpers/MiscellaneousTextEntryHelper.cs b/ScriptNotepad/Editor/Utility/ModelHelpers/MiscellaneousTextEntryHelper.cs index 40670e42..7abb6df6 100644 --- a/ScriptNotepad/Editor/Utility/ModelHelpers/MiscellaneousTextEntryHelper.cs +++ b/ScriptNotepad/Editor/Utility/ModelHelpers/MiscellaneousTextEntryHelper.cs @@ -31,95 +31,94 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Enumerations; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Editor.Utility.ModelHelpers +namespace ScriptNotepad.Editor.Utility.ModelHelpers; + +/// +/// A class to help with entities. +/// Implements the +/// +/// +public class MiscellaneousTextEntryHelper: ErrorHandlingBase { /// - /// A class to help with entities. - /// Implements the + /// Adds an unique miscellaneous text value to the database. /// - /// - public class MiscellaneousTextEntryHelper: ErrorHandlingBase + /// The misc text. + /// Type of the miscellaneous text. + /// The file session. + /// An instance to a if successful, null otherwise. + public static MiscellaneousTextEntry AddUniqueMiscellaneousText(string miscText, + MiscellaneousTextType miscellaneousTextType, FileSession fileSession) { - /// - /// Adds an unique miscellaneous text value to the database. - /// - /// The misc text. - /// Type of the miscellaneous text. - /// The file session. - /// An instance to a if successful, null otherwise. - public static MiscellaneousTextEntry AddUniqueMiscellaneousText(string miscText, - MiscellaneousTextType miscellaneousTextType, FileSession fileSession) + try { - try - { - var context = ScriptNotepadDbContext.DbContext; + var context = ScriptNotepadDbContext.DbContext; - if (!context.MiscellaneousTextEntries.Any(f => + if (!context.MiscellaneousTextEntries.Any(f => f.TextValue == miscText && f.TextType == miscellaneousTextType && f.Session.SessionName == fileSession.SessionName)) + { + var result = new MiscellaneousTextEntry { - var result = new MiscellaneousTextEntry - { - Session = fileSession, - TextType = miscellaneousTextType, - TextValue = miscText - }; + Session = fileSession, + TextType = miscellaneousTextType, + TextValue = miscText, + }; - result = context.MiscellaneousTextEntries.Add(result).Entity; - context.SaveChanges(); - return result; - } - - return context.MiscellaneousTextEntries.FirstOrDefault(f => - f.TextValue == miscText && f.TextType == miscellaneousTextType && - f.Session.SessionName == fileSession.SessionName); // success.. - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return null; // failure.. + result = context.MiscellaneousTextEntries.Add(result).Entity; + context.SaveChanges(); + return result; } + + return context.MiscellaneousTextEntries.FirstOrDefault(f => + f.TextValue == miscText && f.TextType == miscellaneousTextType && + f.Session.SessionName == fileSession.SessionName); // success.. + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return null; // failure.. } + } - /// - /// Deletes the older entries by a given limit to keep. - /// - /// Type of the miscellaneous text. - /// The limit of how many to entries to keep. - /// The file session. - /// true if the operation was successful, false otherwise. - public static bool DeleteOlderEntries(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession) + /// + /// Deletes the older entries by a given limit to keep. + /// + /// Type of the miscellaneous text. + /// The limit of how many to entries to keep. + /// The file session. + /// true if the operation was successful, false otherwise. + public static bool DeleteOlderEntries(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession) + { + try { - try - { - ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.RemoveRange( - ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Where(f => f.Session.SessionName == fileSession.SessionName) - .Except(GetEntriesByLimit(miscellaneousTextType, limit, fileSession))); + ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.RemoveRange( + ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Where(f => f.Session.SessionName == fileSession.SessionName) + .Except(GetEntriesByLimit(miscellaneousTextType, limit, fileSession))); - return true; // success.. - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; // failure.. - } + return true; // success.. } - - /// - /// Gets the entries by a given limit. - /// - /// Type of the miscellaneous text. - /// The limit of how many to entries to get. - /// The file session. - /// System.Collections.Generic.IEnumerable<ScriptNotepad.Database.Entity.Entities.MiscellaneousTextEntry>. - public static IEnumerable GetEntriesByLimit(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession) + catch (Exception ex) { - return ScriptNotepadDbContext.DbContext - .MiscellaneousTextEntries - .Where(f => f.Session.SessionName == fileSession.SessionName && f.TextType == miscellaneousTextType) - .OrderBy(f => f.Added) - .Take(limit); + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; // failure.. } } -} + + /// + /// Gets the entries by a given limit. + /// + /// Type of the miscellaneous text. + /// The limit of how many to entries to get. + /// The file session. + /// System.Collections.Generic.IEnumerable<ScriptNotepad.Database.Entity.Entities.MiscellaneousTextEntry>. + public static IEnumerable GetEntriesByLimit(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession) + { + return ScriptNotepadDbContext.DbContext + .MiscellaneousTextEntries + .Where(f => f.Session.SessionName == fileSession.SessionName && f.TextType == miscellaneousTextType) + .OrderBy(f => f.Added) + .Take(limit); + } +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/ModelHelpers/PluginHelper.cs b/ScriptNotepad/Editor/Utility/ModelHelpers/PluginHelper.cs index ba3ef352..5ae07809 100644 --- a/ScriptNotepad/Editor/Utility/ModelHelpers/PluginHelper.cs +++ b/ScriptNotepad/Editor/Utility/ModelHelpers/PluginHelper.cs @@ -29,147 +29,146 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using ScriptNotepadPluginBase.PluginTemplateInterface; -namespace ScriptNotepad.Editor.Utility.ModelHelpers +namespace ScriptNotepad.Editor.Utility.ModelHelpers; + +/// +/// A class to help with entities. +/// Implements the +/// +/// +public class PluginHelper: ErrorHandlingBase { /// - /// A class to help with entities. - /// Implements the + /// Gets a version string from a given . /// - /// - public class PluginHelper: ErrorHandlingBase + /// The assembly to set the version from. + internal static string VersionStringFromAssembly(Assembly assembly) { - /// - /// Gets a version string from a given . - /// - /// The assembly to set the version from. - internal static string VersionStringFromAssembly(Assembly assembly) + try { - try - { - // return the version from the given assembly.. - return assembly.GetName().Version.ToString(); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + // return the version from the given assembly.. + return assembly.GetName().Version.ToString(); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); - // return a default value.. - return "1.0.0.0"; - } + // return a default value.. + return "1.0.0.0"; } + } - /// - /// Creates an instance of a class to be inserted into the database. - /// - /// The assembly of the plug-in. - /// The initialized plug-in. - /// The full file name of the plug-in assembly. - /// A class instance based on the given arguments. - public static Plugin FromPlugin(Assembly assembly, IScriptNotepadPlugin plugin, string fileNameFull) + /// + /// Creates an instance of a class to be inserted into the database. + /// + /// The assembly of the plug-in. + /// The initialized plug-in. + /// The full file name of the plug-in assembly. + /// A class instance based on the given arguments. + public static Plugin FromPlugin(Assembly assembly, IScriptNotepadPlugin plugin, string fileNameFull) + { + try { - try - { - // create a result based on the given parameters.. - var result = new Plugin - { - FileNameFull = fileNameFull, - FileName = Path.GetFileName(fileNameFull), - FilePath = Path.GetDirectoryName(fileNameFull), - PluginName = plugin.PluginName, - PluginDescription = plugin.PluginDescription, - IsActive = true, - PluginInstalled = DateTime.Now, - PluginVersion = VersionStringFromAssembly(assembly), - }; - - // set the version for the plug-in.. - AssemblyVersion.SetPluginUpdated(result, assembly); - - // return the result.. - return result; - } - catch (Exception ex) + // create a result based on the given parameters.. + var result = new Plugin { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return null; - } + FileNameFull = fileNameFull, + FileName = Path.GetFileName(fileNameFull), + FilePath = Path.GetDirectoryName(fileNameFull), + PluginName = plugin.PluginName, + PluginDescription = plugin.PluginDescription, + IsActive = true, + PluginInstalled = DateTime.Now, + PluginVersion = VersionStringFromAssembly(assembly), + }; + + // set the version for the plug-in.. + AssemblyVersion.SetPluginUpdated(result, assembly); + + // return the result.. + return result; } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return null; + } + } - /// - /// Updates the plug-in entry data. - /// - /// The plug-in entry . - /// The assembly of the plug-in. - /// The initialized plug-in. - /// The full file name of the plug-in assembly. - /// An updated class instance based on the given arguments. - public static Plugin UpdateFromPlugin(Plugin pluginEntry, Assembly assembly, IScriptNotepadPlugin plugin, string fileNameFull) + /// + /// Updates the plug-in entry data. + /// + /// The plug-in entry . + /// The assembly of the plug-in. + /// The initialized plug-in. + /// The full file name of the plug-in assembly. + /// An updated class instance based on the given arguments. + public static Plugin UpdateFromPlugin(Plugin pluginEntry, Assembly assembly, IScriptNotepadPlugin plugin, string fileNameFull) + { + try { - try - { - pluginEntry.FileNameFull = fileNameFull; - pluginEntry.FileName = Path.GetFileName(fileNameFull); - pluginEntry.FilePath = Path.GetDirectoryName(fileNameFull); - pluginEntry.PluginName = plugin.PluginName; - pluginEntry.PluginDescription = plugin.PluginDescription; + pluginEntry.FileNameFull = fileNameFull; + pluginEntry.FileName = Path.GetFileName(fileNameFull); + pluginEntry.FilePath = Path.GetDirectoryName(fileNameFull); + pluginEntry.PluginName = plugin.PluginName; + pluginEntry.PluginDescription = plugin.PluginDescription; - // set the version for the plug-in.. - AssemblyVersion.SetPluginUpdated(pluginEntry, assembly); + // set the version for the plug-in.. + AssemblyVersion.SetPluginUpdated(pluginEntry, assembly); - return pluginEntry; - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return pluginEntry; - } + return pluginEntry; + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return pluginEntry; } + } - /// - /// Return data acquired from an assembly in case a plug-in failed to initialize. - /// - /// The assembly of the plug-in. - /// The full file name of the plug-in assembly. - /// A class instance based on the given arguments. - public static Plugin InvalidPlugin(Assembly assembly, string fileNameFull) + /// + /// Return data acquired from an assembly in case a plug-in failed to initialize. + /// + /// The assembly of the plug-in. + /// The full file name of the plug-in assembly. + /// A class instance based on the given arguments. + public static Plugin InvalidPlugin(Assembly assembly, string fileNameFull) + { + try { - try + string description = string.Empty; + if (assembly != null) { - string description = string.Empty; - if (assembly != null) - { - description = assembly.FullName; - } - - // create a result based on the given parameters.. - var result = new Plugin - { - FileNameFull = fileNameFull, - FileName = Path.GetFileName(fileNameFull), - FilePath = Path.GetDirectoryName(fileNameFull), - PluginName = "Unknown", - PluginDescription = description, - IsActive = false, - PluginInstalled = DateTime.Now, - LoadFailures = 1, - PluginVersion = VersionStringFromAssembly(assembly), - }; - - // set the version for the plug-in.. - AssemblyVersion.SetPluginUpdated(result, assembly); - - // return the result.. - return result; + description = assembly.FullName; } - catch (Exception ex) + + // create a result based on the given parameters.. + var result = new Plugin { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return null; - } + FileNameFull = fileNameFull, + FileName = Path.GetFileName(fileNameFull), + FilePath = Path.GetDirectoryName(fileNameFull), + PluginName = "Unknown", + PluginDescription = description, + IsActive = false, + PluginInstalled = DateTime.Now, + LoadFailures = 1, + PluginVersion = VersionStringFromAssembly(assembly), + }; + + // set the version for the plug-in.. + AssemblyVersion.SetPluginUpdated(result, assembly); + + // return the result.. + return result; + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return null; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Editor/Utility/ModelHelpers/SearchAndReplaceHistoryHelper.cs b/ScriptNotepad/Editor/Utility/ModelHelpers/SearchAndReplaceHistoryHelper.cs index bf6110b2..3176f796 100644 --- a/ScriptNotepad/Editor/Utility/ModelHelpers/SearchAndReplaceHistoryHelper.cs +++ b/ScriptNotepad/Editor/Utility/ModelHelpers/SearchAndReplaceHistoryHelper.cs @@ -31,117 +31,116 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Enumerations; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.Editor.Utility.ModelHelpers +namespace ScriptNotepad.Editor.Utility.ModelHelpers; + +/// +/// A class to help with entities. +/// Implements the +/// +/// +public class SearchAndReplaceHistoryHelper: ErrorHandlingBase { /// - /// A class to help with entities. - /// Implements the + /// Deletes the older entities with a given limit. /// - /// - public class SearchAndReplaceHistoryHelper: ErrorHandlingBase + /// Type of the search and replace search. + /// Type of the search and replace. + /// The limit of how many to entities to keep. + /// The file session. + /// true if the operation was successful, false otherwise. + public static bool DeleteOlderEntries(SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit, + FileSession fileSession) { - /// - /// Deletes the older entities with a given limit. - /// - /// Type of the search and replace search. - /// Type of the search and replace. - /// The limit of how many to entities to keep. - /// The file session. - /// true if the operation was successful, false otherwise. - public static bool DeleteOlderEntries(SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit, - FileSession fileSession) + try { - try - { - ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.RemoveRange( - ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.Where(f => - f.Session.SessionName == fileSession.SessionName && - f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && - f.SearchAndReplaceType == searchAndReplaceType) - .Except(GetEntriesByLimit(searchAndReplaceSearchType, searchAndReplaceType, limit, - fileSession))); + ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.RemoveRange( + ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.Where(f => + f.Session.SessionName == fileSession.SessionName && + f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && + f.SearchAndReplaceType == searchAndReplaceType) + .Except(GetEntriesByLimit(searchAndReplaceSearchType, searchAndReplaceType, limit, + fileSession))); - return true; // success.. - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; // failure.. - } + return true; // success.. } - - /// - /// Gets the entities by a given limit. - /// - /// Type of the search and replace search. - /// Type of the search and replace. - /// The limit of how many to entities to get. - /// The file session. - /// IEnumerable<SearchAndReplaceHistory>. - public static IEnumerable GetEntriesByLimit( - SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit, - FileSession fileSession) + catch (Exception ex) { - return ScriptNotepadDbContext.DbContext - .SearchAndReplaceHistories - .Where(f => f.Session.SessionName == fileSession.SessionName && - f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && - f.SearchAndReplaceType == searchAndReplaceType).OrderBy(f => f.Added) - .Take(limit); + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; // failure.. } + } - /// - /// Adds or updates a entity. - /// - /// The text used for searching or replacing. - /// Type of the search and replace search. - /// Type of the search and replace. - /// if set to true the search or replace is case sensitive. - /// The file session. - /// SearchAndReplaceHistory. - public static SearchAndReplaceHistory AddOrUpdateAndReplaceHistory(string text, - SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, - bool caseSensitive, FileSession fileSession) + /// + /// Gets the entities by a given limit. + /// + /// Type of the search and replace search. + /// Type of the search and replace. + /// The limit of how many to entities to get. + /// The file session. + /// IEnumerable<SearchAndReplaceHistory>. + public static IEnumerable GetEntriesByLimit( + SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit, + FileSession fileSession) + { + return ScriptNotepadDbContext.DbContext + .SearchAndReplaceHistories + .Where(f => f.Session.SessionName == fileSession.SessionName && + f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && + f.SearchAndReplaceType == searchAndReplaceType).OrderBy(f => f.Added) + .Take(limit); + } + + /// + /// Adds or updates a entity. + /// + /// The text used for searching or replacing. + /// Type of the search and replace search. + /// Type of the search and replace. + /// if set to true the search or replace is case sensitive. + /// The file session. + /// SearchAndReplaceHistory. + public static SearchAndReplaceHistory AddOrUpdateAndReplaceHistory(string text, + SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, + bool caseSensitive, FileSession fileSession) + { + try { - try - { - var context = ScriptNotepadDbContext.DbContext; + var context = ScriptNotepadDbContext.DbContext; - if (!context.SearchAndReplaceHistories.Any(f => + if (!context.SearchAndReplaceHistories.Any(f => f.SearchOrReplaceText == text && f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && f.SearchAndReplaceType == searchAndReplaceType && f.CaseSensitive == caseSensitive && f.Session.SessionName == fileSession.SessionName)) + { + var result = new SearchAndReplaceHistory { - var result = new SearchAndReplaceHistory - { - SearchOrReplaceText = text, - SearchAndReplaceSearchType = searchAndReplaceSearchType, - SearchAndReplaceType = searchAndReplaceType, - CaseSensitive = caseSensitive, - Session = fileSession, - }; - - result = context.SearchAndReplaceHistories.Add(result).Entity; - context.SaveChanges(); - return result; - } + SearchOrReplaceText = text, + SearchAndReplaceSearchType = searchAndReplaceSearchType, + SearchAndReplaceType = searchAndReplaceType, + CaseSensitive = caseSensitive, + Session = fileSession, + }; - return context.SearchAndReplaceHistories.FirstOrDefault(f => - f.SearchOrReplaceText == text && - f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && - f.SearchAndReplaceType == searchAndReplaceType && - f.CaseSensitive == caseSensitive && - f.Session.SessionName == fileSession.SessionName); // success.. - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return null; // failure.. + result = context.SearchAndReplaceHistories.Add(result).Entity; + context.SaveChanges(); + return result; } + + return context.SearchAndReplaceHistories.FirstOrDefault(f => + f.SearchOrReplaceText == text && + f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) && + f.SearchAndReplaceType == searchAndReplaceType && + f.CaseSensitive == caseSensitive && + f.Session.SessionName == fileSession.SessionName); // success.. + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return null; // failure.. } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/FormHexEdit.cs b/ScriptNotepad/FormHexEdit.cs index 2bfc0842..d990a491 100644 --- a/ScriptNotepad/FormHexEdit.cs +++ b/ScriptNotepad/FormHexEdit.cs @@ -30,55 +30,54 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.PosLib; using WpfHexaEditor.Core; -namespace ScriptNotepad +namespace ScriptNotepad; + +/// +/// A hex editor for binary files. +/// +/// +public partial class FormHexEdit : DBLangEngineWinforms { /// - /// A hex editor for binary files. + /// Initializes a new instance of the class. /// - /// - public partial class FormHexEdit : DBLangEngineWinforms + public FormHexEdit() { - /// - /// Initializes a new instance of the class. - /// - public FormHexEdit() - { - // Add this form to be positioned.. - PositionForms.Add(this, PositionCore.SizeChangeMode.MoveTopLeft); + // Add this form to be positioned.. + PositionForms.Add(this, PositionCore.SizeChangeMode.MoveTopLeft); - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } - - hexEditor.ForegroundSecondColor = Brushes.Blue; + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - private void toolStripButton1_Click(object sender, EventArgs e) - { - var fileDialog = new OpenFileDialog(); + hexEditor.ForegroundSecondColor = Brushes.Blue; + } - if (fileDialog.ShowDialog() == DialogResult.OK && File.Exists(fileDialog.FileName)) - hexEditor.FileName = fileDialog.FileName; - } + private void toolStripButton1_Click(object sender, EventArgs e) + { + var fileDialog = new OpenFileDialog(); - private void toolStripButton2_Click(object sender, EventArgs e) - { - var fileDialog = new OpenFileDialog(); + if (fileDialog.ShowDialog() == DialogResult.OK && File.Exists(fileDialog.FileName)) + hexEditor.FileName = fileDialog.FileName; + } - if (fileDialog.ShowDialog() == DialogResult.OK && File.Exists(fileDialog.FileName)) - { - hexEditor.LoadTblFile(fileDialog.FileName); - hexEditor.TypeOfCharacterTable = CharacterTableType.TblFile; - } + private void toolStripButton2_Click(object sender, EventArgs e) + { + var fileDialog = new OpenFileDialog(); + + if (fileDialog.ShowDialog() == DialogResult.OK && File.Exists(fileDialog.FileName)) + { + hexEditor.LoadTblFile(fileDialog.FileName); + hexEditor.TypeOfCharacterTable = CharacterTableType.TblFile; } } } \ No newline at end of file diff --git a/ScriptNotepad/FormMain.cs b/ScriptNotepad/FormMain.cs index 8eed8ae8..84bfb01f 100644 --- a/ScriptNotepad/FormMain.cs +++ b/ScriptNotepad/FormMain.cs @@ -102,574 +102,634 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #endregion -namespace ScriptNotepad +namespace ScriptNotepad; + +/// +/// The main form of this software. +/// Implements the +/// +/// +public partial class FormMain : DBLangEngineWinforms { + #region MassiveConstructor /// - /// The main form of this software. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormMain : DBLangEngineWinforms + /// Thrown if the database script isn't successfully run. + public FormMain() { - #region MassiveConstructor - /// - /// Initializes a new instance of the class. - /// - /// Thrown if the database script isn't successfully run. - public FormMain() - { - // Add this form to be positioned.. - PositionForms.Add(this); - - MessageBoxBase.DefaultOwner = this; + // Add this form to be positioned.. + PositionForms.Add(this); - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + MessageBoxBase.DefaultOwner = this; - InitializeComponent(); + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + InitializeComponent(); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - Instance = this; + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // register the code page encodings.. - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + Instance = this; - // this is required.. - FileSessionHelper.ApplicationDataDirectory = Path.Combine(DBLangEngine.DataDir, "Cache"); - if (!Directory.Exists(FileSessionHelper.ApplicationDataDirectory)) - { - Directory.CreateDirectory(FileSessionHelper.ApplicationDataDirectory); - } + // register the code page encodings.. + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // this is required.. + FileSessionHelper.ApplicationDataDirectory = Path.Combine(DBLangEngine.DataDir, "Cache"); + if (!Directory.Exists(FileSessionHelper.ApplicationDataDirectory)) + { + Directory.CreateDirectory(FileSessionHelper.ApplicationDataDirectory); + } - // subscribe to the session ended event to save the documents without asking stupid questions.. - SystemEvents.SessionEnded += SystemEvents_SessionEnded; + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - // create an IPC server at localhost, the port was randomized in the development phase.. - IpcServer = new RpcSelfHost(50670); + // subscribe to the session ended event to save the documents without asking stupid questions.. + SystemEvents.SessionEnded += SystemEvents_SessionEnded; - // subscribe to the IPC event if the application receives a message from another instance of this application.. - IpcServer.MessageReceived += RemoteMessage_MessageReceived; + // create an IPC server at localhost, the port was randomized in the development phase.. + IpcServer = new RpcSelfHost(50670); - var databaseFile = DBLangEngine.DataDir + "ScriptNotepadEntityCore.sqlite"; + // subscribe to the IPC event if the application receives a message from another instance of this application.. + IpcServer.MessageReceived += RemoteMessage_MessageReceived; - var connectionString = $"Data Source={databaseFile}"; + var databaseFile = DBLangEngine.DataDir + "ScriptNotepadEntityCore.sqlite"; - base.Text += - (ProcessElevation.IsElevated ? " (" + - DBLangEngine.GetMessage("msgProcessIsElevated", "Administrator|A message indicating that a process is elevated.") + ")" : string.Empty); + var connectionString = $"Data Source={databaseFile}"; - ExecuteDatabaseMigrate.DefaultSessionName = DBLangEngine.GetStatMessage("msgDefaultSessionName", - "Default|A name of the default session for the documents"); + base.Text += + (ProcessElevation.IsElevated ? " (" + + DBLangEngine.GetMessage("msgProcessIsElevated", "Administrator|A message indicating that a process is elevated.") + ")" : string.Empty); - try - { - // run the database migrations (FluentMigrator).. - ExecuteDatabaseMigrate.Migrate(connectionString); - } - catch (Exception ex) - { - // ..the database already exists, so do create and update the VersionInfo table.. - CheckFluentMigrator.MarkMigration(connectionString); - ExceptionLogger.LogError(ex); - } + ExecuteDatabaseMigrate.DefaultSessionName = DBLangEngine.GetStatMessage("msgDefaultSessionName", + "Default|A name of the default session for the documents"); - // initialize the ScriptNotepadDbContext class instance.. - ScriptNotepadDbContext.InitializeDbContext(connectionString); + try + { + // run the database migrations (FluentMigrator).. + ExecuteDatabaseMigrate.Migrate(connectionString); + } + catch (Exception ex) + { + // ..the database already exists, so do create and update the VersionInfo table.. + CheckFluentMigrator.MarkMigration(connectionString); + ExceptionLogger.LogError(ex); + } - MigrateDatabaseEfCore(); // migrate to Entity Framework Core database.. + // initialize the ScriptNotepadDbContext class instance.. + ScriptNotepadDbContext.InitializeDbContext(connectionString); - // load the external spell check library if defined.. - ExternalSpellChecker.Load(); + MigrateDatabaseEfCore(); // migrate to Entity Framework Core database.. - // localize the open file dialog.. - StaticLocalizeFileDialog.InitFileDialog(odAnyFile); + // load the external spell check library if defined.. + ExternalSpellChecker.Load(); - // localize the save file dialog.. - StaticLocalizeFileDialog.InitFileDialog(sdAnyFile); + // localize the open file dialog.. + StaticLocalizeFileDialog.InitFileDialog(odAnyFile); - // localize the save HTML dialog.. - StaticLocalizeFileDialog.InitHTMLFileDialog(sdHTML); + // localize the save file dialog.. + StaticLocalizeFileDialog.InitFileDialog(sdAnyFile); - // set the value whether to use auto-ellipsis on long URLs with the ScintillaUrlDetect.. - ScintillaUrlDetect.AutoEllipsisUrlLength = FormSettings.Settings.UrlUseAutoEllipsis - ? FormSettings.Settings.UrlMaxLengthBeforeEllipsis - : -1; + // localize the save HTML dialog.. + StaticLocalizeFileDialog.InitHTMLFileDialog(sdHTML); - // set the URL styling to use threads.. - ScintillaUrlDetect.UseThreadsOnUrlStyling = true; + // set the value whether to use auto-ellipsis on long URLs with the ScintillaUrlDetect.. + ScintillaUrlDetect.AutoEllipsisUrlLength = FormSettings.Settings.UrlUseAutoEllipsis + ? FormSettings.Settings.UrlMaxLengthBeforeEllipsis + : -1; - // localize the open and save file dialog titles.. - sdAnyFile.Title = DBLangEngine.GetMessage("msgSaveFileAs", "Save As|A title for a save file as dialog"); - odAnyFile.Title = DBLangEngine.GetMessage("msgOpenFile", "Open|A title for a open file dialog"); + // set the URL styling to use threads.. + ScintillaUrlDetect.UseThreadsOnUrlStyling = true; - // localize the dwell tool tips on used by the ScintillaUrlDetect class library.. - ScintillaUrlDetect.DwellToolTipTextUrl = DBLangEngine.GetMessage("msgUrlDetectToolTipOpenHyperlink", - "Use CTRL + Click to follow the link: {0}|A message for the URL detect library tool tip to open a hyperlink."); + // localize the open and save file dialog titles.. + sdAnyFile.Title = DBLangEngine.GetMessage("msgSaveFileAs", "Save As|A title for a save file as dialog"); + odAnyFile.Title = DBLangEngine.GetMessage("msgOpenFile", "Open|A title for a open file dialog"); - ScintillaUrlDetect.DwellToolTipTextMailTo = DBLangEngine.GetMessage("msgUrlDetectToolTipOpenMailToLink", - "Use CTRL + Click to sent email to: {0}|A message for the URL detect library tool tip to open a email program for a mailto link."); + // localize the dwell tool tips on used by the ScintillaUrlDetect class library.. + ScintillaUrlDetect.DwellToolTipTextUrl = DBLangEngine.GetMessage("msgUrlDetectToolTipOpenHyperlink", + "Use CTRL + Click to follow the link: {0}|A message for the URL detect library tool tip to open a hyperlink."); - // initialize the helper class for the status strip's labels.. - StatusStripTexts.InitLabels(ssLbLineColumn, ssLbLinesColumnSelection, ssLbLDocLinesSize, - ssLbLineEnding, ssLbEncoding, ssLbSessionName, ssLbInsertOverride, sslbZoom, sslbTabs); + ScintillaUrlDetect.DwellToolTipTextMailTo = DBLangEngine.GetMessage("msgUrlDetectToolTipOpenMailToLink", + "Use CTRL + Click to sent email to: {0}|A message for the URL detect library tool tip to open a email program for a mailto link."); - // get the current file session.. - currentSession = FormSettings.Settings.CurrentSessionEntity; + // initialize the helper class for the status strip's labels.. + StatusStripTexts.InitLabels(ssLbLineColumn, ssLbLinesColumnSelection, ssLbLDocLinesSize, + ssLbLineEnding, ssLbEncoding, ssLbSessionName, ssLbInsertOverride, sslbZoom, sslbTabs); - // set the status strip label's to indicate that there is no active document.. - StatusStripTexts.SetEmptyTexts(CurrentSession.SessionName); + // get the current file session.. + currentSession = FormSettings.Settings.CurrentSessionEntity; - // localize some other class properties, etc.. - FormLocalizationHelper.LocalizeMisc(); + // set the status strip label's to indicate that there is no active document.. + StatusStripTexts.SetEmptyTexts(CurrentSession.SessionName); - // get the font size and family from the settings.. - FontFamilyName = FormSettings.Settings.EditorFontName; - FontSize = FormSettings.Settings.EditorFontSize; + // localize some other class properties, etc.. + FormLocalizationHelper.LocalizeMisc(); - // localize the thread if set in the settings.. - if (FormSettings.Settings.LocalizeThread) - { - Thread.CurrentThread.CurrentCulture = DBLangEngine.UseCulture; - Thread.CurrentThread.CurrentUICulture = DBLangEngine.UseCulture; - } + // get the font size and family from the settings.. + FontFamilyName = FormSettings.Settings.EditorFontName; + FontSize = FormSettings.Settings.EditorFontSize; - // localize the context menu before any of the context menus are build to the Scintilla controls.. - ScintillaContextMenu.LocalizeTexts(); + // localize the thread if set in the settings.. + if (FormSettings.Settings.LocalizeThread) + { + Thread.CurrentThread.CurrentCulture = DBLangEngine.UseCulture; + Thread.CurrentThread.CurrentUICulture = DBLangEngine.UseCulture; + } - // create a programming language selection menu.. - ProgrammingLanguageHelper = new ProgrammingLanguageHelper(mnuProgrammingLanguage, - FormSettings.Settings.CategorizeStartCharacterProgrammingLanguage); + // localize the context menu before any of the context menus are build to the Scintilla controls.. + ScintillaContextMenu.LocalizeTexts(); - ProgrammingLanguageHelper.LanguageMenuClick += ProgrammingLanguageHelper_LanguageMenuClick; + // create a programming language selection menu.. + ProgrammingLanguageHelper = new ProgrammingLanguageHelper(mnuProgrammingLanguage, + FormSettings.Settings.CategorizeStartCharacterProgrammingLanguage); - // get the brace highlight colors from the settings.. - sttcMain.UseBraceHighlight = FormSettings.Settings.HighlightBraces; - sttcMain.ColorBraceHighlightForeground = FormSettings.Settings.BraceHighlightForegroundColor; - sttcMain.ColorBraceHighlightBackground = FormSettings.Settings.BraceHighlightBackgroundColor; - sttcMain.ColorBraceHighlightBad = FormSettings.Settings.BraceBadHighlightForegroundColor; - // END::get the brace highlight colors from the settings.. + ProgrammingLanguageHelper.LanguageMenuClick += ProgrammingLanguageHelper_LanguageMenuClick; - // load the recent documents which were saved during the program close.. - LoadDocumentsFromDatabase(CurrentSession.SessionName); + // get the brace highlight colors from the settings.. + sttcMain.UseBraceHighlight = FormSettings.Settings.HighlightBraces; + sttcMain.ColorBraceHighlightForeground = FormSettings.Settings.BraceHighlightForegroundColor; + sttcMain.ColorBraceHighlightBackground = FormSettings.Settings.BraceHighlightBackgroundColor; + sttcMain.ColorBraceHighlightBad = FormSettings.Settings.BraceBadHighlightForegroundColor; + // END::get the brace highlight colors from the settings.. - CharacterSetMenuBuilder.CreateCharacterSetMenu(mnuCharSets, false, "convert_encoding"); - CharacterSetMenuBuilder.EncodingMenuClicked += CharacterSetMenuBuilder_EncodingMenuClicked; + // load the recent documents which were saved during the program close.. + LoadDocumentsFromDatabase(CurrentSession.SessionName); - SessionMenuBuilder.SessionMenuClicked += SessionMenuBuilder_SessionMenuClicked; - SessionMenuBuilder.CreateSessionMenu(mnuSession, CurrentSession); + CharacterSetMenuBuilder.CreateCharacterSetMenu(mnuCharSets, false, "convert_encoding"); + CharacterSetMenuBuilder.EncodingMenuClicked += CharacterSetMenuBuilder_EncodingMenuClicked; - // enable the test menu only when debugging.. - mnuTest.Visible = Debugger.IsAttached; + SessionMenuBuilder.SessionMenuClicked += SessionMenuBuilder_SessionMenuClicked; + SessionMenuBuilder.CreateSessionMenu(mnuSession, CurrentSession); - // localize the recent files open all files text.. - RecentFilesMenuBuilder.MenuOpenAllRecentText = - DBLangEngine.GetMessage("msgOpenAllRecentFiles", "Open all recent files...|A message in the recent files menu to open all the recent files"); + // enable the test menu only when debugging.. + mnuTest.Visible = Debugger.IsAttached; - // create a menu for recent files.. - RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); + // localize the recent files open all files text.. + RecentFilesMenuBuilder.MenuOpenAllRecentText = + DBLangEngine.GetMessage("msgOpenAllRecentFiles", "Open all recent files...|A message in the recent files menu to open all the recent files"); - // subscribe the click event for the recent file menu items.. - RecentFilesMenuBuilder.RecentFileMenuClicked += RecentFilesMenuBuilder_RecentFileMenuClicked; + // create a menu for recent files.. + RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); - // set the current session name to the status strip.. - StatusStripTexts.SetSessionName(CurrentSession.SessionName); + // subscribe the click event for the recent file menu items.. + RecentFilesMenuBuilder.RecentFileMenuClicked += RecentFilesMenuBuilder_RecentFileMenuClicked; - // subscribe the RequestDocuments event of the search and replace dialog.. - FormSearchAndReplace.Instance.RequestDocuments += InstanceRequestDocuments; + // set the current session name to the status strip.. + StatusStripTexts.SetSessionName(CurrentSession.SessionName); - // set the flag to reset the search area as the functionality is incomplete as of yet.. - FormSearchAndReplace.ResetSearchArea = false; // TODO::Make this a setting.. + // subscribe the RequestDocuments event of the search and replace dialog.. + FormSearchAndReplace.Instance.RequestDocuments += InstanceRequestDocuments; - // the user is either logging of from the system or is shutting down the system.. - SystemEvents.SessionEnding += SystemEvents_SessionEnding; + // set the flag to reset the search area as the functionality is incomplete as of yet.. + FormSearchAndReplace.ResetSearchArea = false; // TODO::Make this a setting.. - // subscribe to the event when a search result is clicked from the FormSearchResultTree form.. - FormSearchResultTree.SearchResultSelected += FormSearchResultTreeSearchResultSelected; + // the user is either logging of from the system or is shutting down the system.. + SystemEvents.SessionEnding += SystemEvents_SessionEnding; - // subscribe to events which will occur with the FormSearchResultTree instance docking.. - FormSearchResultTree.RequestDockMainForm += FormSearchResultTree_RequestDockMainForm; - FormSearchResultTree.RequestDockReleaseMainForm += FormSearchResultTree_RequestDockReleaseMainForm; + // subscribe to the event when a search result is clicked from the FormSearchResultTree form.. + FormSearchResultTree.SearchResultSelected += FormSearchResultTreeSearchResultSelected; - // localize the new file name.. - sttcMain.NewFilenameStart = - DBLangEngine.GetMessage("msgNewFileStart", "new |A starting text of how a new document should be named"); + // subscribe to events which will occur with the FormSearchResultTree instance docking.. + FormSearchResultTree.RequestDockMainForm += FormSearchResultTree_RequestDockMainForm; + FormSearchResultTree.RequestDockReleaseMainForm += FormSearchResultTree_RequestDockReleaseMainForm; - // create a dynamic action for the class exception logging.. - AssignExceptionReportingActions(); + // localize the new file name.. + sttcMain.NewFilenameStart = + DBLangEngine.GetMessage("msgNewFileStart", "new |A starting text of how a new document should be named"); - // create the default directory for the plug-ins if it doesn't exist yet.. - FormSettings.CreateDefaultPluginDirectory(); - // create the default directory for custom dictionaries if it doesn't exist yet.. - FormSettings.CreateDefaultCustomDictionaryDirectory(); + // create a dynamic action for the class exception logging.. + AssignExceptionReportingActions(); - // localize the about "box".. - VersionCheck.AboutDialogDisplayDownloadDialog = true; // I want to make it fancy.. - VersionCheck.OverrideCultureString = FormSettings.Settings.Culture.Name; // I want it localized.. - VersionCheck.CacheUpdateHistory = true; // if the user wishes to refer to some change in the history of the software.. + // create the default directory for the plug-ins if it doesn't exist yet.. + FormSettings.CreateDefaultPluginDirectory(); + // create the default directory for custom dictionaries if it doesn't exist yet.. + FormSettings.CreateDefaultCustomDictionaryDirectory(); - VersionCheck.OverrideCultureString = FormSettings.Settings.Culture.Name; + // localize the about "box".. + VersionCheck.AboutDialogDisplayDownloadDialog = true; // I want to make it fancy.. + VersionCheck.OverrideCultureString = FormSettings.Settings.Culture.Name; // I want it localized.. + VersionCheck.CacheUpdateHistory = true; // if the user wishes to refer to some change in the history of the software.. - // initialize the plug-in assemblies.. - InitializePlugins(); + VersionCheck.OverrideCultureString = FormSettings.Settings.Culture.Name; - // set the spell check timer interval.. - tmSpellCheck.Interval = FormSettings.Settings.EditorSpellCheckInactivity; + // initialize the plug-in assemblies.. + InitializePlugins(); - // enable the spell check timer.. - tmSpellCheck.Enabled = true; + // set the spell check timer interval.. + tmSpellCheck.Interval = FormSettings.Settings.EditorSpellCheckInactivity; - // enable the GUI timer.. - tmGUI.Enabled = true; + // enable the spell check timer.. + tmSpellCheck.Enabled = true; - // set the code indentation value from the settings.. - sttcMain.UseCodeIndenting = FormSettings.Settings.EditorUseCodeIndentation; + // enable the GUI timer.. + tmGUI.Enabled = true; - // set the tab width value from the settings.. - sttcMain.TabWidth = FormSettings.Settings.EditorTabWidth; + // set the code indentation value from the settings.. + sttcMain.UseCodeIndenting = FormSettings.Settings.EditorUseCodeIndentation; - // create a menu for open forms within the application.. - WinFormsFormMenuBuilder = new WinFormsFormMenuBuilder(mnuWindow); + // set the tab width value from the settings.. + sttcMain.TabWidth = FormSettings.Settings.EditorTabWidth; - // create a menu for the open tabs.. - TabMenuBuilder = new TabMenuBuilder(mnuTab, sttcMain); + // create a menu for open forms within the application.. + WinFormsFormMenuBuilder = new WinFormsFormMenuBuilder(mnuWindow); - // set the value whether to use individual zoom for the open document(s).. - sttcMain.ZoomSynchronization = !FormSettings.Settings.EditorIndividualZoom; + // create a menu for the open tabs.. + TabMenuBuilder = new TabMenuBuilder(mnuTab, sttcMain); - // this flag can suspend some events from taking place before - // the constructor has finished.. - ConstructorFinished = true; + // set the value whether to use individual zoom for the open document(s).. + sttcMain.ZoomSynchronization = !FormSettings.Settings.EditorIndividualZoom; - // set the default encoding of the DetectEncoding class.. - DetectEncoding.FallBackEncoding = Encoding.Default; + // this flag can suspend some events from taking place before + // the constructor has finished.. + ConstructorFinished = true; - // set the state of the auto-save.. - tmAutoSave.Interval = - (int) TimeSpan.FromMinutes(FormSettings.Settings.ProgramAutoSaveInterval).TotalMilliseconds; - tmAutoSave.Enabled = FormSettings.Settings.ProgramAutoSave; + // set the default encoding of the DetectEncoding class.. + DetectEncoding.FallBackEncoding = Encoding.Default; - // subscribe to an event which is raised upon application activation.. - ApplicationDeactivated += FormMain_ApplicationDeactivated; - ApplicationActivated += FormMain_ApplicationActivated; + // set the state of the auto-save.. + tmAutoSave.Interval = + (int) TimeSpan.FromMinutes(FormSettings.Settings.ProgramAutoSaveInterval).TotalMilliseconds; + tmAutoSave.Enabled = FormSettings.Settings.ProgramAutoSave; - // get the case-sensitivity value from the settings.. - mnuCaseSensitive.Checked = FormSettings.Settings.TextUpperCaseComparison; + // subscribe to an event which is raised upon application activation.. + ApplicationDeactivated += FormMain_ApplicationDeactivated; + ApplicationActivated += FormMain_ApplicationActivated; - // TODO::Take this into use.. - var boxStackContainer = new ToolStripMessageBoxExpandStack - { - Text = DBLangEngine.GetMessage("msgOpenDialogs", - "Open dialogs|A message describing a dropdown control containing message dialog boxes.") - }; - BoxStack = boxStackContainer.MessageBoxExpandStack; - tsMain.Items.Add(boxStackContainer); - BoxStack.Visible = false; + // get the case-sensitivity value from the settings.. + mnuCaseSensitive.Checked = FormSettings.Settings.TextUpperCaseComparison; - // populate the text menu call backs to the run snippet dialog.. - PopulateTextMenuCallBacks(); + // TODO::Take this into use.. + var boxStackContainer = new ToolStripMessageBoxExpandStack + { + Text = DBLangEngine.GetMessage("msgOpenDialogs", + "Open dialogs|A message describing a dropdown control containing message dialog boxes."), + }; + BoxStack = boxStackContainer.MessageBoxExpandStack; + tsMain.Items.Add(boxStackContainer); + BoxStack.Visible = false; - if (FormSettings.Settings.ShowRunSnippetToolbar) - { - ToggleSnippetRunner(); - } + // populate the text menu call backs to the run snippet dialog.. + PopulateTextMenuCallBacks(); - // the constructor code finalized executing.. - runningConstructor = false; + if (FormSettings.Settings.ShowRunSnippetToolbar) + { + ToggleSnippetRunner(); } - #endregion - #region DatabaseMigration - private void MigrateDatabaseEfCore() + // the constructor code finalized executing.. + runningConstructor = false; + } + #endregion + + #region DatabaseMigration + private void MigrateDatabaseEfCore() + { + try { - try + // check the migration level.. + if (FormSettings.Settings.DatabaseMigrationLevel < 2 && File.Exists(Path.Combine(DBLangEngine.DataDir, "ScriptNotepadEntity.sqlite"))) { - // check the migration level.. - if (FormSettings.Settings.DatabaseMigrationLevel < 2 && File.Exists(Path.Combine(DBLangEngine.DataDir, "ScriptNotepadEntity.sqlite"))) - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgDatabaseMigration1", - "The database will be updated. This might take a few minutes.|A message informing that database is migrating to a Entity Framework Code-First database and it might be a lengthy process."), - DBLangEngine.GetMessage("msgInformation", - "Information|A message title describing of some kind information."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgDatabaseMigration1", + "The database will be updated. This might take a few minutes.|A message informing that database is migrating to a Entity Framework Code-First database and it might be a lengthy process."), + DBLangEngine.GetMessage("msgInformation", + "Information|A message title describing of some kind information."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); - List migrateExceptions; + List migrateExceptions; - if ((migrateExceptions = ScriptNotepadOldDbContext.MigrateToEfCore( + if ((migrateExceptions = ScriptNotepadOldDbContext.MigrateToEfCore( Path.Combine(DBLangEngine.DataDir, "ScriptNotepadEntity.sqlite"), Path.Combine(DBLangEngine.DataDir, "ScriptNotepadEntityCore.sqlite"))).Count > 0) + { + foreach (var migrateException in migrateExceptions) { - foreach (var migrateException in migrateExceptions) - { - MessageBoxExtended.Show( - migrateException.Message, - DBLangEngine.GetMessage("msgError", - "Error|A message describing that some kind of error occurred."), MessageBoxButtonsExtended.OK, - MessageBoxIcon.Error, ExtendedDefaultButtons.Button1); - ExceptionLogger.LogError(migrateException); - } - Process.GetCurrentProcess().Kill(); - return; + MessageBoxExtended.Show( + migrateException.Message, + DBLangEngine.GetMessage("msgError", + "Error|A message describing that some kind of error occurred."), MessageBoxButtonsExtended.OK, + MessageBoxIcon.Error, ExtendedDefaultButtons.Button1); + ExceptionLogger.LogError(migrateException); } + Process.GetCurrentProcess().Kill(); + return; + } - FormSettings.Settings.DatabaseMigrationLevel = 2; + FormSettings.Settings.DatabaseMigrationLevel = 2; - File.Delete(Path.Combine(DBLangEngine.DataDir, "ScriptNotepadEntity.sqlite")); - } - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); + File.Delete(Path.Combine(DBLangEngine.DataDir, "ScriptNotepadEntity.sqlite")); } } - #endregion - - #region HelperMethods - /// - /// Toggles the snippet runner tool bar. - /// - private void ToggleSnippetRunner() + catch (Exception ex) { - var dockForm = FormSnippetRunner.Instance; + ExceptionLogger.LogError(ex); + } + } + #endregion - if (pnDockRunSnippet.Controls.Contains(dockForm)) - { - if (dockForm.SearchFocused) - { - dockForm.Close(); - FormSettings.Settings.ShowRunSnippetToolbar = false; - return; - } + #region HelperMethods + /// + /// Toggles the snippet runner tool bar. + /// + private void ToggleSnippetRunner() + { + var dockForm = FormSnippetRunner.Instance; - dockForm.SearchFocused = true; + if (pnDockRunSnippet.Controls.Contains(dockForm)) + { + if (dockForm.SearchFocused) + { + dockForm.Close(); + FormSettings.Settings.ShowRunSnippetToolbar = false; return; } - dockForm.Visible = true; - dockForm.TopLevel = false; - dockForm.AutoScroll = true; - dockForm.FormBorderStyle = FormBorderStyle.None; - dockForm.Location = new Point(0, 0); - dockForm.Width = pnDockRunSnippet.Width; - dockForm.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; - dockForm.Closing += delegate { pnDockRunSnippet.Controls.Remove(dockForm); }; - - pnDockRunSnippet.Controls.Add(dockForm); - dockForm.Focus(); + dockForm.SearchFocused = true; + return; } - /// - /// Populates the text menu call backs to the run snippet dialog. - /// - private void PopulateTextMenuCallBacks() + dockForm.Visible = true; + dockForm.TopLevel = false; + dockForm.AutoScroll = true; + dockForm.FormBorderStyle = FormBorderStyle.None; + dockForm.Location = new Point(0, 0); + dockForm.Width = pnDockRunSnippet.Width; + dockForm.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + dockForm.Closing += delegate { pnDockRunSnippet.Controls.Remove(dockForm); }; + + pnDockRunSnippet.Controls.Add(dockForm); + dockForm.Focus(); + } + + /// + /// Populates the text menu call backs to the run snippet dialog. + /// + private void PopulateTextMenuCallBacks() + { + FormSnippetRunner.Callbacks.AddRange(new[] + { + new TextManipulationCallbackBase + { + CallbackAction = () => mnuSortAscending.PerformClick(), + MethodName = DBLangEngine.GetMessage("msgUtilTextSortLinesAscending", + "Sort lines ascending|A message describing an action to sort lines in ascending order."), + }, + new TextManipulationCallbackBase + { + CallbackAction = () => mnuSortDescending.PerformClick(), + MethodName = DBLangEngine.GetMessage("msgUtilTextSortLinesDescending", + "Sort lines descending|A message describing an action to sort lines in descending order."), + }, + new TextManipulationCallbackBase + { + CallbackAction = () => mnuCustomizedSort.PerformClick(), + MethodName = DBLangEngine.GetMessage("msgUtilTextSortLinesCustom", + "Sort lines in custom order|A message describing an action to sort lines in custom order."), + }, + new TextManipulationCallbackBase + { + CallbackAction = () => mnuWrapDocumentTo.PerformClick(), + MethodName = DBLangEngine.GetMessage("msgUtilTextWrapDocument", + "Wrap document|A message describing an action to wrap document into specified maximum length lines."), + }, + }); + } + + /// + /// Checks for new version of the application. + /// + private void CheckForNewVersion() + { + // no going to the internet if the user doesn't allow it.. + if (FormSettings.Settings.UpdateAutoCheck) { - FormSnippetRunner.Callbacks.AddRange(new[] - { - new TextManipulationCallbackBase - { - CallbackAction = () => mnuSortAscending.PerformClick(), - MethodName = DBLangEngine.GetMessage("msgUtilTextSortLinesAscending", - "Sort lines ascending|A message describing an action to sort lines in ascending order.") - }, - new TextManipulationCallbackBase - { - CallbackAction = () => mnuSortDescending.PerformClick(), - MethodName = DBLangEngine.GetMessage("msgUtilTextSortLinesDescending", - "Sort lines descending|A message describing an action to sort lines in descending order.") - }, - new TextManipulationCallbackBase - { - CallbackAction = () => mnuCustomizedSort.PerformClick(), - MethodName = DBLangEngine.GetMessage("msgUtilTextSortLinesCustom", - "Sort lines in custom order|A message describing an action to sort lines in custom order.") - }, - new TextManipulationCallbackBase - { - CallbackAction = () => mnuWrapDocumentTo.PerformClick(), - MethodName = DBLangEngine.GetMessage("msgUtilTextWrapDocument", - "Wrap document|A message describing an action to wrap document into specified maximum length lines.") - }, - }); + FormCheckVersion.CheckForNewVersion("https://www.vpksoft.net/versions/version.php", + Assembly.GetEntryAssembly(), FormSettings.Settings.Culture.Name); } - - /// - /// Checks for new version of the application. - /// - private void CheckForNewVersion() + } + + /// + /// Sets the state of the spell checker. + /// + /// if set to true the spell checking is enabled. + /// A flag indicating whether to save the spell checking state to the database. + private void SetSpellCheckerState(bool enabled, bool noDatabaseUpdate) + { + CurrentDocumentAction(document => { - // no going to the internet if the user doesn't allow it.. - if (FormSettings.Settings.UpdateAutoCheck) + // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. + if (document.Tag0 != null && + document.Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) { - FormCheckVersion.CheckForNewVersion("https://www.vpksoft.net/versions/version.php", - Assembly.GetEntryAssembly(), FormSettings.Settings.Culture.Name); + // get the TabbedDocumentSpellCheck class instance.. + var spellCheck = (TabbedDocumentSpellCheck) document.Tag0; + + // set the document's spell check to either enabled or disabled.. + tsbSpellCheck.Checked = enabled; + spellCheck.Enabled = enabled; + + var fileSave = (FileSave) document.Tag; + fileSave.UseSpellChecking = spellCheck.Enabled; + if (!noDatabaseUpdate) + { + fileSave.AddOrUpdateFile(); + } + + document.Tag = fileSave; } - } + }); + } - /// - /// Sets the state of the spell checker. - /// - /// if set to true the spell checking is enabled. - /// A flag indicating whether to save the spell checking state to the database. - private void SetSpellCheckerState(bool enabled, bool noDatabaseUpdate) + /// + /// Undo the document changes if possible. + /// + internal void Undo() + { + // if there is an active document.. + CurrentDocumentAction(document => { - CurrentDocumentAction(document => + sttcMain.SuspendTextChangedEvents = true; // suspend the changed events on the ScintillaTabbedTextControl.. + + // ..then undo if it's possible.. + if (document.Scintilla.CanUndo) { - // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. - if (document.Tag0 != null && - document.Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) - { - // get the TabbedDocumentSpellCheck class instance.. - var spellCheck = (TabbedDocumentSpellCheck) document.Tag0; + // undo.. + document.Scintilla.Undo(); - // set the document's spell check to either enabled or disabled.. - tsbSpellCheck.Checked = enabled; - spellCheck.Enabled = enabled; + // get a FileSave class instance from the document's tag.. + var fileSave = (FileSave)document.Tag; - var fileSave = (FileSave) document.Tag; - fileSave.UseSpellChecking = spellCheck.Enabled; - if (!noDatabaseUpdate) - { - fileSave.AddOrUpdateFile(); - } + // undo the encoding change.. + fileSave.UndoEncodingChange(); - document.Tag = fileSave; + if (!document.Scintilla.CanUndo) + { + fileSave.PopPreviousDbModified(); + document.FileTabButton.IsSaved = !IsFileChanged(fileSave); } - }); - } + } + sttcMain.SuspendTextChangedEvents = false; // suspend the changed events on the ScintillaTabbedTextControl.. + }); - /// - /// Undo the document changes if possible. - /// - internal void Undo() - { - // if there is an active document.. - CurrentDocumentAction(document => - { - sttcMain.SuspendTextChangedEvents = true; // suspend the changed events on the ScintillaTabbedTextControl.. + UpdateToolbarButtonsAndMenuItems(); + } - // ..then undo if it's possible.. - if (document.Scintilla.CanUndo) + /// + /// Redo the document changes if possible. + /// + private void Redo() + { + // if there is an active document.. + CurrentDocumentAction(document => + { + // ..then redo if it's possible.. + if (document.Scintilla.CanRedo) { - // undo.. - document.Scintilla.Undo(); + document.Scintilla.Redo(); + } + } + ); + UpdateToolbarButtonsAndMenuItems(); + } - // get a FileSave class instance from the document's tag.. - var fileSave = (FileSave)document.Tag; + /// + /// Enables or disables the main form's GUI timers. + /// + /// if set to true the timers are enabled. + private void EnableDisableTimers(bool enabled) + { + tmSpellCheck.Enabled = enabled; + tmGUI.Enabled = enabled; + } - // undo the encoding change.. - fileSave.UndoEncodingChange(); + /// + /// Disposes the spell checkers attached to the document tabs. + /// + private void DisposeSpellCheckerAndUrlHighlight() + { + for (int i = 0; i < sttcMain.DocumentsCount; i++) + { + // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. + if (sttcMain.Documents[i] != null && sttcMain.Documents[i].Tag0 != null && + sttcMain.Documents[i].Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) + { + // dispose of the spell checker + var spellCheck = (TabbedDocumentSpellCheck) sttcMain.Documents[i].Tag0; - if (!document.Scintilla.CanUndo) - { - fileSave.PopPreviousDbModified(); - document.FileTabButton.IsSaved = !IsFileChanged(fileSave); - } + using (spellCheck) + { + sttcMain.Documents[i].Tag0 = null; } - sttcMain.SuspendTextChangedEvents = false; // suspend the changed events on the ScintillaTabbedTextControl.. - }); + } - UpdateToolbarButtonsAndMenuItems(); - } + // validate that the ScintillaTabbedDocument instance has an URL highlighter attached to it.. + if (sttcMain.Documents[i] != null && sttcMain.Documents[i].Tag1 != null && + sttcMain.Documents[i].Tag1.GetType() == typeof(ScintillaUrlDetect)) + { + var urlDetect = (ScintillaUrlDetect) sttcMain.Documents[i].Tag1; - /// - /// Redo the document changes if possible. - /// - private void Redo() - { - // if there is an active document.. - CurrentDocumentAction(document => + using (urlDetect) { - // ..then redo if it's possible.. - if (document.Scintilla.CanRedo) - { - document.Scintilla.Redo(); - } + sttcMain.Documents[i].Tag1 = null; } - ); - UpdateToolbarButtonsAndMenuItems(); + } } + } - /// - /// Enables or disables the main form's GUI timers. - /// - /// if set to true the timers are enabled. - private void EnableDisableTimers(bool enabled) + /// + /// Unsubscribes the event handlers from the context menus. + /// + private void DisposeContextMenus() + { + for (int i = 0; i < sttcMain.DocumentsCount; i++) { - tmSpellCheck.Enabled = enabled; - tmGUI.Enabled = enabled; + // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. + if (sttcMain.Documents[i] != null && sttcMain.Documents[i].Scintilla.ContextMenuStrip != null) + { + // unsubscribe the events from the context menu.. + ScintillaContextMenu.UnsubscribeEvents(sttcMain.Documents[i].Scintilla); + } } + } - /// - /// Disposes the spell checkers attached to the document tabs. - /// - private void DisposeSpellCheckerAndUrlHighlight() + /// + /// Runs an action to the current document's if there is a current document. + /// + /// The action to run. + public void CurrentScintillaAction(Action action) + { + if (sttcMain.CurrentDocument != null) { - for (int i = 0; i < sttcMain.DocumentsCount; i++) + try { - // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. - if (sttcMain.Documents[i] != null && sttcMain.Documents[i].Tag0 != null && - sttcMain.Documents[i].Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) - { - // dispose of the spell checker - var spellCheck = (TabbedDocumentSpellCheck) sttcMain.Documents[i].Tag0; - - using (spellCheck) - { - sttcMain.Documents[i].Tag0 = null; - } - } - - // validate that the ScintillaTabbedDocument instance has an URL highlighter attached to it.. - if (sttcMain.Documents[i] != null && sttcMain.Documents[i].Tag1 != null && - sttcMain.Documents[i].Tag1.GetType() == typeof(ScintillaUrlDetect)) - { - var urlDetect = (ScintillaUrlDetect) sttcMain.Documents[i].Tag1; + action(sttcMain.CurrentDocument.Scintilla); + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); + } + } + } - using (urlDetect) - { - sttcMain.Documents[i].Tag1 = null; - } - } + /// + /// Runs an action to the current document if there is a current document. + /// + /// The action to run. + public void CurrentDocumentAction(Action action) + { + if (sttcMain.CurrentDocument != null) + { + try + { + action(sttcMain.CurrentDocument); + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); } } + } - /// - /// Unsubscribes the event handlers from the context menus. - /// - private void DisposeContextMenus() + /// + /// Runs an action to the last added if one exists. + /// + /// The action to run. + public void LastAddedDocumentAction(Action action) + { + if (sttcMain.LastAddedDocument != null) { - for (int i = 0; i < sttcMain.DocumentsCount; i++) + try { - // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. - if (sttcMain.Documents[i] != null && sttcMain.Documents[i].Scintilla.ContextMenuStrip != null) - { - // unsubscribe the events from the context menu.. - ScintillaContextMenu.UnsubscribeEvents(sttcMain.Documents[i].Scintilla); - } + action(sttcMain.LastAddedDocument); + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); } } + } - /// - /// Runs an action to the current document's if there is a current document. - /// - /// The action to run. - public void CurrentScintillaAction(Action action) + /// + /// Runs an action to the current document's class instance stored in the Tag property. + /// + /// The action to run. + public void CurrentFileSaveAction(Action action) + { + if (sttcMain.CurrentDocument?.Tag != null) { - if (sttcMain.CurrentDocument != null) + if (sttcMain.CurrentDocument.Tag is FileSave fileSave) { try { - action(sttcMain.CurrentDocument.Scintilla); + action(fileSave); + sttcMain.CurrentDocument.Tag = fileSave; } catch (Exception ex) { @@ -677,18 +737,22 @@ public void CurrentScintillaAction(Action action) } } } + } - /// - /// Runs an action to the current document if there is a current document. - /// - /// The action to run. - public void CurrentDocumentAction(Action action) + /// + /// Runs an action to the last added document's class instance stored in the Tag property. + /// + /// The action to run. + public void LastAddedFileSaveAction(Action action) + { + if (sttcMain.LastAddedDocument?.Tag != null) { - if (sttcMain.CurrentDocument != null) + if (sttcMain.LastAddedDocument.Tag is FileSave fileSave) { try { - action(sttcMain.CurrentDocument); + action(fileSave); + sttcMain.LastAddedDocument.Tag = fileSave; } catch (Exception ex) { @@ -696,3727 +760,3662 @@ public void CurrentDocumentAction(Action action) } } } + } + + /// + /// Gets an item of type from a given object. Useful with events. + /// + /// The type of the object + /// The sender of the event. + /// (T). + public T ItemFromObj(object sender) + { + return (T) sender; + } - /// - /// Runs an action to the last added if one exists. - /// - /// The action to run. - public void LastAddedDocumentAction(Action action) + /// + /// The context menu of the scintilla called this method, so do some related stuff. + /// + /// A class instance from which the context menu strip called the undo method. + private void UndoFromExternal(Scintilla scintilla) + { + // if there is an active document.. + if (sttcMain.CurrentDocument != null && sttcMain.CurrentDocument.Scintilla.Equals(scintilla)) { - if (sttcMain.LastAddedDocument != null) + // get a FileSave class instance from the document's tag.. + var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; + + // undo the encoding change.. + fileSave.UndoEncodingChange(); + + if (!sttcMain.CurrentDocument.Scintilla.CanUndo) { - try - { - action(sttcMain.LastAddedDocument); - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } + fileSave.PopPreviousDbModified(); + sttcMain.CurrentDocument.FileTabButton.IsSaved = !IsFileChanged(fileSave); } } + UpdateToolbarButtonsAndMenuItems(); + } + + /// + /// The context menu of the scintilla called this method, so do some related stuff. + /// + /// A class instance from which the context menu strip called the redo method. + private void RedoFromExternal(Scintilla scintilla) + { + UpdateToolbarButtonsAndMenuItems(); + } - /// - /// Runs an action to the current document's class instance stored in the Tag property. - /// - /// The action to run. - public void CurrentFileSaveAction(Action action) + /// + /// Initializes the plug-ins for the software. + /// + private void InitializePlugins() + { + // initialize the action to detect if a plug-in has crashed the program.. + ModuleExceptionHandler = delegate (string module) { - if (sttcMain.CurrentDocument?.Tag != null) + try { - if (sttcMain.CurrentDocument.Tag is FileSave fileSave) + var plugin = Plugins.FirstOrDefault(f => f.Plugin.FileNameFull == module); + if (plugin.Plugin != null) { - try - { - action(fileSave); - sttcMain.CurrentDocument.Tag = fileSave; - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } + plugin.Plugin.ApplicationCrashes++; + plugin.Plugin.IsActive = false; + ScriptNotepadDbContext.DbContext.SaveChanges(); } } - } + catch + { + // the application is about to crash - let the ExceptionLogger do it's job and log the crash.. + } + }; - /// - /// Runs an action to the last added document's class instance stored in the Tag property. - /// - /// The action to run. - public void LastAddedFileSaveAction(Action action) + IEnumerable databaseEntries = ScriptNotepadDbContext.DbContext.Plugins.ToList(); + bool pluginDeleted = false; + // ReSharper disable once PossibleMultipleEnumeration + foreach (var pluginEntry in databaseEntries) { - if (sttcMain.LastAddedDocument?.Tag != null) + if (pluginEntry.PendingDeletion) { - if (sttcMain.LastAddedDocument.Tag is FileSave fileSave) + try { - try - { - action(fileSave); - sttcMain.LastAddedDocument.Tag = fileSave; - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } + File.Delete(pluginEntry.FileNameFull); } - } - } - - /// - /// Gets an item of type from a given object. Useful with events. - /// - /// The type of the object - /// The sender of the event. - /// (T). - public T ItemFromObj(object sender) - { - return (T) sender; - } - - /// - /// The context menu of the scintilla called this method, so do some related stuff. - /// - /// A class instance from which the context menu strip called the undo method. - private void UndoFromExternal(Scintilla scintilla) - { - // if there is an active document.. - if (sttcMain.CurrentDocument != null && sttcMain.CurrentDocument.Scintilla.Equals(scintilla)) - { - // get a FileSave class instance from the document's tag.. - var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; - - // undo the encoding change.. - fileSave.UndoEncodingChange(); - - if (!sttcMain.CurrentDocument.Scintilla.CanUndo) + catch (Exception ex) { - fileSave.PopPreviousDbModified(); - sttcMain.CurrentDocument.FileTabButton.IsSaved = !IsFileChanged(fileSave); + // log the exception.. + ExceptionLogger.LogError(ex); } + + ScriptNotepadDbContext.DbContext.Plugins.Remove(pluginEntry); + ScriptNotepadDbContext.DbContext.SaveChanges(); + pluginDeleted = true; } - UpdateToolbarButtonsAndMenuItems(); } - /// - /// The context menu of the scintilla called this method, so do some related stuff. - /// - /// A class instance from which the context menu strip called the redo method. - private void RedoFromExternal(Scintilla scintilla) + if (pluginDeleted) { - UpdateToolbarButtonsAndMenuItems(); + databaseEntries = ScriptNotepadDbContext.DbContext.Plugins.ToList(); } - /// - /// Initializes the plug-ins for the software. - /// - private void InitializePlugins() - { - // initialize the action to detect if a plug-in has crashed the program.. - ModuleExceptionHandler = delegate (string module) - { - try - { - var plugin = Plugins.FirstOrDefault(f => f.Plugin.FileNameFull == module); - if (plugin.Plugin != null) - { - plugin.Plugin.ApplicationCrashes++; - plugin.Plugin.IsActive = false; - ScriptNotepadDbContext.DbContext.SaveChanges(); - } - } - catch - { - // the application is about to crash - let the ExceptionLogger do it's job and log the crash.. - } - }; - - IEnumerable databaseEntries = ScriptNotepadDbContext.DbContext.Plugins.ToList(); - bool pluginDeleted = false; - // ReSharper disable once PossibleMultipleEnumeration - foreach (var pluginEntry in databaseEntries) - { - if (pluginEntry.PendingDeletion) - { - try - { - File.Delete(pluginEntry.FileNameFull); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } + // load the existing plug-ins.. + var plugins = PluginDirectoryRoaming.GetPluginAssemblies(FormSettings.Settings.PluginFolder); - ScriptNotepadDbContext.DbContext.Plugins.Remove(pluginEntry); - ScriptNotepadDbContext.DbContext.SaveChanges(); - pluginDeleted = true; - } - } + // loop through the found plug-ins.. + foreach (var plugin in plugins) + { + // check if the plug-in is already in the database.. + var pluginEntry = + // ReSharper disable once PossibleMultipleEnumeration + databaseEntries. + FirstOrDefault( + f => f.FileName == Path.GetFileName(plugin.Path)); - if (pluginDeleted) + // if the plug-in has been logged into the database and is disabled + // save the flag.. + bool loadPlugin = true; + if (pluginEntry != null) { - databaseEntries = ScriptNotepadDbContext.DbContext.Plugins.ToList(); + loadPlugin = pluginEntry.IsActive; } - // load the existing plug-ins.. - var plugins = PluginDirectoryRoaming.GetPluginAssemblies(FormSettings.Settings.PluginFolder); - - // loop through the found plug-ins.. - foreach (var plugin in plugins) + // only valid plug-ins are accepted.. + if (plugin.IsValid && loadPlugin) { - // check if the plug-in is already in the database.. - var pluginEntry = - // ReSharper disable once PossibleMultipleEnumeration - databaseEntries. - FirstOrDefault( - f => f.FileName == Path.GetFileName(plugin.Path)); + // try to load the assembly and the plug-in.. + var pluginAssembly = PluginInitializer.LoadPlugin(plugin.Path); - // if the plug-in has been logged into the database and is disabled - // save the flag.. - bool loadPlugin = true; - if (pluginEntry != null) + // set the locale for the plug-in.. + if (pluginAssembly.Plugin != null) { - loadPlugin = pluginEntry.IsActive; + pluginAssembly.Plugin.Locale = FormSettings.Settings.Culture.Name; } - // only valid plug-ins are accepted.. - if (plugin.IsValid && loadPlugin) - { - // try to load the assembly and the plug-in.. - var pluginAssembly = PluginInitializer.LoadPlugin(plugin.Path); - - // set the locale for the plug-in.. - if (pluginAssembly.Plugin != null) - { - pluginAssembly.Plugin.Locale = FormSettings.Settings.Culture.Name; - } - - // try to initialize the plug-in.. - if (PluginInitializer.InitializePlugin(pluginAssembly.Plugin, + // try to initialize the plug-in.. + if (PluginInitializer.InitializePlugin(pluginAssembly.Plugin, RequestActiveDocument, RequestAllDocuments, PluginException, menuMain, mnuPlugins, CurrentSession.SessionName, this)) - { - pluginEntry = pluginEntry == null - ? PluginHelper.FromPlugin(plugin.Assembly, pluginAssembly.Plugin, plugin.Path) - : PluginHelper.UpdateFromPlugin(pluginEntry, plugin.Assembly, pluginAssembly.Plugin, - plugin.Path); - - // on success, add the plug-in assembly and its instance to the internal list.. - Plugins.Add((plugin.Assembly, pluginAssembly.Plugin, pluginEntry)); - } - - // update the possible version and the update time stamp.. - if (pluginEntry != null) - { - AssemblyVersion.SetPluginUpdated(pluginEntry, plugin.Assembly); + { + pluginEntry = pluginEntry == null + ? PluginHelper.FromPlugin(plugin.Assembly, pluginAssembly.Plugin, plugin.Path) + : PluginHelper.UpdateFromPlugin(pluginEntry, plugin.Assembly, pluginAssembly.Plugin, + plugin.Path); - // update the plug-in information to the database.. - ScriptNotepadDbContext.DbContext.SaveChanges(); - } + // on success, add the plug-in assembly and its instance to the internal list.. + Plugins.Add((plugin.Assembly, pluginAssembly.Plugin, pluginEntry)); } - else + + // update the possible version and the update time stamp.. + if (pluginEntry != null) { - if (pluginEntry != null) - { - pluginEntry.LoadFailures++; - } - else - { - pluginEntry = PluginHelper.InvalidPlugin(plugin.Assembly, plugin.Path); - } - // update the possible version and the update time stamp.. AssemblyVersion.SetPluginUpdated(pluginEntry, plugin.Assembly); // update the plug-in information to the database.. ScriptNotepadDbContext.DbContext.SaveChanges(); - - // on failure, add the "invalid" plug-in assembly and its instance to the internal list.. - Plugins.Add((plugin.Assembly, null, pluginEntry)); } } + else + { + if (pluginEntry != null) + { + pluginEntry.LoadFailures++; + } + else + { + pluginEntry = PluginHelper.InvalidPlugin(plugin.Assembly, plugin.Path); + } + // update the possible version and the update time stamp.. + AssemblyVersion.SetPluginUpdated(pluginEntry, plugin.Assembly); + + // update the plug-in information to the database.. + ScriptNotepadDbContext.DbContext.SaveChanges(); - // set the plug-in menu visible only if any of the plug-ins added to the plug-in menu.. - mnuPlugins.Visible = mnuPlugins.DropDownItems.Count > 0; + // on failure, add the "invalid" plug-in assembly and its instance to the internal list.. + Plugins.Add((plugin.Assembly, null, pluginEntry)); + } } - /// - /// Unsubscribes the external event handlers and disposes of the items created by other classes. - /// - private void DisposeExternal() - { - // release the references for the status strip labels.. - StatusStripTexts.Initialized = false; + // set the plug-in menu visible only if any of the plug-ins added to the plug-in menu.. + mnuPlugins.Visible = mnuPlugins.DropDownItems.Count > 0; + } - // dispose of the encoding menu items.. - CharacterSetMenuBuilder.DisposeCharacterSetMenu(mnuCharSets); + /// + /// Unsubscribes the external event handlers and disposes of the items created by other classes. + /// + private void DisposeExternal() + { + // release the references for the status strip labels.. + StatusStripTexts.Initialized = false; - // dispose of the recent file menu items.. - RecentFilesMenuBuilder.DisposeRecentFilesMenu(mnuRecentFiles); + // dispose of the encoding menu items.. + CharacterSetMenuBuilder.DisposeCharacterSetMenu(mnuCharSets); - // dispose the session menu items.. - SessionMenuBuilder.DisposeSessionMenu(); + // dispose of the recent file menu items.. + RecentFilesMenuBuilder.DisposeRecentFilesMenu(mnuRecentFiles); - // unsubscribe the recent file menu item click handler.. - RecentFilesMenuBuilder.RecentFileMenuClicked -= RecentFilesMenuBuilder_RecentFileMenuClicked; + // dispose the session menu items.. + SessionMenuBuilder.DisposeSessionMenu(); - // unsubscribe to events which will occur with the FormSearchResultTree instance docking.. - FormSearchResultTree.RequestDockMainForm -= FormSearchResultTree_RequestDockMainForm; - FormSearchResultTree.RequestDockReleaseMainForm -= FormSearchResultTree_RequestDockReleaseMainForm; + // unsubscribe the recent file menu item click handler.. + RecentFilesMenuBuilder.RecentFileMenuClicked -= RecentFilesMenuBuilder_RecentFileMenuClicked; - // unsubscribe to an event which is raised upon application activation.. - ApplicationDeactivated -= FormMain_ApplicationDeactivated; - ApplicationActivated -= FormMain_ApplicationActivated; + // unsubscribe to events which will occur with the FormSearchResultTree instance docking.. + FormSearchResultTree.RequestDockMainForm -= FormSearchResultTree_RequestDockMainForm; + FormSearchResultTree.RequestDockReleaseMainForm -= FormSearchResultTree_RequestDockReleaseMainForm; - // dispose of the programming language menu helper.. - using (ProgrammingLanguageHelper) - { - // unsubscribe the programming language click event.. - ProgrammingLanguageHelper.LanguageMenuClick += ProgrammingLanguageHelper_LanguageMenuClick; - } + // unsubscribe to an event which is raised upon application activation.. + ApplicationDeactivated -= FormMain_ApplicationDeactivated; + ApplicationActivated -= FormMain_ApplicationActivated; - // unsubscribe to the event when a search result is clicked from the FormSearchResultTree form.. - FormSearchResultTree.SearchResultSelected -= FormSearchResultTreeSearchResultSelected; + // dispose of the programming language menu helper.. + using (ProgrammingLanguageHelper) + { + // unsubscribe the programming language click event.. + ProgrammingLanguageHelper.LanguageMenuClick += ProgrammingLanguageHelper_LanguageMenuClick; + } - // unsubscribe the IpcClientServer MessageReceived event handler.. - IpcServer.MessageReceived -= RemoteMessage_MessageReceived; - IpcServer.Dispose(); + // unsubscribe to the event when a search result is clicked from the FormSearchResultTree form.. + FormSearchResultTree.SearchResultSelected -= FormSearchResultTreeSearchResultSelected; - // unsubscribe the encoding menu clicked handler.. - CharacterSetMenuBuilder.EncodingMenuClicked -= CharacterSetMenuBuilder_EncodingMenuClicked; + // unsubscribe the IpcClientServer MessageReceived event handler.. + IpcServer.MessageReceived -= RemoteMessage_MessageReceived; + IpcServer.Dispose(); - // unsubscribe the session menu clicked handler.. - SessionMenuBuilder.SessionMenuClicked -= SessionMenuBuilder_SessionMenuClicked; + // unsubscribe the encoding menu clicked handler.. + CharacterSetMenuBuilder.EncodingMenuClicked -= CharacterSetMenuBuilder_EncodingMenuClicked; - // unsubscribe the request documents event handler of the search and replace dialog.. - FormSearchAndReplace.Instance.RequestDocuments -= InstanceRequestDocuments; + // unsubscribe the session menu clicked handler.. + SessionMenuBuilder.SessionMenuClicked -= SessionMenuBuilder_SessionMenuClicked; - // set the search and replace dialog to be allowed to be disposed of.. - FormSearchAndReplace.AllowInstanceDispose = true; + // unsubscribe the request documents event handler of the search and replace dialog.. + FormSearchAndReplace.Instance.RequestDocuments -= InstanceRequestDocuments; - // set the flag for the diff viewer to allow the form to close.. - FormFileDiffView.ApplicationClosing = true; + // set the search and replace dialog to be allowed to be disposed of.. + FormSearchAndReplace.AllowInstanceDispose = true; - // dispose of the WinFormsFormMenuBuilder instance.. - using (WinFormsFormMenuBuilder) - { - WinFormsFormMenuBuilder = null; - } + // set the flag for the diff viewer to allow the form to close.. + FormFileDiffView.ApplicationClosing = true; - // dispose of the tab menu.. - using (TabMenuBuilder) - { - TabMenuBuilder = null; - } + // dispose of the WinFormsFormMenuBuilder instance.. + using (WinFormsFormMenuBuilder) + { + WinFormsFormMenuBuilder = null; + } - // dispose of the loaded plug-in.. - DisposePlugins(); + // dispose of the tab menu.. + using (TabMenuBuilder) + { + TabMenuBuilder = null; } - /// - /// Disposes the plug-ins loaded into the software. - /// - private void DisposePlugins() + // dispose of the loaded plug-in.. + DisposePlugins(); + } + + /// + /// Disposes the plug-ins loaded into the software. + /// + private void DisposePlugins() + { + // loop through the list of loaded plug-ins.. + for (int i = Plugins.Count -1; i >= 0; i--) { - // loop through the list of loaded plug-ins.. - for (int i = Plugins.Count -1; i >= 0; i--) + try { - try + using (Plugins[i].PluginInstance) { - using (Plugins[i].PluginInstance) - { - // just the disposal.. - } + // just the disposal.. } - catch (Exception ex) - { - Plugins[i].Plugin.ExceptionCount++; + } + catch (Exception ex) + { + Plugins[i].Plugin.ExceptionCount++; - // the disposal failed so do add to the exception count.. - ScriptNotepadDbContext.DbContext.SaveChanges(); + // the disposal failed so do add to the exception count.. + ScriptNotepadDbContext.DbContext.SaveChanges(); - // log the dispose failures as well.. - ExceptionLogger.LogMessage($"Plug-in dispose failed. Plug-in: {Plugins[i].PluginInstance.PluginName}, Assembly: {Plugins[i].Assembly.FullName}."); - ExceptionLogger.LogError(ex); - } + // log the dispose failures as well.. + ExceptionLogger.LogMessage($"Plug-in dispose failed. Plug-in: {Plugins[i].PluginInstance.PluginName}, Assembly: {Plugins[i].Assembly.FullName}."); + ExceptionLogger.LogError(ex); } - - // clear the list.. - Plugins.Clear(); } + + // clear the list.. + Plugins.Clear(); + } - /// - /// Creates dynamic actions to static classes for error reporting. - /// - private void AssignExceptionReportingActions() - { - // create a dynamic action for the class exception logging.. + /// + /// Creates dynamic actions to static classes for error reporting. + /// + private void AssignExceptionReportingActions() + { + // create a dynamic action for the class exception logging.. - // many classes are inherited from this one (less copy/paste code!).. - ErrorHandlingBase.ExceptionLogAction = ExceptionLogger.LogError; + // many classes are inherited from this one (less copy/paste code!).. + ErrorHandlingBase.ExceptionLogAction = ExceptionLogger.LogError; - PluginDirectoryRoaming.ExceptionLogAction = - delegate (Exception ex, Assembly assembly, string assemblyFile) - { - ExceptionLogger.LogMessage($"Assembly load failed. Assembly: {(assembly == null ? "unknown" : assembly.FullName)}, FileName: {assemblyFile ?? "unknown"}."); - ExceptionLogger.LogError(ex); - }; + PluginDirectoryRoaming.ExceptionLogAction = + delegate (Exception ex, Assembly assembly, string assemblyFile) + { + ExceptionLogger.LogMessage($"Assembly load failed. Assembly: {(assembly == null ? "unknown" : assembly.FullName)}, FileName: {assemblyFile ?? "unknown"}."); + ExceptionLogger.LogError(ex); + }; - PluginInitializer.ExceptionLogAction = - delegate (Exception ex, Assembly assembly, string assemblyFile, string methodName) - { - ExceptionLogger.LogMessage($"Plug-in assembly initialization failed. Assembly: {(assembly == null ? "unknown" : assembly.FullName)}, FileName: {assemblyFile ?? "unknown"}, Method: {methodName}."); - ExceptionLogger.LogError(ex); - }; + PluginInitializer.ExceptionLogAction = + delegate (Exception ex, Assembly assembly, string assemblyFile, string methodName) + { + ExceptionLogger.LogMessage($"Plug-in assembly initialization failed. Assembly: {(assembly == null ? "unknown" : assembly.FullName)}, FileName: {assemblyFile ?? "unknown"}, Method: {methodName}."); + ExceptionLogger.LogError(ex); + }; - // END: create a dynamic action for the class exception logging.. - } + // END: create a dynamic action for the class exception logging.. + } - /// - /// This method should be called when the application is about to close. - /// - /// A flag indicating whether any user interaction/dialog should occur in the application closing event. - private void EndSession(bool noUserInteraction) + /// + /// This method should be called when the application is about to close. + /// + /// A flag indicating whether any user interaction/dialog should occur in the application closing event. + private void EndSession(bool noUserInteraction) + { + // if the user interaction is denied, prevent the application activation event from checking file system changes, etc.. + if (noUserInteraction) { - // if the user interaction is denied, prevent the application activation event from checking file system changes, etc.. - if (noUserInteraction) - { - Activated -= FormMain_Activated; - FormClosed -= FormMain_FormClosed; + Activated -= FormMain_Activated; + FormClosed -= FormMain_FormClosed; - // close all the dialog boxes with a dialog result of cancel.. - MessageBoxExtendedControl.CloseAllBoxesWithResult(DialogResultExtended.Cancel); + // close all the dialog boxes with a dialog result of cancel.. + MessageBoxExtendedControl.CloseAllBoxesWithResult(DialogResultExtended.Cancel); - // close all other open forms except this MainForm as they might dialogs, etc. to prevent the - // session log of procedure.. - CloseFormUtils.CloseOpenForms(this); - } + // close all other open forms except this MainForm as they might dialogs, etc. to prevent the + // session log of procedure.. + CloseFormUtils.CloseOpenForms(this); + } - // save the current session's documents to the database.. - SaveDocumentsToDatabase(); + // save the current session's documents to the database.. + SaveDocumentsToDatabase(); - // delete excess entries from the file history list from the database.. - var deleted = FileHistoryHelper.CleanupHistoryList(HistoryListAmount, currentSession); - ExceptionLogger.LogMessage($"Database history list cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); + // delete excess entries from the file history list from the database.. + var deleted = FileHistoryHelper.CleanupHistoryList(HistoryListAmount, currentSession); + ExceptionLogger.LogMessage($"Database history list cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); - // delete excess document contents saved in the database.. - deleted = FileHistoryHelper.CleanUpHistoryFiles(SaveFileHistoryContentsCount, CurrentSession); - ExceptionLogger.LogMessage($"Database history contents cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); + // delete excess document contents saved in the database.. + deleted = FileHistoryHelper.CleanUpHistoryFiles(SaveFileHistoryContentsCount, CurrentSession); + ExceptionLogger.LogMessage($"Database history contents cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); - // clean the old search path entries from the database.. - MiscellaneousTextEntryHelper.DeleteOlderEntries(MiscellaneousTextType.Path, - FormSettings.Settings.FileSearchHistoriesLimit, CurrentSession); + // clean the old search path entries from the database.. + MiscellaneousTextEntryHelper.DeleteOlderEntries(MiscellaneousTextType.Path, + FormSettings.Settings.FileSearchHistoriesLimit, CurrentSession); - // clean excess regular expressions from the custom text sorting dialog.. - MiscellaneousTextEntryHelper.DeleteOlderEntries(MiscellaneousTextType.RegexSorting, - 20, CurrentSession); + // clean excess regular expressions from the custom text sorting dialog.. + MiscellaneousTextEntryHelper.DeleteOlderEntries(MiscellaneousTextType.RegexSorting, + 20, CurrentSession); - // clean the old replace replace history entries from the database.. - SearchAndReplaceHistoryHelper.DeleteOlderEntries(SearchAndReplaceSearchType.All, - SearchAndReplaceType.Replace, FormSettings.Settings.FileSearchHistoriesLimit, CurrentSession); + // clean the old replace replace history entries from the database.. + SearchAndReplaceHistoryHelper.DeleteOlderEntries(SearchAndReplaceSearchType.All, + SearchAndReplaceType.Replace, FormSettings.Settings.FileSearchHistoriesLimit, CurrentSession); - // clean the old replace search history entries from the database.. - SearchAndReplaceHistoryHelper.DeleteOlderEntries(SearchAndReplaceSearchType.All, - SearchAndReplaceType.Search, FormSettings.Settings.FileSearchHistoriesLimit, CurrentSession); + // clean the old replace search history entries from the database.. + SearchAndReplaceHistoryHelper.DeleteOlderEntries(SearchAndReplaceSearchType.All, + SearchAndReplaceType.Search, FormSettings.Settings.FileSearchHistoriesLimit, CurrentSession); - // close the main form as the call came from elsewhere than the FormMain_FormClosed event.. - if (noUserInteraction) - { - Close(); - } + // close the main form as the call came from elsewhere than the FormMain_FormClosed event.. + if (noUserInteraction) + { + Close(); + } - // dispose of the spell checkers attached to the documents.. - DisposeSpellCheckerAndUrlHighlight(); + // dispose of the spell checkers attached to the documents.. + DisposeSpellCheckerAndUrlHighlight(); - // unsubscribe the event handlers from the context menus.. - DisposeContextMenus(); - } + // unsubscribe the event handlers from the context menus.. + DisposeContextMenus(); + } - /// - /// Closes the current given session. - /// - private void CloseSession() - { - // save the current session's documents to the database.. - SaveDocumentsToDatabase(); + /// + /// Closes the current given session. + /// + private void CloseSession() + { + // save the current session's documents to the database.. + SaveDocumentsToDatabase(); - // delete excess entries from the file history list from the database.. - var deleted = FileHistoryHelper.CleanupHistoryList(HistoryListAmount, currentSession); - ExceptionLogger.LogMessage($"Database history list cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); + // delete excess entries from the file history list from the database.. + var deleted = FileHistoryHelper.CleanupHistoryList(HistoryListAmount, currentSession); + ExceptionLogger.LogMessage($"Database history list cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); - // delete excess document contents saved in the database.. - deleted = FileHistoryHelper.CleanUpHistoryFiles(SaveFileHistoryContentsCount, CurrentSession); - ExceptionLogger.LogMessage($"Database history contents cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); + // delete excess document contents saved in the database.. + deleted = FileHistoryHelper.CleanUpHistoryFiles(SaveFileHistoryContentsCount, CurrentSession); + ExceptionLogger.LogMessage($"Database history contents cleanup: success = {deleted.success}, amount = {deleted.count}, session = {CurrentSession}."); - // dispose of the spell checkers attached to the documents.. - DisposeSpellCheckerAndUrlHighlight(); + // dispose of the spell checkers attached to the documents.. + DisposeSpellCheckerAndUrlHighlight(); - // unsubscribe the event handlers from the context menus.. - DisposeContextMenus(); + // unsubscribe the event handlers from the context menus.. + DisposeContextMenus(); - // close all the documents.. - sttcMain.CloseAllDocuments(); - } + // close all the documents.. + sttcMain.CloseAllDocuments(); + } - /// - /// Determines whether this instance can display a query dialog. I.e. the main for is active and visible. - /// - /// true if this instance can display a query dialog; otherwise, false. - private bool CanDisplayQueryDialog() - { - var result = !runningConstructor && MessageBoxBase.MessageBoxInstances.Count == 0 && Visible && - (WindowState == FormWindowState.Normal || WindowState == FormWindowState.Maximized); - return result; - } + /// + /// Determines whether this instance can display a query dialog. I.e. the main for is active and visible. + /// + /// true if this instance can display a query dialog; otherwise, false. + private bool CanDisplayQueryDialog() + { + var result = !runningConstructor && MessageBoxBase.MessageBoxInstances.Count == 0 && Visible && + (WindowState == FormWindowState.Normal || WindowState == FormWindowState.Maximized); + return result; + } - /// - /// Checks if an open document has been changed in the file system or removed from the file system and - /// queries the user form appropriate action for the file. - /// - private void CheckFileSysChanges() + /// + /// Checks if an open document has been changed in the file system or removed from the file system and + /// queries the user form appropriate action for the file. + /// + private void CheckFileSysChanges() + { + for (int i = sttcMain.DocumentsCount - 1; i >= 0; i--) { - for (int i = sttcMain.DocumentsCount - 1; i >= 0; i--) - { - // get the FileSave class instance from the document's tag.. - var fileSave = (FileSave)sttcMain.Documents[i].Tag; + // get the FileSave class instance from the document's tag.. + var fileSave = (FileSave)sttcMain.Documents[i].Tag; - // avoid excess checks further in the code.. - if (fileSave == null) - { - continue; - } + // avoid excess checks further in the code.. + if (fileSave == null) + { + continue; + } - // check if the file exists because it cannot be reloaded otherwise - // from the file system.. - if (File.Exists(sttcMain.Documents[i].FileName) && !fileSave.ShouldQueryFileReappeared()) - { - // query the user if one wishes to reload - // the changed file from the disk.. - if (CanDisplayQueryDialog() && fileSave.GetShouldQueryDiskReload()) - { - if (MessageBoxExtended.Show( + // check if the file exists because it cannot be reloaded otherwise + // from the file system.. + if (File.Exists(sttcMain.Documents[i].FileName) && !fileSave.ShouldQueryFileReappeared()) + { + // query the user if one wishes to reload + // the changed file from the disk.. + if (CanDisplayQueryDialog() && fileSave.GetShouldQueryDiskReload()) + { + if (MessageBoxExtended.Show( DBLangEngine.GetMessage("msgFileHasChanged", "The file '{0}' has been changed. Reload from the file system?|As in the opened file has been changed outside the software so do as if a reload should happen", fileSave.FileNameFull), DBLangEngine.GetMessage("msgFileArbitraryFileChange", "A file has been changed|A caption message for a message dialog which will ask if a changed file should be reloaded"), MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button1) == DialogResultExtended.Yes) - { - // the user answered yes.. - sttcMain.SuspendTextChangedEvents = true; // suspend the changed events on the ScintillaTabbedTextControl.. - fileSave.ReloadFromDisk(sttcMain.Documents[i]); // reload the file.. - sttcMain.SuspendTextChangedEvents = false; // resume the changed events on the ScintillaTabbedTextControl.. + { + // the user answered yes.. + sttcMain.SuspendTextChangedEvents = true; // suspend the changed events on the ScintillaTabbedTextControl.. + fileSave.ReloadFromDisk(sttcMain.Documents[i]); // reload the file.. + sttcMain.SuspendTextChangedEvents = false; // resume the changed events on the ScintillaTabbedTextControl.. - // just in case set the tag back.. - sttcMain.Documents[i].Tag = fileSave; + // just in case set the tag back.. + sttcMain.Documents[i].Tag = fileSave; - // set the flag that the form should be activated after the dialog.. - bringToFrontQueued = true; - } - else // the user doesn't want to load the changes made to the document from the file system.. - { - // indicate that the query shouldn't happen again.. - fileSave.SetShouldQueryDiskReload(false); + // set the flag that the form should be activated after the dialog.. + bringToFrontQueued = true; + } + else // the user doesn't want to load the changes made to the document from the file system.. + { + // indicate that the query shouldn't happen again.. + fileSave.SetShouldQueryDiskReload(false); - // set the flag that the file's modified date in the database - // has been changed as the user didn't wish to reload the file from the file system: FS != DB.. - fileSave.SetDatabaseModified(DateTime.Now); + // set the flag that the file's modified date in the database + // has been changed as the user didn't wish to reload the file from the file system: FS != DB.. + fileSave.SetDatabaseModified(DateTime.Now); - // just in case set the tag back.. - sttcMain.Documents[i].Tag = fileSave; + // just in case set the tag back.. + sttcMain.Documents[i].Tag = fileSave; - // set the flag that the form should be activated after the dialog.. - bringToFrontQueued = true; - } + // set the flag that the form should be activated after the dialog.. + bringToFrontQueued = true; } } - else + } + else + { + // query the user if one wishes to keep a deleted + // file from the file system in the editor.. + if (CanDisplayQueryDialog() && fileSave.ShouldQueryKeepFile()) { - // query the user if one wishes to keep a deleted - // file from the file system in the editor.. - if (CanDisplayQueryDialog() && fileSave.ShouldQueryKeepFile()) - { - if (MessageBoxExtended.Show( + if (MessageBoxExtended.Show( DBLangEngine.GetMessage("msgFileHasBeenDeleted", "The file '{0}' has been deleted. Keep the file in the editor?|As in the opened file has been deleted from the file system and user is asked if to keep the deleted file in the editor", fileSave.FileNameFull), DBLangEngine.GetMessage("msgFileHasBeenDeletedTitle", "A file has been deleted|A caption message for a message dialog which will ask if a deleted file should be kept in the editor"), MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button1) == DialogResultExtended.Yes) - { - // the user answered yes.. - fileSave.ExistsInFileSystem = false; // set the flag to false.. - fileSave.IsHistory = false; + { + // the user answered yes.. + fileSave.ExistsInFileSystem = false; // set the flag to false.. + fileSave.IsHistory = false; - fileSave.AddOrUpdateFile(sttcMain.Documents[i], true, false, true); + fileSave.AddOrUpdateFile(sttcMain.Documents[i], true, false, true); - // just in case set the tag back.. - sttcMain.Documents[i].Tag = fileSave; + // just in case set the tag back.. + sttcMain.Documents[i].Tag = fileSave; - // set the flag that the form should be activated after the dialog.. - bringToFrontQueued = true; - } - else - { - // call the handle method.. - HandleCloseTab(fileSave, true, false, false, - sttcMain.Documents[i].Scintilla.CurrentPosition); - } + // set the flag that the form should be activated after the dialog.. + bringToFrontQueued = true; } - else if (CanDisplayQueryDialog() && fileSave.ShouldQueryFileReappeared()) + else { - if (MessageBoxExtended.Show( + // call the handle method.. + HandleCloseTab(fileSave, true, false, false, + sttcMain.Documents[i].Scintilla.CurrentPosition); + } + } + else if (CanDisplayQueryDialog() && fileSave.ShouldQueryFileReappeared()) + { + if (MessageBoxExtended.Show( DBLangEngine.GetMessage("msgFileHasReappeared", "The file '{0}' has reappeared. Reload from the file system?|As in the file has reappeared to the file system and the software queries whether to reload it's contents from the file system", fileSave.FileNameFull), DBLangEngine.GetMessage("msgFileHasReappearedTitle", "A file has reappeared|A caption message for a message dialog which will ask if a reappeared file should be reloaded from the file system"), MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button1) == DialogResultExtended.Yes) - { - // the user answered yes.. - fileSave.ExistsInFileSystem = true; // set the flag to true.. - fileSave.IsHistory = false; + { + // the user answered yes.. + fileSave.ExistsInFileSystem = true; // set the flag to true.. + fileSave.IsHistory = false; - fileSave.AddOrUpdateFile(sttcMain.Documents[i], true, false, true); + fileSave.AddOrUpdateFile(sttcMain.Documents[i], true, false, true); - // just in case set the tag back.. - sttcMain.Documents[i].Tag = fileSave; + // just in case set the tag back.. + sttcMain.Documents[i].Tag = fileSave; - // reload the contents as the user answered yes.. - sttcMain.SuspendTextChangedEvents = true; // suspend the changed events on the ScintillaTabbedTextControl.. - fileSave.ReloadFromDisk(sttcMain.Documents[i]); // reload the file.. - sttcMain.SuspendTextChangedEvents = false; // resume the changed events on the ScintillaTabbedTextControl.. + // reload the contents as the user answered yes.. + sttcMain.SuspendTextChangedEvents = true; // suspend the changed events on the ScintillaTabbedTextControl.. + fileSave.ReloadFromDisk(sttcMain.Documents[i]); // reload the file.. + sttcMain.SuspendTextChangedEvents = false; // resume the changed events on the ScintillaTabbedTextControl.. - // set the flag that the form should be activated after the dialog.. - bringToFrontQueued = true; - } + // set the flag that the form should be activated after the dialog.. + bringToFrontQueued = true; } } } } + } - /// - /// A common method to handle different file closing "events". - /// - /// An instance to class instance. - /// A flag indicating if the file was deleted from the file system and a user decided to not the keep the file in the editor. - /// A flag indicating whether this call was made from the tab closing event of a class instance. - /// A flag indicating whether the tab containing the given should be closed. - /// The position of the caret within the "file". - /// A modified class instance based on the given parameters. - private void HandleCloseTab(FileSave fileSave, bool fileDeleted, bool tabClosing, bool closeTab, - int currentPosition) - { - // disable the timers while a document is closing.. - EnableDisableTimers(false); - - // set the flags according to the parameters.. - fileSave.IsHistory = tabClosing || fileDeleted || closeTab; - - // set the exists in file system flag.. - fileSave.ExistsInFileSystem = File.Exists(fileSave.FileNameFull); - - // delete the previous entries of the same file.. - if (fileSave.IsHistory && !fileSave.ExistsInFileSystem) - { - var existingFileSaves = ScriptNotepadDbContext.DbContext.FileSaves.Where(f => - f.IsHistory && f.FileName == fileSave.FileName && f.Id != fileSave.Id && - f.ExistsInFileSystem == fileSave.ExistsInFileSystem && - f.SessionId == fileSave.SessionId); + /// + /// A common method to handle different file closing "events". + /// + /// An instance to class instance. + /// A flag indicating if the file was deleted from the file system and a user decided to not the keep the file in the editor. + /// A flag indicating whether this call was made from the tab closing event of a class instance. + /// A flag indicating whether the tab containing the given should be closed. + /// The position of the caret within the "file". + /// A modified class instance based on the given parameters. + private void HandleCloseTab(FileSave fileSave, bool fileDeleted, bool tabClosing, bool closeTab, + int currentPosition) + { + // disable the timers while a document is closing.. + EnableDisableTimers(false); - ScriptNotepadDbContext.DbContext.FileSaves.RemoveRange(existingFileSaves); - } + // set the flags according to the parameters.. + fileSave.IsHistory = tabClosing || fileDeleted || closeTab; - fileSave.CurrentCaretPosition = currentPosition; + // set the exists in file system flag.. + fileSave.ExistsInFileSystem = File.Exists(fileSave.FileNameFull); - // get the tabbed document index via the ID number.. - int docIndex = sttcMain.Documents.FindIndex(f => f.ID == fileSave.Id); + // delete the previous entries of the same file.. + if (fileSave.IsHistory && !fileSave.ExistsInFileSystem) + { + var existingFileSaves = ScriptNotepadDbContext.DbContext.FileSaves.Where(f => + f.IsHistory && f.FileName == fileSave.FileName && f.Id != fileSave.Id && + f.ExistsInFileSystem == fileSave.ExistsInFileSystem && + f.SessionId == fileSave.SessionId); - ExceptionLogger.LogMessage($"Tab closing: {docIndex}"); + ScriptNotepadDbContext.DbContext.FileSaves.RemoveRange(existingFileSaves); + } - // this should never be -1 but do check still in case of a bug.. - if (docIndex != -1) - { - // unsubscribe the context menu event(s).. - ScintillaContextMenu.UnsubscribeEvents(sttcMain.Documents[docIndex].Scintilla); + fileSave.CurrentCaretPosition = currentPosition; - // update the file save to the database.. - fileSave.AddOrUpdateFile(sttcMain.Documents[docIndex], true, false, false); - - // update the file history list in the database.. - RecentFileHelper.AddOrUpdateRecentFile(fileSave); + // get the tabbed document index via the ID number.. + int docIndex = sttcMain.Documents.FindIndex(f => f.ID == fileSave.Id); - // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. - if (sttcMain.Documents[docIndex].Tag0 != null && sttcMain.Documents[docIndex].Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) - { - // dispose of the spell checker - var spellCheck = (TabbedDocumentSpellCheck)sttcMain.Documents[docIndex].Tag0; + ExceptionLogger.LogMessage($"Tab closing: {docIndex}"); - using (spellCheck) - { - sttcMain.Documents[docIndex].Tag0 = null; - } - } + // this should never be -1 but do check still in case of a bug.. + if (docIndex != -1) + { + // unsubscribe the context menu event(s).. + ScintillaContextMenu.UnsubscribeEvents(sttcMain.Documents[docIndex].Scintilla); - // URL highlighter disposal.. - if (sttcMain.Documents[docIndex].Tag1 != null && sttcMain.Documents[docIndex].Tag1.GetType() == typeof(ScintillaUrlDetect)) - { - // dispose of the URL highlighter.. - var urlCheck = (ScintillaUrlDetect)sttcMain.Documents[docIndex].Tag1; + // update the file save to the database.. + fileSave.AddOrUpdateFile(sttcMain.Documents[docIndex], true, false, false); + + // update the file history list in the database.. + RecentFileHelper.AddOrUpdateRecentFile(fileSave); - using (urlCheck) - { - sttcMain.Documents[docIndex].Tag1 = null; - } - } + // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. + if (sttcMain.Documents[docIndex].Tag0 != null && sttcMain.Documents[docIndex].Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) + { + // dispose of the spell checker + var spellCheck = (TabbedDocumentSpellCheck)sttcMain.Documents[docIndex].Tag0; - // the file was not requested to be kept in the editor after a deletion from the file system or the tab was requested to be closed.. - if (fileDeleted || closeTab) + using (spellCheck) { - // ..so close the tab.. - sttcMain.CloseDocument(docIndex); + sttcMain.Documents[docIndex].Tag0 = null; } } - // set the bring to front flag based on the given parameters.. - bringToFrontQueued = fileDeleted; - - // re-create a menu for recent files.. - RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); - - // enable the timers after the document has closed.. - EnableDisableTimers(true); - } - /// - /// Updates the indicators if the file changes have been saved to the file system. - /// The logic is weird. - /// - private void UpdateDocumentSaveIndicators() - { - // loop through the documents.. - foreach (ScintillaTabbedDocument document in sttcMain.Documents) + // URL highlighter disposal.. + if (sttcMain.Documents[docIndex].Tag1 != null && sttcMain.Documents[docIndex].Tag1.GetType() == typeof(ScintillaUrlDetect)) { - // get the file FileSave instance from the tag.. - var fileSave = (FileSave)document.Tag; - document.FileTabButton.IsSaved = !IsFileChanged(fileSave); - } - UpdateToolbarButtonsAndMenuItems(); - } + // dispose of the URL highlighter.. + var urlCheck = (ScintillaUrlDetect)sttcMain.Documents[docIndex].Tag1; - /// - /// Determines whether the has changed in the editor vs. the file system. - /// - /// The class to check for. - private bool IsFileChanged(FileSave fileSave) - { - if (!fileSave.ExistsInFileSystem) - { - return true; + using (urlCheck) + { + sttcMain.Documents[docIndex].Tag1 = null; + } } - if (fileSave.FileSystemModified < fileSave.DatabaseModified) + // the file was not requested to be kept in the editor after a deletion from the file system or the tab was requested to be closed.. + if (fileDeleted || closeTab) { - return true; + // ..so close the tab.. + sttcMain.CloseDocument(docIndex); } - - return false; } + // set the bring to front flag based on the given parameters.. + bringToFrontQueued = fileDeleted; - /// - /// Updates the tool bar buttons and the menu items enabled states. - /// - private void UpdateToolbarButtonsAndMenuItems() - { - // get the active tab's Scintilla document - CurrentScintillaAction(scintilla => - { - tsbUndo.Enabled = scintilla.CanUndo; - tsbRedo.Enabled = scintilla.CanRedo; + // re-create a menu for recent files.. + RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); - mnuUndo.Enabled = scintilla.CanUndo; - mnuRedo.Enabled = scintilla.CanRedo; + // enable the timers after the document has closed.. + EnableDisableTimers(true); + } - tsbCopy.Enabled = scintilla.SelectedText.Length > 0; - tsbPaste.Enabled = scintilla.CanPaste; - tsbCut.Enabled = scintilla.SelectedText.Length > 0; + /// + /// Updates the indicators if the file changes have been saved to the file system. + /// The logic is weird. + /// + private void UpdateDocumentSaveIndicators() + { + // loop through the documents.. + foreach (ScintillaTabbedDocument document in sttcMain.Documents) + { + // get the file FileSave instance from the tag.. + var fileSave = (FileSave)document.Tag; + document.FileTabButton.IsSaved = !IsFileChanged(fileSave); + } + UpdateToolbarButtonsAndMenuItems(); + } - mnuCopy.Enabled = scintilla.SelectedText.Length > 0; - mnuCut.Enabled = scintilla.SelectedText.Length > 0; - mnuPaste.Enabled = scintilla.CanPaste; - }); + /// + /// Determines whether the has changed in the editor vs. the file system. + /// + /// The class to check for. + private bool IsFileChanged(FileSave fileSave) + { + if (!fileSave.ExistsInFileSystem) + { + return true; } - #endregion - #region UselessCode - // a test menu item for running "absurd" tests with the software.. - private void testToolStripMenuItem_Click(object sender, EventArgs e) + if (fileSave.FileSystemModified < fileSave.DatabaseModified) { - new Test.FormTestThings().Show(); + return true; } - #endregion - #region DocumentHelperMethods + return false; + } + + /// + /// Updates the tool bar buttons and the menu items enabled states. + /// + private void UpdateToolbarButtonsAndMenuItems() + { + // get the active tab's Scintilla document + CurrentScintillaAction(scintilla => + { + tsbUndo.Enabled = scintilla.CanUndo; + tsbRedo.Enabled = scintilla.CanRedo; + + mnuUndo.Enabled = scintilla.CanUndo; + mnuRedo.Enabled = scintilla.CanRedo; + + tsbCopy.Enabled = scintilla.SelectedText.Length > 0; + tsbPaste.Enabled = scintilla.CanPaste; + tsbCut.Enabled = scintilla.SelectedText.Length > 0; + + mnuCopy.Enabled = scintilla.SelectedText.Length > 0; + mnuCut.Enabled = scintilla.SelectedText.Length > 0; + mnuPaste.Enabled = scintilla.CanPaste; + }); + } + #endregion + + #region UselessCode + // a test menu item for running "absurd" tests with the software.. + private void testToolStripMenuItem_Click(object sender, EventArgs e) + { + new Test.FormTestThings().Show(); + } + #endregion + + #region DocumentHelperMethods - /// - /// Saves the active document snapshots in to the SQLite database. - /// - private void SaveDocumentsToDatabase() + /// + /// Saves the active document snapshots in to the SQLite database. + /// + private void SaveDocumentsToDatabase() + { + for (int i = 0; i < sttcMain.DocumentsCount; i++) { - for (int i = 0; i < sttcMain.DocumentsCount; i++) + try { - try - { - var fileSave = (FileSave) sttcMain.Documents[i].Tag; + var fileSave = (FileSave) sttcMain.Documents[i].Tag; - fileSave.IsActive = sttcMain.Documents[i].FileTabButton.IsActive; - fileSave.VisibilityOrder = i; - fileSave.FoldSave = sttcMain.Documents[i].Scintilla.SaveFolding(); + fileSave.IsActive = sttcMain.Documents[i].FileTabButton.IsActive; + fileSave.VisibilityOrder = i; + fileSave.FoldSave = sttcMain.Documents[i].Scintilla.SaveFolding(); - ScriptNotepadDbContext.DbContext.SaveChanges(); - RecentFileHelper.AddOrUpdateRecentFile(fileSave); - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } + ScriptNotepadDbContext.DbContext.SaveChanges(); + RecentFileHelper.AddOrUpdateRecentFile(fileSave); + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); } } + } - /// - /// Appends a possible style and a spell checking for the document. - /// - /// The document to append the possible style and a spell checking to. - private void AppendStyleAndSpellChecking(ScintillaTabbedDocument document) - { - // ReSharper disable once ObjectCreationAsStatement - new TabbedDocumentSpellCheck(document, !FormSettings.Settings.EditorSpellUseCustomDictionary); + /// + /// Appends a possible style and a spell checking for the document. + /// + /// The document to append the possible style and a spell checking to. + private void AppendStyleAndSpellChecking(ScintillaTabbedDocument document) + { + // ReSharper disable once ObjectCreationAsStatement + new TabbedDocumentSpellCheck(document, !FormSettings.Settings.EditorSpellUseCustomDictionary); - string fileName = FormSettings.NotepadPlusPlusStyleFile; + string fileName = FormSettings.NotepadPlusPlusStyleFile; - // check if a user has selected a style definitions (Notepad++ style XML) file.. - if (File.Exists(fileName)) - { - // ..set the style for the document.. - ScintillaLexers.CreateLexerFromFile(document.Scintilla, document.LexerType, fileName); - } + // check if a user has selected a style definitions (Notepad++ style XML) file.. + if (File.Exists(fileName)) + { + // ..set the style for the document.. + ScintillaLexers.CreateLexerFromFile(document.Scintilla, document.LexerType, fileName); } + } - /// - /// Sets the application title to indicate no active document. - /// - private void SetEmptyApplicationTitle() - { - // ReSharper disable once ArrangeThisQualifier - this.Text = - DBLangEngine.GetMessage("msgAppTitleWithoutFileName", + /// + /// Sets the application title to indicate no active document. + /// + private void SetEmptyApplicationTitle() + { + // ReSharper disable once ArrangeThisQualifier + this.Text = + DBLangEngine.GetMessage("msgAppTitleWithoutFileName", "ScriptNotepad|As in the application name without an active file name") + - (ProcessElevation.IsElevated ? " (" + - DBLangEngine.GetMessage("msgProcessIsElevated", "Administrator|A message indicating that a process is elevated.") + ")" : string.Empty); - } + (ProcessElevation.IsElevated ? " (" + + DBLangEngine.GetMessage("msgProcessIsElevated", "Administrator|A message indicating that a process is elevated.") + ")" : string.Empty); + } - /// - /// Sets the application title to indicate the currently active document. - /// - /// The document. - private void SetApplicationTitle(ScintillaTabbedDocument document) - { - // ReSharper disable once ArrangeThisQualifier - this.Text = - DBLangEngine.GetMessage("msgAppTitleWithFileName", + /// + /// Sets the application title to indicate the currently active document. + /// + /// The document. + private void SetApplicationTitle(ScintillaTabbedDocument document) + { + // ReSharper disable once ArrangeThisQualifier + this.Text = + DBLangEngine.GetMessage("msgAppTitleWithFileName", "ScriptNotepad [{0}]|As in the application name combined with an active file name", document.FileName) + - (ProcessElevation.IsElevated ? " (" + - DBLangEngine.GetMessage("msgProcessIsElevated", "Administrator|A message indicating that a process is elevated.") + ")" : string.Empty); - } + (ProcessElevation.IsElevated ? " (" + + DBLangEngine.GetMessage("msgProcessIsElevated", "Administrator|A message indicating that a process is elevated.") + ")" : string.Empty); + } - /// - /// Sets the document miscellaneous indicators. - /// - /// The document. - private void SetDocumentMiscIndicators(ScintillaTabbedDocument document) + /// + /// Sets the document miscellaneous indicators. + /// + /// The document. + private void SetDocumentMiscIndicators(ScintillaTabbedDocument document) + { + // the spell checking enabled.. + // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. + if (document.Tag0 != null && + document.Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) { - // the spell checking enabled.. - // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. - if (document.Tag0 != null && - document.Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) - { - // get the TabbedDocumentSpellCheck class instance.. - var spellCheck = (TabbedDocumentSpellCheck) document.Tag0; + // get the TabbedDocumentSpellCheck class instance.. + var spellCheck = (TabbedDocumentSpellCheck) document.Tag0; - // set the spell check enable/disable button to indicate the document's spell check state.. - tsbSpellCheck.Checked = spellCheck.Enabled; - } - else - { - // set the spell check enable/disable button to indicate the document's spell check state.. - tsbSpellCheck.Checked = false; - } + // set the spell check enable/disable button to indicate the document's spell check state.. + tsbSpellCheck.Checked = spellCheck.Enabled; + } + else + { + // set the spell check enable/disable button to indicate the document's spell check state.. + tsbSpellCheck.Checked = false; + } - // the percentage mark is also localizable (!).. - sslbZoomPercentage.Text = (document.ZoomPercentage / 100.0) .ToString("P0", DBLangEngine.UseCulture); + // the percentage mark is also localizable (!).. + sslbZoomPercentage.Text = (document.ZoomPercentage / 100.0) .ToString("P0", DBLangEngine.UseCulture); - sslbTabsValue.Text = $@"{sttcMain.CurrentDocumentIndex + 1}/{sttcMain.DocumentsCount}"; - } + sslbTabsValue.Text = $@"{sttcMain.CurrentDocumentIndex + 1}/{sttcMain.DocumentsCount}"; + } - private void SetCaretLineColor() - { - // enabled the caret line background color.. - sttcMain.LastAddedDocument.Scintilla.CaretLineVisible = true; + private void SetCaretLineColor() + { + // enabled the caret line background color.. + sttcMain.LastAddedDocument.Scintilla.CaretLineVisible = true; - // set the color for the caret line.. - sttcMain.LastAddedDocument.Scintilla.CaretLineBackColor = - FormSettings.Settings.CurrentLineBackground; - } + // set the color for the caret line.. + sttcMain.LastAddedDocument.Scintilla.CaretLineBackColor = + FormSettings.Settings.CurrentLineBackground; + } - /// - /// Loads the document snapshots from the SQLite database. - /// - /// A name of the session to which the documents are tagged with. - private void LoadDocumentsFromDatabase(string sessionName) - { - // set the status strip label's to indicate that there is no active document.. - StatusStripTexts.SetEmptyTexts(CurrentSession.SessionName); + /// + /// Loads the document snapshots from the SQLite database. + /// + /// A name of the session to which the documents are tagged with. + private void LoadDocumentsFromDatabase(string sessionName) + { + // set the status strip label's to indicate that there is no active document.. + StatusStripTexts.SetEmptyTexts(CurrentSession.SessionName); - // set the application title to indicate no active document.. - SetEmptyApplicationTitle(); + // set the application title to indicate no active document.. + SetEmptyApplicationTitle(); - IEnumerable files = - ScriptNotepadDbContext.DbContext.FileSaves.Where(f => - f.Session.SessionName == sessionName && !f.IsHistory); + IEnumerable files = + ScriptNotepadDbContext.DbContext.FileSaves.Where(f => + f.Session.SessionName == sessionName && !f.IsHistory); - string activeDocument = string.Empty; + string activeDocument = string.Empty; - foreach (var file in files) + foreach (var file in files) + { + if (file.IsActive) { - if (file.IsActive) - { - activeDocument = file.FileNameFull; - } + activeDocument = file.FileNameFull; + } - sttcMain.AddDocument(file.FileNameFull, file.Id, file.GetEncoding(), file.GetFileContentsAsMemoryStream()); + sttcMain.AddDocument(file.FileNameFull, file.Id, file.GetEncoding(), file.GetFileContentsAsMemoryStream()); - if (sttcMain.LastAddedDocument != null) + if (sttcMain.LastAddedDocument != null) + { + // append additional initialization to the document.. + AdditionalInitializeDocument(sttcMain.LastAddedDocument); + // set the saved position of the document's caret.. + if (file.CurrentCaretPosition > 0 && file.CurrentCaretPosition < sttcMain.LastAddedDocument.Scintilla.TextLength) { - // append additional initialization to the document.. - AdditionalInitializeDocument(sttcMain.LastAddedDocument); - // set the saved position of the document's caret.. - if (file.CurrentCaretPosition > 0 && file.CurrentCaretPosition < sttcMain.LastAddedDocument.Scintilla.TextLength) - { - sttcMain.LastAddedDocument.Scintilla.CurrentPosition = file.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.SelectionStart = file.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.SelectionEnd = file.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.ScrollCaret(); - } + sttcMain.LastAddedDocument.Scintilla.CurrentPosition = file.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.SelectionStart = file.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.SelectionEnd = file.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.ScrollCaret(); + } - sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; + sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; - sttcMain.LastAddedDocument.Tag = file; + sttcMain.LastAddedDocument.Tag = file; - // append possible style and spell checking for the document.. - AppendStyleAndSpellChecking(sttcMain.LastAddedDocument); + // append possible style and spell checking for the document.. + AppendStyleAndSpellChecking(sttcMain.LastAddedDocument); - // set the lexer type from the saved database value.. - sttcMain.LastAddedDocument.LexerType = file.LexerType; + // set the lexer type from the saved database value.. + sttcMain.LastAddedDocument.LexerType = file.LexerType; - SetSpellCheckerState(file.UseSpellChecking, true); + SetSpellCheckerState(file.UseSpellChecking, true); - // enabled the caret line background color.. - SetCaretLineColor(); + // enabled the caret line background color.. + SetCaretLineColor(); - // set the brace matching if enabled.. - SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); + // set the brace matching if enabled.. + SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); - // set the context menu strip for the file tab.. - sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; + // set the context menu strip for the file tab.. + sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; - // the file load can't add an undo option the Scintilla.. - sttcMain.LastAddedDocument.Scintilla.EmptyUndoBuffer(); + // the file load can't add an undo option the Scintilla.. + sttcMain.LastAddedDocument.Scintilla.EmptyUndoBuffer(); - // set the zoom value.. - sttcMain.LastAddedDocument.ZoomPercentage = file.EditorZoomPercentage; + // set the zoom value.. + sttcMain.LastAddedDocument.ZoomPercentage = file.EditorZoomPercentage; - sttcMain.LastAddedDocument.Scintilla.RestoreFolding(file.FoldSave); - } + sttcMain.LastAddedDocument.Scintilla.RestoreFolding(file.FoldSave); + } - UpdateDocumentSaveIndicators(); - } - //sttcMain.ResumeLayout(); + UpdateDocumentSaveIndicators(); + } + //sttcMain.ResumeLayout(); - if (activeDocument != string.Empty) - { - sttcMain.ActivateDocument(activeDocument); - } + if (activeDocument != string.Empty) + { + sttcMain.ActivateDocument(activeDocument); + } - UpdateToolbarButtonsAndMenuItems(); + UpdateToolbarButtonsAndMenuItems(); - // check if any files were changed in the file system.. - CheckFileSysChanges(); - } + // check if any files were changed in the file system.. + CheckFileSysChanges(); + } - /// - /// Sets the additional data for a upon opening or creating one. - /// - /// The document to initialize the additional data for. - private void AdditionalInitializeDocument(ScintillaTabbedDocument document) - { - // create a localizable context menu strip for the Scintilla.. - var menuStrip = ScintillaContextMenu.CreateBasicContextMenuStrip(document.Scintilla, - UndoFromExternal, RedoFromExternal); + /// + /// Sets the additional data for a upon opening or creating one. + /// + /// The document to initialize the additional data for. + private void AdditionalInitializeDocument(ScintillaTabbedDocument document) + { + // create a localizable context menu strip for the Scintilla.. + var menuStrip = ScintillaContextMenu.CreateBasicContextMenuStrip(document.Scintilla, + UndoFromExternal, RedoFromExternal); - // set the editor (Scintilla) properties from the saved settings.. - FormSettings.SetEditorSettings(document.Scintilla); + // set the editor (Scintilla) properties from the saved settings.. + FormSettings.SetEditorSettings(document.Scintilla); - // add the style mark menu to the context menu.. - ContextMenuStyles.CreateStyleMenu(menuStrip, StyleSelectOf_Click, ClearStyleOf_Click, ClearAllStyles_Click); + // add the style mark menu to the context menu.. + ContextMenuStyles.CreateStyleMenu(menuStrip, StyleSelectOf_Click, ClearStyleOf_Click, ClearAllStyles_Click); - // set the editor (Scintilla) properties from the saved settings.. - FormSettings.SetEditorSettings(document.Scintilla); + // set the editor (Scintilla) properties from the saved settings.. + FormSettings.SetEditorSettings(document.Scintilla); - // check the programming language menu item with the current lexer.. - ProgrammingLanguageHelper.CheckLanguage(document.LexerType); + // check the programming language menu item with the current lexer.. + ProgrammingLanguageHelper.CheckLanguage(document.LexerType); - // set the URL detection if enabled.. - if (FormSettings.Settings.HighlightUrls) - { - var urlDetect = new ScintillaUrlDetect(document.Scintilla); - FormSettings.SetUrlDetectStyling(urlDetect); + // set the URL detection if enabled.. + if (FormSettings.Settings.HighlightUrls) + { + var urlDetect = new ScintillaUrlDetect(document.Scintilla); + FormSettings.SetUrlDetectStyling(urlDetect); - urlDetect.AppendIndicatorClear(31); - document.Tag1 = urlDetect; - } + urlDetect.AppendIndicatorClear(31); + document.Tag1 = urlDetect; } + } - /// - /// Opens files given as arguments for the software. - /// - private void OpenArgumentFiles() - { - string[] args = Environment.GetCommandLineArgs(); + /// + /// Opens files given as arguments for the software. + /// + private void OpenArgumentFiles() + { + string[] args = Environment.GetCommandLineArgs(); - // only send the existing files to the running instance, don't send the executable - // file name thus the start from 1.. - for (int i = 1; i < args.Length; i++) + // only send the existing files to the running instance, don't send the executable + // file name thus the start from 1.. + for (int i = 1; i < args.Length; i++) + { + // a file must exist.. + if (File.Exists(args[i])) { - // a file must exist.. - if (File.Exists(args[i])) - { - // add the file to the document control.. - OpenDocument(args[i], DefaultEncodings, false, false); - } + // add the file to the document control.. + OpenDocument(args[i], DefaultEncodings, false, false); } } + } - /// - /// Adds a new document in to the view. - /// - /// True if the operation was successful; otherwise false. - private void NewDocument() + /// + /// Adds a new document in to the view. + /// + /// True if the operation was successful; otherwise false. + private void NewDocument() + { + // a false would happen if the document (file) can not be accessed or required permissions to access a file + // would be missing (also a bug might occur).. + if (sttcMain.AddNewDocument()) { - // a false would happen if the document (file) can not be accessed or required permissions to access a file - // would be missing (also a bug might occur).. - if (sttcMain.AddNewDocument()) + if (sttcMain.LastAddedDocument != null) // if the document was added or updated to the control.. { - if (sttcMain.LastAddedDocument != null) // if the document was added or updated to the control.. - { - // append additional initialization to the document.. - AdditionalInitializeDocument(sttcMain.LastAddedDocument); + // append additional initialization to the document.. + AdditionalInitializeDocument(sttcMain.LastAddedDocument); - sttcMain.LastAddedDocument.Tag = - new FileSave - { - FileName = sttcMain.CurrentDocument.FileName, - FileNameFull = sttcMain.CurrentDocument.FileName, - FilePath = string.Empty, - Session = CurrentSession, - UseFileSystemOnContents = CurrentSession.UseFileSystemOnContents, - }; + sttcMain.LastAddedDocument.Tag = + new FileSave + { + FileName = sttcMain.CurrentDocument.FileName, + FileNameFull = sttcMain.CurrentDocument.FileName, + FilePath = string.Empty, + Session = CurrentSession, + UseFileSystemOnContents = CurrentSession.UseFileSystemOnContents, + }; - sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; + sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; - // assign the context menu strip for the tabbed document.. - sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; + // assign the context menu strip for the tabbed document.. + sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; - // get a FileSave class instance from the document's tag.. - var fileSave = (FileSave)sttcMain.LastAddedDocument.Tag; + // get a FileSave class instance from the document's tag.. + var fileSave = (FileSave)sttcMain.LastAddedDocument.Tag; - // save the FileSave class instance to the Tag property.. - sttcMain.LastAddedDocument.Tag = - fileSave.AddOrUpdateFile(sttcMain.LastAddedDocument, true, false, false); + // save the FileSave class instance to the Tag property.. + sttcMain.LastAddedDocument.Tag = + fileSave.AddOrUpdateFile(sttcMain.LastAddedDocument, true, false, false); - // append possible style and spell checking for the document.. - AppendStyleAndSpellChecking(sttcMain.LastAddedDocument); + // append possible style and spell checking for the document.. + AppendStyleAndSpellChecking(sttcMain.LastAddedDocument); - // set the brace matching if enabled.. - SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); + // set the brace matching if enabled.. + SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); - // the default spell checking state.. - SetSpellCheckerState(FormSettings.Settings.EditorUseSpellCheckingNewFiles, false); - } + // the default spell checking state.. + SetSpellCheckerState(FormSettings.Settings.EditorUseSpellCheckingNewFiles, false); } } + } - /// - /// Opens the document with a given file name into the view. - /// - /// Name of the file to load into the view. - /// The encoding to be used to open the file. - /// An indicator if the contents of the document should be reloaded from the file system. - /// The given encoding should be used while opening the file. - /// if set to true the setting value whether to detect unicode file with no byte-order-mark (BOM) is overridden. - /// A value indicating whether the file was opened from the Windows shell. - private void OpenDocument(string fileName, - Encoding encoding, - bool reloadContents, bool encodingOverridden, - bool overrideDetectBom = false, bool fromShellContext = false) - { - var encodingList = - new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - { - (encoding.WebName, encoding, false, false) - }; + /// + /// Opens the document with a given file name into the view. + /// + /// Name of the file to load into the view. + /// The encoding to be used to open the file. + /// An indicator if the contents of the document should be reloaded from the file system. + /// The given encoding should be used while opening the file. + /// if set to true the setting value whether to detect unicode file with no byte-order-mark (BOM) is overridden. + /// A value indicating whether the file was opened from the Windows shell. + private void OpenDocument(string fileName, + Encoding encoding, + bool reloadContents, bool encodingOverridden, + bool overrideDetectBom = false, bool fromShellContext = false) + { + var encodingList = + new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + { + (encoding.WebName, encoding, false, false), + }; - OpenDocument(fileName, encodingList, reloadContents, encodingOverridden, overrideDetectBom, fromShellContext); - } + OpenDocument(fileName, encodingList, reloadContents, encodingOverridden, overrideDetectBom, fromShellContext); + } - /// - /// Opens the document with a given file name into the view. - /// - /// Name of the file to load into the view. - /// The encodings to be used to try to open the file. - /// An indicator if the contents of the document should be reloaded from the file system. - /// The given encoding should be used while opening the file. - /// A value indicating whether the file was opened from the Windows shell. - /// if set to true the setting value whether to detect unicode file with no byte-order-mark (BOM) is overridden. - /// True if the operation was successful; otherwise false. - private void OpenDocument(string fileName, List<(string encodingName, Encoding encoding, - bool unicodeFailOnInvalidChar, bool unicodeBOM)> encodings, bool reloadContents, bool encodingOverridden, - bool overrideDetectBom = false, bool fromShellContext = false) - { - Encoding encoding = null; - if (File.Exists(fileName)) + /// + /// Opens the document with a given file name into the view. + /// + /// Name of the file to load into the view. + /// The encodings to be used to try to open the file. + /// An indicator if the contents of the document should be reloaded from the file system. + /// The given encoding should be used while opening the file. + /// A value indicating whether the file was opened from the Windows shell. + /// if set to true the setting value whether to detect unicode file with no byte-order-mark (BOM) is overridden. + /// True if the operation was successful; otherwise false. + private void OpenDocument(string fileName, List<(string encodingName, Encoding encoding, + bool unicodeFailOnInvalidChar, bool unicodeBOM)> encodings, bool reloadContents, bool encodingOverridden, + bool overrideDetectBom = false, bool fromShellContext = false) + { + Encoding encoding = null; + if (File.Exists(fileName)) + { + try { - try + foreach (var encodingData in encodings) { - foreach (var encodingData in encodings) - { - // the encoding shouldn't change based on the file's contents if a snapshot of the file already exists in the database.. - encoding = GetFileEncoding(CurrentSession.SessionName, fileName, encodingData.encoding, reloadContents, encodingOverridden, - overrideDetectBom, - out _, - out _, out _); + // the encoding shouldn't change based on the file's contents if a snapshot of the file already exists in the database.. + encoding = GetFileEncoding(CurrentSession.SessionName, fileName, encodingData.encoding, reloadContents, encodingOverridden, + overrideDetectBom, + out _, + out _, out _); - if (encoding != null) - { - break; - } + if (encoding != null) + { + break; } } - catch (Exception ex) - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgErrorOpeningFile", "Error opening file '{0}' with message: '{1}'.|Some kind of error occurred while opening a file.", - fileName, ex.GetBaseException().Message), - DBLangEngine.GetMessage("msgError", - "Error|A message describing that some kind of error occurred."), MessageBoxButtonsExtended.OK, - MessageBoxIcon.Error, ExtendedDefaultButtons.Button1); - return; - } + } + catch (Exception ex) + { + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgErrorOpeningFile", "Error opening file '{0}' with message: '{1}'.|Some kind of error occurred while opening a file.", + fileName, ex.GetBaseException().Message), + DBLangEngine.GetMessage("msgError", + "Error|A message describing that some kind of error occurred."), MessageBoxButtonsExtended.OK, + MessageBoxIcon.Error, ExtendedDefaultButtons.Button1); + return; + } - // a false would happen if the document (file) can not be accessed or required permissions to access a file - // would be missing (also a bug might occur).. - bool addSuccess = sttcMain.AddDocument(fileName, -1, encoding); + // a false would happen if the document (file) can not be accessed or required permissions to access a file + // would be missing (also a bug might occur).. + bool addSuccess = sttcMain.AddDocument(fileName, -1, encoding); - if (addSuccess) + if (addSuccess) + { + if (sttcMain.LastAddedDocument != null) // if the document was added or updated to the control.. { - if (sttcMain.LastAddedDocument != null) // if the document was added or updated to the control.. - { - // append additional initialization to the document.. - AdditionalInitializeDocument(sttcMain.LastAddedDocument); + // append additional initialization to the document.. + AdditionalInitializeDocument(sttcMain.LastAddedDocument); - // check the database first for a FileSave class instance.. - var fileSave = ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => - f.Session.SessionName == currentSession.SessionName && f.FileNameFull == fileName); + // check the database first for a FileSave class instance.. + var fileSave = ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => + f.Session.SessionName == currentSession.SessionName && f.FileNameFull == fileName); - if (sttcMain.LastAddedDocument.Tag == null && fileSave == null) - { - sttcMain.LastAddedDocument.Tag = - FileSaveHelper.CreateFromTabbedDocument(sttcMain.LastAddedDocument, encoding, - currentSession); - } - else if (fileSave != null) + if (sttcMain.LastAddedDocument.Tag == null && fileSave == null) + { + sttcMain.LastAddedDocument.Tag = + FileSaveHelper.CreateFromTabbedDocument(sttcMain.LastAddedDocument, encoding, + currentSession); + } + else if (fileSave != null) + { + sttcMain.LastAddedDocument.Tag = fileSave; + sttcMain.LastAddedDocument.ID = fileSave.Id; + fileSave.SetEncoding(encoding ?? new UTF8Encoding(true)); + + // set the saved position of the document's caret.. + if (fileSave.CurrentCaretPosition > 0 && fileSave.CurrentCaretPosition < sttcMain.LastAddedDocument.Scintilla.TextLength) { - sttcMain.LastAddedDocument.Tag = fileSave; - sttcMain.LastAddedDocument.ID = fileSave.Id; - fileSave.SetEncoding(encoding ?? new UTF8Encoding(true)); - - // set the saved position of the document's caret.. - if (fileSave.CurrentCaretPosition > 0 && fileSave.CurrentCaretPosition < sttcMain.LastAddedDocument.Scintilla.TextLength) - { - sttcMain.LastAddedDocument.Scintilla.CurrentPosition = fileSave.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.SelectionStart = fileSave.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.SelectionEnd = fileSave.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.ScrollCaret(); - } + sttcMain.LastAddedDocument.Scintilla.CurrentPosition = fileSave.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.SelectionStart = fileSave.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.SelectionEnd = fileSave.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.ScrollCaret(); } + } - sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; - - // get a FileSave class instance from the document's tag.. - fileSave = (FileSave)sttcMain.LastAddedDocument.Tag; + sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; - // set the session ID number.. - fileSave.Session = CurrentSession; + // get a FileSave class instance from the document's tag.. + fileSave = (FileSave)sttcMain.LastAddedDocument.Tag; - // not history at least anymore.. - fileSave.IsHistory = false; + // set the session ID number.. + fileSave.Session = CurrentSession; - // ..update the database with the document.. - fileSave = fileSave.AddOrUpdateFile(sttcMain.LastAddedDocument, true, false, true); - sttcMain.LastAddedDocument.ID = fileSave.Id; + // not history at least anymore.. + fileSave.IsHistory = false; - if (reloadContents) - { - fileSave.ReloadFromDisk(sttcMain.LastAddedDocument); - } + // ..update the database with the document.. + fileSave = fileSave.AddOrUpdateFile(sttcMain.LastAddedDocument, true, false, true); + sttcMain.LastAddedDocument.ID = fileSave.Id; - // save the FileSave class instance to the Tag property.. - sttcMain.LastAddedDocument.Tag = fileSave; + if (reloadContents) + { + fileSave.ReloadFromDisk(sttcMain.LastAddedDocument); + } - // append possible style and spell checking for the document.. - AppendStyleAndSpellChecking(sttcMain.LastAddedDocument); + // save the FileSave class instance to the Tag property.. + sttcMain.LastAddedDocument.Tag = fileSave; - // set the lexer type from the saved database value.. - sttcMain.LastAddedDocument.LexerType = fileSave.LexerType; + // append possible style and spell checking for the document.. + AppendStyleAndSpellChecking(sttcMain.LastAddedDocument); - // enabled the caret line background color.. - SetCaretLineColor(); + // set the lexer type from the saved database value.. + sttcMain.LastAddedDocument.LexerType = fileSave.LexerType; - // assign the context menu strip for the tabbed document.. - sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; + // enabled the caret line background color.. + SetCaretLineColor(); - // the file load can't add an undo option the Scintilla.. - sttcMain.LastAddedDocument.Scintilla.EmptyUndoBuffer(); + // assign the context menu strip for the tabbed document.. + sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; - // set the misc indicators.. - SetDocumentMiscIndicators(sttcMain.LastAddedDocument); + // the file load can't add an undo option the Scintilla.. + sttcMain.LastAddedDocument.Scintilla.EmptyUndoBuffer(); - // set the brace matching if enabled.. - SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); + // set the misc indicators.. + SetDocumentMiscIndicators(sttcMain.LastAddedDocument); - // set the zoom value.. - sttcMain.LastAddedDocument.ZoomPercentage = fileSave.EditorZoomPercentage; + // set the brace matching if enabled.. + SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); - // check the programming language menu item with the current lexer.. - ProgrammingLanguageHelper.CheckLanguage(sttcMain.LastAddedDocument.LexerType); + // set the zoom value.. + sttcMain.LastAddedDocument.ZoomPercentage = fileSave.EditorZoomPercentage; - // set the spell checker state based on the settings and the type of the - // file open method.. - SetSpellCheckerState( - fromShellContext - ? FormSettings.Settings.EditorUseSpellCheckingShellContext - : FormSettings.Settings.EditorUseSpellChecking, false); - } + // check the programming language menu item with the current lexer.. + ProgrammingLanguageHelper.CheckLanguage(sttcMain.LastAddedDocument.LexerType); + + // set the spell checker state based on the settings and the type of the + // file open method.. + SetSpellCheckerState( + fromShellContext + ? FormSettings.Settings.EditorUseSpellCheckingShellContext + : FormSettings.Settings.EditorUseSpellChecking, false); } } } + } - /// - /// Saves the document in to the file system. - /// - /// The document to be saved. - /// An indicator if the document should be saved as a new file. - /// True if the operation was successful; otherwise false. - private void SaveDocument(ScintillaTabbedDocument document, bool saveAs) + /// + /// Saves the document in to the file system. + /// + /// The document to be saved. + /// An indicator if the document should be saved as a new file. + /// True if the operation was successful; otherwise false. + private void SaveDocument(ScintillaTabbedDocument document, bool saveAs) + { + try { - try + // check that the given parameter is valid.. + if (document?.Tag != null) { - // check that the given parameter is valid.. - if (document?.Tag != null) + // get the FileSave class instance from the document's tag.. + var fileSave = (FileSave)document.Tag; + + // set the contents to match the document's text.. + fileSave.SetContents(document.Scintilla.Text, true, true, true); + + // only an existing file can be saved directly.. + if (fileSave.ExistsInFileSystem && !saveAs) { - // get the FileSave class instance from the document's tag.. - var fileSave = (FileSave)document.Tag; + File.WriteAllBytes(fileSave.FileNameFull, fileSave.GetFileContents() ?? Array.Empty()); - // set the contents to match the document's text.. - fileSave.SetContents(document.Scintilla.Text, true, true, true); + // update the file system modified time stamp so the software doesn't ask if the file should + // be reloaded from the file system.. + fileSave.FileSystemModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; + fileSave.FileSystemSaved = fileSave.FileSystemModified; + fileSave.SetDatabaseModified(fileSave.FileSystemModified); + + document.Tag = fileSave.AddOrUpdateFile(); + } + // the file doesn't exist in the file system or the user wishes to use save as dialog so + // display a save file dialog.. + else + { + sdAnyFile.Title = DBLangEngine.GetMessage("msgDialogSaveAs", + "Save as|A title for a save file dialog to indicate user that a file is being saved as with a new file name"); - // only an existing file can be saved directly.. - if (fileSave.ExistsInFileSystem && !saveAs) + sdAnyFile.InitialDirectory = FormSettings.Settings.FileLocationSaveAs; + + sdAnyFile.FileName = fileSave.FileNameFull; + if (sdAnyFile.ShowDialog() == DialogResult.OK) { - File.WriteAllBytes(fileSave.FileNameFull, fileSave.GetFileContents() ?? Array.Empty()); + FormSettings.Settings.FileLocationSaveAs = Path.GetDirectoryName(sdAnyFile.FileName); - // update the file system modified time stamp so the software doesn't ask if the file should - // be reloaded from the file system.. - fileSave.FileSystemModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; - fileSave.FileSystemSaved = fileSave.FileSystemModified; - fileSave.SetDatabaseModified(fileSave.FileSystemModified); - - document.Tag = fileSave.AddOrUpdateFile(); - } - // the file doesn't exist in the file system or the user wishes to use save as dialog so - // display a save file dialog.. - else - { - sdAnyFile.Title = DBLangEngine.GetMessage("msgDialogSaveAs", - "Save as|A title for a save file dialog to indicate user that a file is being saved as with a new file name"); - - sdAnyFile.InitialDirectory = FormSettings.Settings.FileLocationSaveAs; - - sdAnyFile.FileName = fileSave.FileNameFull; - if (sdAnyFile.ShowDialog() == DialogResult.OK) - { - FormSettings.Settings.FileLocationSaveAs = Path.GetDirectoryName(sdAnyFile.FileName); + fileSave.FileSystemModified = DateTime.Now; - fileSave.FileSystemModified = DateTime.Now; + // write the new contents of a file to the existing file overriding it's contents.. + File.WriteAllBytes(sdAnyFile.FileName, fileSave.GetFileContents() ?? Array.Empty()); - // write the new contents of a file to the existing file overriding it's contents.. - File.WriteAllBytes(sdAnyFile.FileName, fileSave.GetFileContents() ?? Array.Empty()); + // the file now exists in the file system.. + fileSave.ExistsInFileSystem = true; - // the file now exists in the file system.. - fileSave.ExistsInFileSystem = true; + // the file now has a location so update it.. + fileSave.UpdateFileData(sdAnyFile.FileName); - // the file now has a location so update it.. - fileSave.UpdateFileData(sdAnyFile.FileName); + // update the document.. + document.FileName = fileSave.FileNameFull; + document.FileNameNotPath = fileSave.FilePath; + document.FileTabButton.Text = fileSave.FileName; - // update the document.. - document.FileName = fileSave.FileNameFull; - document.FileNameNotPath = fileSave.FilePath; - document.FileTabButton.Text = fileSave.FileName; + // a new lexer might have to be assigned.. + document.LexerType = LexerFileExtensions.LexerTypeFromFileName(fileSave.FileNameFull); - // a new lexer might have to be assigned.. - document.LexerType = LexerFileExtensions.LexerTypeFromFileName(fileSave.FileNameFull); - - // update the file system modified time stamp so the software doesn't ask if the file should - // be reloaded from the file system.. - fileSave.FileSystemModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; - fileSave.FileSystemSaved = fileSave.FileSystemModified; - fileSave.SetDatabaseModified(fileSave.FileSystemModified); + // update the file system modified time stamp so the software doesn't ask if the file should + // be reloaded from the file system.. + fileSave.FileSystemModified = new FileInfo(fileSave.FileNameFull).LastWriteTime; + fileSave.FileSystemSaved = fileSave.FileSystemModified; + fileSave.SetDatabaseModified(fileSave.FileSystemModified); - // update document misc data, i.e. the assigned lexer to the database.. - fileSave.AddOrUpdateFile(); + // update document misc data, i.e. the assigned lexer to the database.. + fileSave.AddOrUpdateFile(); - document.Tag = fileSave; - } - else - { - // the user canceled the file save dialog.. - return; - } + document.Tag = fileSave; + } + else + { + // the user canceled the file save dialog.. + return; } - - // update the saved indicators.. - UpdateDocumentSaveIndicators(); } + + // update the saved indicators.. + UpdateDocumentSaveIndicators(); } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + } + } - /// - /// Saves all open documents from the to the file system. - /// - /// An indicator if the documents only existing in a "virtual" space should also be saved in to the file system. - private void SaveAllDocuments(bool nonExisting) + /// + /// Saves all open documents from the to the file system. + /// + /// An indicator if the documents only existing in a "virtual" space should also be saved in to the file system. + private void SaveAllDocuments(bool nonExisting) + { + // loop through the documents.. + foreach (ScintillaTabbedDocument document in sttcMain.Documents) { - // loop through the documents.. - foreach (ScintillaTabbedDocument document in sttcMain.Documents) + // get the FileSave class instance from the tag.. + var fileSave = (FileSave)document.Tag; + if (fileSave.ExistsInFileSystem) { - // get the FileSave class instance from the tag.. - var fileSave = (FileSave)document.Tag; - if (fileSave.ExistsInFileSystem) - { - // save the document.. - SaveDocument(document, nonExisting); - } + // save the document.. + SaveDocument(document, nonExisting); } } - #endregion + } + #endregion - #region InternalEvents - // the menu including time formats is about to be opened.. - private void MnuInsertDateAndTime_DropDownOpening(object sender, EventArgs e) - { - var toolStripMenuItem = (ToolStripMenuItem) sender; - var useInvariantCulture = FormSettings.Settings.DateFormatUseInvariantCulture; + #region InternalEvents + // the menu including time formats is about to be opened.. + private void MnuInsertDateAndTime_DropDownOpening(object sender, EventArgs e) + { + var toolStripMenuItem = (ToolStripMenuItem) sender; + var useInvariantCulture = FormSettings.Settings.DateFormatUseInvariantCulture; + + foreach (ToolStripMenuItem toolStripSubMenuItem in toolStripMenuItem.DropDownItems) + { + var formatNumber = int.Parse(toolStripSubMenuItem.Tag.ToString() ?? "0"); + string format; + switch (formatNumber) + { + case 0: + format = FormSettings.Settings.DateFormat1; + break; + case 1: + format = FormSettings.Settings.DateFormat2; + break; + case 2: + format = FormSettings.Settings.DateFormat3; + break; + case 3: + format = FormSettings.Settings.DateFormat4; + break; + case 4: + format = FormSettings.Settings.DateFormat5; + break; + case 5: + format = FormSettings.Settings.DateFormat6; + break; + default: + format = FormSettings.Settings.DateFormat1; + break; + } - foreach (ToolStripMenuItem toolStripSubMenuItem in toolStripMenuItem.DropDownItems) + // must try in case the user has specified and invalid date-time format.. + try { - var formatNumber = int.Parse(toolStripSubMenuItem.Tag.ToString() ?? "0"); - string format; - switch (formatNumber) - { - case 0: - format = FormSettings.Settings.DateFormat1; - break; - case 1: - format = FormSettings.Settings.DateFormat2; - break; - case 2: - format = FormSettings.Settings.DateFormat3; - break; - case 3: - format = FormSettings.Settings.DateFormat4; - break; - case 4: - format = FormSettings.Settings.DateFormat5; - break; - case 5: - format = FormSettings.Settings.DateFormat6; - break; - default: - format = FormSettings.Settings.DateFormat1; - break; - } - - // must try in case the user has specified and invalid date-time format.. - try - { - toolStripSubMenuItem.Text = DBLangEngine.GetMessage("msgDateTimeMenuItemText", - "Insert date and time type {0}: '{1}'|A message describing a text to insert a date and/or time to a Scintilla instance via a menu strip item.", - formatNumber + 1, - DateTime.Now.ToString(format, - // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. - useInvariantCulture ? CultureInfo.InvariantCulture : CultureInfo.InstalledUICulture)); - } - catch (Exception ex) - { - toolStripSubMenuItem.Text = DBLangEngine.GetMessage( - "msgDateTimeInvalidFormat", - "Invalid date and/or time format|The user has issued an non-valid formatted date and/or time formatting string."); + toolStripSubMenuItem.Text = DBLangEngine.GetMessage("msgDateTimeMenuItemText", + "Insert date and time type {0}: '{1}'|A message describing a text to insert a date and/or time to a Scintilla instance via a menu strip item.", + formatNumber + 1, + DateTime.Now.ToString(format, + // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. + useInvariantCulture ? CultureInfo.InvariantCulture : CultureInfo.InstalledUICulture)); + } + catch (Exception ex) + { + toolStripSubMenuItem.Text = DBLangEngine.GetMessage( + "msgDateTimeInvalidFormat", + "Invalid date and/or time format|The user has issued an non-valid formatted date and/or time formatting string."); - // log the exception.. - ExceptionLogger.LogError(ex); - } + // log the exception.. + ExceptionLogger.LogError(ex); } } + } - private void GotoToolStripMenuItem_Click(object sender, EventArgs e) - { - CurrentScintillaAction(FormDialogQueryJumpLocation.Execute); - } + private void GotoToolStripMenuItem_Click(object sender, EventArgs e) + { + CurrentScintillaAction(FormDialogQueryJumpLocation.Execute); + } - // user wants to insert a date and/or time to the current Scintilla document.. - private void MnuDate1_Click(object sender, EventArgs e) + // user wants to insert a date and/or time to the current Scintilla document.. + private void MnuDate1_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => - { - string format; - - int formatNumber = int.Parse(((ToolStripMenuItem) sender).Tag.ToString() ?? "0"); + string format; - var useInvariantCulture = FormSettings.Settings.DateFormatUseInvariantCulture; - - switch (formatNumber) - { - case 0: - format = FormSettings.Settings.DateFormat1; - break; - case 1: - format = FormSettings.Settings.DateFormat2; - break; - case 2: - format = FormSettings.Settings.DateFormat3; - break; - case 3: - format = FormSettings.Settings.DateFormat4; - break; - case 4: - format = FormSettings.Settings.DateFormat5; - break; - case 5: - format = FormSettings.Settings.DateFormat6; - break; - default: - format = FormSettings.Settings.DateFormat1; - break; - } + int formatNumber = int.Parse(((ToolStripMenuItem) sender).Tag.ToString() ?? "0"); - try - { - scintilla.InsertText(scintilla.CurrentPosition, - DateTime.Now.ToString(format, - // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. - useInvariantCulture ? CultureInfo.InvariantCulture : CultureInfo.InstalledUICulture)); - } - // must try in case the user has specified and invalid date-time format.. - catch (Exception ex) - { - // TODO:: Show an error dialog.. + var useInvariantCulture = FormSettings.Settings.DateFormatUseInvariantCulture; - // log the exception.. - ExceptionLogger.LogError(ex); - } - }); - } + switch (formatNumber) + { + case 0: + format = FormSettings.Settings.DateFormat1; + break; + case 1: + format = FormSettings.Settings.DateFormat2; + break; + case 2: + format = FormSettings.Settings.DateFormat3; + break; + case 3: + format = FormSettings.Settings.DateFormat4; + break; + case 4: + format = FormSettings.Settings.DateFormat5; + break; + case 5: + format = FormSettings.Settings.DateFormat6; + break; + default: + format = FormSettings.Settings.DateFormat1; + break; + } - // handles navigation to the next and previous tab and - // to the next and previous session.. - private void MnuNextPrevious_Click(object sender, EventArgs e) - { - if (sender.Equals(mnuNextTab)) + try { - sttcMain.NextTab(true); + scintilla.InsertText(scintilla.CurrentPosition, + DateTime.Now.ToString(format, + // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. + useInvariantCulture ? CultureInfo.InvariantCulture : CultureInfo.InstalledUICulture)); } - else if (sender.Equals(mnuPreviousTab)) + // must try in case the user has specified and invalid date-time format.. + catch (Exception ex) { - sttcMain.PreviousTab(true); + // TODO:: Show an error dialog.. + + // log the exception.. + ExceptionLogger.LogError(ex); } + }); + } + + // handles navigation to the next and previous tab and + // to the next and previous session.. + private void MnuNextPrevious_Click(object sender, EventArgs e) + { + if (sender.Equals(mnuNextTab)) + { + sttcMain.NextTab(true); + } + else if (sender.Equals(mnuPreviousTab)) + { + sttcMain.PreviousTab(true); } + } - private void FormMain_KeyDown(object sender, KeyEventArgs e) + private void FormMain_KeyDown(object sender, KeyEventArgs e) + { + // a user wishes to navigate within the FormSearchResultTree.. + if (e.OnlyAlt() && e.KeyCodeIn(Keys.Left, Keys.Right, Keys.X)) { - // a user wishes to navigate within the FormSearchResultTree.. - if (e.OnlyAlt() && e.KeyCodeIn(Keys.Left, Keys.Right, Keys.X)) + // validate that there is an instance of the FormSearchResultTree which is visible.. + if (FormSearchResultTree.PreviousInstance != null && FormSearchResultTree.PreviousInstance.Visible) { - // validate that there is an instance of the FormSearchResultTree which is visible.. - if (FormSearchResultTree.PreviousInstance != null && FormSearchResultTree.PreviousInstance.Visible) + // Alt+Left navigates to the previous tree node within the form.. + if (e.KeyCode == Keys.Left) { - // Alt+Left navigates to the previous tree node within the form.. - if (e.KeyCode == Keys.Left) - { - FormSearchResultTree.PreviousInstance.PreviousOccurrence(); - } - // Alt+Right navigates to the next tree node within the form.. - else if (e.KeyCode == Keys.Right) - { - FormSearchResultTree.PreviousInstance.NextOccurrence(); - } - // Alt+X closes the FormSearchResultTree instance.. - else - { - FormSearchResultTree.PreviousInstance.CloseTree(); - } - - // this is handled.. - e.Handled = true; + FormSearchResultTree.PreviousInstance.PreviousOccurrence(); } - return; - } - - // a user pressed the insert key a of a keyboard, which indicates toggling for - // insert / override mode for the Scintilla control.. - if (e.KeyCode == Keys.Insert && e.NoModifierKeysDown()) - { - // only if a document exists.. - if (sttcMain.CurrentDocument != null) + // Alt+Right navigates to the next tree node within the form.. + else if (e.KeyCode == Keys.Right) { - // ..set the insert / override text for the status strip.. - StatusStripTexts.SetInsertOverrideStatusStripText(sttcMain.CurrentDocument, true); + FormSearchResultTree.PreviousInstance.NextOccurrence(); } - return; - } - - if (e.KeyCode == Keys.F3) - { - if (e.OnlyShift() || e.NoModifierKeysDown()) + // Alt+X closes the FormSearchResultTree instance.. + else { - // find the next result if available.. - FormSearchAndReplace.Instance.Advance(!e.OnlyShift()); - - // this is handled.. - e.Handled = true; - return; + FormSearchResultTree.PreviousInstance.CloseTree(); } - } - if (e.KeyCodeIn(Keys.Up, Keys.Down, Keys.Left, Keys.Right, Keys.PageDown, Keys.PageUp)) - { - // set the flag to suspend the selection update to avoid excess CPU load.. - suspendSelectionUpdate = true; + // this is handled.. + e.Handled = true; } + return; } - // the navigation menu is opening, so set the drop-down items states accordingly.. - private void MnuNavigation_DropDownOpening(object sender, EventArgs e) + // a user pressed the insert key a of a keyboard, which indicates toggling for + // insert / override mode for the Scintilla control.. + if (e.KeyCode == Keys.Insert && e.NoModifierKeysDown()) { - mnuNextTab.Enabled = sttcMain.DocumentsCount > 0; - mnuPreviousTab.Enabled = sttcMain.DocumentsCount > 0; + // only if a document exists.. + if (sttcMain.CurrentDocument != null) + { + // ..set the insert / override text for the status strip.. + StatusStripTexts.SetInsertOverrideStatusStripText(sttcMain.CurrentDocument, true); + } + return; } - private void FormMain_ApplicationActivated(object sender, EventArgs e) + if (e.KeyCode == Keys.F3) { - FormSearchAndReplace.Instance.TopMost = true; - } + if (e.OnlyShift() || e.NoModifierKeysDown()) + { + // find the next result if available.. + FormSearchAndReplace.Instance.Advance(!e.OnlyShift()); - private void FormMain_ApplicationDeactivated(object sender, EventArgs e) - { - FormSearchAndReplace.Instance.TopMost = false; + // this is handled.. + e.Handled = true; + return; + } } - // a user wishes to search for an open file within the tabbed documents.. - private void MnuFindTab_Click(object sender, EventArgs e) + if (e.KeyCodeIn(Keys.Up, Keys.Down, Keys.Left, Keys.Right, Keys.PageDown, Keys.PageUp)) { - TimersEnabled = false; - FormDialogSelectFileTab.ShowDialog(sttcMain); - TimersEnabled = true; + // set the flag to suspend the selection update to avoid excess CPU load.. + suspendSelectionUpdate = true; } + } + + // the navigation menu is opening, so set the drop-down items states accordingly.. + private void MnuNavigation_DropDownOpening(object sender, EventArgs e) + { + mnuNextTab.Enabled = sttcMain.DocumentsCount > 0; + mnuPreviousTab.Enabled = sttcMain.DocumentsCount > 0; + } + + private void FormMain_ApplicationActivated(object sender, EventArgs e) + { + FormSearchAndReplace.Instance.TopMost = true; + } + + private void FormMain_ApplicationDeactivated(object sender, EventArgs e) + { + FormSearchAndReplace.Instance.TopMost = false; + } - // copy, paste and cut handler for the tool/menu strip.. - private void TsbCopyPasteCut_Click(object sender, EventArgs e) + // a user wishes to search for an open file within the tabbed documents.. + private void MnuFindTab_Click(object sender, EventArgs e) + { + TimersEnabled = false; + FormDialogSelectFileTab.ShowDialog(sttcMain); + TimersEnabled = true; + } + + // copy, paste and cut handler for the tool/menu strip.. + private void TsbCopyPasteCut_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => + if (sender.Equals(tsbCut) || sender.Equals(mnuCut)) { - if (sender.Equals(tsbCut) || sender.Equals(mnuCut)) - { - scintilla.Cut(); - } + scintilla.Cut(); + } - if (sender.Equals(tsbCopy) || sender.Equals(mnuCopy)) - { - scintilla.Copy(); - } + if (sender.Equals(tsbCopy) || sender.Equals(mnuCopy)) + { + scintilla.Copy(); + } - if (sender.Equals(tsbPaste) || sender.Equals(mnuPaste)) - { - scintilla.Paste(); - } - }); - } + if (sender.Equals(tsbPaste) || sender.Equals(mnuPaste)) + { + scintilla.Paste(); + } + }); + } - // printing (print).. - private void TsbPrint_Click(object sender, EventArgs e) + // printing (print).. + private void TsbPrint_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => + if (pdPrint.ShowDialog() == DialogResult.OK) { - if (pdPrint.ShowDialog() == DialogResult.OK) + var print = new ScintillaPrinting.PrintDocument(scintilla) { - var print = new ScintillaPrinting.PrintDocument(scintilla) - { - PrinterSettings = pdPrint.PrinterSettings - }; - print.Print(); - } - }); - } + PrinterSettings = pdPrint.PrinterSettings, + }; + print.Print(); + } + }); + } - // printing (preview).. - private void TsbPrintPreview_Click(object sender, EventArgs e) + // printing (preview).. + private void TsbPrintPreview_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => - { - var print = new ScintillaPrinting.Printing(scintilla); - print.PrintPreview(this); - }); + var print = new ScintillaPrinting.Printing(scintilla); + print.PrintPreview(this); + }); + } + + // the user wants to change the document's zoom value.. + private void ZoomInOut_Click(object sender, EventArgs e) + { + if (sender.Equals(tsbZoomIn)) + { + sttcMain.CurrentDocument.ZoomPercentage += 10; + } + else if (sender.Equals(tsbZoomOut)) + { + sttcMain.CurrentDocument.ZoomPercentage -= 10; } + } - // the user wants to change the document's zoom value.. - private void ZoomInOut_Click(object sender, EventArgs e) + // the user wishes to either save or to add a new document of the + // current document formatted as HTML.. + private void MnuExportAsHTMLToNewDocument_Click(object sender, EventArgs e) + { + string html; + CurrentScintillaAction(scintilla => { - if (sender.Equals(tsbZoomIn)) + // get the HTML from either the selection or from the whole document + // depending if text is selected.. + if (scintilla.SelectedText.Length > 0) { - sttcMain.CurrentDocument.ZoomPercentage += 10; + // ..no selection.. + html = scintilla.GetTextRangeAsHtml(scintilla.SelectionStart, + scintilla.SelectionEnd - scintilla.SelectionStart); } - else if (sender.Equals(tsbZoomOut)) + else { - sttcMain.CurrentDocument.ZoomPercentage -= 10; + // ..get the selected text as HTML.. + html = scintilla.GetTextRangeAsHtml(0, scintilla.TextLength); } - } - - // the user wishes to either save or to add a new document of the - // current document formatted as HTML.. - private void MnuExportAsHTMLToNewDocument_Click(object sender, EventArgs e) - { - string html; - CurrentScintillaAction(scintilla => + + // the user wants to save the HTML directly into a HTML file.. + if (sender.Equals(mnuHTMLToFile) || sender.Equals(mnuHTMLToFileExecute)) { - // get the HTML from either the selection or from the whole document - // depending if text is selected.. - if (scintilla.SelectedText.Length > 0) + sdHTML.InitialDirectory = FormSettings.Settings.FileLocationSaveAsHtml; + if (sdHTML.ShowDialog() == DialogResult.OK) { - // ..no selection.. - html = scintilla.GetTextRangeAsHtml(scintilla.SelectionStart, - scintilla.SelectionEnd - scintilla.SelectionStart); + FormSettings.Settings.FileLocationSaveAsHtml = Path.GetDirectoryName(sdHTML.FileName); + File.WriteAllText(sdHTML.FileName, html, Encoding.UTF8); } - else + + // the user wants to display the saved HTML file in a web browser.. + if (sender.Equals(mnuHTMLToFileExecute)) { - // ..get the selected text as HTML.. - html = scintilla.GetTextRangeAsHtml(0, scintilla.TextLength); + Process.Start(sdHTML.FileName); } - - // the user wants to save the HTML directly into a HTML file.. - if (sender.Equals(mnuHTMLToFile) || sender.Equals(mnuHTMLToFileExecute)) - { - sdHTML.InitialDirectory = FormSettings.Settings.FileLocationSaveAsHtml; - if (sdHTML.ShowDialog() == DialogResult.OK) - { - FormSettings.Settings.FileLocationSaveAsHtml = Path.GetDirectoryName(sdHTML.FileName); - File.WriteAllText(sdHTML.FileName, html, Encoding.UTF8); - } - - // the user wants to display the saved HTML file in a web browser.. - if (sender.Equals(mnuHTMLToFileExecute)) - { - Process.Start(sdHTML.FileName); - } - return; - } + return; + } - // the user wants the HTML to clipboard.. - if (sender.Equals(mnuHTMLToClipboard)) - { - // save the HTML to the clipboard.. - ClipboardTextHelper.ClipboardSetText(html); - return; - } + // the user wants the HTML to clipboard.. + if (sender.Equals(mnuHTMLToClipboard)) + { + // save the HTML to the clipboard.. + ClipboardTextHelper.ClipboardSetText(html); + return; + } - // the user wants the HTML to a new tab.. - NewDocument(); + // the user wants the HTML to a new tab.. + NewDocument(); - LastAddedDocumentAction(document => - { - // set the recently added document contents.. - document.Scintilla.Text = html; + LastAddedDocumentAction(document => + { + // set the recently added document contents.. + document.Scintilla.Text = html; - // as the contents os HTML, do set the lexer correctly.. - document.LexerType = LexerEnumerations.LexerType.HTML; + // as the contents os HTML, do set the lexer correctly.. + document.LexerType = LexerEnumerations.LexerType.HTML; - LastAddedFileSaveAction(fileSave => { fileSave.LexerType = LexerEnumerations.LexerType.HTML; }); + LastAddedFileSaveAction(fileSave => { fileSave.LexerType = LexerEnumerations.LexerType.HTML; }); - LastAddedFileSaveAction(fileSave => { fileSave.AddOrUpdateFile(); }); + LastAddedFileSaveAction(fileSave => { fileSave.AddOrUpdateFile(); }); - // check the programming language menu item with the current lexer.. - ProgrammingLanguageHelper.CheckLanguage(document.LexerType); - }); + // check the programming language menu item with the current lexer.. + ProgrammingLanguageHelper.CheckLanguage(document.LexerType); }); - } + }); + } - // the auto-save timer.. - private void TmAutoSave_Tick(object sender, EventArgs e) - { - tmAutoSave.Enabled = false; - // save the current session's documents to the database.. - SaveDocumentsToDatabase(); - tmAutoSave.Enabled = true; - } + // the auto-save timer.. + private void TmAutoSave_Tick(object sender, EventArgs e) + { + tmAutoSave.Enabled = false; + // save the current session's documents to the database.. + SaveDocumentsToDatabase(); + tmAutoSave.Enabled = true; + } - // a user is dragging a file over the ScintillaTabbedControl instance.. - private void SttcMain_DragEnterOrOver(object sender, DragEventArgs e) - { - // set the effect to Copy == Accept.. - e.Effect = - e.Data.GetDataPresent(DataFormats.FileDrop) ? - DragDropEffects.Copy : DragDropEffects.None; - } + // a user is dragging a file over the ScintillaTabbedControl instance.. + private void SttcMain_DragEnterOrOver(object sender, DragEventArgs e) + { + // set the effect to Copy == Accept.. + e.Effect = + e.Data.GetDataPresent(DataFormats.FileDrop) ? + DragDropEffects.Copy : DragDropEffects.None; + } - // a user dropped file(s) over the ScintillaTabbedControl instance.. - private void SttcMain_DragDrop(object sender, DragEventArgs e) + // a user dropped file(s) over the ScintillaTabbedControl instance.. + private void SttcMain_DragDrop(object sender, DragEventArgs e) + { + // verify the data format.. + if (e.Data.GetDataPresent(DataFormats.FileDrop)) { - // verify the data format.. - if (e.Data.GetDataPresent(DataFormats.FileDrop)) - { - // get the dropped files and directories.. - string[] dropFiles = (string[])e.Data.GetData(DataFormats.FileDrop); + // get the dropped files and directories.. + string[] dropFiles = (string[])e.Data.GetData(DataFormats.FileDrop); - // loop thought the files and directories - foreach (string filePath in dropFiles) + // loop thought the files and directories + foreach (string filePath in dropFiles) + { + if (File.Exists(filePath)) { - if (File.Exists(filePath)) - { - OpenDocument(filePath, DefaultEncodings, false, false); - } + OpenDocument(filePath, DefaultEncodings, false, false); } } } + } + + // the user clicked the zoom percentage label or the zoom percentage value + // label on the tool strip --> reset the zoom.. + private void ResetZoom_Click(object sender, EventArgs e) + { + sttcMain.CurrentDocument.ZoomPercentage = 100; + } - // the user clicked the zoom percentage label or the zoom percentage value - // label on the tool strip --> reset the zoom.. - private void ResetZoom_Click(object sender, EventArgs e) + // the document's zoom has changed, so do display the value.. + // NOTE: Ctrl+NP+, Ctrl+NP- and Control+NP/ and Control+mouse wheel control the zoom of the Scintilla.. + private void SttcMain_DocumentZoomChanged(object sender, ScintillaZoomChangedEventArgs e) + { + // check that the initialization of this class is done.. + if (!ConstructorFinished) { - sttcMain.CurrentDocument.ZoomPercentage = 100; + // ..if not, return.. + return; } - // the document's zoom has changed, so do display the value.. - // NOTE: Ctrl+NP+, Ctrl+NP- and Control+NP/ and Control+mouse wheel control the zoom of the Scintilla.. - private void SttcMain_DocumentZoomChanged(object sender, ScintillaZoomChangedEventArgs e) + // the percentage mark is also localizable (!).. + sslbZoomPercentage.Text = (e.ZoomPercentage / 100.0).ToString("P0", DBLangEngine.UseCulture); + + CurrentDocumentAction(document => { - // check that the initialization of this class is done.. - if (!ConstructorFinished) + if (document.Tag != null) { - // ..if not, return.. - return; + var fileSave = (FileSave) document.Tag; + fileSave.EditorZoomPercentage = e.ZoomPercentage; + fileSave.AddOrUpdateFile(); } + }); + } - // the percentage mark is also localizable (!).. - sslbZoomPercentage.Text = (e.ZoomPercentage / 100.0).ToString("P0", DBLangEngine.UseCulture); - - CurrentDocumentAction(document => + // a user wishes to change the lexer of the current document.. + private void ProgrammingLanguageHelper_LanguageMenuClick(object sender, ProgrammingLanguageMenuClickEventArgs e) + { + CurrentDocumentAction(document => + { + document.LexerType = e.LexerType; + if (document.Tag != null) { - if (document.Tag != null) - { - var fileSave = (FileSave) document.Tag; - fileSave.EditorZoomPercentage = e.ZoomPercentage; - fileSave.AddOrUpdateFile(); - } - }); - } + var fileSave = (FileSave) document.Tag; + fileSave.LexerType = e.LexerType; + fileSave.AddOrUpdateFile(); + } + }); + } - // a user wishes to change the lexer of the current document.. - private void ProgrammingLanguageHelper_LanguageMenuClick(object sender, ProgrammingLanguageMenuClickEventArgs e) + // a user wishes to alphabetically order the the lines of the active document in ascending or descending order.. + private void MnuSortLines_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentDocumentAction(document => - { - document.LexerType = e.LexerType; - if (document.Tag != null) - { - var fileSave = (FileSave) document.Tag; - fileSave.LexerType = e.LexerType; - fileSave.AddOrUpdateFile(); - } - }); - } + SortLines.Sort(scintilla, FormSettings.Settings.TextCurrentComparison, sender.Equals(mnuSortDescending)); + }); + } - // a user wishes to alphabetically order the the lines of the active document in ascending or descending order.. - private void MnuSortLines_Click(object sender, EventArgs e) + // a user wishes to use custom ordering the the lines of the active document in ascending or descending order.. + private void mnuCustomizedSort_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - CurrentScintillaAction(scintilla => + if (document.SelectionLength > 0 && document.SelectionStartLine == document.SelectionEndLine) { - SortLines.Sort(scintilla, FormSettings.Settings.TextCurrentComparison, sender.Equals(mnuSortDescending)); - }); - } + FormDialogQuerySortTextStyle.ShowDialog(this, document.Scintilla, this, document.SelectionStartColumn + 1, document.SelectionLength); + return; + } - // a user wishes to use custom ordering the the lines of the active document in ascending or descending order.. - private void mnuCustomizedSort_Click(object sender, EventArgs e) + FormDialogQuerySortTextStyle.ShowDialog(this, document.Scintilla, this); + }); + } + + // a timer to run a spell check for a Scintilla document if it has + // been changed and the user has been idle for the timer's interval.. + private void TmSpellCheck_Tick(object sender, EventArgs e) + { + tmSpellCheck.Enabled = false; // disable the timer.. + CurrentDocumentAction(document => { - CurrentDocumentAction(document => + // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. + if (document.Tag0 != null && + document.Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) { - if (document.SelectionLength > 0 && document.SelectionStartLine == document.SelectionEndLine) - { - FormDialogQuerySortTextStyle.ShowDialog(this, document.Scintilla, this, document.SelectionStartColumn + 1, document.SelectionLength); - return; - } + // get the TabbedDocumentSpellCheck class instance.. + var spellCheck = (TabbedDocumentSpellCheck) document.Tag0; - FormDialogQuerySortTextStyle.ShowDialog(this, document.Scintilla, this); - }); - } + // check the document's spelling.. + spellCheck.DoSpellCheck(); + } + }); + tmSpellCheck.Enabled = true; // enabled the timer.. + } - // a timer to run a spell check for a Scintilla document if it has - // been changed and the user has been idle for the timer's interval.. - private void TmSpellCheck_Tick(object sender, EventArgs e) + // a user wishes to temporarily disable or enable the spell checking of the current document.. + private void TsbSpellCheck_Click(object sender, EventArgs e) + { + // set the state of the spell checking functionality.. + SetSpellCheckerState(((ToolStripButton) sender).Checked, false); + } + + // a user wishes to wrap the text to a specific line length.. + private void MnuWrapDocumentTo_Click(object sender, EventArgs e) + { + // query the line length.. + int wrapSize = FormDialogQueryNumber.Execute(72,50, 150, + DBLangEngine.GetMessage("msgWrapText", + "Wrap text|A message describing that some kind of wrapping is going to be done to some text"), + DBLangEngine.GetMessage("msgWrapTextToLength", + "Wrap text to length:|A message describing that a text should be wrapped so the its lines have a specified maximum length")); + + // if the user accepted the dialog, wrap either the selection or the whole document.. + if (wrapSize != default) { - tmSpellCheck.Enabled = false; // disable the timer.. - CurrentDocumentAction(document => + CurrentScintillaAction(scintilla => { - // validate that the ScintillaTabbedDocument instance has a spell checker attached to it.. - if (document.Tag0 != null && - document.Tag0.GetType() == typeof(TabbedDocumentSpellCheck)) + if (scintilla.SelectedText.Length > 0) { - // get the TabbedDocumentSpellCheck class instance.. - var spellCheck = (TabbedDocumentSpellCheck) document.Tag0; - - // check the document's spelling.. - spellCheck.DoSpellCheck(); + scintilla.ReplaceSelection(WordWrapToSize.Wrap(scintilla.SelectedText, wrapSize)); + } + else + { + scintilla.Text = WordWrapToSize.Wrap(scintilla.Text, wrapSize); } }); - tmSpellCheck.Enabled = true; // enabled the timer.. } + } - // a user wishes to temporarily disable or enable the spell checking of the current document.. - private void TsbSpellCheck_Click(object sender, EventArgs e) - { - // set the state of the spell checking functionality.. - SetSpellCheckerState(((ToolStripButton) sender).Checked, false); - } + private void FormSearchResultTree_RequestDockReleaseMainForm(object sender, EventArgs e) + { + var dockForm = (FormSearchResultTree)sender; + pnDock.Controls.Remove(dockForm); + dockForm.Close(); + } - // a user wishes to wrap the text to a specific line length.. - private void MnuWrapDocumentTo_Click(object sender, EventArgs e) - { - // query the line length.. - int wrapSize = FormDialogQueryNumber.Execute(72,50, 150, - DBLangEngine.GetMessage("msgWrapText", - "Wrap text|A message describing that some kind of wrapping is going to be done to some text"), - DBLangEngine.GetMessage("msgWrapTextToLength", - "Wrap text to length:|A message describing that a text should be wrapped so the its lines have a specified maximum length")); + private void FormSearchResultTree_RequestDockMainForm(object sender, EventArgs e) + { + // no docking if disabled.. + if (!FormSettings.Settings.DockSearchTreeForm) + { + return; + } + + var dockForm = (FormSearchResultTree)sender; + dockForm.TopLevel = false; + dockForm.AutoScroll = true; + dockForm.FormBorderStyle = FormBorderStyle.None; + dockForm.Location = new Point(0, 0); + dockForm.Width = pnDock.Width; + dockForm.Height = Height * 15 / 100; + dockForm.IsDocked = true; + pnDock.Controls.Add(dockForm); + //dockForm.Dock = DockStyle.Fill; + dockForm.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + } - // if the user accepted the dialog, wrap either the selection or the whole document.. - if (wrapSize != default) + private void FormSearchResultTreeSearchResultSelected(object sender, SearchResultTreeViewClickEventArgs e) + { + // check if the file is opened in the editor.. + if (e.SearchResult.isFileOpen) + { + int idx = sttcMain.Documents.FindIndex(f => f.FileName == e.SearchResult.fileName); + if (idx != -1) { - CurrentScintillaAction(scintilla => - { - if (scintilla.SelectedText.Length > 0) - { - scintilla.ReplaceSelection(WordWrapToSize.Wrap(scintilla.SelectedText, wrapSize)); - } - else - { - scintilla.Text = WordWrapToSize.Wrap(scintilla.Text, wrapSize); - } - }); + sttcMain.ActivateDocument(idx); + var scintilla = sttcMain.Documents[idx].Scintilla; + scintilla.GotoPosition(e.SearchResult.startLocation); + scintilla.CurrentPosition = e.SearchResult.startLocation; + scintilla.SetSelection(e.SearchResult.startLocation, e.SearchResult.startLocation + e.SearchResult.length); + Focus(); } } + else if (!e.SearchResult.isFileOpen) + { + OpenDocument(e.SearchResult.fileName, DefaultEncodings, false, false); + var scintilla = sttcMain.LastAddedDocument?.Scintilla; + if (scintilla != null) + { + scintilla.GotoPosition(e.SearchResult.startLocation); + scintilla.CurrentPosition = e.SearchResult.startLocation; + scintilla.SetSelection(e.SearchResult.startLocation, e.SearchResult.startLocation + e.SearchResult.length); - private void FormSearchResultTree_RequestDockReleaseMainForm(object sender, EventArgs e) - { - var dockForm = (FormSearchResultTree)sender; - pnDock.Controls.Remove(dockForm); - dockForm.Close(); + var formSearchResultTree = (FormSearchResultTree) sender; + formSearchResultTree.SetFileOpened(e.SearchResult.fileName, true); + Focus(); + } } + } - private void FormSearchResultTree_RequestDockMainForm(object sender, EventArgs e) + // the search and replace dialog is requesting for documents opened on this main form.. + private void InstanceRequestDocuments(object sender, ScintillaDocumentEventArgs e) + { + if (e.RequestAllDocuments) { - // no docking if disabled.. - if (!FormSettings.Settings.DockSearchTreeForm) - { - return; - } - - var dockForm = (FormSearchResultTree)sender; - dockForm.TopLevel = false; - dockForm.AutoScroll = true; - dockForm.FormBorderStyle = FormBorderStyle.None; - dockForm.Location = new Point(0, 0); - dockForm.Width = pnDock.Width; - dockForm.Height = Height * 15 / 100; - dockForm.IsDocked = true; - pnDock.Controls.Add(dockForm); - //dockForm.Dock = DockStyle.Fill; - dockForm.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + e.Documents = sttcMain.Documents.Select(f => (f.Scintilla, f.FileName)).ToList(); } - - private void FormSearchResultTreeSearchResultSelected(object sender, SearchResultTreeViewClickEventArgs e) + else if (sttcMain.CurrentDocument != null) { - // check if the file is opened in the editor.. - if (e.SearchResult.isFileOpen) - { - int idx = sttcMain.Documents.FindIndex(f => f.FileName == e.SearchResult.fileName); - if (idx != -1) - { - sttcMain.ActivateDocument(idx); - var scintilla = sttcMain.Documents[idx].Scintilla; - scintilla.GotoPosition(e.SearchResult.startLocation); - scintilla.CurrentPosition = e.SearchResult.startLocation; - scintilla.SetSelection(e.SearchResult.startLocation, e.SearchResult.startLocation + e.SearchResult.length); - Focus(); - } - } - else if (!e.SearchResult.isFileOpen) - { - OpenDocument(e.SearchResult.fileName, DefaultEncodings, false, false); - var scintilla = sttcMain.LastAddedDocument?.Scintilla; - if (scintilla != null) - { - scintilla.GotoPosition(e.SearchResult.startLocation); - scintilla.CurrentPosition = e.SearchResult.startLocation; - scintilla.SetSelection(e.SearchResult.startLocation, e.SearchResult.startLocation + e.SearchResult.length); - - var formSearchResultTree = (FormSearchResultTree) sender; - formSearchResultTree.SetFileOpened(e.SearchResult.fileName, true); - Focus(); - } - } + e.Documents.Add((sttcMain.CurrentDocument.Scintilla, sttcMain.CurrentDocument.FileName)); } + } - // the search and replace dialog is requesting for documents opened on this main form.. - private void InstanceRequestDocuments(object sender, ScintillaDocumentEventArgs e) - { - if (e.RequestAllDocuments) - { - e.Documents = sttcMain.Documents.Select(f => (f.Scintilla, f.FileName)).ToList(); + // a user wishes to manage sessions used by the software.. + private void mnuManageSessions_Click(object sender, EventArgs e) + { + // display the session management dialog.. + FormDialogSessionManage.Execute(); + + // re-create the current session menu.. + SessionMenuBuilder.CreateSessionMenu(mnuSession, CurrentSession); + + // re-create a menu for recent files.. + RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); + } + + /// + /// Tries catch an event crashing the whole application if the error is causes by a plug-in. + /// + public static Action ModuleExceptionHandler { get; set; } + + // checks if file selected in the open file dialog requires elevation and the file exists.. + private void odAnyFile_FileOk(object sender, System.ComponentModel.CancelEventArgs e) + { + if (FileIoPermission.FileRequiresElevation(odAnyFile.FileName).ElevationRequied) + { + if (MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgElevationRequiredForFile", + "Opening the file '{0}' requires elevation (Run as Administrator). Restart the software as Administrator?|A message describing that a access to a file requires elevated permissions (Administrator)", odAnyFile.FileName), + DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog."), + MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2) == DialogResultExtended.Yes) + { + e.Cancel = true; + Program.ElevateFile = odAnyFile.FileName; + Program.RestartElevated = true; + EndSession(true); } - else if (sttcMain.CurrentDocument != null) + else { - e.Documents.Add((sttcMain.CurrentDocument.Scintilla, sttcMain.CurrentDocument.FileName)); + e.Cancel = true; } } - - // a user wishes to manage sessions used by the software.. - private void mnuManageSessions_Click(object sender, EventArgs e) + else { - // display the session management dialog.. - FormDialogSessionManage.Execute(); - - // re-create the current session menu.. - SessionMenuBuilder.CreateSessionMenu(mnuSession, CurrentSession); - - // re-create a menu for recent files.. - RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); + e.Cancel = !File.Exists(odAnyFile.FileName); } + } - /// - /// Tries catch an event crashing the whole application if the error is causes by a plug-in. - /// - public static Action ModuleExceptionHandler { get; set; } + // the user is either logging of from the system or is shutting down the system.. + private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) + { + // log the session ending.. + ExceptionLogger.LogMessage("The Windows session is ending --> save with no questions asked."); - // checks if file selected in the open file dialog requires elevation and the file exists.. - private void odAnyFile_FileOk(object sender, System.ComponentModel.CancelEventArgs e) + // end the without any user interaction/dialog.. + EndSession(true); + } + + // a user wishes to open a recent file.. + private void RecentFilesMenuBuilder_RecentFileMenuClicked(object sender, RecentFilesMenuClickEventArgs e) + { + // if a file snapshot exists in the database then load it.. + if (e.RecentFile.ExistsInDatabase(ScriptNotepadDbContext.DbContext.FileSaves)) { - if (FileIoPermission.FileRequiresElevation(odAnyFile.FileName).ElevationRequied) + LoadDocumentFromDatabase(e.RecentFile); + } + // else open the file from the file system.. + else if (e.RecentFile != null) + { + OpenDocument(e.RecentFile.FileName, EncodingData.EncodingFromString(e.RecentFile.EncodingAsString), + false, false); + } + // in this case the menu item should contain all the recent files belonging to a session.. + else if (e.RecentFiles != null) + { + // loop through the recent files and open them all.. + foreach (var recentFile in e.RecentFiles) { - if (MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgElevationRequiredForFile", - "Opening the file '{0}' requires elevation (Run as Administrator). Restart the software as Administrator?|A message describing that a access to a file requires elevated permissions (Administrator)", odAnyFile.FileName), - DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog."), - MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2) == DialogResultExtended.Yes) + // if a file snapshot exists in the database then load it.. + if (recentFile.ExistsInDatabase(ScriptNotepadDbContext.DbContext.FileSaves)) { - e.Cancel = true; - Program.ElevateFile = odAnyFile.FileName; - Program.RestartElevated = true; - EndSession(true); + LoadDocumentFromDatabase(recentFile); } + // else open the file from the file system.. else { - e.Cancel = true; + OpenDocument(recentFile.FileNameFull, + EncodingData.EncodingFromString(recentFile.EncodingAsString), false, false); } } - else - { - e.Cancel = !File.Exists(odAnyFile.FileName); - } } + } - // the user is either logging of from the system or is shutting down the system.. - private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) - { - // log the session ending.. - ExceptionLogger.LogMessage("The Windows session is ending --> save with no questions asked."); + /// + /// Loads the document from the database based on a given class instance. + /// + /// A class instance containing the file data. + private void LoadDocumentFromDatabase(RecentFile recentFile) + { + // get the file from the database.. + var file = ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => + f.FileNameFull == recentFile.FileNameFull && f.Session.SessionName == recentFile.Session.SessionName); - // end the without any user interaction/dialog.. - EndSession(true); - } - - // a user wishes to open a recent file.. - private void RecentFilesMenuBuilder_RecentFileMenuClicked(object sender, RecentFilesMenuClickEventArgs e) + // only if something was gotten from the database.. + if (file != null) { - // if a file snapshot exists in the database then load it.. - if (e.RecentFile.ExistsInDatabase(ScriptNotepadDbContext.DbContext.FileSaves)) - { - LoadDocumentFromDatabase(e.RecentFile); - } - // else open the file from the file system.. - else if (e.RecentFile != null) - { - OpenDocument(e.RecentFile.FileName, EncodingData.EncodingFromString(e.RecentFile.EncodingAsString), - false, false); - } - // in this case the menu item should contain all the recent files belonging to a session.. - else if (e.RecentFiles != null) + if (!FormSettings.Settings.EditorSaveZoom) { - // loop through the recent files and open them all.. - foreach (var recentFile in e.RecentFiles) - { - // if a file snapshot exists in the database then load it.. - if (recentFile.ExistsInDatabase(ScriptNotepadDbContext.DbContext.FileSaves)) - { - LoadDocumentFromDatabase(recentFile); - } - // else open the file from the file system.. - else - { - OpenDocument(recentFile.FileNameFull, - EncodingData.EncodingFromString(recentFile.EncodingAsString), false, false); - } - } + file.EditorZoomPercentage = 100; } - } - - /// - /// Loads the document from the database based on a given class instance. - /// - /// A class instance containing the file data. - private void LoadDocumentFromDatabase(RecentFile recentFile) - { - // get the file from the database.. - var file = ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => - f.FileNameFull == recentFile.FileNameFull && f.Session.SessionName == recentFile.Session.SessionName); - // only if something was gotten from the database.. - if (file != null) + sttcMain.AddDocument(file.FileNameFull, file.Id, file.GetEncoding(), file.GetFileContentsAsMemoryStream()); + if (sttcMain.LastAddedDocument != null) { - if (!FormSettings.Settings.EditorSaveZoom) - { - file.EditorZoomPercentage = 100; - } + // append additional initialization to the document.. + AdditionalInitializeDocument(sttcMain.LastAddedDocument); - sttcMain.AddDocument(file.FileNameFull, file.Id, file.GetEncoding(), file.GetFileContentsAsMemoryStream()); - if (sttcMain.LastAddedDocument != null) - { - // append additional initialization to the document.. - AdditionalInitializeDocument(sttcMain.LastAddedDocument); - - // set the lexer type from the saved database value.. - sttcMain.LastAddedDocument.LexerType = file.LexerType; + // set the lexer type from the saved database value.. + sttcMain.LastAddedDocument.LexerType = file.LexerType; - // not history any more.. - file.IsHistory = false; + // not history any more.. + file.IsHistory = false; - // set the saved position of the document's caret.. - if (file.CurrentCaretPosition > 0 && file.CurrentCaretPosition < sttcMain.LastAddedDocument.Scintilla.TextLength) - { - sttcMain.LastAddedDocument.Scintilla.CurrentPosition = file.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.SelectionStart = file.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.SelectionEnd = file.CurrentCaretPosition; - sttcMain.LastAddedDocument.Scintilla.ScrollCaret(); - sttcMain.LastAddedDocument.FileTabButton.IsSaved = !IsFileChanged(file); - } + // set the saved position of the document's caret.. + if (file.CurrentCaretPosition > 0 && file.CurrentCaretPosition < sttcMain.LastAddedDocument.Scintilla.TextLength) + { + sttcMain.LastAddedDocument.Scintilla.CurrentPosition = file.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.SelectionStart = file.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.SelectionEnd = file.CurrentCaretPosition; + sttcMain.LastAddedDocument.Scintilla.ScrollCaret(); + sttcMain.LastAddedDocument.FileTabButton.IsSaved = !IsFileChanged(file); + } - sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; + sttcMain.LastAddedDocument.Scintilla.TabWidth = FormSettings.Settings.EditorTabWidth; - // update the history flag to the database.. - ScriptNotepadDbContext.DbContext.SaveChanges(); + // update the history flag to the database.. + ScriptNotepadDbContext.DbContext.SaveChanges(); - // assign the context menu strip for the tabbed document.. - sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; + // assign the context menu strip for the tabbed document.. + sttcMain.LastAddedDocument.FileTabButton.ContextMenuStrip = cmsFileTab; - // set the zoom value.. - sttcMain.LastAddedDocument.ZoomPercentage = file.EditorZoomPercentage; + // set the zoom value.. + sttcMain.LastAddedDocument.ZoomPercentage = file.EditorZoomPercentage; - // enabled the caret line background color.. - SetCaretLineColor(); + // enabled the caret line background color.. + SetCaretLineColor(); - // set the brace matching if enabled.. - SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); + // set the brace matching if enabled.. + SetStyleBraceMatch.SetStyle(sttcMain.LastAddedDocument.Scintilla); - sttcMain.LastAddedDocument.Tag = file; + sttcMain.LastAddedDocument.Tag = file; - // the file load can't add an undo option the Scintilla.. - sttcMain.LastAddedDocument.Scintilla.EmptyUndoBuffer(); + // the file load can't add an undo option the Scintilla.. + sttcMain.LastAddedDocument.Scintilla.EmptyUndoBuffer(); - // ReSharper disable once ObjectCreationAsStatement - new TabbedDocumentSpellCheck(sttcMain.LastAddedDocument, !FormSettings.Settings.EditorSpellUseCustomDictionary); + // ReSharper disable once ObjectCreationAsStatement + new TabbedDocumentSpellCheck(sttcMain.LastAddedDocument, !FormSettings.Settings.EditorSpellUseCustomDictionary); - // set the misc indicators.. - SetDocumentMiscIndicators(sttcMain.LastAddedDocument); - } - sttcMain.ActivateDocument(file.FileNameFull); + // set the misc indicators.. + SetDocumentMiscIndicators(sttcMain.LastAddedDocument); + } + sttcMain.ActivateDocument(file.FileNameFull); - UpdateToolbarButtonsAndMenuItems(); + UpdateToolbarButtonsAndMenuItems(); - // re-create a menu for recent files.. - RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); - } + // re-create a menu for recent files.. + RecentFilesMenuBuilder.CreateRecentFilesMenu(mnuRecentFiles, CurrentSession, HistoryListAmount, true, mnuSplit2); } + } - // a user wishes to change the settings of the software.. - private void mnuSettings_Click(object sender, EventArgs e) + // a user wishes to change the settings of the software.. + private void mnuSettings_Click(object sender, EventArgs e) + { + // ..so display the settings dialog.. + if (FormSettings.Execute(out var restart)) { - // ..so display the settings dialog.. - if (FormSettings.Execute(out var restart)) + // if the user chose to restart the application for the changes to take affect.. + if (restart) { - // if the user chose to restart the application for the changes to take affect.. - if (restart) - { - Program.Restart = true; - Close(); - } + Program.Restart = true; + Close(); } } + } - /// Processes a command key. - /// A , passed by reference, that represents the Win32 message to process. - /// One of the values that represents the key to process. - /// - /// - /// - /// true - /// True - /// true - /// - /// - /// - /// true (True in Visual Basic) if the keystroke was processed and consumed by the control; otherwise, falseFalsefalsefalse (False in Visual Basic) to allow further processing. - /// - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) - { - // somehow the software main form doesn't register keyboard keys of AltGr+2, AltGr+3, AltGr+4 on a finnish keyboard - // so bypass it by the hard way.. - if (FormSettings.Settings.SimulateAltGrKey && FormSettings.Settings.SimulateAltGrKeyIndex == 0) + /// Processes a command key. + /// A , passed by reference, that represents the Win32 message to process. + /// One of the values that represents the key to process. + /// + /// + /// + /// true + /// True + /// true + /// + /// + /// + /// true (True in Visual Basic) if the keystroke was processed and consumed by the control; otherwise, falseFalsefalsefalse (False in Visual Basic) to allow further processing. + /// + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + // somehow the software main form doesn't register keyboard keys of AltGr+2, AltGr+3, AltGr+4 on a finnish keyboard + // so bypass it by the hard way.. + if (FormSettings.Settings.SimulateAltGrKey && FormSettings.Settings.SimulateAltGrKeyIndex == 0) + { + // something in the main form is capturing the "ALT GR" key - which at least in Finland is used to type few + // necessary characters such as '@', '£' and '$', so make the software do this.. + if (keyData == (Keys.Control | Keys.Alt | Keys.D2)) { - // something in the main form is capturing the "ALT GR" key - which at least in Finland is used to type few - // necessary characters such as '@', '£' and '$', so make the software do this.. - if (keyData == (Keys.Control | Keys.Alt | Keys.D2)) - { - // the at sign ('@').. - CurrentScintillaAction(scintilla => { scintilla.ReplaceSelection("@"); }); - return true; - } - - // the pound sign ('£').. - if (keyData == (Keys.Control | Keys.Alt | Keys.D3)) - { - CurrentScintillaAction(scintilla => { scintilla.ReplaceSelection("£"); }); - return true; - } - - // the dollar sign ('$').. - if (keyData == (Keys.Control | Keys.Alt | Keys.D4)) - { - CurrentScintillaAction(scintilla => { scintilla.ReplaceSelection("$"); }); - return true; - } + // the at sign ('@').. + CurrentScintillaAction(scintilla => { scintilla.ReplaceSelection("@"); }); + return true; } - return base.ProcessCmdKey(ref msg, keyData); - } - - private void FormMain_KeyUp(object sender, KeyEventArgs e) - { - if (e.KeyCodeIn(Keys.Up, Keys.Down, Keys.Left, Keys.Right, Keys.PageDown, Keys.PageUp)) + // the pound sign ('£').. + if (keyData == (Keys.Control | Keys.Alt | Keys.D3)) { - // release the flag which suspends the selection update to avoid excess CPU load.. - suspendSelectionUpdate = false; - StatusStripTexts.SetStatusStringText(sttcMain.CurrentDocument, CurrentSession.SessionName); + CurrentScintillaAction(scintilla => { scintilla.ReplaceSelection("£"); }); + return true; } - if ( - // a user pressed a keyboard combination of CTRL+Z, which indicates undo for - // the Scintilla control.. - e.KeyCode == Keys.Z && e.OnlyControl() || - // a user pressed a keyboard combination of CTRL+Y, which indicates redo for - // the Scintilla control.. - e.KeyCode == Keys.Y && e.OnlyControl()) + // the dollar sign ('$').. + if (keyData == (Keys.Control | Keys.Alt | Keys.D4)) { - // if there is an active document.. - CurrentDocumentAction(document => - { - // ..then if the undo is possible.. - if (!document.Scintilla.CanUndo) - { - // get a FileSave class instance from the document's tag.. - var fileSave = (FileSave) document.Tag; - - if (e.KeyCode == Keys.Z) - { - // undo the encoding change.. - fileSave.UndoEncodingChange(); - document.Tag = fileSave; - } - - fileSave.PopPreviousDbModified(); - document.FileTabButton.IsSaved = !IsFileChanged(fileSave); - } - }); - - UpdateToolbarButtonsAndMenuItems(); + CurrentScintillaAction(scintilla => { scintilla.ReplaceSelection("$"); }); + return true; } } - private void sttcMain_DocumentMouseDown(object sender, MouseEventArgs e) - { - // set the flag to suspend the selection update to avoid excess CPU load.. - suspendSelectionUpdate = true; - } + return base.ProcessCmdKey(ref msg, keyData); + } - private void sttcMain_DocumentMouseUp(object sender, MouseEventArgs e) + private void FormMain_KeyUp(object sender, KeyEventArgs e) + { + if (e.KeyCodeIn(Keys.Up, Keys.Down, Keys.Left, Keys.Right, Keys.PageDown, Keys.PageUp)) { // release the flag which suspends the selection update to avoid excess CPU load.. suspendSelectionUpdate = false; StatusStripTexts.SetStatusStringText(sttcMain.CurrentDocument, CurrentSession.SessionName); } - // this event is raised when another instance of this application receives a file name - // via the IPC (no multiple instance allowed).. - private void RemoteMessage_MessageReceived(object sender, IpcExchangeEventArgs e) - { - Invoke(new MethodInvoker(delegate - { - OpenDocument(e.Object, DefaultEncodings, - false, false, false, true); - // the user probably will like the program to show up, if the software activates - // it self from a windows shell call to open a file.. - if (WindowState == FormWindowState.Minimized) - { - WindowState = previousWindowState; - } - BringToFront(); - Activate(); - })); - } - - // a user wanted to create a new file.. - private void tsbNew_Click(object sender, EventArgs e) - { - NewDocument(); - } - - // the user wishes to manage the script snippets in the database.. - private void mnuManageScriptSnippets_Click(object sender, EventArgs e) - { - // ..so display the dialog.. - FormDialogScriptLoad.Execute(true); - } - - // fold the current level.. - private void mnuFoldCurrentLevel_Click(object sender, EventArgs e) + if ( + // a user pressed a keyboard combination of CTRL+Z, which indicates undo for + // the Scintilla control.. + e.KeyCode == Keys.Z && e.OnlyControl() || + // a user pressed a keyboard combination of CTRL+Y, which indicates redo for + // the Scintilla control.. + e.KeyCode == Keys.Y && e.OnlyControl()) { + // if there is an active document.. CurrentDocumentAction(document => { - if (document.Scintilla.CurrentLine != -1) + // ..then if the undo is possible.. + if (!document.Scintilla.CanUndo) { - var parent = document.Scintilla.Lines[document.Scintilla.CurrentLine].FoldParent; - if (parent >= 0) + // get a FileSave class instance from the document's tag.. + var fileSave = (FileSave) document.Tag; + + if (e.KeyCode == Keys.Z) { - document.Scintilla.Lines[parent].FoldLine(sender.Equals(mnuFoldCurrentLevel) ? FoldAction.Contract : FoldAction.Expand); + // undo the encoding change.. + fileSave.UndoEncodingChange(); + document.Tag = fileSave; } + + fileSave.PopPreviousDbModified(); + document.FileTabButton.IsSaved = !IsFileChanged(fileSave); } }); + + UpdateToolbarButtonsAndMenuItems(); } + } + + private void sttcMain_DocumentMouseDown(object sender, MouseEventArgs e) + { + // set the flag to suspend the selection update to avoid excess CPU load.. + suspendSelectionUpdate = true; + } - // fold a specified level.. - private void mnuFold1_Click(object sender, EventArgs e) + private void sttcMain_DocumentMouseUp(object sender, MouseEventArgs e) + { + // release the flag which suspends the selection update to avoid excess CPU load.. + suspendSelectionUpdate = false; + StatusStripTexts.SetStatusStringText(sttcMain.CurrentDocument, CurrentSession.SessionName); + } + + // this event is raised when another instance of this application receives a file name + // via the IPC (no multiple instance allowed).. + private void RemoteMessage_MessageReceived(object sender, IpcExchangeEventArgs e) + { + Invoke(new MethodInvoker(delegate { - var level = 1; - if (sender.Equals(mnuFold2)) + OpenDocument(e.Object, DefaultEncodings, + false, false, false, true); + // the user probably will like the program to show up, if the software activates + // it self from a windows shell call to open a file.. + if (WindowState == FormWindowState.Minimized) { - level = 2; + WindowState = previousWindowState; } - else if (sender.Equals(mnuFold3)) - { - level = 3; - } - else if (sender.Equals(mnuFold4)) + BringToFront(); + Activate(); + })); + } + + // a user wanted to create a new file.. + private void tsbNew_Click(object sender, EventArgs e) + { + NewDocument(); + } + + // the user wishes to manage the script snippets in the database.. + private void mnuManageScriptSnippets_Click(object sender, EventArgs e) + { + // ..so display the dialog.. + FormDialogScriptLoad.Execute(true); + } + + // fold the current level.. + private void mnuFoldCurrentLevel_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => + { + if (document.Scintilla.CurrentLine != -1) { - level = 4; - } - else if (sender.Equals(mnuFold5)) - { - level = 5; - } - else if (sender.Equals(mnuFold6)) - { - level = 6; - } - else if (sender.Equals(mnuFold7)) - { - level = 7; - } - else if (sender.Equals(mnuFold8)) - { - level = 8; + var parent = document.Scintilla.Lines[document.Scintilla.CurrentLine].FoldParent; + if (parent >= 0) + { + document.Scintilla.Lines[parent].FoldLine(sender.Equals(mnuFoldCurrentLevel) ? FoldAction.Contract : FoldAction.Expand); + } } + }); + } - CurrentDocumentAction(document => - { - if (document.Scintilla.CurrentLine != -1) - { - foreach (var scintillaLine in document.Scintilla.Lines) - { - if (scintillaLine.FoldLevel - 1023 == level) - { - scintillaLine.FoldLine(FoldAction.Contract); - } - } - } - }); + // fold a specified level.. + private void mnuFold1_Click(object sender, EventArgs e) + { + var level = 1; + if (sender.Equals(mnuFold2)) + { + level = 2; + } + else if (sender.Equals(mnuFold3)) + { + level = 3; + } + else if (sender.Equals(mnuFold4)) + { + level = 4; + } + else if (sender.Equals(mnuFold5)) + { + level = 5; + } + else if (sender.Equals(mnuFold6)) + { + level = 6; + } + else if (sender.Equals(mnuFold7)) + { + level = 7; + } + else if (sender.Equals(mnuFold8)) + { + level = 8; } - // unfold a specified level.. - private void mnuUnfold1_Click(object sender, EventArgs e) + CurrentDocumentAction(document => { - var level = 1; - if (sender.Equals(mnuUnfold2)) - { - level = 2; - } - else if (sender.Equals(mnuUnfold3)) - { - level = 3; - } - else if (sender.Equals(mnuUnfold4)) - { - level = 4; - } - else if (sender.Equals(mnuUnfold5)) - { - level = 5; - } - else if (sender.Equals(mnuUnfold6)) - { - level = 6; - } - else if (sender.Equals(mnuUnfold7)) - { - level = 7; - } - else if (sender.Equals(mnuUnfold8)) - { - level = 8; - } - - CurrentDocumentAction(document => + if (document.Scintilla.CurrentLine != -1) { - if (document.Scintilla.CurrentLine != -1) + foreach (var scintillaLine in document.Scintilla.Lines) { - foreach (var scintillaLine in document.Scintilla.Lines) + if (scintillaLine.FoldLevel - 1023 == level) { - if (scintillaLine.FoldLevel - 1023 == level) - { - scintillaLine.FoldLine(FoldAction.Expand); - } + scintillaLine.FoldLine(FoldAction.Contract); } } - }); - } + } + }); + } - // a user wanted to find or find and replace something of the active document.. - private void mnuFind_Click(object sender, EventArgs e) + // unfold a specified level.. + private void mnuUnfold1_Click(object sender, EventArgs e) + { + var level = 1; + if (sender.Equals(mnuUnfold2)) { - FormSearchAndReplace.ShowSearch(this, SearchString); + level = 2; } - - // a user wanted to find or find and replace something of the active document.. - private void MnuReplace_Click(object sender, EventArgs e) + else if (sender.Equals(mnuUnfold3)) { - FormSearchAndReplace.ShowReplace(this, SearchString); + level = 3; } - - // a user wanted to find or find and replace something in a defined set of files.. - private void MnuFindInFiles_Click(object sender, EventArgs e) + else if (sender.Equals(mnuUnfold4)) { - FormSearchAndReplace.ShowFindInFiles(this, SearchString); + level = 4; } - - // a user wanted to find and mark words of the current document.. - private void MnuMarkText_Click(object sender, EventArgs e) + else if (sender.Equals(mnuUnfold5)) { - FormSearchAndReplace.ShowMarkMatches(this, SearchString); + level = 5; } - - private void FormMain_FormClosing(object sender, FormClosingEventArgs e) + else if (sender.Equals(mnuUnfold6)) { - // save the changes into the database.. - ScriptNotepadDbContext.DbContext.SaveChanges(); + level = 6; + } + else if (sender.Equals(mnuUnfold7)) + { + level = 7; + } + else if (sender.Equals(mnuUnfold8)) + { + level = 8; + } + + CurrentDocumentAction(document => + { + if (document.Scintilla.CurrentLine != -1) + { + foreach (var scintillaLine in document.Scintilla.Lines) + { + if (scintillaLine.FoldLevel - 1023 == level) + { + scintillaLine.FoldLine(FoldAction.Expand); + } + } + } + }); + } + + // a user wanted to find or find and replace something of the active document.. + private void mnuFind_Click(object sender, EventArgs e) + { + FormSearchAndReplace.ShowSearch(this, SearchString); + } + + // a user wanted to find or find and replace something of the active document.. + private void MnuReplace_Click(object sender, EventArgs e) + { + FormSearchAndReplace.ShowReplace(this, SearchString); + } - // save the possible setting changes.. - FormSettings.Settings.Save(Program.SettingFileName); + // a user wanted to find or find and replace something in a defined set of files.. + private void MnuFindInFiles_Click(object sender, EventArgs e) + { + FormSearchAndReplace.ShowFindInFiles(this, SearchString); + } - // disable the timers not mess with application exit.. - tmAutoSave.Enabled = false; - tmGUI.Enabled = false; - tmSpellCheck.Enabled = false; + // a user wanted to find and mark words of the current document.. + private void MnuMarkText_Click(object sender, EventArgs e) + { + FormSearchAndReplace.ShowMarkMatches(this, SearchString); + } - Instance = null; + private void FormMain_FormClosing(object sender, FormClosingEventArgs e) + { + // save the changes into the database.. + ScriptNotepadDbContext.DbContext.SaveChanges(); - // unsubscribe the external event handlers and dispose of the items created by other classes.. - DisposeExternal(); - } + // save the possible setting changes.. + FormSettings.Settings.Save(Program.SettingFileName); - // if the form is closing, save the snapshots of the open documents to the SQLite database.. - private void FormMain_FormClosed(object sender, FormClosedEventArgs e) - { - EndSession(false); - } + // disable the timers not mess with application exit.. + tmAutoSave.Enabled = false; + tmGUI.Enabled = false; + tmSpellCheck.Enabled = false; + + Instance = null; + + // unsubscribe the external event handlers and dispose of the items created by other classes.. + DisposeExternal(); + } - /// - /// Gets or sets a value indicating whether the text of the Scintilla changed via changing the encoding. - /// - private bool TextChangedViaEncodingChange { get; set; } + // if the form is closing, save the snapshots of the open documents to the SQLite database.. + private void FormMain_FormClosed(object sender, FormClosedEventArgs e) + { + EndSession(false); + } + + /// + /// Gets or sets a value indicating whether the text of the Scintilla changed via changing the encoding. + /// + private bool TextChangedViaEncodingChange { get; set; } - /// - /// A common method to change or convert the encoding of the active document. - /// - /// The encoding to change or convert into. - /// In case of Unicode (UTF8, Unicode or UTF32) whether to fail on invalid characters. - internal void ChangeDocumentEncoding(Encoding encoding, bool unicodeFailInvalidCharacters) + /// + /// A common method to change or convert the encoding of the active document. + /// + /// The encoding to change or convert into. + /// In case of Unicode (UTF8, Unicode or UTF32) whether to fail on invalid characters. + internal void ChangeDocumentEncoding(Encoding encoding, bool unicodeFailInvalidCharacters) + { + if (encoding != null) { - if (encoding != null) + // if there is an active document.. + if (sttcMain.CurrentDocument != null) { - // if there is an active document.. - if (sttcMain.CurrentDocument != null) + // get the FileSave class instance from the tag.. + var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; + if (fileSave.ExistsInFileSystem) // the file exists in the file system.. { - // get the FileSave class instance from the tag.. - var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; - if (fileSave.ExistsInFileSystem) // the file exists in the file system.. + // if the file has been changed in the editor, so confirm the user for a + // reload from the file system.. + if (fileSave.IsChangedInEditor() && !runningConstructor) { - // if the file has been changed in the editor, so confirm the user for a - // reload from the file system.. - if (fileSave.IsChangedInEditor() && !runningConstructor) - { - if (MessageBoxExtended.Show( + if (MessageBoxExtended.Show( DBLangEngine.GetMessage("msgFileHasChangedInEditorAction", "The file '{0}' has been changed in the editor and a reload from the file system is required. Continue?|A file has been changed in the editor and a reload from the file system is required to complete an arbitrary action", fileSave.FileNameFull), DBLangEngine.GetMessage("msgFileArbitraryFileChange", "A file has been changed|A caption message for a message dialog which will ask if a changed file should be reloaded"), MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2) == DialogResultExtended.No) - { - return; // the user decided not to reload.. - } + { + return; // the user decided not to reload.. } + } - fileSave.SetEncoding(encoding); // set the new encoding.. + fileSave.SetEncoding(encoding); // set the new encoding.. - // reload the file with the user given encoding.. - fileSave.ReloadFromDisk(sttcMain.CurrentDocument); + // reload the file with the user given encoding.. + fileSave.ReloadFromDisk(sttcMain.CurrentDocument); - // save the FileSave instance to the document's Tag property.. - sttcMain.CurrentDocument.Tag = fileSave; - } - // the file only exists in the database.. - else - { - // convert the contents to a new encoding.. - sttcMain.CurrentDocument.Scintilla.Text = - StreamStringHelpers.ConvertEncoding(fileSave.GetEncoding(), encoding, sttcMain.CurrentDocument.Scintilla.Text); + // save the FileSave instance to the document's Tag property.. + sttcMain.CurrentDocument.Tag = fileSave; + } + // the file only exists in the database.. + else + { + // convert the contents to a new encoding.. + sttcMain.CurrentDocument.Scintilla.Text = + StreamStringHelpers.ConvertEncoding(fileSave.GetEncoding(), encoding, sttcMain.CurrentDocument.Scintilla.Text); - // save the previous encoding for an undo-possibility.. - fileSave.AddPreviousEncoding(fileSave.GetEncoding()); + // save the previous encoding for an undo-possibility.. + fileSave.AddPreviousEncoding(fileSave.GetEncoding()); - fileSave.SetEncoding(encoding); // set the new encoding.. + fileSave.SetEncoding(encoding); // set the new encoding.. - // save the FileSave instance to the document's Tag property.. - sttcMain.CurrentDocument.Tag = fileSave; - } + // save the FileSave instance to the document's Tag property.. + sttcMain.CurrentDocument.Tag = fileSave; } } } + } - // an event when user clicks the change encoding main menu.. - private void mnuCharSets_Click(object sender, EventArgs e) - { - var encoding = FormDialogQueryEncoding.Execute(out _, - out bool unicodeFailInvalidCharacters); - ChangeDocumentEncoding(encoding, unicodeFailInvalidCharacters); - } + // an event when user clicks the change encoding main menu.. + private void mnuCharSets_Click(object sender, EventArgs e) + { + var encoding = FormDialogQueryEncoding.Execute(out _, + out bool unicodeFailInvalidCharacters); + ChangeDocumentEncoding(encoding, unicodeFailInvalidCharacters); + } - // an event which is fired if an encoding menu item is clicked.. - private void CharacterSetMenuBuilder_EncodingMenuClicked(object sender, EncodingMenuClickEventArgs e) + // an event which is fired if an encoding menu item is clicked.. + private void CharacterSetMenuBuilder_EncodingMenuClicked(object sender, EncodingMenuClickEventArgs e) + { + // a user requested to change the encoding of the file.. + if (e.Data != null && e.Data.ToString() == "convert_encoding") { - // a user requested to change the encoding of the file.. - if (e.Data != null && e.Data.ToString() == "convert_encoding") - { - ChangeDocumentEncoding(e.Encoding, true); - } + ChangeDocumentEncoding(e.Encoding, true); } + } - // a user wishes to change the current session.. - private void SessionMenuBuilder_SessionMenuClicked(object sender, SessionMenuClickEventArgs e) - { - // set the current session to a new value.. - CurrentSession = e.Session; - } + // a user wishes to change the current session.. + private void SessionMenuBuilder_SessionMenuClicked(object sender, SessionMenuClickEventArgs e) + { + // set the current session to a new value.. + CurrentSession = e.Session; + } - // a user is logging of or the system is shutting down.. - private void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e) - { - // ..just no questions asked save the document snapshots into the SQLite database.. - SaveDocumentsToDatabase(); - EndSession(true); - } + // a user is logging of or the system is shutting down.. + private void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e) + { + // ..just no questions asked save the document snapshots into the SQLite database.. + SaveDocumentsToDatabase(); + EndSession(true); + } - /// - /// Gets or sets a value indicating whether the form has shown once. - /// - /// true if [form first shown]; otherwise, false. - private bool FormFirstShown { get; set; } + /// + /// Gets or sets a value indicating whether the form has shown once. + /// + /// true if [form first shown]; otherwise, false. + private bool FormFirstShown { get; set; } - // the form is shown.. - private void FormMain_Shown(object sender, EventArgs e) - { - // ..so open the files given as arguments for the program.. - OpenArgumentFiles(); + // the form is shown.. + private void FormMain_Shown(object sender, EventArgs e) + { + // ..so open the files given as arguments for the program.. + OpenArgumentFiles(); - // check for a new version from the internet.. - CheckForNewVersion(); + // check for a new version from the internet.. + CheckForNewVersion(); - FormFirstShown = true; - } + FormFirstShown = true; + } - // a user decided to save the file.. - private void munSave_Click(object sender, EventArgs e) - { - // ..so lets obey for once.. - SaveDocument(sttcMain.CurrentDocument, sender.Equals(mnuSaveAs) || sender.Equals(tsbSaveAs)); - } + // a user decided to save the file.. + private void munSave_Click(object sender, EventArgs e) + { + // ..so lets obey for once.. + SaveDocument(sttcMain.CurrentDocument, sender.Equals(mnuSaveAs) || sender.Equals(tsbSaveAs)); + } - // a user wanted to open a file via the main menu.. - private void mnuOpen_Click(object sender, EventArgs e) - { - odAnyFile.Title = DBLangEngine.GetMessage("msgDialogOpenFile", - "Open|A title for an open file dialog to indicate that a is user selecting a file to be opened"); + // a user wanted to open a file via the main menu.. + private void mnuOpen_Click(object sender, EventArgs e) + { + odAnyFile.Title = DBLangEngine.GetMessage("msgDialogOpenFile", + "Open|A title for an open file dialog to indicate that a is user selecting a file to be opened"); - odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpen; + odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpen; - // if the file dialog was accepted (i.e. OK) then open the file to the view.. - if (odAnyFile.ShowDialog() == DialogResult.OK) + // if the file dialog was accepted (i.e. OK) then open the file to the view.. + if (odAnyFile.ShowDialog() == DialogResult.OK) + { + FormSettings.Settings.FileLocationOpen = odAnyFile.InitialDirectory; + if (sender.Equals(mnuOpenNoBOM)) { - FormSettings.Settings.FileLocationOpen = odAnyFile.InitialDirectory; - if (sender.Equals(mnuOpenNoBOM)) - { - OpenDocument(odAnyFile.FileName, DefaultEncodings, true, false, true); - } - else - { - OpenDocument(odAnyFile.FileName, DefaultEncodings, false, false); - } + OpenDocument(odAnyFile.FileName, DefaultEncodings, true, false, true); + } + else + { + OpenDocument(odAnyFile.FileName, DefaultEncodings, false, false); } } + } + + // a user wanted to open a file with encoding via the main menu.. + private void mnuOpenWithEncoding_Click(object sender, EventArgs e) + { + odAnyFile.Title = DBLangEngine.GetMessage("msgDialogOpenFileWithEncoding", + "Open with encoding|A title for an open file dialog to indicate that a is user selecting a file to be opened with pre-selected encoding"); - // a user wanted to open a file with encoding via the main menu.. - private void mnuOpenWithEncoding_Click(object sender, EventArgs e) + // ask the encoding first from the user.. + Encoding encoding = FormDialogQueryEncoding.Execute(out _, out _); + if (encoding != null) { - odAnyFile.Title = DBLangEngine.GetMessage("msgDialogOpenFileWithEncoding", - "Open with encoding|A title for an open file dialog to indicate that a is user selecting a file to be opened with pre-selected encoding"); + odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpenWithEncoding; - // ask the encoding first from the user.. - Encoding encoding = FormDialogQueryEncoding.Execute(out _, out _); - if (encoding != null) + // if the file dialog was accepted (i.e. OK) then open the file to the view.. + if (odAnyFile.ShowDialog() == DialogResult.OK) { - odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpenWithEncoding; - - // if the file dialog was accepted (i.e. OK) then open the file to the view.. - if (odAnyFile.ShowDialog() == DialogResult.OK) - { - FormSettings.Settings.FileLocationOpenWithEncoding = Path.GetDirectoryName(odAnyFile.FileName); - OpenDocument(odAnyFile.FileName, encoding, false, true); - } + FormSettings.Settings.FileLocationOpenWithEncoding = Path.GetDirectoryName(odAnyFile.FileName); + OpenDocument(odAnyFile.FileName, encoding, false, true); } } + } - // a user wishes to help with localization of the software (!!).. - private void MnuLocalization_Click(object sender, EventArgs e) + // a user wishes to help with localization of the software (!!).. + private void MnuLocalization_Click(object sender, EventArgs e) + { + try { - try - { - LocalizeRunner.RunLocalizeWindow(Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "ScriptNotepad", - // ReSharper disable once StringLiteralTypo - "lang.sqlite")); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex, "Localization"); - } + LocalizeRunner.RunLocalizeWindow(Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "ScriptNotepad", + // ReSharper disable once StringLiteralTypo + "lang.sqlite")); } - - // a user wishes to dump (update) the current language database.. - private void MnuDumpLanguage_Click(object sender, EventArgs e) + catch (Exception ex) { - try - { - Process.Start(Application.ExecutablePath, "--dblang"); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex, "Localization dump"); - } + // log the exception.. + ExceptionLogger.LogError(ex, "Localization"); } + } - // the software's main form was activated so check if any open file has been changes.. - private void FormMain_Activated(object sender, EventArgs e) + // a user wishes to dump (update) the current language database.. + private void MnuDumpLanguage_Click(object sender, EventArgs e) + { + try { - tmGUI.Enabled = false; - // release the flag which suspends the selection update to avoid excess CPU load.. - suspendSelectionUpdate = false; + Process.Start(Application.ExecutablePath, "--dblang"); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex, "Localization dump"); + } + } - // this event in this case leads to an endless loop.. - Activated -= FormMain_Activated; + // the software's main form was activated so check if any open file has been changes.. + private void FormMain_Activated(object sender, EventArgs e) + { + tmGUI.Enabled = false; + // release the flag which suspends the selection update to avoid excess CPU load.. + suspendSelectionUpdate = false; - CheckFileSysChanges(); + // this event in this case leads to an endless loop.. + Activated -= FormMain_Activated; - // this event in this case leads to an endless loop.. - Activated += FormMain_Activated; + CheckFileSysChanges(); - // start the timer to bring the main form to the front.. - leftActivatedEvent = true; - tmGUI.Enabled = true; - } + // this event in this case leads to an endless loop.. + Activated += FormMain_Activated; - // a tab is closing so save it into the history.. - private void sttcMain_TabClosing(object sender, TabClosingEventArgsExt e) - { - // call the handle method.. - HandleCloseTab((FileSave) e.ScintillaTabbedDocument.Tag, false, true, false, - e.ScintillaTabbedDocument.Scintilla.CurrentPosition); + // start the timer to bring the main form to the front.. + leftActivatedEvent = true; + tmGUI.Enabled = true; + } - // if there are no documents any more.. - if (sttcMain.DocumentsCount - 1 <= 0) - { - // set the status strip label's to indicate that there is no active document.. - StatusStripTexts.SetEmptyTexts(CurrentSession.SessionName); + // a tab is closing so save it into the history.. + private void sttcMain_TabClosing(object sender, TabClosingEventArgsExt e) + { + // call the handle method.. + HandleCloseTab((FileSave) e.ScintillaTabbedDocument.Tag, false, true, false, + e.ScintillaTabbedDocument.Scintilla.CurrentPosition); - // set the application title to indicate no active document.. - SetEmptyApplicationTitle(); - } + // if there are no documents any more.. + if (sttcMain.DocumentsCount - 1 <= 0) + { + // set the status strip label's to indicate that there is no active document.. + StatusStripTexts.SetEmptyTexts(CurrentSession.SessionName); - // re-create the tab menu.. - TabMenuBuilder.CreateMenuOpenTabs(); + // set the application title to indicate no active document.. + SetEmptyApplicationTitle(); } - // a user activated a tab (document) so display it's file name.. - private void sttcMain_TabActivated(object sender, TabActivatedEventArgs e) - { - // set the application title to indicate the currently active document.. - SetApplicationTitle(e.ScintillaTabbedDocument); + // re-create the tab menu.. + TabMenuBuilder.CreateMenuOpenTabs(); + } - SetDocumentMiscIndicators(e.ScintillaTabbedDocument); + // a user activated a tab (document) so display it's file name.. + private void sttcMain_TabActivated(object sender, TabActivatedEventArgs e) + { + // set the application title to indicate the currently active document.. + SetApplicationTitle(e.ScintillaTabbedDocument); - StatusStripTexts.SetDocumentSizeText(e.ScintillaTabbedDocument); + SetDocumentMiscIndicators(e.ScintillaTabbedDocument); - StatusStripTexts.SetStatusStringText(e.ScintillaTabbedDocument, CurrentSession.SessionName); + StatusStripTexts.SetDocumentSizeText(e.ScintillaTabbedDocument); - // re-create the tab menu.. - TabMenuBuilder?.CreateMenuOpenTabs(); + StatusStripTexts.SetStatusStringText(e.ScintillaTabbedDocument, CurrentSession.SessionName); - // check the programming language menu item with the current lexer.. - ProgrammingLanguageHelper.CheckLanguage(e.ScintillaTabbedDocument.LexerType); + // re-create the tab menu.. + TabMenuBuilder?.CreateMenuOpenTabs(); - // the search must be re-set.. - CurrentDocumentAction(document => - { - FormSearchAndReplace.Instance.CreateSingleSearchReplaceAlgorithm( - (document.Scintilla, document.FileName)); - }); + // check the programming language menu item with the current lexer.. + ProgrammingLanguageHelper.CheckLanguage(e.ScintillaTabbedDocument.LexerType); + + // the search must be re-set.. + CurrentDocumentAction(document => + { + FormSearchAndReplace.Instance.CreateSingleSearchReplaceAlgorithm( + (document.Scintilla, document.FileName)); + }); - UpdateToolbarButtonsAndMenuItems(); - } + UpdateToolbarButtonsAndMenuItems(); + } + + // a tab was closed for various reasons.. + private void SttcMain_TabClosed(object sender, TabClosedEventArgs e) + { + // re-create the tab menu.. + TabMenuBuilder?.CreateMenuOpenTabs(); + } + + // a user wanted to see an about dialog of the software.. + private void mnuAbout_Click(object sender, EventArgs e) + { + // ReSharper disable once ObjectCreationAsStatement + new FormAbout(this, "MIT", + "https://raw.githubusercontent.com/VPKSoft/ScriptNotepad/master/LICENSE", + "https://www.vpksoft.net/versions/version.php"); + } - // a tab was closed for various reasons.. - private void SttcMain_TabClosed(object sender, TabClosedEventArgs e) + // this is the event listener for the ScintillaTabbedDocument's selection and caret position change events.. + private void sttcMain_SelectionCaretChanged(object sender, ScintillaTabbedDocumentEventArgsExt e) + { + // set the search and replace from selection flag.. + if (ActiveForm != null && (e.ScintillaTabbedDocument.SelectionLength > 0 && ActiveForm.Equals(this))) { - // re-create the tab menu.. - TabMenuBuilder?.CreateMenuOpenTabs(); + FormSearchAndReplace.Instance.SelectionChangedFromMainForm = true; } - - // a user wanted to see an about dialog of the software.. - private void mnuAbout_Click(object sender, EventArgs e) + else { - // ReSharper disable once ObjectCreationAsStatement - new FormAbout(this, "MIT", - "https://raw.githubusercontent.com/VPKSoft/ScriptNotepad/master/LICENSE", - "https://www.vpksoft.net/versions/version.php"); + FormSearchAndReplace.Instance.SelectionChangedFromMainForm = false; } - // this is the event listener for the ScintillaTabbedDocument's selection and caret position change events.. - private void sttcMain_SelectionCaretChanged(object sender, ScintillaTabbedDocumentEventArgsExt e) + if (e.ScintillaTabbedDocument.Scintilla.SelectionEnd == e.ScintillaTabbedDocument.Scintilla.SelectionStart) { - // set the search and replace from selection flag.. - if (ActiveForm != null && (e.ScintillaTabbedDocument.SelectionLength > 0 && ActiveForm.Equals(this))) - { - FormSearchAndReplace.Instance.SelectionChangedFromMainForm = true; - } - else - { - FormSearchAndReplace.Instance.SelectionChangedFromMainForm = false; - } - - if (e.ScintillaTabbedDocument.Scintilla.SelectionEnd == e.ScintillaTabbedDocument.Scintilla.SelectionStart) - { - Highlight.ClearStyle(e.ScintillaTabbedDocument.Scintilla, 8); - } - - if (!suspendSelectionUpdate) - { - StatusStripTexts.SetStatusStringText(e.ScintillaTabbedDocument, CurrentSession.SessionName); - } - - UpdateToolbarButtonsAndMenuItems(); + Highlight.ClearStyle(e.ScintillaTabbedDocument.Scintilla, 8); } - - // a user wanted to save all documents.. - private void mnuSaveAll_Click(object sender, EventArgs e) + + if (!suspendSelectionUpdate) { - SaveAllDocuments(sender.Equals(tsbSaveAllWithUnsaved) || sender.Equals(mnuSaveAllWithUnsaved)); + StatusStripTexts.SetStatusStringText(e.ScintillaTabbedDocument, CurrentSession.SessionName); } - // saves the changed ScintillaNET document's contents to a MemoryStream if the contents have been changed.. - // hopefully not stressful for the memory or CPU.. - private void sttcMain_DocumentTextChanged(object sender, ScintillaTextChangedEventArgs e) - { - var fileSave = (FileSave)e.ScintillaTabbedDocument.Tag; - fileSave.SetDatabaseModified(DateTime.Now); - fileSave.SetContents(e.ScintillaTabbedDocument.Scintilla.Text, false, false, true); + UpdateToolbarButtonsAndMenuItems(); + } - e.ScintillaTabbedDocument.FileTabButton.IsSaved = !IsFileChanged(fileSave); + // a user wanted to save all documents.. + private void mnuSaveAll_Click(object sender, EventArgs e) + { + SaveAllDocuments(sender.Equals(tsbSaveAllWithUnsaved) || sender.Equals(mnuSaveAllWithUnsaved)); + } - - // if the text has been changed and id did not occur by encoding change - // just clear the undo "buffer".. - if (!TextChangedViaEncodingChange) - { - fileSave.ClearPreviousEncodings(); - TextChangedViaEncodingChange = false; - } - - // update the search if the user manually modified the contents of the document.. - FormSearchAndReplace.Instance.UpdateSearchContents(e.ScintillaTabbedDocument.Scintilla.Text, - e.ScintillaTabbedDocument.FileName); + // saves the changed ScintillaNET document's contents to a MemoryStream if the contents have been changed.. + // hopefully not stressful for the memory or CPU.. + private void sttcMain_DocumentTextChanged(object sender, ScintillaTextChangedEventArgs e) + { + var fileSave = (FileSave)e.ScintillaTabbedDocument.Tag; + fileSave.SetDatabaseModified(DateTime.Now); + fileSave.SetContents(e.ScintillaTabbedDocument.Scintilla.Text, false, false, true); - UpdateToolbarButtonsAndMenuItems(); - } + e.ScintillaTabbedDocument.FileTabButton.IsSaved = !IsFileChanged(fileSave); - // a user wishes to do some scripting (!).. - private void mnuRunScript_Click(object sender, EventArgs e) + + // if the text has been changed and id did not occur by encoding change + // just clear the undo "buffer".. + if (!TextChangedViaEncodingChange) { - // ..so display the script from and allow multiple instances of it.. - FormScript formScript = new FormScript(); - - // subscribe an event for the C# script form when it requires a Scintilla document.. - formScript.ScintillaRequired += FormScript_ScintillaRequired; + fileSave.ClearPreviousEncodings(); + TextChangedViaEncodingChange = false; + } + + // update the search if the user manually modified the contents of the document.. + FormSearchAndReplace.Instance.UpdateSearchContents(e.ScintillaTabbedDocument.Scintilla.Text, + e.ScintillaTabbedDocument.FileName); - // subscribe the FormClosed event so the events can be unsubscribed (ridiculous -right ?).. - formScript.FormClosed += FormScript_FormClosed; + UpdateToolbarButtonsAndMenuItems(); + } - // show the form.. - formScript.Show(); - } + // a user wishes to do some scripting (!).. + private void mnuRunScript_Click(object sender, EventArgs e) + { + // ..so display the script from and allow multiple instances of it.. + FormScript formScript = new FormScript(); - // a C# script form was closed, so do unsubscribe the events.. - private void FormScript_FormClosed(object sender, FormClosedEventArgs e) - { - // get the FormScript instance.. - FormScript formScript = (FormScript)sender; + // subscribe an event for the C# script form when it requires a Scintilla document.. + formScript.ScintillaRequired += FormScript_ScintillaRequired; - // unsubscribe the events.. - formScript.ScintillaRequired -= FormScript_ScintillaRequired; - formScript.FormClosed -= FormScript_FormClosed; + // subscribe the FormClosed event so the events can be unsubscribed (ridiculous -right ?).. + formScript.FormClosed += FormScript_FormClosed; - // bring the form to the front.. - BringToFront(); - } + // show the form.. + formScript.Show(); + } - // a script form requested an active document for a script manipulation.. - private void FormScript_ScintillaRequired(object sender, FormScript.ScintillaRequiredEventArgs e) - { - if (sttcMain.CurrentDocument != null) - { - e.Scintilla = sttcMain.CurrentDocument.Scintilla; - } - } + // a C# script form was closed, so do unsubscribe the events.. + private void FormScript_FormClosed(object sender, FormClosedEventArgs e) + { + // get the FormScript instance.. + FormScript formScript = (FormScript)sender; - // a user wishes to undo changes.. - private void tsbUndo_Click(object sender, EventArgs e) - { - Undo(); - } + // unsubscribe the events.. + formScript.ScintillaRequired -= FormScript_ScintillaRequired; + formScript.FormClosed -= FormScript_FormClosed; + + // bring the form to the front.. + BringToFront(); + } - // a user wishes to redo changes.. - private void tsbRedo_Click(object sender, EventArgs e) + // a script form requested an active document for a script manipulation.. + private void FormScript_ScintillaRequired(object sender, FormScript.ScintillaRequiredEventArgs e) + { + if (sttcMain.CurrentDocument != null) { - Redo(); + e.Scintilla = sttcMain.CurrentDocument.Scintilla; } + } - // a timer to prevent an endless loop with the form activated event (probably a poor solution).. - private void tmGUI_Tick(object sender, EventArgs e) - { - tmGUI.Enabled = false; - if (bringToFrontQueued && leftActivatedEvent) - { - // this event in this case leads to an endless loop.. - Activated -= FormMain_Activated; + // a user wishes to undo changes.. + private void tsbUndo_Click(object sender, EventArgs e) + { + Undo(); + } - // bring the form to the front.. - BringToFront(); - Activate(); + // a user wishes to redo changes.. + private void tsbRedo_Click(object sender, EventArgs e) + { + Redo(); + } - // this event in this case leads to an endless loop.. - Activated += FormMain_Activated; - } + // a timer to prevent an endless loop with the form activated event (probably a poor solution).. + private void tmGUI_Tick(object sender, EventArgs e) + { + tmGUI.Enabled = false; + if (bringToFrontQueued && leftActivatedEvent) + { + // this event in this case leads to an endless loop.. + Activated -= FormMain_Activated; + + // bring the form to the front.. + BringToFront(); + Activate(); - bringToFrontQueued = false; - leftActivatedEvent = false; - tmGUI.Enabled = true; + // this event in this case leads to an endless loop.. + Activated += FormMain_Activated; } - // occurs when a plug-in requests for the currently active document.. - private void RequestActiveDocument(object sender, RequestScintillaDocumentEventArgs e) + bringToFrontQueued = false; + leftActivatedEvent = false; + tmGUI.Enabled = true; + } + + // occurs when a plug-in requests for the currently active document.. + private void RequestActiveDocument(object sender, RequestScintillaDocumentEventArgs e) + { + // verify that there is an active document, etc.. + if (sttcMain.CurrentDocument?.Tag != null) { - // verify that there is an active document, etc.. - if (sttcMain.CurrentDocument?.Tag != null) - { - var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; - e.AllDocuments = false; // set to flag indicating all the documents to false.. + var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; + e.AllDocuments = false; // set to flag indicating all the documents to false.. - // add the document details to the event arguments.. - e.Documents.Add( - (fileSave.GetEncoding(), + // add the document details to the event arguments.. + e.Documents.Add( + (fileSave.GetEncoding(), sttcMain.CurrentDocument.Scintilla, fileSave.FileNameFull, fileSave.FileSystemModified, fileSave.DatabaseModified, true)); - } } + } - // occurs when a plug-in requests for all the open documents.. - private void RequestAllDocuments(object sender, RequestScintillaDocumentEventArgs e) + // occurs when a plug-in requests for all the open documents.. + private void RequestAllDocuments(object sender, RequestScintillaDocumentEventArgs e) + { + // loop through all the documents.. + for (int i = 0; i < sttcMain.DocumentsCount; i++) { - // loop through all the documents.. - for (int i = 0; i < sttcMain.DocumentsCount; i++) + // verify the document's validity.. + if (sttcMain.Documents[i].Tag == null) { - // verify the document's validity.. - if (sttcMain.Documents[i].Tag == null) - { - continue; - } - var fileSave = (FileSave)sttcMain.Documents[i].Tag; + continue; + } + var fileSave = (FileSave)sttcMain.Documents[i].Tag; - // add the document details to the event arguments.. - e.Documents.Add( - (fileSave.GetEncoding(), + // add the document details to the event arguments.. + e.Documents.Add( + (fileSave.GetEncoding(), sttcMain.Documents[i].Scintilla, fileSave.FileNameFull, fileSave.FileSystemModified, fileSave.DatabaseModified, true)); - } - e.AllDocuments = true; // set to flag indicating all the documents to true.. } + e.AllDocuments = true; // set to flag indicating all the documents to true.. + } - // occurs when an exception has occurred in a plug-in (NOTE: The plug-in must have exception handling!).. - private void PluginException(object sender, PluginExceptionEventArgs e) + // occurs when an exception has occurred in a plug-in (NOTE: The plug-in must have exception handling!).. + private void PluginException(object sender, PluginExceptionEventArgs e) + { + ExceptionLogger.LogError(e.Exception, $"PLUG-IN EXCEPTION: '{e.PluginModuleName}'."); + int idx = Plugins.FindIndex(f => f.Plugin.PluginName == e.PluginModuleName); + if (idx != -1) { - ExceptionLogger.LogError(e.Exception, $"PLUG-IN EXCEPTION: '{e.PluginModuleName}'."); - int idx = Plugins.FindIndex(f => f.Plugin.PluginName == e.PluginModuleName); - if (idx != -1) - { - Plugins[idx].Plugin.ExceptionCount++; - ScriptNotepadDbContext.DbContext.SaveChanges(); - } + Plugins[idx].Plugin.ExceptionCount++; + ScriptNotepadDbContext.DbContext.SaveChanges(); } + } - // a user wishes to manage the plug-ins used by the software.. - private void mnuManagePlugins_Click(object sender, EventArgs e) - { - // get the current plug-ins as a List.. - var plugins = Plugins.Select(f => f.Plugin).ToList(); + // a user wishes to manage the plug-ins used by the software.. + private void mnuManagePlugins_Click(object sender, EventArgs e) + { + // get the current plug-ins as a List.. + var plugins = Plugins.Select(f => f.Plugin).ToList(); - // display the plug-in management form passing a reference to the plug-in list.. - if (FormPluginManage.Execute(ref plugins)) + // display the plug-in management form passing a reference to the plug-in list.. + if (FormPluginManage.Execute(ref plugins)) + { + // if the user selected OK, accepted the dialog, + // loop through the plug-ins.. + foreach (var plugin in plugins) { - // if the user selected OK, accepted the dialog, - // loop through the plug-ins.. - foreach (var plugin in plugins) - { - // find an index to the plug-in possibly modified by the dialog.. - int idx = Plugins.FindIndex(f => f.Plugin.Id == plugin.Id); + // find an index to the plug-in possibly modified by the dialog.. + int idx = Plugins.FindIndex(f => f.Plugin.Id == plugin.Id); - // if a valid index was found.. - if (idx != -1) - { - // set the new value for the PLUGINS class instance.. - Plugins[idx] = (Plugins[idx].Assembly, Plugins[idx].PluginInstance, plugin); - } + // if a valid index was found.. + if (idx != -1) + { + // set the new value for the PLUGINS class instance.. + Plugins[idx] = (Plugins[idx].Assembly, Plugins[idx].PluginInstance, plugin); } } } + } - /// - /// The previous window state of this form. - /// - private FormWindowState previousWindowState = FormWindowState.Normal; + /// + /// The previous window state of this form. + /// + private FormWindowState previousWindowState = FormWindowState.Normal; - private void FormMain_Resize(object sender, EventArgs e) + private void FormMain_Resize(object sender, EventArgs e) + { + if (FormFirstShown) { - if (FormFirstShown) + if (WindowState == FormWindowState.Minimized) { - if (WindowState == FormWindowState.Minimized) - { - FormSearchAndReplace.Instance.ToggleVisible(this, false); - } - else if (previousWindowState != WindowState && - (WindowState == FormWindowState.Maximized || WindowState == FormWindowState.Normal)) - { - FormSearchAndReplace.Instance.ToggleVisible(this, true); - } + FormSearchAndReplace.Instance.ToggleVisible(this, false); + } + else if (previousWindowState != WindowState && + (WindowState == FormWindowState.Maximized || WindowState == FormWindowState.Normal)) + { + FormSearchAndReplace.Instance.ToggleVisible(this, true); + } - SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation}); + SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation, }); - PreviousSize = Size; - } + PreviousSize = Size; } + } - // rise the SizeVisibilityChange event when visibility changes.. - private void FormMain_VisibleChanged(object sender, EventArgs e) - { - SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation}); - } + // rise the SizeVisibilityChange event when visibility changes.. + private void FormMain_VisibleChanged(object sender, EventArgs e) + { + SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation, }); + } - // save the previous location and raise the SizeVisibilityChange event.. - private void FormMain_LocationChanged(object sender, EventArgs e) - { - SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation}); - PreviousLocation = Location; - } + // save the previous location and raise the SizeVisibilityChange event.. + private void FormMain_LocationChanged(object sender, EventArgs e) + { + SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation, }); + PreviousLocation = Location; + } - /// - /// Processes Windows messages. - /// - /// The Windows to process. - [SuppressMessage("ReSharper", "IdentifierTypo")] - protected override void WndProc(ref Message m) - { - // ReSharper disable once InconsistentNaming - const int WM_SYSCOMMAND = 0x0112; - // ReSharper disable once InconsistentNaming - const uint SC_MINIMIZE = 0xF020; - // ReSharper disable once InconsistentNaming - const uint SC_MAXIMIZE = 0xF030; - // ReSharper disable once InconsistentNaming - const uint SC_RESTORE = 0xF120; - - if (m.Msg == WM_SYSCOMMAND) - { - if (m.WParamLoWordUnsigned() == SC_MINIMIZE || - m.WParamLoWordUnsigned() == SC_MAXIMIZE || - m.WParamLoWordUnsigned() == SC_RESTORE) - { - SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation}); - previousWindowState = WindowState; - } + /// + /// Processes Windows messages. + /// + /// The Windows to process. + [SuppressMessage("ReSharper", "IdentifierTypo")] + protected override void WndProc(ref Message m) + { + // ReSharper disable once InconsistentNaming + const int WM_SYSCOMMAND = 0x0112; + // ReSharper disable once InconsistentNaming + const uint SC_MINIMIZE = 0xF020; + // ReSharper disable once InconsistentNaming + const uint SC_MAXIMIZE = 0xF030; + // ReSharper disable once InconsistentNaming + const uint SC_RESTORE = 0xF120; + + if (m.Msg == WM_SYSCOMMAND) + { + if (m.WParamLoWordUnsigned() == SC_MINIMIZE || + m.WParamLoWordUnsigned() == SC_MAXIMIZE || + m.WParamLoWordUnsigned() == SC_RESTORE) + { + SizeVisibilityChange?.Invoke(this, new MainFormSizeEventArgs { Size = Size, PreviousSize = PreviousSize, PreviousState = previousWindowState, State = WindowState, Visible = Visible, Location = Location, PreviousLocation = PreviousLocation, }); + previousWindowState = WindowState; } - - base.WndProc(ref m); } - private void SttcMain_DocumentMouseDoubleClick(object sender, MouseEventArgs e) - { - var scintilla = (Scintilla)sender; - // Indicators 0-7 could be in use by a lexer - // so we'll use indicator 8 to highlight words. - Highlight.HighlightWords(scintilla, 8, scintilla.SelectedText, FormSettings.Settings.SmartHighlight); - } + base.WndProc(ref m); + } + + private void SttcMain_DocumentMouseDoubleClick(object sender, MouseEventArgs e) + { + var scintilla = (Scintilla)sender; + // Indicators 0-7 could be in use by a lexer + // so we'll use indicator 8 to highlight words. + Highlight.HighlightWords(scintilla, 8, scintilla.SelectedText, FormSettings.Settings.SmartHighlight); + } - // a user wishes to mark all occurrences of the selected text with a style (1..5).. - private void StyleSelectOf_Click(object sender, EventArgs e) + // a user wishes to mark all occurrences of the selected text with a style (1..5).. + private void StyleSelectOf_Click(object sender, EventArgs e) + { + if (sttcMain.CurrentDocument != null) { - if (sttcMain.CurrentDocument != null) - { - int styleNum = int.Parse(((ToolStripMenuItem) sender).Tag.ToString() ?? "-1"); + int styleNum = int.Parse(((ToolStripMenuItem) sender).Tag.ToString() ?? "-1"); - if (styleNum != -1) - { - Highlight.HighlightWords(sttcMain.CurrentDocument.Scintilla, styleNum, - sttcMain.CurrentDocument.Scintilla.SelectedText, FormSettings.Settings.GetMarkColor(styleNum - 9)); - } + if (styleNum != -1) + { + Highlight.HighlightWords(sttcMain.CurrentDocument.Scintilla, styleNum, + sttcMain.CurrentDocument.Scintilla.SelectedText, FormSettings.Settings.GetMarkColor(styleNum - 9)); } } + } - // a user wishes to clear style mark of style (1..5) from the editor.. - private void ClearStyleOf_Click(object sender, EventArgs e) + // a user wishes to clear style mark of style (1..5) from the editor.. + private void ClearStyleOf_Click(object sender, EventArgs e) + { + if (sttcMain.CurrentDocument != null) { - if (sttcMain.CurrentDocument != null) - { - Highlight.ClearStyle(sttcMain.CurrentDocument.Scintilla, - int.Parse(((ToolStripMenuItem) sender).Tag.ToString() ?? "-1")); - } + Highlight.ClearStyle(sttcMain.CurrentDocument.Scintilla, + int.Parse(((ToolStripMenuItem) sender).Tag.ToString() ?? "-1")); } + } - // a user wishes to clear all style markings of the current document.. - private void ClearAllStyles_Click(object sender, EventArgs e) + // a user wishes to clear all style markings of the current document.. + private void ClearAllStyles_Click(object sender, EventArgs e) + { + if (sttcMain.CurrentDocument != null) { - if (sttcMain.CurrentDocument != null) + for (int i = 9; i < 14; i++) { - for (int i = 9; i < 14; i++) - { - Highlight.ClearStyle(sttcMain.CurrentDocument.Scintilla, i); - } + Highlight.ClearStyle(sttcMain.CurrentDocument.Scintilla, i); } } + } - // a user wishes to reload the file contents from the disk.. - private void MnuReloadFromDisk_Click(object sender, EventArgs e) + // a user wishes to reload the file contents from the disk.. + private void MnuReloadFromDisk_Click(object sender, EventArgs e) + { + if (sttcMain.CurrentDocument != null) { - if (sttcMain.CurrentDocument != null) - { - // get the FileSave class instance from the document's tag.. - var fileSave = (FileSave) sttcMain.CurrentDocument.Tag; + // get the FileSave class instance from the document's tag.. + var fileSave = (FileSave) sttcMain.CurrentDocument.Tag; - // avoid excess checks further in the code.. - if (fileSave == null) - { - return; - } + // avoid excess checks further in the code.. + if (fileSave == null) + { + return; + } - // check if the file exists because it cannot be reloaded otherwise - // from the file system.. - if (File.Exists(sttcMain.CurrentDocument.FileName)) - { - // the encoding shouldn't change based on the file's contents if a snapshot of the file already exists in the database.. - fileSave.SetEncoding( - GetFileEncoding(CurrentSession.SessionName, sttcMain.CurrentDocument.FileName, fileSave.GetEncoding(), true, - false, false, out _, out _, out _)); + // check if the file exists because it cannot be reloaded otherwise + // from the file system.. + if (File.Exists(sttcMain.CurrentDocument.FileName)) + { + // the encoding shouldn't change based on the file's contents if a snapshot of the file already exists in the database.. + fileSave.SetEncoding( + GetFileEncoding(CurrentSession.SessionName, sttcMain.CurrentDocument.FileName, fileSave.GetEncoding(), true, + false, false, out _, out _, out _)); - // the user answered yes.. - sttcMain.SuspendTextChangedEvents = - true; // suspend the changed events on the ScintillaTabbedTextControl.. + // the user answered yes.. + sttcMain.SuspendTextChangedEvents = + true; // suspend the changed events on the ScintillaTabbedTextControl.. - fileSave.ReloadFromDisk(sttcMain.CurrentDocument); // reload the file.. - sttcMain.SuspendTextChangedEvents = - false; // resume the changed events on the ScintillaTabbedTextControl.. + fileSave.ReloadFromDisk(sttcMain.CurrentDocument); // reload the file.. + sttcMain.SuspendTextChangedEvents = + false; // resume the changed events on the ScintillaTabbedTextControl.. - // just in case set the tag back.. - sttcMain.CurrentDocument.Tag = fileSave; + // just in case set the tag back.. + sttcMain.CurrentDocument.Tag = fileSave; - fileSave.SetDatabaseModified(fileSave.FileSystemModified); + fileSave.SetDatabaseModified(fileSave.FileSystemModified); - sttcMain.CurrentDocument.FileTabButton.IsSaved = !IsFileChanged(fileSave); + sttcMain.CurrentDocument.FileTabButton.IsSaved = !IsFileChanged(fileSave); - UpdateToolbarButtonsAndMenuItems(); - } + UpdateToolbarButtonsAndMenuItems(); } } + } - // user wants to see the difference between two open files (tabs) - // comparing the current document to the right side document.. - private void MnuDiffRight_Click(object sender, EventArgs e) + // user wants to see the difference between two open files (tabs) + // comparing the current document to the right side document.. + private void MnuDiffRight_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - CurrentDocumentAction(document => + // get the right side document.. + var documentTwo = GetRightOrLeftFromCurrent(true); + + // ..and if not null, do continue.. + if (documentTwo != null) { - // get the right side document.. - var documentTwo = GetRightOrLeftFromCurrent(true); + FormFileDiffView.Execute(document.Scintilla.Text, documentTwo.Scintilla.Text); + } + }); + } - // ..and if not null, do continue.. - if (documentTwo != null) - { - FormFileDiffView.Execute(document.Scintilla.Text, documentTwo.Scintilla.Text); - } - }); - } + // user wants to see the difference between two open files (tabs) + // comparing the current document to the left side document.. + private void MnuDiffLeft_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => + { + // get the left side document.. + var documentTwo = GetRightOrLeftFromCurrent(false); - // user wants to see the difference between two open files (tabs) - // comparing the current document to the left side document.. - private void MnuDiffLeft_Click(object sender, EventArgs e) + // ..and if not null, do continue.. + if (documentTwo != null) + { + FormFileDiffView.Execute(document.Scintilla.Text, documentTwo.Scintilla.Text); + } + }); + } + + // a menu within the application is opening.. + private void MenuCommon_DropDownOpening(object sender, EventArgs e) + { + if (sender.Equals(mnuEdit)) // the edit menu is opening.. { - CurrentDocumentAction(document => + // get the FileSave from the active document.. + var fileSave = (FileSave) sttcMain.CurrentDocument?.Tag; + + if (fileSave != null) // the second null check.. { - // get the left side document.. - var documentTwo = GetRightOrLeftFromCurrent(false); + // enable / disable items which requires the file to exist in the file system.. + mnuRenameNewFileMainMenu.Enabled = !fileSave.ExistsInFileSystem; + } + } - // ..and if not null, do continue.. - if (documentTwo != null) - { - FormFileDiffView.Execute(document.Scintilla.Text, documentTwo.Scintilla.Text); - } - }); + if (sender.Equals(mnuText)) // the text menu is opening.. + { + mnuSortLines.Enabled = sttcMain.CurrentDocument != null; + mnuRemoveDuplicateLines.Enabled = sttcMain.CurrentDocument != null; + mnuWrapDocumentTo.Enabled = sttcMain.CurrentDocument != null; } + } - // a menu within the application is opening.. - private void MenuCommon_DropDownOpening(object sender, EventArgs e) + // removes duplicate lines from a Scintilla control.. + private void mnuRemoveDuplicateLines_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - if (sender.Equals(mnuEdit)) // the edit menu is opening.. - { - // get the FileSave from the active document.. - var fileSave = (FileSave) sttcMain.CurrentDocument?.Tag; + var fileSave = (FileSave) document.Tag; - if (fileSave != null) // the second null check.. - { - // enable / disable items which requires the file to exist in the file system.. - mnuRenameNewFileMainMenu.Enabled = !fileSave.ExistsInFileSystem; - } - } + DuplicateLines.RemoveDuplicateLines(document.Scintilla, + FormSettings.Settings.TextCurrentComparison, + fileSave.GetFileLineType()); - if (sender.Equals(mnuText)) // the text menu is opening.. + if (!suspendSelectionUpdate) { - mnuSortLines.Enabled = sttcMain.CurrentDocument != null; - mnuRemoveDuplicateLines.Enabled = sttcMain.CurrentDocument != null; - mnuWrapDocumentTo.Enabled = sttcMain.CurrentDocument != null; + StatusStripTexts.SetStatusStringText(document, CurrentSession.SessionName); } - } + }); + } - // removes duplicate lines from a Scintilla control.. - private void mnuRemoveDuplicateLines_Click(object sender, EventArgs e) + // set the value indicating whether Text menu functions should be case-sensitive.. + private void mnuCaseSensitive_Click(object sender, EventArgs e) + { + if (runningConstructor) { - CurrentDocumentAction(document => - { - var fileSave = (FileSave) document.Tag; + return; + } - DuplicateLines.RemoveDuplicateLines(document.Scintilla, - FormSettings.Settings.TextCurrentComparison, - fileSave.GetFileLineType()); + var item = (ToolStripMenuItem) sender; + item.Checked = !item.Checked; + FormSettings.Settings.TextUpperCaseComparison = item.Checked; + } - if (!suspendSelectionUpdate) - { - StatusStripTexts.SetStatusStringText(document, CurrentSession.SessionName); - } - }); + // a user wants to jump to the last or to the first tab.. + private void mnuFirstLastTab_Click(object sender, EventArgs e) + { + if (sttcMain.DocumentsCount > 0) + { + var leftIndex = sender.Equals(mnuLastTab) ? sttcMain.DocumentsCount - 1 : 0; + sttcMain.LeftFileIndex = leftIndex; } + } - // set the value indicating whether Text menu functions should be case-sensitive.. - private void mnuCaseSensitive_Click(object sender, EventArgs e) + private void mnuJsonPrettify_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - if (runningConstructor) + if (document.Tag != null) { - return; + document.Scintilla.Text = sender.Equals(mnuJsonPrettify) + ? document.Scintilla.Text.JsonPrettify() + : document.Scintilla.Text.JsonUglify(); } + }); + } - var item = (ToolStripMenuItem) sender; - item.Checked = !item.Checked; - FormSettings.Settings.TextUpperCaseComparison = item.Checked; - } - - // a user wants to jump to the last or to the first tab.. - private void mnuFirstLastTab_Click(object sender, EventArgs e) + private void mnuXMLPrettify_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - if (sttcMain.DocumentsCount > 0) + if (document.Tag != null) { - var leftIndex = sender.Equals(mnuLastTab) ? sttcMain.DocumentsCount - 1 : 0; - sttcMain.LeftFileIndex = leftIndex; + document.Scintilla.Text = sender.Equals(mnuXMLPrettify) + ? document.Scintilla.Text.XmlPrettify() + : document.Scintilla.Text.XmlUglify(); } - } + }); + } - private void mnuJsonPrettify_Click(object sender, EventArgs e) + private void mnuBase64ToString_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - CurrentDocumentAction(document => + if (document.Tag != null) { - if (document.Tag != null) + if (sender.Equals(mnuBase64ToString)) { - document.Scintilla.Text = sender.Equals(mnuJsonPrettify) - ? document.Scintilla.Text.JsonPrettify() - : document.Scintilla.Text.JsonUglify(); + document.Scintilla.SelectionReplaceWithValue(document.Scintilla.SelectedText.ToBase64()); } - }); - } - - private void mnuXMLPrettify_Click(object sender, EventArgs e) - { - CurrentDocumentAction(document => - { - if (document.Tag != null) + else { - document.Scintilla.Text = sender.Equals(mnuXMLPrettify) - ? document.Scintilla.Text.XmlPrettify() - : document.Scintilla.Text.XmlUglify(); + document.Scintilla.SelectionReplaceWithValue(document.Scintilla.SelectedText.FromBase64()); } - }); - } + } + }); + } - private void mnuBase64ToString_Click(object sender, EventArgs e) - { - CurrentDocumentAction(document => - { - if (document.Tag != null) - { - if (sender.Equals(mnuBase64ToString)) - { - document.Scintilla.SelectionReplaceWithValue(document.Scintilla.SelectedText.ToBase64()); - } - else - { - document.Scintilla.SelectionReplaceWithValue(document.Scintilla.SelectedText.FromBase64()); - } - } - }); - } + private void mnuRunScriptOrCommand_Click(object sender, EventArgs e) + { + ToggleSnippetRunner(); + } - private void mnuRunScriptOrCommand_Click(object sender, EventArgs e) + // fold all the document lines.. + private void mnuFoldAll_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - ToggleSnippetRunner(); - } + foreach (var scintillaLine in document.Scintilla.Lines) + { + scintillaLine.FoldLine(FoldAction.Contract); + } + }); + } - // fold all the document lines.. - private void mnuFoldAll_Click(object sender, EventArgs e) + // unfold all the document lines.. + private void mnuUnfoldAll_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - CurrentDocumentAction(document => + foreach (var scintillaLine in document.Scintilla.Lines) { - foreach (var scintillaLine in document.Scintilla.Lines) - { - scintillaLine.FoldLine(FoldAction.Contract); - } - }); - } + scintillaLine.FoldLine(FoldAction.Expand); + } + }); + } + #endregion + + #region PrivateFields + /// + /// A flag indicating whether the the dialog is still running the code within the constructor. + /// + private readonly bool runningConstructor = true; + + /// + /// A flag indicating if the main form should be activated. + /// + private bool bringToFrontQueued; + + /// + /// A flag indicating if the main form's execution has left the Activated event. + /// + private bool leftActivatedEvent; + + /// + /// A flag indicating whether the selection should be update to the status strip. + /// Continuous updates with keyboard will cause excess CPU usage. + /// + private bool suspendSelectionUpdate; + #endregion + + #region PrivateProperties + /// + /// Gets the message box stack containing the instances. + /// + private MessageBoxExpandStack BoxStack { get; } + + /// + /// Gets or sets the value whether the timers within the program should be enabled or disabled. + /// + private bool TimersEnabled + { + // three timers.. - // unfold all the document lines.. - private void mnuUnfoldAll_Click(object sender, EventArgs e) + set { - CurrentDocumentAction(document => - { - foreach (var scintillaLine in document.Scintilla.Lines) - { - scintillaLine.FoldLine(FoldAction.Expand); - } - }); - } - #endregion - - #region PrivateFields - /// - /// A flag indicating whether the the dialog is still running the code within the constructor. - /// - private readonly bool runningConstructor = true; - - /// - /// A flag indicating if the main form should be activated. - /// - private bool bringToFrontQueued; - - /// - /// A flag indicating if the main form's execution has left the Activated event. - /// - private bool leftActivatedEvent; - - /// - /// A flag indicating whether the selection should be update to the status strip. - /// Continuous updates with keyboard will cause excess CPU usage. - /// - private bool suspendSelectionUpdate; - #endregion - - #region PrivateProperties - /// - /// Gets the message box stack containing the instances. - /// - private MessageBoxExpandStack BoxStack { get; } - - /// - /// Gets or sets the value whether the timers within the program should be enabled or disabled. - /// - private bool TimersEnabled - { - // three timers.. - - set + // comparison for the three timers.. + if ((tmAutoSave.Enabled || tmGUI.Enabled || tmSpellCheck.Enabled) && !value) { - // comparison for the three timers.. - if ((tmAutoSave.Enabled || tmGUI.Enabled || tmSpellCheck.Enabled) && !value) - { - tmAutoSave.Enabled = false; - tmGUI.Enabled = false; - tmSpellCheck.Enabled = false; - } + tmAutoSave.Enabled = false; + tmGUI.Enabled = false; + tmSpellCheck.Enabled = false; + } - if ((!tmAutoSave.Enabled || !tmGUI.Enabled || !tmSpellCheck.Enabled) && value) - { - tmAutoSave.Enabled = true; - tmGUI.Enabled = true; - tmSpellCheck.Enabled = true; - } + if ((!tmAutoSave.Enabled || !tmGUI.Enabled || !tmSpellCheck.Enabled) && value) + { + tmAutoSave.Enabled = true; + tmGUI.Enabled = true; + tmSpellCheck.Enabled = true; } } + } - /// - /// Gets or sets the IPC server. - /// - /// The IPC server. - private static RpcSelfHost IpcServer { get; set; } + /// + /// Gets or sets the IPC server. + /// + /// The IPC server. + private static RpcSelfHost IpcServer { get; set; } - /// - /// Gets the search string in case of a active document has a selection within a one line. - /// - private string SearchString + /// + /// Gets the search string in case of a active document has a selection within a one line. + /// + private string SearchString + { + get { - get + try { - try + if (sttcMain.CurrentDocument != null) { - if (sttcMain.CurrentDocument != null) + var scintilla = sttcMain.CurrentDocument.Scintilla; + if (scintilla.SelectedText.Length > 0) { - var scintilla = sttcMain.CurrentDocument.Scintilla; - if (scintilla.SelectedText.Length > 0) + var selectionStartLine = scintilla.LineFromPosition(scintilla.SelectionStart); + var selectionEndLine = scintilla.LineFromPosition(scintilla.SelectionEnd); + if (selectionStartLine == selectionEndLine) { - var selectionStartLine = scintilla.LineFromPosition(scintilla.SelectionStart); - var selectionEndLine = scintilla.LineFromPosition(scintilla.SelectionEnd); - if (selectionStartLine == selectionEndLine) - { - return scintilla.SelectedText; - } + return scintilla.SelectedText; } } - - return string.Empty; - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - return string.Empty; } + + return string.Empty; + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + return string.Empty; } } + } - /// - /// Gets or sets a value indicating whether constructor of this form has finished. - /// - private bool ConstructorFinished { get; } + /// + /// Gets or sets a value indicating whether constructor of this form has finished. + /// + private bool ConstructorFinished { get; } - /// - /// Gets or sets menu builder used to build the menu of the 's open forms. - /// - private WinFormsFormMenuBuilder WinFormsFormMenuBuilder { get; set; } + /// + /// Gets or sets menu builder used to build the menu of the 's open forms. + /// + private WinFormsFormMenuBuilder WinFormsFormMenuBuilder { get; set; } - /// - /// Gets or sets the tab menu builder for the . - /// - private TabMenuBuilder TabMenuBuilder { get; set; } + /// + /// Gets or sets the tab menu builder for the . + /// + private TabMenuBuilder TabMenuBuilder { get; set; } - /// - /// Gets or sets the programming language helper class . - /// - private ProgrammingLanguageHelper ProgrammingLanguageHelper { get; } + /// + /// Gets or sets the programming language helper class . + /// + private ProgrammingLanguageHelper ProgrammingLanguageHelper { get; } - // a field for the CurrentSession property.. - private FileSession currentSession; + // a field for the CurrentSession property.. + private FileSession currentSession; - /// - /// Gets or sets the current session for the documents. - /// - private FileSession CurrentSession + /// + /// Gets or sets the current session for the documents. + /// + private FileSession CurrentSession + { + get => currentSession; + set { - get => currentSession; - set + if (value == null) // don't allow a null value.. { - if (value == null) // don't allow a null value.. - { - return; - } + return; + } - if (value != currentSession) - { - FormSettings.Settings.CurrentSessionEntity = value; + if (value != currentSession) + { + FormSettings.Settings.CurrentSessionEntity = value; - CloseSession(); - LoadDocumentsFromDatabase(value.SessionName); - } - currentSession = value; + CloseSession(); + LoadDocumentsFromDatabase(value.SessionName); } + currentSession = value; } + } - /// - /// Gets or sets the loaded active plug-ins. - /// - private List<(Assembly Assembly, IScriptNotepadPlugin PluginInstance, Plugin Plugin)> Plugins { get; } = - new(); - - /// - /// Gets or sets the default encoding to be used with the files within this software. - /// - private List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - DefaultEncodings => FormSettings.Settings.GetEncodingList(); - - /// - /// The amount of files to be saved to a document history. - /// - private int HistoryListAmount => FormSettings.Settings.HistoryListAmount; - - /// - /// Gets the save file history contents count. - /// - private int SaveFileHistoryContentsCount => - FormSettings.Settings.SaveFileHistoryContents ? - // the setting value if the setting is enabled.. - FormSettings.Settings.SaveFileHistoryContentsCount : - int.MinValue; - #endregion - - #region InternalProperties - internal static FormMain Instance { get; private set; } - - /// - /// Sets the active document. - /// - /// The active document. - internal Scintilla ActiveScintilla => sttcMain.CurrentDocument?.Scintilla; - - /// - /// Gets the previous size of this form before resize. - /// - /// The previous size of this form before resize. - internal Size PreviousSize { get; set; } = Size.Empty; - - /// - /// Gets the previous location of this form before the change. - /// - /// The previous location of this form before the change. - internal Point PreviousLocation { get; set; } = Point.Empty; - #endregion - - #region Events - internal event EventHandler SizeVisibilityChange; - #endregion - - #region FileContextMenu - // a user wishes to do "do something" with the file (existing one).. - private void CommonContextMenu_FileInteractionClick(object sender, EventArgs e) - { - if (sttcMain.CurrentDocument != null) // the first null check.. - { - var document = sttcMain.CurrentDocument; // get the active document.. + /// + /// Gets or sets the loaded active plug-ins. + /// + private List<(Assembly Assembly, IScriptNotepadPlugin PluginInstance, Plugin Plugin)> Plugins { get; } = + new(); - // get the FileSave from the active document.. - var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; + /// + /// Gets or sets the default encoding to be used with the files within this software. + /// + private List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + DefaultEncodings => FormSettings.Settings.GetEncodingList(); - if (fileSave != null) // the second null check.. - { - // based on the sending menu item, select the appropriate action.. - if (sender.Equals(mnuOpenContainingFolderInCmd)) - { - // open the command prompt with the file's path.. - CommandPromptInteraction.OpenCmdWithPath(Path.GetDirectoryName(fileSave.FileNameFull)); - } - else if (sender.Equals(mnuOpenContainingFolderInWindowsPowerShell)) - { - // open the Windows PowerShell with the file's path.. - CommandPromptInteraction.OpenPowerShellWithPath(Path.GetDirectoryName(fileSave.FileNameFull)); - } - else if (sender.Equals(mnuOpenContainingFolderInExplorer)) - { - // open the Windows explorer and select the file from it.. - WindowsExplorerInteraction.ShowFileOrPathInExplorer(fileSave.FileNameFull); - } - else if (sender.Equals(mnuOpenWithAssociatedApplication)) - { - // open the file with an associated software.. - WindowsExplorerInteraction.OpenWithAssociatedProgram(fileSave.FileNameFull); - } - else if (sender.Equals(mnuFullFilePathToClipboard)) - { - // copy the full file path to the clipboard.. - ClipboardTextHelper.ClipboardSetText(Path.GetDirectoryName(fileSave.FileNameFull)); - } - else if (sender.Equals(mnuFullFilePathAndNameToClipboard)) - { - // copy the full file name to the clipboard.. - ClipboardTextHelper.ClipboardSetText(fileSave.FileNameFull); - } - else if (sender.Equals(mnuFileNameToClipboard)) - { - // copy the file name to the clipboard.. - ClipboardTextHelper.ClipboardSetText(Path.GetFileName(fileSave.FileNameFull)); - } - else if (sender.Equals(mnuCloseTab)) - { - sttcMain.CloseDocument(document, true); - } - } - } - } + /// + /// The amount of files to be saved to a document history. + /// + private int HistoryListAmount => FormSettings.Settings.HistoryListAmount; + + /// + /// Gets the save file history contents count. + /// + private int SaveFileHistoryContentsCount => + FormSettings.Settings.SaveFileHistoryContents ? + // the setting value if the setting is enabled.. + FormSettings.Settings.SaveFileHistoryContentsCount : + int.MinValue; + #endregion + + #region InternalProperties + internal static FormMain Instance { get; private set; } + + /// + /// Sets the active document. + /// + /// The active document. + internal Scintilla ActiveScintilla => sttcMain.CurrentDocument?.Scintilla; + + /// + /// Gets the previous size of this form before resize. + /// + /// The previous size of this form before resize. + internal Size PreviousSize { get; set; } = Size.Empty; + + /// + /// Gets the previous location of this form before the change. + /// + /// The previous location of this form before the change. + internal Point PreviousLocation { get; set; } = Point.Empty; + #endregion - // the context menu is opening for user to "do something" with the file.. - private void cmsFileTab_Opening(object sender, System.ComponentModel.CancelEventArgs e) + #region Events + internal event EventHandler SizeVisibilityChange; + #endregion + + #region FileContextMenu + // a user wishes to do "do something" with the file (existing one).. + private void CommonContextMenu_FileInteractionClick(object sender, EventArgs e) + { + if (sttcMain.CurrentDocument != null) // the first null check.. { + var document = sttcMain.CurrentDocument; // get the active document.. + // get the FileSave from the active document.. - var fileSave = (FileSave) sttcMain.CurrentDocument?.Tag; + var fileSave = (FileSave)sttcMain.CurrentDocument.Tag; if (fileSave != null) // the second null check.. { - // enable / disable items which requires the file to exist in the file system.. - mnuOpenContainingFolderInExplorer.Enabled = File.Exists(fileSave.FileNameFull); - mnuOpenWithAssociatedApplication.Enabled = File.Exists(fileSave.FileNameFull); - mnuOpenContainingFolderInCmd.Enabled = File.Exists(fileSave.FileNameFull); - mnuOpenContainingFolderInWindowsPowerShell.Enabled = File.Exists(fileSave.FileNameFull); - mnuOpenWithAssociatedApplication.Enabled = File.Exists(fileSave.FileNameFull); - mnuRenameNewFile.Enabled = !fileSave.ExistsInFileSystem; + // based on the sending menu item, select the appropriate action.. + if (sender.Equals(mnuOpenContainingFolderInCmd)) + { + // open the command prompt with the file's path.. + CommandPromptInteraction.OpenCmdWithPath(Path.GetDirectoryName(fileSave.FileNameFull)); + } + else if (sender.Equals(mnuOpenContainingFolderInWindowsPowerShell)) + { + // open the Windows PowerShell with the file's path.. + CommandPromptInteraction.OpenPowerShellWithPath(Path.GetDirectoryName(fileSave.FileNameFull)); + } + else if (sender.Equals(mnuOpenContainingFolderInExplorer)) + { + // open the Windows explorer and select the file from it.. + WindowsExplorerInteraction.ShowFileOrPathInExplorer(fileSave.FileNameFull); + } + else if (sender.Equals(mnuOpenWithAssociatedApplication)) + { + // open the file with an associated software.. + WindowsExplorerInteraction.OpenWithAssociatedProgram(fileSave.FileNameFull); + } + else if (sender.Equals(mnuFullFilePathToClipboard)) + { + // copy the full file path to the clipboard.. + ClipboardTextHelper.ClipboardSetText(Path.GetDirectoryName(fileSave.FileNameFull)); + } + else if (sender.Equals(mnuFullFilePathAndNameToClipboard)) + { + // copy the full file name to the clipboard.. + ClipboardTextHelper.ClipboardSetText(fileSave.FileNameFull); + } + else if (sender.Equals(mnuFileNameToClipboard)) + { + // copy the file name to the clipboard.. + ClipboardTextHelper.ClipboardSetText(Path.GetFileName(fileSave.FileNameFull)); + } + else if (sender.Equals(mnuCloseTab)) + { + sttcMain.CloseDocument(document, true); + } } } + } + + // the context menu is opening for user to "do something" with the file.. + private void cmsFileTab_Opening(object sender, System.ComponentModel.CancelEventArgs e) + { + // get the FileSave from the active document.. + var fileSave = (FileSave) sttcMain.CurrentDocument?.Tag; - /// - /// A method for closing multiple documents depending of the given parameters. - /// - /// A flag indicating that from the active document to the right all documents should be closed. - /// A flag indicating that from the active document to the left all documents should be closed. - private void CloseAllFunction(bool right, bool left) + if (fileSave != null) // the second null check.. { - // get the document in question.. - var document = sttcMain.CurrentDocument; + // enable / disable items which requires the file to exist in the file system.. + mnuOpenContainingFolderInExplorer.Enabled = File.Exists(fileSave.FileNameFull); + mnuOpenWithAssociatedApplication.Enabled = File.Exists(fileSave.FileNameFull); + mnuOpenContainingFolderInCmd.Enabled = File.Exists(fileSave.FileNameFull); + mnuOpenContainingFolderInWindowsPowerShell.Enabled = File.Exists(fileSave.FileNameFull); + mnuOpenWithAssociatedApplication.Enabled = File.Exists(fileSave.FileNameFull); + mnuRenameNewFile.Enabled = !fileSave.ExistsInFileSystem; + } + } + + /// + /// A method for closing multiple documents depending of the given parameters. + /// + /// A flag indicating that from the active document to the right all documents should be closed. + /// A flag indicating that from the active document to the left all documents should be closed. + private void CloseAllFunction(bool right, bool left) + { + // get the document in question.. + var document = sttcMain.CurrentDocument; - // get the index for the active document.. - int idx = document != null ? sttcMain.Documents.FindIndex(f => f.Equals(document)) : -1; + // get the index for the active document.. + int idx = document != null ? sttcMain.Documents.FindIndex(f => f.Equals(document)) : -1; - // validate the index.. - if (idx != -1) + // validate the index.. + if (idx != -1) + { + // do a backward loop and close all the documents except the active one.. + for (int i = sttcMain.DocumentsCount - 1; i >= 0; i--) { - // do a backward loop and close all the documents except the active one.. - for (int i = sttcMain.DocumentsCount - 1; i >= 0; i--) + // validate the right and left flags.. + if ((left && i > idx) || (right && i < idx)) { - // validate the right and left flags.. - if ((left && i > idx) || (right && i < idx)) - { - // ..if this is a match then do continue.. - continue; - } - - // the index is the active document.. - if (idx == i) - { - // ..so skip the document.. - continue; - } + // ..if this is a match then do continue.. + continue; + } - // call the handle method.. - HandleCloseTab((FileSave) sttcMain.Documents[i].Tag, false, false, true, - sttcMain.Documents[i].Scintilla.CurrentPosition); + // the index is the active document.. + if (idx == i) + { + // ..so skip the document.. + continue; } + + // call the handle method.. + HandleCloseTab((FileSave) sttcMain.Documents[i].Tag, false, false, true, + sttcMain.Documents[i].Scintilla.CurrentPosition); } } + } - /// - /// A method for getting the right-most or the left-most document compared to the active document. - /// - /// A flag indicating whether to get the right-most or the left-most document compared to active document. - /// The right-most or the left-most document compared to active document; if no document exists the method returns null. - private ScintillaTabbedDocument GetRightOrLeftFromCurrent(bool right) - { - // get the document in question.. - var document = sttcMain.CurrentDocument; + /// + /// A method for getting the right-most or the left-most document compared to the active document. + /// + /// A flag indicating whether to get the right-most or the left-most document compared to active document. + /// The right-most or the left-most document compared to active document; if no document exists the method returns null. + private ScintillaTabbedDocument GetRightOrLeftFromCurrent(bool right) + { + // get the document in question.. + var document = sttcMain.CurrentDocument; - // get the index for the active document.. - int idx = document != null ? sttcMain.Documents.FindIndex(f => f.Equals(document)) : -1; + // get the index for the active document.. + int idx = document != null ? sttcMain.Documents.FindIndex(f => f.Equals(document)) : -1; - // validate the index.. - if (idx != -1) - { - // just a simple plus/minus calculation.. - idx = right ? idx + 1 : idx - 1; + // validate the index.. + if (idx != -1) + { + // just a simple plus/minus calculation.. + idx = right ? idx + 1 : idx - 1; - if (idx >= 0 && idx < sttcMain.DocumentsCount) - { - return sttcMain.Documents[idx]; - } + if (idx >= 0 && idx < sttcMain.DocumentsCount) + { + return sttcMain.Documents[idx]; } - - // no document was found, so do return null.. - return null; } - // a user wishes to close all expect the active document or many documents - // to the right or to the left from the active document.. - private void CommonCloseManyDocuments(object sender, EventArgs e) - { - // call the CloseAllFunction method with this "wondrous" logic.. - CloseAllFunction(sender.Equals(mnuCloseAllToTheRight), sender.Equals(mnuCloseAllToTheLeft)); - } + // no document was found, so do return null.. + return null; + } - // a user wants to compare two unopened files.. - private void MnuDiffFiles_Click(object sender, EventArgs e) + // a user wishes to close all expect the active document or many documents + // to the right or to the left from the active document.. + private void CommonCloseManyDocuments(object sender, EventArgs e) + { + // call the CloseAllFunction method with this "wondrous" logic.. + CloseAllFunction(sender.Equals(mnuCloseAllToTheRight), sender.Equals(mnuCloseAllToTheLeft)); + } + + // a user wants to compare two unopened files.. + private void MnuDiffFiles_Click(object sender, EventArgs e) + { + try { - try - { - string contentsOne; - string contentsTwo; + string contentsOne; + string contentsTwo; - odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpenDiff1; + odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpenDiff1; - odAnyFile.Title = DBLangEngine.GetMessage("msgSelectFileDiff1", - "Select the first file to diff|A title for an open file dialog to indicate user selecting the first file to find differences with a second file"); + odAnyFile.Title = DBLangEngine.GetMessage("msgSelectFileDiff1", + "Select the first file to diff|A title for an open file dialog to indicate user selecting the first file to find differences with a second file"); - if (odAnyFile.ShowDialog() == DialogResult.OK) - { - FormSettings.Settings.FileLocationOpenDiff1 = Path.GetDirectoryName(odAnyFile.FileName); - contentsOne = File.ReadAllText(odAnyFile.FileName); - } - else - { - return; - } + if (odAnyFile.ShowDialog() == DialogResult.OK) + { + FormSettings.Settings.FileLocationOpenDiff1 = Path.GetDirectoryName(odAnyFile.FileName); + contentsOne = File.ReadAllText(odAnyFile.FileName); + } + else + { + return; + } - odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpenDiff2; + odAnyFile.InitialDirectory = FormSettings.Settings.FileLocationOpenDiff2; - odAnyFile.Title = DBLangEngine.GetMessage("msgSelectFileDiff2", - "Select the second file to diff|A title for an open file dialog to indicate user selecting the second file to find differences with a first file"); + odAnyFile.Title = DBLangEngine.GetMessage("msgSelectFileDiff2", + "Select the second file to diff|A title for an open file dialog to indicate user selecting the second file to find differences with a first file"); - if (odAnyFile.ShowDialog() == DialogResult.OK) - { - FormSettings.Settings.FileLocationOpenDiff2 = Path.GetDirectoryName(odAnyFile.FileName); - contentsTwo = File.ReadAllText(odAnyFile.FileName); - } - else - { - return; - } - - FormFileDiffView.Execute(contentsOne, contentsTwo); + if (odAnyFile.ShowDialog() == DialogResult.OK) + { + FormSettings.Settings.FileLocationOpenDiff2 = Path.GetDirectoryName(odAnyFile.FileName); + contentsTwo = File.ReadAllText(odAnyFile.FileName); } - catch (Exception ex) + else { - ExceptionLogger.LogError(ex); + return; } + + FormFileDiffView.Execute(contentsOne, contentsTwo); + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); } + } - // a user wishes to rename a new file.. - private void MnuRenameNewFile_Click(object sender, EventArgs e) + // a user wishes to rename a new file.. + private void MnuRenameNewFile_Click(object sender, EventArgs e) + { + CurrentDocumentAction(document => { - CurrentDocumentAction(document => + var fileSave = (FileSave) document.Tag; + if (fileSave.ExistsInFileSystem) { - var fileSave = (FileSave) document.Tag; - if (fileSave.ExistsInFileSystem) + return; + } + + string newName; + if ((newName = FormDialogRenameNewFile.ShowDialog(this, sttcMain)) != null) + { + if (fileSave == null) { return; } - string newName; - if ((newName = FormDialogRenameNewFile.ShowDialog(this, sttcMain)) != null) - { - if (fileSave == null) - { - return; - } - - // the file now has a location so update it.. - fileSave.FileName = newName; - fileSave.FileNameFull = newName; + // the file now has a location so update it.. + fileSave.FileName = newName; + fileSave.FileNameFull = newName; - // update the document.. - document.FileName = newName; - document.FileNameNotPath = newName; - document.FileTabButton.Text = newName; - sttcMain.LeftFileIndex = sttcMain.LeftFileIndex; + // update the document.. + document.FileName = newName; + document.FileNameNotPath = newName; + document.FileTabButton.Text = newName; + sttcMain.LeftFileIndex = sttcMain.LeftFileIndex; - // update the time stamp.. - fileSave.SetDatabaseModified(DateTime.Now); + // update the time stamp.. + fileSave.SetDatabaseModified(DateTime.Now); - // update document misc data, i.e. the assigned lexer to the database.. - fileSave.AddOrUpdateFile(); - } - }); - } - #endregion + // update document misc data, i.e. the assigned lexer to the database.. + fileSave.AddOrUpdateFile(); + } + }); + } + #endregion - #region EditorSymbols - // enable/disable word wrap.. - private void MnuWordWrap_Click(object sender, EventArgs e) + #region EditorSymbols + // enable/disable word wrap.. + private void MnuWordWrap_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => - { - scintilla.WrapMode = ItemFromObj(sender).Checked ? WrapMode.Word : WrapMode.None; - }); - } + scintilla.WrapMode = ItemFromObj(sender).Checked ? WrapMode.Word : WrapMode.None; + }); + } - // a user wishes to show or hide the white space symbols.. - private void MnuShowWhiteSpaceAndTab_Click(object sender, EventArgs e) + // a user wishes to show or hide the white space symbols.. + private void MnuShowWhiteSpaceAndTab_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => - { - scintilla.ViewWhitespace = ItemFromObj(sender).Checked - ? WhitespaceMode.VisibleAlways - : WhitespaceMode.Invisible; - }); - } + scintilla.ViewWhitespace = ItemFromObj(sender).Checked + ? WhitespaceMode.VisibleAlways + : WhitespaceMode.Invisible; + }); + } - // a user wishes to hide or show the end of line symbols.. - private void MnuShowEndOfLine_Click(object sender, EventArgs e) - { - CurrentScintillaAction(scintilla => { scintilla.ViewEol = ItemFromObj(sender).Checked; }); - } + // a user wishes to hide or show the end of line symbols.. + private void MnuShowEndOfLine_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { scintilla.ViewEol = ItemFromObj(sender).Checked; }); + } - // the show symbol menu drop down items are going to be shown, so set their states accordingly.. - private void MnuShowSymbol_DropDownOpening(object sender, EventArgs e) + // the show symbol menu drop down items are going to be shown, so set their states accordingly.. + private void MnuShowSymbol_DropDownOpening(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => { - CurrentScintillaAction(scintilla => - { - mnuShowEndOfLine.Checked = scintilla.ViewEol; + mnuShowEndOfLine.Checked = scintilla.ViewEol; - mnuShowWhiteSpaceAndTab.Checked = - scintilla.ViewWhitespace != WhitespaceMode.Invisible; + mnuShowWhiteSpaceAndTab.Checked = + scintilla.ViewWhitespace != WhitespaceMode.Invisible; - mnuShowIndentGuide.Checked = scintilla.IndentationGuides == IndentView.Real; + mnuShowIndentGuide.Checked = scintilla.IndentationGuides == IndentView.Real; - mnuShowWrapSymbol.Checked = scintilla.WrapVisualFlags == WrapVisualFlags.End; - }); - } + mnuShowWrapSymbol.Checked = scintilla.WrapVisualFlags == WrapVisualFlags.End; + }); + } - // a user wishes to toggle the scintilla to show or hide the indentation guides.. - private void MnuShowIndentGuide_Click(object sender, EventArgs e) - { - CurrentScintillaAction(scintilla => - scintilla.IndentationGuides = ItemFromObj(sender).Checked - ? IndentView.Real - : IndentView.None); - } + // a user wishes to toggle the scintilla to show or hide the indentation guides.. + private void MnuShowIndentGuide_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => + scintilla.IndentationGuides = ItemFromObj(sender).Checked + ? IndentView.Real + : IndentView.None); + } - // toggle whether to show the word wrap symbol.. - private void MnuShowWrapSymbol_Click(object sender, EventArgs e) - { - CurrentScintillaAction(scintilla => - scintilla.WrapVisualFlags = ItemFromObj(sender).Checked - ? WrapVisualFlags.End - : WrapVisualFlags.None); - } - #endregion + // toggle whether to show the word wrap symbol.. + private void MnuShowWrapSymbol_Click(object sender, EventArgs e) + { + CurrentScintillaAction(scintilla => + scintilla.WrapVisualFlags = ItemFromObj(sender).Checked + ? WrapVisualFlags.End + : WrapVisualFlags.None); } -} + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/Gists/MessageHelper.cs b/ScriptNotepad/Gists/MessageHelper.cs index ddb5b184..89c3f335 100644 --- a/ScriptNotepad/Gists/MessageHelper.cs +++ b/ScriptNotepad/Gists/MessageHelper.cs @@ -31,156 +31,155 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// A name space for the MessageHelper class. /// #pragma warning restore CS1587 // XML comment is not placed on a valid language element -namespace VPKSoft.MessageHelper +namespace VPKSoft.MessageHelper; + +/// +/// A class to help with Message class in such cases as an overridden Control.WndProc Method. +/// +public static class MessageHelper { /// - /// A class to help with Message class in such cases as an overridden Control.WndProc Method. + /// Posted to a window when the cursor moves. + /// + public const int WM_MOUSEMOVE = 0x0200; // Posted to a window when the cursor moves. + + /// + /// Posted when the user releases the right mouse button while the cursor is in the client area of a window. + /// + public const int WM_RBUTTONUP = 0x0205; // Posted to a window when the right mouse button is up. + + /// + /// Posted when the user releases the left mouse button while the cursor is in the client area of a window. + /// + public const int WM_LBUTTONUP = 0x0202; // Posted to a window when the left mouse button is up. + + /// + /// Posted to a window when the cursor leaves the client area of the window specified in a prior call to TrackMouseEvent. + /// + public const int WM_MOUSELEAVE = 0x02A3; // Posted to a window when the cursor leaves the client area of the window specified in a prior call to TrackMouseEvent. + + /// + /// Sent to the window that is losing the mouse capture. + /// + public const int WM_CAPTURECHANGED = 0x0215; // Sent to the window that is losing the mouse capture. + + /// + /// The CTRL key is down. + /// + public const int MK_CONTROL = 0x0008; // The CTRL key is down. + + /// + /// The left mouse button is down. + /// + public const int MK_LBUTTON = 0x0001; // The left mouse button is down. + + /// + /// The middle mouse button is down. + /// + public const int MK_MBUTTON = 0x0010; // The middle mouse button is down. + + /// + /// The right mouse button is down. + /// + public const int MK_RBUTTON = 0x0002; // The right mouse button is down. + + /// + /// The SHIFT key is down. + /// + public const int MK_SHIFT = 0x0004; // The SHIFT key is down. + + /// + /// The first X button is down. + /// + public const int MK_XBUTTON1 = 0x0020; // The first X button is down. + + /// + /// // The second X button is down. + /// + public const int MK_XBUTTON2 = 0x0040; // The second X button is down. + + /// + /// Sent to the focus window when the mouse wheel is rotated. + /// + public const int WM_MOUSEWHEEL = 0x020A; // Sent to the focus window when the mouse wheel is rotated. + + /// + /// Gets the low order word of the lParam's value. + /// + /// A message of which low order word of the lParam's value to get. + /// The low order word of the lParam's value. + public static int LParamLoWord(this Message message) + { + return BitConverter.ToInt16(BitConverter.GetBytes((long)message.LParam), 0); + } + + /// + /// Gets the high order word of the lParam's value. + /// + /// A message of which high order word of the lParam's value to get. + /// The high order word of the lParam's value. + public static int LParamHiWord(this Message message) + { + return BitConverter.ToInt16(BitConverter.GetBytes((long)message.LParam), 2); + } + + /// + /// Gets the low order word of the wParam's value. + /// + /// A message of which low order word of the wParam's value to get. + /// The low order word of the wParam's value. + public static int WParamLoWord(this Message message) + { + return BitConverter.ToInt16(BitConverter.GetBytes((long)message.WParam), 0); + } + + /// + /// Gets the high order word of the wParam's value. + /// + /// A message of which high order word of the wParam's value to get. + /// The high order word of the wParam's value. + public static int WParamHiWord(this Message message) + { + return BitConverter.ToInt16(BitConverter.GetBytes((long)message.WParam), 2); + } + + /// + /// Gets the low order word of the lParam's value unsigned. + /// + /// A message of which low order word of the lParam's value to get unsigned. + /// The low order word of the lParam's value unsigned. + public static uint LParamLoWordUnsigned(this Message message) + { + return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.LParam), 0); + } + + /// + /// Gets the high order word of the lParam's value unsigned. + /// + /// A message of which high order word of the lParam's value to get unsigned. + /// The high order word of the lParam's value unsigned. + public static uint LParamHiWordUnsigned(this Message message) + { + return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.LParam), 2); + } + + /// + /// Gets the low order word of the wParam's value unsigned. + /// + /// A message of which low order word of the wParam's value to get unsigned. + /// The low order word of the wParam's value unsigned. + public static uint WParamLoWordUnsigned(this Message message) + { + return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.WParam), 0); + } + + /// + /// Gets the high order word of the wParam's value unsigned. /// - public static class MessageHelper + /// A message of which high order word of the wParam's value to get unsigned. + /// The high order word of the wParam's value unsigned. + public static uint WParamHiWordUnsigned(this Message message) { - /// - /// Posted to a window when the cursor moves. - /// - public const int WM_MOUSEMOVE = 0x0200; // Posted to a window when the cursor moves. - - /// - /// Posted when the user releases the right mouse button while the cursor is in the client area of a window. - /// - public const int WM_RBUTTONUP = 0x0205; // Posted to a window when the right mouse button is up. - - /// - /// Posted when the user releases the left mouse button while the cursor is in the client area of a window. - /// - public const int WM_LBUTTONUP = 0x0202; // Posted to a window when the left mouse button is up. - - /// - /// Posted to a window when the cursor leaves the client area of the window specified in a prior call to TrackMouseEvent. - /// - public const int WM_MOUSELEAVE = 0x02A3; // Posted to a window when the cursor leaves the client area of the window specified in a prior call to TrackMouseEvent. - - /// - /// Sent to the window that is losing the mouse capture. - /// - public const int WM_CAPTURECHANGED = 0x0215; // Sent to the window that is losing the mouse capture. - - /// - /// The CTRL key is down. - /// - public const int MK_CONTROL = 0x0008; // The CTRL key is down. - - /// - /// The left mouse button is down. - /// - public const int MK_LBUTTON = 0x0001; // The left mouse button is down. - - /// - /// The middle mouse button is down. - /// - public const int MK_MBUTTON = 0x0010; // The middle mouse button is down. - - /// - /// The right mouse button is down. - /// - public const int MK_RBUTTON = 0x0002; // The right mouse button is down. - - /// - /// The SHIFT key is down. - /// - public const int MK_SHIFT = 0x0004; // The SHIFT key is down. - - /// - /// The first X button is down. - /// - public const int MK_XBUTTON1 = 0x0020; // The first X button is down. - - /// - /// // The second X button is down. - /// - public const int MK_XBUTTON2 = 0x0040; // The second X button is down. - - /// - /// Sent to the focus window when the mouse wheel is rotated. - /// - public const int WM_MOUSEWHEEL = 0x020A; // Sent to the focus window when the mouse wheel is rotated. - - /// - /// Gets the low order word of the lParam's value. - /// - /// A message of which low order word of the lParam's value to get. - /// The low order word of the lParam's value. - public static int LParamLoWord(this Message message) - { - return BitConverter.ToInt16(BitConverter.GetBytes((long)message.LParam), 0); - } - - /// - /// Gets the high order word of the lParam's value. - /// - /// A message of which high order word of the lParam's value to get. - /// The high order word of the lParam's value. - public static int LParamHiWord(this Message message) - { - return BitConverter.ToInt16(BitConverter.GetBytes((long)message.LParam), 2); - } - - /// - /// Gets the low order word of the wParam's value. - /// - /// A message of which low order word of the wParam's value to get. - /// The low order word of the wParam's value. - public static int WParamLoWord(this Message message) - { - return BitConverter.ToInt16(BitConverter.GetBytes((long)message.WParam), 0); - } - - /// - /// Gets the high order word of the wParam's value. - /// - /// A message of which high order word of the wParam's value to get. - /// The high order word of the wParam's value. - public static int WParamHiWord(this Message message) - { - return BitConverter.ToInt16(BitConverter.GetBytes((long)message.WParam), 2); - } - - /// - /// Gets the low order word of the lParam's value unsigned. - /// - /// A message of which low order word of the lParam's value to get unsigned. - /// The low order word of the lParam's value unsigned. - public static uint LParamLoWordUnsigned(this Message message) - { - return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.LParam), 0); - } - - /// - /// Gets the high order word of the lParam's value unsigned. - /// - /// A message of which high order word of the lParam's value to get unsigned. - /// The high order word of the lParam's value unsigned. - public static uint LParamHiWordUnsigned(this Message message) - { - return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.LParam), 2); - } - - /// - /// Gets the low order word of the wParam's value unsigned. - /// - /// A message of which low order word of the wParam's value to get unsigned. - /// The low order word of the wParam's value unsigned. - public static uint WParamLoWordUnsigned(this Message message) - { - return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.WParam), 0); - } - - /// - /// Gets the high order word of the wParam's value unsigned. - /// - /// A message of which high order word of the wParam's value to get unsigned. - /// The high order word of the wParam's value unsigned. - public static uint WParamHiWordUnsigned(this Message message) - { - return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.WParam), 2); - } + return BitConverter.ToUInt16(BitConverter.GetBytes((long)message.WParam), 2); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/IOPermission/FileIOPermission.cs b/ScriptNotepad/IOPermission/FileIOPermission.cs index 64887643..6ccf89ef 100644 --- a/ScriptNotepad/IOPermission/FileIOPermission.cs +++ b/ScriptNotepad/IOPermission/FileIOPermission.cs @@ -27,94 +27,93 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using System.Security; -namespace ScriptNotepad.IOPermission +namespace ScriptNotepad.IOPermission; + +/// +/// A class to check for file permissions; i.e. the file access requires elevation. +/// +public class FileIoPermission: ErrorHandlingBase { /// - /// A class to check for file permissions; i.e. the file access requires elevation. + /// Checks if the access to a given file with given permissions requires elevation. /// - public class FileIoPermission: ErrorHandlingBase + /// Name of the file which access permissions to check. + /// The mode of how to try to open the file. + /// The file access mode of how to try to open the file. + /// The file share mode of how to try to open the file. + /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). + public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { - /// - /// Checks if the access to a given file with given permissions requires elevation. - /// - /// Name of the file which access permissions to check. - /// The mode of how to try to open the file. - /// The file access mode of how to try to open the file. - /// The file share mode of how to try to open the file. - /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). - public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) + try { - try + using (new FileStream(fileName, fileMode, fileAccess, fileShare)) { - using (new FileStream(fileName, fileMode, fileAccess, fileShare)) - { - // nothing to see here.. - } + // nothing to see here.. + } - return (false, false); + return (false, false); + } + // catch the exception and determine the result based on the type of the exception. + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + + if (ex.GetType() == typeof(UnauthorizedAccessException) || + ex.GetType() == typeof(SecurityException)) + { + return (true, false); } - // catch the exception and determine the result based on the type of the exception. - catch (Exception ex) + else if (ex.GetType() == typeof(IOException)) { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); - - if (ex.GetType() == typeof(UnauthorizedAccessException) || - ex.GetType() == typeof(SecurityException)) - { - return (true, false); - } - else if (ex.GetType() == typeof(IOException)) - { - return (false, true); - } - else - { - return (true, false); - } + return (false, true); + } + else + { + return (true, false); } } + } - /// - /// Checks if the access to a given file with given permissions requires elevation. - /// The file share is set to ReadWrite. - /// - /// Name of the file which access permissions to check. - /// The mode of how to try to open the file. - /// The file access mode of how to try to open the file. - /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). - public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode, FileAccess fileAccess) - { - // call the "mother" method.. - return FileRequiresElevation(fileName, fileMode, fileAccess, FileShare.ReadWrite); - } + /// + /// Checks if the access to a given file with given permissions requires elevation. + /// The file share is set to ReadWrite. + /// + /// Name of the file which access permissions to check. + /// The mode of how to try to open the file. + /// The file access mode of how to try to open the file. + /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). + public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode, FileAccess fileAccess) + { + // call the "mother" method.. + return FileRequiresElevation(fileName, fileMode, fileAccess, FileShare.ReadWrite); + } - /// - /// Checks if the access to a given file with given permissions requires elevation. - /// The file access is set to ReadWrite. - /// The file share is set to ReadWrite. - /// - /// Name of the file which access permissions to check. - /// The mode of how to try to open the file. - /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). - public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode) - { - // call the "mother" method.. - return FileRequiresElevation(fileName, fileMode, FileAccess.ReadWrite, FileShare.ReadWrite); - } + /// + /// Checks if the access to a given file with given permissions requires elevation. + /// The file access is set to ReadWrite. + /// The file share is set to ReadWrite. + /// + /// Name of the file which access permissions to check. + /// The mode of how to try to open the file. + /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). + public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode) + { + // call the "mother" method.. + return FileRequiresElevation(fileName, fileMode, FileAccess.ReadWrite, FileShare.ReadWrite); + } - /// - /// Checks if the access to a given file requires elevation. - /// The file mode is set to Open. - /// The file access is set to ReadWrite. - /// The file share is set to ReadWrite. - /// - /// Name of the file which access permissions to check. - /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). - public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName) - { - // call the "mother" method.. - return FileRequiresElevation(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); - } + /// + /// Checks if the access to a given file requires elevation. + /// The file mode is set to Open. + /// The file access is set to ReadWrite. + /// The file share is set to ReadWrite. + /// + /// Name of the file which access permissions to check. + /// A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error). + public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName) + { + // call the "mother" method.. + return FileRequiresElevation(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/ExternalLibraryLoader/ExternalSpellChecker.cs b/ScriptNotepad/Localization/ExternalLibraryLoader/ExternalSpellChecker.cs index 26ef7157..50395fdf 100644 --- a/ScriptNotepad/Localization/ExternalLibraryLoader/ExternalSpellChecker.cs +++ b/ScriptNotepad/Localization/ExternalLibraryLoader/ExternalSpellChecker.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -33,34 +33,56 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.ScintillaSpellCheck; using VPKSoft.SpellCheck.ExternalDictionarySource; -namespace ScriptNotepad.Localization.ExternalLibraryLoader +namespace ScriptNotepad.Localization.ExternalLibraryLoader; + +/// +/// If a spell checking for a certain language is provided via an external assembly/library this class can be used to load such library. +/// Implements the +/// +/// +public class ExternalSpellChecker: ErrorHandlingBase { /// - /// If a spell checking for a certain language is provided via an external assembly/library this class can be used to load such library. - /// Implements the + /// Loads a spell checker library from a given path with a given file name. /// - /// - public class ExternalSpellChecker: ErrorHandlingBase + /// The path. + /// Name of the file. + public static void LoadSpellCheck(string path, string fileName) { - /// - /// Loads a spell checker library from a given path with a given file name. - /// - /// The path. - /// Name of the file. - public static void LoadSpellCheck(string path, string fileName) + try { - try - { - fileName = Path.Combine(path, fileName); + fileName = Path.Combine(path, fileName); + + AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; - AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; + var assemblyName = Path.Combine(path, fileName); - var assemblyName = Path.Combine(path, fileName); + // the location of the assembly must be defined.. + Assembly spellCheck = Assembly.LoadFile(assemblyName); + + SetSpellChecker(spellCheck); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } + } - // the location of the assembly must be defined.. - Assembly spellCheck = Assembly.LoadFile(assemblyName); + /// + /// Loads a custom spell checking assembly if defined in the settings file. + /// + public static void Load() + { + if (FormSettings.Settings.EditorSpellUseCustomDictionary) + { + try + { + var data = DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(FormSettings.Settings + .EditorSpellCustomDictionaryDefinitionFile); + ExternalSpellChecker.LoadSpellCheck(Path.GetDirectoryName(FormSettings.Settings + .EditorSpellCustomDictionaryDefinitionFile), data.lib); - SetSpellChecker(spellCheck); } catch (Exception ex) { @@ -68,108 +90,85 @@ public static void LoadSpellCheck(string path, string fileName) ExceptionLogAction?.Invoke(ex); } } + } - /// - /// Loads a custom spell checking assembly if defined in the settings file. - /// - public static void Load() - { - if (FormSettings.Settings.EditorSpellUseCustomDictionary) - { - try - { - var data = DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(FormSettings.Settings - .EditorSpellCustomDictionaryDefinitionFile); - ExternalSpellChecker.LoadSpellCheck(Path.GetDirectoryName(FormSettings.Settings - .EditorSpellCustomDictionaryDefinitionFile), data.lib); - - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - } - } - } + /// + /// Handles the AssemblyResolve event of the CurrentDomain control. + /// + /// The source of the event. + /// The instance containing the event data. + /// Assembly. + private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) + { + // parts of the code borrowed from; Thanks To (C): https://weblog.west-wind.com/posts/2016/dec/12/loading-net-assemblies-out-of-seperate-folders - /// - /// Handles the AssemblyResolve event of the CurrentDomain control. - /// - /// The source of the event. - /// The instance containing the event data. - /// Assembly. - private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) + // ignore resources.. + if (args.Name.Contains(".resources")) { - // parts of the code borrowed from; Thanks To (C): https://weblog.west-wind.com/posts/2016/dec/12/loading-net-assemblies-out-of-seperate-folders - - // ignore resources.. - if (args.Name.Contains(".resources")) - { - return null; - } + return null; + } - // check for assemblies already loaded.. - Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == args.Name); - if (assembly != null) - { - return assembly; - } + // check for assemblies already loaded.. + Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == args.Name); + if (assembly != null) + { + return assembly; + } - // Try to load by filename - split out the filename of the full assembly name - // and append the base path of the original assembly (ie. look in the same dir) - string filename = args.Name.Split(',')[0] + ".dll".ToLower(); + // Try to load by filename - split out the filename of the full assembly name + // and append the base path of the original assembly (ie. look in the same dir) + string filename = args.Name.Split(',')[0] + ".dll".ToLower(); - filename = Path.Combine( - Path.GetDirectoryName(FormSettings.Settings.EditorSpellCustomDictionaryDefinitionFile) ?? string.Empty, - filename); + filename = Path.Combine( + Path.GetDirectoryName(FormSettings.Settings.EditorSpellCustomDictionaryDefinitionFile) ?? string.Empty, + filename); - try - { - return Assembly.LoadFrom(filename); - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - return null; - } + try + { + return Assembly.LoadFrom(filename); + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); + return null; } + } - /// - /// Initializes an external spell checker from a specified - /// - /// The assembly to load the spell checker from. - public static void SetSpellChecker(Assembly assembly) + /// + /// Initializes an external spell checker from a specified + /// + /// The assembly to load the spell checker from. + public static void SetSpellChecker(Assembly assembly) + { + foreach (Type type in assembly.GetTypes()) { - foreach (Type type in assembly.GetTypes()) + // again keep on trying.. + try { - // again keep on trying.. - try - { - // check the validity of the found type.. - if (typeof(IExternalDictionarySource).IsAssignableFrom(type)) - { - ScintillaSpellCheck.ExternalDictionary = (IExternalDictionarySource)Activator.CreateInstance(type); - ScintillaSpellCheck.ExternalDictionary.Initialize(); - - return; - } - } - catch (Exception ex) + // check the validity of the found type.. + if (typeof(IExternalDictionarySource).IsAssignableFrom(type)) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + ScintillaSpellCheck.ExternalDictionary = (IExternalDictionarySource)Activator.CreateInstance(type); + ScintillaSpellCheck.ExternalDictionary.Initialize(); + + return; } } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } } + } - /// - /// Disposes of the resources used by the spell checking library. - /// - public static void DisposeResources() - { - ScintillaSpellCheck.ExternalDictionary?.Dispose(); - AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve; - } + /// + /// Disposes of the resources used by the spell checking library. + /// + public static void DisposeResources() + { + ScintillaSpellCheck.ExternalDictionary?.Dispose(); + AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/Forms/FormLocalizationHelper.cs b/ScriptNotepad/Localization/Forms/FormLocalizationHelper.cs index e080833d..a607f014 100644 --- a/ScriptNotepad/Localization/Forms/FormLocalizationHelper.cs +++ b/ScriptNotepad/Localization/Forms/FormLocalizationHelper.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,140 +27,139 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.Encodings.CharacterSets; using VPKSoft.LangLib; -namespace ScriptNotepad.Localization.Forms +namespace ScriptNotepad.Localization.Forms; + +/// +/// A helper form to localize some other class properties, etc. +/// +/// +public partial class FormLocalizationHelper : DBLangEngineWinforms { /// - /// A helper form to localize some other class properties, etc. + /// Initializes a new instance of the class. /// - /// - public partial class FormLocalizationHelper : DBLangEngineWinforms + public FormLocalizationHelper() { - /// - /// Initializes a new instance of the class. - /// - public FormLocalizationHelper() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - LocalizeCharacterSets(); + LocalizeCharacterSets(); - // localize the names which are used to display line ending types of the document.. - LocalizeLineEndingTypeNames(); - } + // localize the names which are used to display line ending types of the document.. + LocalizeLineEndingTypeNames(); + } - /// - /// Localizes some other class properties, etc. - /// - public static void LocalizeMisc() - { - // just make a new instance of this form and the forget about it.. - // ReSharper disable once ObjectCreationAsStatement - new FormLocalizationHelper(); - } + /// + /// Localizes some other class properties, etc. + /// + public static void LocalizeMisc() + { + // just make a new instance of this form and the forget about it.. + // ReSharper disable once ObjectCreationAsStatement + new FormLocalizationHelper(); + } - /// - /// Localizes the line ending type names. - /// - private void LocalizeLineEndingTypeNames() - { - UtilityClasses.LinesAndBinary.FileLineType.CRLF_Description = - DBLangEngine.GetMessage("msgLineEndingCRLF", "CR+LF|A description for a line ending sequence for CR+LF."); + /// + /// Localizes the line ending type names. + /// + private void LocalizeLineEndingTypeNames() + { + UtilityClasses.LinesAndBinary.FileLineType.CRLF_Description = + DBLangEngine.GetMessage("msgLineEndingCRLF", "CR+LF|A description for a line ending sequence for CR+LF."); - UtilityClasses.LinesAndBinary.FileLineType.LF_Description = - DBLangEngine.GetMessage("msgLineEndingLF", "LF|A description for a line ending sequence for LF."); + UtilityClasses.LinesAndBinary.FileLineType.LF_Description = + DBLangEngine.GetMessage("msgLineEndingLF", "LF|A description for a line ending sequence for LF."); - UtilityClasses.LinesAndBinary.FileLineType.CR_Description = - DBLangEngine.GetMessage("msgLineEndingCR", "CR|A description for a line ending sequence for CR."); + UtilityClasses.LinesAndBinary.FileLineType.CR_Description = + DBLangEngine.GetMessage("msgLineEndingCR", "CR|A description for a line ending sequence for CR."); - UtilityClasses.LinesAndBinary.FileLineType.RS_Description = - DBLangEngine.GetMessage("msgLineEndingRS", "RS|A description for a line ending sequence for RS."); + UtilityClasses.LinesAndBinary.FileLineType.RS_Description = + DBLangEngine.GetMessage("msgLineEndingRS", "RS|A description for a line ending sequence for RS."); - UtilityClasses.LinesAndBinary.FileLineType.LFCR_Description = - DBLangEngine.GetMessage("msgLineEndingLFCR", "LF+CR|A description for a line ending sequence for LF+CR."); + UtilityClasses.LinesAndBinary.FileLineType.LFCR_Description = + DBLangEngine.GetMessage("msgLineEndingLFCR", "LF+CR|A description for a line ending sequence for LF+CR."); - UtilityClasses.LinesAndBinary.FileLineType.NL_Description = - DBLangEngine.GetMessage("msgLineEndingNL", "NL|A description for a line ending sequence for NL."); + UtilityClasses.LinesAndBinary.FileLineType.NL_Description = + DBLangEngine.GetMessage("msgLineEndingNL", "NL|A description for a line ending sequence for NL."); - UtilityClasses.LinesAndBinary.FileLineType.ATASCII_Description = - DBLangEngine.GetMessage("msgLineEndingATASCII", "ATASCII|A description for a line ending sequence for ATASCII."); + UtilityClasses.LinesAndBinary.FileLineType.ATASCII_Description = + DBLangEngine.GetMessage("msgLineEndingATASCII", "ATASCII|A description for a line ending sequence for ATASCII."); - UtilityClasses.LinesAndBinary.FileLineType.NEWLINE_Description = - DBLangEngine.GetMessage("msgLineEndingNEWLINE", "NEWLINE|A description for a line ending sequence for NEWLINE."); + UtilityClasses.LinesAndBinary.FileLineType.NEWLINE_Description = + DBLangEngine.GetMessage("msgLineEndingNEWLINE", "NEWLINE|A description for a line ending sequence for NEWLINE."); - UtilityClasses.LinesAndBinary.FileLineType.Unknown_Description = - DBLangEngine.GetMessage("msgLineEndingUnknown", "Unknown|A description for a line ending sequence for Unknown / non-existent line ending."); + UtilityClasses.LinesAndBinary.FileLineType.Unknown_Description = + DBLangEngine.GetMessage("msgLineEndingUnknown", "Unknown|A description for a line ending sequence for Unknown / non-existent line ending."); - UtilityClasses.LinesAndBinary.FileLineType.Mixed_Description = - DBLangEngine.GetMessage("msgLineEndingMixed", "Mixed|A description for a line ending sequence for Mixed (multiple types of line endings)."); + UtilityClasses.LinesAndBinary.FileLineType.Mixed_Description = + DBLangEngine.GetMessage("msgLineEndingMixed", "Mixed|A description for a line ending sequence for Mixed (multiple types of line endings)."); - UtilityClasses.LinesAndBinary.FileLineType.UCRLF_Description = - DBLangEngine.GetMessage("msgLineEndingUCRLF", "Unicode CR+LF|A description for a line ending sequence for Unicode CR+LF."); + UtilityClasses.LinesAndBinary.FileLineType.UCRLF_Description = + DBLangEngine.GetMessage("msgLineEndingUCRLF", "Unicode CR+LF|A description for a line ending sequence for Unicode CR+LF."); - UtilityClasses.LinesAndBinary.FileLineType.ULF_Description = - DBLangEngine.GetMessage("msgLineEndingULF", "Unicode LF|A description for a line ending sequence for Unicode LF."); + UtilityClasses.LinesAndBinary.FileLineType.ULF_Description = + DBLangEngine.GetMessage("msgLineEndingULF", "Unicode LF|A description for a line ending sequence for Unicode LF."); - UtilityClasses.LinesAndBinary.FileLineType.UCR_Description = - DBLangEngine.GetMessage("msgLineEndingUCR", "Unicode CR|A description for a line ending sequence for Unicode CR."); + UtilityClasses.LinesAndBinary.FileLineType.UCR_Description = + DBLangEngine.GetMessage("msgLineEndingUCR", "Unicode CR|A description for a line ending sequence for Unicode CR."); - UtilityClasses.LinesAndBinary.FileLineType.ULFCR_Description = - DBLangEngine.GetMessage("msgLineEndingULFCR", "Unicode LF+CR|A description for a line ending sequence for Unicode LF+CR."); - } + UtilityClasses.LinesAndBinary.FileLineType.ULFCR_Description = + DBLangEngine.GetMessage("msgLineEndingULFCR", "Unicode LF+CR|A description for a line ending sequence for Unicode LF+CR."); + } - /// - /// Localizes the character sets of the class. - /// - private void LocalizeCharacterSets() - { - EncodingCharacterSet encodingCharacterSet = new EncodingCharacterSet(); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Arabic, DBLangEngine.GetMessage("msgCharSetArabic", "Arabic|A message describing Arabic character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Baltic, DBLangEngine.GetMessage("msgCharSetBaltic", "Baltic|A message describing Arabic character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Canada, DBLangEngine.GetMessage("msgCharSetCanada", "Canada|A message describing Canada character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Cyrillic, DBLangEngine.GetMessage("msgCharSetCyrillic", "Cyrillic|A message describing Cyrillic character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.CentralEuropean, DBLangEngine.GetMessage("msgCharSetCentralEuropean", "Central European|A message describing Central European character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Chinese, DBLangEngine.GetMessage("msgCharSetChinese", "Chinese|A message describing Chinese character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.DenmarkNorway, DBLangEngine.GetMessage("msgCharSetDenmarkNorway", "Denmark-Norway|A message describing Denmark-Norway character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.FinlandSweden, DBLangEngine.GetMessage("msgCharSetFinlandSweden", "Finland-Sweden|A message describing Finland-Sweden character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.France, DBLangEngine.GetMessage("msgCharSetFrance", "France|A message describing France character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.German, DBLangEngine.GetMessage("msgCharSetGerman", "German|A message describing German character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Greek, DBLangEngine.GetMessage("msgCharSetGreek", "Greek|A message describing Greek character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Hebrew, DBLangEngine.GetMessage("msgCharSetHebrew", "Hebrew|A message describing Hebrew character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Icelandic, DBLangEngine.GetMessage("msgCharSetIcelandic", "Icelandic|A message describing Icelandic character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Italy, DBLangEngine.GetMessage("msgCharSetItaly", "Italy|A message describing Italy character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Japanese, DBLangEngine.GetMessage("msgCharSetJapanese", "Japanese|A message describing Japanese character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Korean, DBLangEngine.GetMessage("msgCharSetKorean", "Korean|A message describing Korean character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Latin, DBLangEngine.GetMessage("msgCharSetLatin", "Latin|A message describing Latin character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Miscellaneous, DBLangEngine.GetMessage("msgCharSetMiscellaneous", "Miscellaneous|A message describing Miscellaneous character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Norwegian, DBLangEngine.GetMessage("msgCharSetNorwegian", "Norwegian|A message describing Norwegian character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.WesternEuropean, DBLangEngine.GetMessage("msgCharSetWesternEuropean", "Western European|A message describing Western European character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Spain, DBLangEngine.GetMessage("msgCharSetSpain", "Spain|A message describing Spain character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Swedish, DBLangEngine.GetMessage("msgCharSetSwedish", "Swedish|A message describing Swedish character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Taiwan, DBLangEngine.GetMessage("msgCharSetTaiwan", "Taiwan|A message describing Taiwan character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Thai, DBLangEngine.GetMessage("msgCharSetThai", "Thai|A message describing Thai character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Turkish, DBLangEngine.GetMessage("msgCharSetTurkish", "Turkish|A message describing Turkish character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Unicode, DBLangEngine.GetMessage("msgCharSetUnicode", "Unicode|A message describing Unicode character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Assamese, DBLangEngine.GetMessage("msgCharSetAssamese", "Assamese|A message describing Assamese character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Bengali, DBLangEngine.GetMessage("msgCharSetBengali", "Bengali|A message describing Bengali character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Devanagari, DBLangEngine.GetMessage("msgCharSetDevanagari", "Devanagari|A message describing Devanagari character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Estonian, DBLangEngine.GetMessage("msgCharSetEstonian", "Estonian|A message describing Estonian character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Kannada, DBLangEngine.GetMessage("msgCharSetKannada", "Kannada|A message describing Kannada character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Malayalam, DBLangEngine.GetMessage("msgCharSetMalayalam", "Malayalam|A message describing Arabic character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Oriya, DBLangEngine.GetMessage("msgCharSetOriya", "Oriya|A message describing Oriya character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Punjabi, DBLangEngine.GetMessage("msgCharSetPunjabi", "Punjabi|A message describing Punjabi character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Tamil, DBLangEngine.GetMessage("msgCharSetTamil", "Tamil|A message describing Tamil character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Telugu, DBLangEngine.GetMessage("msgCharSetTelugu", "Telugu|A message describing Telugu character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Vietnamese, DBLangEngine.GetMessage("msgCharSetVietnamese", "Vietnamese|A message describing Vietnamese character set(s).")); - encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.SingleCharacterSets, DBLangEngine.GetMessage("msgCharSetSingleCharacterSets", "Single Character Sets|A message describing Single Character Sets character set(s).")); - } + /// + /// Localizes the character sets of the class. + /// + private void LocalizeCharacterSets() + { + EncodingCharacterSet encodingCharacterSet = new EncodingCharacterSet(); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Arabic, DBLangEngine.GetMessage("msgCharSetArabic", "Arabic|A message describing Arabic character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Baltic, DBLangEngine.GetMessage("msgCharSetBaltic", "Baltic|A message describing Arabic character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Canada, DBLangEngine.GetMessage("msgCharSetCanada", "Canada|A message describing Canada character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Cyrillic, DBLangEngine.GetMessage("msgCharSetCyrillic", "Cyrillic|A message describing Cyrillic character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.CentralEuropean, DBLangEngine.GetMessage("msgCharSetCentralEuropean", "Central European|A message describing Central European character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Chinese, DBLangEngine.GetMessage("msgCharSetChinese", "Chinese|A message describing Chinese character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.DenmarkNorway, DBLangEngine.GetMessage("msgCharSetDenmarkNorway", "Denmark-Norway|A message describing Denmark-Norway character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.FinlandSweden, DBLangEngine.GetMessage("msgCharSetFinlandSweden", "Finland-Sweden|A message describing Finland-Sweden character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.France, DBLangEngine.GetMessage("msgCharSetFrance", "France|A message describing France character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.German, DBLangEngine.GetMessage("msgCharSetGerman", "German|A message describing German character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Greek, DBLangEngine.GetMessage("msgCharSetGreek", "Greek|A message describing Greek character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Hebrew, DBLangEngine.GetMessage("msgCharSetHebrew", "Hebrew|A message describing Hebrew character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Icelandic, DBLangEngine.GetMessage("msgCharSetIcelandic", "Icelandic|A message describing Icelandic character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Italy, DBLangEngine.GetMessage("msgCharSetItaly", "Italy|A message describing Italy character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Japanese, DBLangEngine.GetMessage("msgCharSetJapanese", "Japanese|A message describing Japanese character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Korean, DBLangEngine.GetMessage("msgCharSetKorean", "Korean|A message describing Korean character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Latin, DBLangEngine.GetMessage("msgCharSetLatin", "Latin|A message describing Latin character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Miscellaneous, DBLangEngine.GetMessage("msgCharSetMiscellaneous", "Miscellaneous|A message describing Miscellaneous character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Norwegian, DBLangEngine.GetMessage("msgCharSetNorwegian", "Norwegian|A message describing Norwegian character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.WesternEuropean, DBLangEngine.GetMessage("msgCharSetWesternEuropean", "Western European|A message describing Western European character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Spain, DBLangEngine.GetMessage("msgCharSetSpain", "Spain|A message describing Spain character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Swedish, DBLangEngine.GetMessage("msgCharSetSwedish", "Swedish|A message describing Swedish character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Taiwan, DBLangEngine.GetMessage("msgCharSetTaiwan", "Taiwan|A message describing Taiwan character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Thai, DBLangEngine.GetMessage("msgCharSetThai", "Thai|A message describing Thai character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Turkish, DBLangEngine.GetMessage("msgCharSetTurkish", "Turkish|A message describing Turkish character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Unicode, DBLangEngine.GetMessage("msgCharSetUnicode", "Unicode|A message describing Unicode character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Assamese, DBLangEngine.GetMessage("msgCharSetAssamese", "Assamese|A message describing Assamese character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Bengali, DBLangEngine.GetMessage("msgCharSetBengali", "Bengali|A message describing Bengali character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Devanagari, DBLangEngine.GetMessage("msgCharSetDevanagari", "Devanagari|A message describing Devanagari character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Estonian, DBLangEngine.GetMessage("msgCharSetEstonian", "Estonian|A message describing Estonian character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Kannada, DBLangEngine.GetMessage("msgCharSetKannada", "Kannada|A message describing Kannada character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Malayalam, DBLangEngine.GetMessage("msgCharSetMalayalam", "Malayalam|A message describing Arabic character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Oriya, DBLangEngine.GetMessage("msgCharSetOriya", "Oriya|A message describing Oriya character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Punjabi, DBLangEngine.GetMessage("msgCharSetPunjabi", "Punjabi|A message describing Punjabi character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Tamil, DBLangEngine.GetMessage("msgCharSetTamil", "Tamil|A message describing Tamil character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Telugu, DBLangEngine.GetMessage("msgCharSetTelugu", "Telugu|A message describing Telugu character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.Vietnamese, DBLangEngine.GetMessage("msgCharSetVietnamese", "Vietnamese|A message describing Vietnamese character set(s).")); + encodingCharacterSet.LocalizeCharacterSetName(CharacterSets.SingleCharacterSets, DBLangEngine.GetMessage("msgCharSetSingleCharacterSets", "Single Character Sets|A message describing Single Character Sets character set(s).")); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/Hunspell/HunspellData.cs b/ScriptNotepad/Localization/Hunspell/HunspellData.cs index ac5b0716..b71d4c85 100644 --- a/ScriptNotepad/Localization/Hunspell/HunspellData.cs +++ b/ScriptNotepad/Localization/Hunspell/HunspellData.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,98 +27,97 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Globalization; using System.Text.RegularExpressions; -namespace ScriptNotepad.Localization.Hunspell +namespace ScriptNotepad.Localization.Hunspell; + +/// +/// A class to hold Hunspell dictionary data. +/// +public class HunspellData { /// - /// A class to hold Hunspell dictionary data. + /// Gets or sets the Hunspell culture matching the dictionary file name. + /// + public CultureInfo HunspellCulture { get; set; } + + /// + /// Gets or sets the Hunspell dictionary (*.dic) file. + /// + public string DictionaryFile { get; set; } + + /// + /// Gets or sets the hunspell affix (*.aff) file. + /// + public string AffixFile { get; set; } + + /// + /// Returns a that represents this instance. /// - public class HunspellData + /// A that represents this instance. + public override string ToString() { - /// - /// Gets or sets the Hunspell culture matching the dictionary file name. - /// - public CultureInfo HunspellCulture { get; set; } - - /// - /// Gets or sets the Hunspell dictionary (*.dic) file. - /// - public string DictionaryFile { get; set; } - - /// - /// Gets or sets the hunspell affix (*.aff) file. - /// - public string AffixFile { get; set; } - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() + // get string data of the CultureInfo instance.. + + // a "valid" culture wasn't found so resort to other method to get the string.. + if (HunspellCulture.CultureTypes.HasFlag(CultureTypes.UserCustomCulture) || HunspellCulture.Name == string.Empty) { - // get string data of the CultureInfo instance.. + // do a regex math for the Hunspell dictionary file to see if it's file name contains a valid xx_YY or xx-YY culture name.. + var nameRegex = Regex.Match(Path.GetFileName(DictionaryFile), "\\D{2}(_|-)\\D{2}").Value.Replace('_', '-'); - // a "valid" culture wasn't found so resort to other method to get the string.. - if (HunspellCulture.CultureTypes.HasFlag(CultureTypes.UserCustomCulture) || HunspellCulture.Name == string.Empty) + // if the regex match is empty.. + if (nameRegex == string.Empty) { - // do a regex math for the Hunspell dictionary file to see if it's file name contains a valid xx_YY or xx-YY culture name.. - var nameRegex = Regex.Match(Path.GetFileName(DictionaryFile), "\\D{2}(_|-)\\D{2}").Value.Replace('_', '-'); + // ..get the file name without path and extension.. + nameRegex = Path.GetFileNameWithoutExtension(DictionaryFile); - // if the regex match is empty.. - if (nameRegex == string.Empty) + // if the file name's length is >1 make the first letter to upper case.. + if (nameRegex != null && nameRegex.Length >= 2) { - // ..get the file name without path and extension.. - nameRegex = Path.GetFileNameWithoutExtension(DictionaryFile); - - // if the file name's length is >1 make the first letter to upper case.. - if (nameRegex != null && nameRegex.Length >= 2) - { - nameRegex = nameRegex[0].ToString().ToUpperInvariant() + nameRegex.Substring(1); - } - else - { - // the file name's length is one characters, so make the whole file name to upper case.. - nameRegex = nameRegex?.ToUpperInvariant(); - } + nameRegex = nameRegex[0].ToString().ToUpperInvariant() + nameRegex.Substring(1); } - - // if the ToString() method of a CultureInfo instance returns nothing.. - if (HunspellCulture.ToString() == string.Empty) + else { - // ..return the name gotten using regex and file name.. - return nameRegex ?? string.Empty; + // the file name's length is one characters, so make the whole file name to upper case.. + nameRegex = nameRegex?.ToUpperInvariant(); } - - // otherwise return the CultureInfo instance ToString() with an addition of the name gotten from the file name.. - return HunspellCulture + $" ({nameRegex})"; } - // if a "valid" culture was found, just return it's display name.. - return HunspellCulture.DisplayName; + // if the ToString() method of a CultureInfo instance returns nothing.. + if (HunspellCulture.ToString() == string.Empty) + { + // ..return the name gotten using regex and file name.. + return nameRegex ?? string.Empty; + } + + // otherwise return the CultureInfo instance ToString() with an addition of the name gotten from the file name.. + return HunspellCulture + $" ({nameRegex})"; } - /// - /// Creates a new instance of from the given dictionary file name. - /// - /// The name of the dictionary file. - /// An instance to a class. - public static HunspellData FromDictionaryFile(string fileName) - { - HunspellData result = new HunspellData(); + // if a "valid" culture was found, just return it's display name.. + return HunspellCulture.DisplayName; + } - // the files are excepted to be in format i.e. "en_US.dic".. - string cultureName = Regex.Match(Path.GetFileName(fileName), "\\D{2}(_|-)\\D{2}").Value; - cultureName = cultureName.Replace('_', '-'); + /// + /// Creates a new instance of from the given dictionary file name. + /// + /// The name of the dictionary file. + /// An instance to a class. + public static HunspellData FromDictionaryFile(string fileName) + { + HunspellData result = new HunspellData(); - // get a CultureInfo value for the Hunspell dictionary file.. - result.HunspellCulture = CultureInfo.GetCultureInfo(cultureName); + // the files are excepted to be in format i.e. "en_US.dic".. + string cultureName = Regex.Match(Path.GetFileName(fileName), "\\D{2}(_|-)\\D{2}").Value; + cultureName = cultureName.Replace('_', '-'); - // set the file.. - result.DictionaryFile = fileName; + // get a CultureInfo value for the Hunspell dictionary file.. + result.HunspellCulture = CultureInfo.GetCultureInfo(cultureName); - // set the affix file.. - result.AffixFile = Path.ChangeExtension(fileName, "aff"); + // set the file.. + result.DictionaryFile = fileName; - return result; - } + // set the affix file.. + result.AffixFile = Path.ChangeExtension(fileName, "aff"); + + return result; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/Hunspell/HunspellDictionaryCrawler.cs b/ScriptNotepad/Localization/Hunspell/HunspellDictionaryCrawler.cs index 7867448a..1071c8b5 100644 --- a/ScriptNotepad/Localization/Hunspell/HunspellDictionaryCrawler.cs +++ b/ScriptNotepad/Localization/Hunspell/HunspellDictionaryCrawler.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,59 +28,58 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using ScriptNotepad.UtilityClasses.IO; -namespace ScriptNotepad.Localization.Hunspell +namespace ScriptNotepad.Localization.Hunspell; + +/// +/// A class for searching Hunspell dictionaries from a given folder. +/// Implements the +/// +/// +public class HunspellDictionaryCrawler: ErrorHandlingBase { /// - /// A class for searching Hunspell dictionaries from a given folder. - /// Implements the + /// Crawls the directory containing Hunspell dictionary and affix files. /// - /// - public class HunspellDictionaryCrawler: ErrorHandlingBase + /// The path to search the dictionaries from. + /// List<HunspellData>. + public static List CrawlDirectory(string path) { - /// - /// Crawls the directory containing Hunspell dictionary and affix files. - /// - /// The path to search the dictionaries from. - /// List<HunspellData>. - public static List CrawlDirectory(string path) - { - // create a new instance of the DirectoryCrawler class by user given "arguments".. - DirectoryCrawler crawler = new DirectoryCrawler(path, DirectoryCrawler.SearchTypeMatch.Regex, - "*.dic", true); + // create a new instance of the DirectoryCrawler class by user given "arguments".. + DirectoryCrawler crawler = new DirectoryCrawler(path, DirectoryCrawler.SearchTypeMatch.Regex, + "*.dic", true); - // search for the Hunspell dictionary files (*.dic).. - var files = crawler.GetCrawlResult(); + // search for the Hunspell dictionary files (*.dic).. + var files = crawler.GetCrawlResult(); - // initialize a return value.. - List result = new List(); + // initialize a return value.. + List result = new List(); - // loop through the found dictionary files (*.dic).. - foreach (var file in files) + // loop through the found dictionary files (*.dic).. + foreach (var file in files) + { + try { - try - { - // create a new HunspellData class instance.. - var data = HunspellData.FromDictionaryFile(file); - - // validate that there is a affix (*.aff) pair for the found dictionary file (*.dic).. - if (!File.Exists(data.DictionaryFile) || !File.Exists(data.AffixFile)) - { - // ..if not, do continue.. - continue; - } + // create a new HunspellData class instance.. + var data = HunspellData.FromDictionaryFile(file); - // the validation was successful, so add the data to the result.. - result.Add(data); - } - catch (Exception ex) + // validate that there is a affix (*.aff) pair for the found dictionary file (*.dic).. + if (!File.Exists(data.DictionaryFile) || !File.Exists(data.AffixFile)) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + // ..if not, do continue.. + continue; } - } - // return the result.. - return result; + // the validation was successful, so add the data to the result.. + result.Add(data); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } } + + // return the result.. + return result; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/IStaticMessageProvider.cs b/ScriptNotepad/Localization/IStaticMessageProvider.cs index 2c3ab5bd..4be2535e 100644 --- a/ScriptNotepad/Localization/IStaticMessageProvider.cs +++ b/ScriptNotepad/Localization/IStaticMessageProvider.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,19 +26,18 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; -namespace ScriptNotepad.Localization +namespace ScriptNotepad.Localization; + +/// +/// An interface providing access to the messages. +/// +public interface IStaticMessageProvider { /// - /// An interface providing access to the messages. + /// Gets the message by the specified name localized to the current software culture setting. /// - public interface IStaticMessageProvider - { - /// - /// Gets the message by the specified name localized to the current software culture setting. - /// - /// Name of the message. - /// The default message to fall back into if a localized message was not found. - /// A localized value for the specified message name. - string GetMessage(string messageName, string defaultMessage); - } -} + /// Name of the message. + /// The default message to fall back into if a localized message was not found. + /// A localized value for the specified message name. + string GetMessage(string messageName, string defaultMessage); +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/StaticLocalizeFileDialog.cs b/ScriptNotepad/Localization/StaticLocalizeFileDialog.cs index 7b8e8f82..40836f98 100644 --- a/ScriptNotepad/Localization/StaticLocalizeFileDialog.cs +++ b/ScriptNotepad/Localization/StaticLocalizeFileDialog.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,124 +27,123 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using VPKSoft.LangLib; -namespace ScriptNotepad.Localization +namespace ScriptNotepad.Localization; + +/// +/// A class to localize file dialog extensions. +/// +public static class StaticLocalizeFileDialog { /// - /// A class to localize file dialog extensions. + /// Localizes a given file dialog and adds the localized Hunspell dictionary file filter to it's Filter property. /// - public static class StaticLocalizeFileDialog + /// The file dialog to localize. + public static void InitOpenHunspellDictionaryDialog(FileDialog dialog) { - /// - /// Localizes a given file dialog and adds the localized Hunspell dictionary file filter to it's Filter property. - /// - /// The file dialog to localize. - public static void InitOpenHunspellDictionaryDialog(FileDialog dialog) - { - dialog.Filter = string.Empty; - dialog.Filter += DBLangEngine.GetStatMessage("msgFileDic", "Hunspell dictionary file|*.dic|A text in a file dialog filter to indicate a Hunspell dictionary file"); - } + dialog.Filter = string.Empty; + dialog.Filter += DBLangEngine.GetStatMessage("msgFileDic", "Hunspell dictionary file|*.dic|A text in a file dialog filter to indicate a Hunspell dictionary file"); + } - /// - /// Localizes a given file dialog and adds the localized Hunspell dictionary file filter to it's Filter property. - /// - /// The file dialog to localize. - public static void InitOpenHunspellAffixFileDialog(FileDialog dialog) - { - dialog.Filter = string.Empty; - dialog.Filter += DBLangEngine.GetStatMessage("msgFileAffix", "Hunspell affix file |*.aff|A text in a file dialog filter to indicate a Hunspell affix file"); - } + /// + /// Localizes a given file dialog and adds the localized Hunspell dictionary file filter to it's Filter property. + /// + /// The file dialog to localize. + public static void InitOpenHunspellAffixFileDialog(FileDialog dialog) + { + dialog.Filter = string.Empty; + dialog.Filter += DBLangEngine.GetStatMessage("msgFileAffix", "Hunspell affix file |*.aff|A text in a file dialog filter to indicate a Hunspell affix file"); + } - /// - /// Localizes a given file dialog and adds the localized XML file filter to it's Filter property. - /// - /// The file dialog to localize. - public static void InitOpenXmlFileDialog(FileDialog dialog) - { - dialog.Filter = string.Empty; - dialog.Filter += DBLangEngine.GetStatMessage("msgeXtensibleMarkupLanguageFile", "eXtensible Markup Language file|*.xml;*.xsml;*.xls;*.xsd;*.kml;*.wsdl;*.xlf;*.xliff|A text in a file dialog indicating eXtensible Markup Language files"); - } + /// + /// Localizes a given file dialog and adds the localized XML file filter to it's Filter property. + /// + /// The file dialog to localize. + public static void InitOpenXmlFileDialog(FileDialog dialog) + { + dialog.Filter = string.Empty; + dialog.Filter += DBLangEngine.GetStatMessage("msgeXtensibleMarkupLanguageFile", "eXtensible Markup Language file|*.xml;*.xsml;*.xls;*.xsd;*.kml;*.wsdl;*.xlf;*.xliff|A text in a file dialog indicating eXtensible Markup Language files"); + } - /// - /// Localizes a given file dialog and adds the localized custom spell check library file filter (zip) to it's Filter property. - /// - /// The file dialog to localize. - public static void InitOpenSpellCheckerZip(FileDialog dialog) - { - dialog.Filter = string.Empty; - dialog.Filter += DBLangEngine.GetStatMessage("msgCustomSpellCheckerZipFile", "Custom spell check library|*.zip|A text in a file dialog filter to indicate a custom spell checker library in a compressed zip package"); - } + /// + /// Localizes a given file dialog and adds the localized custom spell check library file filter (zip) to it's Filter property. + /// + /// The file dialog to localize. + public static void InitOpenSpellCheckerZip(FileDialog dialog) + { + dialog.Filter = string.Empty; + dialog.Filter += DBLangEngine.GetStatMessage("msgCustomSpellCheckerZipFile", "Custom spell check library|*.zip|A text in a file dialog filter to indicate a custom spell checker library in a compressed zip package"); + } - /// - /// Localizes a given file dialog with a HTML filter. - /// - /// The file dialog to localize. - // ReSharper disable once InconsistentNaming - public static void InitHTMLFileDialog(FileDialog dialog) - { - dialog.Filter = DBLangEngine.GetStatMessage("msgHyperTextMarkupLanguageFileHTML", "Hyper Text Markup Language file|*.html|A text in a file dialog indicating Hyper Text Markup Language files (HTML only)"); - } + /// + /// Localizes a given file dialog with a HTML filter. + /// + /// The file dialog to localize. + // ReSharper disable once InconsistentNaming + public static void InitHTMLFileDialog(FileDialog dialog) + { + dialog.Filter = DBLangEngine.GetStatMessage("msgHyperTextMarkupLanguageFileHTML", "Hyper Text Markup Language file|*.html|A text in a file dialog indicating Hyper Text Markup Language files (HTML only)"); + } - /// - /// Localizes a given file dialog and adds the localized lexer file types to it's Filter property. - /// - /// The file dialog to localize. - public static void InitFileDialog(FileDialog dialog) - { - dialog.Filter = string.Empty; - dialog.Filter += DBLangEngine.GetStatMessage("msgAllFileTypes", "All types|*.*|A text in a file dialog indicating all files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgNormalTextFile", "Normal text file|*.txt|A text in a file dialog indicating .txt files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgFlashActionScriptFile", "Flash ActionScript file|*.as;*.mx|A text in a file dialog indicating Flash ActionScript files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgAdaFile", "Ada file|*.ada;*.ads;*.adb|A text in a file dialog indicating Ada files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgAssemblySourceFile", "Assembly language source file|*.asm|A text in a file dialog indicating Assembly language source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgActiveServerPagesScriptFile", "Active Server Pages script file|*.asp|A text in a file dialog indicating Active Server Pages script files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgAutoItFile", "AutoIt|*.au3|A text in a file dialog indicating AutoIt files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgUnixScriptFile", "Unix script file|*.sh;*.bsh|A text in a file dialog indicating Unix script files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgBatchFile", "Batch file|*.bat;*.cmd;*.nt|A text in a file dialog indicating Batch files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCSourceFile", "C source file|*.c|A text in a file dialog indicating C source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCategoricalAbstractMachineLanguageFile", "Categorical Abstract Machine Language|*.ml;*.mli;*.sml;*.thy|A text in a file dialog indicating Categorical Abstract Machine Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCMakeFile", "CMake file|*.cmake|A text in a file dialog indicating CMake files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCommonBusinessOrientedLanguage", "Common Business Oriented Language|*.cbl;*.cbd;*.cdb;*.cdc;*.cob|A text in a file dialog indicating Common Business Oriented Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCoffeeScriptLanguage", "Coffee Script file|*.litcoffee|A text in a file dialog indicating Coffee Script files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCPPSourceFile", "C++ source file|*.h;*.hpp;*.hxx;*.cpp;*.cxx;*.cc|A text in a file dialog indicating C++ source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCSSourceFile", "C# source file|*.cs|A text in a file dialog indicating C# source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCSSSourceFile", "Cascading Style Sheets File|*.css|A text in a file dialog indicating Cascading Style Sheets files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgDSourceFile", "D programming language|*.d|A text in a file dialog indicating D programming language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgDiffFile", "Diff file|*.diff;*.patch|A text in a file dialog indicating Diff files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgFortranFreeFormSourceFile", "Fortran free form source file|*.f;*.for;*.f90;*.f95;*.f2k|A text in a file dialog indicating Fortran free form source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgHaskellSourceFile", "Haskell source file|*.hs;*.lhs;*.as;*.las|A text in a file dialog indicating Haskell source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgHyperTextMarkupLanguageFile", "Hyper Text Markup Language file|*.html;*.htm;*.shtml;*.shtm;*.xhtml;*.hta|A text in a file dialog indicating Hyper Text Markup Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMSIniFile", "MS INI file|*.ini;*.inf;*.reg;*.url|A text in a file dialog indicating MS INI files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgInnoSetupScriptFile", "Inno Setup Script File|*.iss|A text in a file dialog indicating Inno Setup Script files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgJavaSourceFile", "Java source file|*.java|A text in a file dialog indicating Java source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgJavaScriptFile", "Java script file|*.js|A text in a file dialog indicating Java script files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgJavaServerPagesFile", "JavaServer pages file|*.jsp|A text in a file dialog indicating JavaServer pages files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgKiXtartFile", "KiXtart file|*.kix|A text in a file dialog indicating KiXtart files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgListProcessingLanguageFile", "List Processing language file|*.lsp;*.lisp|A text in a file dialog indicating List Processing language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgLuaSourceFile", "Lua source file|*.lua|A text in a file dialog indicating Lua source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMakeFile", "Makefile|*.mak|A text in a file dialog indicating Makefile files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMATrixLABoratoryFile", "MATrix LABoratory file|*.m|A text in a file dialog indicating MATrix LABoratory files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMSDOSStyleAsciiArtFile", "MSDOS Style/ASCII Art file|*.nfo|A text in a file dialog indicating MSDOS Style/ASCII Art file files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgNullsoftScriptableInstallSystemScriptFile", "Nullsoft Scriptable Install System script file|*.nsi;*.nsh|A text in a file dialog indicating Nullsoft Scriptable Install System script files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPascalSourceFile", "Pascal source file|*.pas|A text in a file dialog indicating Pascal source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPerlSourceFile", "Perl source file|*.pl;*.pm;*.plx|A text in a file dialog indicating Perl source files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPHPHypertextPreprocessorFile", "PHP Hypertext Preprocessor file|*.php;*.php3;*.phtml|A text in a file dialog indicating PHP Hypertext Preprocessor files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPostScriptFile", "PostScript file|*.ps|A text in a file dialog indicating PostScript files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgWindowsPowerShellFile", "Windows PowerShell file|*.ps1;*.psm1|A text in a file dialog indicating Windows PowerShell files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPropertiesFile", "Properties file|*.properties|A text in a file dialog indicating Properties files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPythonFile", "Python file|*.py;*.pyw|A text in a file dialog indicating Python files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgRProgrammingLanguageFile", "R programming language file|*.r|A text in a file dialog indicating R programming language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgWindowsResourceFile", "Windows resource file|*.rc|A text in a file dialog indicating Windows resource files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgRubyFile", "Ruby file|*.rb;*.rbw|A text in a file dialog indicating Ruby files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgSchemeFile", "Scheme file|*.scm;*.smd;*.ss|A text in a file dialog indicating Scheme files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgSmalltalkFile", "Smalltalk file|*.st|A text in a file dialog indicating Smalltalk files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgStructuredQueryLanguageFile", "Structured Query Language file|*.sql;*.sql_script|A text in a file dialog indicating Structured Query Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgToolCommandLanguageFile", "Tool Command Language file|*.tlc|A text in a file dialog indicating Tool Command Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgTeXFile", "TeX file|*.tex|A text in a file dialog indicating TeX files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgVisualBasicFile", "Visual Basic file|*.vb;*.vbs|A text in a file dialog indicating Visual Basic files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgVerilogFile", "Verilog file|*.vs;*.sv;*.vh;*.svh|A text in a file dialog indicating Verilog files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgVHSICHardwareDescriptionLanguageFile", "VHSIC Hardware Description Language file|*.vhd;*.vhdl|A text in a file dialog indicating VHSIC Hardware Description Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgeXtensibleMarkupLanguageFile", "eXtensible Markup Language file|*.xml;*.xsml;*.xls;*.xsd;*.kml;*.wsdl;*.xlf;*.xliff|A text in a file dialog indicating eXtensible Markup Language files"); - dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgYAMLFile", "YAML Ain't a Markup Language file|*.yml|A text in a file dialog indicating YAML Ain't a Markup Language files"); - } + /// + /// Localizes a given file dialog and adds the localized lexer file types to it's Filter property. + /// + /// The file dialog to localize. + public static void InitFileDialog(FileDialog dialog) + { + dialog.Filter = string.Empty; + dialog.Filter += DBLangEngine.GetStatMessage("msgAllFileTypes", "All types|*.*|A text in a file dialog indicating all files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgNormalTextFile", "Normal text file|*.txt|A text in a file dialog indicating .txt files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgFlashActionScriptFile", "Flash ActionScript file|*.as;*.mx|A text in a file dialog indicating Flash ActionScript files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgAdaFile", "Ada file|*.ada;*.ads;*.adb|A text in a file dialog indicating Ada files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgAssemblySourceFile", "Assembly language source file|*.asm|A text in a file dialog indicating Assembly language source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgActiveServerPagesScriptFile", "Active Server Pages script file|*.asp|A text in a file dialog indicating Active Server Pages script files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgAutoItFile", "AutoIt|*.au3|A text in a file dialog indicating AutoIt files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgUnixScriptFile", "Unix script file|*.sh;*.bsh|A text in a file dialog indicating Unix script files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgBatchFile", "Batch file|*.bat;*.cmd;*.nt|A text in a file dialog indicating Batch files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCSourceFile", "C source file|*.c|A text in a file dialog indicating C source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCategoricalAbstractMachineLanguageFile", "Categorical Abstract Machine Language|*.ml;*.mli;*.sml;*.thy|A text in a file dialog indicating Categorical Abstract Machine Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCMakeFile", "CMake file|*.cmake|A text in a file dialog indicating CMake files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCommonBusinessOrientedLanguage", "Common Business Oriented Language|*.cbl;*.cbd;*.cdb;*.cdc;*.cob|A text in a file dialog indicating Common Business Oriented Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCoffeeScriptLanguage", "Coffee Script file|*.litcoffee|A text in a file dialog indicating Coffee Script files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCPPSourceFile", "C++ source file|*.h;*.hpp;*.hxx;*.cpp;*.cxx;*.cc|A text in a file dialog indicating C++ source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCSSourceFile", "C# source file|*.cs|A text in a file dialog indicating C# source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgCSSSourceFile", "Cascading Style Sheets File|*.css|A text in a file dialog indicating Cascading Style Sheets files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgDSourceFile", "D programming language|*.d|A text in a file dialog indicating D programming language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgDiffFile", "Diff file|*.diff;*.patch|A text in a file dialog indicating Diff files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgFortranFreeFormSourceFile", "Fortran free form source file|*.f;*.for;*.f90;*.f95;*.f2k|A text in a file dialog indicating Fortran free form source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgHaskellSourceFile", "Haskell source file|*.hs;*.lhs;*.as;*.las|A text in a file dialog indicating Haskell source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgHyperTextMarkupLanguageFile", "Hyper Text Markup Language file|*.html;*.htm;*.shtml;*.shtm;*.xhtml;*.hta|A text in a file dialog indicating Hyper Text Markup Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMSIniFile", "MS INI file|*.ini;*.inf;*.reg;*.url|A text in a file dialog indicating MS INI files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgInnoSetupScriptFile", "Inno Setup Script File|*.iss|A text in a file dialog indicating Inno Setup Script files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgJavaSourceFile", "Java source file|*.java|A text in a file dialog indicating Java source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgJavaScriptFile", "Java script file|*.js|A text in a file dialog indicating Java script files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgJavaServerPagesFile", "JavaServer pages file|*.jsp|A text in a file dialog indicating JavaServer pages files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgKiXtartFile", "KiXtart file|*.kix|A text in a file dialog indicating KiXtart files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgListProcessingLanguageFile", "List Processing language file|*.lsp;*.lisp|A text in a file dialog indicating List Processing language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgLuaSourceFile", "Lua source file|*.lua|A text in a file dialog indicating Lua source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMakeFile", "Makefile|*.mak|A text in a file dialog indicating Makefile files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMATrixLABoratoryFile", "MATrix LABoratory file|*.m|A text in a file dialog indicating MATrix LABoratory files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgMSDOSStyleAsciiArtFile", "MSDOS Style/ASCII Art file|*.nfo|A text in a file dialog indicating MSDOS Style/ASCII Art file files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgNullsoftScriptableInstallSystemScriptFile", "Nullsoft Scriptable Install System script file|*.nsi;*.nsh|A text in a file dialog indicating Nullsoft Scriptable Install System script files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPascalSourceFile", "Pascal source file|*.pas|A text in a file dialog indicating Pascal source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPerlSourceFile", "Perl source file|*.pl;*.pm;*.plx|A text in a file dialog indicating Perl source files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPHPHypertextPreprocessorFile", "PHP Hypertext Preprocessor file|*.php;*.php3;*.phtml|A text in a file dialog indicating PHP Hypertext Preprocessor files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPostScriptFile", "PostScript file|*.ps|A text in a file dialog indicating PostScript files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgWindowsPowerShellFile", "Windows PowerShell file|*.ps1;*.psm1|A text in a file dialog indicating Windows PowerShell files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPropertiesFile", "Properties file|*.properties|A text in a file dialog indicating Properties files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgPythonFile", "Python file|*.py;*.pyw|A text in a file dialog indicating Python files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgRProgrammingLanguageFile", "R programming language file|*.r|A text in a file dialog indicating R programming language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgWindowsResourceFile", "Windows resource file|*.rc|A text in a file dialog indicating Windows resource files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgRubyFile", "Ruby file|*.rb;*.rbw|A text in a file dialog indicating Ruby files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgSchemeFile", "Scheme file|*.scm;*.smd;*.ss|A text in a file dialog indicating Scheme files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgSmalltalkFile", "Smalltalk file|*.st|A text in a file dialog indicating Smalltalk files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgStructuredQueryLanguageFile", "Structured Query Language file|*.sql;*.sql_script|A text in a file dialog indicating Structured Query Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgToolCommandLanguageFile", "Tool Command Language file|*.tlc|A text in a file dialog indicating Tool Command Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgTeXFile", "TeX file|*.tex|A text in a file dialog indicating TeX files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgVisualBasicFile", "Visual Basic file|*.vb;*.vbs|A text in a file dialog indicating Visual Basic files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgVerilogFile", "Verilog file|*.vs;*.sv;*.vh;*.svh|A text in a file dialog indicating Verilog files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgVHSICHardwareDescriptionLanguageFile", "VHSIC Hardware Description Language file|*.vhd;*.vhdl|A text in a file dialog indicating VHSIC Hardware Description Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgeXtensibleMarkupLanguageFile", "eXtensible Markup Language file|*.xml;*.xsml;*.xls;*.xsd;*.kml;*.wsdl;*.xlf;*.xliff|A text in a file dialog indicating eXtensible Markup Language files"); + dialog.Filter += @"|" + DBLangEngine.GetStatMessage("msgYAMLFile", "YAML Ain't a Markup Language file|*.yml|A text in a file dialog indicating YAML Ain't a Markup Language files"); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/StaticMessageLocalizationProvider.cs b/ScriptNotepad/Localization/StaticMessageLocalizationProvider.cs index 5d33307c..2bbb503d 100644 --- a/ScriptNotepad/Localization/StaticMessageLocalizationProvider.cs +++ b/ScriptNotepad/Localization/StaticMessageLocalizationProvider.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,38 +26,37 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; -namespace ScriptNotepad.Localization +namespace ScriptNotepad.Localization; + +/// +/// A class to provide static localized messages from the . +/// Implements the +/// +/// +public class StaticMessageLocalizationProvider: IStaticMessageProvider { /// - /// A class to provide static localized messages from the . - /// Implements the + /// Prevents a default instance of the class from being created. + /// + private StaticMessageLocalizationProvider() + { + Instance = this; + } + + /// + /// Gets or sets the of this class. + /// + /// The instance. + public static StaticMessageLocalizationProvider Instance { get; set; } = new(); + + /// + /// Gets the message by the specified name localized to the current software culture setting. /// - /// - public class StaticMessageLocalizationProvider: IStaticMessageProvider + /// Name of the message. + /// The default message to fall back into if a localized message was not found. + /// A localized value for the specified message name. + public string GetMessage(string messageName, string defaultMessage) { - /// - /// Prevents a default instance of the class from being created. - /// - private StaticMessageLocalizationProvider() - { - Instance = this; - } - - /// - /// Gets or sets the of this class. - /// - /// The instance. - public static StaticMessageLocalizationProvider Instance { get; set; } = new(); - - /// - /// Gets the message by the specified name localized to the current software culture setting. - /// - /// Name of the message. - /// The default message to fall back into if a localized message was not found. - /// A localized value for the specified message name. - public string GetMessage(string messageName, string defaultMessage) - { - return DBLangEngine.GetStatMessage(messageName, defaultMessage); - } + return DBLangEngine.GetStatMessage(messageName, defaultMessage); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Localization/StatusStripTexts.cs b/ScriptNotepad/Localization/StatusStripTexts.cs index 9b9e5633..aeab9e38 100644 --- a/ScriptNotepad/Localization/StatusStripTexts.cs +++ b/ScriptNotepad/Localization/StatusStripTexts.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -31,321 +31,320 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.ScintillaTabbedTextControl; -namespace ScriptNotepad.Localization +namespace ScriptNotepad.Localization; + +/// +/// A helper class to set localized status tool strip status label texts. +/// +public class StatusStripTexts { /// - /// A helper class to set localized status tool strip status label texts. + /// Gets or sets a status label for a line and a column. + /// + public static ToolStripStatusLabel LabelLineColumn { get; set; } + + /// + /// Gets or sets a status label for a line, a column and a selection length of a selection. /// - public class StatusStripTexts + public static ToolStripStatusLabel LabelLineColumnSelection { get; set; } + + /// + /// Gets or sets a status label for a count of lines in a document and the size of the document in characters. + /// + public static ToolStripStatusLabel LabelDocumentLinesSize { get; set; } + + /// + /// Gets or sets a status label for a line ending type text. + /// + public static ToolStripStatusLabel LabelLineEnding { get; set; } + + /// + /// Gets or sets a status label for a file encoding name text. + /// + public static ToolStripStatusLabel LabelEncoding { get; set; } + + /// + /// Gets or sets a status label for a session name text. + /// + public static ToolStripStatusLabel LabelSessionName { get; set; } + + /// + /// Gets or sets a status label indicating whether a document editor is in insert or in override mode text. + /// + public static ToolStripStatusLabel LabelModeInsertOverride { get; set; } + + /// + /// Gets or sets a status label text translated from 'Zoom:'. + /// + public static ToolStripStatusLabel LabelZoom { get; set; } + + /// + /// Gets or sets the tab count label. + /// + /// The tab count label. + public static ToolStripStatusLabel LabelTab { get; set; } + + /// + /// Gets or sets a value indicating whether the status strip labels have been assigned. + /// + public static bool Initialized { - /// - /// Gets or sets a status label for a line and a column. - /// - public static ToolStripStatusLabel LabelLineColumn { get; set; } - - /// - /// Gets or sets a status label for a line, a column and a selection length of a selection. - /// - public static ToolStripStatusLabel LabelLineColumnSelection { get; set; } - - /// - /// Gets or sets a status label for a count of lines in a document and the size of the document in characters. - /// - public static ToolStripStatusLabel LabelDocumentLinesSize { get; set; } - - /// - /// Gets or sets a status label for a line ending type text. - /// - public static ToolStripStatusLabel LabelLineEnding { get; set; } - - /// - /// Gets or sets a status label for a file encoding name text. - /// - public static ToolStripStatusLabel LabelEncoding { get; set; } - - /// - /// Gets or sets a status label for a session name text. - /// - public static ToolStripStatusLabel LabelSessionName { get; set; } - - /// - /// Gets or sets a status label indicating whether a document editor is in insert or in override mode text. - /// - public static ToolStripStatusLabel LabelModeInsertOverride { get; set; } - - /// - /// Gets or sets a status label text translated from 'Zoom:'. - /// - public static ToolStripStatusLabel LabelZoom { get; set; } - - /// - /// Gets or sets the tab count label. - /// - /// The tab count label. - public static ToolStripStatusLabel LabelTab { get; set; } - - /// - /// Gets or sets a value indicating whether the status strip labels have been assigned. - /// - public static bool Initialized + get => LabelLineColumn != null && + LabelLineColumnSelection != null && + LabelDocumentLinesSize != null && + LabelLineEnding != null && + LabelEncoding != null && + LabelSessionName != null && + LabelModeInsertOverride != null && + LabelZoom != null && + LabelTab != null; + + set { - get => LabelLineColumn != null && - LabelLineColumnSelection != null && - LabelDocumentLinesSize != null && - LabelLineEnding != null && - LabelEncoding != null && - LabelSessionName != null && - LabelModeInsertOverride != null && - LabelZoom != null && - LabelTab != null; - - set + if (!value) { - if (!value) - { - UnInitLabels(); - } + UnInitLabels(); } } + } - /// - /// Initializes the status strip labels with given values. - /// - /// The status label for a line and a column. - /// The status label for a line, a column and a selection length of a selection. - /// The status label for a count of lines in a document and the size of the document in characters. - /// The status label for a line ending type text. - /// The status label for a file encoding name text. - /// The status label for a session name text. - /// The status label indicating whether a document editor is in insert or in override mode text. - /// A status label indicating the zoom value. - /// The status label indicating the selected tab page in the view. - public static void InitLabels( - ToolStripStatusLabel labelLineColumn, - ToolStripStatusLabel labelLineColumnSelection, - ToolStripStatusLabel labelDocumentLinesSize, - ToolStripStatusLabel labelLineEnding, - ToolStripStatusLabel labelEncoding, - ToolStripStatusLabel labelSessionName, - ToolStripStatusLabel labelModeInsertOverride, - ToolStripStatusLabel labelZoom, - ToolStripStatusLabel labelTab) - { - LabelLineColumn = labelLineColumn; - LabelLineColumnSelection = labelLineColumnSelection; - LabelDocumentLinesSize = labelDocumentLinesSize; - LabelLineEnding = labelLineEnding; - LabelEncoding = labelEncoding; - LabelSessionName = labelSessionName; - LabelModeInsertOverride = labelModeInsertOverride; - LabelZoom = labelZoom; - LabelTab = labelTab; - } + /// + /// Initializes the status strip labels with given values. + /// + /// The status label for a line and a column. + /// The status label for a line, a column and a selection length of a selection. + /// The status label for a count of lines in a document and the size of the document in characters. + /// The status label for a line ending type text. + /// The status label for a file encoding name text. + /// The status label for a session name text. + /// The status label indicating whether a document editor is in insert or in override mode text. + /// A status label indicating the zoom value. + /// The status label indicating the selected tab page in the view. + public static void InitLabels( + ToolStripStatusLabel labelLineColumn, + ToolStripStatusLabel labelLineColumnSelection, + ToolStripStatusLabel labelDocumentLinesSize, + ToolStripStatusLabel labelLineEnding, + ToolStripStatusLabel labelEncoding, + ToolStripStatusLabel labelSessionName, + ToolStripStatusLabel labelModeInsertOverride, + ToolStripStatusLabel labelZoom, + ToolStripStatusLabel labelTab) + { + LabelLineColumn = labelLineColumn; + LabelLineColumnSelection = labelLineColumnSelection; + LabelDocumentLinesSize = labelDocumentLinesSize; + LabelLineEnding = labelLineEnding; + LabelEncoding = labelEncoding; + LabelSessionName = labelSessionName; + LabelModeInsertOverride = labelModeInsertOverride; + LabelZoom = labelZoom; + LabelTab = labelTab; + } - /// - /// Un-initializes the status strip labels with given values. - /// - public static void UnInitLabels() - { - LabelLineColumn = null; - LabelLineColumnSelection = null; - LabelDocumentLinesSize = null; - LabelLineEnding = null; - LabelEncoding = null; - LabelSessionName = null; - LabelModeInsertOverride = null; - LabelZoom = null; - } + /// + /// Un-initializes the status strip labels with given values. + /// + public static void UnInitLabels() + { + LabelLineColumn = null; + LabelLineColumnSelection = null; + LabelDocumentLinesSize = null; + LabelLineEnding = null; + LabelEncoding = null; + LabelSessionName = null; + LabelModeInsertOverride = null; + LabelZoom = null; + } - /// - /// Sets the name of the session for the corresponding status strip label. - /// - /// Name of the session to set for the label. - public static void SetSessionName(string sessionName) + /// + /// Sets the name of the session for the corresponding status strip label. + /// + /// Name of the session to set for the label. + public static void SetSessionName(string sessionName) + { + // the tool strip labels must have been assigned.. + if (!Initialized) { - // the tool strip labels must have been assigned.. - if (!Initialized) - { - // ..so to avoid a null reference just return.. - return; - } - - LabelSessionName.Text = - DBLangEngine.GetStatMessage("msgSessionName", "Session: {0}|A message describing a session name with the name as a parameter", sessionName); + // ..so to avoid a null reference just return.. + return; } - /// - /// Sets the document size status strip label's text. - /// - /// The document of which properties to use to set the status strip values to indicate. - public static void SetDocumentSizeText(ScintillaTabbedDocument document) + LabelSessionName.Text = + DBLangEngine.GetStatMessage("msgSessionName", "Session: {0}|A message describing a session name with the name as a parameter", sessionName); + } + + /// + /// Sets the document size status strip label's text. + /// + /// The document of which properties to use to set the status strip values to indicate. + public static void SetDocumentSizeText(ScintillaTabbedDocument document) + { + // the tool strip labels must have been assigned.. + if (!Initialized) { - // the tool strip labels must have been assigned.. - if (!Initialized) - { - // ..so to avoid a null reference just return.. - return; - } + // ..so to avoid a null reference just return.. + return; + } - LabelDocumentLinesSize.Text = - DBLangEngine.GetStatMessage("msgDocSizeLines", "length: {0} lines: {1}, pos: {2}|As in the ScintillaNET document size in lines and in characters and the current location in characters", + LabelDocumentLinesSize.Text = + DBLangEngine.GetStatMessage("msgDocSizeLines", "length: {0} lines: {1}, pos: {2}|As in the ScintillaNET document size in lines and in characters and the current location in characters", document.Scintilla.Text.Length, document.Scintilla.Lines.Count, document.Scintilla.CurrentPosition); - } + } - /// - /// Sets the main status strip values for the currently active document.. - /// - /// The document of which properties to use to set the status strip values to indicate. - /// Name of the session to set for the label. - public static void SetStatusStringText(ScintillaTabbedDocument document, string sessionName) + /// + /// Sets the main status strip values for the currently active document.. + /// + /// The document of which properties to use to set the status strip values to indicate. + /// Name of the session to set for the label. + public static void SetStatusStringText(ScintillaTabbedDocument document, string sessionName) + { + // first check the parameter validity.. + if (document == null) { - // first check the parameter validity.. - if (document == null) - { - return; - } + return; + } - // the tool strip labels must have been assigned.. - if (!Initialized) - { - // ..so to avoid a null reference just return.. - return; - } + // the tool strip labels must have been assigned.. + if (!Initialized) + { + // ..so to avoid a null reference just return.. + return; + } - LabelLineColumn.Text = - DBLangEngine.GetStatMessage("msgColLine", "Line: {0} Col: {1}|As in the current column and the current line in a ScintillaNET control", + LabelLineColumn.Text = + DBLangEngine.GetStatMessage("msgColLine", "Line: {0} Col: {1}|As in the current column and the current line in a ScintillaNET control", document.LineNumber + 1, document.Column + 1); - LabelLineColumnSelection.Text = - DBLangEngine.GetStatMessage("msgColLineSelection", "Sel1: {0}|{1} Sel2: {2}|{3} Len: {4}|The selection start, end and length in a ScintillaNET control in columns, lines and character count", + LabelLineColumnSelection.Text = + DBLangEngine.GetStatMessage("msgColLineSelection", "Sel1: {0}|{1} Sel2: {2}|{3} Len: {4}|The selection start, end and length in a ScintillaNET control in columns, lines and character count", document.SelectionStartLine + 1, document.SelectionStartColumn + 1, document.SelectionEndLine + 1, document.SelectionEndColumn + 1, document.SelectionLength); - SetDocumentSizeText(document); + SetDocumentSizeText(document); - LabelLineEnding.Text = string.Empty; + LabelLineEnding.Text = string.Empty; - if (document.Tag != null) - { - var fileSave = (FileSave)document.Tag; + if (document.Tag != null) + { + var fileSave = (FileSave)document.Tag; - LabelLineEnding.Text = fileSave.FileLineEndingText(); + LabelLineEnding.Text = fileSave.FileLineEndingText(); - LabelEncoding.Text = - DBLangEngine.GetStatMessage("msgShortEncodingPreText", "Encoding: |A short text to describe a detected encoding value (i.e.) Unicode (UTF-8).") + - fileSave.GetEncoding().EncodingName; + LabelEncoding.Text = + DBLangEngine.GetStatMessage("msgShortEncodingPreText", "Encoding: |A short text to describe a detected encoding value (i.e.) Unicode (UTF-8).") + + fileSave.GetEncoding().EncodingName; + + // special handling for unicode.. + if (fileSave.GetEncoding().CodePage == Encoding.UTF8.CodePage || + fileSave.GetEncoding().CodePage == Encoding.Unicode.CodePage || + fileSave.GetEncoding().CodePage == Encoding.UTF32.CodePage) + { + LabelEncoding.Text += @": "; - // special handling for unicode.. - if (fileSave.GetEncoding().CodePage == Encoding.UTF8.CodePage || - fileSave.GetEncoding().CodePage == Encoding.Unicode.CodePage || - fileSave.GetEncoding().CodePage == Encoding.UTF32.CodePage) + LabelEncoding.Text += fileSave.GetEncoding().EmitsBom() + ? DBLangEngine.GetStatMessage("msgUnicodeBomShort", + "BOM|A short message describing that an unicode encoding contains a BOM (byte-order-mark)") + : DBLangEngine.GetStatMessage("msgUnicodeNoBomShort", + "NO-BOM|A short message describing that an unicode encoding doesn't contain a BOM (byte-order-mark)"); + + // UTF8 has only one byte order so skip the UTF8.. + if (fileSave.GetEncoding().CodePage != Encoding.UTF8.CodePage) { - LabelEncoding.Text += @": "; - - LabelEncoding.Text += fileSave.GetEncoding().EmitsBom() - ? DBLangEngine.GetStatMessage("msgUnicodeBomShort", - "BOM|A short message describing that an unicode encoding contains a BOM (byte-order-mark)") - : DBLangEngine.GetStatMessage("msgUnicodeNoBomShort", - "NO-BOM|A short message describing that an unicode encoding doesn't contain a BOM (byte-order-mark)"); - - // UTF8 has only one byte order so skip the UTF8.. - if (fileSave.GetEncoding().CodePage != Encoding.UTF8.CodePage) - { - LabelEncoding.Text += @"|"; - - LabelEncoding.Text += fileSave.GetEncoding().IsBigEndian() - ? DBLangEngine.GetStatMessage("msgUnicodeBigEndianShort", - "BE|A short message describing that an unicode encoding is in a big endian format") - : DBLangEngine.GetStatMessage("msgUnicodeLittleEndianShort", - "LE|A short message describing that an unicode encoding is in a little endian format"); - } - } + LabelEncoding.Text += @"|"; - LabelSessionName.Text = - DBLangEngine.GetStatMessage("msgSessionName", "Session: {0}|A message describing a session name with the name as a parameter", sessionName); + LabelEncoding.Text += fileSave.GetEncoding().IsBigEndian() + ? DBLangEngine.GetStatMessage("msgUnicodeBigEndianShort", + "BE|A short message describing that an unicode encoding is in a big endian format") + : DBLangEngine.GetStatMessage("msgUnicodeLittleEndianShort", + "LE|A short message describing that an unicode encoding is in a little endian format"); + } } - // set the insert / override text for the status strip.. - SetInsertOverrideStatusStripText(document, false); + LabelSessionName.Text = + DBLangEngine.GetStatMessage("msgSessionName", "Session: {0}|A message describing a session name with the name as a parameter", sessionName); } - /// - /// Sets the main status strip value for insert / override mode for the currently active document.. - /// - /// The document of which properties to use to set the status strip values to indicate. - /// A flag indicating whether the software captured the change before the control; thus indicating an inverted value. - public static void SetInsertOverrideStatusStripText(ScintillaTabbedDocument document, bool isKeyPreview) + // set the insert / override text for the status strip.. + SetInsertOverrideStatusStripText(document, false); + } + + /// + /// Sets the main status strip value for insert / override mode for the currently active document.. + /// + /// The document of which properties to use to set the status strip values to indicate. + /// A flag indicating whether the software captured the change before the control; thus indicating an inverted value. + public static void SetInsertOverrideStatusStripText(ScintillaTabbedDocument document, bool isKeyPreview) + { + // the tool strip labels must have been assigned.. + if (!Initialized) { - // the tool strip labels must have been assigned.. - if (!Initialized) - { - // ..so to avoid a null reference just return.. - return; - } + // ..so to avoid a null reference just return.. + return; + } - if (isKeyPreview) - { - LabelModeInsertOverride.Text = - !document.Scintilla.Overtype ? - DBLangEngine.GetStatMessage("msgOverrideShort", "Cursor mode: OVR|As in the text to be typed to the Scintilla would override the underlying text") : - DBLangEngine.GetStatMessage("msgInsertShort", "Cursor mode: INS|As in the text to be typed to the Scintilla would be inserted within the already existing text"); - } - else - { - LabelModeInsertOverride.Text = - document.Scintilla.Overtype ? - DBLangEngine.GetStatMessage("msgOverrideShort", "Cursor mode: OVR|As in the text to be typed to the Scintilla would override the underlying text") : - DBLangEngine.GetStatMessage("msgInsertShort", "Cursor mode: INS|As in the text to be typed to the Scintilla would be inserted within the already existing text"); - } + if (isKeyPreview) + { + LabelModeInsertOverride.Text = + !document.Scintilla.Overtype ? + DBLangEngine.GetStatMessage("msgOverrideShort", "Cursor mode: OVR|As in the text to be typed to the Scintilla would override the underlying text") : + DBLangEngine.GetStatMessage("msgInsertShort", "Cursor mode: INS|As in the text to be typed to the Scintilla would be inserted within the already existing text"); + } + else + { + LabelModeInsertOverride.Text = + document.Scintilla.Overtype ? + DBLangEngine.GetStatMessage("msgOverrideShort", "Cursor mode: OVR|As in the text to be typed to the Scintilla would override the underlying text") : + DBLangEngine.GetStatMessage("msgInsertShort", "Cursor mode: INS|As in the text to be typed to the Scintilla would be inserted within the already existing text"); } + } - /// - /// Sets the main status strip values to indicate there is no active document. - /// - /// Name of the session to set for the label. - public static void SetEmptyTexts(string sessionName) + /// + /// Sets the main status strip values to indicate there is no active document. + /// + /// Name of the session to set for the label. + public static void SetEmptyTexts(string sessionName) + { + // the tool strip labels must have been assigned.. + if (!Initialized) { - // the tool strip labels must have been assigned.. - if (!Initialized) - { - // ..so to avoid a null reference just return.. - return; - } + // ..so to avoid a null reference just return.. + return; + } - LabelLineColumn.Text = - DBLangEngine.GetStatMessage("msgColLine", "Line: {0} Col: {1}|As in the current column and the current line in a ScintillaNET control", + LabelLineColumn.Text = + DBLangEngine.GetStatMessage("msgColLine", "Line: {0} Col: {1}|As in the current column and the current line in a ScintillaNET control", 1, 1); - LabelLineColumnSelection.Text = - DBLangEngine.GetStatMessage("msgColLineSelection", "Sel1: {0}|{1} Sel2: {2}|{3} Len: {4}|The selection start, end and length in a ScintillaNET control in columns, lines and character count", + LabelLineColumnSelection.Text = + DBLangEngine.GetStatMessage("msgColLineSelection", "Sel1: {0}|{1} Sel2: {2}|{3} Len: {4}|The selection start, end and length in a ScintillaNET control in columns, lines and character count", 1, 1, 1, 1, 0); - LabelLineEnding.Text = - DBLangEngine.GetStatMessage("msgLineEndingShort", "LE: |A short message indicating a file line ending type value(s) as a concatenated text") + - // ReSharper disable once LocalizableElement - $" ({DBLangEngine.GetStatMessage("msgNA", "N/A|A message indicating a none value")})"; + LabelLineEnding.Text = + DBLangEngine.GetStatMessage("msgLineEndingShort", "LE: |A short message indicating a file line ending type value(s) as a concatenated text") + + // ReSharper disable once LocalizableElement + $" ({DBLangEngine.GetStatMessage("msgNA", "N/A|A message indicating a none value")})"; - LabelEncoding.Text = - DBLangEngine.GetStatMessage("msgShortEncodingPreText", "Encoding: |A short text to describe a detected encoding value (i.e.) Unicode (UTF-8).") + - DBLangEngine.GetStatMessage("msgNA", "N/A|A message indicating a none value"); + LabelEncoding.Text = + DBLangEngine.GetStatMessage("msgShortEncodingPreText", "Encoding: |A short text to describe a detected encoding value (i.e.) Unicode (UTF-8).") + + DBLangEngine.GetStatMessage("msgNA", "N/A|A message indicating a none value"); - LabelSessionName.Text = - DBLangEngine.GetStatMessage("msgSessionName", "Session: {0}|A message describing a session name with the name as a parameter", sessionName); + LabelSessionName.Text = + DBLangEngine.GetStatMessage("msgSessionName", "Session: {0}|A message describing a session name with the name as a parameter", sessionName); - LabelModeInsertOverride.Text = - DBLangEngine.GetStatMessage("msgInsertShort", "Cursor mode: INS|As in the text to be typed to the Scintilla would be inserted within the already existing text"); + LabelModeInsertOverride.Text = + DBLangEngine.GetStatMessage("msgInsertShort", "Cursor mode: INS|As in the text to be typed to the Scintilla would be inserted within the already existing text"); - LabelZoom.Text = - DBLangEngine.GetStatMessage("msgZoomLabel", - "Zoom:|A message indicating a text on a label of a following value of zoom percentage"); + LabelZoom.Text = + DBLangEngine.GetStatMessage("msgZoomLabel", + "Zoom:|A message indicating a text on a label of a following value of zoom percentage"); - LabelTab.Text = - DBLangEngine.GetStatMessage("msgTabLabel", - "Tab:|A message indicating a text on a label of a following value of current tab index and tab page count"); - } + LabelTab.Text = + DBLangEngine.GetStatMessage("msgTabLabel", + "Tab:|A message indicating a text on a label of a following value of current tab index and tab page count"); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/PluginHandling/FormPluginManage.cs b/ScriptNotepad/PluginHandling/FormPluginManage.cs index b0296748..bb7b964d 100644 --- a/ScriptNotepad/PluginHandling/FormPluginManage.cs +++ b/ScriptNotepad/PluginHandling/FormPluginManage.cs @@ -35,306 +35,305 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.MessageBoxExtended; -namespace ScriptNotepad.PluginHandling +namespace ScriptNotepad.PluginHandling; + +/// +/// A form to manage installed plug-ins for the software. +/// +/// +public partial class FormPluginManage : DBLangEngineWinforms { /// - /// A form to manage installed plug-ins for the software. + /// Initializes a new instance of the class. /// - /// - public partial class FormPluginManage : DBLangEngineWinforms + public FormPluginManage() { - /// - /// Initializes a new instance of the class. - /// - public FormPluginManage() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - private List plugins = new List(); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } - /// - /// Displays the dialog. - /// - /// True if the user accepted the changes made in the dialog; otherwise false. - public static bool Execute(ref List plugins) - { - FormPluginManage formPluginManage = new FormPluginManage {plugins = plugins}; + private List plugins = new List(); + /// + /// Displays the dialog. + /// + /// True if the user accepted the changes made in the dialog; otherwise false. + public static bool Execute(ref List plugins) + { + FormPluginManage formPluginManage = new FormPluginManage {plugins = plugins, }; - if (formPluginManage.ShowDialog() == DialogResult.OK) - { - plugins = formPluginManage.plugins; - return true; - } - else - { - return false; - } - } - /// - /// Lists the plug-ins to the list box. - /// - private void ListPlugins() + if (formPluginManage.ShowDialog() == DialogResult.OK) { - ListPlugins(string.Empty); + plugins = formPluginManage.plugins; + return true; } - - /// - /// Lists the plug-ins to the list box and filters them if a filter string is given. - /// - /// A filter string to filter the plug-ins in the list box. - private void ListPlugins(string filterString) + else { - lbPluginList.Items.Clear(); - var sortedAndFiltered = - plugins.OrderBy(f => f.SortOrder). - ThenByDescending(f => f.Rating). - ThenBy(f => f.PluginName.ToLowerInvariant()). - ThenBy(f => f.PluginVersion.ToLowerInvariant()).ToList(); - - if (!string.IsNullOrWhiteSpace(filterString)) - { - sortedAndFiltered = - sortedAndFiltered.Where(f => f.ToString().ToLowerInvariant().Contains(filterString.ToLowerInvariant())).ToList(); - } + return false; + } + } - foreach (var plugin in sortedAndFiltered) - { - lbPluginList.Items.Add(plugin); - } + /// + /// Lists the plug-ins to the list box. + /// + private void ListPlugins() + { + ListPlugins(string.Empty); + } - if (lbPluginList.Items.Count > 0) - { - lbPluginList.SelectedIndex = 0; - } - else - { - DisplayPluginData(null); - } + /// + /// Lists the plug-ins to the list box and filters them if a filter string is given. + /// + /// A filter string to filter the plug-ins in the list box. + private void ListPlugins(string filterString) + { + lbPluginList.Items.Clear(); + var sortedAndFiltered = + plugins.OrderBy(f => f.SortOrder). + ThenByDescending(f => f.Rating). + ThenBy(f => f.PluginName.ToLowerInvariant()). + ThenBy(f => f.PluginVersion.ToLowerInvariant()).ToList(); + + if (!string.IsNullOrWhiteSpace(filterString)) + { + sortedAndFiltered = + sortedAndFiltered.Where(f => f.ToString().ToLowerInvariant().Contains(filterString.ToLowerInvariant())).ToList(); } - /// - /// Aligns the order tool strip to the view. - /// - private void AlignArrangeToolStrip() + foreach (var plugin in sortedAndFiltered) { - ttArrangePlugins.Left = (pnArrangePlugins.Width - ttArrangePlugins.Width) / 2; - ttArrangePlugins.Top = (pnArrangePlugins.Height - ttArrangePlugins.Height) / 2; + lbPluginList.Items.Add(plugin); } - private void FormPluginManage_SizeChanged(object sender, EventArgs e) + if (lbPluginList.Items.Count > 0) { - AlignArrangeToolStrip(); + lbPluginList.SelectedIndex = 0; } - - private void FormPluginManage_Shown(object sender, EventArgs e) + else { - AlignArrangeToolStrip(); - ListPlugins(); + DisplayPluginData(null); } + } + + /// + /// Aligns the order tool strip to the view. + /// + private void AlignArrangeToolStrip() + { + ttArrangePlugins.Left = (pnArrangePlugins.Width - ttArrangePlugins.Width) / 2; + ttArrangePlugins.Top = (pnArrangePlugins.Height - ttArrangePlugins.Height) / 2; + } - /// - /// Displays the data of the given plug-in. - /// - /// The plug-in which data to display. - private void DisplayPluginData(Plugin plugin) + private void FormPluginManage_SizeChanged(object sender, EventArgs e) + { + AlignArrangeToolStrip(); + } + + private void FormPluginManage_Shown(object sender, EventArgs e) + { + AlignArrangeToolStrip(); + ListPlugins(); + } + + /// + /// Displays the data of the given plug-in. + /// + /// The plug-in which data to display. + private void DisplayPluginData(Plugin plugin) + { + tbPluginName.Text = plugin == null ? string.Empty : plugin.PluginName; + tbPluginDescription.Text = plugin == null ? string.Empty : plugin.PluginDescription; + tbPluginVersion.Text = plugin == null ? string.Empty : plugin.PluginVersion; + tbExceptionsThrown.Text = plugin == null ? string.Empty : plugin.ExceptionCount.ToString(); + tbLoadFailures.Text = plugin == null ? string.Empty : plugin.LoadFailures.ToString(); + tbAppCrashes.Text = plugin == null ? string.Empty : plugin.ApplicationCrashes.ToString(); + tbInstalledAt.Text = plugin == null ? string.Empty : plugin.PluginInstalled.ToShortDateString(); + tbUpdatedAt.Text = plugin == null ? string.Empty : (plugin.PluginUpdated == DateTime.MinValue ? + DBLangEngine.GetMessage("msgNA", "N/A|A message indicating a none value") : + plugin.PluginUpdated.ToShortDateString()); + nudRating.Value = plugin?.Rating ?? 0; + + cbPluginActive.Checked = plugin != null && plugin.IsActive; + cbPluginExists.Checked = plugin != null && File.Exists(plugin.FileNameFull); + + nudRating.Enabled = plugin != null; + btDeletePlugin.Enabled = plugin != null; + cbPluginActive.Enabled = plugin != null; + + // indicate a serious flaw with the plug-in.. + if (plugin != null && plugin.ApplicationCrashes > 0) { - tbPluginName.Text = plugin == null ? string.Empty : plugin.PluginName; - tbPluginDescription.Text = plugin == null ? string.Empty : plugin.PluginDescription; - tbPluginVersion.Text = plugin == null ? string.Empty : plugin.PluginVersion; - tbExceptionsThrown.Text = plugin == null ? string.Empty : plugin.ExceptionCount.ToString(); - tbLoadFailures.Text = plugin == null ? string.Empty : plugin.LoadFailures.ToString(); - tbAppCrashes.Text = plugin == null ? string.Empty : plugin.ApplicationCrashes.ToString(); - tbInstalledAt.Text = plugin == null ? string.Empty : plugin.PluginInstalled.ToShortDateString(); - tbUpdatedAt.Text = plugin == null ? string.Empty : (plugin.PluginUpdated == DateTime.MinValue ? - DBLangEngine.GetMessage("msgNA", "N/A|A message indicating a none value") : - plugin.PluginUpdated.ToShortDateString()); - nudRating.Value = plugin?.Rating ?? 0; - - cbPluginActive.Checked = plugin != null && plugin.IsActive; - cbPluginExists.Checked = plugin != null && File.Exists(plugin.FileNameFull); - - nudRating.Enabled = plugin != null; - btDeletePlugin.Enabled = plugin != null; - cbPluginActive.Enabled = plugin != null; - - // indicate a serious flaw with the plug-in.. - if (plugin != null && plugin.ApplicationCrashes > 0) - { - lbAppCrashes.Font = new Font(Font, FontStyle.Bold); - lbAppCrashes.ForeColor = Color.Red; - } - // the plug-in is more or less safe.. - else - { - lbAppCrashes.Font = Font; - lbAppCrashes.ForeColor = SystemColors.ControlText; - } + lbAppCrashes.Font = new Font(Font, FontStyle.Bold); + lbAppCrashes.ForeColor = Color.Red; } - - private void lbPluginList_SelectedValueChanged(object sender, EventArgs e) + // the plug-in is more or less safe.. + else { - if (tsbArrangePlugins.Checked) - { - // the plug-ins are being sorted by the user.. - return; - } - ListBox listBox = (ListBox)sender; - Plugin plugin = (Plugin)listBox.SelectedItem; - DisplayPluginData(plugin); + lbAppCrashes.Font = Font; + lbAppCrashes.ForeColor = SystemColors.ControlText; } + } - private void tbFilterPlugins_TextChanged(object sender, EventArgs e) + private void lbPluginList_SelectedValueChanged(object sender, EventArgs e) + { + if (tsbArrangePlugins.Checked) { - ListPlugins(tbFilterPlugins.Text); + // the plug-ins are being sorted by the user.. + return; } + ListBox listBox = (ListBox)sender; + Plugin plugin = (Plugin)listBox.SelectedItem; + DisplayPluginData(plugin); + } - private void btDeletePlugin_Click(object sender, EventArgs e) + private void tbFilterPlugins_TextChanged(object sender, EventArgs e) + { + ListPlugins(tbFilterPlugins.Text); + } + + private void btDeletePlugin_Click(object sender, EventArgs e) + { + Plugin plugin = (Plugin)lbPluginList.SelectedItem; + + if (plugin != null) { - Plugin plugin = (Plugin)lbPluginList.SelectedItem; + int idx = plugins.FindIndex(f => f.Id == plugin.Id); - if (plugin != null) + if (idx != -1) { - int idx = plugins.FindIndex(f => f.Id == plugin.Id); - - if (idx != -1) - { - plugins[idx].PendingDeletion = true; - } + plugins[idx].PendingDeletion = true; } } + } - // a user wishes to arrange the plug-ins.. - private void tsbArrangePlugins_Click(object sender, EventArgs e) + // a user wishes to arrange the plug-ins.. + private void tsbArrangePlugins_Click(object sender, EventArgs e) + { + ToolStripButton button = (ToolStripButton)sender; + tbFilterPlugins.Enabled = !button.Checked; + tsbArrangePluginDownwards.Enabled = button.Checked; + tsbArrangePluginUpwards.Enabled = button.Checked; + if (button.Checked) { - ToolStripButton button = (ToolStripButton)sender; - tbFilterPlugins.Enabled = !button.Checked; - tsbArrangePluginDownwards.Enabled = button.Checked; - tsbArrangePluginUpwards.Enabled = button.Checked; - if (button.Checked) - { - DisplayPluginData(null); - ListPlugins(); - } - else + DisplayPluginData(null); + ListPlugins(); + } + else + { + // save the user set ordering.. + for (int i = 0; i < lbPluginList.Items.Count; i++) { - // save the user set ordering.. - for (int i = 0; i < lbPluginList.Items.Count; i++) + var plugin = (Plugin)lbPluginList.Items[i]; + int idx = plugins.FindIndex(f => f.Id == plugin.Id); + if (idx != -1) { - var plugin = (Plugin)lbPluginList.Items[i]; - int idx = plugins.FindIndex(f => f.Id == plugin.Id); - if (idx != -1) - { - plugins[idx].SortOrder = i; - } + plugins[idx].SortOrder = i; } - ListPlugins(tbFilterPlugins.Text); } + ListPlugins(tbFilterPlugins.Text); } + } - // swap the items so the selected plug-in goes downwards in the ordering.. - private void tsbArrangePluginDownwards_Click(object sender, EventArgs e) + // swap the items so the selected plug-in goes downwards in the ordering.. + private void tsbArrangePluginDownwards_Click(object sender, EventArgs e) + { + if (lbPluginList.SelectedIndex != -1 && + lbPluginList.SelectedIndex + 1 < lbPluginList.Items.Count) { - if (lbPluginList.SelectedIndex != -1 && - lbPluginList.SelectedIndex + 1 < lbPluginList.Items.Count) - { - object item1 = lbPluginList.Items[lbPluginList.SelectedIndex]; - object item2 = lbPluginList.Items[lbPluginList.SelectedIndex + 1]; - lbPluginList.Items[lbPluginList.SelectedIndex + 1] = item1; - lbPluginList.Items[lbPluginList.SelectedIndex] = item2; + object item1 = lbPluginList.Items[lbPluginList.SelectedIndex]; + object item2 = lbPluginList.Items[lbPluginList.SelectedIndex + 1]; + lbPluginList.Items[lbPluginList.SelectedIndex + 1] = item1; + lbPluginList.Items[lbPluginList.SelectedIndex] = item2; - // increase the selected index.. - lbPluginList.SelectedIndex++; - } + // increase the selected index.. + lbPluginList.SelectedIndex++; } + } - // swap the items so the selected plug-in goes upwards in the ordering.. - private void tsbArrangePluginUpwards_Click(object sender, EventArgs e) + // swap the items so the selected plug-in goes upwards in the ordering.. + private void tsbArrangePluginUpwards_Click(object sender, EventArgs e) + { + if (lbPluginList.SelectedIndex != -1 && + lbPluginList.SelectedIndex - 1 > 0) { - if (lbPluginList.SelectedIndex != -1 && - lbPluginList.SelectedIndex - 1 > 0) - { - object item1 = lbPluginList.Items[lbPluginList.SelectedIndex]; - object item2 = lbPluginList.Items[lbPluginList.SelectedIndex - 1]; - lbPluginList.Items[lbPluginList.SelectedIndex - 1] = item1; - lbPluginList.Items[lbPluginList.SelectedIndex] = item2; + object item1 = lbPluginList.Items[lbPluginList.SelectedIndex]; + object item2 = lbPluginList.Items[lbPluginList.SelectedIndex - 1]; + lbPluginList.Items[lbPluginList.SelectedIndex - 1] = item1; + lbPluginList.Items[lbPluginList.SelectedIndex] = item2; - // decrease the selected index.. - lbPluginList.SelectedIndex++; - } + // decrease the selected index.. + lbPluginList.SelectedIndex++; } + } - private void btInstallPlugin_Click(object sender, EventArgs e) - { - odDLL.Title = DBLangEngine.GetMessage("msgDialogSelectPlugin", - "Select a plugin to install|A title for an open file dialog to indicate user that the user is selecting a plugin dll to be installed"); + private void btInstallPlugin_Click(object sender, EventArgs e) + { + odDLL.Title = DBLangEngine.GetMessage("msgDialogSelectPlugin", + "Select a plugin to install|A title for an open file dialog to indicate user that the user is selecting a plugin dll to be installed"); - odDLL.InitialDirectory = FormSettings.Settings.FileLocationOpenPlugin; + odDLL.InitialDirectory = FormSettings.Settings.FileLocationOpenPlugin; - if (odDLL.ShowDialog() == DialogResult.OK) - { - FormSettings.Settings.FileLocationOpenPlugin = Path.GetDirectoryName(odDLL.FileName); + if (odDLL.ShowDialog() == DialogResult.OK) + { + FormSettings.Settings.FileLocationOpenPlugin = Path.GetDirectoryName(odDLL.FileName); - if (TestFileIsAssembly.IsAssembly(odDLL.FileName)) + if (TestFileIsAssembly.IsAssembly(odDLL.FileName)) + { + try { - try - { - // try to copy the file to the plug-in folder.. - File.Copy(odDLL.FileName, - // ReSharper disable once AssignNullToNotNullAttribute - Path.Combine(FormSettings.Settings.PluginFolder, Path.GetFileName(odDLL.FileName)), - true); - } - catch (Exception ex) - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgErrorPluginInstall", - "The plug-in instillation failed with the following error: '{0}'.|Something failed during copying a plug-in to the plug-ins folder", ex.Message), - DBLangEngine.GetMessage("msgError", "Error|A message describing that some kind of error occurred."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Error, ExtendedDefaultButtons.Button1); - - // log the exception.. - ExceptionLogger.LogError(ex); - } + // try to copy the file to the plug-in folder.. + File.Copy(odDLL.FileName, + // ReSharper disable once AssignNullToNotNullAttribute + Path.Combine(FormSettings.Settings.PluginFolder, Path.GetFileName(odDLL.FileName)), + true); } - else + catch (Exception ex) { MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgWarningPluginNotAssembly", - "The plug-in initialization failed because it is not a valid .NET Framework assembly.|The given assembly isn't a .NET Framework assembly"), - DBLangEngine.GetMessage("msgWarning", "Warning|A message warning of some kind problem."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); + DBLangEngine.GetMessage("msgErrorPluginInstall", + "The plug-in instillation failed with the following error: '{0}'.|Something failed during copying a plug-in to the plug-ins folder", ex.Message), + DBLangEngine.GetMessage("msgError", "Error|A message describing that some kind of error occurred."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Error, ExtendedDefaultButtons.Button1); + + // log the exception.. + ExceptionLogger.LogError(ex); } } + else + { + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgWarningPluginNotAssembly", + "The plug-in initialization failed because it is not a valid .NET Framework assembly.|The given assembly isn't a .NET Framework assembly"), + DBLangEngine.GetMessage("msgWarning", "Warning|A message warning of some kind problem."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); + } } + } - // the user wishes to toggle the active state of a plug-in.. - private void cbPluginActive_CheckedChanged(object sender, EventArgs e) + // the user wishes to toggle the active state of a plug-in.. + private void cbPluginActive_CheckedChanged(object sender, EventArgs e) + { + var plugin = (Plugin)lbPluginList.SelectedItem; + + if (plugin != null) { - var plugin = (Plugin)lbPluginList.SelectedItem; + int idx = plugins.FindIndex(f => f.Id == plugin.Id); - if (plugin != null) + if (idx != -1) { - int idx = plugins.FindIndex(f => f.Id == plugin.Id); - - if (idx != -1) - { - plugins[idx].IsActive = ((CheckBox)sender).Checked; - } + plugins[idx].IsActive = ((CheckBox)sender).Checked; } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/PluginHandling/PluginDirectoryRoaming.cs b/ScriptNotepad/PluginHandling/PluginDirectoryRoaming.cs index 0e4ac2c3..4639619c 100644 --- a/ScriptNotepad/PluginHandling/PluginDirectoryRoaming.cs +++ b/ScriptNotepad/PluginHandling/PluginDirectoryRoaming.cs @@ -29,110 +29,109 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Reflection; using VPKSoft.ErrorLogger; -namespace ScriptNotepad.PluginHandling +namespace ScriptNotepad.PluginHandling; + +/// +/// A class witch searches a given directory for possible plug-in assemblies. +/// +public static class PluginDirectoryRoaming { /// - /// A class witch searches a given directory for possible plug-in assemblies. + /// Gets or sets the action to be used to log an exception. + /// + public static Action ExceptionLogAction { get; set; } = null; + + /// + /// Gets the plug-in assemblies for the software. /// - public static class PluginDirectoryRoaming + /// The directory to search the plug-in assemblies from. + /// A collection of tuples containing the information of the found assemblies. + public static IEnumerable<(Assembly Assembly, string Path, bool IsValid)> GetPluginAssemblies(string directory) { - /// - /// Gets or sets the action to be used to log an exception. - /// - public static Action ExceptionLogAction { get; set; } = null; - - /// - /// Gets the plug-in assemblies for the software. - /// - /// The directory to search the plug-in assemblies from. - /// A collection of tuples containing the information of the found assemblies. - public static IEnumerable<(Assembly Assembly, string Path, bool IsValid)> GetPluginAssemblies(string directory) + // create a list for the results.. + List<(Assembly Assembly, string Path, bool IsValid)> result = new List<(Assembly Assembly, string Path, bool IsValid)>(); + + try { - // create a list for the results.. - List<(Assembly Assembly, string Path, bool IsValid)> result = new List<(Assembly Assembly, string Path, bool IsValid)>(); + ExceptionLogger.LogMessage($"Plugin path, get: '{directory}'"); + // recurse the plug-in path.. + string[] assemblies = Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories); - try + // loop through the results.. + foreach (string assemblyFile in assemblies) { - ExceptionLogger.LogMessage($"Plugin path, get: '{directory}'"); - // recurse the plug-in path.. - string[] assemblies = Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories); + // ReSharper disable once CommentTypo + // some other files (.dll_blaa) might come with the *.dll mask.. + if (!String.Equals(Path.GetExtension(assemblyFile), ".dll", StringComparison.InvariantCultureIgnoreCase)) + { + // ..in that case do continue.. + continue; + } - // loop through the results.. - foreach (string assemblyFile in assemblies) + // this might also fail so try.. + try { - // ReSharper disable once CommentTypo - // some other files (.dll_blaa) might come with the *.dll mask.. - if (!String.Equals(Path.GetExtension(assemblyFile), ".dll", StringComparison.InvariantCultureIgnoreCase)) - { - // ..in that case do continue.. - continue; - } + // load the found assembly.. + Assembly assembly = Assembly.LoadFile(assemblyFile); - // this might also fail so try.. - try + foreach (Type type in assembly.GetTypes()) { - // load the found assembly.. - Assembly assembly = Assembly.LoadFile(assemblyFile); - - foreach (Type type in assembly.GetTypes()) + // again keep on trying.. + try { - // again keep on trying.. - try + // check the validity of the found type.. + if (typeof(IScriptNotepadPlugin).IsAssignableFrom(type) && + typeof(ScriptNotepadPlugin).IsAssignableFrom(type)) { - // check the validity of the found type.. - if (typeof(IScriptNotepadPlugin).IsAssignableFrom(type) && - typeof(ScriptNotepadPlugin).IsAssignableFrom(type)) - { - // create an instance of the class implementing the IScriptNotepadPlugin interface.. - IScriptNotepadPlugin plugin = - (IScriptNotepadPlugin)Activator.CreateInstance(type); + // create an instance of the class implementing the IScriptNotepadPlugin interface.. + IScriptNotepadPlugin plugin = + (IScriptNotepadPlugin)Activator.CreateInstance(type); - // the IScriptNotepadPlugin is also disposable, so do dispose of it.. - using (plugin) + // the IScriptNotepadPlugin is also disposable, so do dispose of it.. + using (plugin) + { + if (!result.Exists(f => f.Path != null && Path.GetFileName(f.Path) == Path.GetFileName(assemblyFile))) { - if (!result.Exists(f => f.Path != null && Path.GetFileName(f.Path) == Path.GetFileName(assemblyFile))) - { - result.Add((assembly, assemblyFile, true)); - } + result.Add((assembly, assemblyFile, true)); } } } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex, assembly, assemblyFile); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex, assembly, assemblyFile); - // indicate a failure in the result as well.. - if (!result.Exists(f => f.Path != null && Path.GetFileName(f.Path) == Path.GetFileName(assemblyFile))) - { - result.Add((assembly, assemblyFile, false)); - } + // indicate a failure in the result as well.. + if (!result.Exists(f => f.Path != null && Path.GetFileName(f.Path) == Path.GetFileName(assemblyFile))) + { + result.Add((assembly, assemblyFile, false)); } } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex, null, assemblyFile); - // indicate a failure in the result as well.. - if (!result.Exists(f => f.Path != null && Path.GetFileName(f.Path) == Path.GetFileName(assemblyFile))) - { - result.Add((null, assemblyFile, false)); - } + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex, null, assemblyFile); + + // indicate a failure in the result as well.. + if (!result.Exists(f => f.Path != null && Path.GetFileName(f.Path) == Path.GetFileName(assemblyFile))) + { + result.Add((null, assemblyFile, false)); } } } - // a failure.. - catch (Exception ex) - { - // ..so do log it.. - ExceptionLogAction?.Invoke(ex, null, null); - } - - // return the result.. - return result; } + // a failure.. + catch (Exception ex) + { + // ..so do log it.. + ExceptionLogAction?.Invoke(ex, null, null); + } + + // return the result.. + return result; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/PluginHandling/PluginInitializer.cs b/ScriptNotepad/PluginHandling/PluginInitializer.cs index d2ff6147..6992de92 100644 --- a/ScriptNotepad/PluginHandling/PluginInitializer.cs +++ b/ScriptNotepad/PluginHandling/PluginInitializer.cs @@ -29,105 +29,104 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using static ScriptNotepadPluginBase.Types.DelegateTypes; -namespace ScriptNotepad.PluginHandling +namespace ScriptNotepad.PluginHandling; + +/// +/// A helper class for the plug-in loading and initialization. +/// +public static class PluginInitializer { /// - /// A helper class for the plug-in loading and initialization. + /// Gets or sets the action to be used to log an exception. /// - public static class PluginInitializer - { - /// - /// Gets or sets the action to be used to log an exception. - /// - public static Action ExceptionLogAction { get; set; } = null; + public static Action ExceptionLogAction { get; set; } = null; - /// - /// Tries to loads a plug-in with a given file name. - /// - /// Name of the file containing the plug-in assembly. - /// A tuple containing the assembly and an instance created for the plug-in implementing - /// the interface along with the assembly file name if successful; - /// otherwise the resulting value contains some null values. - public static (Assembly assembly, IScriptNotepadPlugin Plugin, string FileName) LoadPlugin(string fileName) + /// + /// Tries to loads a plug-in with a given file name. + /// + /// Name of the file containing the plug-in assembly. + /// A tuple containing the assembly and an instance created for the plug-in implementing + /// the interface along with the assembly file name if successful; + /// otherwise the resulting value contains some null values. + public static (Assembly assembly, IScriptNotepadPlugin Plugin, string FileName) LoadPlugin(string fileName) + { + try { - try - { - // load the found assembly.. - Assembly assembly = Assembly.LoadFile(fileName); + // load the found assembly.. + Assembly assembly = Assembly.LoadFile(fileName); - foreach (Type type in assembly.GetTypes()) + foreach (Type type in assembly.GetTypes()) + { + // again keep on trying.. + try { - // again keep on trying.. - try + // check the validity of the found type.. + if (typeof(IScriptNotepadPlugin).IsAssignableFrom(type) && + typeof(ScriptNotepadPlugin).IsAssignableFrom(type)) { - // check the validity of the found type.. - if (typeof(IScriptNotepadPlugin).IsAssignableFrom(type) && - typeof(ScriptNotepadPlugin).IsAssignableFrom(type)) - { - // create an instance of the class implementing the IScriptNotepadPlugin interface.. - IScriptNotepadPlugin plugin = - (IScriptNotepadPlugin)Activator.CreateInstance(type); + // create an instance of the class implementing the IScriptNotepadPlugin interface.. + IScriptNotepadPlugin plugin = + (IScriptNotepadPlugin)Activator.CreateInstance(type); - return (assembly, plugin, fileName); - } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex, assembly, fileName, "PluginInitializer.LoadPlugin_#1"); - - // indicate a failure in the result as well.. - return (assembly, null, fileName); + return (assembly, plugin, fileName); } } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex, assembly, fileName, "PluginInitializer.LoadPlugin_#1"); - // a class type implementing the IScriptNotepadPlugin interface wasn't found.. - return (assembly, null, fileName); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex, null, fileName, "PluginInitializer.LoadPlugin_#2"); - return (null, null, fileName); + // indicate a failure in the result as well.. + return (assembly, null, fileName); + } } + + // a class type implementing the IScriptNotepadPlugin interface wasn't found.. + return (assembly, null, fileName); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex, null, fileName, "PluginInitializer.LoadPlugin_#2"); + return (null, null, fileName); } + } - /// - /// Initializes the given plug-in instance. - /// - /// The plug-in instance to initialize. - /// The event provided by the hosting software (ScriptNotepad) to request for the active document within the software. - /// The event provided by the hosting software (ScriptNotepad) to request for all open documents within the software. - /// The event provided by the hosting software (ScriptNotepad) for error reporting. - /// The which is the main menu of the hosting software (ScriptNotepad). - /// The which is the plug-in menu in the hosting software (ScriptNotepad). - /// The name of the current session in the hosting software (ScriptNotepad). - /// A reference to the main form of the hosting software (ScriptNotepad). - /// True if the operation was successful; otherwise false. - public static bool InitializePlugin(IScriptNotepadPlugin plugin, - OnRequestActiveDocument onRequestActiveDocument, - OnRequestAllDocuments onRequestAllDocuments, - OnPluginException onPluginException, - MenuStrip mainMenu, - ToolStripMenuItem pluginMenuStrip, - string sessionName, - FormMain formMain - ) + /// + /// Initializes the given plug-in instance. + /// + /// The plug-in instance to initialize. + /// The event provided by the hosting software (ScriptNotepad) to request for the active document within the software. + /// The event provided by the hosting software (ScriptNotepad) to request for all open documents within the software. + /// The event provided by the hosting software (ScriptNotepad) for error reporting. + /// The which is the main menu of the hosting software (ScriptNotepad). + /// The which is the plug-in menu in the hosting software (ScriptNotepad). + /// The name of the current session in the hosting software (ScriptNotepad). + /// A reference to the main form of the hosting software (ScriptNotepad). + /// True if the operation was successful; otherwise false. + public static bool InitializePlugin(IScriptNotepadPlugin plugin, + OnRequestActiveDocument onRequestActiveDocument, + OnRequestAllDocuments onRequestAllDocuments, + OnPluginException onPluginException, + MenuStrip mainMenu, + ToolStripMenuItem pluginMenuStrip, + string sessionName, + FormMain formMain + ) + { + try { - try - { - // initialize the plug-in.. - plugin.Initialize(onRequestActiveDocument, onRequestAllDocuments, onPluginException, - mainMenu, pluginMenuStrip, sessionName, formMain); - return true; // success.. - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex, null, null, "PluginInitializer.InitializePlugin_#1"); + // initialize the plug-in.. + plugin.Initialize(onRequestActiveDocument, onRequestAllDocuments, onPluginException, + mainMenu, pluginMenuStrip, sessionName, formMain); + return true; // success.. + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex, null, null, "PluginInitializer.InitializePlugin_#1"); - return false; // fail.. - } + return false; // fail.. } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Program.cs b/ScriptNotepad/Program.cs index 00fa6120..cf48d0fb 100644 --- a/ScriptNotepad/Program.cs +++ b/ScriptNotepad/Program.cs @@ -51,247 +51,246 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // limit the PropertyChanged to the Settings class (https://github.com/Fody/PropertyChanged) [assembly: PropertyChanged.FilterType("ScriptNotepad.Settings.")] -namespace ScriptNotepad +namespace ScriptNotepad; + +internal static class Program { - internal static class Program + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main(string [] args) { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main(string [] args) - { - WaitForProcess.WaitForProcessArguments(args, 30); + WaitForProcess.WaitForProcessArguments(args, 30); - if (!Debugger.IsAttached) // this is too efficient, the exceptions aren't caught by the ide :-) - { - ExceptionLogger.Bind(); // bind before any visual objects are created - ExceptionLogger.ApplicationCrashData += ExceptionLogger_ApplicationCrashData; - } + if (!Debugger.IsAttached) // this is too efficient, the exceptions aren't caught by the ide :-) + { + ExceptionLogger.Bind(); // bind before any visual objects are created + ExceptionLogger.ApplicationCrashData += ExceptionLogger_ApplicationCrashData; + } - // localizeProcess (user wishes to localize the software).. - Process localizeProcess = Utils.CreateDBLocalizeProcess(Paths.AppInstallDir); + // localizeProcess (user wishes to localize the software).. + Process localizeProcess = Utils.CreateDBLocalizeProcess(Paths.AppInstallDir); - // if the localize process was requested via the command line.. - if (localizeProcess != null) - { - // start the DBLocalization.exe and return.. - localizeProcess.Start(); + // if the localize process was requested via the command line.. + if (localizeProcess != null) + { + // start the DBLocalization.exe and return.. + localizeProcess.Start(); - ExceptionLogger.LogMessage("Started localize process.."); + ExceptionLogger.LogMessage("Started localize process.."); - if (!Debugger.IsAttached) - { - ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. - } - return; + if (!Debugger.IsAttached) + { + ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. } + return; + } - Paths.MakeAppSettingsFolder(Misc.AppType.Winforms); // ensure there is an application settings folder.. + Paths.MakeAppSettingsFolder(Misc.AppType.Winforms); // ensure there is an application settings folder.. - // Save languages.. - if (Utils.ShouldLocalize() != null) - { - // ReSharper disable once ObjectCreationAsStatement - new FormMain(); - // ReSharper disable once ObjectCreationAsStatement - new FormScript(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogScriptLoad(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogQueryEncoding(); - // ReSharper disable once ObjectCreationAsStatement - new FormHexEdit(); - // ReSharper disable once ObjectCreationAsStatement - new FormSettings(); - // ReSharper disable once ObjectCreationAsStatement - new FormPluginManage(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSessionManage(); - // ReSharper disable once ObjectCreationAsStatement - new FormSearchResultTree(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSearchReplaceProgress(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSearchReplaceProgressFiles(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogQueryNumber(); - // ReSharper disable once ObjectCreationAsStatement - new FormPickAColor(); - // ReSharper disable once ObjectCreationAsStatement - new FormFileDiffView(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogQueryJumpLocation(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSelectFileTab(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogRenameNewFile(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogQuerySortTextStyle(); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogCustomSpellCheckerInfo(); - // this form is instantiated in a different way.. - _ = FormSnippetRunner.Instance; - - FormSearchAndReplace.CreateLocalizationInstance(); // special form, special handling.. - - if (!Debugger.IsAttached) - { - ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. - } + // Save languages.. + if (Utils.ShouldLocalize() != null) + { + // ReSharper disable once ObjectCreationAsStatement + new FormMain(); + // ReSharper disable once ObjectCreationAsStatement + new FormScript(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogScriptLoad(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogQueryEncoding(); + // ReSharper disable once ObjectCreationAsStatement + new FormHexEdit(); + // ReSharper disable once ObjectCreationAsStatement + new FormSettings(); + // ReSharper disable once ObjectCreationAsStatement + new FormPluginManage(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSessionManage(); + // ReSharper disable once ObjectCreationAsStatement + new FormSearchResultTree(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSearchReplaceProgress(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSearchReplaceProgressFiles(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogQueryNumber(); + // ReSharper disable once ObjectCreationAsStatement + new FormPickAColor(); + // ReSharper disable once ObjectCreationAsStatement + new FormFileDiffView(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogQueryJumpLocation(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSelectFileTab(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogRenameNewFile(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogQuerySortTextStyle(); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogCustomSpellCheckerInfo(); + // this form is instantiated in a different way.. + _ = FormSnippetRunner.Instance; + + FormSearchAndReplace.CreateLocalizationInstance(); // special form, special handling.. - ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; - return; + if (!Debugger.IsAttached) + { + ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. } - // if the application is running send the arguments to the existing instance.. - if (AppRunning.CheckIfRunning("VPKSoft.ScriptNotepad.C#")) + ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; + return; + } + + // if the application is running send the arguments to the existing instance.. + if (AppRunning.CheckIfRunning("VPKSoft.ScriptNotepad.C#")) + { + ExceptionLogger.LogMessage($"Application is running. Checking for open file requests. The current directory is: '{Environment.CurrentDirectory}'."); + ExceptionLogger.LogMessage($"The arguments are: '{string.Join("', '", args)}'."); + try { - ExceptionLogger.LogMessage($"Application is running. Checking for open file requests. The current directory is: '{Environment.CurrentDirectory}'."); - ExceptionLogger.LogMessage($"The arguments are: '{string.Join("', '", args)}'."); - try - { - RpcSelfClient ipcClient = new RpcSelfClient(50670); + RpcSelfClient ipcClient = new RpcSelfClient(50670); - // only send the existing files to the running instance.. - foreach (var arg in args) + // only send the existing files to the running instance.. + foreach (var arg in args) + { + if (arg == Process.GetCurrentProcess().MainModule?.FileName) { - if (arg == Process.GetCurrentProcess().MainModule?.FileName) - { - // don't open your self.. - continue; - } - string file = arg; + // don't open your self.. + continue; + } + string file = arg; - ExceptionLogger.LogMessage($"Request file open: '{file}'."); - if (File.Exists(file)) - { - ExceptionLogger.LogMessage($"File exists: '{file}'. Send open request."); - ipcClient.SendData(file); - } + ExceptionLogger.LogMessage($"Request file open: '{file}'."); + if (File.Exists(file)) + { + ExceptionLogger.LogMessage($"File exists: '{file}'. Send open request."); + ipcClient.SendData(file); } } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - // just in case something fails with the IPC communication.. - } - - if (!Debugger.IsAttached) - { - ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. - } + } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); + // just in case something fails with the IPC communication.. + } - ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; - return; + if (!Debugger.IsAttached) + { + ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. } - PositionCore.Bind(ApplicationType.WinForms); // attach the PosLib to the application + ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; + return; + } - SettingFileName = PathHandler.GetSettingsFile(Assembly.GetEntryAssembly(), ".xml", - Environment.SpecialFolder.LocalApplicationData); + PositionCore.Bind(ApplicationType.WinForms); // attach the PosLib to the application - // create a Settings class instance for the settings form.. - FormSettings.Settings = new Settings.Settings(); + SettingFileName = PathHandler.GetSettingsFile(Assembly.GetEntryAssembly(), ".xml", + Environment.SpecialFolder.LocalApplicationData); - FormSettings.Settings.RequestTypeConverter += settings_RequestTypeConverter; + // create a Settings class instance for the settings form.. + FormSettings.Settings = new Settings.Settings(); - if (!File.Exists(SettingFileName)) - { - using var settingsOld = new SettingsOld(); - settingsOld.MoveSettings(FormSettings.Settings); - FormSettings.Settings.Save(SettingFileName); - } - else - { - FormSettings.Settings.DatabaseMigrationLevel = 1; - } + FormSettings.Settings.RequestTypeConverter += settings_RequestTypeConverter; - FormSettings.Settings.Load(SettingFileName); + if (!File.Exists(SettingFileName)) + { + using var settingsOld = new SettingsOld(); + settingsOld.MoveSettings(FormSettings.Settings); + FormSettings.Settings.Save(SettingFileName); + } + else + { + FormSettings.Settings.DatabaseMigrationLevel = 1; + } - DBLangEngine.UseCulture = FormSettings.Settings.Culture; // set the localization value.. + FormSettings.Settings.Load(SettingFileName); - Application.SetHighDpiMode(HighDpiMode.SystemAware); - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new FormMain()); - PositionCore.UnBind(ApplicationType.WinForms); // release the event handlers used by the PosLib and save the default data + DBLangEngine.UseCulture = FormSettings.Settings.Culture; // set the localization value.. - if (!Debugger.IsAttached) - { - ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. - } + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new FormMain()); + PositionCore.UnBind(ApplicationType.WinForms); // release the event handlers used by the PosLib and save the default data - ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; + if (!Debugger.IsAttached) + { + ExceptionLogger.UnBind(); // unbind so the truncate thread is stopped successfully.. + } - if (RestartElevated && File.Exists(ElevateFile) && !Restart) - { - ApplicationProcess.RunApplicationProcess(true, ElevateFile); - } + ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; - if (Restart) - { - ApplicationProcess.RunApplicationProcess(false, string.Empty); - } + if (RestartElevated && File.Exists(ElevateFile) && !Restart) + { + ApplicationProcess.RunApplicationProcess(true, ElevateFile); } - private static void settings_RequestTypeConverter(object sender, RequestTypeConverterEventArgs e) + if (Restart) { - if (e.TypeToConvert == typeof(Color)) - { - e.TypeConverter = new ColorConverter(); - } + ApplicationProcess.RunApplicationProcess(false, string.Empty); } + } - private static void ExceptionLogger_ApplicationCrashData(ApplicationCrashEventArgs e) + private static void settings_RequestTypeConverter(object sender, RequestTypeConverterEventArgs e) + { + if (e.TypeToConvert == typeof(Color)) { - try - { - FormMain.ModuleExceptionHandler?.Invoke(e.Exception.TargetSite.Module.FullyQualifiedName); - } - catch - { - // ignored, no point of return.. - } - - // unsubscribe this event handler.. - ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; + e.TypeConverter = new ColorConverter(); + } + } - if (!Debugger.IsAttached) - { - ExceptionLogger.UnBind(); // unbind the exception logger.. - } + private static void ExceptionLogger_ApplicationCrashData(ApplicationCrashEventArgs e) + { + try + { + FormMain.ModuleExceptionHandler?.Invoke(e.Exception.TargetSite.Module.FullyQualifiedName); + } + catch + { + // ignored, no point of return.. + } - // kill self as the native inter-op libraries may have some issues of keeping the process alive.. - Process.GetCurrentProcess().Kill(); + // unsubscribe this event handler.. + ExceptionLogger.ApplicationCrashData -= ExceptionLogger_ApplicationCrashData; - // This is the end.. + if (!Debugger.IsAttached) + { + ExceptionLogger.UnBind(); // unbind the exception logger.. } - /// - /// Gets or sets a value indicating whether to restart the software upon closing it. - /// - internal static bool Restart { get; set; } = false; - - /// - /// Gets or sets the name of the setting file. - /// - /// The name of the setting file. - internal static string SettingFileName { get; set; } - - #region InternalProperties - /// - /// Gets or sets a value indicating whether the software should be run as elevated (Administrator) after closing self. - /// - internal static bool RestartElevated { get; set; } = false; - - /// - /// Gets or sets the file name which should be opened in an elevated mode (Administrator). - /// - /// - /// The elevate file. - /// - internal static string ElevateFile { get; set; } = ""; - #endregion + // kill self as the native inter-op libraries may have some issues of keeping the process alive.. + Process.GetCurrentProcess().Kill(); + + // This is the end.. } -} + + /// + /// Gets or sets a value indicating whether to restart the software upon closing it. + /// + internal static bool Restart { get; set; } = false; + + /// + /// Gets or sets the name of the setting file. + /// + /// The name of the setting file. + internal static string SettingFileName { get; set; } + + #region InternalProperties + /// + /// Gets or sets a value indicating whether the software should be run as elevated (Administrator) after closing self. + /// + internal static bool RestartElevated { get; set; } = false; + + /// + /// Gets or sets the file name which should be opened in an elevated mode (Administrator). + /// + /// + /// The elevate file. + /// + internal static string ElevateFile { get; set; } = ""; + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/ScriptNotepad.csproj b/ScriptNotepad/ScriptNotepad.csproj index d7159849..e7cdfffa 100644 --- a/ScriptNotepad/ScriptNotepad.csproj +++ b/ScriptNotepad/ScriptNotepad.csproj @@ -1,400 +1,400 @@  - - WinExe - net6.0-windows - true - ScriptNotepad - VPKSoft - ScriptNotepad - A tabbed notepad software with scripting support (C#). - Copyright © VPKSoft 2021 - bin\$(Configuration)\ScriptNotepad.xml - latest - bin\$(Configuration)\ - true - true - - - full - - - pdbonly - AnyCPU - - - notepad7.ico - MIT - https://www.vpksoft.net/2015-03-31-13-33-28/scriptnotepad - https://github.com/VPKSoft/ScriptNotepad - git - ScriptNotepad_icon.png - notepad script editor - 1.1.6 - See: https://github.com/VPKSoft/ScriptNotepad - - - - - FormDialogCustomSpellCheckerInfo.cs - - - - FormDialogQueryJumpLocation.cs - - - - FormDialogQueryNumber.cs - - - - FormDialogRenameNewFile.cs - - - - FormDialogSelectFileTab.cs - - - True - True - Resources.resx - - - - FormPickAColor.cs - - - Component - - - - FormFileDiffView.cs - - - - FormDialogSearchReplaceProgress.cs - - - - FormDialogQueryEncoding.cs - - - - FormLocalizationHelper.cs - - - - FormScript.cs - - - - FormDialogScriptLoad.cs - - - - FormHexEdit.cs - - - - FormPluginManage.cs - - - - FormSettings.cs - - - Form - - - FormTestThingDialog.cs - - - Form - - - FormTestThings.cs - - - - FormMain.cs - - - True - True - Messages.resx - - - Component - - - - FormDialogSearchReplaceProgressFiles.cs - - - - FormSearchAndReplace.cs - - - - FormSearchResultTree.cs - - - - FormDialogSessionManage.cs - - - - FormDialogQuerySortTextStyle.cs - - - FormDialogQueryJumpLocation.cs - - - FormDialogQueryNumber.cs - - - FormDialogRenameNewFile.cs - - - FormDialogSelectFileTab.cs - - - FormDialogCustomSpellCheckerInfo.cs - - - FormPickAColor.cs - - - FormFileDiffView.cs - - - FormDialogSearchReplaceProgress.cs - - - FormDialogQueryEncoding.cs - - - FormHexEdit.cs - - - FormLocalizationHelper.cs - - - FormMain.cs - - - FormScript.cs - - - FormDialogScriptLoad.cs - - - FormPluginManage.cs - - - ResXFileCodeGenerator - Designer - Resources.Designer.cs - - - FormSettings.cs - - - FormTestThingDialog.cs - - - FormTestThings.cs - - - FormDialogSearchReplaceProgressFiles.cs - - - FormSearchAndReplace.cs - - - FormSearchResultTree.cs - - - FormDialogSessionManage.cs - - - FormDialogQuerySortTextStyle.cs - - - True - - - - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - - - - - - - Always - - - Always - - - Always - - - Always - - - Always - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + WinExe + net6.0-windows + true + ScriptNotepad + VPKSoft + ScriptNotepad + A tabbed notepad software with scripting support (C#). + Copyright © VPKSoft 2022 + bin\$(Configuration)\ScriptNotepad.xml + latest + bin\$(Configuration)\ + true + true + + + full + + + pdbonly + AnyCPU + + + notepad7.ico + MIT + https://www.vpksoft.net/2015-03-31-13-33-28/scriptnotepad + https://github.com/VPKSoft/ScriptNotepad + git + ScriptNotepad_icon.png + notepad script editor + 1.1.7 + See: https://github.com/VPKSoft/ScriptNotepad + + + + + FormDialogCustomSpellCheckerInfo.cs + + + + FormDialogQueryJumpLocation.cs + + + + FormDialogQueryNumber.cs + + + + FormDialogRenameNewFile.cs + + + + FormDialogSelectFileTab.cs + + + True + True + Resources.resx + + + + FormPickAColor.cs + + + Component + + + + FormFileDiffView.cs + + + + FormDialogSearchReplaceProgress.cs + + + + FormDialogQueryEncoding.cs + + + + FormLocalizationHelper.cs + + + + FormScript.cs + + + + FormDialogScriptLoad.cs + + + + FormHexEdit.cs + + + + FormPluginManage.cs + + + + FormSettings.cs + + + Form + + + FormTestThingDialog.cs + + + Form + + + FormTestThings.cs + + + + FormMain.cs + + + True + True + Messages.resx + + + Component + + + + FormDialogSearchReplaceProgressFiles.cs + + + + FormSearchAndReplace.cs + + + + FormSearchResultTree.cs + + + + FormDialogSessionManage.cs + + + + FormDialogQuerySortTextStyle.cs + + + FormDialogQueryJumpLocation.cs + + + FormDialogQueryNumber.cs + + + FormDialogRenameNewFile.cs + + + FormDialogSelectFileTab.cs + + + FormDialogCustomSpellCheckerInfo.cs + + + FormPickAColor.cs + + + FormFileDiffView.cs + + + FormDialogSearchReplaceProgress.cs + + + FormDialogQueryEncoding.cs + + + FormHexEdit.cs + + + FormLocalizationHelper.cs + + + FormMain.cs + + + FormScript.cs + + + FormDialogScriptLoad.cs + + + FormPluginManage.cs + + + ResXFileCodeGenerator + Designer + Resources.Designer.cs + + + FormSettings.cs + + + FormTestThingDialog.cs + + + FormTestThings.cs + + + FormDialogSearchReplaceProgressFiles.cs + + + FormSearchAndReplace.cs + + + FormSearchResultTree.cs + + + FormDialogSessionManage.cs + + + FormDialogQuerySortTextStyle.cs + + + True + + + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + Always + + + Always + + + Always + + + Always + + + Always + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ScriptNotepad/Settings/FormDialogCustomSpellCheckerInfo.cs b/ScriptNotepad/Settings/FormDialogCustomSpellCheckerInfo.cs index aa8ac42f..f9ac235c 100644 --- a/ScriptNotepad/Settings/FormDialogCustomSpellCheckerInfo.cs +++ b/ScriptNotepad/Settings/FormDialogCustomSpellCheckerInfo.cs @@ -31,119 +31,104 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.ExternalDictionaryPackage; using VPKSoft.LangLib; -namespace ScriptNotepad.Settings +namespace ScriptNotepad.Settings; + +/// +/// A dialog to display information about a custom spell checker library. +/// Implements the +/// +/// +public partial class FormDialogCustomSpellCheckerInfo : DBLangEngineWinforms { /// - /// A dialog to display information about a custom spell checker library. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogCustomSpellCheckerInfo : DBLangEngineWinforms + public FormDialogCustomSpellCheckerInfo() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogCustomSpellCheckerInfo() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } - - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - // ReSharper disable once InconsistentNaming - private const string NuGetLicenseUrl = "https://licenses.nuget.org/"; + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } + + // ReSharper disable once InconsistentNaming + private const string NuGetLicenseUrl = "https://licenses.nuget.org/"; - /// - /// Shows the form as a modal dialog box with the specified owner. - /// - /// Any object that implements that represents the top-level window that will own the modal dialog box. - /// The XML definition file name. - public static void ShowDialog(IWin32Window owner, string xmlDefinitionFile) + /// + /// Shows the form as a modal dialog box with the specified owner. + /// + /// Any object that implements that represents the top-level window that will own the modal dialog box. + /// The XML definition file name. + public static void ShowDialog(IWin32Window owner, string xmlDefinitionFile) + { + try { + var data = + DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(xmlDefinitionFile); + + var assemblyName = Path.Combine(Path.GetDirectoryName(xmlDefinitionFile) ?? string.Empty, data.lib); + + var version = "1.0.0.0"; + try { - var data = - DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(xmlDefinitionFile); - - var assemblyName = Path.Combine(Path.GetDirectoryName(xmlDefinitionFile) ?? string.Empty, data.lib); - - var version = "1.0.0.0"; - - try - { - var assembly = Assembly.LoadFile(assemblyName); - version = assembly.GetName().Version.ToString(); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } - - - var form = new FormDialogCustomSpellCheckerInfo - { - tbName = {Text = data.name}, - tbLibrary = {Text = data.lib}, - tbCompany = {Text = data.company}, - tbCopyright = {Text = data.copyright}, - tbCulture = {Text = data.cultureName}, - tbCultureDescription = {Text = data.cultureDescription}, - tbCultureDescriptionNative = {Text = data.cultureDescriptionNative}, - lbUrlValue = {Text = data.url}, - lbSpdxLicenseLinkValue = {Text = data.spdxLicenseId, Tag = NuGetLicenseUrl + data.spdxLicenseId}, - tbAssemblyVersion = {Text = version}, - }; - - using (form) - { - form.ShowDialog(); - } + var assembly = Assembly.LoadFile(assemblyName); + version = assembly.GetName().Version.ToString(); } catch (Exception ex) { // log the exception.. ExceptionLogger.LogError(ex); } - } - private void btClose_Click(object sender, EventArgs e) - { - Close(); - } - private void lbSpdxLicenseLinkValue_Click(object sender, EventArgs e) - { - var label = (Label) sender; - if (label.Tag.ToString().StartsWith(NuGetLicenseUrl)) + var form = new FormDialogCustomSpellCheckerInfo + { + tbName = {Text = data.name, }, + tbLibrary = {Text = data.lib, }, + tbCompany = {Text = data.company, }, + tbCopyright = {Text = data.copyright, }, + tbCulture = {Text = data.cultureName, }, + tbCultureDescription = {Text = data.cultureDescription, }, + tbCultureDescriptionNative = {Text = data.cultureDescriptionNative, }, + lbUrlValue = {Text = data.url, }, + lbSpdxLicenseLinkValue = {Text = data.spdxLicenseId, Tag = NuGetLicenseUrl + data.spdxLicenseId, }, + tbAssemblyVersion = {Text = version, }, + }; + + using (form) { - try - { - Process.Start(label.Tag.ToString()); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } + form.ShowDialog(); } } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + } + } - private void lbUrlValue_Click(object sender, EventArgs e) + private void btClose_Click(object sender, EventArgs e) + { + Close(); + } + + private void lbSpdxLicenseLinkValue_Click(object sender, EventArgs e) + { + var label = (Label) sender; + if (label.Tag.ToString().StartsWith(NuGetLicenseUrl)) { try { - var label = (Label) sender; - Process.Start(label.Text); + Process.Start(label.Tag.ToString()); } catch (Exception ex) { @@ -152,4 +137,18 @@ private void lbUrlValue_Click(object sender, EventArgs e) } } } -} + + private void lbUrlValue_Click(object sender, EventArgs e) + { + try + { + var label = (Label) sender; + Process.Start(label.Text); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + } + } +} \ No newline at end of file diff --git a/ScriptNotepad/Settings/FormSettings.cs b/ScriptNotepad/Settings/FormSettings.cs index fb21fcee..a5cec00a 100644 --- a/ScriptNotepad/Settings/FormSettings.cs +++ b/ScriptNotepad/Settings/FormSettings.cs @@ -48,1289 +48,1288 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.Utils; using TabDrawMode = ScintillaNET.TabDrawMode; -namespace ScriptNotepad.Settings +namespace ScriptNotepad.Settings; + +/// +/// A settings/preferences dialog for the application. +/// +/// +public partial class FormSettings : DBLangEngineWinforms { /// - /// A settings/preferences dialog for the application. + /// Initializes a new instance of the class. /// - /// - public partial class FormSettings : DBLangEngineWinforms + public FormSettings() { - /// - /// Initializes a new instance of the class. - /// - public FormSettings() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - // this combo box won't be localized.. - cmbUrlIndicatorStyle.DataSource = Enum.GetValues(typeof(IndicatorStyle)); + // this combo box won't be localized.. + cmbUrlIndicatorStyle.DataSource = Enum.GetValues(typeof(IndicatorStyle)); - // create a new instance of the CharacterSetComboBuilder class.. - CharacterSetComboBuilder = new CharacterSetComboBuilder(cmbCharacterSet, cmbEncoding, false, "encoding"); + // create a new instance of the CharacterSetComboBuilder class.. + CharacterSetComboBuilder = new CharacterSetComboBuilder(cmbCharacterSet, cmbEncoding, false, "encoding"); - // subscribe the encoding selected event.. - CharacterSetComboBuilder.EncodingSelected += CharacterSetComboBuilder_EncodingSelected; + // subscribe the encoding selected event.. + CharacterSetComboBuilder.EncodingSelected += CharacterSetComboBuilder_EncodingSelected; - // translate the tool tips.. - ttMain.SetToolTip(btUTF8, - DBLangEngine.GetMessage("msgUTF8Encoding", "Set to Unicode (UTF8)|Set the selected encoding to UTF8 via a button click")); + // translate the tool tips.. + ttMain.SetToolTip(btUTF8, + DBLangEngine.GetMessage("msgUTF8Encoding", "Set to Unicode (UTF8)|Set the selected encoding to UTF8 via a button click")); - // translate the tool tips.. - ttMain.SetToolTip(btSystemDefaultEncoding, - DBLangEngine.GetMessage("msgSysDefaultEncoding", "Set to system default|Set the selected encoding to system's default encoding via a button click")); + // translate the tool tips.. + ttMain.SetToolTip(btSystemDefaultEncoding, + DBLangEngine.GetMessage("msgSysDefaultEncoding", "Set to system default|Set the selected encoding to system's default encoding via a button click")); - // translate the tool tips.. - ttMain.SetToolTip(pbDefaultFolder, - DBLangEngine.GetMessage("msgSetToDefault", "Set to default|A some value is set to default value")); + // translate the tool tips.. + ttMain.SetToolTip(pbDefaultFolder, + DBLangEngine.GetMessage("msgSetToDefault", "Set to default|A some value is set to default value")); - ttMain.SetToolTip(pbAbout, - DBLangEngine.GetMessage("msgDisplaySpellCheckerInfo", "Display spell checker information|A too tip for a button to display spell information dialog for a custom spell checker library")); + ttMain.SetToolTip(pbAbout, + DBLangEngine.GetMessage("msgDisplaySpellCheckerInfo", "Display spell checker information|A too tip for a button to display spell information dialog for a custom spell checker library")); - // list the translated cultures.. - List cultures = DBLangEngine.GetLocalizedCultures(); + // list the translated cultures.. + List cultures = DBLangEngine.GetLocalizedCultures(); - // a the translated cultures to the selection combo box.. - // ReSharper disable once CoVariantArrayConversion - cmbSelectLanguageValue.Items.AddRange(cultures.ToArray()); + // a the translated cultures to the selection combo box.. + // ReSharper disable once CoVariantArrayConversion + cmbSelectLanguageValue.Items.AddRange(cultures.ToArray()); - foreach (var fontFamily in FontFamily.Families) + foreach (var fontFamily in FontFamily.Families) + { + // validate that the font is fixed of width type.. + if (fontFamily.IsFixedWidth()) { - // validate that the font is fixed of width type.. - if (fontFamily.IsFixedWidth()) - { - cmbFont.Items.Add(new FontFamilyHolder {FontFamily = fontFamily}); - } + cmbFont.Items.Add(new FontFamilyHolder {FontFamily = fontFamily, }); } + } - // on my keyboard the AltGr+(2|3|4) keys somehow aren't registered by the active Scintilla tab, - // so make a way to bypass this weirdness.. - cmbSimulateKeyboard.Items.Add(DBLangEngine.GetMessage("msgAltGrFinnish", - "Finnish AltGr simulation (@, £, $)|A message describing that the AltGr and some key would simulate a keypress for an active Scintilla control.")); + // on my keyboard the AltGr+(2|3|4) keys somehow aren't registered by the active Scintilla tab, + // so make a way to bypass this weirdness.. + cmbSimulateKeyboard.Items.Add(DBLangEngine.GetMessage("msgAltGrFinnish", + "Finnish AltGr simulation (@, £, $)|A message describing that the AltGr and some key would simulate a keypress for an active Scintilla control.")); - // localize the dialog filters.. - StaticLocalizeFileDialog.InitOpenHunspellDictionaryDialog(odDictionaryFile); - StaticLocalizeFileDialog.InitOpenHunspellAffixFileDialog(odAffixFile); - StaticLocalizeFileDialog.InitOpenSpellCheckerZip(odSpellCheckerPackage); - StaticLocalizeFileDialog.InitOpenXmlFileDialog(odXml); + // localize the dialog filters.. + StaticLocalizeFileDialog.InitOpenHunspellDictionaryDialog(odDictionaryFile); + StaticLocalizeFileDialog.InitOpenHunspellAffixFileDialog(odAffixFile); + StaticLocalizeFileDialog.InitOpenSpellCheckerZip(odSpellCheckerPackage); + StaticLocalizeFileDialog.InitOpenXmlFileDialog(odXml); - // create the URL styling class for the Scintilla text box.. - scintillaUrlDetect = new ScintillaUrlDetect(scintillaUrlStyle); - } + // create the URL styling class for the Scintilla text box.. + scintillaUrlDetect = new ScintillaUrlDetect(scintillaUrlStyle); + } - private ScintillaUrlDetect scintillaUrlDetect; + private ScintillaUrlDetect scintillaUrlDetect; - /// - /// Gets or sets a value indicating whether to suspend certain event handler execution to avoid consecutive code execution. - /// - // ReSharper disable once UnusedMember.Local - private bool SuspendEvents { get; set; } + /// + /// Gets or sets a value indicating whether to suspend certain event handler execution to avoid consecutive code execution. + /// + // ReSharper disable once UnusedMember.Local + private bool SuspendEvents { get; set; } - private class FontFamilyHolder + private class FontFamilyHolder + { + public static FontFamilyHolder FromFontFamilyName(string fontFamilyName) { - public static FontFamilyHolder FromFontFamilyName(string fontFamilyName) - { - List families = new List(FontFamily.Families); - var family = families.Find(f => f.Name == fontFamilyName); - return new FontFamilyHolder {FontFamily = family}; - } + List families = new List(FontFamily.Families); + var family = families.Find(f => f.Name == fontFamilyName); + return new FontFamilyHolder {FontFamily = family, }; + } - public FontFamily FontFamily { get; set; } + public FontFamily FontFamily { get; set; } - public override string ToString() - { - return FontFamily.Name; - } + public override string ToString() + { + return FontFamily.Name; } + } - /// - /// Displays the FormSettings dialog and saves the settings if the user selected OK. - /// - /// A value indicating whether the user decided to restart the software for the changes to take affect. - /// True if the user selected to save the settings; otherwise false. - public static bool Execute(out bool restart) - { - FormSettings formSettings = new FormSettings(); - var dialogResult = formSettings.ShowDialog(); + /// + /// Displays the FormSettings dialog and saves the settings if the user selected OK. + /// + /// A value indicating whether the user decided to restart the software for the changes to take affect. + /// True if the user selected to save the settings; otherwise false. + public static bool Execute(out bool restart) + { + FormSettings formSettings = new FormSettings(); + var dialogResult = formSettings.ShowDialog(); - restart = false; + restart = false; - if (dialogResult == DialogResult.OK || dialogResult == DialogResult.Yes) - { - restart = MessageBoxExtended.Show( - DBLangEngine.GetStatMessage("msgRestartSettingsToAffect", - "Restart the application for the changes to take affect?|A message querying the user whether to restart the software saving the changed settings."), - DBLangEngine.GetStatMessage("msgQuestion", "Question|A title for a message box asking a question."), MessageBoxButtonsExtended.YesNo, - MessageBoxIcon.Question, ExtendedDefaultButtons.Button1) == DialogResultExtended.Yes; - - formSettings.SaveSettings(); - return true; - } - return false; + if (dialogResult == DialogResult.OK || dialogResult == DialogResult.Yes) + { + restart = MessageBoxExtended.Show( + DBLangEngine.GetStatMessage("msgRestartSettingsToAffect", + "Restart the application for the changes to take affect?|A message querying the user whether to restart the software saving the changed settings."), + DBLangEngine.GetStatMessage("msgQuestion", "Question|A title for a message box asking a question."), MessageBoxButtonsExtended.YesNo, + MessageBoxIcon.Question, ExtendedDefaultButtons.Button1) == DialogResultExtended.Yes; + + formSettings.SaveSettings(); + return true; } + return false; + } - #region SaveLoad - /// - /// Loads the settings visualized to form. - /// - private void LoadSettings() - { - // select the encoding from the settings.. - CharacterSetComboBuilder.SelectItemByEncoding(Encoding.Default, false); + #region SaveLoad + /// + /// Loads the settings visualized to form. + /// + private void LoadSettings() + { + // select the encoding from the settings.. + CharacterSetComboBuilder.SelectItemByEncoding(Encoding.Default, false); - // get the value whether to use auto-detection on a file encoding on opening a new file.. - cbEncodingAutoDetect.Checked = Settings.AutoDetectEncoding; + // get the value whether to use auto-detection on a file encoding on opening a new file.. + cbEncodingAutoDetect.Checked = Settings.AutoDetectEncoding; - // get the amount of document file names to keep in history.. - nudHistoryDocuments.Value = Settings.HistoryListAmount; + // get the amount of document file names to keep in history.. + nudHistoryDocuments.Value = Settings.HistoryListAmount; - // get the amount of documents contents to be kept after a document has been closed.. - nudDocumentContentHistory.Value = Settings.SaveFileHistoryContentsCount; + // get the amount of documents contents to be kept after a document has been closed.. + nudDocumentContentHistory.Value = Settings.SaveFileHistoryContentsCount; - // get the flag whether to save closed document contents.. - cbDocumentContentHistory.Checked = Settings.SaveFileHistoryContents; + // get the flag whether to save closed document contents.. + cbDocumentContentHistory.Checked = Settings.SaveFileHistoryContents; - // get the current culture from the settings.. - cmbSelectLanguageValue.SelectedItem = Settings.Culture; + // get the current culture from the settings.. + cmbSelectLanguageValue.SelectedItem = Settings.Culture; - // get the current plug-in folder from the settings.. - tbPluginFolder.Text = Settings.PluginFolder; + // get the current plug-in folder from the settings.. + tbPluginFolder.Text = Settings.PluginFolder; - // get the value of whether to dock the search tree form in the main form.. - cbDockSearchTree.Checked = Settings.DockSearchTreeForm; + // get the value of whether to dock the search tree form in the main form.. + cbDockSearchTree.Checked = Settings.DockSearchTreeForm; - // get the value whether to categorize the programming language menu with the language name starting character.. - cbCategorizeProgrammingLanguages.Checked = Settings.CategorizeStartCharacterProgrammingLanguage; + // get the value whether to categorize the programming language menu with the language name starting character.. + cbCategorizeProgrammingLanguages.Checked = Settings.CategorizeStartCharacterProgrammingLanguage; - // get the color values.. - btSmartHighlightColor.BackColor = Settings.SmartHighlight; - btMarkStyle1Color.BackColor = Settings.Mark1Color; - btMarkStyle2Color.BackColor = Settings.Mark2Color; - btMarkStyle3Color.BackColor = Settings.Mark3Color; - btMarkStyle4Color.BackColor = Settings.Mark4Color; - btMarkStyle5Color.BackColor = Settings.Mark5Color; - btCurrentLineBackgroundColor.BackColor = Settings.CurrentLineBackground; + // get the color values.. + btSmartHighlightColor.BackColor = Settings.SmartHighlight; + btMarkStyle1Color.BackColor = Settings.Mark1Color; + btMarkStyle2Color.BackColor = Settings.Mark2Color; + btMarkStyle3Color.BackColor = Settings.Mark3Color; + btMarkStyle4Color.BackColor = Settings.Mark4Color; + btMarkStyle5Color.BackColor = Settings.Mark5Color; + btCurrentLineBackgroundColor.BackColor = Settings.CurrentLineBackground; - btBraceHighlightForegroundColor.BackColor = Settings.BraceHighlightForegroundColor; - btBraceHighlightBackgroundColor.BackColor = Settings.BraceHighlightBackgroundColor; - btBadBraceColor.BackColor = Settings.BraceBadHighlightForegroundColor; - cbUseBraceMatching.Checked = Settings.HighlightBraces; - rbBraceStyleItalic.Checked = Settings.HighlightBracesItalic; - rbBraceStyleBold.Checked = Settings.HighlightBracesBold; - // END: get the color values.. + btBraceHighlightForegroundColor.BackColor = Settings.BraceHighlightForegroundColor; + btBraceHighlightBackgroundColor.BackColor = Settings.BraceHighlightBackgroundColor; + btBadBraceColor.BackColor = Settings.BraceBadHighlightForegroundColor; + cbUseBraceMatching.Checked = Settings.HighlightBraces; + rbBraceStyleItalic.Checked = Settings.HighlightBracesItalic; + rbBraceStyleBold.Checked = Settings.HighlightBracesBold; + // END: get the color values.. - // get the value of file's maximum size in megabytes (MB) to include in the file search.. - nudMaximumSearchFileSize.Value = Settings.FileSearchMaxSizeMb; + // get the value of file's maximum size in megabytes (MB) to include in the file search.. + nudMaximumSearchFileSize.Value = Settings.FileSearchMaxSizeMb; - // get the amount of how much search history (search text, replace text, directories, paths, etc.) to keep.. - nudHistoryAmount.Value = Settings.FileSearchHistoriesLimit; + // get the amount of how much search history (search text, replace text, directories, paths, etc.) to keep.. + nudHistoryAmount.Value = Settings.FileSearchHistoriesLimit; - // get the size of the white space dot.. - nudWhiteSpaceSize.Value = Settings.EditorWhiteSpaceSize; + // get the size of the white space dot.. + nudWhiteSpaceSize.Value = Settings.EditorWhiteSpaceSize; - // get the value whether to use tabs in the editor (tabulator characters).. - cbUseTabs.Checked = Settings.EditorUseTabs; + // get the value whether to use tabs in the editor (tabulator characters).. + cbUseTabs.Checked = Settings.EditorUseTabs; - // get the value whether to use individual zoom value for all - // the open documents.. - cbIndividualZoom.Checked = Settings.EditorIndividualZoom; + // get the value whether to use individual zoom value for all + // the open documents.. + cbIndividualZoom.Checked = Settings.EditorIndividualZoom; - // get the value whether the zoom value of the document(s) - // should be saved into the database.. - cbSaveDocumentZoom.Checked = Settings.EditorSaveZoom; + // get the value whether the zoom value of the document(s) + // should be saved into the database.. + cbSaveDocumentZoom.Checked = Settings.EditorSaveZoom; - // gets the type of the tab character symbol.. - rbTabSymbolStrikeout.Checked = Settings.EditorTabSymbol != 0; - rbTabSymbolArrow.Checked = Settings.EditorTabSymbol == 0; + // gets the type of the tab character symbol.. + rbTabSymbolStrikeout.Checked = Settings.EditorTabSymbol != 0; + rbTabSymbolArrow.Checked = Settings.EditorTabSymbol == 0; - // get the indent guide value.. - cbIndentGuideOn.Checked = Settings.EditorIndentGuideOn; + // get the indent guide value.. + cbIndentGuideOn.Checked = Settings.EditorIndentGuideOn; - #region SpellCheck - // get the spell checking properties.. - if (File.Exists(Settings.EditorHunspellDictionaryFile) && File.Exists(Settings.EditorHunspellAffixFile) && - (Settings.EditorUseSpellChecking || Settings.EditorUseSpellCheckingNewFiles)) - { - cbSpellCheckInUse.Checked = Settings.EditorUseSpellChecking; - cbSpellCheckInUseNewFiles.Checked = Settings.EditorUseSpellCheckingNewFiles; - cbSpellCheckInShellContext.Checked = Settings.EditorUseSpellCheckingShellContext; - } + #region SpellCheck + // get the spell checking properties.. + if (File.Exists(Settings.EditorHunspellDictionaryFile) && File.Exists(Settings.EditorHunspellAffixFile) && + (Settings.EditorUseSpellChecking || Settings.EditorUseSpellCheckingNewFiles)) + { + cbSpellCheckInUse.Checked = Settings.EditorUseSpellChecking; + cbSpellCheckInUseNewFiles.Checked = Settings.EditorUseSpellCheckingNewFiles; + cbSpellCheckInShellContext.Checked = Settings.EditorUseSpellCheckingShellContext; + } - tbDictionaryPath.Text = Settings.EditorHunspellDictionaryPath; - btSpellCheckMarkColor.BackColor = Settings.EditorSpellCheckColor; + tbDictionaryPath.Text = Settings.EditorHunspellDictionaryPath; + btSpellCheckMarkColor.BackColor = Settings.EditorSpellCheckColor; - tbHunspellAffixFile.Text = Settings.EditorHunspellAffixFile; - tbHunspellDictionary.Text = Settings.EditorHunspellDictionaryFile; - nudEditorSpellRecheckInactivity.Value = Settings.EditorSpellCheckInactivity; - #endregion + tbHunspellAffixFile.Text = Settings.EditorHunspellAffixFile; + tbHunspellDictionary.Text = Settings.EditorHunspellDictionaryFile; + nudEditorSpellRecheckInactivity.Value = Settings.EditorSpellCheckInactivity; + #endregion - // get the editor font settings.. - nudFontSize.Value = Settings.EditorFontSize; + // get the editor font settings.. + nudFontSize.Value = Settings.EditorFontSize; - var item = FontFamilyHolder.FromFontFamilyName(Settings.EditorFontName); + var item = FontFamilyHolder.FromFontFamilyName(Settings.EditorFontName); - for (int i = 0; i < cmbFont.Items.Count; i++) + for (int i = 0; i < cmbFont.Items.Count; i++) + { + if (Equals(((FontFamilyHolder)cmbFont.Items[i]).FontFamily, item.FontFamily)) { - if (Equals(((FontFamilyHolder)cmbFont.Items[i]).FontFamily, item.FontFamily)) - { - cmbFont.SelectedIndex = i; - break; - } + cmbFont.SelectedIndex = i; + break; } + } - nudFontSize.Value = Settings.EditorFontSize; + nudFontSize.Value = Settings.EditorFontSize; - // get the Notepad++ them path.. - tbNotepadPlusPlusThemePath.Text = Settings.NotepadPlusPlusThemePath; + // get the Notepad++ them path.. + tbNotepadPlusPlusThemePath.Text = Settings.NotepadPlusPlusThemePath; - // list the Notepad++ then files if any.. - ListNotepadPlusPLusThemes(); + // list the Notepad++ then files if any.. + ListNotepadPlusPLusThemes(); - // get the Notepad++ theme settings.. - cbUseNotepadPlusPlusTheme.Checked = Settings.UseNotepadPlusPlusTheme; + // get the Notepad++ theme settings.. + cbUseNotepadPlusPlusTheme.Checked = Settings.UseNotepadPlusPlusTheme; - if (Settings.NotepadPlusPlusThemeFile != null) - { - cmbNotepadPlusPlusTheme.SelectedIndex = cmbNotepadPlusPlusTheme.Items.IndexOf( - Path.GetFileNameWithoutExtension(Settings.NotepadPlusPlusThemeFile)); - } - - // get the AltGr capture bypass method if set.. - if (Settings.SimulateAltGrKeyIndex != -1) - { - cbSimulateKeyboard.Checked = true; - cmbSimulateKeyboard.SelectedIndex = Settings.SimulateAltGrKeyIndex; - } - - // get the code indentation and editor tab width values.. - cbUseCodeIndentation.Checked = Settings.EditorUseCodeIndentation; - nudTabWidth.Value = Settings.EditorTabWidth; - - // get the no-BOM detection value.. - cbDetectNoBomUnicode.Checked = Settings.DetectNoBom; + if (Settings.NotepadPlusPlusThemeFile != null) + { + cmbNotepadPlusPlusTheme.SelectedIndex = cmbNotepadPlusPlusTheme.Items.IndexOf( + Path.GetFileNameWithoutExtension(Settings.NotepadPlusPlusThemeFile)); + } - gpSkipEncodings.Enabled = Settings.DetectNoBom; + // get the AltGr capture bypass method if set.. + if (Settings.SimulateAltGrKeyIndex != -1) + { + cbSimulateKeyboard.Checked = true; + cmbSimulateKeyboard.SelectedIndex = Settings.SimulateAltGrKeyIndex; + } - // get the auto-save settings.. - cbUseAutoSave.Checked = Settings.ProgramAutoSave; - nudAutoSaveInterval.Value = Settings.ProgramAutoSaveInterval; + // get the code indentation and editor tab width values.. + cbUseCodeIndentation.Checked = Settings.EditorUseCodeIndentation; + nudTabWidth.Value = Settings.EditorTabWidth; - // set the value whether to use auto-complete on the search box combo boxes.. - cbSearchUseAutoComplete.Checked = Settings.AutoCompleteEnabled; + // get the no-BOM detection value.. + cbDetectNoBomUnicode.Checked = Settings.DetectNoBom; - // get the tread locale value.. - cbSetThreadLocale.Checked = Settings.LocalizeThread; + gpSkipEncodings.Enabled = Settings.DetectNoBom; - // get the value whether to check for a new application version upon startup.. - cbUpdateAutoCheck.Checked = Settings.UpdateAutoCheck; + // get the auto-save settings.. + cbUseAutoSave.Checked = Settings.ProgramAutoSave; + nudAutoSaveInterval.Value = Settings.ProgramAutoSaveInterval; - // get the Unicode detection skip values.. - cbNoUnicodeLE.Checked = Settings.SkipUnicodeDetectLe; - cbNoUnicodeBE.Checked = Settings.SkipUnicodeDetectBe; - cbNoUTF32LE.Checked = Settings.SkipUtf32Le; - cbNoUTF32BE.Checked = Settings.SkipUtf32Be; + // set the value whether to use auto-complete on the search box combo boxes.. + cbSearchUseAutoComplete.Checked = Settings.AutoCompleteEnabled; - #region TextSettings - cbCaseSensitive.Checked = Settings.TextUpperCaseComparison; - switch (Settings.TextComparisonType) - { - case 0: rbTextInvariant.Checked = true; break; - case 1: rbTextCurrent.Checked = true; break; - case 2: rbTextOrdinal.Checked = true; break; - default: rbTextInvariant.Checked = true; break; - } - #endregion + // get the tread locale value.. + cbSetThreadLocale.Checked = Settings.LocalizeThread; - // the default encoding setting is deprecated and hidden.. - var encodings = Settings.GetEncodingList(); + // get the value whether to check for a new application version upon startup.. + cbUpdateAutoCheck.Checked = Settings.UpdateAutoCheck; - foreach (var encoding in encodings) - { - dgvEncodings.Rows.Add(encoding.encoding, encoding.encodingName, encoding.unicodeBOM, - encoding.unicodeFailOnInvalidChar); - } + // get the Unicode detection skip values.. + cbNoUnicodeLE.Checked = Settings.SkipUnicodeDetectLe; + cbNoUnicodeBE.Checked = Settings.SkipUnicodeDetectBe; + cbNoUTF32LE.Checked = Settings.SkipUtf32Le; + cbNoUTF32BE.Checked = Settings.SkipUtf32Be; - // custom spell checker library.. - cbUseCustomSpellCheckingLibrary.Checked = Settings.EditorSpellUseCustomDictionary; - tbSpellCheckingLibraryFile.Text = Settings.EditorSpellCustomDictionaryDefinitionFile; - - #region EditorAdditional - // an experimental auto-complete for the C# programming language and the Scintilla control.. - cbUseAutoCompleteCs.Checked = Settings.UseCSharpAutoComplete; - #endregion - - #region UrlStyle - cbHighlightUrls.Checked = Settings.HighlightUrls; - cbStartProcessOnUrlClick.Checked = Settings.StartProcessOnUrlClick; - btUrlTextColor.BackColor = Settings.UrlTextColor; - btUrlIndicatorColor.BackColor = Settings.UrlIndicatorColor; - cmbUrlIndicatorStyle.SelectedItem = (IndicatorStyle)Settings.UrlIndicatorStyle; - cbUseDwellToolTip.Checked = Settings.UrlUseDwellToolTip; - nudDwellToolTipDelay.Value = Settings.UrlDwellToolTipTime; - btDwellToolTipForegroundColor.BackColor = Settings.UrlDwellToolTipForegroundColor; - btDwellToolTipBackgroundColor.BackColor = Settings.UrlDwellToolTipBackgroundColor; - nudURLUseAutoEllipsis.Value = Settings.UrlMaxLengthBeforeEllipsis; - cbURLUseAutoEllipsis.Checked = Settings.UrlUseAutoEllipsis; - #endregion - - #region DateTime - // get the date and time formats.. - tbDateTimeFormat1.Text = Settings.DateFormat1; - tbDateTimeFormat2.Text = Settings.DateFormat2; - tbDateTimeFormat3.Text = Settings.DateFormat3; - tbDateTimeFormat4.Text = Settings.DateFormat4; - tbDateTimeFormat5.Text = Settings.DateFormat5; - tbDateTimeFormat6.Text = Settings.DateFormat6; - cbDateTimeUseInvarianCulture.Checked = Settings.DateFormatUseInvariantCulture; - #endregion + #region TextSettings + cbCaseSensitive.Checked = Settings.TextUpperCaseComparison; + switch (Settings.TextComparisonType) + { + case 0: rbTextInvariant.Checked = true; break; + case 1: rbTextCurrent.Checked = true; break; + case 2: rbTextOrdinal.Checked = true; break; + default: rbTextInvariant.Checked = true; break; } + #endregion + + // the default encoding setting is deprecated and hidden.. + var encodings = Settings.GetEncodingList(); - /// - /// Saves the settings visualized on the form. - /// - private void SaveSettings() + foreach (var encoding in encodings) { - // save the value whether to use auto-detection on a file encoding on opening a new file.. - Settings.AutoDetectEncoding = cbEncodingAutoDetect.Checked; + dgvEncodings.Rows.Add(encoding.encoding, encoding.encodingName, encoding.unicodeBOM, + encoding.unicodeFailOnInvalidChar); + } - // save the amount of history documents to keep.. - Settings.HistoryListAmount = (int)nudHistoryDocuments.Value; + // custom spell checker library.. + cbUseCustomSpellCheckingLibrary.Checked = Settings.EditorSpellUseCustomDictionary; + tbSpellCheckingLibraryFile.Text = Settings.EditorSpellCustomDictionaryDefinitionFile; - // save the amount of documents contents to be kept after a document has been closed.. - Settings.SaveFileHistoryContentsCount = (int)nudDocumentContentHistory.Value; + #region EditorAdditional + // an experimental auto-complete for the C# programming language and the Scintilla control.. + cbUseAutoCompleteCs.Checked = Settings.UseCSharpAutoComplete; + #endregion - // save the flag whether to save closed document contents.. - Settings.SaveFileHistoryContents = cbDocumentContentHistory.Checked; + #region UrlStyle + cbHighlightUrls.Checked = Settings.HighlightUrls; + cbStartProcessOnUrlClick.Checked = Settings.StartProcessOnUrlClick; + btUrlTextColor.BackColor = Settings.UrlTextColor; + btUrlIndicatorColor.BackColor = Settings.UrlIndicatorColor; + cmbUrlIndicatorStyle.SelectedItem = (IndicatorStyle)Settings.UrlIndicatorStyle; + cbUseDwellToolTip.Checked = Settings.UrlUseDwellToolTip; + nudDwellToolTipDelay.Value = Settings.UrlDwellToolTipTime; + btDwellToolTipForegroundColor.BackColor = Settings.UrlDwellToolTipForegroundColor; + btDwellToolTipBackgroundColor.BackColor = Settings.UrlDwellToolTipBackgroundColor; + nudURLUseAutoEllipsis.Value = Settings.UrlMaxLengthBeforeEllipsis; + cbURLUseAutoEllipsis.Checked = Settings.UrlUseAutoEllipsis; + #endregion - // save the selected culture for localization.. - Settings.Culture = (CultureInfo)cmbSelectLanguageValue.SelectedItem; + #region DateTime + // get the date and time formats.. + tbDateTimeFormat1.Text = Settings.DateFormat1; + tbDateTimeFormat2.Text = Settings.DateFormat2; + tbDateTimeFormat3.Text = Settings.DateFormat3; + tbDateTimeFormat4.Text = Settings.DateFormat4; + tbDateTimeFormat5.Text = Settings.DateFormat5; + tbDateTimeFormat6.Text = Settings.DateFormat6; + cbDateTimeUseInvarianCulture.Checked = Settings.DateFormatUseInvariantCulture; + #endregion + } - // save the selected plug-in folder to the settings.. - Settings.PluginFolder = tbPluginFolder.Text; + /// + /// Saves the settings visualized on the form. + /// + private void SaveSettings() + { + // save the value whether to use auto-detection on a file encoding on opening a new file.. + Settings.AutoDetectEncoding = cbEncodingAutoDetect.Checked; - // save the value of whether to dock the search tree form in the main form.. - Settings.DockSearchTreeForm = cbDockSearchTree.Checked; + // save the amount of history documents to keep.. + Settings.HistoryListAmount = (int)nudHistoryDocuments.Value; - // save the value whether to categorize the programming language menu with the language name starting character.. - Settings.CategorizeStartCharacterProgrammingLanguage = cbCategorizeProgrammingLanguages.Checked; + // save the amount of documents contents to be kept after a document has been closed.. + Settings.SaveFileHistoryContentsCount = (int)nudDocumentContentHistory.Value; - // save the color values.. - Settings.SmartHighlight = btSmartHighlightColor.BackColor; - Settings.Mark1Color = btMarkStyle1Color.BackColor; - Settings.Mark2Color = btMarkStyle2Color.BackColor; - Settings.Mark3Color = btMarkStyle3Color.BackColor; - Settings.Mark4Color = btMarkStyle4Color.BackColor; - Settings.Mark5Color = btMarkStyle5Color.BackColor; - Settings.CurrentLineBackground = btCurrentLineBackgroundColor.BackColor; + // save the flag whether to save closed document contents.. + Settings.SaveFileHistoryContents = cbDocumentContentHistory.Checked; - Settings.BraceHighlightForegroundColor = btBraceHighlightForegroundColor.BackColor; - Settings.BraceHighlightBackgroundColor = btBraceHighlightBackgroundColor.BackColor; - Settings.BraceBadHighlightForegroundColor = btBadBraceColor.BackColor; - Settings.HighlightBraces = cbUseBraceMatching.Checked; - Settings.HighlightBracesItalic = rbBraceStyleItalic.Checked; - Settings.HighlightBracesBold = rbBraceStyleBold.Checked; - // END: save the color values.. + // save the selected culture for localization.. + Settings.Culture = (CultureInfo)cmbSelectLanguageValue.SelectedItem; - // set the value of file's maximum size in megabytes (MB) to include in the file search.. - Settings.FileSearchMaxSizeMb = (long)nudMaximumSearchFileSize.Value; + // save the selected plug-in folder to the settings.. + Settings.PluginFolder = tbPluginFolder.Text; - // set the amount of how much search history (search text, replace text, directories, paths, etc.) to keep.. - Settings.FileSearchHistoriesLimit = (int)nudHistoryAmount.Value; + // save the value of whether to dock the search tree form in the main form.. + Settings.DockSearchTreeForm = cbDockSearchTree.Checked; - // set the size of the white space dot.. - Settings.EditorWhiteSpaceSize = (int)nudWhiteSpaceSize.Value; + // save the value whether to categorize the programming language menu with the language name starting character.. + Settings.CategorizeStartCharacterProgrammingLanguage = cbCategorizeProgrammingLanguages.Checked; - // set the value whether to use tabs in the editor (tabulator characters).. - Settings.EditorUseTabs = cbUseTabs.Checked; + // save the color values.. + Settings.SmartHighlight = btSmartHighlightColor.BackColor; + Settings.Mark1Color = btMarkStyle1Color.BackColor; + Settings.Mark2Color = btMarkStyle2Color.BackColor; + Settings.Mark3Color = btMarkStyle3Color.BackColor; + Settings.Mark4Color = btMarkStyle4Color.BackColor; + Settings.Mark5Color = btMarkStyle5Color.BackColor; + Settings.CurrentLineBackground = btCurrentLineBackgroundColor.BackColor; - // set the value whether to use individual zoom value for all - // the open documents.. - Settings.EditorIndividualZoom = cbIndividualZoom.Checked; + Settings.BraceHighlightForegroundColor = btBraceHighlightForegroundColor.BackColor; + Settings.BraceHighlightBackgroundColor = btBraceHighlightBackgroundColor.BackColor; + Settings.BraceBadHighlightForegroundColor = btBadBraceColor.BackColor; + Settings.HighlightBraces = cbUseBraceMatching.Checked; + Settings.HighlightBracesItalic = rbBraceStyleItalic.Checked; + Settings.HighlightBracesBold = rbBraceStyleBold.Checked; + // END: save the color values.. - // set the value whether the zoom value of the document(s) - // should be saved into the database.. - Settings.EditorSaveZoom = cbSaveDocumentZoom.Checked; + // set the value of file's maximum size in megabytes (MB) to include in the file search.. + Settings.FileSearchMaxSizeMb = (long)nudMaximumSearchFileSize.Value; - // set the type of the tab character symbol.. - if (rbTabSymbolArrow.Checked) - { - Settings.EditorTabSymbol = (int) TabDrawMode.LongArrow; - } - else - { - Settings.EditorTabSymbol = (int) TabDrawMode.Strikeout; - } + // set the amount of how much search history (search text, replace text, directories, paths, etc.) to keep.. + Settings.FileSearchHistoriesLimit = (int)nudHistoryAmount.Value; - // set the indent guide value.. - Settings.EditorIndentGuideOn = cbIndentGuideOn.Checked; + // set the size of the white space dot.. + Settings.EditorWhiteSpaceSize = (int)nudWhiteSpaceSize.Value; - #region SpellCheck - // set the spell checking properties.. - Settings.EditorUseSpellChecking = cbSpellCheckInUse.Checked; - Settings.EditorUseSpellCheckingNewFiles = cbSpellCheckInUseNewFiles.Checked; - Settings.EditorSpellCheckColor = btSpellCheckMarkColor.BackColor; - Settings.EditorHunspellAffixFile = tbHunspellAffixFile.Text; - Settings.EditorHunspellDictionaryFile = tbHunspellDictionary.Text; - Settings.EditorSpellCheckInactivity = (int)nudEditorSpellRecheckInactivity.Value; - Settings.EditorHunspellDictionaryPath = tbDictionaryPath.Text; - Settings.EditorUseSpellCheckingShellContext = cbSpellCheckInShellContext.Checked; - #endregion + // set the value whether to use tabs in the editor (tabulator characters).. + Settings.EditorUseTabs = cbUseTabs.Checked; - // set the editor font settings.. - Settings.EditorFontSize = (int) nudFontSize.Value; - Settings.EditorFontName = ((FontFamilyHolder) cmbFont.SelectedItem).ToString(); + // set the value whether to use individual zoom value for all + // the open documents.. + Settings.EditorIndividualZoom = cbIndividualZoom.Checked; - // set the Notepad++ them settings.. - Settings.NotepadPlusPlusThemePath = tbNotepadPlusPlusThemePath.Text; + // set the value whether the zoom value of the document(s) + // should be saved into the database.. + Settings.EditorSaveZoom = cbSaveDocumentZoom.Checked; - Settings.UseNotepadPlusPlusTheme = cbUseNotepadPlusPlusTheme.Checked; + // set the type of the tab character symbol.. + if (rbTabSymbolArrow.Checked) + { + Settings.EditorTabSymbol = (int) TabDrawMode.LongArrow; + } + else + { + Settings.EditorTabSymbol = (int) TabDrawMode.Strikeout; + } - if (cmbNotepadPlusPlusTheme.SelectedIndex != -1 && cbUseNotepadPlusPlusTheme.Checked) - { - var file = cmbNotepadPlusPlusTheme.Items[cmbNotepadPlusPlusTheme.SelectedIndex].ToString(); - file += ".xml"; + // set the indent guide value.. + Settings.EditorIndentGuideOn = cbIndentGuideOn.Checked; + + #region SpellCheck + // set the spell checking properties.. + Settings.EditorUseSpellChecking = cbSpellCheckInUse.Checked; + Settings.EditorUseSpellCheckingNewFiles = cbSpellCheckInUseNewFiles.Checked; + Settings.EditorSpellCheckColor = btSpellCheckMarkColor.BackColor; + Settings.EditorHunspellAffixFile = tbHunspellAffixFile.Text; + Settings.EditorHunspellDictionaryFile = tbHunspellDictionary.Text; + Settings.EditorSpellCheckInactivity = (int)nudEditorSpellRecheckInactivity.Value; + Settings.EditorHunspellDictionaryPath = tbDictionaryPath.Text; + Settings.EditorUseSpellCheckingShellContext = cbSpellCheckInShellContext.Checked; + #endregion - Settings.NotepadPlusPlusThemeFile = file; + // set the editor font settings.. + Settings.EditorFontSize = (int) nudFontSize.Value; + Settings.EditorFontName = ((FontFamilyHolder) cmbFont.SelectedItem).ToString(); - file = Path.Combine(tbNotepadPlusPlusThemePath.Text, file); - if (File.Exists(file)) - { - Settings.UseNotepadPlusPlusTheme = cbUseNotepadPlusPlusTheme.Checked; - } - } - else // no deal here on the theme.. - { - Settings.UseNotepadPlusPlusTheme = false; - Settings.NotepadPlusPlusThemeFile = string.Empty; - } + // set the Notepad++ them settings.. + Settings.NotepadPlusPlusThemePath = tbNotepadPlusPlusThemePath.Text; - // set the AltGr capture bypass method if set.. - if (cmbSimulateKeyboard.SelectedIndex != -1 && cbSimulateKeyboard.Checked) - { - Settings.SimulateAltGrKey = true; - Settings.SimulateAltGrKeyIndex = cmbSimulateKeyboard.SelectedIndex; - } - else // no deal here on the AltGr simulation.. - { - Settings.SimulateAltGrKey = false; - Settings.SimulateAltGrKeyIndex = -1; - } + Settings.UseNotepadPlusPlusTheme = cbUseNotepadPlusPlusTheme.Checked; - // set the code indentation and editor tab width values.. - Settings.EditorUseCodeIndentation = cbUseCodeIndentation.Checked; - Settings.EditorTabWidth = (int)nudTabWidth.Value; + if (cmbNotepadPlusPlusTheme.SelectedIndex != -1 && cbUseNotepadPlusPlusTheme.Checked) + { + var file = cmbNotepadPlusPlusTheme.Items[cmbNotepadPlusPlusTheme.SelectedIndex].ToString(); + file += ".xml"; - // set the no-BOM detection value.. - Settings.DetectNoBom = cbDetectNoBomUnicode.Checked; + Settings.NotepadPlusPlusThemeFile = file; - // set the auto-save settings.. - Settings.ProgramAutoSave = cbUseAutoSave.Checked; - Settings.ProgramAutoSaveInterval = (int)nudAutoSaveInterval.Value; + file = Path.Combine(tbNotepadPlusPlusThemePath.Text, file); + if (File.Exists(file)) + { + Settings.UseNotepadPlusPlusTheme = cbUseNotepadPlusPlusTheme.Checked; + } + } + else // no deal here on the theme.. + { + Settings.UseNotepadPlusPlusTheme = false; + Settings.NotepadPlusPlusThemeFile = string.Empty; + } - // set the value whether to use auto-complete on the search box combo boxes.. - Settings.AutoCompleteEnabled = cbSearchUseAutoComplete.Checked; - FormSearchAndReplace.Instance.SetAutoCompleteState(Settings.AutoCompleteEnabled); // this setting doesn't require a application restart.. + // set the AltGr capture bypass method if set.. + if (cmbSimulateKeyboard.SelectedIndex != -1 && cbSimulateKeyboard.Checked) + { + Settings.SimulateAltGrKey = true; + Settings.SimulateAltGrKeyIndex = cmbSimulateKeyboard.SelectedIndex; + } + else // no deal here on the AltGr simulation.. + { + Settings.SimulateAltGrKey = false; + Settings.SimulateAltGrKeyIndex = -1; + } - // set the tread locale value.. - Settings.LocalizeThread = cbSetThreadLocale.Checked; + // set the code indentation and editor tab width values.. + Settings.EditorUseCodeIndentation = cbUseCodeIndentation.Checked; + Settings.EditorTabWidth = (int)nudTabWidth.Value; + + // set the no-BOM detection value.. + Settings.DetectNoBom = cbDetectNoBomUnicode.Checked; + + // set the auto-save settings.. + Settings.ProgramAutoSave = cbUseAutoSave.Checked; + Settings.ProgramAutoSaveInterval = (int)nudAutoSaveInterval.Value; + + // set the value whether to use auto-complete on the search box combo boxes.. + Settings.AutoCompleteEnabled = cbSearchUseAutoComplete.Checked; + FormSearchAndReplace.Instance.SetAutoCompleteState(Settings.AutoCompleteEnabled); // this setting doesn't require a application restart.. + + // set the tread locale value.. + Settings.LocalizeThread = cbSetThreadLocale.Checked; + + // set the value whether to check for a new application version upon startup.. + Settings.UpdateAutoCheck = cbUpdateAutoCheck.Checked; + + // set the Unicode detection skip values.. + Settings.SkipUnicodeDetectLe = cbNoUnicodeLE.Checked; + Settings.SkipUnicodeDetectBe = cbNoUnicodeBE.Checked; + Settings.SkipUtf32Le = cbNoUTF32LE.Checked; + Settings.SkipUtf32Be = cbNoUTF32BE.Checked; + + // the default encoding setting is deprecated and hidden.. + var encodings = Settings.EncodingsFromDataGrid(dgvEncodings); + + Settings.EncodingList = + Settings.EncodingStringFromDefinitionList(encodings); + + // custom spell checker library.. + Settings.EditorSpellUseCustomDictionary = cbUseCustomSpellCheckingLibrary.Checked; + Settings.EditorSpellCustomDictionaryDefinitionFile = tbSpellCheckingLibraryFile.Text; + + #region UrlStyle + Settings.HighlightUrls = cbHighlightUrls.Checked; + Settings.StartProcessOnUrlClick = cbStartProcessOnUrlClick.Checked; + Settings.UrlTextColor = btUrlTextColor.BackColor; + Settings.UrlIndicatorColor = btUrlIndicatorColor.BackColor; + Settings.UrlIndicatorStyle = (int)cmbUrlIndicatorStyle.SelectedItem; + Settings.UrlUseDwellToolTip = cbUseDwellToolTip.Checked; + Settings.UrlDwellToolTipTime = (int)nudDwellToolTipDelay.Value; + Settings.UrlDwellToolTipForegroundColor = btDwellToolTipForegroundColor.BackColor; + Settings.UrlDwellToolTipBackgroundColor = btDwellToolTipBackgroundColor.BackColor; + Settings.UrlMaxLengthBeforeEllipsis = (int)nudURLUseAutoEllipsis.Value; + Settings.UrlUseAutoEllipsis = cbURLUseAutoEllipsis.Checked; + #endregion - // set the value whether to check for a new application version upon startup.. - Settings.UpdateAutoCheck = cbUpdateAutoCheck.Checked; + #region TextSettings + Settings.TextUpperCaseComparison = cbCaseSensitive.Checked; + Settings.TextComparisonType = Convert.ToInt32(gbComparisonType.Tag); + #endregion - // set the Unicode detection skip values.. - Settings.SkipUnicodeDetectLe = cbNoUnicodeLE.Checked; - Settings.SkipUnicodeDetectBe = cbNoUnicodeBE.Checked; - Settings.SkipUtf32Le = cbNoUTF32LE.Checked; - Settings.SkipUtf32Be = cbNoUTF32BE.Checked; + #region DateTime + // set the date and time formats.. + Settings.DateFormat1 = tbDateTimeFormat1.Text; + Settings.DateFormat2 = tbDateTimeFormat2.Text; + Settings.DateFormat3 = tbDateTimeFormat3.Text; + Settings.DateFormat4 = tbDateTimeFormat4.Text; + Settings.DateFormat5 = tbDateTimeFormat5.Text; + Settings.DateFormat6 = tbDateTimeFormat6.Text; + Settings.DateFormatUseInvariantCulture = cbDateTimeUseInvarianCulture.Checked; + #endregion - // the default encoding setting is deprecated and hidden.. - var encodings = Settings.EncodingsFromDataGrid(dgvEncodings); - - Settings.EncodingList = - Settings.EncodingStringFromDefinitionList(encodings); - - // custom spell checker library.. - Settings.EditorSpellUseCustomDictionary = cbUseCustomSpellCheckingLibrary.Checked; - Settings.EditorSpellCustomDictionaryDefinitionFile = tbSpellCheckingLibraryFile.Text; - - #region UrlStyle - Settings.HighlightUrls = cbHighlightUrls.Checked; - Settings.StartProcessOnUrlClick = cbStartProcessOnUrlClick.Checked; - Settings.UrlTextColor = btUrlTextColor.BackColor; - Settings.UrlIndicatorColor = btUrlIndicatorColor.BackColor; - Settings.UrlIndicatorStyle = (int)cmbUrlIndicatorStyle.SelectedItem; - Settings.UrlUseDwellToolTip = cbUseDwellToolTip.Checked; - Settings.UrlDwellToolTipTime = (int)nudDwellToolTipDelay.Value; - Settings.UrlDwellToolTipForegroundColor = btDwellToolTipForegroundColor.BackColor; - Settings.UrlDwellToolTipBackgroundColor = btDwellToolTipBackgroundColor.BackColor; - Settings.UrlMaxLengthBeforeEllipsis = (int)nudURLUseAutoEllipsis.Value; - Settings.UrlUseAutoEllipsis = cbURLUseAutoEllipsis.Checked; - #endregion - - #region TextSettings - Settings.TextUpperCaseComparison = cbCaseSensitive.Checked; - Settings.TextComparisonType = Convert.ToInt32(gbComparisonType.Tag); - #endregion - - #region DateTime - // set the date and time formats.. - Settings.DateFormat1 = tbDateTimeFormat1.Text; - Settings.DateFormat2 = tbDateTimeFormat2.Text; - Settings.DateFormat3 = tbDateTimeFormat3.Text; - Settings.DateFormat4 = tbDateTimeFormat4.Text; - Settings.DateFormat5 = tbDateTimeFormat5.Text; - Settings.DateFormat6 = tbDateTimeFormat6.Text; - Settings.DateFormatUseInvariantCulture = cbDateTimeUseInvarianCulture.Checked; - #endregion - - #region EditorAdditional - // an experimental auto-complete for the C# programming language and the Scintilla control.. - Settings.UseCSharpAutoComplete = cbUseAutoCompleteCs.Checked; - #endregion - - Settings.Save(Program.SettingFileName); - } + #region EditorAdditional + // an experimental auto-complete for the C# programming language and the Scintilla control.. + Settings.UseCSharpAutoComplete = cbUseAutoCompleteCs.Checked; #endregion - /// - /// Gets or sets the character set combo box builder. - /// - private CharacterSetComboBuilder CharacterSetComboBuilder { get; } + Settings.Save(Program.SettingFileName); + } + #endregion - // this event is fired when the encoding is changed from the corresponding combo box.. - private void CharacterSetComboBuilder_EncodingSelected(object sender, OnEncodingSelectedEventArgs e) - { - // save the changed value.. - } + /// + /// Gets or sets the character set combo box builder. + /// + private CharacterSetComboBuilder CharacterSetComboBuilder { get; } + + // this event is fired when the encoding is changed from the corresponding combo box.. + private void CharacterSetComboBuilder_EncodingSelected(object sender, OnEncodingSelectedEventArgs e) + { + // save the changed value.. + } - /// - /// Gets or sets the settings class instance containing the settings for the software. - /// - public static Settings Settings { get; set; } + /// + /// Gets or sets the settings class instance containing the settings for the software. + /// + public static Settings Settings { get; set; } - /// - /// Gets the Notepad++ style definition file if assigned in the settings. - /// - public static string NotepadPlusPlusStyleFile + /// + /// Gets the Notepad++ style definition file if assigned in the settings. + /// + public static string NotepadPlusPlusStyleFile + { + get { - get + if (Settings != null) { - if (Settings != null) + var file = Path.Combine(Settings.NotepadPlusPlusThemePath, Settings.NotepadPlusPlusThemeFile); + if (File.Exists(file)) { - var file = Path.Combine(Settings.NotepadPlusPlusThemePath, Settings.NotepadPlusPlusThemeFile); - if (File.Exists(file)) - { - return file; - } - - return string.Empty; + return file; } return string.Empty; } + + return string.Empty; } + } - /// - /// Sets the editor settings for a given . - /// - /// The scintilla which settings to set. - public static void SetEditorSettings(Scintilla scintilla) - { - // set the size of the white space dot.. - scintilla.WhitespaceSize = Settings.EditorWhiteSpaceSize; + /// + /// Sets the editor settings for a given . + /// + /// The scintilla which settings to set. + public static void SetEditorSettings(Scintilla scintilla) + { + // set the size of the white space dot.. + scintilla.WhitespaceSize = Settings.EditorWhiteSpaceSize; - // set the value whether to use tabs in the editor (tabulator characters).. - scintilla.UseTabs = Settings.EditorUseTabs; + // set the value whether to use tabs in the editor (tabulator characters).. + scintilla.UseTabs = Settings.EditorUseTabs; - // set the type of the tab character symbol.. - scintilla.TabDrawMode = (TabDrawMode) Settings.EditorTabSymbol; + // set the type of the tab character symbol.. + scintilla.TabDrawMode = (TabDrawMode) Settings.EditorTabSymbol; - // set the value whether to show the indent guides.. - scintilla.IndentationGuides = Settings.EditorIndentGuideOn ? IndentView.Real : IndentView.None; + // set the value whether to show the indent guides.. + scintilla.IndentationGuides = Settings.EditorIndentGuideOn ? IndentView.Real : IndentView.None; + } + + private void FormSettings_FormClosing(object sender, FormClosingEventArgs e) + { + using (CharacterSetComboBuilder) + { + // unsubscribe the encoding selected event.. + CharacterSetComboBuilder.EncodingSelected -= CharacterSetComboBuilder_EncodingSelected; } - private void FormSettings_FormClosing(object sender, FormClosingEventArgs e) + // dispose this, otherwise the application dead-locks upon closing.. + if (scintillaUrlDetect != null) { - using (CharacterSetComboBuilder) + using (scintillaUrlDetect) { - // unsubscribe the encoding selected event.. - CharacterSetComboBuilder.EncodingSelected -= CharacterSetComboBuilder_EncodingSelected; - } - - // dispose this, otherwise the application dead-locks upon closing.. - if (scintillaUrlDetect != null) - { - using (scintillaUrlDetect) - { - scintillaUrlDetect = null; - } + scintillaUrlDetect = null; } } + } - private void FormSettings_Shown(object sender, EventArgs e) - { - // load the settings visualized on the form.. - LoadSettings(); + private void FormSettings_Shown(object sender, EventArgs e) + { + // load the settings visualized on the form.. + LoadSettings(); - // ReSharper disable once CoVariantArrayConversion - cmbInstalledDictionaries.Items.AddRange(HunspellDictionaryCrawler - .CrawlDirectory(Settings.EditorHunspellDictionaryPath).OrderBy(f => f.ToString().ToLowerInvariant()) - .ToArray()); + // ReSharper disable once CoVariantArrayConversion + cmbInstalledDictionaries.Items.AddRange(HunspellDictionaryCrawler + .CrawlDirectory(Settings.EditorHunspellDictionaryPath).OrderBy(f => f.ToString().ToLowerInvariant()) + .ToArray()); - // set the states of the tool strip with the encoding settings grid.. - ValidateEncodingToolStrip(); + // set the states of the tool strip with the encoding settings grid.. + ValidateEncodingToolStrip(); - // re-style the Scintilla URL styling text box with loaded settings.. - ReStyleUrlScintillaBox(); - } + // re-style the Scintilla URL styling text box with loaded settings.. + ReStyleUrlScintillaBox(); + } - private void btDefaultEncodings_Click(object sender, EventArgs e) - { - // select the encoding based on which button the user clicked.. - CharacterSetComboBuilder.SelectItemByEncoding(sender.Equals(btUTF8) ? Encoding.UTF8 : Encoding.Default, false); - } + private void btDefaultEncodings_Click(object sender, EventArgs e) + { + // select the encoding based on which button the user clicked.. + CharacterSetComboBuilder.SelectItemByEncoding(sender.Equals(btUTF8) ? Encoding.UTF8 : Encoding.Default, false); + } - private void cbDocumentContentHistory_CheckedChanged(object sender, EventArgs e) - { - CheckBox checkBox = (CheckBox)sender; - nudDocumentContentHistory.Enabled = checkBox.Checked; - } + private void cbDocumentContentHistory_CheckedChanged(object sender, EventArgs e) + { + CheckBox checkBox = (CheckBox)sender; + nudDocumentContentHistory.Enabled = checkBox.Checked; + } - /// - /// Creates the default plug-in directory for the software. - /// - /// The location of the folder. - public static string CreateDefaultPluginDirectory() + /// + /// Creates the default plug-in directory for the software. + /// + /// The location of the folder. + public static string CreateDefaultPluginDirectory() + { + // create a folder for plug-ins if it doesn't exist already.. + if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins"))) { - // create a folder for plug-ins if it doesn't exist already.. - if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins"))) + try { - try - { - // create the folder.. - Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins")); + // create the folder.. + Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins")); - // save the folder in the settings.. - Settings.PluginFolder = Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins"); - } - catch (Exception ex) // a failure so do log it.. - { - ExceptionLogger.LogError(ex); - return string.Empty; - } + // save the folder in the settings.. + Settings.PluginFolder = Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins"); } - return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins"); - } - - /// - /// Creates the default custom dictionary install folder for the software. - /// - /// The location of the folder. - public static string CreateDefaultCustomDictionaryDirectory() - { - // create a folder for custom dictionaries if it doesn't exist already.. - if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries"))) + catch (Exception ex) // a failure so do log it.. { - try - { - // create the folder.. - Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries")); - - // save the folder in the settings.. - Settings.EditorSpellCustomDictionaryInstallPath = Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries"); - } - catch (Exception ex) // a failure so do log it.. - { - ExceptionLogger.LogError(ex); - return string.Empty; - } + ExceptionLogger.LogError(ex); + return string.Empty; } - return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries"); } + return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "Plugins"); + } - private void btCommonSelectFolder_Click(object sender, EventArgs e) + /// + /// Creates the default custom dictionary install folder for the software. + /// + /// The location of the folder. + public static string CreateDefaultCustomDictionaryDirectory() + { + // create a folder for custom dictionaries if it doesn't exist already.. + if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries"))) { - var dialog = new VistaFolderBrowserDialog {UseDescriptionForTitle = true}; - - var button = (Button) sender; - TextBox textBox = default; - if (button.Tag.ToString() == "tbPluginFolder") - { - dialog.Description = DBLangEngine.GetMessage("msgDirectoryDialogPlugin", - "Select the plugin folder|A message describing that the user should select a plugin folder from a browse folder dialog"); - textBox = tbPluginFolder; - } - else if (button.Tag.ToString() == "tbDictionaryPath") + try { - dialog.Description = DBLangEngine.GetMessage("msgDirectoryDialogDictionary", - "Select the dictionary folder|A message describing that the user should select a folder where the Hunspell dictionaries reside"); - textBox = tbDictionaryPath; + // create the folder.. + Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries")); + + // save the folder in the settings.. + Settings.EditorSpellCustomDictionaryInstallPath = Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries"); } - else if (button.Tag.ToString() == "tbNotepadPlusPlusThemePath") + catch (Exception ex) // a failure so do log it.. { - dialog.Description = DBLangEngine.GetMessage("msgDirectoryDialogNotepadPlusPlusThemes", - "Select a theme folder|A message describing that the user should select a folder where the Notepad++ theme files"); - textBox = tbNotepadPlusPlusThemePath; + ExceptionLogger.LogError(ex); + return string.Empty; } + } + return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "CustomDictionaries"); + } - if (textBox != null) - { - if (Directory.Exists(tbPluginFolder.Text)) - { - dialog.SelectedPath = textBox.Text; - } + private void btCommonSelectFolder_Click(object sender, EventArgs e) + { + var dialog = new VistaFolderBrowserDialog {UseDescriptionForTitle = true, }; - if (dialog.ShowDialog() == DialogResult.OK) - { - textBox.Text = dialog.SelectedPath; - } - } + var button = (Button) sender; + TextBox textBox = default; + if (button.Tag.ToString() == "tbPluginFolder") + { + dialog.Description = DBLangEngine.GetMessage("msgDirectoryDialogPlugin", + "Select the plugin folder|A message describing that the user should select a plugin folder from a browse folder dialog"); + textBox = tbPluginFolder; } - - private void pbDefaultFolder_Click(object sender, EventArgs e) + else if (button.Tag.ToString() == "tbDictionaryPath") { - tbPluginFolder.Text = CreateDefaultPluginDirectory(); + dialog.Description = DBLangEngine.GetMessage("msgDirectoryDialogDictionary", + "Select the dictionary folder|A message describing that the user should select a folder where the Hunspell dictionaries reside"); + textBox = tbDictionaryPath; } - - private void tbPluginFolder_TextChanged(object sender, EventArgs e) + else if (button.Tag.ToString() == "tbNotepadPlusPlusThemePath") { - btOK.Enabled = Directory.Exists(tbPluginFolder.Text); + dialog.Description = DBLangEngine.GetMessage("msgDirectoryDialogNotepadPlusPlusThemes", + "Select a theme folder|A message describing that the user should select a folder where the Notepad++ theme files"); + textBox = tbNotepadPlusPlusThemePath; } - private void lbPluginFolder_Click(object sender, EventArgs e) + if (textBox != null) { if (Directory.Exists(tbPluginFolder.Text)) { - WindowsExplorerInteraction.OpenFolderInExplorer(tbPluginFolder.Text); + dialog.SelectedPath = textBox.Text; } - } - private void ColorButton_Click(object sender, EventArgs e) - { - if (cdColors.ShowDialog() == DialogResult.OK) + if (dialog.ShowDialog() == DialogResult.OK) { - Button button = (Button) sender; - button.BackColor = cdColors.Color; - - if (button.Equals(btUrlTextColor) || button.Equals(btUrlIndicatorColor) || - button.Equals(btDwellToolTipForegroundColor) || button.Equals(btDwellToolTipBackgroundColor)) - { - ReStyleUrlScintillaBox(); // the button is one of the color buttons for the URL detection library.. - } + textBox.Text = dialog.SelectedPath; } } + } - private void BtDefaults_Click(object sender, EventArgs e) + private void pbDefaultFolder_Click(object sender, EventArgs e) + { + tbPluginFolder.Text = CreateDefaultPluginDirectory(); + } + + private void tbPluginFolder_TextChanged(object sender, EventArgs e) + { + btOK.Enabled = Directory.Exists(tbPluginFolder.Text); + } + + private void lbPluginFolder_Click(object sender, EventArgs e) + { + if (Directory.Exists(tbPluginFolder.Text)) { - btSmartHighlightColor.BackColor = Color.FromArgb(0, 255, 0); - btMarkStyle1Color.BackColor = Color.FromArgb(0, 255, 255); - btMarkStyle2Color.BackColor = Color.FromArgb(255, 128, 0); - btMarkStyle3Color.BackColor = Color.FromArgb(255, 255, 0); - btMarkStyle4Color.BackColor = Color.FromArgb(128, 0, 255); - btMarkStyle5Color.BackColor = Color.FromArgb(0, 128, 0); - btCurrentLineBackgroundColor.BackColor = Color.FromArgb(232, 232, 255); + WindowsExplorerInteraction.OpenFolderInExplorer(tbPluginFolder.Text); } + } - /// - /// Lists the found Notepad++ themes to the selection combo box. - /// - private void ListNotepadPlusPLusThemes() + private void ColorButton_Click(object sender, EventArgs e) + { + if (cdColors.ShowDialog() == DialogResult.OK) { - try - { - cmbNotepadPlusPlusTheme.Items.Clear(); - if (Directory.Exists(tbNotepadPlusPlusThemePath.Text)) - { - var files = Directory.GetFiles(tbNotepadPlusPlusThemePath.Text, "*.xml"); - foreach (var file in files) - { - cmbNotepadPlusPlusTheme.Items.Add(Path.GetFileNameWithoutExtension(file)); - } - } - } - catch (Exception ex) + Button button = (Button) sender; + button.BackColor = cdColors.Color; + + if (button.Equals(btUrlTextColor) || button.Equals(btUrlIndicatorColor) || + button.Equals(btDwellToolTipForegroundColor) || button.Equals(btDwellToolTipBackgroundColor)) { - // log the exception.. - ExceptionLogger.LogError(ex); + ReStyleUrlScintillaBox(); // the button is one of the color buttons for the URL detection library.. } } + } - private void BtHunspellDictionary_Click(object sender, EventArgs e) - { - odDictionaryFile.InitialDirectory = Settings.FileLocationOpenDictionary; - - odDictionaryFile.Title = DBLangEngine.GetMessage("msgDialogSelectDicFile", - "Select a dictionary file|A title for an open file dialog to indicate user that the user is selecting a dictionary file for the spell checking"); + private void BtDefaults_Click(object sender, EventArgs e) + { + btSmartHighlightColor.BackColor = Color.FromArgb(0, 255, 0); + btMarkStyle1Color.BackColor = Color.FromArgb(0, 255, 255); + btMarkStyle2Color.BackColor = Color.FromArgb(255, 128, 0); + btMarkStyle3Color.BackColor = Color.FromArgb(255, 255, 0); + btMarkStyle4Color.BackColor = Color.FromArgb(128, 0, 255); + btMarkStyle5Color.BackColor = Color.FromArgb(0, 128, 0); + btCurrentLineBackgroundColor.BackColor = Color.FromArgb(232, 232, 255); + } - if (odDictionaryFile.ShowDialog() == DialogResult.OK) + /// + /// Lists the found Notepad++ themes to the selection combo box. + /// + private void ListNotepadPlusPLusThemes() + { + try + { + cmbNotepadPlusPlusTheme.Items.Clear(); + if (Directory.Exists(tbNotepadPlusPlusThemePath.Text)) { - Settings.FileLocationOpenDictionary = Path.GetDirectoryName(odDictionaryFile.FileName); - tbHunspellDictionary.Text = odDictionaryFile.FileName; + var files = Directory.GetFiles(tbNotepadPlusPlusThemePath.Text, "*.xml"); + foreach (var file in files) + { + cmbNotepadPlusPlusTheme.Items.Add(Path.GetFileNameWithoutExtension(file)); + } } } - - private void BtHunspellAffixFile_Click(object sender, EventArgs e) + catch (Exception ex) { - odAffixFile.InitialDirectory = Settings.FileLocationOpenAffix; + // log the exception.. + ExceptionLogger.LogError(ex); + } + } - odAffixFile.Title = DBLangEngine.GetMessage("msgDialogSelectAffixFile", - "Select an affix file|A title for an open file dialog to indicate user that the user is selecting a Hunspell affix file for the spell checking"); + private void BtHunspellDictionary_Click(object sender, EventArgs e) + { + odDictionaryFile.InitialDirectory = Settings.FileLocationOpenDictionary; - if (odAffixFile.ShowDialog() == DialogResult.OK) - { - Settings.FileLocationOpenAffix = Path.GetDirectoryName(odAffixFile.FileName); - tbHunspellAffixFile.Text = odAffixFile.FileName; - } + odDictionaryFile.Title = DBLangEngine.GetMessage("msgDialogSelectDicFile", + "Select a dictionary file|A title for an open file dialog to indicate user that the user is selecting a dictionary file for the spell checking"); + + if (odDictionaryFile.ShowDialog() == DialogResult.OK) + { + Settings.FileLocationOpenDictionary = Path.GetDirectoryName(odDictionaryFile.FileName); + tbHunspellDictionary.Text = odDictionaryFile.FileName; } + } + + private void BtHunspellAffixFile_Click(object sender, EventArgs e) + { + odAffixFile.InitialDirectory = Settings.FileLocationOpenAffix; + + odAffixFile.Title = DBLangEngine.GetMessage("msgDialogSelectAffixFile", + "Select an affix file|A title for an open file dialog to indicate user that the user is selecting a Hunspell affix file for the spell checking"); - private void CbSpellCheckInUse_Click(object sender, EventArgs e) + if (odAffixFile.ShowDialog() == DialogResult.OK) { - if (((!File.Exists(tbHunspellDictionary.Text) || !File.Exists(tbHunspellAffixFile.Text)) && !cbUseCustomSpellCheckingLibrary.Checked) || - (!File.Exists(tbSpellCheckingLibraryFile.Text) && cbUseCustomSpellCheckingLibrary.Checked)) - { - if (sender.Equals(cbSpellCheckInUse)) - { - cbSpellCheckInUse.Checked = false; - } - else if (sender.Equals(cbSpellCheckInUseNewFiles)) - { - cbSpellCheckInUseNewFiles.Checked = false; - } - } + Settings.FileLocationOpenAffix = Path.GetDirectoryName(odAffixFile.FileName); + tbHunspellAffixFile.Text = odAffixFile.FileName; } + } - private void CmbFont_SelectedIndexChanged(object sender, EventArgs e) + private void CbSpellCheckInUse_Click(object sender, EventArgs e) + { + if (((!File.Exists(tbHunspellDictionary.Text) || !File.Exists(tbHunspellAffixFile.Text)) && !cbUseCustomSpellCheckingLibrary.Checked) || + (!File.Exists(tbSpellCheckingLibraryFile.Text) && cbUseCustomSpellCheckingLibrary.Checked)) { - if (cmbFont.SelectedItem != null) + if (sender.Equals(cbSpellCheckInUse)) { - FontFamilyHolder holder = (FontFamilyHolder) cmbFont.SelectedItem; - scintilla.Styles[Style.Default].Font = holder.ToString(); - scintilla.Styles[Style.Default].Size = (int) nudFontSize.Value; - btOK.Enabled = true; + cbSpellCheckInUse.Checked = false; } - else + else if (sender.Equals(cbSpellCheckInUseNewFiles)) { - btOK.Enabled = false; + cbSpellCheckInUseNewFiles.Checked = false; } } + } - private void CmbInstalledDictionaries_SelectedIndexChanged(object sender, EventArgs e) + private void CmbFont_SelectedIndexChanged(object sender, EventArgs e) + { + if (cmbFont.SelectedItem != null) { - var comboBox = (ComboBox) sender; - if (comboBox.SelectedIndex != -1) - { - HunspellData data = (HunspellData) comboBox.Items[comboBox.SelectedIndex]; - tbHunspellDictionary.Text = data.DictionaryFile; - tbHunspellAffixFile.Text = data.AffixFile; - } + FontFamilyHolder holder = (FontFamilyHolder) cmbFont.SelectedItem; + scintilla.Styles[Style.Default].Font = holder.ToString(); + scintilla.Styles[Style.Default].Size = (int) nudFontSize.Value; + btOK.Enabled = true; } + else + { + btOK.Enabled = false; + } + } - private void CmbNotepadPlusPlusTheme_SelectedIndexChanged(object sender, EventArgs e) + private void CmbInstalledDictionaries_SelectedIndexChanged(object sender, EventArgs e) + { + var comboBox = (ComboBox) sender; + if (comboBox.SelectedIndex != -1) { - if (cmbNotepadPlusPlusTheme.SelectedIndex != -1 && cbUseNotepadPlusPlusTheme.Checked) - { - var file = cmbNotepadPlusPlusTheme.Items[cmbNotepadPlusPlusTheme.SelectedIndex].ToString(); - file += ".xml"; + HunspellData data = (HunspellData) comboBox.Items[comboBox.SelectedIndex]; + tbHunspellDictionary.Text = data.DictionaryFile; + tbHunspellAffixFile.Text = data.AffixFile; + } + } - file = Path.Combine(tbNotepadPlusPlusThemePath.Text, file); - if (File.Exists(file)) - { - var colors = MarkColorsHelper.FromFile(file); - btSmartHighlightColor.BackColor = colors.SmartHighlight; - btMarkStyle1Color.BackColor = colors.Mark1Color; - btMarkStyle2Color.BackColor = colors.Mark2Color; - btMarkStyle3Color.BackColor = colors.Mark3Color; - btMarkStyle4Color.BackColor = colors.Mark4Color; - btMarkStyle5Color.BackColor = colors.Mark5Color; - btCurrentLineBackgroundColor.BackColor = colors.CurrentLineBackground; - } + private void CmbNotepadPlusPlusTheme_SelectedIndexChanged(object sender, EventArgs e) + { + if (cmbNotepadPlusPlusTheme.SelectedIndex != -1 && cbUseNotepadPlusPlusTheme.Checked) + { + var file = cmbNotepadPlusPlusTheme.Items[cmbNotepadPlusPlusTheme.SelectedIndex].ToString(); + file += ".xml"; + + file = Path.Combine(tbNotepadPlusPlusThemePath.Text, file); + if (File.Exists(file)) + { + var colors = MarkColorsHelper.FromFile(file); + btSmartHighlightColor.BackColor = colors.SmartHighlight; + btMarkStyle1Color.BackColor = colors.Mark1Color; + btMarkStyle2Color.BackColor = colors.Mark2Color; + btMarkStyle3Color.BackColor = colors.Mark3Color; + btMarkStyle4Color.BackColor = colors.Mark4Color; + btMarkStyle5Color.BackColor = colors.Mark5Color; + btCurrentLineBackgroundColor.BackColor = colors.CurrentLineBackground; } } + } - private string lastFocusedDateTime = string.Empty; + private string lastFocusedDateTime = string.Empty; - private void TbDateTimeFormat1_TextChanged(object sender, EventArgs e) + private void TbDateTimeFormat1_TextChanged(object sender, EventArgs e) + { + TextBox textBox = null; + try { - TextBox textBox = null; - try + if (sender is TextBox box) { - if (sender is TextBox box) - { - textBox = box; - lastFocusedDateTime = textBox.Text; - - lbDateTimeFormatDescriptionValue.Text = DateTime.Now.ToString(lastFocusedDateTime, - // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. - cbDateTimeUseInvarianCulture.Checked - ? CultureInfo.InvariantCulture - : CultureInfo.InstalledUICulture); - } - else if (sender is CheckBox) - { - lbDateTimeFormatDescriptionValue.Text = DateTime.Now.ToString(lastFocusedDateTime, - // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. - cbDateTimeUseInvarianCulture.Checked - ? CultureInfo.InvariantCulture - : CultureInfo.InstalledUICulture); - } - - if (textBox != null) - { - textBox.BackColor = SystemColors.Window; - } + textBox = box; + lastFocusedDateTime = textBox.Text; + + lbDateTimeFormatDescriptionValue.Text = DateTime.Now.ToString(lastFocusedDateTime, + // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. + cbDateTimeUseInvarianCulture.Checked + ? CultureInfo.InvariantCulture + : CultureInfo.InstalledUICulture); } - catch (Exception ex) + else if (sender is CheckBox) { - if (textBox != null) - { - textBox.BackColor = Color.Red; - } - - lbDateTimeFormatDescriptionValue.Text = DBLangEngine.GetMessage( - "msgDateTimeInvalidFormat", - "Invalid date and/or time format|The user has issued an non-valid formatted date and/or time formatting string."); - - ExceptionLogger.LogError(ex); + lbDateTimeFormatDescriptionValue.Text = DateTime.Now.ToString(lastFocusedDateTime, + // we need to ensure that an overridden thread locale will not affect the non-invariant culture setting.. + cbDateTimeUseInvarianCulture.Checked + ? CultureInfo.InvariantCulture + : CultureInfo.InstalledUICulture); } - } - // try to open a web browser for further instructions of how to specify a time and/or date.. - private void LbDateTimeInstructionLink_Click(object sender, EventArgs e) - { - try + if (textBox != null) { - Process.Start( - "https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings"); + textBox.BackColor = SystemColors.Window; } - catch (Exception ex) + } + catch (Exception ex) + { + if (textBox != null) { - // log the exception.. - ExceptionLogger.LogError(ex); + textBox.BackColor = Color.Red; } + + lbDateTimeFormatDescriptionValue.Text = DBLangEngine.GetMessage( + "msgDateTimeInvalidFormat", + "Invalid date and/or time format|The user has issued an non-valid formatted date and/or time formatting string."); + + ExceptionLogger.LogError(ex); } + } - // the user wants to reset the date and/or time format strings to default values.. - private void BtDateTimeDefaults_Click(object sender, EventArgs e) + // try to open a web browser for further instructions of how to specify a time and/or date.. + private void LbDateTimeInstructionLink_Click(object sender, EventArgs e) + { + try { - tbDateTimeFormat1.Text = @"yyyy'/'MM'/'dd"; // default to american.. - tbDateTimeFormat2.Text = @"dd'.'MM'.'yyyy"; // default to european.. - tbDateTimeFormat3.Text = @"yyyy'/'MM'/'dd hh'.'mm tt"; // default to american.. - tbDateTimeFormat4.Text = @"dd'.'MM'.'yyyy HH':'mm':'ss"; // default to european.. - tbDateTimeFormat5.Text = @"hh'.'mm tt"; // default to american.. - tbDateTimeFormat6.Text = @"HH':'mm':'ss"; // default to european.. + Process.Start( + "https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings"); } - - // the setting of the Unicode detection has changed.. - private void CbDetectNoBomUnicode_CheckedChanged(object sender, EventArgs e) + catch (Exception ex) { - gpSkipEncodings.Enabled = cbDetectNoBomUnicode.Checked; + // log the exception.. + ExceptionLogger.LogError(ex); } + } + + // the user wants to reset the date and/or time format strings to default values.. + private void BtDateTimeDefaults_Click(object sender, EventArgs e) + { + tbDateTimeFormat1.Text = @"yyyy'/'MM'/'dd"; // default to american.. + tbDateTimeFormat2.Text = @"dd'.'MM'.'yyyy"; // default to european.. + tbDateTimeFormat3.Text = @"yyyy'/'MM'/'dd hh'.'mm tt"; // default to american.. + tbDateTimeFormat4.Text = @"dd'.'MM'.'yyyy HH':'mm':'ss"; // default to european.. + tbDateTimeFormat5.Text = @"hh'.'mm tt"; // default to american.. + tbDateTimeFormat6.Text = @"HH':'mm':'ss"; // default to european.. + } + + // the setting of the Unicode detection has changed.. + private void CbDetectNoBomUnicode_CheckedChanged(object sender, EventArgs e) + { + gpSkipEncodings.Enabled = cbDetectNoBomUnicode.Checked; + } - /// - /// Validates the encoding tool strip buttons enabled states. - /// - private void ValidateEncodingToolStrip() + /// + /// Validates the encoding tool strip buttons enabled states. + /// + private void ValidateEncodingToolStrip() + { + // if there is no selection and a selection is possible, select something.. + if (dgvEncodings.RowCount > 0 && dgvEncodings.CurrentRow == null) { - // if there is no selection and a selection is possible, select something.. - if (dgvEncodings.RowCount > 0 && dgvEncodings.CurrentRow == null) - { - dgvEncodings.Rows[0].Cells[colEncodingName.Index].Selected = true; - } + dgvEncodings.Rows[0].Cells[colEncodingName.Index].Selected = true; + } - // set the states of the buttons.. - tsbEncodingMoveUp.Enabled = - dgvEncodings.CurrentRow != null && dgvEncodings.CurrentRow.Index > 0; + // set the states of the buttons.. + tsbEncodingMoveUp.Enabled = + dgvEncodings.CurrentRow != null && dgvEncodings.CurrentRow.Index > 0; - tsbEncodingMoveDown.Enabled = - dgvEncodings.CurrentRow != null && dgvEncodings.CurrentRow.Index + 1 < dgvEncodings.RowCount; + tsbEncodingMoveDown.Enabled = + dgvEncodings.CurrentRow != null && dgvEncodings.CurrentRow.Index + 1 < dgvEncodings.RowCount; - tsbDeleteEncoding.Enabled = dgvEncodings.CurrentRow != null; - // END: set the states of the buttons.. + tsbDeleteEncoding.Enabled = dgvEncodings.CurrentRow != null; + // END: set the states of the buttons.. - // validate the input on the data grid view.. - ValidateUserEncodingsSettings(); - } + // validate the input on the data grid view.. + ValidateUserEncodingsSettings(); + } - // handle the tools strip button clicks with the encoding grid.. - private void TsbEncodingList_Click(object sender, EventArgs e) + // handle the tools strip button clicks with the encoding grid.. + private void TsbEncodingList_Click(object sender, EventArgs e) + { + if (sender.Equals(tsbAddEncoding)) { - if (sender.Equals(tsbAddEncoding)) + Encoding encoding; + if ((encoding = FormDialogQueryEncoding.Execute(out bool unicodeBom, + out bool unicodeFailInvalidCharacters)) != null) { - Encoding encoding; - if ((encoding = FormDialogQueryEncoding.Execute(out bool unicodeBom, - out bool unicodeFailInvalidCharacters)) != null) - { - dgvEncodings.Rows.Add(encoding, encoding.EncodingName, unicodeBom, - unicodeFailInvalidCharacters); - } + dgvEncodings.Rows.Add(encoding, encoding.EncodingName, unicodeBom, + unicodeFailInvalidCharacters); } - else if (sender.Equals(tsbDeleteEncoding)) + } + else if (sender.Equals(tsbDeleteEncoding)) + { + if (dgvEncodings.CurrentRow != null) { - if (dgvEncodings.CurrentRow != null) - { - dgvEncodings.Rows.Remove(dgvEncodings.CurrentRow); - } + dgvEncodings.Rows.Remove(dgvEncodings.CurrentRow); } - else if (sender.Equals(tsbDefault)) - { - // the default encoding setting is deprecated and hidden.. - var encodings = Settings.GetEncodingList(Settings.DefaultEncodingList); + } + else if (sender.Equals(tsbDefault)) + { + // the default encoding setting is deprecated and hidden.. + var encodings = Settings.GetEncodingList(Settings.DefaultEncodingList); - dgvEncodings.Rows.Clear(); + dgvEncodings.Rows.Clear(); - foreach (var encoding in encodings) - { - dgvEncodings.Rows.Add(encoding.encoding, encoding.encodingName, encoding.unicodeBOM, - encoding.unicodeFailOnInvalidChar); - } + foreach (var encoding in encodings) + { + dgvEncodings.Rows.Add(encoding.encoding, encoding.encodingName, encoding.unicodeBOM, + encoding.unicodeFailOnInvalidChar); } - else if (sender.Equals(tsbEncodingMoveUp) || sender.Equals(tsbEncodingMoveDown)) + } + else if (sender.Equals(tsbEncodingMoveUp) || sender.Equals(tsbEncodingMoveDown)) + { + if (dgvEncodings.CurrentRow != null) { - if (dgvEncodings.CurrentRow != null) + if (dgvEncodings.CurrentRow.Index > 0 && sender.Equals(tsbEncodingMoveUp) || + dgvEncodings.CurrentRow.Index + 1 < dgvEncodings.RowCount && sender.Equals(tsbEncodingMoveDown) + ) { - if (dgvEncodings.CurrentRow.Index > 0 && sender.Equals(tsbEncodingMoveUp) || - dgvEncodings.CurrentRow.Index + 1 < dgvEncodings.RowCount && sender.Equals(tsbEncodingMoveDown) - ) - { - int index1 = dgvEncodings.CurrentRow.Index + (sender.Equals(tsbEncodingMoveUp) ? -1 : 1); - int index2 = dgvEncodings.CurrentRow.Index; + int index1 = dgvEncodings.CurrentRow.Index + (sender.Equals(tsbEncodingMoveUp) ? -1 : 1); + int index2 = dgvEncodings.CurrentRow.Index; - int colIndex = dgvEncodings.CurrentCell?.ColumnIndex ?? 1; + int colIndex = dgvEncodings.CurrentCell?.ColumnIndex ?? 1; - foreach (DataGridViewColumn column in dgvEncodings.Columns) - { - object tmp = dgvEncodings.Rows[index1].Cells[column.Index].Value; - dgvEncodings.Rows[index1].Cells[column.Index].Value = - dgvEncodings.Rows[index2].Cells[column.Index].Value; - dgvEncodings.Rows[index2].Cells[column.Index].Value = tmp; - } + foreach (DataGridViewColumn column in dgvEncodings.Columns) + { + object tmp = dgvEncodings.Rows[index1].Cells[column.Index].Value; + dgvEncodings.Rows[index1].Cells[column.Index].Value = + dgvEncodings.Rows[index2].Cells[column.Index].Value; + dgvEncodings.Rows[index2].Cells[column.Index].Value = tmp; + } - dgvEncodings.ClearSelection(); + dgvEncodings.ClearSelection(); - dgvEncodings.Rows[index1].Cells[colIndex].Selected = true; - } + dgvEncodings.Rows[index1].Cells[colIndex].Selected = true; } } - - // set the states of the tool strip with the encoding settings grid.. - ValidateEncodingToolStrip(); - } - - private void DgvEncodings_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) - { - // set the states of the tool strip with the encoding settings grid.. - ValidateEncodingToolStrip(); - } - - private void DgvEncodings_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) - { - // set the states of the tool strip with the encoding settings grid.. - ValidateEncodingToolStrip(); } - /// - /// Validates the user given encoding settings. - /// - private void ValidateUserEncodingsSettings() - { - // first assume no error.. - tbAlertEncoding.Text = string.Empty; - pbAlertEncoding.Image = null; - btOK.Enabled = true; - - // check the row count --> zero is the first error.. - if (dgvEncodings.RowCount == 0) - { - pbAlertEncoding.Image = SystemIcons.Warning.ToBitmap(); - tbAlertEncoding.Text = DBLangEngine.GetMessage("msgEncodingRequireOne", - "At least one configured encoding is required.|A message in a label indicating to the user that at least one encoding must be selected from the settings."); - btOK.Enabled = false; - return; // no need to continue as the input errors are not cumulative.. - } + // set the states of the tool strip with the encoding settings grid.. + ValidateEncodingToolStrip(); + } - // create a list of unicode encodings as code pages.. - List unicodeCodePages = new List(new[] {65001, 1200, 1201, 12000, 12001}); + private void DgvEncodings_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) + { + // set the states of the tool strip with the encoding settings grid.. + ValidateEncodingToolStrip(); + } - // create a variable to detect the second error of the encodings (all Unicode and all throwing exceptions).. - bool allUnicodeThrowException = true; + private void DgvEncodings_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) + { + // set the states of the tool strip with the encoding settings grid.. + ValidateEncodingToolStrip(); + } - // loop through the rows in the data grid view.. - foreach (DataGridViewRow row in dgvEncodings.Rows) - { - // get the encoding.. - var encoding = (Encoding) row.Cells[_colEncoding.Index].Value; + /// + /// Validates the user given encoding settings. + /// + private void ValidateUserEncodingsSettings() + { + // first assume no error.. + tbAlertEncoding.Text = string.Empty; + pbAlertEncoding.Image = null; + btOK.Enabled = true; - // get the throw an exception upon invalid bytes value.. - var throwInvalidBytes = (bool) row.Cells[colUnicodeFailInvalidChar.Index].Value; + // check the row count --> zero is the first error.. + if (dgvEncodings.RowCount == 0) + { + pbAlertEncoding.Image = SystemIcons.Warning.ToBitmap(); + tbAlertEncoding.Text = DBLangEngine.GetMessage("msgEncodingRequireOne", + "At least one configured encoding is required.|A message in a label indicating to the user that at least one encoding must be selected from the settings."); + btOK.Enabled = false; + return; // no need to continue as the input errors are not cumulative.. + } - // append to the variable.. - allUnicodeThrowException &= throwInvalidBytes & unicodeCodePages.Contains(encoding.CodePage); - } + // create a list of unicode encodings as code pages.. + List unicodeCodePages = new List(new[] {65001, 1200, 1201, 12000, 12001, }); - // if the variable is still true, warn the user and disable the OK button.. - if (allUnicodeThrowException) - { - pbAlertEncoding.Image = SystemIcons.Warning.ToBitmap(); - tbAlertEncoding.Text = DBLangEngine.GetMessage("msgEncodingAllVolatile", - "All the listed encodings will throw an exception upon an invalid byte. This leads to the software instability; fix the issue before continuing.|A message describing all the listed encodings in the settings form grid will throw an exception in case of an invalid byte leading to software instability; the user needs to fix this."); - btOK.Enabled = false; - } - } + // create a variable to detect the second error of the encodings (all Unicode and all throwing exceptions).. + bool allUnicodeThrowException = true; - private void DgvEncodings_CellClick(object sender, DataGridViewCellEventArgs e) + // loop through the rows in the data grid view.. + foreach (DataGridViewRow row in dgvEncodings.Rows) { - // set the states of the tool strip with the encoding settings grid.. - ValidateEncodingToolStrip(); - } + // get the encoding.. + var encoding = (Encoding) row.Cells[_colEncoding.Index].Value; - private void TextVariantStyle_CheckedChanged(object sender, EventArgs e) - { - var radioButton = (RadioButton) sender; - gbComparisonType.Tag = radioButton.Tag; + // get the throw an exception upon invalid bytes value.. + var throwInvalidBytes = (bool) row.Cells[colUnicodeFailInvalidChar.Index].Value; + + // append to the variable.. + allUnicodeThrowException &= throwInvalidBytes & unicodeCodePages.Contains(encoding.CodePage); } - // reset the URL detection settings to defaults.. - private void btUrlDetectDefaults_Click(object sender, EventArgs e) + // if the variable is still true, warn the user and disable the OK button.. + if (allUnicodeThrowException) { - cbHighlightUrls.Checked = true; - cbStartProcessOnUrlClick.Checked = true; - btUrlTextColor.BackColor = Color.Blue; - btUrlIndicatorColor.BackColor = Color.Blue; - cmbUrlIndicatorStyle.SelectedItem = IndicatorStyle.Plain; - cbUseDwellToolTip.Checked = true; - nudDwellToolTipDelay.Value = 400; - btDwellToolTipForegroundColor.BackColor = SystemColors.InfoText; - btDwellToolTipBackgroundColor.BackColor = SystemColors.Info; - cbURLUseAutoEllipsis.Checked = true; - nudURLUseAutoEllipsis.Value = 68; - ReStyleUrlScintillaBox(); // apply the style to the sample Scintilla control.. + pbAlertEncoding.Image = SystemIcons.Warning.ToBitmap(); + tbAlertEncoding.Text = DBLangEngine.GetMessage("msgEncodingAllVolatile", + "All the listed encodings will throw an exception upon an invalid byte. This leads to the software instability; fix the issue before continuing.|A message describing all the listed encodings in the settings form grid will throw an exception in case of an invalid byte leading to software instability; the user needs to fix this."); + btOK.Enabled = false; } + } - private void ReStyleUrlScintillaBox() - { - if (!cbHighlightUrls.Checked) - { - using (scintillaUrlDetect) - { - scintillaUrlDetect = null; - return; - } - } + private void DgvEncodings_CellClick(object sender, DataGridViewCellEventArgs e) + { + // set the states of the tool strip with the encoding settings grid.. + ValidateEncodingToolStrip(); + } - scintillaUrlDetect ??= new ScintillaUrlDetect(scintillaUrlStyle); + private void TextVariantStyle_CheckedChanged(object sender, EventArgs e) + { + var radioButton = (RadioButton) sender; + gbComparisonType.Tag = radioButton.Tag; + } - scintillaUrlDetect.ScintillaUrlIndicatorColor = btUrlIndicatorColor.BackColor; - scintillaUrlDetect.ScintillaUrlTextIndicatorColor = btUrlTextColor.BackColor; - scintillaUrlDetect.ScintillaUrlIndicatorStyle = (IndicatorStyle) cmbUrlIndicatorStyle.SelectedItem; - ScintillaUrlDetect.DwellToolTipTime = (int) nudDwellToolTipDelay.Value; - scintillaUrlDetect.DwellToolTipForegroundColor = btDwellToolTipForegroundColor.BackColor; - scintillaUrlDetect.DwellToolTipBackgroundColor = btDwellToolTipBackgroundColor.BackColor; - scintillaUrlDetect.UseDwellToolTip = cbUseDwellToolTip.Checked; - ScintillaUrlDetect.AllowProcessStartOnUrlClick = cbStartProcessOnUrlClick.Checked; - } + // reset the URL detection settings to defaults.. + private void btUrlDetectDefaults_Click(object sender, EventArgs e) + { + cbHighlightUrls.Checked = true; + cbStartProcessOnUrlClick.Checked = true; + btUrlTextColor.BackColor = Color.Blue; + btUrlIndicatorColor.BackColor = Color.Blue; + cmbUrlIndicatorStyle.SelectedItem = IndicatorStyle.Plain; + cbUseDwellToolTip.Checked = true; + nudDwellToolTipDelay.Value = 400; + btDwellToolTipForegroundColor.BackColor = SystemColors.InfoText; + btDwellToolTipBackgroundColor.BackColor = SystemColors.Info; + cbURLUseAutoEllipsis.Checked = true; + nudURLUseAutoEllipsis.Value = 68; + ReStyleUrlScintillaBox(); // apply the style to the sample Scintilla control.. + } - /// - /// Sets the URL styling settings for a class instance. Also static properties are set. - /// - /// An instance to a class. - internal static void SetUrlDetectStyling(ScintillaUrlDetect scintillaUrlDetect) + private void ReStyleUrlScintillaBox() + { + if (!cbHighlightUrls.Checked) { - if (scintillaUrlDetect == null || !Settings.HighlightUrls) + using (scintillaUrlDetect) { + scintillaUrlDetect = null; return; } - - scintillaUrlDetect.ScintillaUrlIndicatorColor = Settings.UrlIndicatorColor; - scintillaUrlDetect.ScintillaUrlTextIndicatorColor = Settings.UrlTextColor; - scintillaUrlDetect.ScintillaUrlIndicatorStyle = (IndicatorStyle) Settings.UrlIndicatorStyle; - ScintillaUrlDetect.DwellToolTipTime = Settings.UrlDwellToolTipTime; - scintillaUrlDetect.DwellToolTipForegroundColor = Settings.UrlDwellToolTipForegroundColor; - scintillaUrlDetect.DwellToolTipBackgroundColor = Settings.UrlDwellToolTipBackgroundColor; - scintillaUrlDetect.UseDwellToolTip = Settings.UrlUseDwellToolTip; - ScintillaUrlDetect.AllowProcessStartOnUrlClick = Settings.StartProcessOnUrlClick; } - private void urlStyling_Changed(object sender, EventArgs e) + scintillaUrlDetect ??= new ScintillaUrlDetect(scintillaUrlStyle); + + scintillaUrlDetect.ScintillaUrlIndicatorColor = btUrlIndicatorColor.BackColor; + scintillaUrlDetect.ScintillaUrlTextIndicatorColor = btUrlTextColor.BackColor; + scintillaUrlDetect.ScintillaUrlIndicatorStyle = (IndicatorStyle) cmbUrlIndicatorStyle.SelectedItem; + ScintillaUrlDetect.DwellToolTipTime = (int) nudDwellToolTipDelay.Value; + scintillaUrlDetect.DwellToolTipForegroundColor = btDwellToolTipForegroundColor.BackColor; + scintillaUrlDetect.DwellToolTipBackgroundColor = btDwellToolTipBackgroundColor.BackColor; + scintillaUrlDetect.UseDwellToolTip = cbUseDwellToolTip.Checked; + ScintillaUrlDetect.AllowProcessStartOnUrlClick = cbStartProcessOnUrlClick.Checked; + } + + /// + /// Sets the URL styling settings for a class instance. Also static properties are set. + /// + /// An instance to a class. + internal static void SetUrlDetectStyling(ScintillaUrlDetect scintillaUrlDetect) + { + if (scintillaUrlDetect == null || !Settings.HighlightUrls) { - ReStyleUrlScintillaBox(); + return; } - private void cbUseCustomSpellCheckingLibrary_CheckedChanged(object sender, EventArgs e) + scintillaUrlDetect.ScintillaUrlIndicatorColor = Settings.UrlIndicatorColor; + scintillaUrlDetect.ScintillaUrlTextIndicatorColor = Settings.UrlTextColor; + scintillaUrlDetect.ScintillaUrlIndicatorStyle = (IndicatorStyle) Settings.UrlIndicatorStyle; + ScintillaUrlDetect.DwellToolTipTime = Settings.UrlDwellToolTipTime; + scintillaUrlDetect.DwellToolTipForegroundColor = Settings.UrlDwellToolTipForegroundColor; + scintillaUrlDetect.DwellToolTipBackgroundColor = Settings.UrlDwellToolTipBackgroundColor; + scintillaUrlDetect.UseDwellToolTip = Settings.UrlUseDwellToolTip; + ScintillaUrlDetect.AllowProcessStartOnUrlClick = Settings.StartProcessOnUrlClick; + } + + private void urlStyling_Changed(object sender, EventArgs e) + { + ReStyleUrlScintillaBox(); + } + + private void cbUseCustomSpellCheckingLibrary_CheckedChanged(object sender, EventArgs e) + { + var checkBox = (CheckBox) sender; + pnEditorSpellCustomSetting.Visible = checkBox.Checked; + if (checkBox.Checked) { - var checkBox = (CheckBox) sender; - pnEditorSpellCustomSetting.Visible = checkBox.Checked; - if (checkBox.Checked) - { - pnEditorSpellCustomSetting.Location = new Point(pnEditorSpellCustomSetting.Location.X, - lbHunspellDictionary.Location.Y); - } + pnEditorSpellCustomSetting.Location = new Point(pnEditorSpellCustomSetting.Location.X, + lbHunspellDictionary.Location.Y); } + } - private void btInstallSpellCheckerFromFile_Click(object sender, EventArgs e) - { - odSpellCheckerPackage.Title = DBLangEngine.GetMessage("msgDialogSelectCustomSpellChecker", - "Select a spell checker library package|A title for an open file dialog to indicate user that the user is selecting a compressed zip file containing an assembly providing custom spell checking functionality"); + private void btInstallSpellCheckerFromFile_Click(object sender, EventArgs e) + { + odSpellCheckerPackage.Title = DBLangEngine.GetMessage("msgDialogSelectCustomSpellChecker", + "Select a spell checker library package|A title for an open file dialog to indicate user that the user is selecting a compressed zip file containing an assembly providing custom spell checking functionality"); - if (odSpellCheckerPackage.ShowDialog() == DialogResult.OK) - { - var zip = odSpellCheckerPackage.FileName; - var package = DictionaryPackage.InstallPackage(zip, Settings.EditorSpellCustomDictionaryInstallPath); - tbSpellCheckingLibraryFile.Text = package; - } + if (odSpellCheckerPackage.ShowDialog() == DialogResult.OK) + { + var zip = odSpellCheckerPackage.FileName; + var package = DictionaryPackage.InstallPackage(zip, Settings.EditorSpellCustomDictionaryInstallPath); + tbSpellCheckingLibraryFile.Text = package; } + } - private void btRemoveInstalledSpellChecker_Click(object sender, EventArgs e) + private void btRemoveInstalledSpellChecker_Click(object sender, EventArgs e) + { + try { - try - { - var info = DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(tbSpellCheckingLibraryFile.Text); - var result = - MessageBoxExtended.Show(this, + var info = DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(tbSpellCheckingLibraryFile.Text); + var result = + MessageBoxExtended.Show(this, DBLangEngine.GetMessage("msgQueryDeleteSpellCheckLibrary", "Really remove spell check library '{0}' ({1}) ?|A message confirming that the user is removing a custom spell checker library", info.name, info.lib), DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog"), MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2); - if (result == DialogResultExtended.Yes) + if (result == DialogResultExtended.Yes) + { + var deletePath = Path.GetDirectoryName(tbSpellCheckingLibraryFile.Text); + if (Directory.Exists(deletePath)) { - var deletePath = Path.GetDirectoryName(tbSpellCheckingLibraryFile.Text); - if (Directory.Exists(deletePath)) - { - Directory.Delete(deletePath, true); - } - - tbSpellCheckingLibraryFile.Text = - DBLangEngine.GetMessage("msgNA", "N/A|A message indicating a none value"); + Directory.Delete(deletePath, true); } - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); + + tbSpellCheckingLibraryFile.Text = + DBLangEngine.GetMessage("msgNA", "N/A|A message indicating a none value"); } } - - private void tbSpellCheckingLibraryFile_TextChanged(object sender, EventArgs e) + catch (Exception ex) { - var textBox = (TextBox) sender; - textBox.ForeColor = File.Exists(textBox.Text) ? Color.Black : Color.Red; - btRemoveInstalledSpellChecker.Enabled = File.Exists(textBox.Text); + ExceptionLogger.LogError(ex); } + } - private void pbAbout_Click(object sender, EventArgs e) - { - FormDialogCustomSpellCheckerInfo.ShowDialog(this, tbSpellCheckingLibraryFile.Text); - } + private void tbSpellCheckingLibraryFile_TextChanged(object sender, EventArgs e) + { + var textBox = (TextBox) sender; + textBox.ForeColor = File.Exists(textBox.Text) ? Color.Black : Color.Red; + btRemoveInstalledSpellChecker.Enabled = File.Exists(textBox.Text); + } + + private void pbAbout_Click(object sender, EventArgs e) + { + FormDialogCustomSpellCheckerInfo.ShowDialog(this, tbSpellCheckingLibraryFile.Text); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Settings/Settings.cs b/ScriptNotepad/Settings/Settings.cs index 6d5820ba..7f35e1f2 100644 --- a/ScriptNotepad/Settings/Settings.cs +++ b/ScriptNotepad/Settings/Settings.cs @@ -14,968 +14,967 @@ using ScriptNotepad.UtilityClasses.ErrorHandling; using TabDrawMode = ScintillaNET.TabDrawMode; -namespace ScriptNotepad.Settings +namespace ScriptNotepad.Settings; + +/// +/// A class for the application settings. +/// Implements the +/// +/// +public class Settings: XmlSettings { /// - /// A class for the application settings. - /// Implements the + /// The amount of files to be saved to a document history. /// - /// - public class Settings: XmlSettings - { - /// - /// The amount of files to be saved to a document history. - /// - /// The amount of files to be saved to a document history. - public int HistoryListAmount { get; set; } = 20; - - #region DatabaseState - - /// - /// Gets or sets the fancy-named database migration level; for now this is used for the Entity Framework conversion. - /// - /// The migration level. - [IsSetting] // return an invalid value before the software is ready to branch merge.. - public int DatabaseMigrationLevel { get; set; } = 1; - #endregion - - #region ColorSettings - /// - /// Gets or sets the color of the current line background style. - /// - /// The color of the current line background style. - [IsSetting] - public Color CurrentLineBackground { get; set; } = Color.FromArgb(232, 232, 255); - - /// - /// Gets or sets the color of the smart highlight style. - /// - /// The color of the smart highlight style. - [IsSetting] - public Color SmartHighlight { get; set; } = Color.FromArgb(0, 255, 0); - - /// - /// Gets or sets the color of the mark one style. - /// - /// The color of the mark one style. - [IsSetting] - public Color Mark1Color { get; set; } = Color.FromArgb(0, 255, 255); - - /// - /// Gets or sets the color of the mark two style. - /// - /// The color of the mark two style. - [IsSetting] - public Color Mark2Color { get; set; } = Color.FromArgb(255, 128, 0); - - /// - /// Gets or sets the color of the mark three style. - /// - /// The color of the mark three style. - [IsSetting] - public Color Mark3Color { get; set; } = Color.FromArgb(255, 255, 0); - - /// - /// Gets or sets the color of the mark four style. - /// - /// The color of the mark four style. - [IsSetting] - public Color Mark4Color { get; set; } = Color.FromArgb(128, 0, 255); - - /// - /// Gets or sets the color of the mark five style. - /// - /// The color of the mark five style. - [IsSetting] - public Color Mark5Color { get; set; } = Color.FromArgb(0, 128, 0); - - /// - /// Gets or sets the color of the mark used in the search and replace dialog. - /// - [IsSetting] - public Color MarkSearchReplaceColor { get; set; } = Color.DeepPink; - - /// - /// Gets or sets the foreground color of brace highlighting. - /// - [IsSetting] - public Color BraceHighlightForegroundColor { get; set; } = Color.BlueViolet; - - /// - /// Gets or sets the background color of brace highlighting. - /// - [IsSetting] - public Color BraceHighlightBackgroundColor { get; set; } = Color.LightGray; - - /// - /// Gets or sets the foreground color of a bad brace. - /// - [IsSetting] - public Color BraceBadHighlightForegroundColor { get; set; } = Color.Red; - #endregion - - #region DeprecatedSettings - /// - /// Gets or sets the default encoding to be used with the files within this software. - /// - [Obsolete("DefaultEncoding is deprecated, the EncodingList property replaces this property.")] - [IsSetting] - public Encoding DefaultEncoding { get; set; } = Encoding.UTF8; - #endregion - - #region MainSettings - /// - /// Gets or sets a value indicating whether the thread locale should be set matching to the localization value. - /// - [IsSetting] - public bool LocalizeThread { get; set; } - - /// - /// Gets or sets a value indicating whether the software should try to auto-detect the encoding of a file. - /// - [IsSetting] - public bool AutoDetectEncoding { get; set; } = true; - - /// - /// Gets or sets a value indicating whether the software should try to detect a no-BOM unicode files. - /// - [IsSetting] - public bool DetectNoBom { get; set; } - - /// - /// Gets or sets a value indicating whether the software should skip trying to detect little-endian Unicode encoding if the is enabled. - /// - [IsSetting] - public bool SkipUnicodeDetectLe { get; set; } - - /// - /// Gets or sets a value indicating whether the software should skip trying to detect big-endian Unicode encoding if the is enabled. - /// - [IsSetting] - public bool SkipUnicodeDetectBe { get; set; } + /// The amount of files to be saved to a document history. + public int HistoryListAmount { get; set; } = 20; + + #region DatabaseState + + /// + /// Gets or sets the fancy-named database migration level; for now this is used for the Entity Framework conversion. + /// + /// The migration level. + [IsSetting] // return an invalid value before the software is ready to branch merge.. + public int DatabaseMigrationLevel { get; set; } = 1; + #endregion + + #region ColorSettings + /// + /// Gets or sets the color of the current line background style. + /// + /// The color of the current line background style. + [IsSetting] + public Color CurrentLineBackground { get; set; } = Color.FromArgb(232, 232, 255); + + /// + /// Gets or sets the color of the smart highlight style. + /// + /// The color of the smart highlight style. + [IsSetting] + public Color SmartHighlight { get; set; } = Color.FromArgb(0, 255, 0); + + /// + /// Gets or sets the color of the mark one style. + /// + /// The color of the mark one style. + [IsSetting] + public Color Mark1Color { get; set; } = Color.FromArgb(0, 255, 255); + + /// + /// Gets or sets the color of the mark two style. + /// + /// The color of the mark two style. + [IsSetting] + public Color Mark2Color { get; set; } = Color.FromArgb(255, 128, 0); + + /// + /// Gets or sets the color of the mark three style. + /// + /// The color of the mark three style. + [IsSetting] + public Color Mark3Color { get; set; } = Color.FromArgb(255, 255, 0); + + /// + /// Gets or sets the color of the mark four style. + /// + /// The color of the mark four style. + [IsSetting] + public Color Mark4Color { get; set; } = Color.FromArgb(128, 0, 255); + + /// + /// Gets or sets the color of the mark five style. + /// + /// The color of the mark five style. + [IsSetting] + public Color Mark5Color { get; set; } = Color.FromArgb(0, 128, 0); + + /// + /// Gets or sets the color of the mark used in the search and replace dialog. + /// + [IsSetting] + public Color MarkSearchReplaceColor { get; set; } = Color.DeepPink; + + /// + /// Gets or sets the foreground color of brace highlighting. + /// + [IsSetting] + public Color BraceHighlightForegroundColor { get; set; } = Color.BlueViolet; + + /// + /// Gets or sets the background color of brace highlighting. + /// + [IsSetting] + public Color BraceHighlightBackgroundColor { get; set; } = Color.LightGray; + + /// + /// Gets or sets the foreground color of a bad brace. + /// + [IsSetting] + public Color BraceBadHighlightForegroundColor { get; set; } = Color.Red; + #endregion + + #region DeprecatedSettings + /// + /// Gets or sets the default encoding to be used with the files within this software. + /// + [Obsolete("DefaultEncoding is deprecated, the EncodingList property replaces this property.")] + [IsSetting] + public Encoding DefaultEncoding { get; set; } = Encoding.UTF8; + #endregion + + #region MainSettings + /// + /// Gets or sets a value indicating whether the thread locale should be set matching to the localization value. + /// + [IsSetting] + public bool LocalizeThread { get; set; } + + /// + /// Gets or sets a value indicating whether the software should try to auto-detect the encoding of a file. + /// + [IsSetting] + public bool AutoDetectEncoding { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the software should try to detect a no-BOM unicode files. + /// + [IsSetting] + public bool DetectNoBom { get; set; } + + /// + /// Gets or sets a value indicating whether the software should skip trying to detect little-endian Unicode encoding if the is enabled. + /// + [IsSetting] + public bool SkipUnicodeDetectLe { get; set; } + + /// + /// Gets or sets a value indicating whether the software should skip trying to detect big-endian Unicode encoding if the is enabled. + /// + [IsSetting] + public bool SkipUnicodeDetectBe { get; set; } - /// - /// Gets or sets a value indicating whether the software should skip trying to detect little-endian UTF32 encoding if the is enabled. - /// - [IsSetting] - public bool SkipUtf32Le { get; set; } - - /// - /// Gets or sets a value indicating whether the software should skip trying to detect big-endian UTF32 encoding if the is enabled. - /// - [IsSetting] - public bool SkipUtf32Be { get; set; } - - // a field to hold the EncodingList property value.. - private string encodingList = string.Empty; - - /// - /// Gets or sets an ordered encoding list for the software to try in the order. - /// - [IsSetting] - public string EncodingList + /// + /// Gets or sets a value indicating whether the software should skip trying to detect little-endian UTF32 encoding if the is enabled. + /// + [IsSetting] + public bool SkipUtf32Le { get; set; } + + /// + /// Gets or sets a value indicating whether the software should skip trying to detect big-endian UTF32 encoding if the is enabled. + /// + [IsSetting] + public bool SkipUtf32Be { get; set; } + + // a field to hold the EncodingList property value.. + private string encodingList = string.Empty; + + /// + /// Gets or sets an ordered encoding list for the software to try in the order. + /// + [IsSetting] + public string EncodingList + { + // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... + get { - // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... - get + // if empty; create a list of one item.. + if (encodingList == string.Empty) { - // if empty; create a list of one item.. - if (encodingList == string.Empty) - { // the deprecated property is still in for backwards compatibility - so disable the warning.. #pragma warning disable 618 - encodingList = - new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + - new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + - (DefaultEncoding.WebName == new UTF8Encoding().WebName - ? Encoding.Default.WebName - : DefaultEncoding.WebName) + ';' + false + ';' + false + '|'; + encodingList = + new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + + new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + + (DefaultEncoding.WebName == new UTF8Encoding().WebName + ? Encoding.Default.WebName + : DefaultEncoding.WebName) + ';' + false + ';' + false + '|'; #pragma warning restore 618 - } + } - return encodingList; - } - set => encodingList = value; - } - #endregion - - #region EditorSpell - /// - /// Gets or sets a value indicating whether the spell checking is enabled for the document. - /// - [IsSetting] - public bool EditorUseSpellChecking { get; set; } - - /// - /// Gets or sets a value indicating whether the spell checking is enabled for the document when opening a file via the shell context menu. - /// - [IsSetting] - public bool EditorUseSpellCheckingShellContext { get; set; } - - /// - /// Gets or sets a value indicating whether the spell checking is enabled for the document for new files. - /// - [IsSetting] - public bool EditorUseSpellCheckingNewFiles { get; set; } - - /// - /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. - /// - [IsSetting] - public string EditorHunspellDictionaryFile { get; set; } = string.Empty; - - /// - /// Gets or sets a value of the Hunspell affix file to be used with spell checking for the document. - /// - [IsSetting] - public string EditorHunspellAffixFile { get; set; } = string.Empty; - - /// - /// Gets or sets the color of the spell check mark. - /// - [IsSetting] - public Color EditorSpellCheckColor { get; set; } = Color.Red; - - /// - /// Gets or sets the color of the spell check mark. - /// - [IsSetting] - public int EditorSpellCheckInactivity { get; set; } = 500; // set the default to 500 milliseconds.. - - /// - /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. - /// - [IsSetting] - public string EditorHunspellDictionaryPath { get; set; } = DefaultDirectory("Dictionaries"); - - /// - /// Gets or sets a value indicating whether the spell checker should use a custom dictionary (an external assembly) for the spell checking. - /// - [IsSetting] - public bool EditorSpellUseCustomDictionary { get; set; } - - /// - /// Gets or sets the editor spell custom dictionary (an external assembly) definition file. - /// - [IsSetting] - public string EditorSpellCustomDictionaryDefinitionFile { get; set; } - - /// - /// Gets or sets the editor spell custom dictionary install path. - /// - [IsSetting] - public string EditorSpellCustomDictionaryInstallPath { get; set; } = - FormSettings.CreateDefaultCustomDictionaryDirectory(); - #endregion - - #region UrlDetection - - /// - /// Gets or sets a value indicating whether to highlight URLs within the control. - /// - [IsSetting] - public bool HighlightUrls { get; set; } = true; - - /// - /// Gets or sets a value indicating whether to start an associated program on clicking a highlighted URL. - /// - [IsSetting] - public bool StartProcessOnUrlClick { get; set; } = true; - - /// - /// Gets or sets the color of the URL text. - /// - [IsSetting] - public Color UrlTextColor { get; set; } = Color.Blue; - - /// - /// Gets or sets the color of the URL indicator. - /// - [IsSetting] - public Color UrlIndicatorColor { get; set; } = Color.Blue; - - /// - /// Gets or sets the URL indicator style. - /// - [IsSetting] - public int UrlIndicatorStyle { get; set; } = (int) IndicatorStyle.Plain; - - /// - /// Gets or sets a value indicating whether to use a dwell tool tip on URLs. - /// - [IsSetting] - public bool UrlUseDwellToolTip { get; set; } = true; - - /// - /// Gets or sets the foreground color to be used with the URL tool tips. - /// - [IsSetting] - public Color UrlDwellToolTipForegroundColor { get; set; } = SystemColors.InfoText; - - /// - /// Gets or sets the background color to be used with the URL tool tips. - /// - [IsSetting] - public Color UrlDwellToolTipBackgroundColor { get; set; } = SystemColors.Info; - - /// - /// Gets or sets the foreground color to be used with the URL tool tips. - /// - [IsSetting] - public int UrlDwellToolTipTime { get; set; } = 400; - - /// - /// Gets or sets the URL maximum length before the use of an ellipsis to shorten it. - /// - [IsSetting] - public int UrlMaxLengthBeforeEllipsis { get; set; } = 60; - - /// - /// Gets or sets a value indicating whether to use automatic ellipsis on long URLs. - /// - [IsSetting] - public bool UrlUseAutoEllipsis { get; set; } = true; - #endregion - - #region Editor - /// - /// Gets or sets the font for the control. - /// - // ReSharper disable once StringLiteralTypo - [IsSetting] - // ReSharper disable once StringLiteralTypo - public string EditorFontName { get; set; } = @"Consolas"; - - /// - /// Gets or sets the tab width for the control. - /// - [IsSetting] - public int EditorTabWidth { get; set; } = 4; + return encodingList; + } + set => encodingList = value; + } + #endregion + + #region EditorSpell + /// + /// Gets or sets a value indicating whether the spell checking is enabled for the document. + /// + [IsSetting] + public bool EditorUseSpellChecking { get; set; } + + /// + /// Gets or sets a value indicating whether the spell checking is enabled for the document when opening a file via the shell context menu. + /// + [IsSetting] + public bool EditorUseSpellCheckingShellContext { get; set; } + + /// + /// Gets or sets a value indicating whether the spell checking is enabled for the document for new files. + /// + [IsSetting] + public bool EditorUseSpellCheckingNewFiles { get; set; } + + /// + /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. + /// + [IsSetting] + public string EditorHunspellDictionaryFile { get; set; } = string.Empty; + + /// + /// Gets or sets a value of the Hunspell affix file to be used with spell checking for the document. + /// + [IsSetting] + public string EditorHunspellAffixFile { get; set; } = string.Empty; + + /// + /// Gets or sets the color of the spell check mark. + /// + [IsSetting] + public Color EditorSpellCheckColor { get; set; } = Color.Red; + + /// + /// Gets or sets the color of the spell check mark. + /// + [IsSetting] + public int EditorSpellCheckInactivity { get; set; } = 500; // set the default to 500 milliseconds.. + + /// + /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. + /// + [IsSetting] + public string EditorHunspellDictionaryPath { get; set; } = DefaultDirectory("Dictionaries"); + + /// + /// Gets or sets a value indicating whether the spell checker should use a custom dictionary (an external assembly) for the spell checking. + /// + [IsSetting] + public bool EditorSpellUseCustomDictionary { get; set; } + + /// + /// Gets or sets the editor spell custom dictionary (an external assembly) definition file. + /// + [IsSetting] + public string EditorSpellCustomDictionaryDefinitionFile { get; set; } + + /// + /// Gets or sets the editor spell custom dictionary install path. + /// + [IsSetting] + public string EditorSpellCustomDictionaryInstallPath { get; set; } = + FormSettings.CreateDefaultCustomDictionaryDirectory(); + #endregion + + #region UrlDetection + + /// + /// Gets or sets a value indicating whether to highlight URLs within the control. + /// + [IsSetting] + public bool HighlightUrls { get; set; } = true; + + /// + /// Gets or sets a value indicating whether to start an associated program on clicking a highlighted URL. + /// + [IsSetting] + public bool StartProcessOnUrlClick { get; set; } = true; + + /// + /// Gets or sets the color of the URL text. + /// + [IsSetting] + public Color UrlTextColor { get; set; } = Color.Blue; + + /// + /// Gets or sets the color of the URL indicator. + /// + [IsSetting] + public Color UrlIndicatorColor { get; set; } = Color.Blue; + + /// + /// Gets or sets the URL indicator style. + /// + [IsSetting] + public int UrlIndicatorStyle { get; set; } = (int) IndicatorStyle.Plain; + + /// + /// Gets or sets a value indicating whether to use a dwell tool tip on URLs. + /// + [IsSetting] + public bool UrlUseDwellToolTip { get; set; } = true; + + /// + /// Gets or sets the foreground color to be used with the URL tool tips. + /// + [IsSetting] + public Color UrlDwellToolTipForegroundColor { get; set; } = SystemColors.InfoText; + + /// + /// Gets or sets the background color to be used with the URL tool tips. + /// + [IsSetting] + public Color UrlDwellToolTipBackgroundColor { get; set; } = SystemColors.Info; + + /// + /// Gets or sets the foreground color to be used with the URL tool tips. + /// + [IsSetting] + public int UrlDwellToolTipTime { get; set; } = 400; + + /// + /// Gets or sets the URL maximum length before the use of an ellipsis to shorten it. + /// + [IsSetting] + public int UrlMaxLengthBeforeEllipsis { get; set; } = 60; + + /// + /// Gets or sets a value indicating whether to use automatic ellipsis on long URLs. + /// + [IsSetting] + public bool UrlUseAutoEllipsis { get; set; } = true; + #endregion + + #region Editor + /// + /// Gets or sets the font for the control. + /// + // ReSharper disable once StringLiteralTypo + [IsSetting] + // ReSharper disable once StringLiteralTypo + public string EditorFontName { get; set; } = @"Consolas"; + + /// + /// Gets or sets the tab width for the control. + /// + [IsSetting] + public int EditorTabWidth { get; set; } = 4; - /// - /// Gets or sets a value indicating whether to use code indentation with the control. - /// - [IsSetting] - public bool EditorUseCodeIndentation { get; set; } - - /// - /// Gets or sets a value indicating whether the zoom value of the document should be to the database. - /// - [IsSetting] - public bool EditorSaveZoom { get; set; } = true; - - /// - /// Gets or sets a value indicating whether the zoom value should be individual for all the open documents. - /// - [IsSetting] - public bool EditorIndividualZoom { get; set; } = true; - - /// - /// Gets or sets the size of the font used in the control. - /// - [IsSetting] - public int EditorFontSize { get; set; } = 10; - - /// - /// Gets or sets a value indicating whether the editor should use tabs. - /// - [IsSetting] - public bool EditorUseTabs { get; set; } = true; - - /// - /// Gets or sets a value indicating whether the editor indent guide is enabled. - /// - [IsSetting] - public bool EditorIndentGuideOn { get; set; } = true; - - /// - /// Gets or sets a value of the tab character symbol type. - /// - [IsSetting] - public int EditorTabSymbol { get; set; } = (int) TabDrawMode.LongArrow; - - /// - /// Gets or sets the size of the editor white space in points. - /// - [IsSetting] - public int EditorWhiteSpaceSize { get; set; } = 1; - - /// - /// Gets or sets a value indicating whether the main window should capture some key combinations to simulate an AltGr+Key press for the active editor . - /// - [IsSetting] - public bool SimulateAltGrKey { get; set; } - - /// - /// Gets or sets a value indicating whether the editor () should highlight braces. - /// - [IsSetting] - public bool HighlightBraces { get; set; } - - /// - /// Gets or sets a value indicating whether the editor () should use italic font style when highlighting braces. - /// - [IsSetting] - public bool HighlightBracesItalic { get; set; } - - /// - /// Gets or sets a value indicating whether the editor () should use bold font style when highlighting braces. - /// - [IsSetting] - public bool HighlightBracesBold { get; set; } - - /// - /// Gets or sets a value indicating whether the editor should use RTL (Right-to-left) script with the controls. - /// - [IsSetting] - // ReSharper disable once UnusedMember.Global, perhaps in the future.. - public bool EditorUseRtl { get; set; } - - /// - /// Gets or sets the index of the type of simulation of an AltGr+Key press for the active editor . - /// - [IsSetting] - public int SimulateAltGrKeyIndex { get; set; } = -1; - #endregion - - #region EditorAdditional - /// - /// Gets or sets a value indicating whether to use automatic code completion for the C# programming language. - /// - /// true to use automatic code completion for the C# programming language; otherwise, false. - [IsSetting] - public bool UseCSharpAutoComplete { get; set; } - #endregion - - #region Styles - /// - /// Gets or sets a value for the Notepad++ theme definition files for the document. - /// - [IsSetting] - public string NotepadPlusPlusThemePath { get; set; } = DefaultDirectory("Notepad-plus-plus-themes"); - - /// - /// Gets or sets a value for the Notepad++ theme definition file name for the document. - /// - [IsSetting] - public string NotepadPlusPlusThemeFile { get; set; } = string.Empty; - - /// - /// Gets or sets a value indicating whether to use a style definition file from the Notepad++ software. - /// - [IsSetting] - public bool UseNotepadPlusPlusTheme { get; set; } - #endregion - - #region MiscSettings - - /// - /// Gets or sets a value indicating whether search and replace dialog should be transparent. - /// - [IsSetting] - public int SearchBoxTransparency { get; set; } = 1; // 0 = false, 1 = false when inactive, 2 = always.. - - /// - /// Gets or sets a value of opacity of the form. - /// - [IsSetting] - public double SearchBoxOpacity { get; set; } = 0.8; - - /// - /// Gets or sets a value indicating whether the default session name has been localized. - /// - [IsSetting] - public bool DefaultSessionLocalized { get; set; } - - /// - /// Gets or sets a value indicating whether the software should check for updates upon startup. - /// - [IsSetting] - public bool UpdateAutoCheck { get; set; } - - /// - /// Gets or sets the plug-in folder for the software. - /// - [IsSetting] - public string PluginFolder { get; set; } = FormSettings.CreateDefaultPluginDirectory(); - - /// - /// Gets or sets a value indicating whether the search three form should be an independent form or a docked control to the main form. - /// - [IsSetting] - public bool DockSearchTreeForm { get; set; } - - /// - /// Gets or sets a value indicating whether tp categorize the programming language menu with the language name starting character. - /// - [IsSetting] - public bool CategorizeStartCharacterProgrammingLanguage { get; set; } - #endregion - - #region DataSettings - - /// - /// Gets or sets a value indicating whether save closed file contents to database as history. - /// - [IsSetting] - public bool SaveFileHistoryContents { get; set; } = true; - - /// - /// Gets or sets a value indicating whether to use file system to cache the contents of the files. Otherwise the database is used. - /// - [IsSetting] - public bool UseFileSystemCache { get; set; } - - /// - /// Gets or sets the save file history contents count. - /// - [IsSetting] - public int SaveFileHistoryContentsCount { get; set; } = 100; - - /// - /// Gets or sets the current session (for the documents). - /// - [IsSetting] - public string CurrentSession { get; set; } = @"Default"; - - /// - /// Gets the current session entity. - /// - public FileSession CurrentSessionEntity + /// + /// Gets or sets a value indicating whether to use code indentation with the control. + /// + [IsSetting] + public bool EditorUseCodeIndentation { get; set; } + + /// + /// Gets or sets a value indicating whether the zoom value of the document should be to the database. + /// + [IsSetting] + public bool EditorSaveZoom { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the zoom value should be individual for all the open documents. + /// + [IsSetting] + public bool EditorIndividualZoom { get; set; } = true; + + /// + /// Gets or sets the size of the font used in the control. + /// + [IsSetting] + public int EditorFontSize { get; set; } = 10; + + /// + /// Gets or sets a value indicating whether the editor should use tabs. + /// + [IsSetting] + public bool EditorUseTabs { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the editor indent guide is enabled. + /// + [IsSetting] + public bool EditorIndentGuideOn { get; set; } = true; + + /// + /// Gets or sets a value of the tab character symbol type. + /// + [IsSetting] + public int EditorTabSymbol { get; set; } = (int) TabDrawMode.LongArrow; + + /// + /// Gets or sets the size of the editor white space in points. + /// + [IsSetting] + public int EditorWhiteSpaceSize { get; set; } = 1; + + /// + /// Gets or sets a value indicating whether the main window should capture some key combinations to simulate an AltGr+Key press for the active editor . + /// + [IsSetting] + public bool SimulateAltGrKey { get; set; } + + /// + /// Gets or sets a value indicating whether the editor () should highlight braces. + /// + [IsSetting] + public bool HighlightBraces { get; set; } + + /// + /// Gets or sets a value indicating whether the editor () should use italic font style when highlighting braces. + /// + [IsSetting] + public bool HighlightBracesItalic { get; set; } + + /// + /// Gets or sets a value indicating whether the editor () should use bold font style when highlighting braces. + /// + [IsSetting] + public bool HighlightBracesBold { get; set; } + + /// + /// Gets or sets a value indicating whether the editor should use RTL (Right-to-left) script with the controls. + /// + [IsSetting] + // ReSharper disable once UnusedMember.Global, perhaps in the future.. + public bool EditorUseRtl { get; set; } + + /// + /// Gets or sets the index of the type of simulation of an AltGr+Key press for the active editor . + /// + [IsSetting] + public int SimulateAltGrKeyIndex { get; set; } = -1; + #endregion + + #region EditorAdditional + /// + /// Gets or sets a value indicating whether to use automatic code completion for the C# programming language. + /// + /// true to use automatic code completion for the C# programming language; otherwise, false. + [IsSetting] + public bool UseCSharpAutoComplete { get; set; } + #endregion + + #region Styles + /// + /// Gets or sets a value for the Notepad++ theme definition files for the document. + /// + [IsSetting] + public string NotepadPlusPlusThemePath { get; set; } = DefaultDirectory("Notepad-plus-plus-themes"); + + /// + /// Gets or sets a value for the Notepad++ theme definition file name for the document. + /// + [IsSetting] + public string NotepadPlusPlusThemeFile { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether to use a style definition file from the Notepad++ software. + /// + [IsSetting] + public bool UseNotepadPlusPlusTheme { get; set; } + #endregion + + #region MiscSettings + + /// + /// Gets or sets a value indicating whether search and replace dialog should be transparent. + /// + [IsSetting] + public int SearchBoxTransparency { get; set; } = 1; // 0 = false, 1 = false when inactive, 2 = always.. + + /// + /// Gets or sets a value of opacity of the form. + /// + [IsSetting] + public double SearchBoxOpacity { get; set; } = 0.8; + + /// + /// Gets or sets a value indicating whether the default session name has been localized. + /// + [IsSetting] + public bool DefaultSessionLocalized { get; set; } + + /// + /// Gets or sets a value indicating whether the software should check for updates upon startup. + /// + [IsSetting] + public bool UpdateAutoCheck { get; set; } + + /// + /// Gets or sets the plug-in folder for the software. + /// + [IsSetting] + public string PluginFolder { get; set; } = FormSettings.CreateDefaultPluginDirectory(); + + /// + /// Gets or sets a value indicating whether the search three form should be an independent form or a docked control to the main form. + /// + [IsSetting] + public bool DockSearchTreeForm { get; set; } + + /// + /// Gets or sets a value indicating whether tp categorize the programming language menu with the language name starting character. + /// + [IsSetting] + public bool CategorizeStartCharacterProgrammingLanguage { get; set; } + #endregion + + #region DataSettings + + /// + /// Gets or sets a value indicating whether save closed file contents to database as history. + /// + [IsSetting] + public bool SaveFileHistoryContents { get; set; } = true; + + /// + /// Gets or sets a value indicating whether to use file system to cache the contents of the files. Otherwise the database is used. + /// + [IsSetting] + public bool UseFileSystemCache { get; set; } + + /// + /// Gets or sets the save file history contents count. + /// + [IsSetting] + public int SaveFileHistoryContentsCount { get; set; } = 100; + + /// + /// Gets or sets the current session (for the documents). + /// + [IsSetting] + public string CurrentSession { get; set; } = @"Default"; + + /// + /// Gets the current session entity. + /// + public FileSession CurrentSessionEntity + { + get { - get + var defaultSessionName = DBLangEngine.GetStatMessage("msgDefaultSessionName", + "Default|A name of the default session for the documents"); + + try { - var defaultSessionName = DBLangEngine.GetStatMessage("msgDefaultSessionName", - "Default|A name of the default session for the documents"); + var session = + ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => f.Id == 1); - try + if (session != null) { - var session = - ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => f.Id == 1); - - if (session != null) + if (session.SessionName != defaultSessionName) { - if (session.SessionName != defaultSessionName) - { - session.SessionName = defaultSessionName; - } + session.SessionName = defaultSessionName; } - - return session; - } - catch - { - return null; } - } - set => CurrentSession = value.SessionName; - } - #endregion - - #region SearchSettings - - /// - /// Gets or sets the file's maximum size in megabytes (MB) to include in the file search. - /// - /// The file search maximum size mb. - [IsSetting] - public long FileSearchMaxSizeMb { get; set; } = 100; - - /// - /// Gets or sets the limit count of the history texts (filters, search texts, replace texts and directories) to be saved and retrieved to the form. - /// - [IsSetting] - public int FileSearchHistoriesLimit { get; set; } = 25; - - /// - /// Gets or sets the value whether to use auto-complete on the search dialog combo boxes. - /// - [IsSetting] - public bool AutoCompleteEnabled { get; set; } = true; - #endregion - - #region ProgramSettings - - /// - /// Gets or sets a value indicating whether to use auto-save with a specified . - /// - [IsSetting] - public bool ProgramAutoSave { get; set; } = true; - - /// - /// Gets or sets the program's automatic save interval in minutes. - /// - /// The program automatic save interval. - [IsSetting] - public int ProgramAutoSaveInterval { get; set; } = 5; - - // the current language (Culture) to be used with the software.. - private static CultureInfo _culture; - - /// - /// Gets or sets the name of the culture used with localization. - /// - /// The name of the culture used with localization. - [IsSetting] - public string CultureName { get; set; } = "en-US"; - - /// - /// Gets or sets the current language (Culture) to be used with the software's localization. - /// - public CultureInfo Culture - { - get => - _culture ?? new CultureInfo(CultureName ?? "en-US"); - - set + return session; + } + catch { - _culture = value; - CultureName = value.Name; + return null; } } - #endregion - - #region SaveOpenDialogSettings - /// - /// Gets or sets the initial directory for a save as dialog. - /// - [IsSetting] - public string FileLocationSaveAs { get; set; } - - /// - /// Gets or sets the initial directory for a save as HTML dialog. - /// - [IsSetting] - public string FileLocationSaveAsHtml { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog on the main form. - /// - [IsSetting] - public string FileLocationOpen { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog on the main form with encoding. - /// - [IsSetting] - public string FileLocationOpenWithEncoding { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open the first file for the diff form. - /// - [IsSetting] - public string FileLocationOpenDiff1 { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open the second file for the diff form. - /// - [IsSetting] - public string FileLocationOpenDiff2 { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to install a plugin from the plugin management dialog. - /// - [IsSetting] - public string FileLocationOpenPlugin { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open a Hunspell dictionary file from the settings form. - /// - [IsSetting] - public string FileLocationOpenDictionary { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open a Hunspell affix file from the settings form. - /// - [IsSetting] - public string FileLocationOpenAffix { get; set; } - #endregion - - #region DateTimeSettings - - /// - /// Gets or sets the date and/or time format 1. - /// - [IsSetting] - public string DateFormat1 { get; set; } = @"yyyy'/'MM'/'dd"; // default to american.. - - /// - /// Gets or sets the date and/or time format 2. - /// - [IsSetting] - public string DateFormat2 { get; set; } = @"dd'.'MM'.'yyyy"; // default to european.. - - /// - /// Gets or sets the date and/or time format 3. - /// - [IsSetting] - public string DateFormat3 { get; set; } = @"yyyy'/'MM'/'dd hh'.'mm tt"; // default to american.. - - /// - /// Gets or sets the date and/or time format 4. - /// - [IsSetting] - public string DateFormat4 { get; set; } = @"dd'.'MM'.'yyyy HH':'mm':'ss"; // default to european.. - - /// - /// Gets or sets the date and/or time format 5. - /// - [IsSetting] - public string DateFormat5 { get; set; } = @"hh'.'mm tt"; // default to american.. - - /// - /// Gets or sets the date and/or time format 6. - /// - [IsSetting] - public string DateFormat6 { get; set; } = @"HH':'mm':'ss"; // default to european.. - - /// - /// Gets or sets a value indicating whether to use invariant culture formatting date and time via the edit menu. - /// - [IsSetting] - public bool DateFormatUseInvariantCulture { get; set; } - #endregion - - #region TextSettings - /// - /// Gets or sets a value indicating whether to use case sensitivity with text manipulation. - /// - [IsSetting] - public bool TextUpperCaseComparison { get; set; } - - /// - /// Gets or sets the type of the text comparison to use with text manipulation. - /// - [IsSetting] - public int TextComparisonType { get; set; } = 0; // 0 = invariant, 1 = current, 2 = ordinal.. - - /// - /// Gets or sets a value indicating whether to show the run snippet tool bar. - /// - /// true if to show the run snippet tool bar; otherwise, false. - [IsSetting] - public bool ShowRunSnippetToolbar { get; set; } - - /// - /// Gets the text current comparison type . - /// - public StringComparison TextCurrentComparison - { - get - { - switch (TextComparisonType) - { - case 0: - return TextUpperCaseComparison - ? StringComparison.InvariantCulture - : StringComparison.InvariantCultureIgnoreCase; - - case 1: - return TextUpperCaseComparison - ? StringComparison.CurrentCulture - : StringComparison.CurrentCultureIgnoreCase; - - case 2: - return TextUpperCaseComparison - ? StringComparison.Ordinal - : StringComparison.OrdinalIgnoreCase; - } - return TextUpperCaseComparison - ? StringComparison.InvariantCulture - : StringComparison.InvariantCultureIgnoreCase; - } + set => CurrentSession = value.SessionName; + } + #endregion + + #region SearchSettings + + /// + /// Gets or sets the file's maximum size in megabytes (MB) to include in the file search. + /// + /// The file search maximum size mb. + [IsSetting] + public long FileSearchMaxSizeMb { get; set; } = 100; + + /// + /// Gets or sets the limit count of the history texts (filters, search texts, replace texts and directories) to be saved and retrieved to the form. + /// + [IsSetting] + public int FileSearchHistoriesLimit { get; set; } = 25; + + /// + /// Gets or sets the value whether to use auto-complete on the search dialog combo boxes. + /// + [IsSetting] + public bool AutoCompleteEnabled { get; set; } = true; + #endregion + + #region ProgramSettings + + /// + /// Gets or sets a value indicating whether to use auto-save with a specified . + /// + [IsSetting] + public bool ProgramAutoSave { get; set; } = true; + + /// + /// Gets or sets the program's automatic save interval in minutes. + /// + /// The program automatic save interval. + [IsSetting] + public int ProgramAutoSaveInterval { get; set; } = 5; + + // the current language (Culture) to be used with the software.. + private static CultureInfo _culture; + + /// + /// Gets or sets the name of the culture used with localization. + /// + /// The name of the culture used with localization. + [IsSetting] + public string CultureName { get; set; } = "en-US"; + + /// + /// Gets or sets the current language (Culture) to be used with the software's localization. + /// + public CultureInfo Culture + { + get => + _culture ?? new CultureInfo(CultureName ?? "en-US"); + + set + { + _culture = value; + CultureName = value.Name; } - #endregion - - #region PublicMethods - /// - /// Gets the color of the mark. - /// - /// The index of the mark style (0-4). - /// A color matching the given marks index. - public Color GetMarkColor(int index) + } + #endregion + + #region SaveOpenDialogSettings + /// + /// Gets or sets the initial directory for a save as dialog. + /// + [IsSetting] + public string FileLocationSaveAs { get; set; } + + /// + /// Gets or sets the initial directory for a save as HTML dialog. + /// + [IsSetting] + public string FileLocationSaveAsHtml { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog on the main form. + /// + [IsSetting] + public string FileLocationOpen { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog on the main form with encoding. + /// + [IsSetting] + public string FileLocationOpenWithEncoding { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog to open the first file for the diff form. + /// + [IsSetting] + public string FileLocationOpenDiff1 { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog to open the second file for the diff form. + /// + [IsSetting] + public string FileLocationOpenDiff2 { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog to install a plugin from the plugin management dialog. + /// + [IsSetting] + public string FileLocationOpenPlugin { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog to open a Hunspell dictionary file from the settings form. + /// + [IsSetting] + public string FileLocationOpenDictionary { get; set; } + + /// + /// Gets or sets the initial directory for an open file dialog to open a Hunspell affix file from the settings form. + /// + [IsSetting] + public string FileLocationOpenAffix { get; set; } + #endregion + + #region DateTimeSettings + + /// + /// Gets or sets the date and/or time format 1. + /// + [IsSetting] + public string DateFormat1 { get; set; } = @"yyyy'/'MM'/'dd"; // default to american.. + + /// + /// Gets or sets the date and/or time format 2. + /// + [IsSetting] + public string DateFormat2 { get; set; } = @"dd'.'MM'.'yyyy"; // default to european.. + + /// + /// Gets or sets the date and/or time format 3. + /// + [IsSetting] + public string DateFormat3 { get; set; } = @"yyyy'/'MM'/'dd hh'.'mm tt"; // default to american.. + + /// + /// Gets or sets the date and/or time format 4. + /// + [IsSetting] + public string DateFormat4 { get; set; } = @"dd'.'MM'.'yyyy HH':'mm':'ss"; // default to european.. + + /// + /// Gets or sets the date and/or time format 5. + /// + [IsSetting] + public string DateFormat5 { get; set; } = @"hh'.'mm tt"; // default to american.. + + /// + /// Gets or sets the date and/or time format 6. + /// + [IsSetting] + public string DateFormat6 { get; set; } = @"HH':'mm':'ss"; // default to european.. + + /// + /// Gets or sets a value indicating whether to use invariant culture formatting date and time via the edit menu. + /// + [IsSetting] + public bool DateFormatUseInvariantCulture { get; set; } + #endregion + + #region TextSettings + /// + /// Gets or sets a value indicating whether to use case sensitivity with text manipulation. + /// + [IsSetting] + public bool TextUpperCaseComparison { get; set; } + + /// + /// Gets or sets the type of the text comparison to use with text manipulation. + /// + [IsSetting] + public int TextComparisonType { get; set; } = 0; // 0 = invariant, 1 = current, 2 = ordinal.. + + /// + /// Gets or sets a value indicating whether to show the run snippet tool bar. + /// + /// true if to show the run snippet tool bar; otherwise, false. + [IsSetting] + public bool ShowRunSnippetToolbar { get; set; } + + /// + /// Gets the text current comparison type . + /// + public StringComparison TextCurrentComparison + { + get { - switch (index) + switch (TextComparisonType) { - case 0: return Mark1Color; - case 1: return Mark2Color; - case 2: return Mark3Color; - case 3: return Mark4Color; - case 4: return Mark5Color; - default: return SmartHighlight; + case 0: + return TextUpperCaseComparison + ? StringComparison.InvariantCulture + : StringComparison.InvariantCultureIgnoreCase; + + case 1: + return TextUpperCaseComparison + ? StringComparison.CurrentCulture + : StringComparison.CurrentCultureIgnoreCase; + + case 2: + return TextUpperCaseComparison + ? StringComparison.Ordinal + : StringComparison.OrdinalIgnoreCase; } + + return TextUpperCaseComparison + ? StringComparison.InvariantCulture + : StringComparison.InvariantCultureIgnoreCase; } + } + #endregion - /// - /// Gets the default encoding list for the settings form grid. - /// - public static string DefaultEncodingList => - new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + - new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + - Encoding.Default.WebName + ';' + false + ';' + false + '|'; - - /// - /// Gets the property value as a value tuple. - /// - /// A value tuple containing the encodings from the property. - public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - GetEncodingList() + #region PublicMethods + /// + /// Gets the color of the mark. + /// + /// The index of the mark style (0-4). + /// A color matching the given marks index. + public Color GetMarkColor(int index) + { + switch (index) { - return GetEncodingList(EncodingList); + case 0: return Mark1Color; + case 1: return Mark2Color; + case 2: return Mark3Color; + case 3: return Mark4Color; + case 4: return Mark5Color; + default: return SmartHighlight; } + } - /// - /// Gets the given string value as a value tuple containing encodings. - /// - /// A string containing a delimited list of encodings. - /// A value tuple containing the encodings from the value. - public static List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - GetEncodingList(string encodingList) - { - // create a return value.. - List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = - new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); + /// + /// Gets the default encoding list for the settings form grid. + /// + public static string DefaultEncodingList => + new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + + new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + + Encoding.Default.WebName + ';' + false + ';' + false + '|'; + + /// + /// Gets the property value as a value tuple. + /// + /// A value tuple containing the encodings from the property. + public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + GetEncodingList() + { + return GetEncodingList(EncodingList); + } - string[] encodings = encodingList.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries); - foreach (var encoding in encodings) + /// + /// Gets the given string value as a value tuple containing encodings. + /// + /// A string containing a delimited list of encodings. + /// A value tuple containing the encodings from the value. + public static List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + GetEncodingList(string encodingList) + { + // create a return value.. + List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = + new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); + + string[] encodings = encodingList.Split(new []{'|', }, StringSplitOptions.RemoveEmptyEntries); + foreach (var encoding in encodings) + { + Encoding enc; + try { - Encoding enc; - try - { - enc = Encoding.GetEncoding(encoding.Split(';')[0]); - } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - continue; - } + enc = Encoding.GetEncoding(encoding.Split(';')[0]); + } + catch (Exception ex) + { + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + continue; + } - // UTF7.. - if (enc.CodePage == 65000) - { + // UTF7.. + if (enc.CodePage == 65000) + { #pragma warning disable 618 #pragma warning disable SYSLIB0001 // Type or member is obsolete - // the UTF7 encoding is required to access legacy files.. - enc = new UTF7Encoding(bool.Parse(encoding.Split(';')[1])); + // the UTF7 encoding is required to access legacy files.. + enc = new UTF7Encoding(bool.Parse(encoding.Split(';')[1])); #pragma warning restore SYSLIB0001 // Type or member is obsolete #pragma warning restore 618 - } - - // UTF8.. - if (enc.CodePage == 65001) - { - enc = new UTF8Encoding(bool.Parse(encoding.Split(';')[2]), - bool.Parse(encoding.Split(';')[1])); - } + } - // Unicode, little/big endian.. - if (enc.CodePage == 1200 || enc.CodePage == 1201) - { - enc = new UnicodeEncoding(enc.CodePage == 1201, bool.Parse(encoding.Split(';')[2]), - bool.Parse(encoding.Split(';')[1])); - } + // UTF8.. + if (enc.CodePage == 65001) + { + enc = new UTF8Encoding(bool.Parse(encoding.Split(';')[2]), + bool.Parse(encoding.Split(';')[1])); + } - // UTF32, little/big endian.. - if (enc.CodePage == 12000 || enc.CodePage == 12001) - { - enc = new UTF32Encoding(enc.CodePage == 12001, bool.Parse(encoding.Split(';')[2]), - bool.Parse(encoding.Split(';')[1])); - } + // Unicode, little/big endian.. + if (enc.CodePage == 1200 || enc.CodePage == 1201) + { + enc = new UnicodeEncoding(enc.CodePage == 1201, bool.Parse(encoding.Split(';')[2]), + bool.Parse(encoding.Split(';')[1])); + } - // add the encoding to the return value.. - result.Add((encodingName: enc.EncodingName, encoding: enc, - unicodeFailOnInvalidChar: bool.Parse(encoding.Split(';')[1]), - unicodeBOM: bool.Parse(encoding.Split(';')[2]))); + // UTF32, little/big endian.. + if (enc.CodePage == 12000 || enc.CodePage == 12001) + { + enc = new UTF32Encoding(enc.CodePage == 12001, bool.Parse(encoding.Split(';')[2]), + bool.Parse(encoding.Split(';')[1])); } - return result; + // add the encoding to the return value.. + result.Add((encodingName: enc.EncodingName, encoding: enc, + unicodeFailOnInvalidChar: bool.Parse(encoding.Split(';')[1]), + unicodeBOM: bool.Parse(encoding.Split(';')[2]))); } - /// - /// Generates a list of value tuples containing encoding data from a given . - /// - /// - /// A list of value tuples containing the encoding information. - public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - EncodingsFromDataGrid(DataGridView dataGridView) - { - // create a return value.. - List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = - new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); + return result; + } - foreach (DataGridViewRow row in dataGridView.Rows) - { - result.Add((EncodingsFromObjects(row.Cells[0].Value, ((Encoding) row.Cells[0].Value).WebName, - row.Cells[3].Value, row.Cells[2].Value))); - } + /// + /// Generates a list of value tuples containing encoding data from a given . + /// + /// + /// A list of value tuples containing the encoding information. + public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + EncodingsFromDataGrid(DataGridView dataGridView) + { + // create a return value.. + List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = + new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); - return result; + foreach (DataGridViewRow row in dataGridView.Rows) + { + result.Add((EncodingsFromObjects(row.Cells[0].Value, ((Encoding) row.Cells[0].Value).WebName, + row.Cells[3].Value, row.Cells[2].Value))); } - /// - /// Gets an encoding data from a given parameters to be used for the form. - /// - /// An array of objects to cast into a value tuple. - /// A value tuple containing the encoding information. - public (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) - EncodingsFromObjects(params object[] objects) - { - // create a return value.. - (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) result = ( - (string) objects[1], (Encoding) objects[0], (bool) objects[2], - (bool) objects[3]); + return result; + } - return result; - } + /// + /// Gets an encoding data from a given parameters to be used for the form. + /// + /// An array of objects to cast into a value tuple. + /// A value tuple containing the encoding information. + public (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) + EncodingsFromObjects(params object[] objects) + { + // create a return value.. + (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) result = ( + (string) objects[1], (Encoding) objects[0], (bool) objects[2], + (bool) objects[3]); + + return result; + } - /// - /// Gets an encoding list formatted as a string from a given value tuple list. - /// - /// A value tuple list containing the data for the encodings. - /// A formatted string suitable to be assigned to the property value. - public string EncodingStringFromDefinitionList( - List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> encodings) + /// + /// Gets an encoding list formatted as a string from a given value tuple list. + /// + /// A value tuple list containing the data for the encodings. + /// A formatted string suitable to be assigned to the property value. + public string EncodingStringFromDefinitionList( + List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> encodings) + { + // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... + string result = string.Empty; + foreach (var encoding in encodings) { - // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... - string result = string.Empty; - foreach (var encoding in encodings) - { - result += - encoding.encodingName + ';' + encoding.unicodeFailOnInvalidChar + ';' + encoding.unicodeBOM + '|'; - } + result += + encoding.encodingName + ';' + encoding.unicodeFailOnInvalidChar + ';' + encoding.unicodeBOM + '|'; + } - return result; + return result; + } + + /// + /// Creates a directory to the local application data folder for the software. + /// + public static string DefaultDirectory(string defaultDirectory) + { + if (defaultDirectory == string.Empty) + { + return Paths.GetAppSettingsFolder(Misc.AppType.Winforms); } - /// - /// Creates a directory to the local application data folder for the software. - /// - public static string DefaultDirectory(string defaultDirectory) + // create a folder for plug-ins if it doesn't exist already.. + if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory))) { - if (defaultDirectory == string.Empty) + try { - return Paths.GetAppSettingsFolder(Misc.AppType.Winforms); + // create the folder.. + Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), + defaultDirectory)); } - - // create a folder for plug-ins if it doesn't exist already.. - if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory))) + catch (Exception ex) // a failure so do log it.. { - try - { - // create the folder.. - Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), - defaultDirectory)); - } - catch (Exception ex) // a failure so do log it.. - { - ExceptionLogger.LogError(ex); - return string.Empty; - } + ExceptionLogger.LogError(ex); + return string.Empty; } - - return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory); } - #endregion + + return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory); } -} + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/Settings/SettingsOld.cs b/ScriptNotepad/Settings/SettingsOld.cs index 7da8022a..6cb6bf90 100644 --- a/ScriptNotepad/Settings/SettingsOld.cs +++ b/ScriptNotepad/Settings/SettingsOld.cs @@ -43,1266 +43,1264 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using TabDrawMode = ScintillaNET.TabDrawMode; // (C): https://github.com/Fody/PropertyChanged, MIT license -namespace ScriptNotepad.Settings +namespace ScriptNotepad.Settings; + +/// +/// Settings for the ScriptNotepad software. +/// +/// +public class SettingsOld : INotifyPropertyChanged, IDisposable { + internal void MoveSettings(Settings settingsNew) + { + settingsNew.HistoryListAmount = HistoryListAmount; + settingsNew.CurrentLineBackground = CurrentLineBackground; + settingsNew.SmartHighlight = SmartHighlight; + settingsNew.Mark1Color = Mark1Color; + settingsNew.Mark2Color = Mark2Color; + settingsNew.Mark3Color = Mark3Color; + settingsNew.Mark4Color = Mark4Color; + settingsNew.Mark5Color = Mark5Color; + settingsNew.MarkSearchReplaceColor = MarkSearchReplaceColor; + settingsNew.BraceHighlightForegroundColor = BraceHighlightForegroundColor; + settingsNew.BraceHighlightBackgroundColor = BraceHighlightBackgroundColor; + settingsNew.BraceBadHighlightForegroundColor = BraceBadHighlightForegroundColor; +#pragma warning disable 618 + // this is for backwards compatibility.. + settingsNew.DefaultEncoding = DefaultEncoding; +#pragma warning restore 618 + settingsNew.LocalizeThread = LocalizeThread; + settingsNew.AutoDetectEncoding = AutoDetectEncoding; + settingsNew.DetectNoBom = DetectNoBom; + settingsNew.SkipUnicodeDetectLe = SkipUnicodeDetectLE; + settingsNew.SkipUnicodeDetectBe = SkipUnicodeDetectBE; + settingsNew.SkipUtf32Le = SkipUtf32LE; + settingsNew.SkipUtf32Be = SkipUtf32BE; + settingsNew.EncodingList = EncodingList; + settingsNew.EditorUseSpellChecking = EditorUseSpellChecking; + settingsNew.EditorUseSpellCheckingShellContext = EditorUseSpellCheckingShellContext; + settingsNew.EditorUseSpellCheckingNewFiles = EditorUseSpellCheckingNewFiles; + settingsNew.EditorHunspellDictionaryFile = EditorHunspellDictionaryFile; + settingsNew.EditorHunspellAffixFile = EditorHunspellAffixFile; + settingsNew.EditorSpellCheckColor = EditorSpellCheckColor; + settingsNew.EditorSpellCheckInactivity = EditorSpellCheckInactivity; + settingsNew.EditorHunspellDictionaryPath = EditorHunspellDictionaryPath; + settingsNew.EditorSpellUseCustomDictionary = EditorSpellUseCustomDictionary; + settingsNew.EditorSpellCustomDictionaryDefinitionFile = EditorSpellCustomDictionaryDefinitionFile; + settingsNew.EditorSpellCustomDictionaryInstallPath = EditorSpellCustomDictionaryInstallPath; + settingsNew.HighlightUrls = HighlightUrls; + settingsNew.StartProcessOnUrlClick = StartProcessOnUrlClick; + settingsNew.UrlTextColor = UrlTextColor; + settingsNew.UrlIndicatorColor = UrlIndicatorColor; + settingsNew.UrlIndicatorStyle = UrlIndicatorStyle; + settingsNew.UrlUseDwellToolTip = UrlUseDwellToolTip; + settingsNew.UrlDwellToolTipForegroundColor = UrlDwellToolTipForegroundColor; + settingsNew.UrlDwellToolTipBackgroundColor = UrlDwellToolTipBackgroundColor; + settingsNew.UrlDwellToolTipTime = UrlDwellToolTipTime; + settingsNew.UrlMaxLengthBeforeEllipsis = UrlMaxLengthBeforeEllipsis; + settingsNew.UrlUseAutoEllipsis = UrlUseAutoEllipsis; + settingsNew.EditorFontName = EditorFontName; + settingsNew.EditorTabWidth = EditorTabWidth; + settingsNew.EditorUseCodeIndentation = EditorUseCodeIndentation; + settingsNew.EditorSaveZoom = EditorSaveZoom; + settingsNew.EditorIndividualZoom = EditorIndividualZoom; + settingsNew.EditorFontSize = EditorFontSize; + settingsNew.EditorUseTabs = EditorUseTabs; + settingsNew.EditorIndentGuideOn = EditorIndentGuideOn; + settingsNew.EditorTabSymbol = EditorTabSymbol; + settingsNew.EditorWhiteSpaceSize = EditorWhiteSpaceSize; + settingsNew.SimulateAltGrKey = SimulateAltGrKey; + settingsNew.HighlightBraces = HighlightBraces; + settingsNew.HighlightBracesItalic = HighlightBracesItalic; + settingsNew.HighlightBracesBold = HighlightBracesBold; + settingsNew.EditorUseRtl = EditorUseRTL; + settingsNew.SimulateAltGrKeyIndex = SimulateAltGrKeyIndex; + settingsNew.NotepadPlusPlusThemePath = NotepadPlusPlusThemePath; + settingsNew.NotepadPlusPlusThemeFile = NotepadPlusPlusThemeFile; + settingsNew.UseNotepadPlusPlusTheme = UseNotepadPlusPlusTheme; + settingsNew.SearchBoxTransparency = SearchBoxTransparency; + settingsNew.SearchBoxOpacity = SearchBoxOpacity; + settingsNew.DefaultSessionLocalized = DefaultSessionLocalized; + settingsNew.UpdateAutoCheck = UpdateAutoCheck; + settingsNew.PluginFolder = PluginFolder; + settingsNew.DockSearchTreeForm = DockSearchTreeForm; + settingsNew.CategorizeStartCharacterProgrammingLanguage = CategorizeStartCharacterProgrammingLanguage; + settingsNew.SaveFileHistoryContents = SaveFileHistoryContents; + settingsNew.UseFileSystemCache = UseFileSystemCache; + settingsNew.SaveFileHistoryContentsCount = SaveFileHistoryContentsCount; + settingsNew.CurrentSession = CurrentSession; + settingsNew.FileSearchMaxSizeMb = FileSearchMaxSizeMb; + settingsNew.FileSearchHistoriesLimit = FileSearchHistoriesLimit; + settingsNew.AutoCompleteEnabled = AutoCompleteEnabled; + settingsNew.ProgramAutoSave = ProgramAutoSave; + settingsNew.ProgramAutoSaveInterval = ProgramAutoSaveInterval; + settingsNew.FileLocationSaveAs = FileLocationSaveAs; + settingsNew.FileLocationSaveAsHtml = FileLocationSaveAsHTML; + settingsNew.FileLocationOpen = FileLocationOpen; + settingsNew.FileLocationOpenWithEncoding = FileLocationOpenWithEncoding; + settingsNew.FileLocationOpenDiff1 = FileLocationOpenDiff1; + settingsNew.FileLocationOpenDiff2 = FileLocationOpenDiff2; + settingsNew.FileLocationOpenPlugin = FileLocationOpenPlugin; + settingsNew.FileLocationOpenDictionary = FileLocationOpenDictionary; + settingsNew.FileLocationOpenAffix = FileLocationOpenAffix; + settingsNew.DateFormat1 = DateFormat1; + settingsNew.DateFormat2 = DateFormat2; + settingsNew.DateFormat3 = DateFormat3; + settingsNew.DateFormat4 = DateFormat4; + settingsNew.DateFormat5 = DateFormat5; + settingsNew.DateFormat6 = DateFormat6; + settingsNew.DatabaseMigrationLevel = DatabaseMigrationLevel; + settingsNew.DateFormatUseInvariantCulture = DateFormatUseInvariantCulture; + settingsNew.TextUpperCaseComparison = TextUpperCaseComparison; + settingsNew.TextComparisonType = TextComparisonType; + } + /// - /// Settings for the ScriptNotepad software. + /// Initializes a new instance of the class. /// - /// - public class SettingsOld : INotifyPropertyChanged, IDisposable + #region HeftyConstructor + public SettingsOld() { - internal void MoveSettings(Settings settingsNew) + if (conflib == null) // don't initialize if already initialized.. { - settingsNew.HistoryListAmount = HistoryListAmount; - settingsNew.CurrentLineBackground = CurrentLineBackground; - settingsNew.SmartHighlight = SmartHighlight; - settingsNew.Mark1Color = Mark1Color; - settingsNew.Mark2Color = Mark2Color; - settingsNew.Mark3Color = Mark3Color; - settingsNew.Mark4Color = Mark4Color; - settingsNew.Mark5Color = Mark5Color; - settingsNew.MarkSearchReplaceColor = MarkSearchReplaceColor; - settingsNew.BraceHighlightForegroundColor = BraceHighlightForegroundColor; - settingsNew.BraceHighlightBackgroundColor = BraceHighlightBackgroundColor; - settingsNew.BraceBadHighlightForegroundColor = BraceBadHighlightForegroundColor; -#pragma warning disable 618 - // this is for backwards compatibility.. - settingsNew.DefaultEncoding = DefaultEncoding; -#pragma warning restore 618 - settingsNew.LocalizeThread = LocalizeThread; - settingsNew.AutoDetectEncoding = AutoDetectEncoding; - settingsNew.DetectNoBom = DetectNoBom; - settingsNew.SkipUnicodeDetectLe = SkipUnicodeDetectLE; - settingsNew.SkipUnicodeDetectBe = SkipUnicodeDetectBE; - settingsNew.SkipUtf32Le = SkipUtf32LE; - settingsNew.SkipUtf32Be = SkipUtf32BE; - settingsNew.EncodingList = EncodingList; - settingsNew.EditorUseSpellChecking = EditorUseSpellChecking; - settingsNew.EditorUseSpellCheckingShellContext = EditorUseSpellCheckingShellContext; - settingsNew.EditorUseSpellCheckingNewFiles = EditorUseSpellCheckingNewFiles; - settingsNew.EditorHunspellDictionaryFile = EditorHunspellDictionaryFile; - settingsNew.EditorHunspellAffixFile = EditorHunspellAffixFile; - settingsNew.EditorSpellCheckColor = EditorSpellCheckColor; - settingsNew.EditorSpellCheckInactivity = EditorSpellCheckInactivity; - settingsNew.EditorHunspellDictionaryPath = EditorHunspellDictionaryPath; - settingsNew.EditorSpellUseCustomDictionary = EditorSpellUseCustomDictionary; - settingsNew.EditorSpellCustomDictionaryDefinitionFile = EditorSpellCustomDictionaryDefinitionFile; - settingsNew.EditorSpellCustomDictionaryInstallPath = EditorSpellCustomDictionaryInstallPath; - settingsNew.HighlightUrls = HighlightUrls; - settingsNew.StartProcessOnUrlClick = StartProcessOnUrlClick; - settingsNew.UrlTextColor = UrlTextColor; - settingsNew.UrlIndicatorColor = UrlIndicatorColor; - settingsNew.UrlIndicatorStyle = UrlIndicatorStyle; - settingsNew.UrlUseDwellToolTip = UrlUseDwellToolTip; - settingsNew.UrlDwellToolTipForegroundColor = UrlDwellToolTipForegroundColor; - settingsNew.UrlDwellToolTipBackgroundColor = UrlDwellToolTipBackgroundColor; - settingsNew.UrlDwellToolTipTime = UrlDwellToolTipTime; - settingsNew.UrlMaxLengthBeforeEllipsis = UrlMaxLengthBeforeEllipsis; - settingsNew.UrlUseAutoEllipsis = UrlUseAutoEllipsis; - settingsNew.EditorFontName = EditorFontName; - settingsNew.EditorTabWidth = EditorTabWidth; - settingsNew.EditorUseCodeIndentation = EditorUseCodeIndentation; - settingsNew.EditorSaveZoom = EditorSaveZoom; - settingsNew.EditorIndividualZoom = EditorIndividualZoom; - settingsNew.EditorFontSize = EditorFontSize; - settingsNew.EditorUseTabs = EditorUseTabs; - settingsNew.EditorIndentGuideOn = EditorIndentGuideOn; - settingsNew.EditorTabSymbol = EditorTabSymbol; - settingsNew.EditorWhiteSpaceSize = EditorWhiteSpaceSize; - settingsNew.SimulateAltGrKey = SimulateAltGrKey; - settingsNew.HighlightBraces = HighlightBraces; - settingsNew.HighlightBracesItalic = HighlightBracesItalic; - settingsNew.HighlightBracesBold = HighlightBracesBold; - settingsNew.EditorUseRtl = EditorUseRTL; - settingsNew.SimulateAltGrKeyIndex = SimulateAltGrKeyIndex; - settingsNew.NotepadPlusPlusThemePath = NotepadPlusPlusThemePath; - settingsNew.NotepadPlusPlusThemeFile = NotepadPlusPlusThemeFile; - settingsNew.UseNotepadPlusPlusTheme = UseNotepadPlusPlusTheme; - settingsNew.SearchBoxTransparency = SearchBoxTransparency; - settingsNew.SearchBoxOpacity = SearchBoxOpacity; - settingsNew.DefaultSessionLocalized = DefaultSessionLocalized; - settingsNew.UpdateAutoCheck = UpdateAutoCheck; - settingsNew.PluginFolder = PluginFolder; - settingsNew.DockSearchTreeForm = DockSearchTreeForm; - settingsNew.CategorizeStartCharacterProgrammingLanguage = CategorizeStartCharacterProgrammingLanguage; - settingsNew.SaveFileHistoryContents = SaveFileHistoryContents; - settingsNew.UseFileSystemCache = UseFileSystemCache; - settingsNew.SaveFileHistoryContentsCount = SaveFileHistoryContentsCount; - settingsNew.CurrentSession = CurrentSession; - settingsNew.FileSearchMaxSizeMb = FileSearchMaxSizeMb; - settingsNew.FileSearchHistoriesLimit = FileSearchHistoriesLimit; - settingsNew.AutoCompleteEnabled = AutoCompleteEnabled; - settingsNew.ProgramAutoSave = ProgramAutoSave; - settingsNew.ProgramAutoSaveInterval = ProgramAutoSaveInterval; - settingsNew.FileLocationSaveAs = FileLocationSaveAs; - settingsNew.FileLocationSaveAsHtml = FileLocationSaveAsHTML; - settingsNew.FileLocationOpen = FileLocationOpen; - settingsNew.FileLocationOpenWithEncoding = FileLocationOpenWithEncoding; - settingsNew.FileLocationOpenDiff1 = FileLocationOpenDiff1; - settingsNew.FileLocationOpenDiff2 = FileLocationOpenDiff2; - settingsNew.FileLocationOpenPlugin = FileLocationOpenPlugin; - settingsNew.FileLocationOpenDictionary = FileLocationOpenDictionary; - settingsNew.FileLocationOpenAffix = FileLocationOpenAffix; - settingsNew.DateFormat1 = DateFormat1; - settingsNew.DateFormat2 = DateFormat2; - settingsNew.DateFormat3 = DateFormat3; - settingsNew.DateFormat4 = DateFormat4; - settingsNew.DateFormat5 = DateFormat5; - settingsNew.DateFormat6 = DateFormat6; - settingsNew.DatabaseMigrationLevel = DatabaseMigrationLevel; - settingsNew.DateFormatUseInvariantCulture = DateFormatUseInvariantCulture; - settingsNew.TextUpperCaseComparison = TextUpperCaseComparison; - settingsNew.TextComparisonType = TextComparisonType; + conflib = new Conflib + { + AutoCreateSettings = true, // set it to auto-create SQLite database tables.. + }; // create a new instance of the Conflib class.. } - /// - /// Initializes a new instance of the class. - /// - #region HeftyConstructor - public SettingsOld() + PropertyInfo propertyInfo = // first get the property info for the property.. + GetType().GetProperty("DefaultEncoding", BindingFlags.Instance | BindingFlags.Public); + + // get the setting attribute value of the property.. + if (propertyInfo != null) { - if (conflib == null) // don't initialize if already initialized.. + SettingAttribute settingAttribute = + (SettingAttribute) propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); + + // set the default encoding value.. +#pragma warning disable 618 +// the deprecated property is still in for backwards compatibility - so disable the warning.. + try { - conflib = new Conflib - { - AutoCreateSettings = true // set it to auto-create SQLite database tables.. - }; // create a new instance of the Conflib class.. + DefaultEncoding = Encoding.GetEncoding(conflib[settingAttribute.SettingName, DefaultEncoding.WebName]); + } + catch + { + DefaultEncoding = Encoding.Default; } +#pragma warning restore 618 - PropertyInfo propertyInfo = // first get the property info for the property.. - GetType().GetProperty("DefaultEncoding", BindingFlags.Instance | BindingFlags.Public); + // get all public instance properties of this class.. + PropertyInfo[] propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); - // get the setting attribute value of the property.. - if (propertyInfo != null) + // loop through the properties.. + // ReSharper disable once ForCanBeConvertedToForeach + for (int i = 0; i < propertyInfos.Length; i++) { - SettingAttribute settingAttribute = - (SettingAttribute) propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); - - // set the default encoding value.. -#pragma warning disable 618 -// the deprecated property is still in for backwards compatibility - so disable the warning.. - try + // a special property to which the Convert class can't be used.. + if (propertyInfos[i].Name == "DefaultEncoding") { - DefaultEncoding = Encoding.GetEncoding(conflib[settingAttribute.SettingName, DefaultEncoding.WebName]); + continue; // ..so do continue.. } - catch + + // a CultureInfo instance, which is not an auto-property.. + if (propertyInfos[i].Name == "Culture") { - DefaultEncoding = Encoding.Default; + continue; // ..so do continue.. } -#pragma warning restore 618 - - // get all public instance properties of this class.. - PropertyInfo[] propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); - // loop through the properties.. - // ReSharper disable once ForCanBeConvertedToForeach - for (int i = 0; i < propertyInfos.Length; i++) + try // avoid crashes.. { - // a special property to which the Convert class can't be used.. - if (propertyInfos[i].Name == "DefaultEncoding") + // get the SettingAttribute class instance of the property.. + settingAttribute = + (SettingAttribute) propertyInfos[i].GetCustomAttribute(typeof(SettingAttribute)); + + if (settingAttribute == null) // no null values.. { - continue; // ..so do continue.. + continue; } - // a CultureInfo instance, which is not an auto-property.. - if (propertyInfos[i].Name == "Culture") + // get the default value for the property.. + object currentValue = propertyInfos[i].GetValue(this); + + // set the value for the property using the default value as a + // fall-back value.. + + if (settingAttribute.SettingType == typeof(Color)) { - continue; // ..so do continue.. + propertyInfos[i].SetValue(this, ColorTranslator.FromHtml( + conflib[settingAttribute.SettingName, ColorTranslator.ToHtml((Color) currentValue)])); } - - try // avoid crashes.. + else { - // get the SettingAttribute class instance of the property.. - settingAttribute = - (SettingAttribute) propertyInfos[i].GetCustomAttribute(typeof(SettingAttribute)); - - if (settingAttribute == null) // no null values.. + if (currentValue == null && settingAttribute.SettingType != typeof(string)) { continue; } - // get the default value for the property.. - object currentValue = propertyInfos[i].GetValue(this); - - // set the value for the property using the default value as a - // fall-back value.. - - if (settingAttribute.SettingType == typeof(Color)) - { - propertyInfos[i].SetValue(this, ColorTranslator.FromHtml( - conflib[settingAttribute.SettingName, ColorTranslator.ToHtml((Color) currentValue)])); - } - else - { - if (currentValue == null && settingAttribute.SettingType != typeof(string)) - { - continue; - } - - propertyInfos[i].SetValue(this, - Convert.ChangeType(conflib[settingAttribute.SettingName, currentValue?.ToString()], - settingAttribute.SettingType)); - } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); + propertyInfos[i].SetValue(this, + Convert.ChangeType(conflib[settingAttribute.SettingName, currentValue?.ToString()], + settingAttribute.SettingType)); } } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + } } - - // subscribe the event handler.. - PropertyChanged += Settings_PropertyChanged; } - #endregion - #region Fields - /// - /// An instance to a Conflib class. - /// - private readonly Conflib conflib; + // subscribe the event handler.. + PropertyChanged += Settings_PropertyChanged; + } + #endregion + + #region Fields + /// + /// An instance to a Conflib class. + /// + private readonly Conflib conflib; - /// - /// Occurs when a property value changes. - /// + /// + /// Occurs when a property value changes. + /// #pragma warning disable CS0067 // disable the CS0067 as the PropertyChanged event is raised via the PropertyChanged.Fody class library.. - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; #pragma warning restore CS0067 - #endregion - - // NOTE:: - // These properties must have a default value for them to work properly with the class logic! - - #region DatabaseState - /// - /// Gets or sets the fancy-named database migration level; for now this is used for the Entity Framework conversion. - /// - /// The migration level. - [Setting("database/migrationLevel", typeof(int))] - //public int DatabaseMigrationLevel { get; set; } = 0; - public int DatabaseMigrationLevel { get; set; } = 0; // return an invalid value before the software is ready to branch merge.. - #endregion - - #region GuiSettings - /// - /// The amount of files to be saved to a document history. - /// - [Setting("gui/history", typeof(int))] - public int HistoryListAmount { get; set; } = 20; - #endregion - - #region ColorSettings - /// - /// Gets or sets the color of the current line background style. - /// - /// The color of the current line background style. - [Setting("color/currentLineBackground", typeof(Color))] - public Color CurrentLineBackground { get; set; } = Color.FromArgb(232, 232, 255); - - /// - /// Gets or sets the color of the smart highlight style. - /// - /// The color of the smart highlight style. - [Setting("color/smartHighLight", typeof(Color))] - public Color SmartHighlight { get; set; } = Color.FromArgb(0, 255, 0); - - /// - /// Gets or sets the color of the mark one style. - /// - /// The color of the mark one style. - [Setting("color/mark1", typeof(Color))] - public Color Mark1Color { get; set; } = Color.FromArgb(0, 255, 255); - - /// - /// Gets or sets the color of the mark two style. - /// - /// The color of the mark two style. - [Setting("color/mark2", typeof(Color))] - public Color Mark2Color { get; set; } = Color.FromArgb(255, 128, 0); - - /// - /// Gets or sets the color of the mark three style. - /// - /// The color of the mark three style. - [Setting("color/mark3", typeof(Color))] - public Color Mark3Color { get; set; } = Color.FromArgb(255, 255, 0); - - /// - /// Gets or sets the color of the mark four style. - /// - /// The color of the mark four style. - [Setting("color/mark4", typeof(Color))] - public Color Mark4Color { get; set; } = Color.FromArgb(128, 0, 255); - - /// - /// Gets or sets the color of the mark five style. - /// - /// The color of the mark five style. - [Setting("color/mark5", typeof(Color))] - public Color Mark5Color { get; set; } = Color.FromArgb(0, 128, 0); - - /// - /// Gets or sets the color of the mark used in the search and replace dialog. - /// - [Setting("color/markSearchReplace", typeof(Color))] - public Color MarkSearchReplaceColor { get; set; } = Color.DeepPink; - - /// - /// Gets or sets the foreground color of brace highlighting. - /// - [Setting("color/braceHighlightForeground", typeof(Color))] - public Color BraceHighlightForegroundColor { get; set; } = Color.BlueViolet; - - /// - /// Gets or sets the background color of brace highlighting. - /// - [Setting("color/braceHighlightBackground", typeof(Color))] - public Color BraceHighlightBackgroundColor { get; set; } = Color.LightGray; - - /// - /// Gets or sets the foreground color of a bad brace. - /// - [Setting("color/braceHighlightForegroundBad", typeof(Color))] - public Color BraceBadHighlightForegroundColor { get; set; } = Color.Red; - #endregion - - #region DeprecatedSettings - /// - /// Gets or sets the default encoding to be used with the files within this software. - /// - [Obsolete("DefaultEncoding is deprecated, the EncodingList property replaces this property.")] - [Setting("main/encoding", typeof(Encoding))] - public Encoding DefaultEncoding { get; set; } = Encoding.UTF8; - #endregion - - #region MainSettings - /// - /// Gets or sets a value indicating whether the thread locale should be set matching to the localization value. - /// - [Setting("main/localizeThread", typeof(bool))] - public bool LocalizeThread { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the software should try to auto-detect the encoding of a file. - /// - [Setting("main/autoDetectEncoding", typeof(bool))] - public bool AutoDetectEncoding { get; set; } = true; - - /// - /// Gets or sets a value indicating whether the software should try to detect a no-BOM unicode files. - /// - [Setting("main/detectNoBom", typeof(bool))] - public bool DetectNoBom { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the software should skip trying to detect little-endian Unicode encoding if the is enabled. - /// - [Setting("main/skipUnicodeLE", typeof(bool))] - // ReSharper disable once InconsistentNaming - public bool SkipUnicodeDetectLE { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the software should skip trying to detect big-endian Unicode encoding if the is enabled. - /// - [Setting("main/skipUnicodeBE", typeof(bool))] - // ReSharper disable once InconsistentNaming - public bool SkipUnicodeDetectBE { get; set; } = false; + #endregion + + // NOTE:: + // These properties must have a default value for them to work properly with the class logic! + + #region DatabaseState + /// + /// Gets or sets the fancy-named database migration level; for now this is used for the Entity Framework conversion. + /// + /// The migration level. + [Setting("database/migrationLevel", typeof(int))] + //public int DatabaseMigrationLevel { get; set; } = 0; + public int DatabaseMigrationLevel { get; set; } = 0; // return an invalid value before the software is ready to branch merge.. + #endregion + + #region GuiSettings + /// + /// The amount of files to be saved to a document history. + /// + [Setting("gui/history", typeof(int))] + public int HistoryListAmount { get; set; } = 20; + #endregion + + #region ColorSettings + /// + /// Gets or sets the color of the current line background style. + /// + /// The color of the current line background style. + [Setting("color/currentLineBackground", typeof(Color))] + public Color CurrentLineBackground { get; set; } = Color.FromArgb(232, 232, 255); + + /// + /// Gets or sets the color of the smart highlight style. + /// + /// The color of the smart highlight style. + [Setting("color/smartHighLight", typeof(Color))] + public Color SmartHighlight { get; set; } = Color.FromArgb(0, 255, 0); + + /// + /// Gets or sets the color of the mark one style. + /// + /// The color of the mark one style. + [Setting("color/mark1", typeof(Color))] + public Color Mark1Color { get; set; } = Color.FromArgb(0, 255, 255); + + /// + /// Gets or sets the color of the mark two style. + /// + /// The color of the mark two style. + [Setting("color/mark2", typeof(Color))] + public Color Mark2Color { get; set; } = Color.FromArgb(255, 128, 0); + + /// + /// Gets or sets the color of the mark three style. + /// + /// The color of the mark three style. + [Setting("color/mark3", typeof(Color))] + public Color Mark3Color { get; set; } = Color.FromArgb(255, 255, 0); + + /// + /// Gets or sets the color of the mark four style. + /// + /// The color of the mark four style. + [Setting("color/mark4", typeof(Color))] + public Color Mark4Color { get; set; } = Color.FromArgb(128, 0, 255); + + /// + /// Gets or sets the color of the mark five style. + /// + /// The color of the mark five style. + [Setting("color/mark5", typeof(Color))] + public Color Mark5Color { get; set; } = Color.FromArgb(0, 128, 0); + + /// + /// Gets or sets the color of the mark used in the search and replace dialog. + /// + [Setting("color/markSearchReplace", typeof(Color))] + public Color MarkSearchReplaceColor { get; set; } = Color.DeepPink; + + /// + /// Gets or sets the foreground color of brace highlighting. + /// + [Setting("color/braceHighlightForeground", typeof(Color))] + public Color BraceHighlightForegroundColor { get; set; } = Color.BlueViolet; + + /// + /// Gets or sets the background color of brace highlighting. + /// + [Setting("color/braceHighlightBackground", typeof(Color))] + public Color BraceHighlightBackgroundColor { get; set; } = Color.LightGray; + + /// + /// Gets or sets the foreground color of a bad brace. + /// + [Setting("color/braceHighlightForegroundBad", typeof(Color))] + public Color BraceBadHighlightForegroundColor { get; set; } = Color.Red; + #endregion + + #region DeprecatedSettings + /// + /// Gets or sets the default encoding to be used with the files within this software. + /// + [Obsolete("DefaultEncoding is deprecated, the EncodingList property replaces this property.")] + [Setting("main/encoding", typeof(Encoding))] + public Encoding DefaultEncoding { get; set; } = Encoding.UTF8; + #endregion + + #region MainSettings + /// + /// Gets or sets a value indicating whether the thread locale should be set matching to the localization value. + /// + [Setting("main/localizeThread", typeof(bool))] + public bool LocalizeThread { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the software should try to auto-detect the encoding of a file. + /// + [Setting("main/autoDetectEncoding", typeof(bool))] + public bool AutoDetectEncoding { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the software should try to detect a no-BOM unicode files. + /// + [Setting("main/detectNoBom", typeof(bool))] + public bool DetectNoBom { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the software should skip trying to detect little-endian Unicode encoding if the is enabled. + /// + [Setting("main/skipUnicodeLE", typeof(bool))] + // ReSharper disable once InconsistentNaming + public bool SkipUnicodeDetectLE { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the software should skip trying to detect big-endian Unicode encoding if the is enabled. + /// + [Setting("main/skipUnicodeBE", typeof(bool))] + // ReSharper disable once InconsistentNaming + public bool SkipUnicodeDetectBE { get; set; } = false; - /// - /// Gets or sets a value indicating whether the software should skip trying to detect little-endian UTF32 encoding if the is enabled. - /// - [Setting("main/skipUtf32LE", typeof(bool))] - // ReSharper disable once InconsistentNaming - public bool SkipUtf32LE { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the software should skip trying to detect big-endian UTF32 encoding if the is enabled. - /// - [Setting("main/skipUtf32BE", typeof(bool))] - // ReSharper disable once InconsistentNaming - public bool SkipUtf32BE { get; set; } = false; - - // a field to hold the EncodingList property value.. - private string encodingList = string.Empty; - - /// - /// Gets or sets an ordered encoding list for the software to try in the order. - /// - [Setting("main/encodingList", typeof(string))] - public string EncodingList + /// + /// Gets or sets a value indicating whether the software should skip trying to detect little-endian UTF32 encoding if the is enabled. + /// + [Setting("main/skipUtf32LE", typeof(bool))] + // ReSharper disable once InconsistentNaming + public bool SkipUtf32LE { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the software should skip trying to detect big-endian UTF32 encoding if the is enabled. + /// + [Setting("main/skipUtf32BE", typeof(bool))] + // ReSharper disable once InconsistentNaming + public bool SkipUtf32BE { get; set; } = false; + + // a field to hold the EncodingList property value.. + private string encodingList = string.Empty; + + /// + /// Gets or sets an ordered encoding list for the software to try in the order. + /// + [Setting("main/encodingList", typeof(string))] + public string EncodingList + { + // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... + get { - // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... - get + // if empty; create a list of one item.. + if (encodingList == string.Empty) { - // if empty; create a list of one item.. - if (encodingList == string.Empty) - { // the deprecated property is still in for backwards compatibility - so disable the warning.. #pragma warning disable 618 - encodingList = - new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + - new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + - (DefaultEncoding.WebName == new UTF8Encoding().WebName - ? Encoding.Default.WebName - : DefaultEncoding.WebName) + ';' + false + ';' + false + '|'; + encodingList = + new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + + new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + + (DefaultEncoding.WebName == new UTF8Encoding().WebName + ? Encoding.Default.WebName + : DefaultEncoding.WebName) + ';' + false + ';' + false + '|'; #pragma warning restore 618 - } + } - return encodingList; - } - set => encodingList = value; - } - #endregion - - #region EditorSpell - /// - /// Gets or sets a value indicating whether the spell checking is enabled for the document. - /// - [Setting("editorSpell/useSpellChecking", typeof(bool))] - public bool EditorUseSpellChecking { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the spell checking is enabled for the document when opening a file via the shell context menu. - /// - [Setting("editorSpell/editorUseSpellCheckingShellContext", typeof(bool))] - public bool EditorUseSpellCheckingShellContext { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the spell checking is enabled for the document for new files. - /// - [Setting("editorSpell/useSpellCheckingOnNew", typeof(bool))] - public bool EditorUseSpellCheckingNewFiles { get; set; } = false; - - /// - /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. - /// - [Setting("editorSpell/dictionaryFile", typeof(string))] - public string EditorHunspellDictionaryFile { get; set; } = string.Empty; - - /// - /// Gets or sets a value of the Hunspell affix file to be used with spell checking for the document. - /// - [Setting("editorSpell/affixFile", typeof(string))] - public string EditorHunspellAffixFile { get; set; } = string.Empty; - - /// - /// Gets or sets the color of the spell check mark. - /// - [Setting("editorSpell/markColor", typeof(Color))] - public Color EditorSpellCheckColor { get; set; } = Color.Red; - - /// - /// Gets or sets the color of the spell check mark. - /// - [Setting("editorSpell/SpellRecheckAfterInactivity", typeof(int))] - public int EditorSpellCheckInactivity { get; set; } = 500; // set the default to 500 milliseconds.. - - /// - /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. - /// - [Setting("editorSpell/dictionaryPath", typeof(string))] - public string EditorHunspellDictionaryPath { get; set; } = DefaultDirectory("Dictionaries"); - - /// - /// Gets or sets a value indicating whether the spell checker should use a custom dictionary (an external assembly) for the spell checking. - /// - [Setting("editorSpell/useCustomDictionary", typeof(bool))] - public bool EditorSpellUseCustomDictionary { get; set; } - - /// - /// Gets or sets the editor spell custom dictionary (an external assembly) definition file. - /// - [Setting("editorSpell/customDictionaryDefinitionFile", typeof(string))] - public string EditorSpellCustomDictionaryDefinitionFile { get; set; } - - /// - /// Gets or sets the editor spell custom dictionary install path. - /// - [Setting("editorSpell/customDictionaryInstallPath", typeof(string))] - public string EditorSpellCustomDictionaryInstallPath { get; set; } = - FormSettings.CreateDefaultCustomDictionaryDirectory(); - #endregion - - #region UrlDetection - /// - /// Gets or sets a value indicating whether to highlight URLs within the control. - /// - [Setting("editorUrls/highlightUrls", typeof(bool))] - public bool HighlightUrls { get; set; } = true; - - /// - /// Gets or sets a value indicating whether to start an associated program on clicking a highlighted URL. - /// - [Setting("editorUrls/startProcessOnUrlClick", typeof(bool))] - public bool StartProcessOnUrlClick { get; set; } = true; - - /// - /// Gets or sets the color of the URL text. - /// - [Setting("editorUrls/textColor", typeof(Color))] - public Color UrlTextColor { get; set; } = Color.Blue; - - /// - /// Gets or sets the color of the URL indicator. - /// - [Setting("editorUrls/indicatorColor", typeof(Color))] - public Color UrlIndicatorColor { get; set; } = Color.Blue; - - /// - /// Gets or sets the URL indicator style. - /// - [Setting("editorUrls/indicatorStyle", typeof(int))] - public int UrlIndicatorStyle { get; set; } = (int) IndicatorStyle.Plain; - - /// - /// Gets or sets a value indicating whether to use a dwell tool tip on URLs. - /// - [Setting("editorUrls/useDwellToolTip", typeof(bool))] - public bool UrlUseDwellToolTip { get; set; } = true; - - /// - /// Gets or sets the foreground color to be used with the URL tool tips. - /// - [Setting("editorUrls/dwellToolTipForegroundColor", typeof(Color))] - public Color UrlDwellToolTipForegroundColor { get; set; } = SystemColors.InfoText; - - /// - /// Gets or sets the background color to be used with the URL tool tips. - /// - [Setting("editorUrls/dwellToolTipBackgroundColor", typeof(Color))] - public Color UrlDwellToolTipBackgroundColor { get; set; } = SystemColors.Info; - - /// - /// Gets or sets the foreground color to be used with the URL tool tips. - /// - [Setting("editorUrls/dwellToolTipTime", typeof(int))] - public int UrlDwellToolTipTime { get; set; } = 400; - - /// - /// Gets or sets the URL maximum length before the use of an ellipsis to shorten it. - /// - [Setting("editorUrls/autoEllipsisMaxLength", typeof(int))] - public int UrlMaxLengthBeforeEllipsis { get; set; } = 60; - - /// - /// Gets or sets a value indicating whether to use automatic ellipsis on long URLs. - /// - [Setting("editorUrls/useAutoEllipsis", typeof(bool))] - public bool UrlUseAutoEllipsis { get; set; } = true; - #endregion - - #region Editor - /// - /// Gets or sets the font for the control. - /// - [Setting("editor/fontName", typeof(string))] - // ReSharper disable once StringLiteralTypo - public string EditorFontName { get; set; } = @"Consolas"; - - /// - /// Gets or sets the tab width for the control. - /// - [Setting("editor/tabWidth", typeof(int))] - public int EditorTabWidth { get; set; } = 4; + return encodingList; + } + set => encodingList = value; + } + #endregion + + #region EditorSpell + /// + /// Gets or sets a value indicating whether the spell checking is enabled for the document. + /// + [Setting("editorSpell/useSpellChecking", typeof(bool))] + public bool EditorUseSpellChecking { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the spell checking is enabled for the document when opening a file via the shell context menu. + /// + [Setting("editorSpell/editorUseSpellCheckingShellContext", typeof(bool))] + public bool EditorUseSpellCheckingShellContext { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the spell checking is enabled for the document for new files. + /// + [Setting("editorSpell/useSpellCheckingOnNew", typeof(bool))] + public bool EditorUseSpellCheckingNewFiles { get; set; } = false; + + /// + /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. + /// + [Setting("editorSpell/dictionaryFile", typeof(string))] + public string EditorHunspellDictionaryFile { get; set; } = string.Empty; + + /// + /// Gets or sets a value of the Hunspell affix file to be used with spell checking for the document. + /// + [Setting("editorSpell/affixFile", typeof(string))] + public string EditorHunspellAffixFile { get; set; } = string.Empty; + + /// + /// Gets or sets the color of the spell check mark. + /// + [Setting("editorSpell/markColor", typeof(Color))] + public Color EditorSpellCheckColor { get; set; } = Color.Red; + + /// + /// Gets or sets the color of the spell check mark. + /// + [Setting("editorSpell/SpellRecheckAfterInactivity", typeof(int))] + public int EditorSpellCheckInactivity { get; set; } = 500; // set the default to 500 milliseconds.. + + /// + /// Gets or sets a value of the Hunspell dictionary file to be used with spell checking for the document. + /// + [Setting("editorSpell/dictionaryPath", typeof(string))] + public string EditorHunspellDictionaryPath { get; set; } = DefaultDirectory("Dictionaries"); + + /// + /// Gets or sets a value indicating whether the spell checker should use a custom dictionary (an external assembly) for the spell checking. + /// + [Setting("editorSpell/useCustomDictionary", typeof(bool))] + public bool EditorSpellUseCustomDictionary { get; set; } + + /// + /// Gets or sets the editor spell custom dictionary (an external assembly) definition file. + /// + [Setting("editorSpell/customDictionaryDefinitionFile", typeof(string))] + public string EditorSpellCustomDictionaryDefinitionFile { get; set; } + + /// + /// Gets or sets the editor spell custom dictionary install path. + /// + [Setting("editorSpell/customDictionaryInstallPath", typeof(string))] + public string EditorSpellCustomDictionaryInstallPath { get; set; } = + FormSettings.CreateDefaultCustomDictionaryDirectory(); + #endregion + + #region UrlDetection + /// + /// Gets or sets a value indicating whether to highlight URLs within the control. + /// + [Setting("editorUrls/highlightUrls", typeof(bool))] + public bool HighlightUrls { get; set; } = true; + + /// + /// Gets or sets a value indicating whether to start an associated program on clicking a highlighted URL. + /// + [Setting("editorUrls/startProcessOnUrlClick", typeof(bool))] + public bool StartProcessOnUrlClick { get; set; } = true; + + /// + /// Gets or sets the color of the URL text. + /// + [Setting("editorUrls/textColor", typeof(Color))] + public Color UrlTextColor { get; set; } = Color.Blue; + + /// + /// Gets or sets the color of the URL indicator. + /// + [Setting("editorUrls/indicatorColor", typeof(Color))] + public Color UrlIndicatorColor { get; set; } = Color.Blue; + + /// + /// Gets or sets the URL indicator style. + /// + [Setting("editorUrls/indicatorStyle", typeof(int))] + public int UrlIndicatorStyle { get; set; } = (int) IndicatorStyle.Plain; + + /// + /// Gets or sets a value indicating whether to use a dwell tool tip on URLs. + /// + [Setting("editorUrls/useDwellToolTip", typeof(bool))] + public bool UrlUseDwellToolTip { get; set; } = true; + + /// + /// Gets or sets the foreground color to be used with the URL tool tips. + /// + [Setting("editorUrls/dwellToolTipForegroundColor", typeof(Color))] + public Color UrlDwellToolTipForegroundColor { get; set; } = SystemColors.InfoText; + + /// + /// Gets or sets the background color to be used with the URL tool tips. + /// + [Setting("editorUrls/dwellToolTipBackgroundColor", typeof(Color))] + public Color UrlDwellToolTipBackgroundColor { get; set; } = SystemColors.Info; + + /// + /// Gets or sets the foreground color to be used with the URL tool tips. + /// + [Setting("editorUrls/dwellToolTipTime", typeof(int))] + public int UrlDwellToolTipTime { get; set; } = 400; + + /// + /// Gets or sets the URL maximum length before the use of an ellipsis to shorten it. + /// + [Setting("editorUrls/autoEllipsisMaxLength", typeof(int))] + public int UrlMaxLengthBeforeEllipsis { get; set; } = 60; + + /// + /// Gets or sets a value indicating whether to use automatic ellipsis on long URLs. + /// + [Setting("editorUrls/useAutoEllipsis", typeof(bool))] + public bool UrlUseAutoEllipsis { get; set; } = true; + #endregion + + #region Editor + /// + /// Gets or sets the font for the control. + /// + [Setting("editor/fontName", typeof(string))] + // ReSharper disable once StringLiteralTypo + public string EditorFontName { get; set; } = @"Consolas"; + + /// + /// Gets or sets the tab width for the control. + /// + [Setting("editor/tabWidth", typeof(int))] + public int EditorTabWidth { get; set; } = 4; - /// - /// Gets or sets a value indicating whether to use code indentation with the control. - /// - [Setting("editor/useCodeIndentation", typeof(bool))] - public bool EditorUseCodeIndentation { get; set; } - - /// - /// Gets or sets a value indicating whether the zoom value of the document should be to the database. - /// - [Setting("editor/saveZoom", typeof(bool))] - public bool EditorSaveZoom { get; set; } = true; - - /// - /// Gets or sets a value indicating whether the zoom value should be individual for all the open documents. - /// - [Setting("editor/individualZoom", typeof(bool))] - public bool EditorIndividualZoom { get; set; } = true; - - /// - /// Gets or sets the size of the font used in the control. - /// - [Setting("editor/fontSize", typeof(int))] - public int EditorFontSize { get; set; } = 10; - - /// - /// Gets or sets a value indicating whether the editor should use tabs. - /// - [Setting("editor/useTabs", typeof(bool))] - public bool EditorUseTabs { get; set; } = true; - - /// - /// Gets or sets a value indicating whether the editor indent guide is enabled. - /// - [Setting("editor/indentGuideOn", typeof(bool))] - public bool EditorIndentGuideOn { get; set; } = true; - - /// - /// Gets or sets a value of the tab character symbol type. - /// - [Setting("editor/tabSymbol", typeof(int))] - public int EditorTabSymbol { get; set; } = (int)TabDrawMode.LongArrow; - - /// - /// Gets or sets the size of the editor white space in points. - /// - [Setting("editor/whiteSpaceSize", typeof(int))] - public int EditorWhiteSpaceSize { get; set; } = 1; - - /// - /// Gets or sets a value indicating whether the main window should capture some key combinations to simulate an AltGr+Key press for the active editor . - /// - [Setting("editor/simulateAltGrKey", typeof(bool))] - public bool SimulateAltGrKey { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the editor () should highlight braces. - /// - [Setting("editor/highlightBraces", typeof(bool))] - public bool HighlightBraces { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the editor () should use italic font style when highlighting braces. - /// - [Setting("editor/highlightBracesItalic", typeof(bool))] - public bool HighlightBracesItalic { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the editor () should use bold font style when highlighting braces. - /// - [Setting("editor/highlightBracesBold", typeof(bool))] - public bool HighlightBracesBold { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the editor should use RTL (Right-to-left) script with the controls. - /// - [Setting("editor/useRTL", typeof(bool))] - // ReSharper disable once InconsistentNaming - public bool EditorUseRTL { get; set; } = false; - - /// - /// Gets or sets the index of the type of simulation of an AltGr+Key press for the active editor . - /// - [Setting("editor/simulateAltGrKeyIndex", typeof(int))] - public int SimulateAltGrKeyIndex { get; set; } = -1; - #endregion - - #region Styles - /// - /// Gets or sets a value for the Notepad++ theme definition files for the document. - /// - [Setting("style/notepadPlusPlusThemePath", typeof(string))] - public string NotepadPlusPlusThemePath { get; set; } = DefaultDirectory("Notepad-plus-plus-themes"); - - /// - /// Gets or sets a value for the Notepad++ theme definition file name for the document. - /// - [Setting("style/notepadPlusPlusThemeFile", typeof(string))] - public string NotepadPlusPlusThemeFile { get; set; } = string.Empty; - - /// - /// Gets or sets a value indicating whether to use a style definition file from the Notepad++ software. - /// - [Setting("style/useNotepadPlusPlusTheme", typeof(bool))] - public bool UseNotepadPlusPlusTheme { get; set; } = false; - #endregion - - #region MiscSettings - /// - /// Gets or sets a value indicating whether search and replace dialog should be transparent. - /// - [Setting("misc/searchBoxTransparency", typeof(int))] - public int SearchBoxTransparency { get; set; } = 1; // 0 = false, 1 = false when inactive, 2 = always.. - - /// - /// Gets or sets a value of opacity of the form. - /// - [Setting("misc/searchBoxOpacity", typeof(double))] - public double SearchBoxOpacity { get; set; } = 0.8; - - /// - /// Gets or sets a value indicating whether the default session name has been localized. - /// - [Setting("misc/currentSessionLocalized", typeof(bool))] - public bool DefaultSessionLocalized { get; set; } = false; - - /// - /// Gets or sets a value indicating whether the software should check for updates upon startup. - /// - [Setting("misc/updateAutoCheck", typeof(bool))] - public bool UpdateAutoCheck { get; set; } = false; - - /// - /// Gets or sets the plug-in folder for the software. - /// - [Setting("misc/pluginFolder", typeof(string))] - public string PluginFolder { get; set; } = FormSettings.CreateDefaultPluginDirectory(); - - /// - /// Gets or sets a value indicating whether the search three form should be an independent form or a docked control to the main form. - /// - [Setting("misc/dockSearchTree", typeof(bool))] - public bool DockSearchTreeForm { get; set; } = true; - - /// - /// Gets or sets a value indicating whether tp categorize the programming language menu with the language name starting character. - /// - [Setting("misc/categorizeStartCharacterProgrammingLanguage", typeof(bool))] - public bool CategorizeStartCharacterProgrammingLanguage { get; set; } = true; - #endregion - - #region DataSettings - /// - /// Gets or sets a value indicating whether save closed file contents to database as history. - /// - [Setting("database/historyContents", typeof(bool))] - public bool SaveFileHistoryContents { get; set; } = true; - - /// - /// Gets or sets a value indicating whether to use file system to cache the contents of the files. Otherwise the database is used. - /// - [Setting("database/useFileSystemCache", typeof(bool))] - public bool UseFileSystemCache { get; set; } = false; - - /// - /// Gets or sets the save file history contents count. - /// - [Setting("database/historyContentsCount", typeof(int))] - public int SaveFileHistoryContentsCount { get; set; } = 100; - - /// - /// Gets or sets the current session (for the documents). - /// - [Setting("database/currentSession", typeof(string))] - private string CurrentSession { get; set; } = "Default"; - - /// - /// Gets the current session entity. - /// - public FileSession CurrentSessionEntity - { - get - { - var defaultSessionName = DBLangEngine.GetStatMessage("msgDefaultSessionName", - "Default|A name of the default session for the documents"); + /// + /// Gets or sets a value indicating whether to use code indentation with the control. + /// + [Setting("editor/useCodeIndentation", typeof(bool))] + public bool EditorUseCodeIndentation { get; set; } - var session = - ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => f.Id == 1); + /// + /// Gets or sets a value indicating whether the zoom value of the document should be to the database. + /// + [Setting("editor/saveZoom", typeof(bool))] + public bool EditorSaveZoom { get; set; } = true; - if (session != null) - { - if (session.SessionName != defaultSessionName) - { - session.SessionName = defaultSessionName; - } - } + /// + /// Gets or sets a value indicating whether the zoom value should be individual for all the open documents. + /// + [Setting("editor/individualZoom", typeof(bool))] + public bool EditorIndividualZoom { get; set; } = true; - return session; - } + /// + /// Gets or sets the size of the font used in the control. + /// + [Setting("editor/fontSize", typeof(int))] + public int EditorFontSize { get; set; } = 10; - set => CurrentSession = value.SessionName; - } - #endregion - - #region SearchSettings - /// - /// Gets or sets the file's maximum size in megabytes (MB) to include in the file search. - /// - /// The file search maximum size mb. - [Setting("search/fileSysFileMaxSizeMB", typeof(long))] - public long FileSearchMaxSizeMb { get; set; } = 100; - - /// - /// Gets or sets the limit count of the history texts (filters, search texts, replace texts and directories) to be saved and retrieved to the form. - /// - [Setting("search/commonHistoryLimit", typeof(int))] - public int FileSearchHistoriesLimit { get; set; } = 25; - - /// - /// Gets or sets the value whether to use auto-complete on the search dialog combo boxes. - /// - [Setting("search/autoCompleteEnabled", typeof(bool))] - public bool AutoCompleteEnabled { get; set; } = true; - #endregion - - #region ProgramSettings - /// - /// Gets or sets a value indicating whether to use auto-save with a specified . - /// - [Setting("program/autoSave", typeof(bool))] - public bool ProgramAutoSave { get; set; } = true; - - /// - /// Gets or sets the program's automatic save interval in minutes. - /// - /// The program automatic save interval. - [Setting("program/autoSaveInterval", typeof(int))] - public int ProgramAutoSaveInterval { get; set; } = 5; - - // the current language (Culture) to be used with the software.. - // ReSharper disable once InconsistentNaming - private static CultureInfo culture; - - /// - /// Gets or sets the current language (Culture) to be used with the software's localization. - /// - [DoNotNotify] - public CultureInfo Culture - { - get => - culture ?? new CultureInfo(conflib["language/culture", "en-US"]); + /// + /// Gets or sets a value indicating whether the editor should use tabs. + /// + [Setting("editor/useTabs", typeof(bool))] + public bool EditorUseTabs { get; set; } = true; - set - { - culture = value; - conflib["language/culture"] = culture.Name; - } - } - #endregion - - #region SaveOpenDialogSettings - /// - /// Gets or sets the initial directory for a save as dialog. - /// - [Setting("fileDialog/locationSaveAs", typeof(string))] - public string FileLocationSaveAs { get; set; } - - /// - /// Gets or sets the initial directory for a save as HTML dialog. - /// - [Setting("fileDialog/locationSaveAsHTML", typeof(string))] - // ReSharper disable once InconsistentNaming - public string FileLocationSaveAsHTML { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog on the main form. - /// - [Setting("fileDialog/locationOpen", typeof(string))] - public string FileLocationOpen { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog on the main form with encoding. - /// - [Setting("fileDialog/locationOpenWithEncoding", typeof(string))] - public string FileLocationOpenWithEncoding { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open the first file for the diff form. - /// - [Setting("fileDialog/locationOpenDiff1", typeof(string))] - public string FileLocationOpenDiff1 { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open the second file for the diff form. - /// - [Setting("fileDialog/locationOpenDiff2", typeof(string))] - public string FileLocationOpenDiff2 { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to install a plugin from the plugin management dialog. - /// - [Setting("fileDialog/locationOpenPlugin", typeof(string))] - public string FileLocationOpenPlugin { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open a Hunspell dictionary file from the settings form. - /// - [Setting("fileDialog/locationOpenDictionary", typeof(string))] - public string FileLocationOpenDictionary { get; set; } - - /// - /// Gets or sets the initial directory for an open file dialog to open a Hunspell affix file from the settings form. - /// - [Setting("fileDialog/locationOpenAffix", typeof(string))] - public string FileLocationOpenAffix { get; set; } - #endregion - - #region DateTimeSettings - /// - /// Gets or sets the date and/or time format 1. - /// - [Setting("dateTime/date1", typeof(string))] - public string DateFormat1 { get; set; } = "yyyy'/'MM'/'dd"; // default to american.. - - /// - /// Gets or sets the date and/or time format 2. - /// - [Setting("dateTime/date2", typeof(string))] - public string DateFormat2 { get; set; } = "dd'.'MM'.'yyyy"; // default to european.. - - /// - /// Gets or sets the date and/or time format 3. - /// - [Setting("dateTime/date3", typeof(string))] - public string DateFormat3 { get; set; } = "yyyy'/'MM'/'dd hh'.'mm tt"; // default to american.. - - /// - /// Gets or sets the date and/or time format 4. - /// - [Setting("dateTime/date4", typeof(string))] - public string DateFormat4 { get; set; } = "dd'.'MM'.'yyyy HH':'mm':'ss"; // default to european.. - - /// - /// Gets or sets the date and/or time format 5. - /// - [Setting("dateTime/date5", typeof(string))] - public string DateFormat5 { get; set; } = "hh'.'mm tt"; // default to american.. - - /// - /// Gets or sets the date and/or time format 6. - /// - [Setting("dateTime/date6", typeof(string))] - public string DateFormat6 { get; set; } = "HH':'mm':'ss"; // default to european.. - - /// - /// Gets or sets a value indicating whether to use invariant culture formatting date and time via the edit menu. - /// - [Setting("dateTime/invarianCulture", typeof(bool))] - public bool DateFormatUseInvariantCulture { get; set; } = false; // default to not use.. - #endregion - - #region TextSettings - /// - /// Gets or sets a value indicating whether to use case sensitivity with text manipulation. - /// - [Setting("text/textUpperCaseComparison", typeof(bool))] - public bool TextUpperCaseComparison { get; set; } = false; - - /// - /// Gets or sets the type of the text comparison to use with text manipulation. - /// - [Setting("text/textComparisonType", typeof(int))] - public int TextComparisonType { get; set; } = 0; // 0 = invariant, 1 = current, 2 = ordinal.. - - /// - /// Gets the text current comparison type . - /// - [DoNotNotify] - public StringComparison TextCurrentComparison + /// + /// Gets or sets a value indicating whether the editor indent guide is enabled. + /// + [Setting("editor/indentGuideOn", typeof(bool))] + public bool EditorIndentGuideOn { get; set; } = true; + + /// + /// Gets or sets a value of the tab character symbol type. + /// + [Setting("editor/tabSymbol", typeof(int))] + public int EditorTabSymbol { get; set; } = (int)TabDrawMode.LongArrow; + + /// + /// Gets or sets the size of the editor white space in points. + /// + [Setting("editor/whiteSpaceSize", typeof(int))] + public int EditorWhiteSpaceSize { get; set; } = 1; + + /// + /// Gets or sets a value indicating whether the main window should capture some key combinations to simulate an AltGr+Key press for the active editor . + /// + [Setting("editor/simulateAltGrKey", typeof(bool))] + public bool SimulateAltGrKey { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the editor () should highlight braces. + /// + [Setting("editor/highlightBraces", typeof(bool))] + public bool HighlightBraces { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the editor () should use italic font style when highlighting braces. + /// + [Setting("editor/highlightBracesItalic", typeof(bool))] + public bool HighlightBracesItalic { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the editor () should use bold font style when highlighting braces. + /// + [Setting("editor/highlightBracesBold", typeof(bool))] + public bool HighlightBracesBold { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the editor should use RTL (Right-to-left) script with the controls. + /// + [Setting("editor/useRTL", typeof(bool))] + // ReSharper disable once InconsistentNaming + public bool EditorUseRTL { get; set; } = false; + + /// + /// Gets or sets the index of the type of simulation of an AltGr+Key press for the active editor . + /// + [Setting("editor/simulateAltGrKeyIndex", typeof(int))] + public int SimulateAltGrKeyIndex { get; set; } = -1; + #endregion + + #region Styles + /// + /// Gets or sets a value for the Notepad++ theme definition files for the document. + /// + [Setting("style/notepadPlusPlusThemePath", typeof(string))] + public string NotepadPlusPlusThemePath { get; set; } = DefaultDirectory("Notepad-plus-plus-themes"); + + /// + /// Gets or sets a value for the Notepad++ theme definition file name for the document. + /// + [Setting("style/notepadPlusPlusThemeFile", typeof(string))] + public string NotepadPlusPlusThemeFile { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether to use a style definition file from the Notepad++ software. + /// + [Setting("style/useNotepadPlusPlusTheme", typeof(bool))] + public bool UseNotepadPlusPlusTheme { get; set; } = false; + #endregion + + #region MiscSettings + /// + /// Gets or sets a value indicating whether search and replace dialog should be transparent. + /// + [Setting("misc/searchBoxTransparency", typeof(int))] + public int SearchBoxTransparency { get; set; } = 1; // 0 = false, 1 = false when inactive, 2 = always.. + + /// + /// Gets or sets a value of opacity of the form. + /// + [Setting("misc/searchBoxOpacity", typeof(double))] + public double SearchBoxOpacity { get; set; } = 0.8; + + /// + /// Gets or sets a value indicating whether the default session name has been localized. + /// + [Setting("misc/currentSessionLocalized", typeof(bool))] + public bool DefaultSessionLocalized { get; set; } = false; + + /// + /// Gets or sets a value indicating whether the software should check for updates upon startup. + /// + [Setting("misc/updateAutoCheck", typeof(bool))] + public bool UpdateAutoCheck { get; set; } = false; + + /// + /// Gets or sets the plug-in folder for the software. + /// + [Setting("misc/pluginFolder", typeof(string))] + public string PluginFolder { get; set; } = FormSettings.CreateDefaultPluginDirectory(); + + /// + /// Gets or sets a value indicating whether the search three form should be an independent form or a docked control to the main form. + /// + [Setting("misc/dockSearchTree", typeof(bool))] + public bool DockSearchTreeForm { get; set; } = true; + + /// + /// Gets or sets a value indicating whether tp categorize the programming language menu with the language name starting character. + /// + [Setting("misc/categorizeStartCharacterProgrammingLanguage", typeof(bool))] + public bool CategorizeStartCharacterProgrammingLanguage { get; set; } = true; + #endregion + + #region DataSettings + /// + /// Gets or sets a value indicating whether save closed file contents to database as history. + /// + [Setting("database/historyContents", typeof(bool))] + public bool SaveFileHistoryContents { get; set; } = true; + + /// + /// Gets or sets a value indicating whether to use file system to cache the contents of the files. Otherwise the database is used. + /// + [Setting("database/useFileSystemCache", typeof(bool))] + public bool UseFileSystemCache { get; set; } = false; + + /// + /// Gets or sets the save file history contents count. + /// + [Setting("database/historyContentsCount", typeof(int))] + public int SaveFileHistoryContentsCount { get; set; } = 100; + + /// + /// Gets or sets the current session (for the documents). + /// + [Setting("database/currentSession", typeof(string))] + private string CurrentSession { get; set; } = "Default"; + + /// + /// Gets the current session entity. + /// + public FileSession CurrentSessionEntity + { + get { - get + var defaultSessionName = DBLangEngine.GetStatMessage("msgDefaultSessionName", + "Default|A name of the default session for the documents"); + + var session = + ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f => f.Id == 1); + + if (session != null) { - switch (TextComparisonType) + if (session.SessionName != defaultSessionName) { - case 0: - return TextUpperCaseComparison - ? StringComparison.InvariantCulture - : StringComparison.InvariantCultureIgnoreCase; - - case 1: - return TextUpperCaseComparison - ? StringComparison.CurrentCulture - : StringComparison.CurrentCultureIgnoreCase; - - case 2: - return TextUpperCaseComparison - ? StringComparison.Ordinal - : StringComparison.OrdinalIgnoreCase; + session.SessionName = defaultSessionName; } - - return TextUpperCaseComparison - ? StringComparison.InvariantCulture - : StringComparison.InvariantCultureIgnoreCase; } + + return session; } - #endregion - - #region Methods - /// - /// Gets the default encoding list for the settings form grid. - /// - public static string DefaultEncodingList => - new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + - new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + - Encoding.Default.WebName + ';' + false + ';' + false + '|'; - - /// - /// Gets the property value as a value tuple. - /// - /// A value tuple containing the encodings from the property. - public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - GetEncodingList() + + set => CurrentSession = value.SessionName; + } + #endregion + + #region SearchSettings + /// + /// Gets or sets the file's maximum size in megabytes (MB) to include in the file search. + /// + /// The file search maximum size mb. + [Setting("search/fileSysFileMaxSizeMB", typeof(long))] + public long FileSearchMaxSizeMb { get; set; } = 100; + + /// + /// Gets or sets the limit count of the history texts (filters, search texts, replace texts and directories) to be saved and retrieved to the form. + /// + [Setting("search/commonHistoryLimit", typeof(int))] + public int FileSearchHistoriesLimit { get; set; } = 25; + + /// + /// Gets or sets the value whether to use auto-complete on the search dialog combo boxes. + /// + [Setting("search/autoCompleteEnabled", typeof(bool))] + public bool AutoCompleteEnabled { get; set; } = true; + #endregion + + #region ProgramSettings + /// + /// Gets or sets a value indicating whether to use auto-save with a specified . + /// + [Setting("program/autoSave", typeof(bool))] + public bool ProgramAutoSave { get; set; } = true; + + /// + /// Gets or sets the program's automatic save interval in minutes. + /// + /// The program automatic save interval. + [Setting("program/autoSaveInterval", typeof(int))] + public int ProgramAutoSaveInterval { get; set; } = 5; + + // the current language (Culture) to be used with the software.. + // ReSharper disable once InconsistentNaming + private static CultureInfo culture; + + /// + /// Gets or sets the current language (Culture) to be used with the software's localization. + /// + [DoNotNotify] + public CultureInfo Culture + { + get => + culture ?? new CultureInfo(conflib["language/culture", "en-US"]); + + set { - return GetEncodingList(EncodingList); + culture = value; + conflib["language/culture"] = culture.Name; } + } + #endregion - /// - /// Gets the given string value as a value tuple containing encodings. - /// - /// A string containing a delimited list of encodings. - /// A value tuple containing the encodings from the value. - public static List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - GetEncodingList(string encodingList) - { - // create a return value.. - List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = - new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); + #region SaveOpenDialogSettings + /// + /// Gets or sets the initial directory for a save as dialog. + /// + [Setting("fileDialog/locationSaveAs", typeof(string))] + public string FileLocationSaveAs { get; set; } - string[] encodings = encodingList.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries); - foreach (var encoding in encodings) - { - Encoding enc; + /// + /// Gets or sets the initial directory for a save as HTML dialog. + /// + [Setting("fileDialog/locationSaveAsHTML", typeof(string))] + // ReSharper disable once InconsistentNaming + public string FileLocationSaveAsHTML { get; set; } - try - { - enc = Encoding.GetEncoding(encoding.Split(';')[0]); - } - catch - { - continue; - } + /// + /// Gets or sets the initial directory for an open file dialog on the main form. + /// + [Setting("fileDialog/locationOpen", typeof(string))] + public string FileLocationOpen { get; set; } - // UTF7.. - if (enc.CodePage == 65000) - { -#pragma warning disable 618 -#pragma warning disable SYSLIB0001 // Type or member is obsolete - // the UTF7 encoding is required to access legacy files.. - enc = new UTF7Encoding(bool.Parse(encoding.Split(';')[1])); -#pragma warning restore SYSLIB0001 // Type or member is obsolete -#pragma warning restore 618 - } + /// + /// Gets or sets the initial directory for an open file dialog on the main form with encoding. + /// + [Setting("fileDialog/locationOpenWithEncoding", typeof(string))] + public string FileLocationOpenWithEncoding { get; set; } - // UTF8.. - if (enc.CodePage == 65001) - { - enc = new UTF8Encoding(bool.Parse(encoding.Split(';')[2]), - bool.Parse(encoding.Split(';')[1])); - } + /// + /// Gets or sets the initial directory for an open file dialog to open the first file for the diff form. + /// + [Setting("fileDialog/locationOpenDiff1", typeof(string))] + public string FileLocationOpenDiff1 { get; set; } - // Unicode, little/big endian.. - if (enc.CodePage == 1200 || enc.CodePage == 1201) - { - enc = new UnicodeEncoding(enc.CodePage == 1201, bool.Parse(encoding.Split(';')[2]), - bool.Parse(encoding.Split(';')[1])); - } + /// + /// Gets or sets the initial directory for an open file dialog to open the second file for the diff form. + /// + [Setting("fileDialog/locationOpenDiff2", typeof(string))] + public string FileLocationOpenDiff2 { get; set; } - // UTF32, little/big endian.. - if (enc.CodePage == 12000 || enc.CodePage == 12001) - { - enc = new UTF32Encoding(enc.CodePage == 12001, bool.Parse(encoding.Split(';')[2]), - bool.Parse(encoding.Split(';')[1])); - } + /// + /// Gets or sets the initial directory for an open file dialog to install a plugin from the plugin management dialog. + /// + [Setting("fileDialog/locationOpenPlugin", typeof(string))] + public string FileLocationOpenPlugin { get; set; } - // add the encoding to the return value.. - result.Add((encodingName: enc.EncodingName, encoding: enc, - unicodeFailOnInvalidChar: bool.Parse(encoding.Split(';')[1]), - unicodeBOM: bool.Parse(encoding.Split(';')[2]))); - } + /// + /// Gets or sets the initial directory for an open file dialog to open a Hunspell dictionary file from the settings form. + /// + [Setting("fileDialog/locationOpenDictionary", typeof(string))] + public string FileLocationOpenDictionary { get; set; } - return result; - } + /// + /// Gets or sets the initial directory for an open file dialog to open a Hunspell affix file from the settings form. + /// + [Setting("fileDialog/locationOpenAffix", typeof(string))] + public string FileLocationOpenAffix { get; set; } + #endregion + + #region DateTimeSettings + /// + /// Gets or sets the date and/or time format 1. + /// + [Setting("dateTime/date1", typeof(string))] + public string DateFormat1 { get; set; } = "yyyy'/'MM'/'dd"; // default to american.. + + /// + /// Gets or sets the date and/or time format 2. + /// + [Setting("dateTime/date2", typeof(string))] + public string DateFormat2 { get; set; } = "dd'.'MM'.'yyyy"; // default to european.. + + /// + /// Gets or sets the date and/or time format 3. + /// + [Setting("dateTime/date3", typeof(string))] + public string DateFormat3 { get; set; } = "yyyy'/'MM'/'dd hh'.'mm tt"; // default to american.. + + /// + /// Gets or sets the date and/or time format 4. + /// + [Setting("dateTime/date4", typeof(string))] + public string DateFormat4 { get; set; } = "dd'.'MM'.'yyyy HH':'mm':'ss"; // default to european.. + + /// + /// Gets or sets the date and/or time format 5. + /// + [Setting("dateTime/date5", typeof(string))] + public string DateFormat5 { get; set; } = "hh'.'mm tt"; // default to american.. + + /// + /// Gets or sets the date and/or time format 6. + /// + [Setting("dateTime/date6", typeof(string))] + public string DateFormat6 { get; set; } = "HH':'mm':'ss"; // default to european.. + + /// + /// Gets or sets a value indicating whether to use invariant culture formatting date and time via the edit menu. + /// + [Setting("dateTime/invarianCulture", typeof(bool))] + public bool DateFormatUseInvariantCulture { get; set; } = false; // default to not use.. + #endregion + + #region TextSettings + /// + /// Gets or sets a value indicating whether to use case sensitivity with text manipulation. + /// + [Setting("text/textUpperCaseComparison", typeof(bool))] + public bool TextUpperCaseComparison { get; set; } = false; + + /// + /// Gets or sets the type of the text comparison to use with text manipulation. + /// + [Setting("text/textComparisonType", typeof(int))] + public int TextComparisonType { get; set; } = 0; // 0 = invariant, 1 = current, 2 = ordinal.. - /// - /// Gets an encoding data from a given parameters to be used for the form. - /// - /// An array of objects to cast into a value tuple. - /// A value tuple containing the encoding information. - public (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) - EncodingsFromObjects(params object[] objects) + /// + /// Gets the text current comparison type . + /// + [DoNotNotify] + public StringComparison TextCurrentComparison + { + get { - // create a return value.. - (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) result = ( - (string) objects[1], (Encoding) objects[0], (bool) objects[2], - (bool) objects[3]); + switch (TextComparisonType) + { + case 0: + return TextUpperCaseComparison + ? StringComparison.InvariantCulture + : StringComparison.InvariantCultureIgnoreCase; + + case 1: + return TextUpperCaseComparison + ? StringComparison.CurrentCulture + : StringComparison.CurrentCultureIgnoreCase; + + case 2: + return TextUpperCaseComparison + ? StringComparison.Ordinal + : StringComparison.OrdinalIgnoreCase; + } - return result; + return TextUpperCaseComparison + ? StringComparison.InvariantCulture + : StringComparison.InvariantCultureIgnoreCase; } + } + #endregion + + #region Methods + /// + /// Gets the default encoding list for the settings form grid. + /// + public static string DefaultEncodingList => + new UTF8Encoding().WebName + ';' + true + ';' + true + '|' + + new UTF8Encoding().WebName + ';' + true + ';' + false + '|' + + Encoding.Default.WebName + ';' + false + ';' + false + '|'; + + /// + /// Gets the property value as a value tuple. + /// + /// A value tuple containing the encodings from the property. + public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + GetEncodingList() + { + return GetEncodingList(EncodingList); + } + + /// + /// Gets the given string value as a value tuple containing encodings. + /// + /// A string containing a delimited list of encodings. + /// A value tuple containing the encodings from the value. + public static List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + GetEncodingList(string encodingList) + { + // create a return value.. + List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = + new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); - /// - /// Generates a list of value tuples containing encoding data from a given . - /// - /// - /// A list of value tuples containing the encoding information. - public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> - EncodingsFromDataGrid(DataGridView dataGridView) + string[] encodings = encodingList.Split(new []{'|', }, StringSplitOptions.RemoveEmptyEntries); + foreach (var encoding in encodings) { - // create a return value.. - List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = - new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); + Encoding enc; - foreach (DataGridViewRow row in dataGridView.Rows) + try + { + enc = Encoding.GetEncoding(encoding.Split(';')[0]); + } + catch { - result.Add((EncodingsFromObjects(row.Cells[0].Value, ((Encoding) row.Cells[0].Value).WebName, - row.Cells[3].Value, row.Cells[2].Value))); + continue; } - return result; - } + // UTF7.. + if (enc.CodePage == 65000) + { +#pragma warning disable 618 +#pragma warning disable SYSLIB0001 // Type or member is obsolete + // the UTF7 encoding is required to access legacy files.. + enc = new UTF7Encoding(bool.Parse(encoding.Split(';')[1])); +#pragma warning restore SYSLIB0001 // Type or member is obsolete +#pragma warning restore 618 + } - /// - /// Gets an encoding list formatted as a string from a given value tuple list. - /// - /// A value tuple list containing the data for the encodings. - /// A formatted string suitable to be assigned to the property value. - public string EncodingStringFromDefinitionList( - List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> encodings) - { - // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... - string result = string.Empty; - foreach (var encoding in encodings) + // UTF8.. + if (enc.CodePage == 65001) { - result += - encoding.encodingName + ';' + encoding.unicodeFailOnInvalidChar + ';' + encoding.unicodeBOM + '|'; + enc = new UTF8Encoding(bool.Parse(encoding.Split(';')[2]), + bool.Parse(encoding.Split(';')[1])); } - return result; - } + // Unicode, little/big endian.. + if (enc.CodePage == 1200 || enc.CodePage == 1201) + { + enc = new UnicodeEncoding(enc.CodePage == 1201, bool.Parse(encoding.Split(';')[2]), + bool.Parse(encoding.Split(';')[1])); + } - /// - /// Gets the color of the mark. - /// - /// The index of the mark style (0-4). - /// A color matching the given marks index. - public Color GetMarkColor(int index) - { - switch (index) + // UTF32, little/big endian.. + if (enc.CodePage == 12000 || enc.CodePage == 12001) { - case 0: return Mark1Color; - case 1: return Mark2Color; - case 2: return Mark3Color; - case 3: return Mark4Color; - case 4: return Mark5Color; - default: return SmartHighlight; + enc = new UTF32Encoding(enc.CodePage == 12001, bool.Parse(encoding.Split(';')[2]), + bool.Parse(encoding.Split(';')[1])); } + + // add the encoding to the return value.. + result.Add((encodingName: enc.EncodingName, encoding: enc, + unicodeFailOnInvalidChar: bool.Parse(encoding.Split(';')[1]), + unicodeBOM: bool.Parse(encoding.Split(';')[2]))); } - /// - /// Handles the PropertyChanged event of the Settings class instance. - /// - /// The source of the event. - /// The instance containing the event data. - private void Settings_PropertyChanged(object sender, PropertyChangedEventArgs e) + return result; + } + + /// + /// Gets an encoding data from a given parameters to be used for the form. + /// + /// An array of objects to cast into a value tuple. + /// A value tuple containing the encoding information. + public (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) + EncodingsFromObjects(params object[] objects) + { + // create a return value.. + (string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM) result = ( + (string) objects[1], (Encoding) objects[0], (bool) objects[2], + (bool) objects[3]); + + return result; + } + + /// + /// Generates a list of value tuples containing encoding data from a given . + /// + /// + /// A list of value tuples containing the encoding information. + public List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> + EncodingsFromDataGrid(DataGridView dataGridView) + { + // create a return value.. + List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> result = + new List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)>(); + + foreach (DataGridViewRow row in dataGridView.Rows) { - // NOTE:: Do use this attribute, if no notification is required from a property: [DoNotNotify] + result.Add((EncodingsFromObjects(row.Cells[0].Value, ((Encoding) row.Cells[0].Value).WebName, + row.Cells[3].Value, row.Cells[2].Value))); + } - try // just try from the beginning.. - { - PropertyInfo propertyInfo = // first get the property info for the property.. - GetType().GetProperty(e.PropertyName, BindingFlags.Instance | BindingFlags.Public); + return result; + } - // get the property value.. - object value = propertyInfo?.GetValue(this); + /// + /// Gets an encoding list formatted as a string from a given value tuple list. + /// + /// A value tuple list containing the data for the encodings. + /// A formatted string suitable to be assigned to the property value. + public string EncodingStringFromDefinitionList( + List<(string encodingName, Encoding encoding, bool unicodeFailOnInvalidChar, bool unicodeBOM)> encodings) + { + // the list type is Encoding1.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|Encoding2.WebName;FailOnErrorInCaseOfUnicode;BOMInCaseOfUnicode|... + string result = string.Empty; + foreach (var encoding in encodings) + { + result += + encoding.encodingName + ';' + encoding.unicodeFailOnInvalidChar + ';' + encoding.unicodeBOM + '|'; + } - // get the setting attribute value of the property.. - if (propertyInfo != null) - { - SettingAttribute settingAttribute = (SettingAttribute)propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); + return result; + } - if (value != null && settingAttribute != null) - { - // this is a special case, otherwise try just to use simple types.. - if (settingAttribute.SettingType == typeof(Encoding)) - { - Encoding encoding = (Encoding)value; - conflib[settingAttribute.SettingName] = encoding.WebName; - } - else if (settingAttribute.SettingType == typeof(Color)) - { - conflib[settingAttribute.SettingName] = ColorTranslator.ToHtml((Color) value); - } - else // a simple type.. - { - conflib[settingAttribute.SettingName] = value.ToString(); - } - } - } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } + /// + /// Gets the color of the mark. + /// + /// The index of the mark style (0-4). + /// A color matching the given marks index. + public Color GetMarkColor(int index) + { + switch (index) + { + case 0: return Mark1Color; + case 1: return Mark2Color; + case 2: return Mark3Color; + case 3: return Mark4Color; + case 4: return Mark5Color; + default: return SmartHighlight; } + } + + /// + /// Handles the PropertyChanged event of the Settings class instance. + /// + /// The source of the event. + /// The instance containing the event data. + private void Settings_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + // NOTE:: Do use this attribute, if no notification is required from a property: [DoNotNotify] - /// - /// Creates a directory to the local application data folder for the software. - /// - public static string DefaultDirectory(string defaultDirectory) + try // just try from the beginning.. { - if (defaultDirectory == string.Empty) - { - return Paths.GetAppSettingsFolder(Misc.AppType.Winforms); - } + PropertyInfo propertyInfo = // first get the property info for the property.. + GetType().GetProperty(e.PropertyName, BindingFlags.Instance | BindingFlags.Public); + + // get the property value.. + object value = propertyInfo?.GetValue(this); - // create a folder for plug-ins if it doesn't exist already.. - if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory))) + // get the setting attribute value of the property.. + if (propertyInfo != null) { - try - { - // create the folder.. - Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), - defaultDirectory)); - } - catch (Exception ex) // a failure so do log it.. + SettingAttribute settingAttribute = (SettingAttribute)propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); + + if (value != null && settingAttribute != null) { - ExceptionLogger.LogError(ex); - return string.Empty; + // this is a special case, otherwise try just to use simple types.. + if (settingAttribute.SettingType == typeof(Encoding)) + { + Encoding encoding = (Encoding)value; + conflib[settingAttribute.SettingName] = encoding.WebName; + } + else if (settingAttribute.SettingType == typeof(Color)) + { + conflib[settingAttribute.SettingName] = ColorTranslator.ToHtml((Color) value); + } + else // a simple type.. + { + conflib[settingAttribute.SettingName] = value.ToString(); + } } } - - return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory); } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + } + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + /// + /// Creates a directory to the local application data folder for the software. + /// + public static string DefaultDirectory(string defaultDirectory) + { + if (defaultDirectory == string.Empty) { - Dispose(true); - GC.SuppressFinalize(this); + return Paths.GetAppSettingsFolder(Misc.AppType.Winforms); } - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) + // create a folder for plug-ins if it doesn't exist already.. + if (!Directory.Exists(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory))) { - if (disposing) + try { - // unsubscribe the event handler.. - PropertyChanged -= Settings_PropertyChanged; - - // close the conflib class instance.. - conflib?.Close(); + // create the folder.. + Directory.CreateDirectory(Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), + defaultDirectory)); + } + catch (Exception ex) // a failure so do log it.. + { + ExceptionLogger.LogError(ex); + return string.Empty; } } - #endregion + + return Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), defaultDirectory); } /// - /// An attribute class for describing a setting name and it's type (VPKSoft.ConfLib). + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// - /// - [AttributeUsage(AttributeTargets.Property)] // target a property only.. - public class SettingAttribute: Attribute + public void Dispose() { - /// - /// Gets or sets the name of the setting (VPKSoft.ConfLib). - /// - public string SettingName { get; set; } - - /// - /// Gets or sets the type of the setting (VPKSoft.ConfLib). - /// - public Type SettingType { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// Name of the setting (VPKSoft.ConfLib). - /// The type of the setting (VPKSoft.ConfLib). - public SettingAttribute(string settingName, Type type) + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (disposing) { - SettingName = settingName; // save the given values.. - SettingType = type; + // unsubscribe the event handler.. + PropertyChanged -= Settings_PropertyChanged; + + // close the conflib class instance.. + conflib?.Close(); } } - + #endregion } + +/// +/// An attribute class for describing a setting name and it's type (VPKSoft.ConfLib). +/// +/// +[AttributeUsage(AttributeTargets.Property)] // target a property only.. +public class SettingAttribute: Attribute +{ + /// + /// Gets or sets the name of the setting (VPKSoft.ConfLib). + /// + public string SettingName { get; set; } + + /// + /// Gets or sets the type of the setting (VPKSoft.ConfLib). + /// + public Type SettingType { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the setting (VPKSoft.ConfLib). + /// The type of the setting (VPKSoft.ConfLib). + public SettingAttribute(string settingName, Type type) + { + SettingName = settingName; // save the given values.. + SettingType = type; + } +} \ No newline at end of file diff --git a/ScriptNotepad/Settings/XmlNotepadPlusMarks/MarkColorsHelper.cs b/ScriptNotepad/Settings/XmlNotepadPlusMarks/MarkColorsHelper.cs index b7c31722..34dce29a 100644 --- a/ScriptNotepad/Settings/XmlNotepadPlusMarks/MarkColorsHelper.cs +++ b/ScriptNotepad/Settings/XmlNotepadPlusMarks/MarkColorsHelper.cs @@ -30,80 +30,79 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.ScintillaLexers.ScintillaNotepadPlusPlus; -namespace ScriptNotepad.Settings.XmlNotepadPlusMarks +namespace ScriptNotepad.Settings.XmlNotepadPlusMarks; + +/// +/// A class to load the mark colors (highlight) from a Notepad++ style definition file. +/// Implements the +/// +/// +class MarkColorsHelper : ErrorHandlingBase { /// - /// A class to load the mark colors (highlight) from a Notepad++ style definition file. - /// Implements the + /// Gets or sets the color for smart highlight for the document. /// - /// - class MarkColorsHelper : ErrorHandlingBase + public Color SmartHighlight { get; set; } + + /// + /// Gets or sets the color for the mark one for the document. + /// + public Color Mark1Color { get; set; } + + /// + /// Gets or sets the color for the mark two for the document. + /// + public Color Mark2Color { get; set; } + + /// + /// Gets or sets the color for the mark three for the document. + /// + public Color Mark3Color { get; set; } + + /// + /// Gets or sets the color for the mark four for the document. + /// + public Color Mark4Color { get; set; } + + /// + /// Gets or sets the color for the mark five for the document. + /// + public Color Mark5Color { get; set; } + + /// + /// Gets or sets the color for the current line background. + /// + public Color CurrentLineBackground { get; set; } + + /// + /// Creates a new instance of "this" class from a Notepad++ style definition XML file. + /// + /// Name of the XML file. + /// MarkColorsHelper. + public static MarkColorsHelper FromFile(string fileName) { - /// - /// Gets or sets the color for smart highlight for the document. - /// - public Color SmartHighlight { get; set; } - - /// - /// Gets or sets the color for the mark one for the document. - /// - public Color Mark1Color { get; set; } - - /// - /// Gets or sets the color for the mark two for the document. - /// - public Color Mark2Color { get; set; } - - /// - /// Gets or sets the color for the mark three for the document. - /// - public Color Mark3Color { get; set; } - - /// - /// Gets or sets the color for the mark four for the document. - /// - public Color Mark4Color { get; set; } - - /// - /// Gets or sets the color for the mark five for the document. - /// - public Color Mark5Color { get; set; } - - /// - /// Gets or sets the color for the current line background. - /// - public Color CurrentLineBackground { get; set; } - - /// - /// Creates a new instance of "this" class from a Notepad++ style definition XML file. - /// - /// Name of the XML file. - /// MarkColorsHelper. - public static MarkColorsHelper FromFile(string fileName) + try { - try - { - var markColors = MarkColors.FromFile(fileName); - - return new MarkColorsHelper - { - SmartHighlight = markColors.SmartHighLightingBackground, - Mark1Color = markColors.MarkOneBackground, - Mark2Color = markColors.MarkTwoBackground, - Mark3Color = markColors.MarkThreeBackground, - Mark4Color = markColors.MarkFourBackground, - Mark5Color = markColors.MarkFiveBackground, - CurrentLineBackground = markColors.CurrentLineBackground - }; - } - catch (Exception ex) + var markColors = MarkColors.FromFile(fileName); + + return new MarkColorsHelper { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + SmartHighlight = markColors.SmartHighLightingBackground, + Mark1Color = markColors.MarkOneBackground, + Mark2Color = markColors.MarkTwoBackground, + Mark3Color = markColors.MarkThreeBackground, + Mark4Color = markColors.MarkFourBackground, + Mark5Color = markColors.MarkFiveBackground, + CurrentLineBackground = markColors.CurrentLineBackground, + }; + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); - // ..and return default.. - return default; - } + // ..and return default.. + return default; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Test/FormTestThingDialog.cs b/ScriptNotepad/Test/FormTestThingDialog.cs index e857e895..c3f5e815 100644 --- a/ScriptNotepad/Test/FormTestThingDialog.cs +++ b/ScriptNotepad/Test/FormTestThingDialog.cs @@ -26,20 +26,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; -namespace ScriptNotepad.Test +namespace ScriptNotepad.Test; + +/// +/// A test dialog form for various things (...). +/// +/// +public partial class FormTestThingDialog : Form { /// - /// A test dialog form for various things (...). + /// Initializes a new instance of the class. /// - /// - public partial class FormTestThingDialog : Form + public FormTestThingDialog() { - /// - /// Initializes a new instance of the class. - /// - public FormTestThingDialog() - { - InitializeComponent(); - } + InitializeComponent(); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/Test/FormTestThings.cs b/ScriptNotepad/Test/FormTestThings.cs index a201af21..ce656aa0 100644 --- a/ScriptNotepad/Test/FormTestThings.cs +++ b/ScriptNotepad/Test/FormTestThings.cs @@ -32,81 +32,80 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.TextSorting; using VPKSoft.MessageBoxExtended; -namespace ScriptNotepad.Test +namespace ScriptNotepad.Test; + +/// +/// A test form for various things (...). +/// +/// +public partial class FormTestThings : Form { /// - /// A test form for various things (...). + /// Initializes a new instance of the class. /// - /// - public partial class FormTestThings : Form + public FormTestThings() { - /// - /// Initializes a new instance of the class. - /// - public FormTestThings() - { - InitializeComponent(); - } - - private void button1_Click(object sender, EventArgs e) - { - //MessageBox.Show(FormDialogQueryEncoding.Execute().ToString()); + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + //MessageBox.Show(FormDialogQueryEncoding.Execute().ToString()); // Printing printer = new Printing(sttcMain.Documents[0].Scintilla); // printer.PrintPreview(); - } + } - private void button2_Click(object sender, EventArgs e) - { - MessageBox.Show("A very long test text".SafeSubString(0, 3)); - } + private void button2_Click(object sender, EventArgs e) + { + MessageBox.Show("A very long test text".SafeSubString(0, 3)); + } - private void button3_Click(object sender, EventArgs e) - { - MessageBox.Show(ProcessElevation.IsElevated.ToString()); - } + private void button3_Click(object sender, EventArgs e) + { + MessageBox.Show(ProcessElevation.IsElevated.ToString()); + } - private void Button4_Click(object sender, EventArgs e) - { - MessageBox.Show(Regex.Unescape(textBox1.Text)); - } + private void Button4_Click(object sender, EventArgs e) + { + MessageBox.Show(Regex.Unescape(textBox1.Text)); + } - private void Button5_Click(object sender, EventArgs e) - { - MessageBox.Show( - textBox3.Text.LastIndexOf(textBox2.Text, textBox3.TextLength - 1, textBox3.TextLength - ) - .ToString()); - } + private void Button5_Click(object sender, EventArgs e) + { + MessageBox.Show( + textBox3.Text.LastIndexOf(textBox2.Text, textBox3.TextLength - 1, textBox3.TextLength + ) + .ToString()); + } - private void TextBox2_TextChanged(object sender, EventArgs e) - { + private void TextBox2_TextChanged(object sender, EventArgs e) + { - } + } - private void Button6_Click(object sender, EventArgs e) - { - new FormDialogQuerySortTextStyle().ShowDialog(); - } + private void Button6_Click(object sender, EventArgs e) + { + new FormDialogQuerySortTextStyle().ShowDialog(); + } - private void Button7_Click(object sender, EventArgs e) - { - var data = HunspellData.FromDictionaryFile(@"C:\Files\GitHub\dictionaries\en\en_US.dic"); - MessageBox.Show(data.HunspellCulture.ToString()); + private void Button7_Click(object sender, EventArgs e) + { + var data = HunspellData.FromDictionaryFile(@"C:\Files\GitHub\dictionaries\en\en_US.dic"); + MessageBox.Show(data.HunspellCulture.ToString()); - var result = HunspellDictionaryCrawler.CrawlDirectory(@"C:\Files\GitHub\dictionaries"); - } + var result = HunspellDictionaryCrawler.CrawlDirectory(@"C:\Files\GitHub\dictionaries"); + } - private void button8_Click(object sender, EventArgs e) - { - MessageBoxExtended.Localize("fi"); + private void button8_Click(object sender, EventArgs e) + { + MessageBoxExtended.Localize("fi"); - MessageBox.Show( + MessageBox.Show( MessageBoxExtended.Show(this, "Helevetin helevetin helevetti!", "Testing..", //MessageBoxButtonsExtended.YesNo, MessageBoxButtonsExtended.YesNoYesToAllRememberNoToAllRemember, MessageBoxIcon.Hand).ToString()); - } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ApplicationHelpers/ApplicationActivateDeactivate.cs b/ScriptNotepad/UtilityClasses/ApplicationHelpers/ApplicationActivateDeactivate.cs index 8ac7edfc..f644abda 100644 --- a/ScriptNotepad/UtilityClasses/ApplicationHelpers/ApplicationActivateDeactivate.cs +++ b/ScriptNotepad/UtilityClasses/ApplicationHelpers/ApplicationActivateDeactivate.cs @@ -29,63 +29,62 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // (C)::https://www.cyotek.com/blog/how-to-be-notified-when-your-application-is-activated-and-deactivated -namespace ScriptNotepad.UtilityClasses.ApplicationHelpers +namespace ScriptNotepad.UtilityClasses.ApplicationHelpers; + +/// +/// A class containing helper methods to listen to the WM_ACTIVATEAPP WndProc message. +/// +public static class ApplicationActivateDeactivate { /// - /// A class containing helper methods to listen to the WM_ACTIVATEAPP WndProc message. + /// Occurs when the application was activated. /// - public static class ApplicationActivateDeactivate - { - /// - /// Occurs when the application was activated. - /// - public static event EventHandler ApplicationActivated; + public static event EventHandler ApplicationActivated; - /// - /// Occurs when application was deactivated. - /// - public static event EventHandler ApplicationDeactivated; + /// + /// Occurs when application was deactivated. + /// + public static event EventHandler ApplicationDeactivated; - /// - /// A message send to the WndProc when the application activates / deactivates. - /// - // ReSharper disable once InconsistentNaming - public const int WM_ACTIVATEAPP = 0x1C; + /// + /// A message send to the WndProc when the application activates / deactivates. + /// + // ReSharper disable once InconsistentNaming + public const int WM_ACTIVATEAPP = 0x1C; - /// - /// A method which can be called from within a overridden method to raise the and the events. - /// - /// The form from which WndProc method this method was called. - /// The Windows to process. - /// true if the was handled by the method, false otherwise. - public static bool WndProcApplicationActivateHelper(Form form, ref Message m) + /// + /// A method which can be called from within a overridden method to raise the and the events. + /// + /// The form from which WndProc method this method was called. + /// The Windows to process. + /// true if the was handled by the method, false otherwise. + public static bool WndProcApplicationActivateHelper(Form form, ref Message m) + { + try { - try + if (m.Msg == WM_ACTIVATEAPP) { - if (m.Msg == WM_ACTIVATEAPP) + if (m.WParam != IntPtr.Zero) { - if (m.WParam != IntPtr.Zero) - { - // the application is getting activated.. - ApplicationActivated?.Invoke(form, new EventArgs()); - } - else - { - // the application is getting deactivated.. - ApplicationDeactivated?.Invoke(form, new EventArgs()); - } - - return true; + // the application is getting activated.. + ApplicationActivated?.Invoke(form, new EventArgs()); + } + else + { + // the application is getting deactivated.. + ApplicationDeactivated?.Invoke(form, new EventArgs()); } - return false; - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - return false; + return true; } + + return false; + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); + return false; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Assembly/TestFileIsAssembly.cs b/ScriptNotepad/UtilityClasses/Assembly/TestFileIsAssembly.cs index 0960a400..868dc7ab 100644 --- a/ScriptNotepad/UtilityClasses/Assembly/TestFileIsAssembly.cs +++ b/ScriptNotepad/UtilityClasses/Assembly/TestFileIsAssembly.cs @@ -28,49 +28,48 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Reflection; // (C): https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/assemblies-gac/how-to-determine-if-a-file-is-an-assembly -namespace ScriptNotepad.UtilityClasses.Assembly +namespace ScriptNotepad.UtilityClasses.Assembly; + +/// +/// A class to test if an given file is a .NET Framework assembly. +/// +public class TestFileIsAssembly: ErrorHandlingBase { /// - /// A class to test if an given file is a .NET Framework assembly. + /// Determines whether the specified file is a .NET Framework assembly. /// - public class TestFileIsAssembly: ErrorHandlingBase + /// The name of the file to test for. + /// True if the file is an assembly; otherwise false. + public static bool IsAssembly(string fileName) { - /// - /// Determines whether the specified file is a .NET Framework assembly. - /// - /// The name of the file to test for. - /// True if the file is an assembly; otherwise false. - public static bool IsAssembly(string fileName) + try + { + AssemblyName.GetAssemblyName(fileName); + return true; + } + catch (FileNotFoundException ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; + } + catch (BadImageFormatException ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; + } + catch (FileLoadException ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; + } + catch (Exception ex) { - try - { - AssemblyName.GetAssemblyName(fileName); - return true; - } - catch (FileNotFoundException ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; - } - catch (BadImageFormatException ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; - } - catch (FileLoadException ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; - } + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Clipboard/ClipboardTextHelper.cs b/ScriptNotepad/UtilityClasses/Clipboard/ClipboardTextHelper.cs index d800a477..8ccc8376 100644 --- a/ScriptNotepad/UtilityClasses/Clipboard/ClipboardTextHelper.cs +++ b/ScriptNotepad/UtilityClasses/Clipboard/ClipboardTextHelper.cs @@ -26,31 +26,30 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.Clipboard +namespace ScriptNotepad.UtilityClasses.Clipboard; + +/// +/// A simple class to help to set clipboard text contents. +/// +public class ClipboardTextHelper: ErrorHandlingBase { /// - /// A simple class to help to set clipboard text contents. + /// Set the Clipboard's contents to a given text. /// - public class ClipboardTextHelper: ErrorHandlingBase + /// The text to set the clipboard's contents to. + /// True if the operation was successful; otherwise false. + public static bool ClipboardSetText(string text) { - /// - /// Set the Clipboard's contents to a given text. - /// - /// The text to set the clipboard's contents to. - /// True if the operation was successful; otherwise false. - public static bool ClipboardSetText(string text) + try + { + System.Windows.Forms.Clipboard.SetDataObject(text, true, 20, 150); + return true; + } + catch (Exception ex) { - try - { - System.Windows.Forms.Clipboard.SetDataObject(text, true, 20, 150); - return true; - } - catch (Exception ex) - { - // clipboard operation may fail.. - ExceptionLogAction?.Invoke(ex); - return false; - } + // clipboard operation may fail.. + ExceptionLogAction?.Invoke(ex); + return false; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerLines.cs b/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerLines.cs index 14db1e44..5d635ff4 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerLines.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerLines.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,127 +28,175 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Threading.Tasks; using VPKSoft.ErrorLogger; -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// A class to run C# script snippets a file contents as line strings with line endings. +/// +/// +public class CsCodeDomScriptRunnerLines: IScriptRunner { /// - /// A class to run C# script snippets a file contents as line strings with line endings. + /// Initializes a new instance of the class. /// - /// - public class CsCodeDomScriptRunnerLines: IScriptRunner + public CsCodeDomScriptRunnerLines() { - /// - /// Initializes a new instance of the class. - /// - public CsCodeDomScriptRunnerLines() - { - CSharpScriptBase = - string.Join(Environment.NewLine, - // ReSharper disable once StringLiteralTypo - "#region Usings", - "using System;", - "using System.Linq;", - "using System.Collections;", - "using System.Collections.Generic;", - "using System.Text;", - "using System.Text.RegularExpressions;", - "using System.Xml.Linq;", - "#endregion", - Environment.NewLine, - "public class ManipulateLineLines", - "{", - " public static string Evaluate(List fileLines)", - " {", - " string result = string.Empty;", - " // insert code here..", - " for (int i = 0; i < fileLines.Count; i++)", - " {", - " // A sample: fileLines[i] = fileLines[i]; // NOTE: Line manipulation must be added..", - " }", - string.Empty, - " result = string.Concat(fileLines); // concatenate the result lines.. ", - " return result;", - " }", - "}"); - - ScriptCode = CSharpScriptBase; - } + CSharpScriptBase = + string.Join(Environment.NewLine, + // ReSharper disable once StringLiteralTypo + "#region Usings", + "using System;", + "using System.Linq;", + "using System.Collections;", + "using System.Collections.Generic;", + "using System.Text;", + "using System.Text.RegularExpressions;", + "using System.Xml.Linq;", + "#endregion", + Environment.NewLine, + "public class ManipulateLineLines", + "{", + " public static string Evaluate(List fileLines)", + " {", + " string result = string.Empty;", + " // insert code here..", + " for (int i = 0; i < fileLines.Count; i++)", + " {", + " // A sample: fileLines[i] = fileLines[i]; // NOTE: Line manipulation must be added..", + " }", + string.Empty, + " result = string.Concat(fileLines); // concatenate the result lines.. ", + " return result;", + " }", + "}"); + + ScriptCode = CSharpScriptBase; + } - /// - /// Runs the C# script against the given lines and returns the concatenated lines as a string. - /// The line strings may contain various different line endings. - /// - /// The file lines to run the C# script against. - /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. - public async Task> ExecuteLinesAsync(List fileLines) + /// + /// Evaluates the C# script. + /// + /// The file contents to run the C# script against. + /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. + public async Task Evaluate(string fileContents) + { + try { - try + ScriptRunner = new RoslynScriptRunner(new RoslynGlobals { DataVariable = fileContents, }); + + var result = await ScriptRunner.ExecuteAsync(ScriptCode); + + if (result is Exception exceptionEvaluate) { - CompileException = null; + throw exceptionEvaluate; + } - ScriptRunner = new RoslynScriptRunner(new RoslynGlobals> {DataVariable = fileLines}); + CompileFailed = false; - await ScriptRunner.ExecuteAsync(ScriptCode); + return true; // indicate a success.. + } + catch (Exception ex) + { + CompileException = ScriptRunner?.PreviousCompileException; + CompileFailed = true; + ExceptionLogger.LogError(ex); + return false; // fail.. + } + } + + /// + /// Runs the C# script against the given lines and returns the concatenated lines as a string. + /// The line strings may contain various different line endings. + /// + /// The file lines to run the C# script against. + /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. + public async Task> ExecuteLinesAsync(List fileLines) + { + try + { + CompileException = null; - // try to run the C# script against the given file lines.. - object result = await ScriptRunner.ExecuteAsync("ManipulateLineLines.Evaluate(DataVariable)"); + ScriptRunner = new RoslynScriptRunner(new RoslynGlobals> {DataVariable = fileLines, }); - if (result is Exception exception) + var resultEvaluate = await ScriptRunner.ExecuteAsync(ScriptCode); + + if (resultEvaluate != null) + { + if (resultEvaluate is Exception exceptionEvaluate) { - throw exception; + throw exceptionEvaluate; } + } - CompileFailed = false; + // try to run the C# script against the given file lines.. + object result = await ScriptRunner.ExecuteAsync("ManipulateLineLines.Evaluate(DataVariable)"); - return new KeyValuePair(result as string, true); // indicate a success.. - } - catch (Exception ex) + if (result is Exception exception) { - CompileException = ScriptRunner?.PreviousCompileException; - CompileFailed = true; - ExceptionLogger.LogError(ex); - // fail.. - return new KeyValuePair(string.Concat(fileLines), false); + throw exception; } + + CompileFailed = false; + + return new KeyValuePair(result as string, true); // indicate a success.. } + catch (Exception ex) + { + CompileException = ScriptRunner?.PreviousCompileException; + CompileFailed = true; + ExceptionLogger.LogError(ex); + // fail.. + return new KeyValuePair(string.Concat(fileLines), false); + } + } + + /// + /// Gets or sets the C# script runner. + /// + /// The C# script runner. + public RoslynScriptRunner ScriptRunner { get; set; } - /// - /// Gets or sets the C# script runner. - /// - /// The C# script runner. - public RoslynScriptRunner ScriptRunner { get; set; } - - /// - /// Gets or sets the base "skeleton" C# code snippet for manipulating text. - /// - /// The base "skeleton" C# code snippet for manipulating text. - public string CSharpScriptBase { get; set; } - - /// - /// Gets or sets the C# script code. - /// - /// The C# script code. - public string ScriptCode { get; set; } - - /// - /// Gets or sets a value indicating whether the script compile failed. - /// - /// true if the script compile failed; otherwise, false. - public bool CompileFailed { get; set; } - - /// - /// Gets the previous compile exception. - /// - /// The previous compile exception. - public Exception CompileException { get; set; } - - /// - /// Executes the script. - /// - /// The text in some format. - /// The object containing the manipulated text if the operation was successful. - public async Task ExecuteScript(object text) + /// + /// Gets or sets the base "skeleton" C# code snippet for manipulating text. + /// + /// The base "skeleton" C# code snippet for manipulating text. + public string CSharpScriptBase { get; set; } + + private string scriptCode = string.Empty; + + /// + /// Gets or sets the C# script code. + /// + /// The C# script code. + public string ScriptCode + { + get => scriptCode; + set { - return await ExecuteLinesAsync((List) text); + scriptCode = value; + CompileFailed = !Evaluate(scriptCode).Result; } } -} + + /// + /// Gets or sets a value indicating whether the script compile failed. + /// + /// true if the script compile failed; otherwise, false. + public bool CompileFailed { get; set; } + + /// + /// Gets the previous compile exception. + /// + /// The previous compile exception. + public Exception CompileException { get; set; } + + /// + /// Executes the script. + /// + /// The text in some format. + /// The object containing the manipulated text if the operation was successful. + public async Task ExecuteScript(object text) + { + return await ExecuteLinesAsync((List) text); + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerText.cs b/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerText.cs index 2b5a454b..64fa288a 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerText.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerText.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,20 +28,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Threading.Tasks; using VPKSoft.ErrorLogger; -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// A class to run C# script snippets against the contents of a Scintilla document as text. +/// +/// +public class CsCodeDomScriptRunnerText: IScriptRunner { /// - /// A class to run C# script snippets against the contents of a Scintilla document as text. + /// Initializes a new instance of the class. /// - /// - public class CsCodeDomScriptRunnerText: IScriptRunner + public CsCodeDomScriptRunnerText() { - /// - /// Initializes a new instance of the class. - /// - public CsCodeDomScriptRunnerText() - { - CSharpScriptBase = + CSharpScriptBase = string.Join(Environment.NewLine, // ReSharper disable once StringLiteralTypo "#region Usings", @@ -64,84 +64,120 @@ public CsCodeDomScriptRunnerText() " }", "}"); - ScriptCode = CSharpScriptBase; - } + ScriptCode = CSharpScriptBase; + } - /// - /// Runs the C# script against the given string containing lines and returns the result as a string. - /// The string may contain various different line endings. - /// - /// The file contents to run the C# script against. - /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. - public async Task> ExecuteText(string fileContents) + /// + /// Evaluates the C# script. + /// + /// The file contents to run the C# script against. + /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. + public async Task Evaluate(string fileContents) + { + try { - try - { - CompileException = null; + ScriptRunner = new RoslynScriptRunner(new RoslynGlobals { DataVariable = fileContents, }); + + var result = await ScriptRunner.ExecuteAsync(ScriptCode); - ScriptRunner = new RoslynScriptRunner(new RoslynGlobals {DataVariable = fileContents}); + if (result is Exception exceptionEvaluate) + { + throw exceptionEvaluate; + } - await ScriptRunner.ExecuteAsync(ScriptCode); + CompileFailed = false; - // try to run the C# script against the given file contents.. - object result = await ScriptRunner.ExecuteAsync("ManipulateText.Evaluate(DataVariable)"); - - if (result is Exception exception) - { - throw exception; - } + return true; // indicate a success.. + } + catch (Exception ex) + { + CompileException = ScriptRunner?.PreviousCompileException; + CompileFailed = true; + ExceptionLogger.LogError(ex); + return false; // fail.. + } + } - CompileFailed = false; + /// + /// Runs the C# script against the given string containing lines and returns the result as a string. + /// The string may contain various different line endings. + /// + /// The file contents to run the C# script against. + /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. + public async Task> ExecuteText(string fileContents) + { + try + { + CompileException = null; - return new KeyValuePair(result as string, true); // indicate a success.. - } - catch (Exception ex) + // try to run the C# script against the given file contents.. + object result = await ScriptRunner.ExecuteAsync("ManipulateText.Evaluate(DataVariable)"); + + if (result is Exception exception) { - CompileException = ScriptRunner?.PreviousCompileException; - CompileFailed = true; - ExceptionLogger.LogError(ex); - return new KeyValuePair(fileContents, false); // fail.. + throw exception; } + + CompileFailed = false; + + return new KeyValuePair(result as string, true); // indicate a success.. } + catch (Exception ex) + { + CompileException = ScriptRunner?.PreviousCompileException; + CompileFailed = true; + ExceptionLogger.LogError(ex); + return new KeyValuePair(fileContents, false); // fail.. + } + } + + /// + /// Gets or sets the C# script runner. + /// + /// The C# script runner. + public RoslynScriptRunner ScriptRunner { get; set; } - /// - /// Gets or sets the C# script runner. - /// - /// The C# script runner. - public RoslynScriptRunner ScriptRunner { get; set; } - - /// - /// Gets or sets the base "skeleton" C# code snippet for manipulating text. - /// - /// The base "skeleton" C# code snippet for manipulating text. - public string CSharpScriptBase { get; set; } - - /// - /// Gets or sets the C# script code. - /// - /// The C# script code. - public string ScriptCode { get; set; } - - /// - /// Gets or sets a value indicating whether the script compile failed. - /// - /// true if the script compile failed; otherwise, false. - public bool CompileFailed { get; set; } - - /// - /// Gets the previous compile exception. - /// - /// The previous compile exception. - public Exception CompileException { get; set; } - - /// - /// Executes the script. - /// - /// The text in some format. - /// The object containing the manipulated text if the operation was successful. - public async Task ExecuteScript(object text) + /// + /// Gets or sets the base "skeleton" C# code snippet for manipulating text. + /// + /// The base "skeleton" C# code snippet for manipulating text. + public string CSharpScriptBase { get; set; } + + private string scriptCode = string.Empty; + + /// + /// Gets or sets the C# script code. + /// + /// The C# script code. + public string ScriptCode + { + get => scriptCode; + set { - return await ExecuteText((string)text); + scriptCode = value; + CompileFailed = !Evaluate(scriptCode).Result; } } -} + + /// + /// Gets or sets a value indicating whether the script compile failed. + /// + /// true if the script compile failed; otherwise, false. + public bool CompileFailed { get; set; } + + /// + /// Gets the previous compile exception. + /// + /// The previous compile exception. + public Exception CompileException { get; set; } + + /// + /// Executes the script. + /// + /// The text in some format. + /// The object containing the manipulated text if the operation was successful. + public async Task ExecuteScript(object text) + { + return await ExecuteText((string)text); + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/CsScriptRunnerText.cs b/ScriptNotepad/UtilityClasses/CodeDom/CsScriptRunnerText.cs index 8e4c5389..b342994e 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/CsScriptRunnerText.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/CsScriptRunnerText.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,62 +28,61 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Threading.Tasks; using VPKSoft.ErrorLogger; -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// A class to run C# scripts to manipulate specified text. +/// +public class CsScriptRunnerText { + // a CodeDOM provider for executing C# scripts for a list of lines.. + private static readonly CsCodeDomScriptRunnerLines ScriptRunnerLines = new (); + + // a CodeDOM provider for executing C# scripts for a string.. + private static readonly CsCodeDomScriptRunnerText ScriptRunnerText = new (); + /// - /// A class to run C# scripts to manipulate specified text. + /// Runs the script for the specified text. /// - public class CsScriptRunnerText + /// The script code. + /// The text. + /// System.Threading.Tasks.Task<System.Collections.Generic.KeyValuePair<string, bool>>. + public static async Task> RunScriptText(string code, string text) { - // a CodeDOM provider for executing C# scripts for a list of lines.. - private static readonly CsCodeDomScriptRunnerLines ScriptRunnerLines = new (); - - // a CodeDOM provider for executing C# scripts for a string.. - private static readonly CsCodeDomScriptRunnerText ScriptRunnerText = new (); - - /// - /// Runs the script for the specified text. - /// - /// The script code. - /// The text. - /// System.Threading.Tasks.Task<System.Collections.Generic.KeyValuePair<string, bool>>. - public static async Task> RunScriptText(string code, string text) + try { - try - { - ScriptRunnerText.ScriptCode = code; + ScriptRunnerText.ScriptCode = code; - // a reference to a Scintilla document was gotten so do run the code.. - return await ScriptRunnerText.ExecuteText(text); - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } - return new KeyValuePair(string.Empty, false); + // a reference to a Scintilla document was gotten so do run the code.. + return await ScriptRunnerText.ExecuteText(text); } - - /// - /// Runs the script for the specified lines. - /// - /// The code. - /// The lines. - /// System.Threading.Tasks.Task<System.Collections.Generic.KeyValuePair<string, bool>>. - public static async Task> RunScriptLines(string code, List lines) + catch (Exception ex) { - try - { - ScriptRunnerText.ScriptCode = code; + ExceptionLogger.LogError(ex); + } + return new KeyValuePair(string.Empty, false); + } - // a reference to a Scintilla document was gotten so do run the code.. - return new KeyValuePair((await ScriptRunnerLines.ExecuteScript(lines))?.ToString() ?? string.Empty, true); - } - catch (Exception ex) - { - ExceptionLogger.LogError(ex); - } + /// + /// Runs the script for the specified lines. + /// + /// The code. + /// The lines. + /// System.Threading.Tasks.Task<System.Collections.Generic.KeyValuePair<string, bool>>. + public static async Task> RunScriptLines(string code, List lines) + { + try + { + ScriptRunnerText.ScriptCode = code; - return new KeyValuePair(string.Empty, false); + // a reference to a Scintilla document was gotten so do run the code.. + return new KeyValuePair((await ScriptRunnerLines.ExecuteScript(lines))?.ToString() ?? string.Empty, true); } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); + } + + return new KeyValuePair(string.Empty, false); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/FormScript.cs b/ScriptNotepad/UtilityClasses/CodeDom/FormScript.cs index 820a7b8d..eab1d001 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/FormScript.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/FormScript.cs @@ -45,579 +45,584 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using static VPKSoft.ScintillaLexers.LexerEnumerations; using Utils = VPKSoft.LangLib.Utils; -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// A windows form tho run a C# script against a Scintilla document's contents. +/// +/// +public partial class FormScript : DBLangEngineWinforms { - /// - /// A windows form tho run a C# script against a Scintilla document's contents. - /// - /// - public partial class FormScript : DBLangEngineWinforms - { - #region PrivateFields - // a list to track the instances of this form so the changes can be delegated to each other.. - // ReSharper disable once CollectionNeverQueried.Local - private static readonly List FormScriptInstances = new List(); + #region PrivateFields + // a list to track the instances of this form so the changes can be delegated to each other.. + // ReSharper disable once CollectionNeverQueried.Local + private static readonly List FormScriptInstances = new List(); - // a CodeDOM provider for executing C# scripts for a list of lines.. - private readonly CsCodeDomScriptRunnerLines scriptRunnerLines = new CsCodeDomScriptRunnerLines(); + // a CodeDOM provider for executing C# scripts for a list of lines.. + private readonly CsCodeDomScriptRunnerLines scriptRunnerLines = new CsCodeDomScriptRunnerLines(); - // a CodeDOM provider for executing C# scripts for a string.. - private readonly CsCodeDomScriptRunnerText scriptRunnerText = new CsCodeDomScriptRunnerText(); + // a CodeDOM provider for executing C# scripts for a string.. + private readonly CsCodeDomScriptRunnerText scriptRunnerText = new CsCodeDomScriptRunnerText(); - // an indicator if the Scintilla's text changed event should be disregarded.. - private bool suspendChangedEvent; + // an indicator if the Scintilla's text changed event should be disregarded.. + private bool suspendChangedEvent; - // a field to hold localized name for a script template for manipulating Scintilla contents as text.. - private readonly string defaultNameScriptTemplateText = string.Empty; + // a field to hold localized name for a script template for manipulating Scintilla contents as text.. + private readonly string defaultNameScriptTemplateText = string.Empty; - // a field to hold localized name for a script template for manipulating Scintilla contents as lines.. - private readonly string defaultNameScriptTemplateLines = string.Empty; + // a field to hold localized name for a script template for manipulating Scintilla contents as lines.. + private readonly string defaultNameScriptTemplateLines = string.Empty; - // a field to hold the code snippet's contents for saving possibility.. - private CodeSnippet currentCodeSnippet; - #endregion + // a field to hold the code snippet's contents for saving possibility.. + private CodeSnippet currentCodeSnippet; + #endregion - #region PrivateProperties - #endregion + #region PrivateProperties + #endregion - #region MassiveConstructor - /// - /// Initializes a new instance of the class. - /// - public FormScript() - { - // Add this form to be positioned.. - PositionForms.Add(this); + #region MassiveConstructor + /// + /// Initializes a new instance of the class. + /// + public FormScript() + { + // Add this form to be positioned.. + PositionForms.Add(this); - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change.. + suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change.. - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - // localize the script type default names.. - defaultNameScriptTemplateText = - DBLangEngine.GetMessage("msgDefaultScriptSnippetText", "A text script snippet|As in a script for manipulating Scintilla contents as text"); + // localize the script type default names.. + defaultNameScriptTemplateText = + DBLangEngine.GetMessage("msgDefaultScriptSnippetText", "A text script snippet|As in a script for manipulating Scintilla contents as text"); - defaultNameScriptTemplateLines = - DBLangEngine.GetMessage("msgDefaultScriptSnippetLines", "A line script snippet|As in a script for manipulating Scintilla contents as lines"); + defaultNameScriptTemplateLines = + DBLangEngine.GetMessage("msgDefaultScriptSnippetLines", "A line script snippet|As in a script for manipulating Scintilla contents as lines"); - // localize the currently supported script types.. - tsbComboScriptType.Items.Clear(); - tsbComboScriptType.Items.Add( - DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text") - ); + // localize the currently supported script types.. + tsbComboScriptType.Items.Clear(); + tsbComboScriptType.Items.Add( + DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text") + ); - tsbComboScriptType.Items.Add( - DBLangEngine.GetMessage("msgScriptTypeLines", "Script lines|As in the C# script type should be handling the Scintilla's contents as lines") - ); + tsbComboScriptType.Items.Add( + DBLangEngine.GetMessage("msgScriptTypeLines", "Script lines|As in the C# script type should be handling the Scintilla's contents as lines") + ); - tsbComboScriptType.SelectedItem = - DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text"); + tsbComboScriptType.SelectedItem = + DBLangEngine.GetMessage("msgScriptTypeText", "Script text|As in the C# script type should be handling the Scintilla's contents as text"); - // set the default script for manipulating text.. - scintillaScript.Text = scriptRunnerText.CSharpScriptBase; + // set the default script for manipulating text.. + scintillaScript.Text = scriptRunnerText.CSharpScriptBase; - // set the text for the default script snippet.. - tstScriptName.Text = defaultNameScriptTemplateText; + // set the text for the default script snippet.. + tstScriptName.Text = defaultNameScriptTemplateText; - CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. + CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. - // set the lexer as C#.. - ScintillaLexers.CreateLexer(scintillaScript, LexerType.Cs); + // set the lexer as C#.. + ScintillaLexers.CreateLexer(scintillaScript, LexerType.Cs); - // highlight the braces.. - SetBraceHighlights(); + // highlight the braces.. + SetBraceHighlights(); + scintillaScript.Margins[0].Width = 20; - suspendChangedEvent = false; // "resume" the event handler.. - - // track the instances of this form so the changes can be delegated to each other.. - FormScriptInstances.Add(this); - } - #endregion + suspendChangedEvent = false; // "resume" the event handler.. - #region InternalHelpers - /// - /// Gets the type of the selected script in the tool strip's combo box. - /// - private int SelectedScriptType => - // the tool strip combo box doesn't seem to remember it's index, - // so get the index by using another way.. - tsbComboScriptType.Items.IndexOf(tsbComboScriptType.Text); + // track the instances of this form so the changes can be delegated to each other.. + FormScriptInstances.Add(this); + } + #endregion - /// - /// Compiles the script in the view and outputs the compilation results. - /// - /// True if the compilation was successful; otherwise false. - private bool Compile() - { - tbCompilerResults.Text = string.Empty; // clear the previous results.. + #region InternalHelpers + /// + /// Gets the type of the selected script in the tool strip's combo box. + /// + private int SelectedScriptType => + // the tool strip combo box doesn't seem to remember it's index, + // so get the index by using another way.. + tsbComboScriptType.Items.IndexOf(tsbComboScriptType.Text); - IScriptRunner scriptRunnerParent; - if (SelectedScriptType == 0) - { - scriptRunnerParent = scriptRunnerText; - } - else if (SelectedScriptType == 1) - { - scriptRunnerParent = scriptRunnerLines; - } - else - { - tbCompilerResults.Text += - DBLangEngine.GetMessage("msgScriptCompileFailed", "Compile failed.|A text to be shown if a script snippet compilation wasn't successful.") + - Environment.NewLine; - return false; - } + /// + /// Compiles the script in the view and outputs the compilation results. + /// + /// True if the compilation was successful; otherwise false. + private bool Compile() + { + tbCompilerResults.Text = string.Empty; // clear the previous results.. - // set the script code from the Scintilla document contents.. - scriptRunnerParent.ScriptCode = scintillaScript.Text; + IScriptRunner scriptRunnerParent; + if (SelectedScriptType == 0) + { + scriptRunnerParent = scriptRunnerText; + } + else if (SelectedScriptType == 1) + { + scriptRunnerParent = scriptRunnerLines; + } + else + { + tbCompilerResults.Text += + DBLangEngine.GetMessage("msgScriptCompileFailed", "Compile failed.|A text to be shown if a script snippet compilation wasn't successful.") + + Environment.NewLine; + return false; + } - if (scriptRunnerParent.CompileFailed) - { - // loop through the compilation results.. - tbCompilerResults.Text += scriptRunnerParent.CompileException?.Message + Environment.NewLine; + // set the script code from the Scintilla document contents.. + scriptRunnerParent.ScriptCode = scintillaScript.Text; - Exception exception; + if (scriptRunnerParent.CompileFailed) + { + // loop through the compilation results.. + tbCompilerResults.Text += scriptRunnerParent.CompileException?.Message + Environment.NewLine; - while ((exception = scriptRunnerParent.CompileException?.InnerException) != null) - { - tbCompilerResults.Text += exception.Message + Environment.NewLine; - } - } + Exception exception; - // no need to continue if the script compilation failed.. - if (scriptRunnerParent.CompileFailed) + while ((exception = scriptRunnerParent.CompileException?.InnerException) != null) { - tbCompilerResults.Text += - DBLangEngine.GetMessage("msgScriptCompileFailed", "Compile failed.|A text to be shown if a script snippet compilation wasn't successful.") + - Environment.NewLine; - return false; + tbCompilerResults.Text += exception.Message + Environment.NewLine; } + } + // no need to continue if the script compilation failed.. + if (scriptRunnerParent.CompileFailed) + { tbCompilerResults.Text += - DBLangEngine.GetMessage("msgScriptCompileSuccess", "Compile successful.|A text to be shown if a script snippet compilation was successful.") + + DBLangEngine.GetMessage("msgScriptCompileFailed", "Compile failed.|A text to be shown if a script snippet compilation wasn't successful.") + Environment.NewLine; - - return true; + return false; } - /// - /// Blinks the name of the script in the tool strip if a user has set a "reserved" name for the script - /// or a user tries to save a script as with an existing name. - /// - private void ErrorBlink() - { - // save the background color to a variable.. - Color backColorSave = tstScriptName.BackColor; + tbCompilerResults.Text += + DBLangEngine.GetMessage("msgScriptCompileSuccess", "Compile successful.|A text to be shown if a script snippet compilation was successful.") + + Environment.NewLine; - // loop few times changing the color from red to the original color.. - for (int i = 0; i < 6; i++) - { - // a normal remainder operator for two options.. - tstScriptName.BackColor = (i % 2) == 0 ? Color.Red : backColorSave; - Thread.Sleep(100); // sleep form a hundred milliseconds.. - Application.DoEvents(); // keep the GUI alive.. - } - } + return true; + } - /// - /// Creates a CODE_SNIPPETS class instance from the GUI items. - /// - /// A CODE_SNIPPETS class instance. - private void CreateNewCodeSnippet() - { - // just call the overload.. - CreateNewCodeSnippet(scintillaScript.Text, tstScriptName.Text, SelectedScriptType); - } + /// + /// Blinks the name of the script in the tool strip if a user has set a "reserved" name for the script + /// or a user tries to save a script as with an existing name. + /// + private void ErrorBlink() + { + // save the background color to a variable.. + Color backColorSave = tstScriptName.BackColor; - /// - /// Creates a CODE_SNIPPETS class instance from the given parameters. - /// - /// The contents of the script. - /// The name of the script. - /// The type of the script. - /// A CODE_SNIPPETS class instance. - private CodeSnippet CreateNewCodeSnippet(string contents, string name, int scriptType) + // loop few times changing the color from red to the original color.. + for (int i = 0; i < 6; i++) { - // return a new CODE_SNIPPETS class instance using the given parameters.. - return currentCodeSnippet = new CodeSnippet - { - ScriptContents = contents, - ScriptName = name, - ScriptLanguage = CodeSnippetLanguage.Cs, - ScriptTextManipulationType = (ScriptSnippetType)scriptType, - Modified = DateTime.Now, - }; + // a normal remainder operator for two options.. + tstScriptName.BackColor = (i % 2) == 0 ? Color.Red : backColorSave; + Thread.Sleep(100); // sleep form a hundred milliseconds.. + Application.DoEvents(); // keep the GUI alive.. } + } - /// - /// Enables or disabled the controls that might end up for the user to lose his work. - /// - /// A flag indicating if the controls should be enabled or disabled. - private void EnableDisableControlsOnChange(bool enable) - { - tsbComboScriptType.Enabled = enable; // set the value.. - tsbOpen.Enabled = enable; - } + /// + /// Creates a CODE_SNIPPETS class instance from the GUI items. + /// + /// A CODE_SNIPPETS class instance. + private void CreateNewCodeSnippet() + { + // just call the overload.. + CreateNewCodeSnippet(scintillaScript.Text, tstScriptName.Text, SelectedScriptType); + } - /// - /// Validates the name of the script (i.e. reserved words or existing scripts). - /// - /// A name of the script of which validity to check. - /// True if the given script name was valid; otherwise false. - private bool ValidateScriptName(string scriptName) + /// + /// Creates a CODE_SNIPPETS class instance from the given parameters. + /// + /// The contents of the script. + /// The name of the script. + /// The type of the script. + /// A CODE_SNIPPETS class instance. + private CodeSnippet CreateNewCodeSnippet(string contents, string name, int scriptType) + { + // return a new CODE_SNIPPETS class instance using the given parameters.. + return currentCodeSnippet = new CodeSnippet { - // no white space allowed.. - scriptName = scriptName.Trim(); - - // an unnamed script is not allowed.. - if (scriptName == string.Empty) - { - return false; - } + ScriptContents = contents, + ScriptName = name, + ScriptLanguage = CodeSnippetLanguage.Cs, + ScriptTextManipulationType = (ScriptSnippetType)scriptType, + Modified = DateTime.Now, + }; + } - var result = !((scriptName == defaultNameScriptTemplateText || // a localized template name for text will not do.. - scriptName == defaultNameScriptTemplateLines || // a localized template name for lines will not do.. - scriptName == "Simple line ending change script" || // a non-localized database template for lines will not do.. - scriptName == "Simple replace script" || - scriptName == "Simple XML manipulation script")); + /// + /// Enables or disabled the controls that might end up for the user to lose his work. + /// + /// A flag indicating if the controls should be enabled or disabled. + private void EnableDisableControlsOnChange(bool enable) + { + tsbComboScriptType.Enabled = enable; // set the value.. + tsbOpen.Enabled = enable; + } - // return the result.. - return result; - } - #endregion + /// + /// Validates the name of the script (i.e. reserved words or existing scripts). + /// + /// A name of the script of which validity to check. + /// True if the given script name was valid; otherwise false. + private bool ValidateScriptName(string scriptName) + { + // no white space allowed.. + scriptName = scriptName.Trim(); - #region InternalEvents - private void FormScript_FormClosing(object sender, FormClosingEventArgs e) + // an unnamed script is not allowed.. + if (scriptName == string.Empty) { - // this form is no longer going to be an instance for much longer.. - FormScriptInstances.Remove(this); + return false; } - // a user wants to run the script against the active Scintilla document on the main form.. - private async void tsbRunScript_Click(object sender, EventArgs e) + var result = !((scriptName == defaultNameScriptTemplateText || // a localized template name for text will not do.. + scriptName == defaultNameScriptTemplateLines || // a localized template name for lines will not do.. + scriptName == "Simple line ending change script" || // a non-localized database template for lines will not do.. + scriptName == "Simple replace script" || + scriptName == "Simple XML manipulation script")); + + // return the result.. + return result; + } + #endregion + + #region InternalEvents + private void FormScript_FormClosing(object sender, FormClosingEventArgs e) + { + // this form is no longer going to be an instance for much longer.. + FormScriptInstances.Remove(this); + } + + // a user wants to run the script against the active Scintilla document on the main form.. + private async void tsbRunScript_Click(object sender, EventArgs e) + { + // no need to continue if the script compilation failed.. + if (!Compile()) { - // no need to continue if the script compilation failed.. - if (!Compile()) - { - return; - } + return; + } - // create a new instance of a ScintillaRequiredEventArgs class.. - ScintillaRequiredEventArgs args = new ScintillaRequiredEventArgs(); + // create a new instance of a ScintillaRequiredEventArgs class.. + ScintillaRequiredEventArgs args = new ScintillaRequiredEventArgs(); - // if the ScintillaRequired event is subscribed do raise the event.. - ScintillaRequired?.Invoke(this, args); + // if the ScintillaRequired event is subscribed do raise the event.. + ScintillaRequired?.Invoke(this, args); - // we really don't care if the event was subscribed or not, - // only the value of the ScintillaRequiredEventArgs needs checking.. - if (args.Scintilla != null) + // we really don't care if the event was subscribed or not, + // only the value of the ScintillaRequiredEventArgs needs checking.. + if (args.Scintilla != null) + { + // a text contents manipulation script was requested.. + if (SelectedScriptType == 0) { - // a text contents manipulation script was requested.. - if (SelectedScriptType == 0) + var evaluateSuccess = await scriptRunnerText.Evaluate(args.Scintilla.Text); + + // a reference to a Scintilla document was gotten so do run the code.. + var result = await scriptRunnerText.ExecuteText(args.Scintilla.Text); + if (result.Value && evaluateSuccess) { - // a reference to a Scintilla document was gotten so do run the code.. - var result = await scriptRunnerText.ExecuteText(args.Scintilla.Text); - if (result.Value) - { - args.Scintilla.Text = result.Key; - } + args.Scintilla.Text = result.Key; } - // a line contents manipulation script was requested.. - else if (SelectedScriptType == 1) + } + // a line contents manipulation script was requested.. + else if (SelectedScriptType == 1) + { + var evaluateSuccess = await scriptRunnerLines.Evaluate(args.Scintilla.Text); + + // a reference to a Scintilla document was gotten so do run the code.. + var result = + await scriptRunnerLines.ExecuteLinesAsync(ScintillaLines.GetLinesAsList(args.Scintilla)); + + if (result.Value && evaluateSuccess) { - // a reference to a Scintilla document was gotten so do run the code.. - var result = - await scriptRunnerLines.ExecuteLinesAsync(ScintillaLines.GetLinesAsList(args.Scintilla)); - if (result.Value) - { - args.Scintilla.Text = result.Key; - } + args.Scintilla.Text = result.Key; } } } + } - // a user wishes to load a script from the database.. - private void tsbOpen_Click(object sender, EventArgs e) - { - // display the script dialog.. - var snippet = FormDialogScriptLoad.Execute(false); + // a user wishes to load a script from the database.. + private void tsbOpen_Click(object sender, EventArgs e) + { + // display the script dialog.. + var snippet = FormDialogScriptLoad.Execute(false); - // if a selection was made.. - if (snippet != null) - { - suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change.. - tstScriptName.Text = snippet.ScriptName; - scintillaScript.Text = snippet.ScriptContents; - tsbComboScriptType.SelectedIndex = (int)snippet.ScriptTextManipulationType; - suspendChangedEvent = false; // "resume" the event handler.. - currentCodeSnippet = snippet; - } + // if a selection was made.. + if (snippet != null) + { + suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change.. + tstScriptName.Text = snippet.ScriptName; + scintillaScript.Text = snippet.ScriptContents; + tsbComboScriptType.SelectedIndex = (int)snippet.ScriptTextManipulationType; + suspendChangedEvent = false; // "resume" the event handler.. + currentCodeSnippet = snippet; } + } - // the text was changed either in the scintilla or in the script's - // name text box or the script type combo box selected item was changed.. - private void common_Changed(object sender, EventArgs e) + // the text was changed either in the scintilla or in the script's + // name text box or the script type combo box selected item was changed.. + private void common_Changed(object sender, EventArgs e) + { + if (!suspendChangedEvent) // only do something if "listening" flag is set to enabled.. { - if (!suspendChangedEvent) // only do something if "listening" flag is set to enabled.. + if (sender.Equals(tsbComboScriptType)) { - if (sender.Equals(tsbComboScriptType)) + suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change.. + if (tsbComboScriptType.SelectedIndex == 0) { - suspendChangedEvent = true; // suspend the event handler as the contents of the script is about to change.. - if (tsbComboScriptType.SelectedIndex == 0) - { - scintillaScript.Text = scriptRunnerText.CSharpScriptBase; - tstScriptName.Text = defaultNameScriptTemplateText; - CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. - } - else - { - scintillaScript.Text = scriptRunnerLines.CSharpScriptBase; - tstScriptName.Text = defaultNameScriptTemplateLines; - CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. - } - suspendChangedEvent = false; // "resume" the event handler.. - return; + scintillaScript.Text = scriptRunnerText.CSharpScriptBase; + tstScriptName.Text = defaultNameScriptTemplateText; + CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. } - - if (currentCodeSnippet == null) + else { + scintillaScript.Text = scriptRunnerLines.CSharpScriptBase; + tstScriptName.Text = defaultNameScriptTemplateLines; CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. } + suspendChangedEvent = false; // "resume" the event handler.. + return; + } - currentCodeSnippet.ScriptName = tstScriptName.Text; - currentCodeSnippet.ScriptContents = scintillaScript.Text; - - // don't allow the user to lose one's work on the current script.. - EnableDisableControlsOnChange(false); + if (currentCodeSnippet == null) + { + CreateNewCodeSnippet(); // create a new CODE_SNIPPETS class instance.. } + + currentCodeSnippet.ScriptName = tstScriptName.Text; + currentCodeSnippet.ScriptContents = scintillaScript.Text; + + // don't allow the user to lose one's work on the current script.. + EnableDisableControlsOnChange(false); } + } - private void tsbDiscardChanges_Click(object sender, EventArgs e) + private void tsbDiscardChanges_Click(object sender, EventArgs e) + { + // enable the controls as the user chose to discard the changes of the script.. + EnableDisableControlsOnChange(true); + } + + // an event which occurs when the save or a save as button is clicked.. + private void tsbSaveButtons_Click(object sender, EventArgs e) + { + // if the script's name is invalid.. + if (!ValidateScriptName(tstScriptName.Text)) { - // enable the controls as the user chose to discard the changes of the script.. - EnableDisableControlsOnChange(true); + ErrorBlink(); // ..indicate an error.. + return; // ..and return.. } - // an event which occurs when the save or a save as button is clicked.. - private void tsbSaveButtons_Click(object sender, EventArgs e) + // if the currentCodeSnippet is null then create a new one.. + if (currentCodeSnippet == null) { - // if the script's name is invalid.. - if (!ValidateScriptName(tstScriptName.Text)) - { - ErrorBlink(); // ..indicate an error.. - return; // ..and return.. - } - - // if the currentCodeSnippet is null then create a new one.. - if (currentCodeSnippet == null) - { - currentCodeSnippet = CreateNewCodeSnippet(scintillaScript.Text, tstScriptName.Text, SelectedScriptType); - } + currentCodeSnippet = CreateNewCodeSnippet(scintillaScript.Text, tstScriptName.Text, SelectedScriptType); + } - // display an error if the script's name is any of the reserved script names.. - if (ScriptNotepadDbContext.DbContext.CodeSnippets.Any(f => f.ScriptName.In( + // display an error if the script's name is any of the reserved script names.. + if (ScriptNotepadDbContext.DbContext.CodeSnippets.Any(f => f.ScriptName.In( defaultNameScriptTemplateText, defaultNameScriptTemplateLines, "Simple line ending change script", "Simple replace script", "Simple XML manipulation script"))) - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgReservedScriptName", "The given script name is reserved for the script samples. The script wasn't saved.|A message informing that the given script name is reserved for static sample scripts."), - DBLangEngine.GetMessage("msgWarning", - "Warning|A message warning of some kind problem"), MessageBoxButtonsExtended.OK, - MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); - - EnableDisableControlsOnChange(true); - - return; - } - - ScriptNotepadDbContext.DbContext.CodeSnippets.Add(currentCodeSnippet); - ScriptNotepadDbContext.DbContext.SaveChanges(); + { + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgReservedScriptName", "The given script name is reserved for the script samples. The script wasn't saved.|A message informing that the given script name is reserved for static sample scripts."), + DBLangEngine.GetMessage("msgWarning", + "Warning|A message warning of some kind problem"), MessageBoxButtonsExtended.OK, + MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); - // enable the controls as the user chose to save the changes of the script.. EnableDisableControlsOnChange(true); - } - // a user wants to compile the script to see if it's valid.. - private void tsbTestScript_Click(object sender, EventArgs e) - { - // ..so do compile and output the results.. - Compile(); + return; } - #endregion - #region PublicEvents - /// - /// A delegate for the ScintillaRequired event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnScintillaRequired(object sender, ScintillaRequiredEventArgs e); + ScriptNotepadDbContext.DbContext.CodeSnippets.Add(currentCodeSnippet); + ScriptNotepadDbContext.DbContext.SaveChanges(); - /// - /// Event arguments for the ScintillaRequired event. - /// - /// - public class ScintillaRequiredEventArgs : EventArgs - { - /// - /// Gets or sets the Scintilla document which contents to manipulate via a C# script. - /// - public Scintilla Scintilla { get; set; } = null; - } + // enable the controls as the user chose to save the changes of the script.. + EnableDisableControlsOnChange(true); + } + + // a user wants to compile the script to see if it's valid.. + private void tsbTestScript_Click(object sender, EventArgs e) + { + // ..so do compile and output the results.. + Compile(); + } + #endregion + + #region PublicEvents + /// + /// A delegate for the ScintillaRequired event. + /// + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnScintillaRequired(object sender, ScintillaRequiredEventArgs e); + /// + /// Event arguments for the ScintillaRequired event. + /// + /// + public class ScintillaRequiredEventArgs : EventArgs + { /// - /// Occurs when a user wants to run a script for a Scintilla document contents. + /// Gets or sets the Scintilla document which contents to manipulate via a C# script. /// - public event OnScintillaRequired ScintillaRequired; - #endregion + public Scintilla Scintilla { get; set; } = null; + } - #region "CodeIndent Handlers" - // This (C): https://gist.github.com/Ahmad45123/f2910192987a73a52ab4 - // ReSharper disable once InconsistentNaming - private const int SCI_SETLINEINDENTATION = 2126; - // ReSharper disable once InconsistentNaming - private const int SCI_GETLINEINDENTATION = 2127; - void SetIndent(Scintilla scintilla, int line, int indent) - { - scintilla.DirectMessage(SCI_SETLINEINDENTATION, new IntPtr(line), new IntPtr(indent)); - } - int GetIndent(Scintilla scintilla, int line) - { - return (scintilla.DirectMessage(SCI_GETLINEINDENTATION, new IntPtr(line), IntPtr.Zero).ToInt32()); - } + /// + /// Occurs when a user wants to run a script for a Scintilla document contents. + /// + public event OnScintillaRequired ScintillaRequired; + #endregion + + #region "CodeIndent Handlers" + // This (C): https://gist.github.com/Ahmad45123/f2910192987a73a52ab4 + // ReSharper disable once InconsistentNaming + private const int SCI_SETLINEINDENTATION = 2126; + // ReSharper disable once InconsistentNaming + private const int SCI_GETLINEINDENTATION = 2127; + void SetIndent(Scintilla scintilla, int line, int indent) + { + scintilla.DirectMessage(SCI_SETLINEINDENTATION, new IntPtr(line), new IntPtr(indent)); + } + int GetIndent(Scintilla scintilla, int line) + { + return (scintilla.DirectMessage(SCI_GETLINEINDENTATION, new IntPtr(line), IntPtr.Zero).ToInt32()); + } - private void Scintilla_CharAdded(object sender, CharAddedEventArgs e) - { - var scintilla = (Scintilla) sender; + private void Scintilla_CharAdded(object sender, CharAddedEventArgs e) + { + var scintilla = (Scintilla) sender; - //The '}' char. - if (e.Char == '}') { - int curLine = scintilla.LineFromPosition(scintilla.CurrentPosition); + //The '}' char. + if (e.Char == '}') { + int curLine = scintilla.LineFromPosition(scintilla.CurrentPosition); - if (scintilla.Lines[curLine].Text.Trim() == "}") { //Check whether the bracket is the only thing on the line.. For cases like "if() { }". - SetIndent(scintilla, curLine, GetIndent(scintilla, curLine) - FormSettings.Settings.EditorTabWidth); - } + if (scintilla.Lines[curLine].Text.Trim() == "}") { //Check whether the bracket is the only thing on the line.. For cases like "if() { }". + SetIndent(scintilla, curLine, GetIndent(scintilla, curLine) - FormSettings.Settings.EditorTabWidth); } } + } - private void Scintilla_InsertCheck(object sender, InsertCheckEventArgs e) - { - // This (C): https://gist.github.com/Ahmad45123/f2910192987a73a52ab4 - var scintilla = (Scintilla) sender; + private void Scintilla_InsertCheck(object sender, InsertCheckEventArgs e) + { + // This (C): https://gist.github.com/Ahmad45123/f2910192987a73a52ab4 + var scintilla = (Scintilla) sender; - if ((e.Text.EndsWith("\r") || e.Text.EndsWith("\n"))) { - int startPos = scintilla.Lines[scintilla.LineFromPosition(scintilla.CurrentPosition)].Position; - int endPos = e.Position; - string curLineText = scintilla.GetTextRange(startPos, (endPos - startPos)); //Text until the caret so that the whitespace is always equal in every line. + if ((e.Text.EndsWith("\r") || e.Text.EndsWith("\n"))) { + int startPos = scintilla.Lines[scintilla.LineFromPosition(scintilla.CurrentPosition)].Position; + int endPos = e.Position; + string curLineText = scintilla.GetTextRange(startPos, (endPos - startPos)); //Text until the caret so that the whitespace is always equal in every line. - Match indent = Regex.Match(curLineText, "^[ \\t]*"); - e.Text = (e.Text + indent.Value); - if (Regex.IsMatch(curLineText, "{\\s*$")) { - e.Text = (e.Text + "\t"); - } + Match indent = Regex.Match(curLineText, "^[ \\t]*"); + e.Text = (e.Text + indent.Value); + if (Regex.IsMatch(curLineText, "{\\s*$")) { + e.Text = (e.Text + "\t"); } } - #endregion + } + #endregion - #region BraceHighLight - // (C): https://github.com/jacobslusser/ScintillaNET/wiki/Brace-Matching - private static bool IsBrace(int c) + #region BraceHighLight + // (C): https://github.com/jacobslusser/ScintillaNET/wiki/Brace-Matching + private static bool IsBrace(int c) + { + switch (c) { - switch (c) - { - case '(': - case ')': - case '[': - case ']': - case '{': - case '}': - case '<': - case '>': - return true; - } - - return false; + case '(': + case ')': + case '[': + case ']': + case '{': + case '}': + case '<': + case '>': + return true; } - /// - /// Sets the brace highlight colors for a instance. - /// - private void SetBraceHighlights() + return false; + } + + /// + /// Sets the brace highlight colors for a instance. + /// + private void SetBraceHighlights() + { + // not in the settings, so do return.. + if (!FormSettings.Settings.HighlightBraces) { - // not in the settings, so do return.. - if (!FormSettings.Settings.HighlightBraces) - { - return; - } + return; + } - scintillaScript.Styles[Style.BraceLight].ForeColor = FormSettings.Settings.BraceHighlightForegroundColor; - scintillaScript.Styles[Style.BraceLight].BackColor = FormSettings.Settings.BraceHighlightBackgroundColor; - scintillaScript.Styles[Style.BraceBad].BackColor = FormSettings.Settings.BraceBadHighlightForegroundColor; + scintillaScript.Styles[Style.BraceLight].ForeColor = FormSettings.Settings.BraceHighlightForegroundColor; + scintillaScript.Styles[Style.BraceLight].BackColor = FormSettings.Settings.BraceHighlightBackgroundColor; + scintillaScript.Styles[Style.BraceBad].BackColor = FormSettings.Settings.BraceBadHighlightForegroundColor; - scintillaScript.Styles[Style.BraceLight].Italic = FormSettings.Settings.HighlightBracesItalic; - scintillaScript.Styles[Style.BraceLight].Bold = FormSettings.Settings.HighlightBracesBold; - } + scintillaScript.Styles[Style.BraceLight].Italic = FormSettings.Settings.HighlightBracesItalic; + scintillaScript.Styles[Style.BraceLight].Bold = FormSettings.Settings.HighlightBracesBold; + } - private int lastCaretPos = -1; + private int lastCaretPos = -1; - private void Scintilla_UpdateUI(object sender, UpdateUIEventArgs e) + private void Scintilla_UpdateUI(object sender, UpdateUIEventArgs e) + { + // (C): https://github.com/jacobslusser/ScintillaNET/wiki/Brace-Matching + // Has the caret changed position? + var caretPos = scintillaScript.CurrentPosition; + if (lastCaretPos != caretPos) { - // (C): https://github.com/jacobslusser/ScintillaNET/wiki/Brace-Matching - // Has the caret changed position? - var caretPos = scintillaScript.CurrentPosition; - if (lastCaretPos != caretPos) - { - lastCaretPos = caretPos; - var bracePos1 = -1; + lastCaretPos = caretPos; + var bracePos1 = -1; - // Is there a brace to the left or right? - if (caretPos > 0 && IsBrace(scintillaScript.GetCharAt(caretPos - 1))) - { - bracePos1 = (caretPos - 1); - } - else if (IsBrace(scintillaScript.GetCharAt(caretPos))) - { - bracePos1 = caretPos; - } + // Is there a brace to the left or right? + if (caretPos > 0 && IsBrace(scintillaScript.GetCharAt(caretPos - 1))) + { + bracePos1 = (caretPos - 1); + } + else if (IsBrace(scintillaScript.GetCharAt(caretPos))) + { + bracePos1 = caretPos; + } - if (bracePos1 >= 0) + if (bracePos1 >= 0) + { + // Find the matching brace + var bracePos2 = scintillaScript.BraceMatch(bracePos1); + if (bracePos2 == Scintilla.InvalidPosition) { - // Find the matching brace - var bracePos2 = scintillaScript.BraceMatch(bracePos1); - if (bracePos2 == Scintilla.InvalidPosition) - { - scintillaScript.BraceBadLight(bracePos1); - } - else - { - scintillaScript.BraceHighlight(bracePos1, bracePos2); - } + scintillaScript.BraceBadLight(bracePos1); } else { - // Turn off brace matching - scintillaScript.BraceHighlight(Scintilla.InvalidPosition, Scintilla.InvalidPosition); + scintillaScript.BraceHighlight(bracePos1, bracePos2); } } + else + { + // Turn off brace matching + scintillaScript.BraceHighlight(Scintilla.InvalidPosition, Scintilla.InvalidPosition); + } } - #endregion } -} + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/IScriptRunner.cs b/ScriptNotepad/UtilityClasses/CodeDom/IScriptRunner.cs index f11173e0..cf61b2a2 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/IScriptRunner.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/IScriptRunner.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -24,50 +24,57 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion +using System.Collections.Generic; using System.Threading.Tasks; -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// An interface for the script runner classes. +/// +public interface IScriptRunner { /// - /// An interface for the script runner classes. + /// Gets or sets the C# script runner. /// - public interface IScriptRunner - { - /// - /// Gets or sets the C# script runner. - /// - /// The C# script runner. - public RoslynScriptRunner ScriptRunner { get; set; } + /// The C# script runner. + public RoslynScriptRunner ScriptRunner { get; set; } - /// - /// Gets or sets the base "skeleton" C# code snippet for manipulating text. - /// - /// The base "skeleton" C# code snippet for manipulating text. - string CSharpScriptBase { get; set; } + /// + /// Gets or sets the base "skeleton" C# code snippet for manipulating text. + /// + /// The base "skeleton" C# code snippet for manipulating text. + string CSharpScriptBase { get; set; } - /// - /// Gets or sets the C# script code. - /// - /// The C# script code. - string ScriptCode { get; set; } + /// + /// Gets or sets the C# script code. + /// + /// The C# script code. + string ScriptCode { get; set; } + + /// + /// Gets or sets a value indicating whether the script compile failed. + /// + /// true if the script compile failed; otherwise, false. + bool CompileFailed { get; set; } - /// - /// Gets or sets a value indicating whether the script compile failed. - /// - /// true if the script compile failed; otherwise, false. - bool CompileFailed { get; set; } + /// + /// Gets the previous compile exception. + /// + /// The previous compile exception. + public Exception CompileException { get; set; } - /// - /// Gets the previous compile exception. - /// - /// The previous compile exception. - public Exception CompileException { get; set; } + /// + /// Executes the script. + /// + /// The text in some format. + /// The object containing the manipulated text if the operation was successful. + Task ExecuteScript(object text); - /// - /// Executes the script. - /// - /// The text in some format. - /// The object containing the manipulated text if the operation was successful. - Task ExecuteScript(object text); - } -} + /// + /// Evaluates the C# script. + /// + /// The file contents to run the C# script against. + /// A containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded. + Task Evaluate(string fileContents); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/RoslynGlobals.cs b/ScriptNotepad/UtilityClasses/CodeDom/RoslynGlobals.cs index eae36bf6..ba9d149a 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/RoslynGlobals.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/RoslynGlobals.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -24,18 +24,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// A class to pass global data to Roslyn. +/// +/// The type for the property. +public class RoslynGlobals { /// - /// A class to pass global data to Roslyn. + /// Gets or sets the data to pass to Roslyn. /// - /// The type for the property. - public class RoslynGlobals - { - /// - /// Gets or sets the data to pass to Roslyn. - /// - /// The data to pass to Roslyn. - public T DataVariable { get; set; } - } -} + /// The data to pass to Roslyn. + public T DataVariable { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/CodeDom/RoslynScriptRunner.cs b/ScriptNotepad/UtilityClasses/CodeDom/RoslynScriptRunner.cs index a0c16603..fd59e9fd 100644 --- a/ScriptNotepad/UtilityClasses/CodeDom/RoslynScriptRunner.cs +++ b/ScriptNotepad/UtilityClasses/CodeDom/RoslynScriptRunner.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -36,110 +36,109 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; -namespace ScriptNotepad.UtilityClasses.CodeDom +namespace ScriptNotepad.UtilityClasses.CodeDom; + +/// +/// A class to run C# scripts with Roslyn. +/// +public class RoslynScriptRunner { /// - /// A class to run C# scripts with Roslyn. + /// Initializes a new instance of the class. + /// + public RoslynScriptRunner() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The globals object value. This can not be used within a class. + public RoslynScriptRunner(object globalValue) + { + GlobalValue = globalValue; + GlobalValueType = globalValue.GetType(); + } + + /// + /// Gets the globals value for the script. + /// + /// The globals value for the script. + private object? GlobalValue { get; } + + /// + /// Gets the type of the globals value. + /// + /// The type of the globals value. + private Type? GlobalValueType { get; } + + /// + /// Gets or sets the state of the script. + /// + /// The state of the script. + private ScriptState? ScriptState { get; set; } + + /// + /// Gets the options. + /// + /// The options. + private ScriptOptions Options { get; } = ScriptOptions.Default + .AddReferences(typeof(object).Assembly, + typeof(Thread).Assembly, + typeof(Task).Assembly, + typeof(List<>).Assembly, + typeof(Regex).Assembly, + typeof(StringBuilder).Assembly, + typeof(Uri).Assembly, + typeof(Enumerable).Assembly, + typeof(IEnumerable).Assembly, + typeof(Path).Assembly, + typeof(System.Reflection.Assembly).Assembly, + typeof(System.Text.RegularExpressions.Regex).Assembly, + typeof(System.Linq.Enumerable).Assembly, + typeof(XmlDocument).Assembly, + typeof(XDocument).Assembly); + + /// + /// Executes C# script as an asynchronous operation. /// - public class RoslynScriptRunner + /// The code to either append to the previous or script or to evaluate. + /// System.Nullable<System.Object> containing the script result value or an exception object if one occurred. + public async Task ExecuteAsync(string code) { - /// - /// Initializes a new instance of the class. - /// - public RoslynScriptRunner() + // success, no exceptions.. + PreviousCompileException = null; + + try { + ScriptState = ScriptState == null + ? await CSharpScript.RunAsync(code, Options, GlobalValue, GlobalValueType) + : await ScriptState.ContinueWithAsync(code, Options); } - - /// - /// Initializes a new instance of the class. - /// - /// The globals object value. This can not be used within a class. - public RoslynScriptRunner(object globalValue) + catch (Exception exception) { - GlobalValue = globalValue; - GlobalValueType = globalValue.GetType(); + // save the exception for further analysis.. + PreviousCompileException = exception; + + // return the exception from the CSharpScript.. + return exception; } - /// - /// Gets the globals value for the script. - /// - /// The globals value for the script. - private object? GlobalValue { get; } - - /// - /// Gets the type of the globals value. - /// - /// The type of the globals value. - private Type? GlobalValueType { get; } - - /// - /// Gets or sets the state of the script. - /// - /// The state of the script. - private ScriptState? ScriptState { get; set; } - - /// - /// Gets the options. - /// - /// The options. - private ScriptOptions Options { get; } = ScriptOptions.Default - .AddReferences(typeof(object).Assembly, - typeof(Thread).Assembly, - typeof(Task).Assembly, - typeof(List<>).Assembly, - typeof(Regex).Assembly, - typeof(StringBuilder).Assembly, - typeof(Uri).Assembly, - typeof(Enumerable).Assembly, - typeof(IEnumerable).Assembly, - typeof(Path).Assembly, - typeof(System.Reflection.Assembly).Assembly, - typeof(System.Text.RegularExpressions.Regex).Assembly, - typeof(System.Linq.Enumerable).Assembly, - typeof(XmlDocument).Assembly, - typeof(XDocument).Assembly); - - /// - /// Executes C# script as an asynchronous operation. - /// - /// The code to either append to the previous or script or to evaluate. - /// System.Nullable<System.Object> containing the script result value or an exception object if one occurred. - public async Task ExecuteAsync(string code) + if (ScriptState?.ReturnValue != null && !string.IsNullOrEmpty(ScriptState.ReturnValue.ToString())) { - // success, no exceptions.. - PreviousCompileException = null; - - try - { - ScriptState = ScriptState == null - ? await CSharpScript.RunAsync(code, Options, GlobalValue, GlobalValueType) - : await ScriptState.ContinueWithAsync(code, Options); - } - catch (Exception exception) - { - // save the exception for further analysis.. - PreviousCompileException = exception; - - // return the exception from the CSharpScript.. - return exception; - } - - if (ScriptState?.ReturnValue != null && !string.IsNullOrEmpty(ScriptState.ReturnValue.ToString())) - { - var result = ScriptState.ReturnValue; - // reset the script state after a result is gotten.. - ScriptState = null; - - return result; - } - - return null; + var result = ScriptState.ReturnValue; + // reset the script state after a result is gotten.. + ScriptState = null; + + return result; } - /// - /// Gets the previous compile exception. - /// - /// The previous compile exception. - public Exception? PreviousCompileException { get; private set; } + return null; } -} + + /// + /// Gets the previous compile exception. + /// + /// The previous compile exception. + public Exception? PreviousCompileException { get; private set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ColorHelpers/FormPickAColor.cs b/ScriptNotepad/UtilityClasses/ColorHelpers/FormPickAColor.cs index 3b9c18e8..64509e3f 100644 --- a/ScriptNotepad/UtilityClasses/ColorHelpers/FormPickAColor.cs +++ b/ScriptNotepad/UtilityClasses/ColorHelpers/FormPickAColor.cs @@ -30,107 +30,106 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using ColorMine.ColorSpaces; -namespace ScriptNotepad.UtilityClasses.ColorHelpers +namespace ScriptNotepad.UtilityClasses.ColorHelpers; + +/// +/// A class to detect if the selection contains a color definition. +/// Implements the +/// +/// +public partial class FormPickAColor : DBLangEngineWinforms { /// - /// A class to detect if the selection contains a color definition. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormPickAColor : DBLangEngineWinforms + public FormPickAColor() { - /// - /// Initializes a new instance of the class. - /// - public FormPickAColor() - { - InitializeComponent(); - - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + InitializeComponent(); - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - /// - /// A field to hold the current instance of this class. - /// - // ReSharper disable once InconsistentNaming - private static FormPickAColor formPickAColor; - - /// - /// Displays the dialog with a specified color. - /// - /// The color to use with the dialog. - /// Color. - public static Color Execute(Color color) + if (Utils.ShouldLocalize() != null) { - formPickAColor = new FormPickAColor(); - formPickAColor.UpdateColor(color); - formPickAColor.ShowDialog(); - return formPickAColor.pnColor.BackColor; + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - private Color UpdateColor(Color color) - { - pnColor.BackColor = color; - // ReSharper disable once LocalizableElement - // ReSharper disable once StringLiteralTypo - tbColorFromArgb.Text = $"Color.FromArgb({color.A}, {color.R}, {color.G}, {color.B})"; + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + } - // ReSharper disable once LocalizableElement - tbHexRGB.Text = $"#{color.R:X2}{color.G:X2}{color.B:X2}"; + /// + /// A field to hold the current instance of this class. + /// + // ReSharper disable once InconsistentNaming + private static FormPickAColor formPickAColor; - // ReSharper disable once LocalizableElement - tbHexARGB.Text = $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}"; - // ReSharper disable once StringLiteralTypo + /// + /// Displays the dialog with a specified color. + /// + /// The color to use with the dialog. + /// Color. + public static Color Execute(Color color) + { + formPickAColor = new FormPickAColor(); + formPickAColor.UpdateColor(color); + formPickAColor.ShowDialog(); + return formPickAColor.pnColor.BackColor; + } + + private Color UpdateColor(Color color) + { + pnColor.BackColor = color; + // ReSharper disable once LocalizableElement + // ReSharper disable once StringLiteralTypo + tbColorFromArgb.Text = $"Color.FromArgb({color.A}, {color.R}, {color.G}, {color.B})"; - Hex hex = new Hex($"#{color.R:X2}{color.G:X2}{color.B:X2}"); + // ReSharper disable once LocalizableElement + tbHexRGB.Text = $"#{color.R:X2}{color.G:X2}{color.B:X2}"; + + // ReSharper disable once LocalizableElement + tbHexARGB.Text = $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}"; + // ReSharper disable once StringLiteralTypo + + Hex hex = new Hex($"#{color.R:X2}{color.G:X2}{color.B:X2}"); - var hsb = hex.To(); + var hsb = hex.To(); - // ReSharper disable once LocalizableElement - tbHSB.Text = - $"hsb({(int) hsb.H}, {(int)hsb.S * 100}%, {(int)hsb.B * 100}%)"; + // ReSharper disable once LocalizableElement + tbHSB.Text = + $"hsb({(int) hsb.H}, {(int)hsb.S * 100}%, {(int)hsb.B * 100}%)"; - var hsv = hex.To(); - // ReSharper disable once LocalizableElement - tbHSV.Text = - $"hsv({(int) hsv.H}, {(int) hsv.S * 100}%, {(int) hsv.V * 100}%)"; + var hsv = hex.To(); + // ReSharper disable once LocalizableElement + tbHSV.Text = + $"hsv({(int) hsv.H}, {(int) hsv.S * 100}%, {(int) hsv.V * 100}%)"; - var hsl = hex.To(); - // ReSharper disable once LocalizableElement - tbHSL.Text = - $"hsl({(int) hsl.H}, {(int) hsl.S * 100}%, {(int) hsl.L * 100}%)"; + var hsl = hex.To(); + // ReSharper disable once LocalizableElement + tbHSL.Text = + $"hsl({(int) hsl.H}, {(int) hsl.S * 100}%, {(int) hsl.L * 100}%)"; - // ReSharper disable once IdentifierTypo - var cmyk = hex.To(); + // ReSharper disable once IdentifierTypo + var cmyk = hex.To(); - // ReSharper disable once LocalizableElement - tbCMYK.Text = - // ReSharper disable once StringLiteralTypo - $@"cmyk({(int)cmyk.C * 100}%, {(int) cmyk.M * 100}%, {(int) cmyk.Y * 100}%, {(int)cmyk.K * 100}%)"; + // ReSharper disable once LocalizableElement + tbCMYK.Text = + // ReSharper disable once StringLiteralTypo + $@"cmyk({(int)cmyk.C * 100}%, {(int) cmyk.M * 100}%, {(int) cmyk.Y * 100}%, {(int)cmyk.K * 100}%)"; - return color; - } + return color; + } - /// - /// Handles the Click event of the PnColor control. - /// - /// The source of the event. - /// The instance containing the event data. - private void PnColor_Click(object sender, EventArgs e) + /// + /// Handles the Click event of the PnColor control. + /// + /// The source of the event. + /// The instance containing the event data. + private void PnColor_Click(object sender, EventArgs e) + { + if (cdColors.ShowDialog() == DialogResult.OK) { - if (cdColors.ShowDialog() == DialogResult.OK) - { - pnColor.BackColor = UpdateColor(cdColors.Color); - } + pnColor.BackColor = UpdateColor(cdColors.Color); } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Common/DataToolStripMenuItem.cs b/ScriptNotepad/UtilityClasses/Common/DataToolStripMenuItem.cs index 1bdbd727..30774895 100644 --- a/ScriptNotepad/UtilityClasses/Common/DataToolStripMenuItem.cs +++ b/ScriptNotepad/UtilityClasses/Common/DataToolStripMenuItem.cs @@ -26,105 +26,104 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.Common +namespace ScriptNotepad.UtilityClasses.Common; + +/// +/// A tool strip menu item containing additional data. +/// +/// +public class DataToolStripMenuItem : ToolStripMenuItem { /// - /// A tool strip menu item containing additional data. + /// Gets or sets the additional data assigned to the tool strip menu item. /// - /// - public class DataToolStripMenuItem : ToolStripMenuItem - { - /// - /// Gets or sets the additional data assigned to the tool strip menu item. - /// - public object Data { get; set; } = null; + public object Data { get; set; } = null; - #region BaseConstructors - /// - /// Initializes a new instance of the class. - /// - public DataToolStripMenuItem() : base() - { - // nothing to do here.. - } + #region BaseConstructors + /// + /// Initializes a new instance of the class. + /// + public DataToolStripMenuItem() : base() + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The text to display on the menu item. - public DataToolStripMenuItem(string text) : base(text) - { - // nothing to do here.. - } + /// + /// Initializes a new instance of the class. + /// + /// The text to display on the menu item. + public DataToolStripMenuItem(string text) : base(text) + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The to display on the control. - public DataToolStripMenuItem(System.Drawing.Image image) : base(image) - { - // nothing to do here.. - } + /// + /// Initializes a new instance of the class. + /// + /// The to display on the control. + public DataToolStripMenuItem(System.Drawing.Image image) : base(image) + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The text to display on the menu item. - /// The to display on the control. - public DataToolStripMenuItem(string text, System.Drawing.Image image) : base(text, image) - { - // nothing to do here.. - } + /// + /// Initializes a new instance of the class. + /// + /// The text to display on the menu item. + /// The to display on the control. + public DataToolStripMenuItem(string text, System.Drawing.Image image) : base(text, image) + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The text to display on the menu item. - /// The to display on the control. - /// An event handler that raises the event when the control is clicked. - public DataToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick) : - base(text, image, onClick) - { - // nothing to do here.. - } + /// + /// Initializes a new instance of the class. + /// + /// The text to display on the menu item. + /// The to display on the control. + /// An event handler that raises the event when the control is clicked. + public DataToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick) : + base(text, image, onClick) + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The text to display on the menu item. - /// The to display on the control. - /// The menu items to display when the control is clicked. - public DataToolStripMenuItem(string text, System.Drawing.Image image, params ToolStripItem[] dropDownItems) : - base(text, image, dropDownItems) - { - // nothing to do here.. - } + /// + /// Initializes a new instance of the class. + /// + /// The text to display on the menu item. + /// The to display on the control. + /// The menu items to display when the control is clicked. + public DataToolStripMenuItem(string text, System.Drawing.Image image, params ToolStripItem[] dropDownItems) : + base(text, image, dropDownItems) + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The text to display on the menu item. - /// The to display on the control. - /// An event handler that raises the event when the control is clicked. - /// One of the values of that represents the shortcut key for the . - public DataToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick, Keys shortcutKeys) : - base(text, image, onClick, shortcutKeys) - { - // nothing to do here.. - } + /// + /// Initializes a new instance of the class. + /// + /// The text to display on the menu item. + /// The to display on the control. + /// An event handler that raises the event when the control is clicked. + /// One of the values of that represents the shortcut key for the . + public DataToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick, Keys shortcutKeys) : + base(text, image, onClick, shortcutKeys) + { + // nothing to do here.. + } - /// - /// Initializes a new instance of the class. - /// - /// The text to display on the menu item. - /// The to display on the control. - /// An event handler that raises the event when the control is clicked. - /// The name of the menu item. - public DataToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick, string name) : - base(text, image, onClick, name) - { - // nothing to do here.. - } - #endregion + /// + /// Initializes a new instance of the class. + /// + /// The text to display on the menu item. + /// The to display on the control. + /// An event handler that raises the event when the control is clicked. + /// The name of the menu item. + public DataToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick, string name) : + base(text, image, onClick, name) + { + // nothing to do here.. } -} + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Common/StatusStripComboItem.cs b/ScriptNotepad/UtilityClasses/Common/StatusStripComboItem.cs index 209902e4..cddbc899 100644 --- a/ScriptNotepad/UtilityClasses/Common/StatusStripComboItem.cs +++ b/ScriptNotepad/UtilityClasses/Common/StatusStripComboItem.cs @@ -29,143 +29,142 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using System.Windows.Forms.Design; -namespace ScriptNotepad.UtilityClasses.Common +namespace ScriptNotepad.UtilityClasses.Common; + +/// +/// A class for a simple combo box for a tool strip. +/// Implements the +/// +/// +[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.StatusStrip)] +// Not needed for internal use: [System.Drawing.ToolboxBitmap()] +public class StatusStripComboItem: ToolStripControlHost { /// - /// A class for a simple combo box for a tool strip. - /// Implements the + /// Gets or sets the ComboBox of the . /// - /// - [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.StatusStrip)] - // Not needed for internal use: [System.Drawing.ToolboxBitmap()] - public class StatusStripComboItem: ToolStripControlHost + private ComboBox ComboBox { get; } + + /// + /// Initializes a new instance of the class. + /// + public StatusStripComboItem() + : base(new ComboBox()) { - /// - /// Gets or sets the ComboBox of the . - /// - private ComboBox ComboBox { get; } - - /// - /// Initializes a new instance of the class. - /// - public StatusStripComboItem() - : base(new ComboBox()) + ComboBox = Control as ComboBox; + + if (ComboBox != null) { - ComboBox = Control as ComboBox; + ComboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; + ComboBox.SelectedValueChanged += ComboBox_SelectedValueChanged; + } - if (ComboBox != null) - { - ComboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; - ComboBox.SelectedValueChanged += ComboBox_SelectedValueChanged; - } + Disposed += StatusStripComboItem_Disposed; + } - Disposed += StatusStripComboItem_Disposed; - } + // release the event subscription.. + private void StatusStripComboItem_Disposed(object sender, EventArgs e) + { + ComboBox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged; + ComboBox.SelectedValueChanged -= ComboBox_SelectedValueChanged; + Disposed -= StatusStripComboItem_Disposed; + } - // release the event subscription.. - private void StatusStripComboItem_Disposed(object sender, EventArgs e) - { - ComboBox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged; - ComboBox.SelectedValueChanged -= ComboBox_SelectedValueChanged; - Disposed -= StatusStripComboItem_Disposed; - } + // event re-delegation.. + private void ComboBox_SelectedValueChanged(object sender, EventArgs e) + { + SelectedValueChanged?.Invoke(sender, e); + } - // event re-delegation.. - private void ComboBox_SelectedValueChanged(object sender, EventArgs e) - { - SelectedValueChanged?.Invoke(sender, e); - } + // event re-delegation.. + private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) + { + SelectedIndexChanged?.Invoke(sender, e); + } - // event re-delegation.. - private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) - { - SelectedIndexChanged?.Invoke(sender, e); - } + #region ComboBoxAccess + /// + /// Gets an object representing the collection of the items contained in this . + /// + [Browsable(true)] + [Category("Data")] + [Description("Gets an object representing the collection of the items contained in this ComboBox.")] + [Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor", typeof (UITypeEditor))] + public ComboBox.ObjectCollection Items => ComboBox.Items; - #region ComboBoxAccess - /// - /// Gets an object representing the collection of the items contained in this . - /// - [Browsable(true)] - [Category("Data")] - [Description("Gets an object representing the collection of the items contained in this ComboBox.")] - [Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor", typeof (UITypeEditor))] - public ComboBox.ObjectCollection Items => ComboBox.Items; - - /// - /// Gets or sets a value specifying the style of the combo box. - /// - [Browsable(true)] - [Category("Appearance")] - [Description("Gets or sets a value specifying the style of the combo box.")] - public ComboBoxStyle DropDownStyle - { - get => ComboBox.DropDownStyle; - set => ComboBox.DropDownStyle = value; - } + /// + /// Gets or sets a value specifying the style of the combo box. + /// + [Browsable(true)] + [Category("Appearance")] + [Description("Gets or sets a value specifying the style of the combo box.")] + public ComboBoxStyle DropDownStyle + { + get => ComboBox.DropDownStyle; + set => ComboBox.DropDownStyle = value; + } - /// - /// Gets or sets currently selected item in the . - /// - [Browsable(false)] - public object SelectedItem - { - get => ComboBox.SelectedItem; - set => ComboBox.SelectedItem = value; - } + /// + /// Gets or sets currently selected item in the . + /// + [Browsable(false)] + public object SelectedItem + { + get => ComboBox.SelectedItem; + set => ComboBox.SelectedItem = value; + } - /// - /// Gets or sets the index specifying the currently selected item. - /// - [Browsable(false)] - public int SelectedIndex - { - get => ComboBox.SelectedIndex; - set => ComboBox.SelectedIndex = value; - } + /// + /// Gets or sets the index specifying the currently selected item. + /// + [Browsable(false)] + public int SelectedIndex + { + get => ComboBox.SelectedIndex; + set => ComboBox.SelectedIndex = value; + } - /// - /// Gets or sets the text associated with this control. - /// - [Browsable(true)] - [Category("Appearance")] - [Description("Gets or sets the text associated with this control.")] - public override string Text + /// + /// Gets or sets the text associated with this control. + /// + [Browsable(true)] + [Category("Appearance")] + [Description("Gets or sets the text associated with this control.")] + public override string Text + { + get { - get - { - // some "weird" handling with the text.. - if (!base.Text.Equals(ComboBox.Text)) - { - ComboBox.Text = base.Text; - } - return base.Text; - } - - set + // some "weird" handling with the text.. + if (!base.Text.Equals(ComboBox.Text)) { - base.Text = value; - ComboBox.Text = value; - } - } + ComboBox.Text = base.Text; + } + return base.Text; + } - /// - /// Occurs when the property has changed. - /// - [Browsable(true)] - [Category("Behavior")] - [Description("Occurs when the ComboBox.SelectedIndex property has changed.")] - public EventHandler SelectedIndexChanged; - - /// - /// Occurs when the property changes. - /// - [Browsable(true)] - [Category("Behavior")] - [Description("Occurs when the ComboBox.SelectedValue property has changes.")] - public EventHandler SelectedValueChanged; - #endregion + set + { + base.Text = value; + ComboBox.Text = value; + } } -} + + /// + /// Occurs when the property has changed. + /// + [Browsable(true)] + [Category("Behavior")] + [Description("Occurs when the ComboBox.SelectedIndex property has changed.")] + public EventHandler SelectedIndexChanged; + + /// + /// Occurs when the property changes. + /// + [Browsable(true)] + [Category("Behavior")] + [Description("Occurs when the ComboBox.SelectedValue property has changes.")] + public EventHandler SelectedValueChanged; + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/DateTimeUtilities/DateTimeHelpers.cs b/ScriptNotepad/UtilityClasses/DateTimeUtilities/DateTimeHelpers.cs index c50f38e5..9fc8ff30 100644 --- a/ScriptNotepad/UtilityClasses/DateTimeUtilities/DateTimeHelpers.cs +++ b/ScriptNotepad/UtilityClasses/DateTimeUtilities/DateTimeHelpers.cs @@ -24,21 +24,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.DateTimeUtilities +namespace ScriptNotepad.UtilityClasses.DateTimeUtilities; + +/// +/// A helper class for . +/// +public static class DateTimeHelpers { /// - /// A helper class for . + /// Truncates the specified date time to a an accuracy of a second. /// - public static class DateTimeHelpers + /// The date time to truncate. + /// A truncated instance. + public static DateTime Truncate(this DateTime dateTime) { - /// - /// Truncates the specified date time to a an accuracy of a second. - /// - /// The date time to truncate. - /// A truncated instance. - public static DateTime Truncate(this DateTime dateTime) - { - return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind); - } + return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetComboBuilder.cs b/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetComboBuilder.cs index e49320a2..a6181970 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetComboBuilder.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetComboBuilder.cs @@ -27,450 +27,448 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Linq; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.Encodings.CharacterSets +namespace ScriptNotepad.UtilityClasses.Encodings.CharacterSets; + +/// +/// A class to be used with combo boxes for listing character sets and their encodings. +/// +public class CharacterSetComboItem { /// - /// A class to be used with combo boxes for listing character sets and their encodings. + /// Gets or sets the character set. + /// + public CharacterSets CharacterSet { get; set; } = CharacterSets.Unicode; + + /// + /// Gets or sets the encoding "bound" to the character set. + /// + public System.Text.Encoding Encoding { get; set; } + + /// + /// Gets a value indicating whether this instance contains an encoding class instance. + /// + public bool ContainsEncoding => Encoding != null; + + /// + /// Gets or sets an arbitrary object value that can be used to store custom information about this element. /// - public class CharacterSetComboItem + public object Tag { get; set; } + + /// + /// Returns a that represents this instance. + /// + public override string ToString() { - /// - /// Gets or sets the character set. - /// - public CharacterSets CharacterSet { get; set; } = CharacterSets.Unicode; - - /// - /// Gets or sets the encoding "bound" to the character set. - /// - public System.Text.Encoding Encoding { get; set; } - - /// - /// Gets a value indicating whether this instance contains an encoding class instance. - /// - public bool ContainsEncoding => Encoding != null; - - /// - /// Gets or sets an arbitrary object value that can be used to store custom information about this element. - /// - public object Tag { get; set; } - - /// - /// Returns a that represents this instance. - /// - public override string ToString() - { - // return a value based on to a comparison whether this instance contains an encoding or not.. - return ContainsEncoding ? Encoding.EncodingName : CharacterSetComboBuilder.EncodingCharacterSet.GetCharacterSetName(CharacterSet); - } + // return a value based on to a comparison whether this instance contains an encoding or not.. + return ContainsEncoding ? Encoding.EncodingName : CharacterSetComboBuilder.EncodingCharacterSet.GetCharacterSetName(CharacterSet); } +} +/// +/// A class to help to help to fill combo boxes with known character sets () and their encodings . +/// +public class CharacterSetComboBuilder: IDisposable +{ /// - /// A class to help to help to fill combo boxes with known character sets () and their encodings . + /// Initializes a new instance of the class. /// - public class CharacterSetComboBuilder: IDisposable + /// An instance to a combo box containing the character sets. + /// An instance to a combo box containing the encodings belonging to a character set. + /// A text box for searching for an encoding. + /// A flag indicating if character sets containing only single encoding should be used. + /// Additional data to be assigned to an instance of the CharacterSetComboItem class. + public CharacterSetComboBuilder( + ComboBox characterSetComboBox, + ComboBox encodingComboBox, + TextBox filterEncodingTextBox, + bool singleCodePageResults, + object data) { - /// - /// Initializes a new instance of the class. - /// - /// An instance to a combo box containing the character sets. - /// An instance to a combo box containing the encodings belonging to a character set. - /// A text box for searching for an encoding. - /// A flag indicating if character sets containing only single encoding should be used. - /// Additional data to be assigned to an instance of the CharacterSetComboItem class. - public CharacterSetComboBuilder( - ComboBox characterSetComboBox, - ComboBox encodingComboBox, - TextBox filterEncodingTextBox, - bool singleCodePageResults, - object data) - { - ConstructorHelper(characterSetComboBox, encodingComboBox, filterEncodingTextBox, singleCodePageResults, data); - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance to a combo box containing the character sets. - /// An instance to a combo box containing the encodings belonging to a character set. - /// A flag indicating if character sets containing only single encoding should be used. - /// Additional data to be assigned to an instance of the CharacterSetComboItem class. - public CharacterSetComboBuilder( - ComboBox characterSetComboBox, - ComboBox encodingComboBox, - bool singleCodePageResults, - object data) - { - ConstructorHelper(characterSetComboBox, encodingComboBox, null, singleCodePageResults, data); - } + ConstructorHelper(characterSetComboBox, encodingComboBox, filterEncodingTextBox, singleCodePageResults, data); + } - /// - /// A helper method for multiple constructor overloads. - /// - /// An instance to a combo box containing the character sets. - /// An instance to a combo box containing the encodings belonging to a character set. - /// A text box for searching for an encoding. - /// A flag indicating if character sets containing only single encoding should be used. - /// Additional data to be assigned to an instance of the CharacterSetComboItem class. - private void ConstructorHelper( - ComboBox characterSetComboBox, - ComboBox encodingComboBox, - TextBox filterEncodingTextBox, - bool singleCodePageResults, - object data) - { - // save the combo box instance to the class.. - CharacterSetComboBox = characterSetComboBox; + /// + /// Initializes a new instance of the class. + /// + /// An instance to a combo box containing the character sets. + /// An instance to a combo box containing the encodings belonging to a character set. + /// A flag indicating if character sets containing only single encoding should be used. + /// Additional data to be assigned to an instance of the CharacterSetComboItem class. + public CharacterSetComboBuilder( + ComboBox characterSetComboBox, + ComboBox encodingComboBox, + bool singleCodePageResults, + object data) + { + ConstructorHelper(characterSetComboBox, encodingComboBox, null, singleCodePageResults, data); + } - // save the combo box instance to the class.. - EncodingComboBox = encodingComboBox; + /// + /// A helper method for multiple constructor overloads. + /// + /// An instance to a combo box containing the character sets. + /// An instance to a combo box containing the encodings belonging to a character set. + /// A text box for searching for an encoding. + /// A flag indicating if character sets containing only single encoding should be used. + /// Additional data to be assigned to an instance of the CharacterSetComboItem class. + private void ConstructorHelper( + ComboBox characterSetComboBox, + ComboBox encodingComboBox, + TextBox filterEncodingTextBox, + bool singleCodePageResults, + object data) + { + // save the combo box instance to the class.. + CharacterSetComboBox = characterSetComboBox; - // save the text box instance to the class.. - FilterEncodingTextBox = filterEncodingTextBox; + // save the combo box instance to the class.. + EncodingComboBox = encodingComboBox; - // save the singleCodePageResults parameter value.. - SingleCodePageResults = singleCodePageResults; + // save the text box instance to the class.. + FilterEncodingTextBox = filterEncodingTextBox; - // save the data for the combo boxes.. - Data = data; + // save the singleCodePageResults parameter value.. + SingleCodePageResults = singleCodePageResults; - // subscribe the SelectedIndexChanged event.. - CharacterSetComboBox.SelectedIndexChanged += CharacterSetComboBox_SelectedIndexChanged; + // save the data for the combo boxes.. + Data = data; - // subscribe the SelectedIndexChanged event.. - EncodingComboBox.SelectedIndexChanged += EncodingComboBox_SelectedIndexChanged; + // subscribe the SelectedIndexChanged event.. + CharacterSetComboBox.SelectedIndexChanged += CharacterSetComboBox_SelectedIndexChanged; - // subscribe the text changed event.. - if (FilterEncodingTextBox != null) // this can be null for the constructor overload.. - { - FilterEncodingTextBox.TextChanged += FilterEncodingTextBox_TextChanged; - } + // subscribe the SelectedIndexChanged event.. + EncodingComboBox.SelectedIndexChanged += EncodingComboBox_SelectedIndexChanged; - // list the encodings.. - if (FilterEncodingTextBox != null) - { - CreateFilteredEncodingList(); - } - else - { - CreateUnFilteredEncodingList(); - } + // subscribe the text changed event.. + if (FilterEncodingTextBox != null) // this can be null for the constructor overload.. + { + FilterEncodingTextBox.TextChanged += FilterEncodingTextBox_TextChanged; } - /// - /// Creates a non-filtered encoding list for the combo box. - /// - private void CreateUnFilteredEncodingList() + // list the encodings.. + if (FilterEncodingTextBox != null) { - // get the character sets contained in the EncodingCharacterSet class.. - var charSets = EncodingCharacterSet.GetCharacterSetList(SingleCodePageResults); + CreateFilteredEncodingList(); + } + else + { + CreateUnFilteredEncodingList(); + } + } - CharacterSetComboBox.Items.Clear(); + /// + /// Creates a non-filtered encoding list for the combo box. + /// + private void CreateUnFilteredEncodingList() + { + // get the character sets contained in the EncodingCharacterSet class.. + var charSets = EncodingCharacterSet.GetCharacterSetList(SingleCodePageResults); - // loop through the character sets.. - foreach (var item in charSets) - { - // add the character sets to the characterSetComboBox.. - CharacterSetComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item, Tag = Data }); - } + CharacterSetComboBox.Items.Clear(); - // set the index for the combo box.. - if (CharacterSetComboBox.Items.Count > 0) - { - // ..if the combo box has any items.. - CharacterSetComboBox.SelectedIndex = 0; - } - else - { - // if there are no character sets, clear the encoding combo box as well.. - EncodingComboBox.Items.Clear(); - } + // loop through the character sets.. + foreach (var item in charSets) + { + // add the character sets to the characterSetComboBox.. + CharacterSetComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item, Tag = Data, }); } - /// - /// Creates a filtered encoding list for the combo box. - /// - private void CreateFilteredEncodingList() + // set the index for the combo box.. + if (CharacterSetComboBox.Items.Count > 0) { - string text = FilterText; + // ..if the combo box has any items.. + CharacterSetComboBox.SelectedIndex = 0; + } + else + { + // if there are no character sets, clear the encoding combo box as well.. + EncodingComboBox.Items.Clear(); + } + } - // if there is no filter the just list the encodings non-filtered.. - if (text == string.Empty) - { - CreateUnFilteredEncodingList(); - return; - } + /// + /// Creates a filtered encoding list for the combo box. + /// + private void CreateFilteredEncodingList() + { + string text = FilterText; - // get an instance of the EncodingCharacterSet class.. - var encodingCharacterSet = EncodingCharacterSet; + // if there is no filter the just list the encodings non-filtered.. + if (text == string.Empty) + { + CreateUnFilteredEncodingList(); + return; + } - // get the character sets contained in the EncodingCharacterSet class.. - var charSets = encodingCharacterSet.GetCharacterSetList(SingleCodePageResults); + // get an instance of the EncodingCharacterSet class.. + var encodingCharacterSet = EncodingCharacterSet; - CharacterSetComboBox.Items.Clear(); + // get the character sets contained in the EncodingCharacterSet class.. + var charSets = encodingCharacterSet.GetCharacterSetList(SingleCodePageResults); - // loop through the character sets.. - foreach (var item in charSets) - { - var encodings = encodingCharacterSet[item]; - encodings = encodings.Where(FilterEncoding); + CharacterSetComboBox.Items.Clear(); - if (encodings.ToList().Count > 0) - { - // add the character sets to the characterSetComboBox.. - CharacterSetComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item, Tag = Data }); - } - } + // loop through the character sets.. + foreach (var item in charSets) + { + var encodings = encodingCharacterSet[item]; + encodings = encodings.Where(FilterEncoding); - // set the index for the combo box.. - if (CharacterSetComboBox.Items.Count > 0) - { - // ..if the combo box has any items.. - CharacterSetComboBox.SelectedIndex = 0; - } - else + if (encodings.ToList().Count > 0) { - // if there are no character sets, clear the encoding combo box as well.. - EncodingComboBox.Items.Clear(); + // add the character sets to the characterSetComboBox.. + CharacterSetComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item, Tag = Data, }); } - EncodingSelected?.Invoke(this, new OnEncodingSelectedEventArgs { Data = Data, Encoding = CurrentEncoding }); } - /// - /// Gets the filter text for the encodings. - /// - private string FilterText => - FilterEncodingTextBox == null ? string.Empty : - string.IsNullOrWhiteSpace(FilterEncodingTextBox.Text) ? string.Empty : FilterEncodingTextBox.Text.Trim(' ').ToLowerInvariant(); - - /// - /// Checks if the given encoding matches the current filter text. - /// - /// The encoding to check. - /// True if the encoding matches the filter text; otherwise false; - private bool FilterEncoding(System.Text.Encoding encoding) + // set the index for the combo box.. + if (CharacterSetComboBox.Items.Count > 0) { - if (FilterText == string.Empty) - { - return true; - } + // ..if the combo box has any items.. + CharacterSetComboBox.SelectedIndex = 0; + } + else + { + // if there are no character sets, clear the encoding combo box as well.. + EncodingComboBox.Items.Clear(); + } + EncodingSelected?.Invoke(this, new OnEncodingSelectedEventArgs { Data = Data, Encoding = CurrentEncoding, }); + } - // split the filter text with space character.. - string[] filters = FilterText.Split(' '); + /// + /// Gets the filter text for the encodings. + /// + private string FilterText => + FilterEncodingTextBox == null ? string.Empty : + string.IsNullOrWhiteSpace(FilterEncodingTextBox.Text) ? string.Empty : FilterEncodingTextBox.Text.Trim(' ').ToLowerInvariant(); - bool match = true; - foreach (string filter in filters) - { - // check the string property match.. - match &= encoding.BodyName.ToLowerInvariant().Contains(filter) || - encoding.EncodingName.ToLowerInvariant().Contains(filter) || - encoding.HeaderName.ToLowerInvariant().Contains(filter) || - encoding.WebName.ToLowerInvariant().Contains(filter); - - // check the code page match.. - match |= encoding.CodePage.ToString() == filter; - } - return match; + /// + /// Checks if the given encoding matches the current filter text. + /// + /// The encoding to check. + /// True if the encoding matches the filter text; otherwise false; + private bool FilterEncoding(System.Text.Encoding encoding) + { + if (FilterText == string.Empty) + { + return true; } - // the filter text box text was changed.. - private void FilterEncodingTextBox_TextChanged(object sender, EventArgs e) + // split the filter text with space character.. + string[] filters = FilterText.Split(' '); + + bool match = true; + foreach (string filter in filters) { - // so filter the encodings.. - CreateFilteredEncodingList(); + // check the string property match.. + match &= encoding.BodyName.ToLowerInvariant().Contains(filter) || + encoding.EncodingName.ToLowerInvariant().Contains(filter) || + encoding.HeaderName.ToLowerInvariant().Contains(filter) || + encoding.WebName.ToLowerInvariant().Contains(filter); + + // check the code page match.. + match |= encoding.CodePage.ToString() == filter; } + return match; + } + + // the filter text box text was changed.. + private void FilterEncodingTextBox_TextChanged(object sender, EventArgs e) + { + // so filter the encodings.. + CreateFilteredEncodingList(); + } - /// - /// Selects the character set combo box and the encoding combo box selected items by given encoding. - /// - /// The encoding to set the selected index of the both combo boxes. - /// A flag indicating if character sets containing only single encoding should be used. - public void SelectItemByEncoding(System.Text.Encoding encoding, bool singleCodePageResults) + /// + /// Selects the character set combo box and the encoding combo box selected items by given encoding. + /// + /// The encoding to set the selected index of the both combo boxes. + /// A flag indicating if character sets containing only single encoding should be used. + public void SelectItemByEncoding(System.Text.Encoding encoding, bool singleCodePageResults) + { + var charSet = EncodingCharacterSet.GetCharacterSetsForEncoding(encoding, singleCodePageResults).FirstOrDefault(); + try { - var charSet = EncodingCharacterSet.GetCharacterSetsForEncoding(encoding, singleCodePageResults).FirstOrDefault(); - try + for (int i = 0; i < CharacterSetComboBox.Items.Count; i++) { - for (int i = 0; i < CharacterSetComboBox.Items.Count; i++) + var item = (CharacterSetComboItem)CharacterSetComboBox.Items[i]; + if (item.CharacterSet == charSet) { - var item = (CharacterSetComboItem)CharacterSetComboBox.Items[i]; - if (item.CharacterSet == charSet) - { - CharacterSetComboBox.SelectedIndex = i; - break; - } + CharacterSetComboBox.SelectedIndex = i; + break; } + } - for (int i = 0; i < EncodingComboBox.Items.Count; i++) + for (int i = 0; i < EncodingComboBox.Items.Count; i++) + { + var item = (CharacterSetComboItem)EncodingComboBox.Items[i]; + if (!item.ContainsEncoding) { - var item = (CharacterSetComboItem)EncodingComboBox.Items[i]; - if (!item.ContainsEncoding) - { - continue; - } + continue; + } - if (item.Encoding.CodePage == encoding.CodePage) - { - EncodingComboBox.SelectedIndex = i; - break; - } + if (item.Encoding.CodePage == encoding.CodePage) + { + EncodingComboBox.SelectedIndex = i; + break; } } - catch (Exception ex) - { - LastException = ex; - } } - - /// - /// Gets or sets the last exception thrown by an instance of this class. - /// - public static Exception LastException { get; set; } - - /// - /// Gets or sets the data associated with the combo box. - /// - private object Data { get; set; } - - /// - /// Gets or sets the character set ComboBox. - /// - private ComboBox CharacterSetComboBox { get; set; } - - /// - /// Gets or sets the encoding ComboBox. - /// - private ComboBox EncodingComboBox { get; set; } - - /// - /// Gets or sets the filter text box. - /// - private TextBox FilterEncodingTextBox { get; set; } - - /// - /// A flag indicating if character sets containing only single encoding should be used. - /// - private bool SingleCodePageResults { get; set; } - - /// - /// Gets or sets the encoding character set (a single instance is required and needs not to be disposed of). - /// - internal static EncodingCharacterSet EncodingCharacterSet { get; set; } = new EncodingCharacterSet(); - - // the character set combo box selected item was changed.. - private void CharacterSetComboBox_SelectedIndexChanged(object sender, EventArgs e) + catch (Exception ex) { - // get the combo box instance.. - ComboBox comboBox = (ComboBox)sender; + LastException = ex; + } + } - // a null check just in case.. - if (comboBox.SelectedItem != null) - { - // get the selected item of the combo box.. - CharacterSetComboItem item = (CharacterSetComboItem)comboBox.SelectedItem; - var encodings = EncodingCharacterSet[item.CharacterSet]; + /// + /// Gets or sets the last exception thrown by an instance of this class. + /// + public static Exception LastException { get; set; } + + /// + /// Gets or sets the data associated with the combo box. + /// + private object Data { get; set; } + + /// + /// Gets or sets the character set ComboBox. + /// + private ComboBox CharacterSetComboBox { get; set; } + + /// + /// Gets or sets the encoding ComboBox. + /// + private ComboBox EncodingComboBox { get; set; } + + /// + /// Gets or sets the filter text box. + /// + private TextBox FilterEncodingTextBox { get; set; } + + /// + /// A flag indicating if character sets containing only single encoding should be used. + /// + private bool SingleCodePageResults { get; set; } + + /// + /// Gets or sets the encoding character set (a single instance is required and needs not to be disposed of). + /// + internal static EncodingCharacterSet EncodingCharacterSet { get; set; } = new EncodingCharacterSet(); + + // the character set combo box selected item was changed.. + private void CharacterSetComboBox_SelectedIndexChanged(object sender, EventArgs e) + { + // get the combo box instance.. + ComboBox comboBox = (ComboBox)sender; + + // a null check just in case.. + if (comboBox.SelectedItem != null) + { + // get the selected item of the combo box.. + CharacterSetComboItem item = (CharacterSetComboItem)comboBox.SelectedItem; + var encodings = EncodingCharacterSet[item.CharacterSet]; - // clear the previous items from the encoding combo box.. - EncodingComboBox.Items.Clear(); + // clear the previous items from the encoding combo box.. + EncodingComboBox.Items.Clear(); - // loop through the encodings and add them the combo box containing the encodings.. - foreach (var encoding in encodings) + // loop through the encodings and add them the combo box containing the encodings.. + foreach (var encoding in encodings) + { + // if the encodings are being filtered.. + if (FilterText != string.Empty) { - // if the encodings are being filtered.. - if (FilterText != string.Empty) - { - if (FilterEncoding(encoding)) - { - // only add the matching encodings.. - EncodingComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item.CharacterSet, Encoding = encoding, Tag = Data }); - } - } - else + if (FilterEncoding(encoding)) { - // add all the encoding as the encodings are not being filtered.. - EncodingComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item.CharacterSet, Encoding = encoding, Tag = Data }); + // only add the matching encodings.. + EncodingComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item.CharacterSet, Encoding = encoding, Tag = Data, }); } } - - // set the index for the combo box.. - if (EncodingComboBox.Items.Count > 0) + else { - // ..if the combo box has any items.. - EncodingComboBox.SelectedIndex = 0; + // add all the encoding as the encodings are not being filtered.. + EncodingComboBox.Items.Add(new CharacterSetComboItem { CharacterSet = item.CharacterSet, Encoding = encoding, Tag = Data, }); } } + + // set the index for the combo box.. + if (EncodingComboBox.Items.Count > 0) + { + // ..if the combo box has any items.. + EncodingComboBox.SelectedIndex = 0; + } } + } - /// - /// Gets the currently selected encoding in the encoding combo box. - /// - public System.Text.Encoding CurrentEncoding => ((CharacterSetComboItem) EncodingComboBox.SelectedItem)?.Encoding; + /// + /// Gets the currently selected encoding in the encoding combo box. + /// + public System.Text.Encoding CurrentEncoding => ((CharacterSetComboItem) EncodingComboBox.SelectedItem)?.Encoding; - // the encoding combo box selected item was changed.. - private void EncodingComboBox_SelectedIndexChanged(object sender, EventArgs e) - { - EncodingSelected?.Invoke(this, new OnEncodingSelectedEventArgs { Data = Data, Encoding = CurrentEncoding }); - } + // the encoding combo box selected item was changed.. + private void EncodingComboBox_SelectedIndexChanged(object sender, EventArgs e) + { + EncodingSelected?.Invoke(this, new OnEncodingSelectedEventArgs { Data = Data, Encoding = CurrentEncoding, }); + } - /// - /// Releases all resources used by the class. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } + /// + /// Releases all resources used by the class. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - // unsubscribe the SelectedIndexChanged event.. - CharacterSetComboBox.SelectedIndexChanged -= CharacterSetComboBox_SelectedIndexChanged; + // unsubscribe the SelectedIndexChanged event.. + CharacterSetComboBox.SelectedIndexChanged -= CharacterSetComboBox_SelectedIndexChanged; - // unsubscribe the SelectedIndexChanged event.. - EncodingComboBox.SelectedIndexChanged -= EncodingComboBox_SelectedIndexChanged; + // unsubscribe the SelectedIndexChanged event.. + EncodingComboBox.SelectedIndexChanged -= EncodingComboBox_SelectedIndexChanged; - // unsubscribe the TextChanged event if the FilterEncodingTextBox is not null.. - if (FilterEncodingTextBox != null) - { - FilterEncodingTextBox.TextChanged -= FilterEncodingTextBox_TextChanged; - } + // unsubscribe the TextChanged event if the FilterEncodingTextBox is not null.. + if (FilterEncodingTextBox != null) + { + FilterEncodingTextBox.TextChanged -= FilterEncodingTextBox_TextChanged; } } + } - /// - /// A delegate for the EncodingMenuClicked event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnEncodingSelected(object sender, OnEncodingSelectedEventArgs e); + /// + /// A delegate for the EncodingMenuClicked event. + /// + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnEncodingSelected(object sender, OnEncodingSelectedEventArgs e); - /// - /// Occurs when an encoding menu item was clicked. - /// - public event OnEncodingSelected EncodingSelected; - } + /// + /// Occurs when an encoding menu item was clicked. + /// + public event OnEncodingSelected EncodingSelected; +} +/// +/// Event arguments for the EncodingSelected event. +/// +/// +public class OnEncodingSelectedEventArgs : EventArgs +{ /// - /// Event arguments for the EncodingSelected event. + /// Gets the encoding of the clicked encoding menu item. /// - /// - public class OnEncodingSelectedEventArgs : EventArgs - { - /// - /// Gets the encoding of the clicked encoding menu item. - /// - public System.Text.Encoding Encoding { get; internal set; } - - /// - /// Gets the data associated with the encoding menu item. - /// - public object Data { get; internal set; } - } + public System.Text.Encoding Encoding { get; internal set; } -} + /// + /// Gets the data associated with the encoding menu item. + /// + public object Data { get; internal set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetMenuBuilder.cs b/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetMenuBuilder.cs index cfa3dcdc..f94061ce 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetMenuBuilder.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/CharacterSetMenuBuilder.cs @@ -28,172 +28,171 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using ScriptNotepad.UtilityClasses.Common; -namespace ScriptNotepad.UtilityClasses.Encodings.CharacterSets +namespace ScriptNotepad.UtilityClasses.Encodings.CharacterSets; + +/// +/// A class to help to build a menu for known character sets (). +/// +public static class CharacterSetMenuBuilder { /// - /// A class to help to build a menu for known character sets (). + /// Creates the character set menu with encodings as sub menu items. /// - public static class CharacterSetMenuBuilder + /// The parent tool strip menu item. + /// A flag indicating if character sets containing only single encoding should be returned. + /// Additional data to be assigned to the encoding tool strip menu item. + public static void CreateCharacterSetMenu(ToolStripMenuItem parent, bool singleCodePageResults, object data) { - /// - /// Creates the character set menu with encodings as sub menu items. - /// - /// The parent tool strip menu item. - /// A flag indicating if character sets containing only single encoding should be returned. - /// Additional data to be assigned to the encoding tool strip menu item. - public static void CreateCharacterSetMenu(ToolStripMenuItem parent, bool singleCodePageResults, object data) - { - // create an instance of the EncodingCharacterSet class.. - var encodingCharacterSet = new EncodingCharacterSet(); + // create an instance of the EncodingCharacterSet class.. + var encodingCharacterSet = new EncodingCharacterSet(); - // get the character sets contained in the EncodingCharacterSet class.. - var charSets = encodingCharacterSet.GetCharacterSetList(singleCodePageResults); + // get the character sets contained in the EncodingCharacterSet class.. + var charSets = encodingCharacterSet.GetCharacterSetList(singleCodePageResults); - // loop through the character sets.. - foreach (var item in charSets) - { - // create a "dummy" menu to contain the actual encodings for the character set.. - ToolStripMenuItem menuItem = - new ToolStripMenuItem(encodingCharacterSet.GetCharacterSetName(item)) {Tag = item}; + // loop through the character sets.. + foreach (var item in charSets) + { + // create a "dummy" menu to contain the actual encodings for the character set.. + ToolStripMenuItem menuItem = + new ToolStripMenuItem(encodingCharacterSet.GetCharacterSetName(item)) {Tag = item, }; - // set the tag to contain the character set enumeration value.. + // set the tag to contain the character set enumeration value.. - // get the encodings for the character set.. - var encodings = encodingCharacterSet[item]; + // get the encodings for the character set.. + var encodings = encodingCharacterSet[item]; - // loop through the encodings within the character set.. - foreach (var encoding in encodings) + // loop through the encodings within the character set.. + foreach (var encoding in encodings) + { + if (encoding == null) { - if (encoding == null) - { - continue; - } - - // create a menu item for the encoding.. - DataToolStripMenuItem menuItemEncoding = new DataToolStripMenuItem(encoding.EncodingName) - { - Tag = encoding, Data = data - }; + continue; + } - // set the Tag property to contain the encoding.. + // create a menu item for the encoding.. + DataToolStripMenuItem menuItemEncoding = new DataToolStripMenuItem(encoding.EncodingName) + { + Tag = encoding, Data = data, + }; - // set the user given additional data for the menu item.. + // set the Tag property to contain the encoding.. - // subscribe the click event.. - menuItemEncoding.Click += MenuItemEncoding_Click; + // set the user given additional data for the menu item.. - // add the menu item to the character set menu.. - menuItem.DropDownItems.Add(menuItemEncoding); - } + // subscribe the click event.. + menuItemEncoding.Click += MenuItemEncoding_Click; - // add the character set menu item to the given parent menu.. - parent.DropDownItems.Add(menuItem); + // add the menu item to the character set menu.. + menuItem.DropDownItems.Add(menuItemEncoding); } + + // add the character set menu item to the given parent menu.. + parent.DropDownItems.Add(menuItem); } + } - /// - /// Disposes the character set menu constructed via the method. - /// - /// The parent tool strip menu item. - public static void DisposeCharacterSetMenu(ToolStripMenuItem parent) + /// + /// Disposes the character set menu constructed via the method. + /// + /// The parent tool strip menu item. + public static void DisposeCharacterSetMenu(ToolStripMenuItem parent) + { + List disposeList = new List(); + foreach (var item in parent.DropDownItems) { - List disposeList = new List(); - foreach (var item in parent.DropDownItems) + // only accept types of ToolStripMenuItem.. + if (item.GetType() != typeof(ToolStripMenuItem)) { - // only accept types of ToolStripMenuItem.. - if (item.GetType() != typeof(ToolStripMenuItem)) - { - continue; - } + continue; + } - // cast the object as ToolStripMenuItem.. - var charsetMenuItem = (ToolStripMenuItem)item; + // cast the object as ToolStripMenuItem.. + var charsetMenuItem = (ToolStripMenuItem)item; - // loop through the character set menu item's drop down items.. - foreach (var encodingItem in charsetMenuItem.DropDownItems) + // loop through the character set menu item's drop down items.. + foreach (var encodingItem in charsetMenuItem.DropDownItems) + { + // only accept types of DataToolStripMenuItem.. + if (encodingItem.GetType() != typeof(DataToolStripMenuItem)) { - // only accept types of DataToolStripMenuItem.. - if (encodingItem.GetType() != typeof(DataToolStripMenuItem)) - { - continue; - } - - // cast the object as DataToolStripMenuItem.. - var encodingMenuItem = (DataToolStripMenuItem)encodingItem; - - // unsubscribe the event handler.. - encodingMenuItem.Click -= MenuItemEncoding_Click; - - // add the menu item to the list of ToolStripMenuItems to disposed of.. - disposeList.Add(encodingMenuItem); + continue; } - // clear the drop down menu item.. - charsetMenuItem.DropDownItems.Clear(); + // cast the object as DataToolStripMenuItem.. + var encodingMenuItem = (DataToolStripMenuItem)encodingItem; + + // unsubscribe the event handler.. + encodingMenuItem.Click -= MenuItemEncoding_Click; // add the menu item to the list of ToolStripMenuItems to disposed of.. - disposeList.Add(charsetMenuItem); + disposeList.Add(encodingMenuItem); } - // clear the drop down items from the parent menu item.. - parent.DropDownItems.Clear(); + // clear the drop down menu item.. + charsetMenuItem.DropDownItems.Clear(); + + // add the menu item to the list of ToolStripMenuItems to disposed of.. + disposeList.Add(charsetMenuItem); + } + + // clear the drop down items from the parent menu item.. + parent.DropDownItems.Clear(); - // loop through the list of ToolStripMenuItems to disposed of.. - for (int i = 0; i < disposeList.Count; i++) + // loop through the list of ToolStripMenuItems to disposed of.. + for (int i = 0; i < disposeList.Count; i++) + { + // dispose.. + using (disposeList[i]) { - // dispose.. - using (disposeList[i]) - { - // null assignment isn't necessary, but the using clause - // would look a little "orphan" without that.. - disposeList[i] = null; - } + // null assignment isn't necessary, but the using clause + // would look a little "orphan" without that.. + disposeList[i] = null; } } + } - // an internal event handler to raise the EncodingMenuClicked event if subscribed.. - private static void MenuItemEncoding_Click(object sender, EventArgs e) - { - // get the sender and assume a type of DataToolStripMenuItem.. - DataToolStripMenuItem dataToolStripMenuItem = (DataToolStripMenuItem)sender; + // an internal event handler to raise the EncodingMenuClicked event if subscribed.. + private static void MenuItemEncoding_Click(object sender, EventArgs e) + { + // get the sender and assume a type of DataToolStripMenuItem.. + DataToolStripMenuItem dataToolStripMenuItem = (DataToolStripMenuItem)sender; - // raise the event if subscribed.. - EncodingMenuClicked?. - Invoke(sender, + // raise the event if subscribed.. + EncodingMenuClicked?. + Invoke(sender, new EncodingMenuClickEventArgs { Encoding = (System.Text.Encoding)dataToolStripMenuItem.Tag, - Data = dataToolStripMenuItem.Data + Data = dataToolStripMenuItem.Data, }); - } - - /// - /// A delegate for the EncodingMenuClicked event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnEncodingMenuClicked(object sender, EncodingMenuClickEventArgs e); - - /// - /// Occurs when an encoding menu item was clicked. - /// - public static event OnEncodingMenuClicked EncodingMenuClicked; } /// - /// Event arguments for the EncodingMenuClicked event. + /// A delegate for the EncodingMenuClicked event. /// - /// - public class EncodingMenuClickEventArgs: EventArgs - { - /// - /// Gets the encoding of the clicked encoding menu item. - /// - public System.Text.Encoding Encoding { get; internal set; } - - /// - /// Gets the data associated with the encoding menu item. - /// - public object Data { get; internal set; } - } + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnEncodingMenuClicked(object sender, EncodingMenuClickEventArgs e); + + /// + /// Occurs when an encoding menu item was clicked. + /// + public static event OnEncodingMenuClicked EncodingMenuClicked; } + +/// +/// Event arguments for the EncodingMenuClicked event. +/// +/// +public class EncodingMenuClickEventArgs: EventArgs +{ + /// + /// Gets the encoding of the clicked encoding menu item. + /// + public System.Text.Encoding Encoding { get; internal set; } + + /// + /// Gets the data associated with the encoding menu item. + /// + public object Data { get; internal set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/EncodingCharacterSet.cs b/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/EncodingCharacterSet.cs index 94d911aa..2e0bd66d 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/EncodingCharacterSet.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/CharacterSets/EncodingCharacterSet.cs @@ -28,446 +28,445 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Linq; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.Encodings.CharacterSets +namespace ScriptNotepad.UtilityClasses.Encodings.CharacterSets; + +/// +/// An enumeration containing different categories for different encodings. +/// +public enum CharacterSets { /// - /// An enumeration containing different categories for different encodings. + /// An enumeration value for the Arabic character sets. /// - public enum CharacterSets - { - /// - /// An enumeration value for the Arabic character sets. - /// - Arabic, - - /// - /// An enumeration value for the Baltic character sets. - /// - Baltic, - - /// - /// An enumeration value for the Canada character sets. - /// - Canada, - - /// - /// An enumeration value for the Cyrillic character sets. - /// - Cyrillic, - - /// - /// An enumeration value for the Central European character sets. - /// - CentralEuropean, - - /// - /// An enumeration value for the Chinese character sets. - /// - Chinese, - - /// - /// An enumeration value for the Denmark and Norway character sets. - /// - DenmarkNorway, - - /// - /// An enumeration value for the Finland and Sweden character sets. - /// - FinlandSweden, - - /// - /// An enumeration value for the France character sets. - /// - France, - - /// - /// An enumeration value for the German character sets. - /// - German, - - /// - /// An enumeration value for the Greek character sets. - /// - Greek, - - /// - /// An enumeration value for the Hebrew character sets. - /// - Hebrew, - - /// - /// An enumeration value for the Icelandic character sets. - /// - Icelandic, - - /// - /// An enumeration value for the Italy character sets. - /// - Italy, - - /// - /// An enumeration value for the Arabic character sets. - /// - Japanese, - - /// - /// An enumeration value for the Korean character sets. - /// - Korean, - - /// - /// An enumeration value for the Latin character sets. - /// - Latin, - - /// - /// An enumeration value for the Miscellaneous character sets. - /// - Miscellaneous, - - /// - /// An enumeration value for the Norwegian character sets. - /// - Norwegian, - - /// - /// An enumeration value for the Western European character sets. - /// - WesternEuropean, - - /// - /// An enumeration value for the Spain character sets. - /// - Spain, - - /// - /// An enumeration value for the Swedish character sets. - /// - Swedish, - - /// - /// An enumeration value for the Taiwan character sets. - /// - Taiwan, - - /// - /// An enumeration value for the Thai character sets. - /// - Thai, - - /// - /// An enumeration value for the Turkish character sets. - /// - Turkish, - - /// - /// An enumeration value for the Unicode character sets. - /// - Unicode, - - /// - /// An enumeration value for the Assamese character sets. - /// - Assamese, - - /// - /// An enumeration value for the Bengali character sets. - /// - Bengali, - - /// - /// An enumeration value for the Devanagari character sets. - /// - Devanagari, - - /// - /// An enumeration value for the Estonian character sets. - /// - Estonian, - - /// - /// An enumeration value for the Kannada character sets. - /// - Kannada, - - /// - /// An enumeration value for the Malayalam character sets. - /// - Malayalam, - - /// - /// An enumeration value for the Oriya character sets. - /// - Oriya, - - /// - /// An enumeration value for the Punjabi character sets. - /// - Punjabi, - - /// - /// An enumeration value for the Tamil character sets. - /// - Tamil, - - /// - /// An enumeration value for the Telugu character sets. - /// - Telugu, - - /// - /// An enumeration value for the Vietnamese character sets. - /// - Vietnamese, - - /// - /// An enumeration value for the single character sets. - /// - SingleCharacterSets - } + Arabic, + + /// + /// An enumeration value for the Baltic character sets. + /// + Baltic, + + /// + /// An enumeration value for the Canada character sets. + /// + Canada, + + /// + /// An enumeration value for the Cyrillic character sets. + /// + Cyrillic, + + /// + /// An enumeration value for the Central European character sets. + /// + CentralEuropean, + + /// + /// An enumeration value for the Chinese character sets. + /// + Chinese, + + /// + /// An enumeration value for the Denmark and Norway character sets. + /// + DenmarkNorway, + + /// + /// An enumeration value for the Finland and Sweden character sets. + /// + FinlandSweden, + + /// + /// An enumeration value for the France character sets. + /// + France, + + /// + /// An enumeration value for the German character sets. + /// + German, + + /// + /// An enumeration value for the Greek character sets. + /// + Greek, + + /// + /// An enumeration value for the Hebrew character sets. + /// + Hebrew, + + /// + /// An enumeration value for the Icelandic character sets. + /// + Icelandic, + + /// + /// An enumeration value for the Italy character sets. + /// + Italy, + + /// + /// An enumeration value for the Arabic character sets. + /// + Japanese, + + /// + /// An enumeration value for the Korean character sets. + /// + Korean, + + /// + /// An enumeration value for the Latin character sets. + /// + Latin, + + /// + /// An enumeration value for the Miscellaneous character sets. + /// + Miscellaneous, + + /// + /// An enumeration value for the Norwegian character sets. + /// + Norwegian, + + /// + /// An enumeration value for the Western European character sets. + /// + WesternEuropean, + + /// + /// An enumeration value for the Spain character sets. + /// + Spain, + + /// + /// An enumeration value for the Swedish character sets. + /// + Swedish, + + /// + /// An enumeration value for the Taiwan character sets. + /// + Taiwan, /// - /// A class which categorizes the .NET character encodings under different localizable name-category pairs. + /// An enumeration value for the Thai character sets. /// - public class EncodingCharacterSet: ErrorHandlingBase + Thai, + + /// + /// An enumeration value for the Turkish character sets. + /// + Turkish, + + /// + /// An enumeration value for the Unicode character sets. + /// + Unicode, + + /// + /// An enumeration value for the Assamese character sets. + /// + Assamese, + + /// + /// An enumeration value for the Bengali character sets. + /// + Bengali, + + /// + /// An enumeration value for the Devanagari character sets. + /// + Devanagari, + + /// + /// An enumeration value for the Estonian character sets. + /// + Estonian, + + /// + /// An enumeration value for the Kannada character sets. + /// + Kannada, + + /// + /// An enumeration value for the Malayalam character sets. + /// + Malayalam, + + /// + /// An enumeration value for the Oriya character sets. + /// + Oriya, + + /// + /// An enumeration value for the Punjabi character sets. + /// + Punjabi, + + /// + /// An enumeration value for the Tamil character sets. + /// + Tamil, + + /// + /// An enumeration value for the Telugu character sets. + /// + Telugu, + + /// + /// An enumeration value for the Vietnamese character sets. + /// + Vietnamese, + + /// + /// An enumeration value for the single character sets. + /// + SingleCharacterSets, +} + +/// +/// A class which categorizes the .NET character encodings under different localizable name-category pairs. +/// +public class EncodingCharacterSet: ErrorHandlingBase +{ + /// + /// An internal list of character sets and their encodings. + /// + private readonly List, CharacterSets>> internalList = new List, CharacterSets>>(); + + /// + /// An internal list of character set names with their corresponding enumeration pairs. + /// + private static readonly List> InternalEnumDescriptionPairs = new List>(); + + /// + /// Constructs the internal lists for to be used with this class. + /// + private void ConstructInternalList() { - /// - /// An internal list of character sets and their encodings. - /// - private readonly List, CharacterSets>> internalList = new List, CharacterSets>>(); - - /// - /// An internal list of character set names with their corresponding enumeration pairs. - /// - private static readonly List> InternalEnumDescriptionPairs = new List>(); - - /// - /// Constructs the internal lists for to be used with this class. - /// - private void ConstructInternalList() + #region CharacterSetList + internalList.Clear(); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 708, 720, 864, 1256, 10004, 20420, 28596, 57010, }.ToList(), CharacterSets.Arabic)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 775, 1257, 28594, }.ToList(), CharacterSets.Baltic)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 37, 863, 1140, }.ToList(), CharacterSets.Canada)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 855, 866, 1251, 10007, 20866, 20880, 21025, 21866, 28595, }.ToList(), CharacterSets.Cyrillic)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 852, 1250, 10029, 28592, }.ToList(), CharacterSets.CentralEuropean)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 936, 950, 10002, 10008, 20000, 20002, 20936, 50227, 51936, 52936, 54936, }.ToList(), CharacterSets.Chinese)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1142, 20277, }.ToList(), CharacterSets.DenmarkNorway)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1143, 20278, }.ToList(), CharacterSets.FinlandSweden)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1147, 20297, }.ToList(), CharacterSets.France)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1141, 20106, 20273, }.ToList(), CharacterSets.German)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 737, 869, 875, 1253, 10006, 20423, 28597, }.ToList(), CharacterSets.Greek)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 862, 1255, 10005, 20424, 28598, 38598, }.ToList(), CharacterSets.Hebrew)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 861, 1149, 10079, 20871, }.ToList(), CharacterSets.Icelandic)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1144, 20280, }.ToList(), CharacterSets.Italy)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 932, 10001, 20290, 20932, 50220, 50221, 50222, 51932, }.ToList(), CharacterSets.Japanese)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 949, 1361, 10003, 20833, 20949, 50225, 51949, }.ToList(), CharacterSets.Korean)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 858, 870, 1026, 1047, 20924, 28593, 28605, }.ToList(), CharacterSets.Latin)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 500, 860, 865, 1146, 1148, 10010, 10017, 10082, 20127, 20261, 20269, 20285, 29001, }.ToList(), CharacterSets.Miscellaneous)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1142, 20108, 20277, }.ToList(), CharacterSets.Norwegian)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 850, 1252, 10000, 20105, 28591, }.ToList(), CharacterSets.WesternEuropean)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1145, 20284, }.ToList(), CharacterSets.Spain)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1143, 20107, 20278, }.ToList(), CharacterSets.Swedish)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 20001, 20003, 20004, 20005, }.ToList(), CharacterSets.Taiwan)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 874, 10021, 20838, }.ToList(), CharacterSets.Thai)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 857, 1026, 1254, 10081, 20905, 28599, }.ToList(), CharacterSets.Turkish)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 437, 1200, 1201, 12000, 12001, 65000, 65001, }.ToList(), CharacterSets.Unicode)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57006, }.ToList(), CharacterSets.Assamese)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57003, }.ToList(), CharacterSets.Bengali)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57002, }.ToList(), CharacterSets.Devanagari)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 28603, }.ToList(), CharacterSets.Estonian)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57008, }.ToList(), CharacterSets.Kannada)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57009, }.ToList(), CharacterSets.Malayalam)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57007, }.ToList(), CharacterSets.Oriya)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57011, }.ToList(), CharacterSets.Punjabi)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57004, }.ToList(), CharacterSets.Tamil)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57005, }.ToList(), CharacterSets.Telugu)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1258, }.ToList(), CharacterSets.Vietnamese)); + internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57006, 57003, 57002, 28603, 57008, 57009, 57007, 57011, 57004, 57005, 1258, }.ToList(), CharacterSets.SingleCharacterSets)); + #endregion + + // the static list will be created with a constructor.. + if (InternalEnumDescriptionPairs.Count == 0) { - #region CharacterSetList - internalList.Clear(); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 708, 720, 864, 1256, 10004, 20420, 28596, 57010 }.ToList(), CharacterSets.Arabic)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 775, 1257, 28594 }.ToList(), CharacterSets.Baltic)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 37, 863, 1140 }.ToList(), CharacterSets.Canada)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 855, 866, 1251, 10007, 20866, 20880, 21025, 21866, 28595 }.ToList(), CharacterSets.Cyrillic)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 852, 1250, 10029, 28592 }.ToList(), CharacterSets.CentralEuropean)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 936, 950, 10002, 10008, 20000, 20002, 20936, 50227, 51936, 52936, 54936 }.ToList(), CharacterSets.Chinese)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1142, 20277 }.ToList(), CharacterSets.DenmarkNorway)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1143, 20278 }.ToList(), CharacterSets.FinlandSweden)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1147, 20297 }.ToList(), CharacterSets.France)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1141, 20106, 20273 }.ToList(), CharacterSets.German)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 737, 869, 875, 1253, 10006, 20423, 28597 }.ToList(), CharacterSets.Greek)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 862, 1255, 10005, 20424, 28598, 38598 }.ToList(), CharacterSets.Hebrew)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 861, 1149, 10079, 20871 }.ToList(), CharacterSets.Icelandic)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1144, 20280 }.ToList(), CharacterSets.Italy)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 932, 10001, 20290, 20932, 50220, 50221, 50222, 51932 }.ToList(), CharacterSets.Japanese)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 949, 1361, 10003, 20833, 20949, 50225, 51949 }.ToList(), CharacterSets.Korean)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 858, 870, 1026, 1047, 20924, 28593, 28605 }.ToList(), CharacterSets.Latin)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 500, 860, 865, 1146, 1148, 10010, 10017, 10082, 20127, 20261, 20269, 20285, 29001 }.ToList(), CharacterSets.Miscellaneous)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1142, 20108, 20277 }.ToList(), CharacterSets.Norwegian)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 850, 1252, 10000, 20105, 28591 }.ToList(), CharacterSets.WesternEuropean)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1145, 20284 }.ToList(), CharacterSets.Spain)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1143, 20107, 20278 }.ToList(), CharacterSets.Swedish)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 20001, 20003, 20004, 20005 }.ToList(), CharacterSets.Taiwan)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 874, 10021, 20838 }.ToList(), CharacterSets.Thai)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 857, 1026, 1254, 10081, 20905, 28599 }.ToList(), CharacterSets.Turkish)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 437, 1200, 1201, 12000, 12001, 65000, 65001 }.ToList(), CharacterSets.Unicode)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57006 }.ToList(), CharacterSets.Assamese)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57003 }.ToList(), CharacterSets.Bengali)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57002 }.ToList(), CharacterSets.Devanagari)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 28603 }.ToList(), CharacterSets.Estonian)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57008 }.ToList(), CharacterSets.Kannada)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57009 }.ToList(), CharacterSets.Malayalam)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57007 }.ToList(), CharacterSets.Oriya)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57011 }.ToList(), CharacterSets.Punjabi)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57004 }.ToList(), CharacterSets.Tamil)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57005 }.ToList(), CharacterSets.Telugu)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 1258 }.ToList(), CharacterSets.Vietnamese)); - internalList.Add(new KeyValuePair, CharacterSets>(new[] { 57006, 57003, 57002, 28603, 57008, 57009, 57007, 57011, 57004, 57005, 1258 }.ToList(), CharacterSets.SingleCharacterSets)); - #endregion - - // the static list will be created with a constructor.. - if (InternalEnumDescriptionPairs.Count == 0) - { - ConstructInternalCharacterSetEnumNamePairs(); - } + ConstructInternalCharacterSetEnumNamePairs(); } + } - /// - /// Constructs the internal character set-enumeration pairs. - /// - private static void ConstructInternalCharacterSetEnumNamePairs() - { - #region CharacterSetEnumNamePairs - InternalEnumDescriptionPairs.Clear(); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Arabic, "Arabic")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Baltic, "Baltic")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Canada, "Canada")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Cyrillic, "Cyrillic")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.CentralEuropean, "Central European")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Chinese, "Chinese")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.DenmarkNorway, "Denmark-Norway")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.FinlandSweden, "Finland-Sweden")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.France, "France")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.German, "German")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Greek, "Greek")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Hebrew, "Hebrew")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Icelandic, "Icelandic")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Italy, "Italy")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Japanese, "Japanese")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Korean, "Korean")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Latin, "Latin")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Miscellaneous, "Miscellaneous")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Norwegian, "Norwegian")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.WesternEuropean, "Western European")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Spain, "Spain")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Swedish, "Swedish")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Taiwan, "Taiwan")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Thai, "Thai")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Turkish, "Turkish")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Unicode, "Unicode")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Assamese, "Assamese")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Bengali, "Bengali")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Devanagari, "Devanagari")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Estonian, "Estonian")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Kannada, "Kannada")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Malayalam, "Malayalam")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Oriya, "Oriya")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Punjabi, "Punjabi")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Tamil, "Tamil")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Telugu, "Telugu")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Vietnamese, "Vietnamese")); - InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.SingleCharacterSets, "Single Character Sets")); - #endregion - } + /// + /// Constructs the internal character set-enumeration pairs. + /// + private static void ConstructInternalCharacterSetEnumNamePairs() + { + #region CharacterSetEnumNamePairs + InternalEnumDescriptionPairs.Clear(); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Arabic, "Arabic")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Baltic, "Baltic")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Canada, "Canada")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Cyrillic, "Cyrillic")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.CentralEuropean, "Central European")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Chinese, "Chinese")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.DenmarkNorway, "Denmark-Norway")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.FinlandSweden, "Finland-Sweden")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.France, "France")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.German, "German")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Greek, "Greek")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Hebrew, "Hebrew")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Icelandic, "Icelandic")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Italy, "Italy")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Japanese, "Japanese")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Korean, "Korean")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Latin, "Latin")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Miscellaneous, "Miscellaneous")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Norwegian, "Norwegian")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.WesternEuropean, "Western European")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Spain, "Spain")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Swedish, "Swedish")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Taiwan, "Taiwan")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Thai, "Thai")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Turkish, "Turkish")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Unicode, "Unicode")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Assamese, "Assamese")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Bengali, "Bengali")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Devanagari, "Devanagari")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Estonian, "Estonian")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Kannada, "Kannada")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Malayalam, "Malayalam")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Oriya, "Oriya")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Punjabi, "Punjabi")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Tamil, "Tamil")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Telugu, "Telugu")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.Vietnamese, "Vietnamese")); + InternalEnumDescriptionPairs.Add(new KeyValuePair(CharacterSets.SingleCharacterSets, "Single Character Sets")); + #endregion + } - /// - /// Initializes a new instance of the class. - /// - public EncodingCharacterSet() - { - // make the internal list to be used with this class.. - ConstructInternalList(); - } + /// + /// Initializes a new instance of the class. + /// + public EncodingCharacterSet() + { + // make the internal list to be used with this class.. + ConstructInternalList(); + } - /// - /// Gets the character set list. - /// - /// A flag indicating if character sets containing only single encoding should be returned. - /// A collection of CharacterSets enumeration based on the given parameters. - public IEnumerable GetCharacterSetList(bool singleCodePageResults) + /// + /// Gets the character set list. + /// + /// A flag indicating if character sets containing only single encoding should be returned. + /// A collection of CharacterSets enumeration based on the given parameters. + public IEnumerable GetCharacterSetList(bool singleCodePageResults) + { + foreach (var item in internalList) { - foreach (var item in internalList) + if (item.Key.Count == 1 && !singleCodePageResults) { - if (item.Key.Count == 1 && !singleCodePageResults) - { - continue; - } - yield return item.Value; + continue; } + yield return item.Value; } + } - /// - /// Gets the character sets list for the given encoding. - /// - /// The encoding to be used to get the character sets the encoding belongs to. - /// A flag indicating if character sets containing only single encoding should be returned. - /// A collection of CharacterSets enumeration based on the given parameters. - public IEnumerable GetCharacterSetsForEncoding(Encoding encoding, bool singleCodePageResults) + /// + /// Gets the character sets list for the given encoding. + /// + /// The encoding to be used to get the character sets the encoding belongs to. + /// A flag indicating if character sets containing only single encoding should be returned. + /// A collection of CharacterSets enumeration based on the given parameters. + public IEnumerable GetCharacterSetsForEncoding(Encoding encoding, bool singleCodePageResults) + { + foreach (var item in internalList) { - foreach (var item in internalList) + if (item.Key.Count == 1 && !singleCodePageResults) { - if (item.Key.Count == 1 && !singleCodePageResults) - { - continue; - } + continue; + } - // loop through the code pages of the character set.. - foreach (var codePages in item.Key) + // loop through the code pages of the character set.. + foreach (var codePages in item.Key) + { + // if a match is found.. + if (codePages == encoding.CodePage) { - // if a match is found.. - if (codePages == encoding.CodePage) - { - // ..add it to the resulting collection.. - yield return item.Value; - } + // ..add it to the resulting collection.. + yield return item.Value; } } } + } - /// - /// Gets the name of the character set. - /// - /// The CharacterSets enumeration value. - /// A name for a given CharacterSets enumeration. - public string GetCharacterSetName(CharacterSets characterSets) + /// + /// Gets the name of the character set. + /// + /// The CharacterSets enumeration value. + /// A name for a given CharacterSets enumeration. + public string GetCharacterSetName(CharacterSets characterSets) + { + int idx = InternalEnumDescriptionPairs.FindIndex(f => f.Key == characterSets); + return idx != -1 ? InternalEnumDescriptionPairs[idx].Value : string.Empty; + } + + /// + /// Localizes the name of the character set. + /// + /// An enumeration of the character set of which to give a new name. + /// A new name (hopefully localized) for the character set. + public void LocalizeCharacterSetName(CharacterSets characterSets, string name) + { + if (name.Trim() == string.Empty) { - int idx = InternalEnumDescriptionPairs.FindIndex(f => f.Key == characterSets); - return idx != -1 ? InternalEnumDescriptionPairs[idx].Value : string.Empty; + return; } - - /// - /// Localizes the name of the character set. - /// - /// An enumeration of the character set of which to give a new name. - /// A new name (hopefully localized) for the character set. - public void LocalizeCharacterSetName(CharacterSets characterSets, string name) + int idx = InternalEnumDescriptionPairs.FindIndex(f => f.Key == characterSets); + if (idx != -1) { - if (name.Trim() == string.Empty) - { - return; - } - int idx = InternalEnumDescriptionPairs.FindIndex(f => f.Key == characterSets); - if (idx != -1) - { - InternalEnumDescriptionPairs[idx] = new KeyValuePair(characterSets, name); - } + InternalEnumDescriptionPairs[idx] = new KeyValuePair(characterSets, name); } + } - /// - /// Gets a collection the class instances corresponding to the given character set enumeration. - /// - /// An enumeration value indicating which character set's encodings to get. - /// A collection of class instances for the given character set enumeration. - public IEnumerable this[CharacterSets characterSets] + /// + /// Gets a collection the class instances corresponding to the given character set enumeration. + /// + /// An enumeration value indicating which character set's encodings to get. + /// A collection of class instances for the given character set enumeration. + public IEnumerable this[CharacterSets characterSets] + { + get { - get + var result = new List(); + int idx = internalList.FindIndex(f => f.Value == characterSets); + if (idx != -1) { - var result = new List(); - int idx = internalList.FindIndex(f => f.Value == characterSets); - if (idx != -1) + foreach (int encodingNum in internalList[idx].Key) { - foreach (int encodingNum in internalList[idx].Key) + try { + var encoding = Encoding.GetEncoding(encodingNum); + result.Add(encoding); + } + catch (Exception ex) + { + ExceptionLogAction?.Invoke(ex); try { - var encoding = Encoding.GetEncoding(encodingNum); - result.Add(encoding); - } - catch (Exception ex) - { - ExceptionLogAction?.Invoke(ex); - try - { - var encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingNum); + var encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingNum); - if (encoding != null) - { - result.Add(encoding); - } - } - catch (Exception exInner) + if (encoding != null) { - ExceptionLogAction?.Invoke(exInner); + result.Add(encoding); } } + catch (Exception exInner) + { + ExceptionLogAction?.Invoke(exInner); + } } } - - return result; } + + return result; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/DetectEncoding.cs b/ScriptNotepad/UtilityClasses/Encodings/DetectEncoding.cs index 50ebc846..12097bbe 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/DetectEncoding.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/DetectEncoding.cs @@ -29,287 +29,286 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using UtfUnknown; -namespace ScriptNotepad.UtilityClasses.Encodings +namespace ScriptNotepad.UtilityClasses.Encodings; + +/// +/// A class to help to detect an encoding of a text. +/// +// (C): https://en.wikipedia.org/wiki/ISO/IEC_8859-1 +// (C): https://en.wikipedia.org/wiki/Byte_order_mar +// (C): https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character +public class DetectEncoding: ErrorHandlingBase { /// - /// A class to help to detect an encoding of a text. + /// The UTF8 byte order marks. /// - // (C): https://en.wikipedia.org/wiki/ISO/IEC_8859-1 - // (C): https://en.wikipedia.org/wiki/Byte_order_mar - // (C): https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character - public class DetectEncoding: ErrorHandlingBase + internal static readonly List Utf8Bom = new List(new byte[] {0xEF, 0xBB, 0xBF, }); + + // ReSharper disable once IdentifierTypo + /// + /// The UTF16 big endian byte order marks. + /// + internal static readonly List Utf16BigEndianBom = new List(new byte[] {0xFE, 0xFF, }); + + // ReSharper disable once IdentifierTypo + /// + /// The UTF16 little endian byte order marks. + /// + internal static readonly List Utf16LittleEndianBom = new List(new byte[] {0xFF, 0xFE, }); + + // ReSharper disable once IdentifierTypo + /// + /// The UTF23 big endian byte order marks. + /// + internal static readonly List Utf32BigEndianBom = new List(new byte[] {0x00, 0x00, 0xFE, 0xFF, }); + + // ReSharper disable once IdentifierTypo + /// + /// The UTF23 little endian byte order marks. + /// + internal static readonly List Utf32LittleEndianBom = new List(new byte[] {0xFF, 0xFE, 0x00, 0x00, }); + + /// + /// The first variant of the UTF7 byte order marks. + /// + internal static readonly List Utf7Bom1 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x38, }); + + /// + /// The second variant of the UTF7 byte order marks. + /// + internal static readonly List Utf7Bom2 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x39, }); + + /// + /// The third variant of the UTF7 byte order marks. + /// + internal static readonly List Utf7Bom3 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x2B, }); + + /// + /// The fourth variant of the UTF7 byte order marks. + /// + internal static readonly List Utf7Bom4 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x2F, }); + + /// + /// The fifth variant of the UTF7 byte order marks. + /// + internal static readonly List Utf7Bom5 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x38, 0x2D, }); + + /// + /// The UTF8 replacement character. + /// + // ReSharper disable once UnusedMember.Local + internal static readonly List Utf8ReplacementChar = new List(new byte[] {0xFF, 0xFD, }); + + /// + /// Checks if a given byte array matches a given byte order mark. + /// + /// The bytes to verify the byte order mark from. + /// The byte order mark (BOM). + /// true if given bytes matches the given byte order mark, false otherwise. + internal static bool ByteMatch(byte[] bytes, List bom) { - /// - /// The UTF8 byte order marks. - /// - internal static readonly List Utf8Bom = new List(new byte[] {0xEF, 0xBB, 0xBF}); - - // ReSharper disable once IdentifierTypo - /// - /// The UTF16 big endian byte order marks. - /// - internal static readonly List Utf16BigEndianBom = new List(new byte[] {0xFE, 0xFF}); - - // ReSharper disable once IdentifierTypo - /// - /// The UTF16 little endian byte order marks. - /// - internal static readonly List Utf16LittleEndianBom = new List(new byte[] {0xFF, 0xFE}); - - // ReSharper disable once IdentifierTypo - /// - /// The UTF23 big endian byte order marks. - /// - internal static readonly List Utf32BigEndianBom = new List(new byte[] {0x00, 0x00, 0xFE, 0xFF}); - - // ReSharper disable once IdentifierTypo - /// - /// The UTF23 little endian byte order marks. - /// - internal static readonly List Utf32LittleEndianBom = new List(new byte[] {0xFF, 0xFE, 0x00, 0x00}); - - /// - /// The first variant of the UTF7 byte order marks. - /// - internal static readonly List Utf7Bom1 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x38}); - - /// - /// The second variant of the UTF7 byte order marks. - /// - internal static readonly List Utf7Bom2 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x39}); - - /// - /// The third variant of the UTF7 byte order marks. - /// - internal static readonly List Utf7Bom3 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x2B}); - - /// - /// The fourth variant of the UTF7 byte order marks. - /// - internal static readonly List Utf7Bom4 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x2F}); - - /// - /// The fifth variant of the UTF7 byte order marks. - /// - internal static readonly List Utf7Bom5 = new List(new byte[] {0x2B, 0x2F, 0x76, 0x38, 0x2D}); - - /// - /// The UTF8 replacement character. - /// - // ReSharper disable once UnusedMember.Local - internal static readonly List Utf8ReplacementChar = new List(new byte[] {0xFF, 0xFD}); - - /// - /// Checks if a given byte array matches a given byte order mark. - /// - /// The bytes to verify the byte order mark from. - /// The byte order mark (BOM). - /// true if given bytes matches the given byte order mark, false otherwise. - internal static bool ByteMatch(byte[] bytes, List bom) + // avoid a useless exception.. + if (bytes.Length < bom.Count) { - // avoid a useless exception.. - if (bytes.Length < bom.Count) + return false; + } + + // compare the BOM bytes.. + for (int i = 0; i < bom.Count; i++) + { + if (bytes[i] != bom[i]) { + // in-equality, so failure.. return false; } + } - // compare the BOM bytes.. - for (int i = 0; i < bom.Count; i++) - { - if (bytes[i] != bom[i]) - { - // in-equality, so failure.. - return false; - } - } + // success.. + return true; + } - // success.. - return true; - } + /// + /// Determines whether the specified byte array is a byte-order-mark (BOM). + /// + /// The byte array to check for a BOM. + /// true if the specified byte array has a byte-order-mark (BOM); otherwise, false. + public static bool HasBom(byte[] bom) + { + List bomBytes = new List(bom); + return ByteMatch(Utf8Bom.ToArray(), bomBytes) || + ByteMatch(Utf16BigEndianBom.ToArray(), bomBytes) || + ByteMatch(Utf16LittleEndianBom.ToArray(), bomBytes) || + ByteMatch(Utf32BigEndianBom.ToArray(), bomBytes) || + ByteMatch(Utf32LittleEndianBom.ToArray(), bomBytes); + } - /// - /// Determines whether the specified byte array is a byte-order-mark (BOM). - /// - /// The byte array to check for a BOM. - /// true if the specified byte array has a byte-order-mark (BOM); otherwise, false. - public static bool HasBom(byte[] bom) - { - List bomBytes = new List(bom); - return ByteMatch(Utf8Bom.ToArray(), bomBytes) || - ByteMatch(Utf16BigEndianBom.ToArray(), bomBytes) || - ByteMatch(Utf16LittleEndianBom.ToArray(), bomBytes) || - ByteMatch(Utf32BigEndianBom.ToArray(), bomBytes) || - ByteMatch(Utf32LittleEndianBom.ToArray(), bomBytes); - } + /// + /// Determines whether the specified byte array is a big-endian byte-order-mark (BOM). + /// + /// The byte array to check for a byte order. + /// true if the specified byte array is a big-endian byte-order-mark (BOM); otherwise, false. + public static bool IsBigEndian(byte[] bom) + { + List bomBytes = new List(bom); + return ByteMatch(Utf16BigEndianBom.ToArray(), bomBytes) || + ByteMatch(Utf32BigEndianBom.ToArray(), bomBytes); + } - /// - /// Determines whether the specified byte array is a big-endian byte-order-mark (BOM). - /// - /// The byte array to check for a byte order. - /// true if the specified byte array is a big-endian byte-order-mark (BOM); otherwise, false. - public static bool IsBigEndian(byte[] bom) - { - List bomBytes = new List(bom); - return ByteMatch(Utf16BigEndianBom.ToArray(), bomBytes) || - ByteMatch(Utf32BigEndianBom.ToArray(), bomBytes); - } + /// + /// Gets the encoding comparison bytes (the first five bytes of the stream). + /// + /// The stream get the bytes from. + /// System.Byte[]. + internal static byte[] GetEncodingComparisonBytes(MemoryStream stream) + { + stream.Position = 0; - /// - /// Gets the encoding comparison bytes (the first five bytes of the stream). - /// - /// The stream get the bytes from. - /// System.Byte[]. - internal static byte[] GetEncodingComparisonBytes(MemoryStream stream) - { - stream.Position = 0; + byte[] bytes = new byte[5]; - byte[] bytes = new byte[5]; + stream.Read(bytes, 0, 5); - stream.Read(bytes, 0, 5); + return bytes; + } - return bytes; - } + /// + /// Gets or sets the fall back encoding if no other encodings are detected. + /// + public static Encoding FallBackEncoding { get; set; } = Encoding.Default; - /// - /// Gets or sets the fall back encoding if no other encodings are detected. - /// - public static Encoding FallBackEncoding { get; set; } = Encoding.Default; - - /// - /// Gets an from a given byte array. - /// - /// The byte array to get the encoding from. - /// The detected . - public static Encoding FromBytes(byte[] bytes) - { - using var memoryStream = new MemoryStream(bytes); - return FromStream(memoryStream); - } + /// + /// Gets an from a given byte array. + /// + /// The byte array to get the encoding from. + /// The detected . + public static Encoding FromBytes(byte[] bytes) + { + using var memoryStream = new MemoryStream(bytes); + return FromStream(memoryStream); + } - /// - /// Gets an from a given list of bytes. - /// - /// The list of bytes to get the encoding from. - /// The detected . - public static Encoding FromBytes(List bytes) - { - using var memoryStream = new MemoryStream(bytes.ToArray()); - return FromStream(memoryStream); - } + /// + /// Gets an from a given list of bytes. + /// + /// The list of bytes to get the encoding from. + /// The detected . + public static Encoding FromBytes(List bytes) + { + using var memoryStream = new MemoryStream(bytes.ToArray()); + return FromStream(memoryStream); + } - /// - /// Gets an from a given file stream. - /// - /// The stream to get the encoding from. - /// The detected . - public static Encoding FromStream(FileStream stream) - { - using var memoryStream = new MemoryStream(); - stream.CopyTo(memoryStream); - return FromStream(memoryStream); - } + /// + /// Gets an from a given file stream. + /// + /// The stream to get the encoding from. + /// The detected . + public static Encoding FromStream(FileStream stream) + { + using var memoryStream = new MemoryStream(); + stream.CopyTo(memoryStream); + return FromStream(memoryStream); + } - /// - /// Gets the from value. - /// - /// The result of the call. - /// The detected encoding. - public static Encoding GetPrimaryFromCharsetDetector(DetectionResult result) - { - var resultOrdered = - result.Details.OrderByDescending(f => f.Confidence).ThenBy( - e => e.Encoding is UTF7Encoding || e.Encoding is UTF8Encoding || e.Encoding is UnicodeEncoding || - e.Encoding is UTF32Encoding).ToList(); + /// + /// Gets the from value. + /// + /// The result of the call. + /// The detected encoding. + public static Encoding GetPrimaryFromCharsetDetector(DetectionResult result) + { + var resultOrdered = + result.Details.OrderByDescending(f => f.Confidence).ThenBy( + e => e.Encoding is UTF7Encoding || e.Encoding is UTF8Encoding || e.Encoding is UnicodeEncoding || + e.Encoding is UTF32Encoding).ToList(); - var encoding = resultOrdered.FirstOrDefault()?.Encoding; + var encoding = resultOrdered.FirstOrDefault()?.Encoding; - if (encoding != null) + if (encoding != null) + { + if (encoding is UTF8Encoding) { - if (encoding is UTF8Encoding) - { - return new UTF8Encoding(false); - } - - if (encoding is UnicodeEncoding unicodeEncoding) - { - return new UnicodeEncoding(unicodeEncoding.IsBigEndian(), false); - } - - if (encoding is UTF32Encoding utf32Encoding) - { - return new UnicodeEncoding(utf32Encoding.IsBigEndian(), false); - } + return new UTF8Encoding(false); } - return encoding; + if (encoding is UnicodeEncoding unicodeEncoding) + { + return new UnicodeEncoding(unicodeEncoding.IsBigEndian(), false); + } + + if (encoding is UTF32Encoding utf32Encoding) + { + return new UnicodeEncoding(utf32Encoding.IsBigEndian(), false); + } } - /// - /// Gets an from a given memory stream. - /// - /// The stream to get the encoding from. - /// The detected . - public static Encoding FromStream(MemoryStream stream) - { - byte[] bytes = GetEncodingComparisonBytes(stream); + return encoding; + } - if (ByteMatch(bytes, Utf7Bom5) || - ByteMatch(bytes, Utf7Bom4) || - ByteMatch(bytes, Utf7Bom3) || - ByteMatch(bytes, Utf7Bom2) || - ByteMatch(bytes, Utf7Bom1)) - { + /// + /// Gets an from a given memory stream. + /// + /// The stream to get the encoding from. + /// The detected . + public static Encoding FromStream(MemoryStream stream) + { + byte[] bytes = GetEncodingComparisonBytes(stream); + + if (ByteMatch(bytes, Utf7Bom5) || + ByteMatch(bytes, Utf7Bom4) || + ByteMatch(bytes, Utf7Bom3) || + ByteMatch(bytes, Utf7Bom2) || + ByteMatch(bytes, Utf7Bom1)) + { #pragma warning disable 618 #pragma warning disable SYSLIB0001 // Type or member is obsolete - // the UTF7 encoding is required to access legacy files.. - return new UTF7Encoding(false); + // the UTF7 encoding is required to access legacy files.. + return new UTF7Encoding(false); #pragma warning restore SYSLIB0001 // Type or member is obsolete #pragma warning restore 618 - } + } - if (ByteMatch(bytes, Utf8Bom)) - { - return new UTF8Encoding(true, true); - } + if (ByteMatch(bytes, Utf8Bom)) + { + return new UTF8Encoding(true, true); + } - if (ByteMatch(bytes, Utf16BigEndianBom)) - { - return new UnicodeEncoding(true, true, true); - } + if (ByteMatch(bytes, Utf16BigEndianBom)) + { + return new UnicodeEncoding(true, true, true); + } - if (ByteMatch(bytes, Utf16LittleEndianBom)) - { - return new UnicodeEncoding(false, true, true); - } + if (ByteMatch(bytes, Utf16LittleEndianBom)) + { + return new UnicodeEncoding(false, true, true); + } - if (ByteMatch(bytes, Utf32BigEndianBom)) - { - return new UTF32Encoding(true, true, true); - } + if (ByteMatch(bytes, Utf32BigEndianBom)) + { + return new UTF32Encoding(true, true, true); + } - if (ByteMatch(bytes, Utf32LittleEndianBom)) - { - return new UTF32Encoding(false, true, true); - } + if (ByteMatch(bytes, Utf32LittleEndianBom)) + { + return new UTF32Encoding(false, true, true); + } - try // use the UTF-unknown (C: https://github.com/CharsetDetector/UTF-unknown) library.. - { - stream.Position = 0; - var result = CharsetDetector.DetectFromStream(stream); - var encoding = GetPrimaryFromCharsetDetector(result); - if (encoding != null) - { - // US-ASCII seems to be the library default, so use the default instead.. - return encoding.CodePage == 20127 ? FallBackEncoding : encoding; - } - } - catch (Exception ex) + try // use the UTF-unknown (C: https://github.com/CharsetDetector/UTF-unknown) library.. + { + stream.Position = 0; + var result = CharsetDetector.DetectFromStream(stream); + var encoding = GetPrimaryFromCharsetDetector(result); + if (encoding != null) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + // US-ASCII seems to be the library default, so use the default instead.. + return encoding.CodePage == 20127 ? FallBackEncoding : encoding; } - - return FallBackEncoding; } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } + + return FallBackEncoding; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/EncodingData.cs b/ScriptNotepad/UtilityClasses/Encodings/EncodingData.cs index c26578bd..b9f9e666 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/EncodingData.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/EncodingData.cs @@ -27,152 +27,151 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Reflection; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.Encodings +namespace ScriptNotepad.UtilityClasses.Encodings; + +/// +/// A class to get data as a string format and vice versa. +/// +public class EncodingData: ErrorHandlingBase { /// - /// A class to get data as a string format and vice versa. + /// Converts to given encoding to a semicolon-delimited string containing the web name, code page, byte order mark, + /// little/big endian and a value whether the encoding will throw an exception on invalid characters. + /// I.e: utf-32BE;True;True;True. /// - public class EncodingData: ErrorHandlingBase + /// The encoding of which data to parse into a string. + /// A string representing the the . + public static string EncodingToString(Encoding encoding) { - /// - /// Converts to given encoding to a semicolon-delimited string containing the web name, code page, byte order mark, - /// little/big endian and a value whether the encoding will throw an exception on invalid characters. - /// I.e: utf-32BE;True;True;True. - /// - /// The encoding of which data to parse into a string. - /// A string representing the the . - public static string EncodingToString(Encoding encoding) + // avoid null reference exception.. + if (encoding == null) { - // avoid null reference exception.. - if (encoding == null) - { - encoding = Encoding.Default; - } + encoding = Encoding.Default; + } - try + try + { + // special case for UTF8; use reflection.. + if (encoding is UTF8Encoding) { - // special case for UTF8; use reflection.. - if (encoding is UTF8Encoding) - { - FieldInfo infoEmitUtf8Identifier = encoding.GetType().GetField("emitUTF8Identifier", - BindingFlags.Instance | BindingFlags.NonPublic); - FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", - BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo infoEmitUtf8Identifier = encoding.GetType().GetField("emitUTF8Identifier", + BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", + BindingFlags.Instance | BindingFlags.NonPublic); - bool emitUtf8 = infoEmitUtf8Identifier != null && (bool) infoEmitUtf8Identifier.GetValue(encoding); + bool emitUtf8 = infoEmitUtf8Identifier != null && (bool) infoEmitUtf8Identifier.GetValue(encoding); - bool throwInvalidChars = - infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); + bool throwInvalidChars = + infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); - return encoding.WebName + $";{encoding.CodePage};{emitUtf8};{false};{throwInvalidChars}"; - } + return encoding.WebName + $";{encoding.CodePage};{emitUtf8};{false};{throwInvalidChars}"; + } - // special case for Unicode; use reflection.. - if (encoding is UnicodeEncoding) - { - FieldInfo infoByteOrderMark = encoding.GetType() - .GetField("byteOrderMark", BindingFlags.Instance | BindingFlags.NonPublic); + // special case for Unicode; use reflection.. + if (encoding is UnicodeEncoding) + { + FieldInfo infoByteOrderMark = encoding.GetType() + .GetField("byteOrderMark", BindingFlags.Instance | BindingFlags.NonPublic); - FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", - BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", + BindingFlags.Instance | BindingFlags.NonPublic); - FieldInfo infoBigEndian = encoding.GetType() - .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo infoBigEndian = encoding.GetType() + .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); - bool byteOrderMark = infoByteOrderMark != null && (bool) infoByteOrderMark.GetValue(encoding); + bool byteOrderMark = infoByteOrderMark != null && (bool) infoByteOrderMark.GetValue(encoding); - bool throwInvalidChars = - infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); + bool throwInvalidChars = + infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); - bool bigEndian = infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); + bool bigEndian = infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); - return encoding.WebName + $";{encoding.CodePage};{byteOrderMark};{bigEndian};{throwInvalidChars}"; - } + return encoding.WebName + $";{encoding.CodePage};{byteOrderMark};{bigEndian};{throwInvalidChars}"; + } - // special case for UTF32; use reflection.. - if (encoding is UTF32Encoding) - { - FieldInfo infoEmitUtf32ByteOrderMark = encoding.GetType().GetField("emitUTF32ByteOrderMark", - BindingFlags.Instance | BindingFlags.NonPublic); - FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", - BindingFlags.Instance | BindingFlags.NonPublic); - FieldInfo infoBigEndian = encoding.GetType() - .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); + // special case for UTF32; use reflection.. + if (encoding is UTF32Encoding) + { + FieldInfo infoEmitUtf32ByteOrderMark = encoding.GetType().GetField("emitUTF32ByteOrderMark", + BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", + BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo infoBigEndian = encoding.GetType() + .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); - bool emitUtf32ByteOrderMark = infoEmitUtf32ByteOrderMark != null && - (bool) infoEmitUtf32ByteOrderMark.GetValue(encoding); + bool emitUtf32ByteOrderMark = infoEmitUtf32ByteOrderMark != null && + (bool) infoEmitUtf32ByteOrderMark.GetValue(encoding); - bool throwInvalidChars = - infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); + bool throwInvalidChars = + infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); - bool bigEndian = infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); + bool bigEndian = infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); - return encoding.WebName + - $";{encoding.CodePage};{emitUtf32ByteOrderMark};{bigEndian};{throwInvalidChars}"; - } + return encoding.WebName + + $";{encoding.CodePage};{emitUtf32ByteOrderMark};{bigEndian};{throwInvalidChars}"; } - catch - { - encoding = Encoding.Default; - } - - // the normal case.. there are no byte order marks, etc.. - return encoding.WebName + $";{encoding.CodePage};{false};{false};{false}"; } + catch + { + encoding = Encoding.Default; + } + + // the normal case.. there are no byte order marks, etc.. + return encoding.WebName + $";{encoding.CodePage};{false};{false};{false}"; + } - /// - /// Gets an class instance from string describing the encoding. - /// - /// The string describing the . I.e: utf-32BE;True;True;True. - /// Returns the created from the given string instance. - public static Encoding EncodingFromString(string encodingString) + /// + /// Gets an class instance from string describing the encoding. + /// + /// The string describing the . I.e: utf-32BE;True;True;True. + /// Returns the created from the given string instance. + public static Encoding EncodingFromString(string encodingString) + { + try { - try - { - string[] encodingValues = encodingString.Split(';'); + string[] encodingValues = encodingString.Split(';'); - string webName = encodingValues.Length >= 1 ? encodingValues[0] : Encoding.Default.WebName; - bool byteOrderMark = encodingValues.Length >= 3 && bool.Parse(encodingValues[2]); - bool throwInvalidChars = encodingValues.Length >= 5 && bool.Parse(encodingValues[4]); + string webName = encodingValues.Length >= 1 ? encodingValues[0] : Encoding.Default.WebName; + bool byteOrderMark = encodingValues.Length >= 3 && bool.Parse(encodingValues[2]); + bool throwInvalidChars = encodingValues.Length >= 5 && bool.Parse(encodingValues[4]); - if (webName == "utf-8") - { - return new UTF8Encoding(byteOrderMark, throwInvalidChars); - } + if (webName == "utf-8") + { + return new UTF8Encoding(byteOrderMark, throwInvalidChars); + } - if (webName == "utf-16" || webName == "utf-16BE") - { - return new UnicodeEncoding(webName == "utf-16BE", byteOrderMark, throwInvalidChars); - } + if (webName == "utf-16" || webName == "utf-16BE") + { + return new UnicodeEncoding(webName == "utf-16BE", byteOrderMark, throwInvalidChars); + } - if (webName == "utf-32" || webName == "utf-32BE") - { - return new UTF32Encoding(webName == "utf-32BE", byteOrderMark, throwInvalidChars); - } + if (webName == "utf-32" || webName == "utf-32BE") + { + return new UTF32Encoding(webName == "utf-32BE", byteOrderMark, throwInvalidChars); + } + try + { + return Encoding.GetEncoding(webName); + } + catch (Exception ex) + { + ExceptionLogAction?.Invoke(ex); try { - return Encoding.GetEncoding(webName); + return CodePagesEncodingProvider.Instance.GetEncoding(webName); } - catch (Exception ex) + catch (Exception exInner) { - ExceptionLogAction?.Invoke(ex); - try - { - return CodePagesEncodingProvider.Instance.GetEncoding(webName); - } - catch (Exception exInner) - { - ExceptionLogAction?.Invoke(exInner); - return Encoding.Default; - } + ExceptionLogAction?.Invoke(exInner); + return Encoding.Default; } } - catch (Exception ex) - { - ExceptionLogAction?.Invoke(ex); - return Encoding.Default; - } + } + catch (Exception ex) + { + ExceptionLogAction?.Invoke(ex); + return Encoding.Default; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/EncodingExceptionEventArgs.cs b/ScriptNotepad/UtilityClasses/Encodings/EncodingExceptionEventArgs.cs index 6082bb66..51df6309 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/EncodingExceptionEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/EncodingExceptionEventArgs.cs @@ -24,19 +24,18 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.Encodings +namespace ScriptNotepad.UtilityClasses.Encodings; + +/// +/// Event arguments for the event. +/// Implements the +/// +/// +public class EncodingExceptionEventArgs : EventArgs { /// - /// Event arguments for the event. - /// Implements the + /// Gets or sets the exception which occurred. /// - /// - public class EncodingExceptionEventArgs : EventArgs - { - /// - /// Gets or sets the exception which occurred. - /// - /// The exception. - public Exception Exception { get; set; } - } -} + /// The exception. + public Exception Exception { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/EncodingHelpers.cs b/ScriptNotepad/UtilityClasses/Encodings/EncodingHelpers.cs index 405af8b4..0ec6aee8 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/EncodingHelpers.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/EncodingHelpers.cs @@ -26,120 +26,119 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Reflection; -namespace ScriptNotepad.UtilityClasses.Encodings +namespace ScriptNotepad.UtilityClasses.Encodings; + +/// +/// A helper class for the class. +/// +public static class EncodingHelpers { /// - /// A helper class for the class. + /// Gets a value indicating whether the encoding uses identifier / byte-order-mark. /// - public static class EncodingHelpers + /// The encoding from which to get the value from. + /// true if the encoding uses identifier / byte-order-mark, false otherwise. + public static bool EmitsBom(this Encoding encoding) { - /// - /// Gets a value indicating whether the encoding uses identifier / byte-order-mark. - /// - /// The encoding from which to get the value from. - /// true if the encoding uses identifier / byte-order-mark, false otherwise. - public static bool EmitsBom(this Encoding encoding) + // special case for UTF8; use reflection.. + if (encoding is UTF8Encoding) { - // special case for UTF8; use reflection.. - if (encoding is UTF8Encoding) - { - FieldInfo infoEmitUtf8Identifier = encoding.GetType().GetField("emitUTF8Identifier", - BindingFlags.Instance | BindingFlags.NonPublic); - - return infoEmitUtf8Identifier != null && (bool) infoEmitUtf8Identifier.GetValue(encoding); - } + FieldInfo infoEmitUtf8Identifier = encoding.GetType().GetField("emitUTF8Identifier", + BindingFlags.Instance | BindingFlags.NonPublic); - // special case for Unicode; use reflection.. - if (encoding is UnicodeEncoding) - { - FieldInfo infoByteOrderMark = encoding.GetType() - .GetField("byteOrderMark", BindingFlags.Instance | BindingFlags.NonPublic); + return infoEmitUtf8Identifier != null && (bool) infoEmitUtf8Identifier.GetValue(encoding); + } + // special case for Unicode; use reflection.. + if (encoding is UnicodeEncoding) + { + FieldInfo infoByteOrderMark = encoding.GetType() + .GetField("byteOrderMark", BindingFlags.Instance | BindingFlags.NonPublic); - return infoByteOrderMark != null && (bool) infoByteOrderMark.GetValue(encoding); - } - // special case for UTF32; use reflection.. - if (encoding is UTF32Encoding) - { - FieldInfo infoEmitUtf32ByteOrderMark = encoding.GetType().GetField("emitUTF32ByteOrderMark", - BindingFlags.Instance | BindingFlags.NonPublic); + return infoByteOrderMark != null && (bool) infoByteOrderMark.GetValue(encoding); + } - return infoEmitUtf32ByteOrderMark != null && - (bool) infoEmitUtf32ByteOrderMark.GetValue(encoding); - } + // special case for UTF32; use reflection.. + if (encoding is UTF32Encoding) + { + FieldInfo infoEmitUtf32ByteOrderMark = encoding.GetType().GetField("emitUTF32ByteOrderMark", + BindingFlags.Instance | BindingFlags.NonPublic); - return false; + return infoEmitUtf32ByteOrderMark != null && + (bool) infoEmitUtf32ByteOrderMark.GetValue(encoding); } - /// - /// Determines whether the encoding is big endian. - /// - /// The encoding to check for little/big endian.. - /// true if the encoding is big endian; otherwise, false. - public static bool IsBigEndian(this Encoding encoding) - { - // special case for Unicode; use reflection.. - if (encoding is UnicodeEncoding) - { - FieldInfo infoBigEndian = encoding.GetType() - .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); + return false; + } + /// + /// Determines whether the encoding is big endian. + /// + /// The encoding to check for little/big endian.. + /// true if the encoding is big endian; otherwise, false. + public static bool IsBigEndian(this Encoding encoding) + { + // special case for Unicode; use reflection.. + if (encoding is UnicodeEncoding) + { + FieldInfo infoBigEndian = encoding.GetType() + .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); - return infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); - } - // special case for UTF32; use reflection.. - if (encoding is UTF32Encoding) - { - FieldInfo infoBigEndian = encoding.GetType() - .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); + return infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); + } + // special case for UTF32; use reflection.. + if (encoding is UTF32Encoding) + { + FieldInfo infoBigEndian = encoding.GetType() + .GetField("bigEndian", BindingFlags.Instance | BindingFlags.NonPublic); - return infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); - } - return false; + return infoBigEndian != null && (bool) infoBigEndian.GetValue(encoding); } - /// - /// Gets a value indicating whether the Encoding raises an exception in case of an invalid character. - /// - /// The encoding to check the value for. - /// true if the Encoding raises an exception in case of an invalid character, false otherwise. - public static bool ThrowOnInvalidCharacters(this Encoding encoding) - { - // special case for UTF8; use reflection.. - if (encoding is UTF8Encoding) - { - FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", - BindingFlags.Instance | BindingFlags.NonPublic); + return false; + } + /// + /// Gets a value indicating whether the Encoding raises an exception in case of an invalid character. + /// + /// The encoding to check the value for. + /// true if the Encoding raises an exception in case of an invalid character, false otherwise. + public static bool ThrowOnInvalidCharacters(this Encoding encoding) + { + // special case for UTF8; use reflection.. + if (encoding is UTF8Encoding) + { + FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", + BindingFlags.Instance | BindingFlags.NonPublic); - return infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); - } - // special case for Unicode; use reflection.. - if (encoding is UnicodeEncoding) - { - FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", - BindingFlags.Instance | BindingFlags.NonPublic); + return infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); + } - return - infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); - } + // special case for Unicode; use reflection.. + if (encoding is UnicodeEncoding) + { + FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", + BindingFlags.Instance | BindingFlags.NonPublic); - // special case for UTF32; use reflection.. - if (encoding is UTF32Encoding) - { - FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", - BindingFlags.Instance | BindingFlags.NonPublic); + return + infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); + } - return - infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); - } + // special case for UTF32; use reflection.. + if (encoding is UTF32Encoding) + { + FieldInfo infoIsThrowException = encoding.GetType().GetField("isThrowException", + BindingFlags.Instance | BindingFlags.NonPublic); - return false; + return + infoIsThrowException != null && (bool) infoIsThrowException.GetValue(encoding); } + + return false; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/FileEncoding.cs b/ScriptNotepad/UtilityClasses/Encodings/FileEncoding.cs index e3a3736d..58abae1e 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/FileEncoding.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/FileEncoding.cs @@ -31,79 +31,78 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.ErrorLogger; using static ScriptNotepad.UtilityClasses.Encodings.TryMakeEncoding; -namespace ScriptNotepad.UtilityClasses.Encodings +namespace ScriptNotepad.UtilityClasses.Encodings; + +/// +/// A class to help with file encoding within the software. +/// +public class FileEncoding { /// - /// A class to help with file encoding within the software. + /// Gets the file encoding. /// - public class FileEncoding + /// Name of the session. + /// Name of the file. + /// The default encoding for the file. + /// if set to true the file contents should be reloaded from the file system. + /// if set to true the encoding should be reassigned. + /// if set to true the setting value whether to detect unicode file with no byte-order-mark (BOM) is overridden. + /// A value indicating if the encoding is reconstructed and unicode is used, should the byte-order-mark be excluded from encoding. + /// A value indicating whether to use big-endian or little-endian byte order with unicode encoding. + /// A value indicating whether a snapshot of the file exists in the database. + /// Encoding. + public static Encoding GetFileEncoding(string sessionName, string fileName, Encoding encoding, bool reloadContents, + bool encodingOverridden, bool overrideDetectBom, out bool noBom, out bool bigEndian, out bool existsInDatabase) { - /// - /// Gets the file encoding. - /// - /// Name of the session. - /// Name of the file. - /// The default encoding for the file. - /// if set to true the file contents should be reloaded from the file system. - /// if set to true the encoding should be reassigned. - /// if set to true the setting value whether to detect unicode file with no byte-order-mark (BOM) is overridden. - /// A value indicating if the encoding is reconstructed and unicode is used, should the byte-order-mark be excluded from encoding. - /// A value indicating whether to use big-endian or little-endian byte order with unicode encoding. - /// A value indicating whether a snapshot of the file exists in the database. - /// Encoding. - public static Encoding GetFileEncoding(string sessionName, string fileName, Encoding encoding, bool reloadContents, - bool encodingOverridden, bool overrideDetectBom, out bool noBom, out bool bigEndian, out bool existsInDatabase) + try { - try - { - // the encoding shouldn't change based on the file's contents if a snapshot of the file already exists in the database.. - existsInDatabase = ScriptNotepadDbContext.DbContext.FileSaves.Any(f => f.Session.SessionName == sessionName && f.FileNameFull == fileName); - - noBom = false; - bigEndian = false; + // the encoding shouldn't change based on the file's contents if a snapshot of the file already exists in the database.. + existsInDatabase = ScriptNotepadDbContext.DbContext.FileSaves.Any(f => f.Session.SessionName == sessionName && f.FileNameFull == fileName); - if (FormSettings.Settings.AutoDetectEncoding && !encodingOverridden && - (!existsInDatabase || reloadContents)) - { - using FileStream fileStream = File.OpenRead(fileName); - encoding = DetectEncoding.FromStream(fileStream); - return encoding; - } + noBom = false; + bigEndian = false; - if ((FormSettings.Settings.DetectNoBom || overrideDetectBom) && !encodingOverridden && - (!existsInDatabase || reloadContents)) - { - string contents = TryEncodings(fileName, out var detectedEncoding, out bigEndian, out noBom); + if (FormSettings.Settings.AutoDetectEncoding && !encodingOverridden && + (!existsInDatabase || reloadContents)) + { + using FileStream fileStream = File.OpenRead(fileName); + encoding = DetectEncoding.FromStream(fileStream); + return encoding; + } - if (contents != null) - { - encoding = detectedEncoding; - return encoding; - } - } + if ((FormSettings.Settings.DetectNoBom || overrideDetectBom) && !encodingOverridden && + (!existsInDatabase || reloadContents)) + { + string contents = TryEncodings(fileName, out var detectedEncoding, out bigEndian, out noBom); - if (existsInDatabase && !reloadContents && !encodingOverridden && !File.Exists(fileName)) + if (contents != null) { - encoding = ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Session.SessionName == sessionName && f.FileNameFull == fileName)?.GetEncoding(); + encoding = detectedEncoding; return encoding; } - - // the last check.. - if (File.Exists(fileName)) - { - File.ReadAllText(fileName, encoding); - } } - catch (Exception ex) + + if (existsInDatabase && !reloadContents && !encodingOverridden && !File.Exists(fileName)) { - ExceptionLogger.LogError(ex); - existsInDatabase = false; - noBom = false; - bigEndian = false; - encoding = null; + encoding = ScriptNotepadDbContext.DbContext.FileSaves.FirstOrDefault(f => f.Session.SessionName == sessionName && f.FileNameFull == fileName)?.GetEncoding(); + return encoding; } - return encoding; + // the last check.. + if (File.Exists(fileName)) + { + File.ReadAllText(fileName, encoding); + } } + catch (Exception ex) + { + ExceptionLogger.LogError(ex); + existsInDatabase = false; + noBom = false; + bigEndian = false; + encoding = null; + } + + return encoding; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Encodings/TryMakeEncoding.cs b/ScriptNotepad/UtilityClasses/Encodings/TryMakeEncoding.cs index f08c59e6..bfb95a30 100644 --- a/ScriptNotepad/UtilityClasses/Encodings/TryMakeEncoding.cs +++ b/ScriptNotepad/UtilityClasses/Encodings/TryMakeEncoding.cs @@ -28,143 +28,120 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Settings; using static ScriptNotepad.UtilityClasses.Encodings.DetectEncoding; -namespace ScriptNotepad.UtilityClasses.Encodings +namespace ScriptNotepad.UtilityClasses.Encodings; + +/// +/// A class to help to match a given byte data to an encoded string. +/// +public class TryMakeEncoding { /// - /// A class to help to match a given byte data to an encoded string. + /// A delegate for the event. + /// + /// Name of the method in which the exception was caused. + /// The instance containing the event data. + public delegate void OnExceptionOccurred(string methodName, EncodingExceptionEventArgs e); + + /// + /// Occurs when exception occurred in one of the methods of this class. + /// + public static event OnExceptionOccurred ExceptionOccurred; + + /// + /// Tries different unicode encodings for a given file (with or without a BOM). /// - public class TryMakeEncoding + /// Name of the file. + /// The detected encoding if any. + /// A value indicating whether the detected encoding is big-endian. + /// A value indicating whether the detected unicode file contains a byte-order-mark. + /// The contents of the file as a string if an unicode encoding variant was found for it. + public static string TryEncodings(string fileName, out Encoding encoding, out bool bigEndian, out bool noBom) { - /// - /// A delegate for the event. - /// - /// Name of the method in which the exception was caused. - /// The instance containing the event data. - public delegate void OnExceptionOccurred(string methodName, EncodingExceptionEventArgs e); - - /// - /// Occurs when exception occurred in one of the methods of this class. - /// - public static event OnExceptionOccurred ExceptionOccurred; - - /// - /// Tries different unicode encodings for a given file (with or without a BOM). - /// - /// Name of the file. - /// The detected encoding if any. - /// A value indicating whether the detected encoding is big-endian. - /// A value indicating whether the detected unicode file contains a byte-order-mark. - /// The contents of the file as a string if an unicode encoding variant was found for it. - public static string TryEncodings(string fileName, out Encoding encoding, out bool bigEndian, out bool noBom) + noBom = false; + bigEndian = false; + try { - noBom = false; - bigEndian = false; - try + using FileStream fileStream = File.OpenRead(fileName); + using MemoryStream memoryStream = new MemoryStream(); + fileStream.CopyTo(memoryStream); + + // try the UTF8 encoding.. + var result = TryUtf8Encoding(memoryStream, out encoding, out noBom); + + if (result != null) { - using FileStream fileStream = File.OpenRead(fileName); - using MemoryStream memoryStream = new MemoryStream(); - fileStream.CopyTo(memoryStream); - - // try the UTF8 encoding.. - var result = TryUtf8Encoding(memoryStream, out encoding, out noBom); - - if (result != null) - { - bigEndian = false; - return result; - } - - // try the UTF16 encoding with LittleEndian.. - result = TryUtf16Encoding(memoryStream, false, out encoding, out noBom); - - if (result != null) - { - bigEndian = false; - return result; - } - - // try the UTF16 encoding with BigEndian.. - result = TryUtf16Encoding(memoryStream, true, out encoding, out noBom); - - if (result != null) - { - bigEndian = true; - return result; - } - - // try the UTF32 encoding with LittleEndian.. - result = TryUtf32Encoding(memoryStream, false, out encoding, out noBom); - - if (result != null) - { - bigEndian = false; - return result; - } - - // try the UTF32 encoding with BigEndian.. - result = TryUtf32Encoding(memoryStream, true, out encoding, out noBom); - - if (result != null) - { - bigEndian = true; - return result; - } + bigEndian = false; + return result; } - catch (Exception ex) + + // try the UTF16 encoding with LittleEndian.. + result = TryUtf16Encoding(memoryStream, false, out encoding, out noBom); + + if (result != null) { - ExceptionOccurred?.Invoke("TryEncodings", new EncodingExceptionEventArgs {Exception = ex}); + bigEndian = false; + return result; + } - // failed.. - encoding = null; - return null; + // try the UTF16 encoding with BigEndian.. + result = TryUtf16Encoding(memoryStream, true, out encoding, out noBom); + + if (result != null) + { + bigEndian = true; + return result; } - return null; - } + // try the UTF32 encoding with LittleEndian.. + result = TryUtf32Encoding(memoryStream, false, out encoding, out noBom); - /// - /// Tries to convert a given memory stream to the UTF8 encoding by adding an UTF8 BOM to the stream. - /// - /// The stream to try to convert to. - /// The encoding successfully used with the stream data. - /// A value indicating whether the detected unicode file contains a byte-order-mark. - /// A string converted into the UTF8 encoding if successful; otherwise null. - public static string TryUtf8Encoding(MemoryStream stream, out Encoding encoding, out bool noBom) - { - noBom = false; - if (ByteMatch(GetEncodingComparisonBytes(stream), Utf8Bom)) + if (result != null) { - try - { - encoding = new UTF8Encoding(true, true); - return encoding.GetString(stream.ToArray()); - } - catch (Exception ex) - { - ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs {Exception = ex}); - - // failed.. - encoding = null; - return null; - } + bigEndian = false; + return result; } - try // there is no BOM.. + // try the UTF32 encoding with BigEndian.. + result = TryUtf32Encoding(memoryStream, true, out encoding, out noBom); + + if (result != null) { - // get the contents of the memory stream into a list of bytes.. - List bytes = new List(stream.ToArray()); + bigEndian = true; + return result; + } + } + catch (Exception ex) + { + ExceptionOccurred?.Invoke("TryEncodings", new EncodingExceptionEventArgs {Exception = ex, }); + + // failed.. + encoding = null; + return null; + } - // insert the BOM.. - bytes.InsertRange(0, Utf8Bom); + return null; + } - // try the UTF8 encoding with the BOM.. - encoding = new UTF8Encoding(false, true); - noBom = true; - return encoding.GetString(bytes.ToArray()); + /// + /// Tries to convert a given memory stream to the UTF8 encoding by adding an UTF8 BOM to the stream. + /// + /// The stream to try to convert to. + /// The encoding successfully used with the stream data. + /// A value indicating whether the detected unicode file contains a byte-order-mark. + /// A string converted into the UTF8 encoding if successful; otherwise null. + public static string TryUtf8Encoding(MemoryStream stream, out Encoding encoding, out bool noBom) + { + noBom = false; + if (ByteMatch(GetEncodingComparisonBytes(stream), Utf8Bom)) + { + try + { + encoding = new UTF8Encoding(true, true); + return encoding.GetString(stream.ToArray()); } catch (Exception ex) { - ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs {Exception = ex}); + ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs {Exception = ex, }); // failed.. encoding = null; @@ -172,63 +149,54 @@ public static string TryUtf8Encoding(MemoryStream stream, out Encoding encoding, } } - /// - /// Tries to convert a given memory stream to the UTF16 encoding by adding an UTF16 BOM to the stream. - /// - /// The stream to try to convert to. - /// The encoding successfully used with the stream data. - /// true to use the big endian byte order (most significant byte first); false to use the little endian byte order (least significant byte first). - /// A value indicating whether the detected unicode file contains a byte-order-mark. - /// A string converted into the UTF16 encoding if successful; otherwise null. - public static string TryUtf16Encoding(MemoryStream stream, bool bigEndian, out Encoding encoding, out bool noBom) + try // there is no BOM.. { - noBom = false; + // get the contents of the memory stream into a list of bytes.. + List bytes = new List(stream.ToArray()); - if (!FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian && - ByteMatch(GetEncodingComparisonBytes(stream), Utf16LittleEndianBom) || - !FormSettings.Settings.SkipUnicodeDetectBe && bigEndian && - ByteMatch(GetEncodingComparisonBytes(stream), Utf16BigEndianBom)) - { - try - { - encoding = new UnicodeEncoding(bigEndian, true, true); - return encoding.GetString(stream.ToArray()); - } - catch (Exception ex) - { - ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs {Exception = ex}); - - // failed.. - encoding = null; - return null; - } - } + // insert the BOM.. + bytes.InsertRange(0, Utf8Bom); - // the user doesn't want this detection.. - if (FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian || - FormSettings.Settings.SkipUnicodeDetectBe && bigEndian) - { - // so just return.. - encoding = null; - return null; - } + // try the UTF8 encoding with the BOM.. + encoding = new UTF8Encoding(false, true); + noBom = true; + return encoding.GetString(bytes.ToArray()); + } + catch (Exception ex) + { + ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs {Exception = ex, }); - try // there is no BOM.. - { - // get the contents of the memory stream into a list of bytes.. - List bytes = new List(stream.ToArray()); + // failed.. + encoding = null; + return null; + } + } - // insert the BOM.. -// bytes.InsertRange(0, bigEndian ? Utf16BigEndianBom : Utf16LittleEndianBom); + /// + /// Tries to convert a given memory stream to the UTF16 encoding by adding an UTF16 BOM to the stream. + /// + /// The stream to try to convert to. + /// The encoding successfully used with the stream data. + /// true to use the big endian byte order (most significant byte first); false to use the little endian byte order (least significant byte first). + /// A value indicating whether the detected unicode file contains a byte-order-mark. + /// A string converted into the UTF16 encoding if successful; otherwise null. + public static string TryUtf16Encoding(MemoryStream stream, bool bigEndian, out Encoding encoding, out bool noBom) + { + noBom = false; - // try the UTF16 encoding with the BOM.. - encoding = new UnicodeEncoding(bigEndian, false, true); - noBom = true; - return encoding.GetString(bytes.ToArray()); + if (!FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian && + ByteMatch(GetEncodingComparisonBytes(stream), Utf16LittleEndianBom) || + !FormSettings.Settings.SkipUnicodeDetectBe && bigEndian && + ByteMatch(GetEncodingComparisonBytes(stream), Utf16BigEndianBom)) + { + try + { + encoding = new UnicodeEncoding(bigEndian, true, true); + return encoding.GetString(stream.ToArray()); } catch (Exception ex) { - ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs {Exception = ex}); + ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs {Exception = ex, }); // failed.. encoding = null; @@ -236,66 +204,97 @@ public static string TryUtf16Encoding(MemoryStream stream, bool bigEndian, out E } } - /// - /// Tries to convert a given memory stream to the UTF32 encoding by adding an UTF32 BOM to the stream. - /// - /// The stream to try to convert to. - /// The encoding successfully used with the stream data. - /// true to use the big endian byte order (most significant byte first); false to use the little endian byte order (least significant byte first). - /// A value indicating whether the detected unicode file contains a byte-order-mark. - /// A string converted into the UTF32 encoding if successful; otherwise null. - public static string TryUtf32Encoding(MemoryStream stream, bool bigEndian, out Encoding encoding, out bool noBom) + // the user doesn't want this detection.. + if (FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian || + FormSettings.Settings.SkipUnicodeDetectBe && bigEndian) { - noBom = false; + // so just return.. + encoding = null; + return null; + } - if (!FormSettings.Settings.SkipUtf32Le && !bigEndian && ByteMatch(GetEncodingComparisonBytes(stream), Utf32LittleEndianBom) || - !FormSettings.Settings.SkipUtf32Be && bigEndian && ByteMatch(GetEncodingComparisonBytes(stream), Utf32BigEndianBom)) - { - try - { - encoding = new UTF32Encoding(bigEndian, true, true); - return encoding.GetString(stream.ToArray()); - } - catch (Exception ex) - { - ExceptionOccurred?.Invoke("TryUtf32Encoding", new EncodingExceptionEventArgs {Exception = ex}); - - // failed.. - encoding = null; - return null; - } - } + try // there is no BOM.. + { + // get the contents of the memory stream into a list of bytes.. + List bytes = new List(stream.ToArray()); - // the user doesn't want this detection.. - if (FormSettings.Settings.SkipUtf32Le && !bigEndian || - FormSettings.Settings.SkipUtf32Be && bigEndian) - { - // ..so just return.. - encoding = null; - return null; - } + // insert the BOM.. +// bytes.InsertRange(0, bigEndian ? Utf16BigEndianBom : Utf16LittleEndianBom); - try // there is no BOM.. - { - // get the contents of the memory stream into a list of bytes.. - List bytes = new List(stream.ToArray()); + // try the UTF16 encoding with the BOM.. + encoding = new UnicodeEncoding(bigEndian, false, true); + noBom = true; + return encoding.GetString(bytes.ToArray()); + } + catch (Exception ex) + { + ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs {Exception = ex, }); - // insert the BOM.. - //bytes.InsertRange(0, bigEndian ? Utf32BigEndianBom : Utf32LittleEndianBom); + // failed.. + encoding = null; + return null; + } + } + + /// + /// Tries to convert a given memory stream to the UTF32 encoding by adding an UTF32 BOM to the stream. + /// + /// The stream to try to convert to. + /// The encoding successfully used with the stream data. + /// true to use the big endian byte order (most significant byte first); false to use the little endian byte order (least significant byte first). + /// A value indicating whether the detected unicode file contains a byte-order-mark. + /// A string converted into the UTF32 encoding if successful; otherwise null. + public static string TryUtf32Encoding(MemoryStream stream, bool bigEndian, out Encoding encoding, out bool noBom) + { + noBom = false; - // try the UTF32 encoding with the BOM.. - encoding = new UTF32Encoding(bigEndian, false, true); - noBom = true; - return encoding.GetString(bytes.ToArray()); + if (!FormSettings.Settings.SkipUtf32Le && !bigEndian && ByteMatch(GetEncodingComparisonBytes(stream), Utf32LittleEndianBom) || + !FormSettings.Settings.SkipUtf32Be && bigEndian && ByteMatch(GetEncodingComparisonBytes(stream), Utf32BigEndianBom)) + { + try + { + encoding = new UTF32Encoding(bigEndian, true, true); + return encoding.GetString(stream.ToArray()); } catch (Exception ex) { - ExceptionOccurred?.Invoke("TryUtf32Encoding", new EncodingExceptionEventArgs {Exception = ex}); + ExceptionOccurred?.Invoke("TryUtf32Encoding", new EncodingExceptionEventArgs {Exception = ex, }); // failed.. encoding = null; return null; } } + + // the user doesn't want this detection.. + if (FormSettings.Settings.SkipUtf32Le && !bigEndian || + FormSettings.Settings.SkipUtf32Be && bigEndian) + { + // ..so just return.. + encoding = null; + return null; + } + + try // there is no BOM.. + { + // get the contents of the memory stream into a list of bytes.. + List bytes = new List(stream.ToArray()); + + // insert the BOM.. + //bytes.InsertRange(0, bigEndian ? Utf32BigEndianBom : Utf32LittleEndianBom); + + // try the UTF32 encoding with the BOM.. + encoding = new UTF32Encoding(bigEndian, false, true); + noBom = true; + return encoding.GetString(bytes.ToArray()); + } + catch (Exception ex) + { + ExceptionOccurred?.Invoke("TryUtf32Encoding", new EncodingExceptionEventArgs {Exception = ex, }); + + // failed.. + encoding = null; + return null; + } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ErrorHandling/ErrorHandlingBase.cs b/ScriptNotepad/UtilityClasses/ErrorHandling/ErrorHandlingBase.cs index 93437542..19bdc98b 100644 --- a/ScriptNotepad/UtilityClasses/ErrorHandling/ErrorHandlingBase.cs +++ b/ScriptNotepad/UtilityClasses/ErrorHandling/ErrorHandlingBase.cs @@ -24,16 +24,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.ErrorHandling +namespace ScriptNotepad.UtilityClasses.ErrorHandling; + +/// +/// A class from which a classes logging errors should be derived from. +/// +public class ErrorHandlingBase { /// - /// A class from which a classes logging errors should be derived from. + /// Gets or sets the action to be used to log an exception. /// - public class ErrorHandlingBase - { - /// - /// Gets or sets the action to be used to log an exception. - /// - public static Action ExceptionLogAction { get; set; } = null; - } -} + public static Action ExceptionLogAction { get; set; } = null; +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/EventArguments/MainFormSizeEventArgs.cs b/ScriptNotepad/UtilityClasses/EventArguments/MainFormSizeEventArgs.cs index 3905d390..96839b39 100644 --- a/ScriptNotepad/UtilityClasses/EventArguments/MainFormSizeEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/EventArguments/MainFormSizeEventArgs.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,67 +27,66 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Drawing; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.EventArguments +namespace ScriptNotepad.UtilityClasses.EventArguments; + +/// +/// Event arguments for the event. +/// Implements the +/// +/// +public class MainFormSizeEventArgs: System.EventArgs { /// - /// Event arguments for the event. - /// Implements the + /// Gets or sets the size of the instance. /// - /// - public class MainFormSizeEventArgs: System.EventArgs - { - /// - /// Gets or sets the size of the instance. - /// - /// The size of the instance. - public Size Size { get; set; } + /// The size of the instance. + public Size Size { get; set; } - /// - /// Gets or sets the previous size of the instance. - /// - /// The previous size of the instance. - public Size PreviousSize { get; set; } + /// + /// Gets or sets the previous size of the instance. + /// + /// The previous size of the instance. + public Size PreviousSize { get; set; } - /// - /// Gets or sets the location of the instance. - /// - /// The location of the instance. - public Point Location { get; set; } + /// + /// Gets or sets the location of the instance. + /// + /// The location of the instance. + public Point Location { get; set; } - /// - /// Gets or sets the previous location of the instance. - /// - /// The previous location of the instance. - public Point PreviousLocation { get; set; } + /// + /// Gets or sets the previous location of the instance. + /// + /// The previous location of the instance. + public Point PreviousLocation { get; set; } - /// - /// Gets or sets the state of the instance. - /// - /// The state of the instance. - public FormWindowState State { get; set; } + /// + /// Gets or sets the state of the instance. + /// + /// The state of the instance. + public FormWindowState State { get; set; } - /// - /// Gets or sets the previous state of the instance. - /// - /// The previous state of the instance. - public FormWindowState PreviousState { get; set; } + /// + /// Gets or sets the previous state of the instance. + /// + /// The previous state of the instance. + public FormWindowState PreviousState { get; set; } - /// - /// Gets or sets a value indicating whether the instance is visible. - /// - /// true if the instance is visible; otherwise, false. - public bool Visible { get; set; } + /// + /// Gets or sets a value indicating whether the instance is visible. + /// + /// true if the instance is visible; otherwise, false. + public bool Visible { get; set; } - /// - /// Gets the boundaries of the size and location of the the instance. - /// - /// The boundaries of the size and location of the the instance. - public Rectangle Boundaries => new (Location.X, Location.Y, Size.Width, Size.Height); + /// + /// Gets the boundaries of the size and location of the the instance. + /// + /// The boundaries of the size and location of the the instance. + public Rectangle Boundaries => new (Location.X, Location.Y, Size.Width, Size.Height); - /// - /// Gets the boundaries of the previous size and location of the the instance. - /// - /// The boundaries of the previous size and location of the the instance. - public Rectangle PreviousBoundaries => new (PreviousLocation.X, PreviousLocation.Y, PreviousSize.Width, PreviousSize.Height); - } -} + /// + /// Gets the boundaries of the previous size and location of the the instance. + /// + /// The boundaries of the previous size and location of the the instance. + public Rectangle PreviousBoundaries => new (PreviousLocation.X, PreviousLocation.Y, PreviousSize.Width, PreviousSize.Height); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/ApplicationProcess.cs b/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/ApplicationProcess.cs index 35029c14..c597bb12 100644 --- a/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/ApplicationProcess.cs +++ b/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/ApplicationProcess.cs @@ -28,42 +28,41 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Diagnostics; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.ExternalProcessInteraction +namespace ScriptNotepad.UtilityClasses.ExternalProcessInteraction; + +/// +/// A class to run the current application with parameters. +/// +public class ApplicationProcess: ErrorHandlingBase { /// - /// A class to run the current application with parameters. + /// Executes a new instance of the current application with possible elevated permissions. /// - public class ApplicationProcess: ErrorHandlingBase + /// If set to true try to run the process as administrator. + /// The arguments to be passed to the process. + /// + public static bool RunApplicationProcess(bool elevated, string arguments) { - /// - /// Executes a new instance of the current application with possible elevated permissions. - /// - /// If set to true try to run the process as administrator. - /// The arguments to be passed to the process. - /// - public static bool RunApplicationProcess(bool elevated, string arguments) + try { - try + var processStartInfo = new ProcessStartInfo() { - var processStartInfo = new ProcessStartInfo() - { - FileName = Application.ExecutablePath, - LoadUserProfile = true, - Verb = elevated ? "runas" : null, // process elevation.. - Arguments = arguments - }; + FileName = Application.ExecutablePath, + LoadUserProfile = true, + Verb = elevated ? "runas" : null, // process elevation.. + Arguments = arguments, + }; - System.Diagnostics.Process.Start(processStartInfo); + System.Diagnostics.Process.Start(processStartInfo); - return true; - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); + return true; + } + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); - return false; - } + return false; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/CommandPromptInteraction.cs b/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/CommandPromptInteraction.cs index 93c7d6ff..61444aa3 100644 --- a/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/CommandPromptInteraction.cs +++ b/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/CommandPromptInteraction.cs @@ -27,70 +27,68 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using System.Diagnostics; -namespace ScriptNotepad.UtilityClasses.ExternalProcessInteraction +namespace ScriptNotepad.UtilityClasses.ExternalProcessInteraction; + +/// +/// A class for interacting with the Command Prompt (cmd.exe) and with Windows PowerShell (powershell.exe). +/// +public class CommandPromptInteraction: ErrorHandlingBase { /// - /// A class for interacting with the Command Prompt (cmd.exe) and with Windows PowerShell (powershell.exe). + /// Shows the Command Prompt (cmd.exe) with a given specific path. /// - public class CommandPromptInteraction: ErrorHandlingBase + /// The path to start the Command Prompt with. + /// True if the operation was successful; otherwise false. + public static bool OpenCmdWithPath(string path) { - /// - /// Shows the Command Prompt (cmd.exe) with a given specific path. - /// - /// The path to start the Command Prompt with. - /// True if the operation was successful; otherwise false. - public static bool OpenCmdWithPath(string path) + try { - try + var processStartInfo = new ProcessStartInfo() { - var processStartInfo = new ProcessStartInfo() - { - FileName = "cmd.exe", - WorkingDirectory = path, - UseShellExecute = false, - LoadUserProfile = true, - }; + FileName = "cmd.exe", + WorkingDirectory = path, + UseShellExecute = false, + LoadUserProfile = true, + }; - System.Diagnostics.Process.Start(processStartInfo); + System.Diagnostics.Process.Start(processStartInfo); - return true; - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); - return false; - } + return true; + } + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + return false; } + } - /// - /// Opens the Windows PowerShell (powershell.exe) with a given specific path. - /// - /// The path to start the Windows PowerShell with. - /// True if the operation was successful; otherwise false. - public static bool OpenPowerShellWithPath(string path) + /// + /// Opens the Windows PowerShell (powershell.exe) with a given specific path. + /// + /// The path to start the Windows PowerShell with. + /// True if the operation was successful; otherwise false. + public static bool OpenPowerShellWithPath(string path) + { + try { - try + var processStartInfo = new ProcessStartInfo() { - var processStartInfo = new ProcessStartInfo() - { - FileName = "powershell.exe", - WorkingDirectory = path, - UseShellExecute = false, - LoadUserProfile = true, - }; + FileName = "powershell.exe", + WorkingDirectory = path, + UseShellExecute = false, + LoadUserProfile = true, + }; - System.Diagnostics.Process.Start(processStartInfo); + System.Diagnostics.Process.Start(processStartInfo); - return true; - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); - return false; - } + return true; + } + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + return false; } } -} - +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/WindowsExplorerInteraction.cs b/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/WindowsExplorerInteraction.cs index 37b28bbd..3c7d2636 100644 --- a/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/WindowsExplorerInteraction.cs +++ b/ScriptNotepad/UtilityClasses/ExternalProcessInteraction/WindowsExplorerInteraction.cs @@ -26,73 +26,72 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.ExternalProcessInteraction +namespace ScriptNotepad.UtilityClasses.ExternalProcessInteraction; + +/// +/// A class to interact with Windows explorer. +/// +public class WindowsExplorerInteraction: ErrorHandlingBase { /// - /// A class to interact with Windows explorer. + /// Shows the file or path in Windows explorer. /// - public class WindowsExplorerInteraction: ErrorHandlingBase + /// The file or path to show in the Windows explorer. + /// True if the operation was successful; otherwise false. + public static bool ShowFileOrPathInExplorer(string fileOrPath) { - /// - /// Shows the file or path in Windows explorer. - /// - /// The file or path to show in the Windows explorer. - /// True if the operation was successful; otherwise false. - public static bool ShowFileOrPathInExplorer(string fileOrPath) + try + { + // (C): https://social.msdn.microsoft.com/Forums/vstudio/en-US/a6e1458a-20d0-48b4-8e3a-0a00c8618d75/opening-folder-in-explorer-by-c-code?forum=netfxbcl + System.Diagnostics.Process.Start("explorer.exe", $"/e,/select,{fileOrPath}"); + return true; + } + catch (Exception ex) { - try - { - // (C): https://social.msdn.microsoft.com/Forums/vstudio/en-US/a6e1458a-20d0-48b4-8e3a-0a00c8618d75/opening-folder-in-explorer-by-c-code?forum=netfxbcl - System.Diagnostics.Process.Start("explorer.exe", $"/e,/select,{fileOrPath}"); - return true; - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); - return false; - } + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + return false; } + } - /// - /// Opens the folder in explorer. - /// - /// The folder to show in the Windows explorer. - /// True if the operation was successful; otherwise false. - public static bool OpenFolderInExplorer(string folder) + /// + /// Opens the folder in explorer. + /// + /// The folder to show in the Windows explorer. + /// True if the operation was successful; otherwise false. + public static bool OpenFolderInExplorer(string folder) + { + try { - try - { - System.Diagnostics.Process.Start("explorer.exe", folder); - return true; - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); - return false; - } + System.Diagnostics.Process.Start("explorer.exe", folder); + return true; } + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + return false; + } + } - /// - /// Opens the file with associated program. - /// - /// The name of the file to open. - /// True if the operation was successful; otherwise false. - public static bool OpenWithAssociatedProgram(string fileName) + /// + /// Opens the file with associated program. + /// + /// The name of the file to open. + /// True if the operation was successful; otherwise false. + public static bool OpenWithAssociatedProgram(string fileName) + { + try + { + System.Diagnostics.Process.Start(fileName); + return true; + } + catch (Exception ex) { - try - { - System.Diagnostics.Process.Start(fileName); - return true; - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); - return false; - } + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + return false; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/GraphicUtils/FontFamilyHelpers.cs b/ScriptNotepad/UtilityClasses/GraphicUtils/FontFamilyHelpers.cs index 41a507d8..5ff0003c 100644 --- a/ScriptNotepad/UtilityClasses/GraphicUtils/FontFamilyHelpers.cs +++ b/ScriptNotepad/UtilityClasses/GraphicUtils/FontFamilyHelpers.cs @@ -27,48 +27,47 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Drawing; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.GraphicUtils +namespace ScriptNotepad.UtilityClasses.GraphicUtils; + +/// +/// A class with helper methods for the class. +/// +public static class FontFamilyHelpers { /// - /// A class with helper methods for the class. + /// Determines whether the given font family is fixed width (mono-space). /// - public static class FontFamilyHelpers + /// The font family to check for. + // (C): https://social.msdn.microsoft.com/Forums/windows/en-US/5b582b96-ade5-4354-99cf-3fe64cc6b53b/determining-if-font-is-monospaced?forum=winforms + public static bool IsFixedWidth(this FontFamily fontFamily) { - /// - /// Determines whether the given font family is fixed width (mono-space). - /// - /// The font family to check for. - // (C): https://social.msdn.microsoft.com/Forums/windows/en-US/5b582b96-ade5-4354-99cf-3fe64cc6b53b/determining-if-font-is-monospaced?forum=winforms - public static bool IsFixedWidth(this FontFamily fontFamily) + char[] measureChars = { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.', }; + if (Form.ActiveForm != null) { - char[] measureChars = { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' }; - if (Form.ActiveForm != null) + using (Graphics graphics = Graphics.FromHwnd(Form.ActiveForm.Handle)) { - using (Graphics graphics = Graphics.FromHwnd(Form.ActiveForm.Handle)) + try { - try + using (Font font = new Font(fontFamily, 10, FontStyle.Regular, GraphicsUnit.Pixel)) { - using (Font font = new Font(fontFamily, 10, FontStyle.Regular, GraphicsUnit.Pixel)) + float charWidth = graphics.MeasureString("I", font).Width; + foreach (var measureChar in measureChars) { - float charWidth = graphics.MeasureString("I", font).Width; - foreach (var measureChar in measureChars) + // ReSharper disable once CompareOfFloatsByEqualityOperator + if (graphics.MeasureString(measureChar.ToString(), font).Width != charWidth) { - // ReSharper disable once CompareOfFloatsByEqualityOperator - if (graphics.MeasureString(measureChar.ToString(), font).Width != charWidth) - { - return false; - } + return false; } } } - catch - { - return false; - } + } + catch + { + return false; } } - - return true; } + + return true; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/IO/DirectoryCrawler.cs b/ScriptNotepad/UtilityClasses/IO/DirectoryCrawler.cs index a90016c2..78f4384f 100644 --- a/ScriptNotepad/UtilityClasses/IO/DirectoryCrawler.cs +++ b/ScriptNotepad/UtilityClasses/IO/DirectoryCrawler.cs @@ -31,236 +31,304 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // ReSharper disable PossibleMultipleEnumeration -namespace ScriptNotepad.UtilityClasses.IO +namespace ScriptNotepad.UtilityClasses.IO; + +/// +/// A class to crawl through directories to search either files or directories. +/// +public class DirectoryCrawler: ErrorHandlingBase { /// - /// A class to crawl through directories to search either files or directories. + /// The type of the search for the class. /// - public class DirectoryCrawler: ErrorHandlingBase + public enum SearchTypeMatch { /// - /// The type of the search for the class. + /// Files matching a given mask are searched. /// - public enum SearchTypeMatch - { - /// - /// Files matching a given mask are searched. - /// - FileMask, - - /// - /// Files matching a given regular expression are searched. - /// - Regex, - - /// - /// All files a searched with the mask of '*.*'. - /// - AllFiles, - - /// - /// Files are searched with the mask of '*.'. - /// - FilesNoExtension, - - /// - /// Only directories are searched. - /// - Directories, - } + FileMask, /// - /// A value indicating if the current search process should be canceled. + /// Files matching a given regular expression are searched. /// - public volatile bool Canceled = false; + Regex, /// - /// Gets or sets the type of the search. + /// All files a searched with the mask of '*.*'. /// - private SearchTypeMatch SearchType { get; set; } + AllFiles, /// - /// Gets or sets the search mask. + /// Files are searched with the mask of '*.'. /// - private string SearchMask { get; set; } + FilesNoExtension, /// - /// Gets or sets the compiled regular expression in case the search type is . + /// Only directories are searched. /// - private Regex FileExtensionMatch { get; set; } + Directories, + } - /// - /// Gets or sets the starting path of the search. - /// - private string Path { get; set; } + /// + /// A value indicating if the current search process should be canceled. + /// + public volatile bool Canceled = false; - /// - /// Gets or sets a value indicating whether this uses recursion; i.e. searches from the subdirectories as well. - /// - private bool Recursion { get; set; } + /// + /// Gets or sets the type of the search. + /// + private SearchTypeMatch SearchType { get; set; } - /// - /// Creates a compiled regular expression from a given list of file extensions. - /// - /// The file extensions to be used with the search. - /// An instance to a class. - private static Regex FromExtensions(params string[] extensions) + /// + /// Gets or sets the search mask. + /// + private string SearchMask { get; set; } + + /// + /// Gets or sets the compiled regular expression in case the search type is . + /// + private Regex FileExtensionMatch { get; set; } + + /// + /// Gets or sets the starting path of the search. + /// + private string Path { get; set; } + + /// + /// Gets or sets a value indicating whether this uses recursion; i.e. searches from the subdirectories as well. + /// + private bool Recursion { get; set; } + + /// + /// Creates a compiled regular expression from a given list of file extensions. + /// + /// The file extensions to be used with the search. + /// An instance to a class. + private static Regex FromExtensions(params string[] extensions) + { + // remove the useless '*.' and '.' character combinations from the given parameters.. + for (int i = 0; i < extensions.Length; i++) { - // remove the useless '*.' and '.' character combinations from the given parameters.. - for (int i = 0; i < extensions.Length; i++) - { - extensions[i] = - extensions[i]. - Replace("*.", ""). - Replace(".", ""); + extensions[i] = + extensions[i]. + Replace("*.", ""). + Replace(".", ""); - // the '*' character requires special handling; otherwise an exception would occur.. - if (extensions[i] == "*") - { - extensions[i] = "." + extensions[i]; - } - } - - // create a compiled regular expression of the given parameters - // and return it.. hint: '\.(cs|txt|xml)$' - try + // the '*' character requires special handling; otherwise an exception would occur.. + if (extensions[i] == "*") { - return new Regex(@"\.(" + string.Join("|", extensions) + ")$", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + extensions[i] = "." + extensions[i]; } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + } + + // create a compiled regular expression of the given parameters + // and return it.. hint: '\.(cs|txt|xml)$' + try + { + return new Regex(@"\.(" + string.Join("|", extensions) + ")$", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); - // return a regexp matching all file endings.. - return new Regex(@"\\.*", RegexOptions.IgnoreCase | RegexOptions.Compiled); - } + // return a regexp matching all file endings.. + return new Regex(@"\\.*", RegexOptions.IgnoreCase | RegexOptions.Compiled); } + } - /// - /// Checks if a compiled regular expression from a given list of file extensions is valid. - /// - /// The file extensions to be used with the check. - /// True if the created regular expression is valid; otherwise false. - public static bool ValidateExtensionRegexp(params string[] extensions) + /// + /// Checks if a compiled regular expression from a given list of file extensions is valid. + /// + /// The file extensions to be used with the check. + /// True if the created regular expression is valid; otherwise false. + public static bool ValidateExtensionRegexp(params string[] extensions) + { + // remove the useless '*.' and '.' character combinations from the given parameters.. + for (int i = 0; i < extensions.Length; i++) { - // remove the useless '*.' and '.' character combinations from the given parameters.. - for (int i = 0; i < extensions.Length; i++) - { - extensions[i] = - extensions[i]. - Replace("*.", ""). - Replace(".", ""); + extensions[i] = + extensions[i]. + Replace("*.", ""). + Replace(".", ""); - // the '*' character requires special handling; otherwise an exception would occur.. - if (extensions[i] == "*") - { - extensions[i] = "." + extensions[i]; - } - } - - // create a compiled regular expression of the given parameters - // and return it.. hint: '\.(cs|txt|xml)$' - try - { - // ReSharper disable once ObjectCreationAsStatement - new Regex(@"\.(" + string.Join("|", extensions) + ")$", - RegexOptions.IgnoreCase | RegexOptions.Compiled); - return true; - } - catch (Exception ex) + // the '*' character requires special handling; otherwise an exception would occur.. + if (extensions[i] == "*") { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; + extensions[i] = "." + extensions[i]; } } + + // create a compiled regular expression of the given parameters + // and return it.. hint: '\.(cs|txt|xml)$' + try + { + // ReSharper disable once ObjectCreationAsStatement + new Regex(@"\.(" + string.Join("|", extensions) + ")$", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + return true; + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + return false; + } + } - /// - /// Initializes a new instance of the class. - /// - /// The path to start the search from. - /// Type of the search. - /// The search mask. - /// if set to true the subdirectories are searched as well. - public DirectoryCrawler(string path, SearchTypeMatch searchType, string searchMask, bool subDirectories) + /// + /// Initializes a new instance of the class. + /// + /// The path to start the search from. + /// Type of the search. + /// The search mask. + /// if set to true the subdirectories are searched as well. + public DirectoryCrawler(string path, SearchTypeMatch searchType, string searchMask, bool subDirectories) + { + // set the constructor values.. + Path = path; + SearchType = searchType; + SearchMask = searchMask; + Recursion = subDirectories; + // END: set the constructor values.. + + // based on the give search type, manipulate the search mask accordingly.. + switch (SearchType) { - // set the constructor values.. - Path = path; - SearchType = searchType; - SearchMask = searchMask; - Recursion = subDirectories; - // END: set the constructor values.. - - // based on the give search type, manipulate the search mask accordingly.. - switch (SearchType) - { - case SearchTypeMatch.Regex: - FileExtensionMatch = FromExtensions(searchMask.Split(';')); - break; + case SearchTypeMatch.Regex: + FileExtensionMatch = FromExtensions(searchMask.Split(';')); + break; - case SearchTypeMatch.AllFiles: - SearchMask = "*"; // this matches all files with or without an extension.. - break; + case SearchTypeMatch.AllFiles: + SearchMask = "*"; // this matches all files with or without an extension.. + break; - case SearchTypeMatch.FilesNoExtension: - SearchMask = "*."; // this matches files without an extension.. - break; + case SearchTypeMatch.FilesNoExtension: + SearchMask = "*."; // this matches files without an extension.. + break; - case SearchTypeMatch.Directories: - SearchMask = string.Empty; // no filtering for directories.. - break; + case SearchTypeMatch.Directories: + SearchMask = string.Empty; // no filtering for directories.. + break; - case SearchTypeMatch.FileMask: - SearchMask = searchMask; // the search mask can be the user given one.. - break; - } + case SearchTypeMatch.FileMask: + SearchMask = searchMask; // the search mask can be the user given one.. + break; } + } - /// - /// Gets the crawl result; A list of files or directories based on the class initialization. - /// - /// IEnumerable<System.String>. - public IEnumerable GetCrawlResult() + /// + /// Gets the crawl result; A list of files or directories based on the class initialization. + /// + /// IEnumerable<System.String>. + public IEnumerable GetCrawlResult() + { + if (SearchType == SearchTypeMatch.Directories) { - if (SearchType == SearchTypeMatch.Directories) + return GetDirectories(Path, Recursion); + } + + return GetFiles(Path, Recursion); + } + + /// + /// A delegate for the event. + /// + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnReportProgress(object sender, DirectoryCrawlerEventArgs e); + + /// + /// Occurs when the is reporting progress. + /// + public event OnReportProgress ReportProgress; + + /// + /// Gets the directories based on the class initialization. + /// + /// The path to start enumerating the directories from. + /// if set to true the subdirectories are also included in the result. + /// IEnumerable<System.String>. + private IEnumerable GetDirectories(string path, bool subDirectories) + { + List result = new List(); + // a SecurityException or a UnauthorizedAccessException may intrude the enumeration + // process any time and it will also result in exception if the directories where + // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories).. + try + { + List directories = new List(); + + foreach (var directory in Directory.EnumerateDirectories(path)) { - return GetDirectories(Path, Recursion); + // the process was requested to be canceled.. + if (Canceled) + { + return result; + } + + // report the progress if subscribed.. + ReportProgress?.Invoke(this, + new DirectoryCrawlerEventArgs + {CurrentDirectory = path, FileName = string.Empty, Directory = directory, }); + result.Add(directory); + directories.Add(directory); } - return GetFiles(Path, Recursion); + if (subDirectories) + { + // a SecurityException or a UnauthorizedAccessException may intrude the enumeration + // process any time and it will also result in exception if the directories where + // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories).. + try + { + foreach (var directory in directories) + { + // the process was requested to be canceled.. + if (Canceled) + { + return result; + } + + result.AddRange(GetDirectories(directory, true)); + } + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } + } + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); } - /// - /// A delegate for the event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnReportProgress(object sender, DirectoryCrawlerEventArgs e); + return result; + } - /// - /// Occurs when the is reporting progress. - /// - public event OnReportProgress ReportProgress; + /// + /// Gets the files based on the class initialization. + /// + /// The path to start enumerating the files from. + /// if set to true the files in subdirectories are also included in the result. + /// IEnumerable<System.String>. + private IEnumerable GetFiles(string path, bool subDirectories) + { + List result = new List(); - /// - /// Gets the directories based on the class initialization. - /// - /// The path to start enumerating the directories from. - /// if set to true the subdirectories are also included in the result. - /// IEnumerable<System.String>. - private IEnumerable GetDirectories(string path, bool subDirectories) + // a SecurityException or a UnauthorizedAccessException may intrude the enumeration + // process any time and it will also result in exception if the files where enumerated + // solely depending on the Directory.EnumerateFiles(path, ...,SearchOption.AllDirectories).. + try { - List result = new List(); - // a SecurityException or a UnauthorizedAccessException may intrude the enumeration - // process any time and it will also result in exception if the directories where - // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories).. - try + // based on the search type append to the result.. + if (SearchType == SearchTypeMatch.Regex) { - List directories = new List(); - - foreach (var directory in Directory.EnumerateDirectories(path)) + foreach (var file in Directory.EnumerateFiles(path).Where(f => FileExtensionMatch.IsMatch(f))) { // the process was requested to be canceled.. if (Canceled) @@ -271,84 +339,41 @@ private IEnumerable GetDirectories(string path, bool subDirectories) // report the progress if subscribed.. ReportProgress?.Invoke(this, new DirectoryCrawlerEventArgs - {CurrentDirectory = path, FileName = string.Empty, Directory = directory}); - result.Add(directory); - directories.Add(directory); - } + {CurrentDirectory = path, FileName = file, Directory = string.Empty, }); - if (subDirectories) + // add to the result.. + result.Add(file); + } + } + else if (SearchType == SearchTypeMatch.AllFiles || SearchType == SearchTypeMatch.FileMask || + SearchType == SearchTypeMatch.FilesNoExtension) + { + foreach (var file in Directory.EnumerateFiles(path, SearchMask)) { - // a SecurityException or a UnauthorizedAccessException may intrude the enumeration - // process any time and it will also result in exception if the directories where - // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories).. - try - { - foreach (var directory in directories) - { - // the process was requested to be canceled.. - if (Canceled) - { - return result; - } - - result.AddRange(GetDirectories(directory, true)); - } - } - catch (Exception ex) + // the process was requested to be canceled.. + if (Canceled) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); + return result; } - } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - } - return result; - } + // report the progress if subscribed.. + ReportProgress?.Invoke(this, + new DirectoryCrawlerEventArgs + {CurrentDirectory = path, FileName = file, Directory = string.Empty, }); - /// - /// Gets the files based on the class initialization. - /// - /// The path to start enumerating the files from. - /// if set to true the files in subdirectories are also included in the result. - /// IEnumerable<System.String>. - private IEnumerable GetFiles(string path, bool subDirectories) - { - List result = new List(); + // add to the result.. + result.Add(file); + } + } - // a SecurityException or a UnauthorizedAccessException may intrude the enumeration - // process any time and it will also result in exception if the files where enumerated - // solely depending on the Directory.EnumerateFiles(path, ...,SearchOption.AllDirectories).. - try + if (subDirectories) { - // based on the search type append to the result.. - if (SearchType == SearchTypeMatch.Regex) - { - foreach (var file in Directory.EnumerateFiles(path).Where(f => FileExtensionMatch.IsMatch(f))) - { - // the process was requested to be canceled.. - if (Canceled) - { - return result; - } - - // report the progress if subscribed.. - ReportProgress?.Invoke(this, - new DirectoryCrawlerEventArgs - {CurrentDirectory = path, FileName = file, Directory = string.Empty}); - - // add to the result.. - result.Add(file); - } - } - else if (SearchType == SearchTypeMatch.AllFiles || SearchType == SearchTypeMatch.FileMask || - SearchType == SearchTypeMatch.FilesNoExtension) + // a SecurityException or a UnauthorizedAccessException may intrude the enumeration + // process any time and it will also result in exception if the directories where + // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories).. + try { - foreach (var file in Directory.EnumerateFiles(path, SearchMask)) + foreach (var directory in Directory.EnumerateDirectories(path)) { // the process was requested to be canceled.. if (Canceled) @@ -359,51 +384,25 @@ private IEnumerable GetFiles(string path, bool subDirectories) // report the progress if subscribed.. ReportProgress?.Invoke(this, new DirectoryCrawlerEventArgs - {CurrentDirectory = path, FileName = file, Directory = string.Empty}); + {CurrentDirectory = path, FileName = string.Empty, Directory = directory, }); // add to the result.. - result.Add(file); - } + result.AddRange(GetFiles(directory, true)); + } } - - if (subDirectories) + catch (Exception ex) { - // a SecurityException or a UnauthorizedAccessException may intrude the enumeration - // process any time and it will also result in exception if the directories where - // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories).. - try - { - foreach (var directory in Directory.EnumerateDirectories(path)) - { - // the process was requested to be canceled.. - if (Canceled) - { - return result; - } - - // report the progress if subscribed.. - ReportProgress?.Invoke(this, - new DirectoryCrawlerEventArgs - {CurrentDirectory = path, FileName = string.Empty, Directory = directory}); - - // add to the result.. - result.AddRange(GetFiles(directory, true)); - } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - } + // log the exception.. + ExceptionLogAction?.Invoke(ex); } } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - } - - return result; } + catch (Exception ex) + { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + } + + return result; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/IO/DirectoryCrawlerEventArgs.cs b/ScriptNotepad/UtilityClasses/IO/DirectoryCrawlerEventArgs.cs index ebfd49e2..22c811cf 100644 --- a/ScriptNotepad/UtilityClasses/IO/DirectoryCrawlerEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/IO/DirectoryCrawlerEventArgs.cs @@ -24,28 +24,27 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.IO +namespace ScriptNotepad.UtilityClasses.IO; + +/// +/// Event arguments for the class. +/// Implements the +/// +/// +public class DirectoryCrawlerEventArgs: EventArgs { /// - /// Event arguments for the class. - /// Implements the + /// Gets or sets the currently found file name. + /// + public string FileName { get; set; } + + /// + /// Gets or sets the currently found directory. + /// + public string Directory { get; set; } + + /// + /// Gets or sets the current directory being searched. /// - /// - public class DirectoryCrawlerEventArgs: EventArgs - { - /// - /// Gets or sets the currently found file name. - /// - public string FileName { get; set; } - - /// - /// Gets or sets the currently found directory. - /// - public string Directory { get; set; } - - /// - /// Gets or sets the current directory being searched. - /// - public string CurrentDirectory { get; set; } - } -} + public string CurrentDirectory { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Installer/WaitForProcess.cs b/ScriptNotepad/UtilityClasses/Installer/WaitForProcess.cs index bb9fe4c9..1de8afad 100644 --- a/ScriptNotepad/UtilityClasses/Installer/WaitForProcess.cs +++ b/ScriptNotepad/UtilityClasses/Installer/WaitForProcess.cs @@ -36,98 +36,96 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ // ReSharper disable once CheckNamespace -namespace VPKSoft.WaitForProcessUtil +namespace VPKSoft.WaitForProcessUtil; + +/// +/// A class to wait for a process to finish executing with a possibility for a time-out. +/// +// ReSharper disable once UnusedMember.Global +public class WaitForProcess { /// - /// A class to wait for a process to finish executing with a possibility for a time-out. + /// Gets the process identifier from a command line argument array. /// - // ReSharper disable once UnusedMember.Global - public class WaitForProcess + /// The arguments to look for a '--waitPid' argument. + /// The process identifier to wait for or -1 of the argument is not defined or some kind of error occurred. + public static int GetWaitProcessId(string[] args) { - /// - /// Gets the process identifier from a command line argument array. - /// - /// The arguments to look for a '--waitPid' argument. - /// The process identifier to wait for or -1 of the argument is not defined or some kind of error occurred. - public static int GetWaitProcessId(string[] args) + try { - try - { - List argList = new List(args); - var index = argList.IndexOf("--waitPid"); // case-sensitive.. + List argList = new List(args); + var index = argList.IndexOf("--waitPid"); // case-sensitive.. - // must have the following process id number.. - if (index != -1 && index + 1 < argList.Count) + // must have the following process id number.. + if (index != -1 && index + 1 < argList.Count) + { + // check the ar + if (int.TryParse(argList[index + 1], out _)) { - // check the ar - if (int.TryParse(argList[index + 1], out _)) - { - return int.Parse(argList[index + 1]); - } + return int.Parse(argList[index + 1]); } - - return -1; - } - catch - { - return -1; // unknown reason of failure in a prefect code (ha-ha).. } + + return -1; + } + catch + { + return -1; // unknown reason of failure in a prefect code (ha-ha).. } + } + + /// + /// Waits for a process which identifier is specified in the given arguments with a '--waitPid' argument to exit. + /// + /// The arguments to check for. + /// The maximum amount in seconds to wait for the process to exit. + // ReSharper disable once UnusedMember.Global + public static void WaitForProcessArguments(string[] args, int maxWaitSeconds = 0) + { + WaitProcess(GetWaitProcessId(args), maxWaitSeconds); + } - /// - /// Waits for a process which identifier is specified in the given arguments with a '--waitPid' argument to exit. - /// - /// The arguments to check for. - /// The maximum amount in seconds to wait for the process to exit. - // ReSharper disable once UnusedMember.Global - public static void WaitForProcessArguments(string[] args, int maxWaitSeconds = 0) + /// + /// Waits the process to exit with a specified process identifier and a specified time-out. + /// + /// The process identifier for the process which exit to wait for. + /// The maximum amount in seconds to wait for the process to exit. + public static void WaitProcess(int processId, int maxWaitSeconds = 0) + { + if (processId == -1) // invalid identifier = no deal.. { - WaitProcess(GetWaitProcessId(args), maxWaitSeconds); + return; } - /// - /// Waits the process to exit with a specified process identifier and a specified time-out. - /// - /// The process identifier for the process which exit to wait for. - /// The maximum amount in seconds to wait for the process to exit. - public static void WaitProcess(int processId, int maxWaitSeconds = 0) + try { - if (processId == -1) // invalid identifier = no deal.. + using (var process = Process.GetProcessById(processId)) { - return; - } - try - { - using (var process = Process.GetProcessById(processId)) + if (maxWaitSeconds == 0) { + process.WaitForExit(); + } - if (maxWaitSeconds == 0) - { - process.WaitForExit(); - } - - if (maxWaitSeconds > 0) // if the wait time is specified, then wait for the process in a loop.. + if (maxWaitSeconds > 0) // if the wait time is specified, then wait for the process in a loop.. + { + var waitCount = 0; + var waitMax = maxWaitSeconds * 1000; + while (waitCount < waitMax) // ..for the specified maximum time amount.. { - var waitCount = 0; - var waitMax = maxWaitSeconds * 1000; - while (waitCount < waitMax) // ..for the specified maximum time amount.. + if (process.WaitForExit(100)) { - if (process.WaitForExit(100)) - { - return; - } - - waitCount += 100; + return; } + + waitCount += 100; } } } - catch - { - // the process information couldn't be gotten.. - } + } + catch + { + // the process information couldn't be gotten.. } } -} - +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Keyboard/KeySendList.ExcludeLicense.cs b/ScriptNotepad/UtilityClasses/Keyboard/KeySendList.ExcludeLicense.cs index 105a10c1..9cc1daed 100644 --- a/ScriptNotepad/UtilityClasses/Keyboard/KeySendList.ExcludeLicense.cs +++ b/ScriptNotepad/UtilityClasses/Keyboard/KeySendList.ExcludeLicense.cs @@ -9,117 +9,116 @@ This file is public domain. using System.Collections.Generic; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.Keyboard +namespace ScriptNotepad.UtilityClasses.Keyboard; + +/// +/// A class for sending key presses to controls. +/// +public static class KeySendList { + private static readonly List> KeyList = new List>(new [] + { + new KeyValuePair(Keys.Back, "{BACKSPACE}"), + new KeyValuePair(Keys.Pause, "{BREAK}"), + // ReSharper disable once StringLiteralTypo + new KeyValuePair(Keys.CapsLock, "{CAPSLOCK}"), + new KeyValuePair(Keys.Delete, "{DELETE}"), + new KeyValuePair(Keys.Down, "{DOWN}"), + new KeyValuePair(Keys.End, "{END}"), + new KeyValuePair(Keys.Return, "{ENTER}"), + new KeyValuePair(Keys.Escape, "{ESC}"), + new KeyValuePair(Keys.Help, "{HELP}"), + new KeyValuePair(Keys.Home, "{HOME}"), + new KeyValuePair(Keys.Insert, "{INSERT}"), + new KeyValuePair(Keys.Left, "{LEFT}"), + // ReSharper disable once StringLiteralTypo + new KeyValuePair(Keys.NumLock, "{NUMLOCK}"), + // ReSharper disable once StringLiteralTypo + new KeyValuePair(Keys.PageDown, "{PGDN}"), + // ReSharper disable once StringLiteralTypo + new KeyValuePair(Keys.PageUp, "{PGUP}"), + // ReSharper disable once StringLiteralTypo + new KeyValuePair(Keys.PrintScreen, "{PRTSC}"), + new KeyValuePair(Keys.Right, "{RIGHT}"), + // ReSharper disable once StringLiteralTypo + new KeyValuePair(Keys.Scroll, "{SCROLLLOCK}"), + new KeyValuePair(Keys.Tab, "{TAB}"), + new KeyValuePair(Keys.Up, "{UP}"), + new KeyValuePair(Keys.F1, "{F1}"), + new KeyValuePair(Keys.F2, "{F2}"), + new KeyValuePair(Keys.F3, "{F3}"), + new KeyValuePair(Keys.F4, "{F4}"), + new KeyValuePair(Keys.F5, "{F5}"), + new KeyValuePair(Keys.F6, "{F6}"), + new KeyValuePair(Keys.F7, "{F7}"), + new KeyValuePair(Keys.F8, "{F8}"), + new KeyValuePair(Keys.F9, "{F9}"), + new KeyValuePair(Keys.F10, "{F10}"), + new KeyValuePair(Keys.F11, "{F11}"), + new KeyValuePair(Keys.F12, "{F12}"), + new KeyValuePair(Keys.F13, "{F13}"), + new KeyValuePair(Keys.F14, "{F14}"), + new KeyValuePair(Keys.F15, "{F15}"), + new KeyValuePair(Keys.F16, "{F16}"), + new KeyValuePair(Keys.Add, "{ADD}"), + new KeyValuePair(Keys.Subtract, "{SUBTRACT}"), + new KeyValuePair(Keys.Multiply, "{MULTIPLY}"), + new KeyValuePair(Keys.Divide, "{DIVIDE}"), + new KeyValuePair(Keys.OemMinus, "-"), // Added: 19.10.19, VPKSoft.. + new KeyValuePair(Keys.OemPeriod, "."), // Added: 19.10.19, VPKSoft.. + }); + /// - /// A class for sending key presses to controls. + /// Determines whether the specified key is supported by the class. /// - public static class KeySendList + /// The key to check for. + /// true if the specified key is supported by the class; otherwise, false. + public static bool HasKey(Keys key) { - private static readonly List> KeyList = new List>(new [] - { - new KeyValuePair(Keys.Back, "{BACKSPACE}"), - new KeyValuePair(Keys.Pause, "{BREAK}"), - // ReSharper disable once StringLiteralTypo - new KeyValuePair(Keys.CapsLock, "{CAPSLOCK}"), - new KeyValuePair(Keys.Delete, "{DELETE}"), - new KeyValuePair(Keys.Down, "{DOWN}"), - new KeyValuePair(Keys.End, "{END}"), - new KeyValuePair(Keys.Return, "{ENTER}"), - new KeyValuePair(Keys.Escape, "{ESC}"), - new KeyValuePair(Keys.Help, "{HELP}"), - new KeyValuePair(Keys.Home, "{HOME}"), - new KeyValuePair(Keys.Insert, "{INSERT}"), - new KeyValuePair(Keys.Left, "{LEFT}"), - // ReSharper disable once StringLiteralTypo - new KeyValuePair(Keys.NumLock, "{NUMLOCK}"), - // ReSharper disable once StringLiteralTypo - new KeyValuePair(Keys.PageDown, "{PGDN}"), - // ReSharper disable once StringLiteralTypo - new KeyValuePair(Keys.PageUp, "{PGUP}"), - // ReSharper disable once StringLiteralTypo - new KeyValuePair(Keys.PrintScreen, "{PRTSC}"), - new KeyValuePair(Keys.Right, "{RIGHT}"), - // ReSharper disable once StringLiteralTypo - new KeyValuePair(Keys.Scroll, "{SCROLLLOCK}"), - new KeyValuePair(Keys.Tab, "{TAB}"), - new KeyValuePair(Keys.Up, "{UP}"), - new KeyValuePair(Keys.F1, "{F1}"), - new KeyValuePair(Keys.F2, "{F2}"), - new KeyValuePair(Keys.F3, "{F3}"), - new KeyValuePair(Keys.F4, "{F4}"), - new KeyValuePair(Keys.F5, "{F5}"), - new KeyValuePair(Keys.F6, "{F6}"), - new KeyValuePair(Keys.F7, "{F7}"), - new KeyValuePair(Keys.F8, "{F8}"), - new KeyValuePair(Keys.F9, "{F9}"), - new KeyValuePair(Keys.F10, "{F10}"), - new KeyValuePair(Keys.F11, "{F11}"), - new KeyValuePair(Keys.F12, "{F12}"), - new KeyValuePair(Keys.F13, "{F13}"), - new KeyValuePair(Keys.F14, "{F14}"), - new KeyValuePair(Keys.F15, "{F15}"), - new KeyValuePair(Keys.F16, "{F16}"), - new KeyValuePair(Keys.Add, "{ADD}"), - new KeyValuePair(Keys.Subtract, "{SUBTRACT}"), - new KeyValuePair(Keys.Multiply, "{MULTIPLY}"), - new KeyValuePair(Keys.Divide, "{DIVIDE}"), - new KeyValuePair(Keys.OemMinus, "-"), // Added: 19.10.19, VPKSoft.. - new KeyValuePair(Keys.OemPeriod, "."), // Added: 19.10.19, VPKSoft.. - }); - - /// - /// Determines whether the specified key is supported by the class. - /// - /// The key to check for. - /// true if the specified key is supported by the class; otherwise, false. - public static bool HasKey(Keys key) - { - return GetKeyString(key) != null; - } + return GetKeyString(key) != null; + } - /// - /// Determines whether the specified key is supported by the class. - /// - /// The key to check for. - /// true if the specified key is supported by the class; otherwise, false. - public static bool HasKey(string key) - { - return GetKeyKeys(key) != null; - } + /// + /// Determines whether the specified key is supported by the class. + /// + /// The key to check for. + /// true if the specified key is supported by the class; otherwise, false. + public static bool HasKey(string key) + { + return GetKeyKeys(key) != null; + } - /// - /// Gets a string matching the given . - /// - /// The key for which to get the corresponding string for. - /// A string matching the if found; otherwise null. - public static string GetKeyString(Keys key) + /// + /// Gets a string matching the given . + /// + /// The key for which to get the corresponding string for. + /// A string matching the if found; otherwise null. + public static string GetKeyString(Keys key) + { + foreach (var k in KeyList) { - foreach (var k in KeyList) + if (k.Key == key) { - if (k.Key == key) - { - return k.Value; - } + return k.Value; } - return null; } + return null; + } - /// - /// Gets a enumeration value matching the given string value. - /// - /// The key as a string value. - /// A enumeration value if found; otherwise null. - public static Keys? GetKeyKeys(string key) + /// + /// Gets a enumeration value matching the given string value. + /// + /// The key as a string value. + /// A enumeration value if found; otherwise null. + public static Keys? GetKeyKeys(string key) + { + foreach (var k in KeyList) { - foreach (var k in KeyList) + if (k.Value == key) { - if (k.Value == key) - { - return k.Key; - } + return k.Key; } - return null; } + return null; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Keyboard/KeyboardHelpers.cs b/ScriptNotepad/UtilityClasses/Keyboard/KeyboardHelpers.cs index 275a7dda..74bb5005 100644 --- a/ScriptNotepad/UtilityClasses/Keyboard/KeyboardHelpers.cs +++ b/ScriptNotepad/UtilityClasses/Keyboard/KeyboardHelpers.cs @@ -26,103 +26,102 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.Keyboard +namespace ScriptNotepad.UtilityClasses.Keyboard; + +/// +/// A class containing some helper methods dealing with the keyboard. +/// +public static class KeyboardHelpers { /// - /// A class containing some helper methods dealing with the keyboard. + /// Gets a value indicating if some of the modifier keys are down (Control, Alt or Shift). /// - public static class KeyboardHelpers + /// The instance containing the event data. + /// true if some of the modifier keys are down, false otherwise. + public static bool SomeModifierKeysDown(this KeyEventArgs e) { - /// - /// Gets a value indicating if some of the modifier keys are down (Control, Alt or Shift). - /// - /// The instance containing the event data. - /// true if some of the modifier keys are down, false otherwise. - public static bool SomeModifierKeysDown(this KeyEventArgs e) - { - return e.Alt || e.Control || e.Shift; - } + return e.Alt || e.Control || e.Shift; + } - /// - /// Gets a value indicating if all of the modifier keys are down (Control, Alt or Shift). - /// - /// The instance containing the event data. - /// true if all of the modifier keys are down, false otherwise. - public static bool AllModifierKeysDown(this KeyEventArgs e) - { - return e.Alt && e.Control && e.Shift; - } + /// + /// Gets a value indicating if all of the modifier keys are down (Control, Alt or Shift). + /// + /// The instance containing the event data. + /// true if all of the modifier keys are down, false otherwise. + public static bool AllModifierKeysDown(this KeyEventArgs e) + { + return e.Alt && e.Control && e.Shift; + } - /// - /// Gets a value indicating if none of the modifier keys are down (Control, Alt or Shift). - /// - /// The instance containing the event data. - /// true if none of the modifier keys are down, false otherwise. - public static bool NoModifierKeysDown(this KeyEventArgs e) - { - return !e.Alt && !e.Control && !e.Shift; - } + /// + /// Gets a value indicating if none of the modifier keys are down (Control, Alt or Shift). + /// + /// The instance containing the event data. + /// true if none of the modifier keys are down, false otherwise. + public static bool NoModifierKeysDown(this KeyEventArgs e) + { + return !e.Alt && !e.Control && !e.Shift; + } - /// - /// Gets a value if only the Alt modifier key is down. - /// - /// The instance containing the event data. - /// true if only the Alt modifier key is down, false otherwise. - public static bool OnlyAlt(this KeyEventArgs e) - { - return e.ModifierKeysDown(true, false, false); - } + /// + /// Gets a value if only the Alt modifier key is down. + /// + /// The instance containing the event data. + /// true if only the Alt modifier key is down, false otherwise. + public static bool OnlyAlt(this KeyEventArgs e) + { + return e.ModifierKeysDown(true, false, false); + } - /// - /// Gets a value if only the Shift modifier key is down. - /// - /// The instance containing the event data. - /// true if only the Shift modifier key is down, false otherwise. - public static bool OnlyShift(this KeyEventArgs e) - { - return e.ModifierKeysDown(false, false, true); - } + /// + /// Gets a value if only the Shift modifier key is down. + /// + /// The instance containing the event data. + /// true if only the Shift modifier key is down, false otherwise. + public static bool OnlyShift(this KeyEventArgs e) + { + return e.ModifierKeysDown(false, false, true); + } - /// - /// Gets a value if only the Control modifier key is down. - /// - /// The instance containing the event data. - /// true if only the Control modifier key is down, false otherwise. - public static bool OnlyControl(this KeyEventArgs e) - { - return e.ModifierKeysDown(false, true, false); - } + /// + /// Gets a value if only the Control modifier key is down. + /// + /// The instance containing the event data. + /// true if only the Control modifier key is down, false otherwise. + public static bool OnlyControl(this KeyEventArgs e) + { + return e.ModifierKeysDown(false, true, false); + } - /// - /// Gets a value indicating if the given modifier keys are down (Control, Alt or Shift). - /// - /// The instance containing the event data. - /// if set to true the Alt key should be down. - /// if set to true the Control key should be down. - /// if set to true the Shift key should be down. - /// true if the given modifier keys are down, false otherwise. - public static bool ModifierKeysDown(this KeyEventArgs e, bool alt, bool control, bool shift) - { - return e.Alt && alt || e.Control && control || e.Shift && shift; - } + /// + /// Gets a value indicating if the given modifier keys are down (Control, Alt or Shift). + /// + /// The instance containing the event data. + /// if set to true the Alt key should be down. + /// if set to true the Control key should be down. + /// if set to true the Shift key should be down. + /// true if the given modifier keys are down, false otherwise. + public static bool ModifierKeysDown(this KeyEventArgs e, bool alt, bool control, bool shift) + { + return e.Alt && alt || e.Control && control || e.Shift && shift; + } - /// - /// Gets a value if some key is down in the given list of . - /// - /// The instance containing the event data. - /// The keys to check for. - /// true if some key is down in the given list of , false otherwise. - public static bool KeyCodeIn(this KeyEventArgs e, params Keys[] keys) + /// + /// Gets a value if some key is down in the given list of . + /// + /// The instance containing the event data. + /// The keys to check for. + /// true if some key is down in the given list of , false otherwise. + public static bool KeyCodeIn(this KeyEventArgs e, params Keys[] keys) + { + foreach (var key in keys) { - foreach (var key in keys) + if (e.KeyCode == key) { - if (e.KeyCode == key) - { - return true; - } + return true; } - - return false; } + + return false; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/KeyboardShortcutHelper/KeyboardMultiCombination.cs b/ScriptNotepad/UtilityClasses/KeyboardShortcutHelper/KeyboardMultiCombination.cs index d13a3657..49d77593 100644 --- a/ScriptNotepad/UtilityClasses/KeyboardShortcutHelper/KeyboardMultiCombination.cs +++ b/ScriptNotepad/UtilityClasses/KeyboardShortcutHelper/KeyboardMultiCombination.cs @@ -28,389 +28,387 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Linq; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.KeyboardShortcutHelper -{ - /* - Usage: - combination = new KeyboardCollectiveCombination(someForm); +namespace ScriptNotepad.UtilityClasses.KeyboardShortcutHelper; +/* + Usage: + combination = new KeyboardCollectiveCombination(someForm); - // Ctrl + D, 1, 2.. - combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.D}, "test"); - combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.D1}, "test"); - combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.D2}, "test"); + // Ctrl + D, 1, 2.. + combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.D}, "test"); + combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.D1}, "test"); + combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.D2}, "test"); - // Ctrl + A, B.. - combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.A}, "test2"); - combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.B}, "test2"); - */ + // Ctrl + A, B.. + combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.A}, "test2"); + combination.AddKeyChord(new KeyData {Ctrl = true, Key = Keys.B}, "test2"); +*/ +/// +/// A class to collect multi-key combinations. I.e. digits and letters. +/// +public class KeyboardMultiCombination: IDisposable +{ /// - /// A class to collect multi-key combinations. I.e. digits and letters. + /// Initializes a new instance of the class. /// - public class KeyboardMultiCombination: IDisposable + /// The form of which keyboard combinations to listen to . + /// The timer interval in milliseconds to assume the key combination is broken. + public KeyboardMultiCombination(Form form, int timerIntervalMs = 1000) { - /// - /// Initializes a new instance of the class. - /// - /// The form of which keyboard combinations to listen to . - /// The timer interval in milliseconds to assume the key combination is broken. - public KeyboardMultiCombination(Form form, int timerIntervalMs = 1000) + this.form = form; // save the form instance.. + form.KeyPreview = true; // set the key-preview to true.. + form.KeyDown += Form_KeyDown; // subscribe the keydown event.. + + ResetTimeMilliseconds = timerIntervalMs; // save the reset value.. + + TimerKeyDown = new Timer { - this.form = form; // save the form instance.. - form.KeyPreview = true; // set the key-preview to true.. - form.KeyDown += Form_KeyDown; // subscribe the keydown event.. + Interval = 10, // set the timer interval.. + }; + TimerKeyDown.Tick += TimerKeyDown_Tick; // subscribe the tick even.. + TimerKeyDown.Enabled = true; // enabled the timer.. + } - ResetTimeMilliseconds = timerIntervalMs; // save the reset value.. + /// + /// A field to hold the instance of which key board combinations to listen to. + /// + private readonly Form form; - TimerKeyDown = new Timer - { - Interval = 10 // set the timer interval.. - }; - TimerKeyDown.Tick += TimerKeyDown_Tick; // subscribe the tick even.. - TimerKeyDown.Enabled = true; // enabled the timer.. + /// + /// Adds a given keyboard combination for the class to listen for. To make the keyboard combination to consist of many keys, use the method multiple times. + /// + /// A class instance describing a single key press. At least one modifier key must be down. + /// A name for a key combination. + /// True if the key combination was successfully added (no empty name and at least one modifier key down). + public bool AddKeyChord(KeyData keyData, string name) + { + // the name cannot be empty.. + if (name == string.Empty) + { + return false; } - /// - /// A field to hold the instance of which key board combinations to listen to. - /// - private readonly Form form; - - /// - /// Adds a given keyboard combination for the class to listen for. To make the keyboard combination to consist of many keys, use the method multiple times. - /// - /// A class instance describing a single key press. At least one modifier key must be down. - /// A name for a key combination. - /// True if the key combination was successfully added (no empty name and at least one modifier key down). - public bool AddKeyChord(KeyData keyData, string name) + // one modifier key must be down.. + if (!keyData.Alt && !keyData.Ctrl && !keyData.Shift) { - // the name cannot be empty.. - if (name == string.Empty) - { - return false; - } + return false; + } - // one modifier key must be down.. - if (!keyData.Alt && !keyData.Ctrl && !keyData.Shift) - { - return false; - } + // add the given chord to the key combination list.. + var location = KeyList.Count(f => f.name == name); - // add the given chord to the key combination list.. - var location = KeyList.Count(f => f.name == name); + KeyList.Add((keyData.Alt, keyData.Ctrl, keyData.Shift, keyData.Key, name, location)); - KeyList.Add((keyData.Alt, keyData.Ctrl, keyData.Shift, keyData.Key, name, location)); + // success.. + return true; + } - // success.. - return true; + /// + /// Adds a given keyboard combination for the class to listen for. + /// A name for a key combination. + /// An array of class instances describing a keyboard combination. At least one modifier key must be down. + /// + /// True if the key combination was successfully added (no empty name and at least one modifier key down). + public bool AddKeyCombination(string name, params KeyData[] keyDataList) + { + // the name cannot be empty.. + if (name == string.Empty) + { + return false; } - /// - /// Adds a given keyboard combination for the class to listen for. - /// A name for a key combination. - /// An array of class instances describing a keyboard combination. At least one modifier key must be down. - /// - /// True if the key combination was successfully added (no empty name and at least one modifier key down). - public bool AddKeyCombination(string name, params KeyData[] keyDataList) + // one modifier key must be down.. + foreach (var keyData in keyDataList) { - // the name cannot be empty.. - if (name == string.Empty) + if (!keyData.Alt && !keyData.Ctrl && !keyData.Shift) { return false; } - - // one modifier key must be down.. - foreach (var keyData in keyDataList) - { - if (!keyData.Alt && !keyData.Ctrl && !keyData.Shift) - { - return false; - } - } - - // add the chords to the key combination list.. - foreach (var keyData in keyDataList) - { - AddKeyChord(keyData, name); - } - - // success.. - return true; } - /// - /// Removes a key combination from the class. - /// - /// The name of the key combination to remove. - /// True if the key combination was successfully removed (existed); otherwise false. - public bool ClearKeyCombination(string name) + // add the chords to the key combination list.. + foreach (var keyData in keyDataList) { - return KeyList.RemoveAll(f => f.name == name) > 0; + AddKeyChord(keyData, name); } - /// - /// Gets or sets the internal key combination list the class should listen for. - /// - private List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int location)> - KeyList { get; } = - new List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int location)>(); + // success.. + return true; + } + + /// + /// Removes a key combination from the class. + /// + /// The name of the key combination to remove. + /// True if the key combination was successfully removed (existed); otherwise false. + public bool ClearKeyCombination(string name) + { + return KeyList.RemoveAll(f => f.name == name) > 0; + } - internal List KeysCollected { get; set; } = new List(); + /// + /// Gets or sets the internal key combination list the class should listen for. + /// + private List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int location)> + KeyList { get; } = + new List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int location)>(); - /// - /// Gets or set a value of how many milliseconds has passed within the timers tick event running at 10 millisecond interval. - /// - private int MillisecondsPassed { get; set; } + internal List KeysCollected { get; set; } = new List(); - /// - /// Gets or sets the reset amount in milliseconds to reset the keyboard listening. - /// - private int ResetTimeMilliseconds { get; } + /// + /// Gets or set a value of how many milliseconds has passed within the timers tick event running at 10 millisecond interval. + /// + private int MillisecondsPassed { get; set; } - private void TimerKeyDown_Tick(object sender, EventArgs e) - { - // disable the timer.. - TimerKeyDown.Enabled = false; + /// + /// Gets or sets the reset amount in milliseconds to reset the keyboard listening. + /// + private int ResetTimeMilliseconds { get; } - // increase the milliseconds passed count by the timer's interval.. - MillisecondsPassed += 10; + private void TimerKeyDown_Tick(object sender, EventArgs e) + { + // disable the timer.. + TimerKeyDown.Enabled = false; - // if the interval exceeds the given maximum value.. - if (MillisecondsPassed > ResetTimeMilliseconds) - { - // ..reset the collected key chords.. - MillisecondsPassed = 0; - keyLocation = 0; - KeysCollected.Clear(); - } + // increase the milliseconds passed count by the timer's interval.. + MillisecondsPassed += 10; - // enable the timer.. - TimerKeyDown.Enabled = true; + // if the interval exceeds the given maximum value.. + if (MillisecondsPassed > ResetTimeMilliseconds) + { + // ..reset the collected key chords.. + MillisecondsPassed = 0; + keyLocation = 0; + KeysCollected.Clear(); } + // enable the timer.. + TimerKeyDown.Enabled = true; + } + - /// - /// A delegate for the event. - /// - /// The sender. - /// The instance containing the event data. - public delegate void OnKeyCombination(object sender, KeyCombinationInformationEventArgs e); - - /// - /// Occurs when the program detects - /// - public event OnKeyCombination KeyCombination; - - /// - /// A timer to detect a keyboard event expiration. - /// - internal Timer TimerKeyDown { get; set; } - - /// - /// A field to hold the keyboard location. - /// - private int keyLocation; - - /// - /// Gets or set a list of keyboard combination names matching the current input. - /// - private List CurrentCombinationNames { get; set; } - - /// - /// Checks if a given enumeration is in the list of key combinations at the current location. - /// - /// A Keys enumeration value. - /// True if a keyboard combination exists in the current chord list; otherwise false. - private bool IsSomeChordDown(Keys keys) - { - // find all with specific location.. - var keyList = KeyList.Where(f => f.location == keyLocation); + /// + /// A delegate for the event. + /// + /// The sender. + /// The instance containing the event data. + public delegate void OnKeyCombination(object sender, KeyCombinationInformationEventArgs e); - // loop through the results.. - foreach (var keyEntry in keyList) + /// + /// Occurs when the program detects + /// + public event OnKeyCombination KeyCombination; + + /// + /// A timer to detect a keyboard event expiration. + /// + internal Timer TimerKeyDown { get; set; } + + /// + /// A field to hold the keyboard location. + /// + private int keyLocation; + + /// + /// Gets or set a list of keyboard combination names matching the current input. + /// + private List CurrentCombinationNames { get; set; } + + /// + /// Checks if a given enumeration is in the list of key combinations at the current location. + /// + /// A Keys enumeration value. + /// True if a keyboard combination exists in the current chord list; otherwise false. + private bool IsSomeChordDown(Keys keys) + { + // find all with specific location.. + var keyList = KeyList.Where(f => f.location == keyLocation); + + // loop through the results.. + foreach (var keyEntry in keyList) + { + // check if the result contains the key.. + if (keyEntry.keys == keys) { - // check if the result contains the key.. - if (keyEntry.keys == keys) - { - // ..if yes then return true.. - return true; - } + // ..if yes then return true.. + return true; } - - // no match was found.. - return false; } - /// - /// Handles the KeyDown event of the Form control. - /// - /// The source of the event. - /// The instance containing the event data. - private void Form_KeyDown(object sender, KeyEventArgs e) + // no match was found.. + return false; + } + + /// + /// Handles the KeyDown event of the Form control. + /// + /// The source of the event. + /// The instance containing the event data. + private void Form_KeyDown(object sender, KeyEventArgs e) + { + // reset the time passed counter on any keyboard event.. + MillisecondsPassed = 0; + + // at least one modifier key must be down and the key code must match a specified + // key with the specified location on the key chord list.. + if ((e.Alt || e.Control || e.Shift) && IsSomeChordDown(e.KeyCode)) { - // reset the time passed counter on any keyboard event.. - MillisecondsPassed = 0; + // get the possible key combinations.. + var combinations = KeyList.Where(f => + f.location == keyLocation && f.modifierAlt == e.Alt && f.modifierCtrl == e.Control && + f.modifierShift == e.Shift && (keyLocation == 0 || CurrentCombinationNames.Contains(f.name))).ToList(); - // at least one modifier key must be down and the key code must match a specified - // key with the specified location on the key chord list.. - if ((e.Alt || e.Control || e.Shift) && IsSomeChordDown(e.KeyCode)) + // get the name of the possible key combinations.. + var names = combinations.Select(f => f.name); + + // set the CurrentCombinationNames property value with the combinations as a list.. + CurrentCombinationNames = new List(names.ToList()); + + // if matching combination(s) where found.. + if (combinations.Count > 0) { - // get the possible key combinations.. - var combinations = KeyList.Where(f => - f.location == keyLocation && f.modifierAlt == e.Alt && f.modifierCtrl == e.Control && - f.modifierShift == e.Shift && (keyLocation == 0 || CurrentCombinationNames.Contains(f.name))).ToList(); + // ..add the collected key combination to the internal list.. + KeysCollected.Add(new KeyData { Alt = e.Alt, Ctrl = e.Control, Shift = e.Shift, Key = e.KeyCode, }); - // get the name of the possible key combinations.. - var names = combinations.Select(f => f.name); + // suppress the key press.. + e.SuppressKeyPress = true; - // set the CurrentCombinationNames property value with the combinations as a list.. - CurrentCombinationNames = new List(names.ToList()); + // detect if the collected key combination matches + // any specified combinations within this class instance.. + string name = MatchCombination(); - // if matching combination(s) where found.. - if (combinations.Count > 0) + // ..a non-null value means yes.. + if (name != null) { - // ..add the collected key combination to the internal list.. - KeysCollected.Add(new KeyData { Alt = e.Alt, Ctrl = e.Control, Shift = e.Shift, Key = e.KeyCode}); - - // suppress the key press.. - e.SuppressKeyPress = true; - - // detect if the collected key combination matches - // any specified combinations within this class instance.. - string name = MatchCombination(); - - // ..a non-null value means yes.. - if (name != null) - { - // ..so clear the collected keys and reset the chord location.. - keyLocation = 0; - KeysCollected.Clear(); - - // raise the event with a combination name if subscribed.. - KeyCombination?.Invoke(form, new KeyCombinationInformationEventArgs { Name = name}); - } - else - { - // the combination wasn't found yet, but the chord was collected, - // increase the location.. - keyLocation++; - } + // ..so clear the collected keys and reset the chord location.. + keyLocation = 0; + KeysCollected.Clear(); + + // raise the event with a combination name if subscribed.. + KeyCombination?.Invoke(form, new KeyCombinationInformationEventArgs { Name = name, }); } - // ..nothing valid was found.. else { - // ..so do reset the collected key combination list and the chord location.. - keyLocation = 0; - KeysCollected.Clear(); + // the combination wasn't found yet, but the chord was collected, + // increase the location.. + keyLocation++; } } - } - - /// - /// Gets a name of a key combination if it should match a user user input key combination. - /// - /// A name of the match for a key combination if found; otherwise null. - private string MatchCombination() - { - // initialize a new tuple containing possible valid combinations.. - List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int location)> - combinations = - new List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int - location)>(); - - // get a list of invalid names; they have more chords than the currently - // collected key combination list within the class.. - List invalidNames = - KeyList.Where(f => f.location > keyLocation).Select(f => f.name).Distinct().ToList(); - - for (int i = 0; i < keyLocation; i++) + // ..nothing valid was found.. + else { - // if the collected chord index is larger than the currently - // collected amount of key combinations, consider it as invalid.. - if (combinations.Exists(f => f.location > keyLocation)) - { - // ..so do continue the loop.. - continue; - } - - // add to the list of valid key combinations in case the - // location and the chord matches the specified keyboard - // combinations within the class.. - combinations.AddRange( - KeyList.Where(f => - f.location == i && f.modifierAlt == KeysCollected[i].Alt && - f.modifierCtrl == KeysCollected[i].Ctrl && f.modifierShift == KeysCollected[i].Shift && - f.keys == KeysCollected[i].Key).ToList()); + // ..so do reset the collected key combination list and the chord location.. + keyLocation = 0; + KeysCollected.Clear(); } + } + } - // select the collected combination names.. - var combination = combinations.Select(f => f.name).Distinct().ToList(); - - // ..if a the name count is one.. - if (combination.Count == 1) + /// + /// Gets a name of a key combination if it should match a user user input key combination. + /// + /// A name of the match for a key combination if found; otherwise null. + private string MatchCombination() + { + // initialize a new tuple containing possible valid combinations.. + List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int location)> + combinations = + new List<(bool modifierAlt, bool modifierCtrl, bool modifierShift, Keys keys, string name, int + location)>(); + + // get a list of invalid names; they have more chords than the currently + // collected key combination list within the class.. + List invalidNames = + KeyList.Where(f => f.location > keyLocation).Select(f => f.name).Distinct().ToList(); + + for (int i = 0; i < keyLocation; i++) + { + // if the collected chord index is larger than the currently + // collected amount of key combinations, consider it as invalid.. + if (combinations.Exists(f => f.location > keyLocation)) { - // ..and the is in the collection of invalid combinations.. - if (invalidNames.Contains(combination.FirstOrDefault())) - { - // ..return null to indicate failure.. - return null; - } - - // success.. - return combination.FirstOrDefault(); + // ..so do continue the loop.. + continue; } - // somewhere something went wrong, so return null.. - return null; + // add to the list of valid key combinations in case the + // location and the chord matches the specified keyboard + // combinations within the class.. + combinations.AddRange( + KeyList.Where(f => + f.location == i && f.modifierAlt == KeysCollected[i].Alt && + f.modifierCtrl == KeysCollected[i].Ctrl && f.modifierShift == KeysCollected[i].Shift && + f.keys == KeysCollected[i].Key).ToList()); } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + // select the collected combination names.. + var combination = combinations.Select(f => f.name).Distinct().ToList(); + + // ..if a the name count is one.. + if (combination.Count == 1) { - using (TimerKeyDown) + // ..and the is in the collection of invalid combinations.. + if (invalidNames.Contains(combination.FirstOrDefault())) { - TimerKeyDown.Enabled = false; - TimerKeyDown.Tick -= TimerKeyDown_Tick; + // ..return null to indicate failure.. + return null; } - form.KeyDown -= Form_KeyDown; // unsubscribe the keydown event.. + + // success.. + return combination.FirstOrDefault(); } + + // somewhere something went wrong, so return null.. + return null; } /// - /// A class which instance is passed via the event. + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// - public class KeyCombinationInformationEventArgs: EventArgs + public void Dispose() { - /// - /// Gets or sets the name of the keyboard combination which occurred. - /// - public string Name { get; set; } + using (TimerKeyDown) + { + TimerKeyDown.Enabled = false; + TimerKeyDown.Tick -= TimerKeyDown_Tick; + } + form.KeyDown -= Form_KeyDown; // unsubscribe the keydown event.. } +} +/// +/// A class which instance is passed via the event. +/// +public class KeyCombinationInformationEventArgs: EventArgs +{ /// - /// A class to hold a single key information. + /// Gets or sets the name of the keyboard combination which occurred. /// - public class KeyData - { - /// - /// Gets or set the value whether the Alt modifier key is down. - /// - internal bool Alt { get; set; } - - /// - /// Gets or set the value whether the Ctrl modifier key is down. - /// - internal bool Ctrl { get; set; } - - /// - /// Gets or set the value whether the Shift modifier key is down. - /// - internal bool Shift { get; set; } - - /// - /// Gets or set the value of a key which is down. - /// - internal Keys Key { get; set; } - } + public string Name { get; set; } } + +/// +/// A class to hold a single key information. +/// +public class KeyData +{ + /// + /// Gets or set the value whether the Alt modifier key is down. + /// + internal bool Alt { get; set; } + + /// + /// Gets or set the value whether the Ctrl modifier key is down. + /// + internal bool Ctrl { get; set; } + + /// + /// Gets or set the value whether the Shift modifier key is down. + /// + internal bool Shift { get; set; } + + /// + /// Gets or set the value of a key which is down. + /// + internal Keys Key { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/LinesAndBinary/FileLineType.cs b/ScriptNotepad/UtilityClasses/LinesAndBinary/FileLineType.cs index b7802a10..44105e52 100644 --- a/ScriptNotepad/UtilityClasses/LinesAndBinary/FileLineType.cs +++ b/ScriptNotepad/UtilityClasses/LinesAndBinary/FileLineType.cs @@ -29,359 +29,359 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // ReSharper disable InconsistentNaming // ReSharper disable CommentTypo -namespace ScriptNotepad.UtilityClasses.LinesAndBinary +namespace ScriptNotepad.UtilityClasses.LinesAndBinary; + +/// +/// An enumeration describing common and less common new line character sequences of a text file. +/// (C): https://en.wikipedia.org/wiki/Newline +/// +[Flags] +public enum FileLineTypes { /// - /// An enumeration describing common and less common new line character sequences of a text file. - /// (C): https://en.wikipedia.org/wiki/Newline + /// Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems. /// - [Flags] - public enum FileLineTypes - { - /// - /// Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems. - /// - CRLF = 1, // \r\n, 0x0D/U0x000D + 0x0A/U0x000A, 13|10 - - /// - /// Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others. - /// - LF = 2, // \n, 0x0A/U0x000A, 10 - - /// - /// Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9. - /// - CR = 4, // \r, 0x0D/U0x000D, 13 - - /// - /// QNX pre-POSIX implementation (version < 4). - /// - RS = 8, // 0x1E, 30 - - /// - /// Acorn BBC and RISC OS spooled text output. - /// - LFCR = 16, // \n\r, 0x0A/U0x000A + 0x0D/U0x000D, 10|13 - - /// - /// IBM mainframe systems, including z/OS (OS/390) and i5/OS (OS/400). - /// - NL = 32, // \025, 0x15, 21 - - /// - /// Atari 8-bit machines. - /// - ATASCII = 64, // \9B, 155, - - /// - /// ZX80 and ZX81 (Home computers from Sinclair Research Ltd). - /// - NEWLINE = 128, // 0x76, 118 - - /// - /// An unknown line ending or nothing. - /// - Unknown = 256, - - /// - /// A value indicating that mixed line endings occur in a file. - /// - Mixed = 512, - - /// - /// Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems (Unicode). - /// - UCRLF = 1024, // \r\n, 0x0D/U0x000D + 0x0A/U0x000A, 13|10 - - /// - /// Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others (Unicode). - /// - ULF = 2048, // \n, 0x0A/U0x000A, 10 - - /// - /// Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9 (Unicode). - /// - UCR = 4096, // \r, 0x0D/U0x000D, 13 - - /// - /// Acorn BBC and RISC OS spooled text output (Unicode). - /// - ULFCR = 8192, // \n\r, 0x0A/U0x000A + 0x0D/U0x000D, 10|13 - } + CRLF = 1, // \r\n, 0x0D/U0x000D + 0x0A/U0x000A, 13|10 + + /// + /// Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others. + /// + LF = 2, // \n, 0x0A/U0x000A, 10 + + /// + /// Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9. + /// + CR = 4, // \r, 0x0D/U0x000D, 13 + + /// + /// QNX pre-POSIX implementation (version < 4). + /// + RS = 8, // 0x1E, 30 + + /// + /// Acorn BBC and RISC OS spooled text output. + /// + LFCR = 16, // \n\r, 0x0A/U0x000A + 0x0D/U0x000D, 10|13 + + /// + /// IBM mainframe systems, including z/OS (OS/390) and i5/OS (OS/400). + /// + NL = 32, // \025, 0x15, 21 + + /// + /// Atari 8-bit machines. + /// + ATASCII = 64, // \9B, 155, + + /// + /// ZX80 and ZX81 (Home computers from Sinclair Research Ltd). + /// + NEWLINE = 128, // 0x76, 118 + + /// + /// An unknown line ending or nothing. + /// + Unknown = 256, + + /// + /// A value indicating that mixed line endings occur in a file. + /// + Mixed = 512, + + /// + /// Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems (Unicode). + /// + UCRLF = 1024, // \r\n, 0x0D/U0x000D + 0x0A/U0x000A, 13|10 + + /// + /// Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others (Unicode). + /// + ULF = 2048, // \n, 0x0A/U0x000A, 10 + + /// + /// Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9 (Unicode). + /// + UCR = 4096, // \r, 0x0D/U0x000D, 13 + + /// + /// Acorn BBC and RISC OS spooled text output (Unicode). + /// + ULFCR = 8192, // \n\r, 0x0A/U0x000A + 0x0D/U0x000D, 10|13 +} + +/// +/// A class for detecting a new line type of a text file. +/// +public static class FileLineType +{ + #region LineEndingLocalizeableDescriptions + /// + /// A short description for the line ending for: Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems. + /// + public static string CRLF_Description { get; set; } = "CR+LF"; + + /// + /// A short description for the line ending for: Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others. + /// + public static string LF_Description { get; set; } = "LF"; + + /// + /// A short description for the line ending for: Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9. + /// + public static string CR_Description { get; set; } = "CR"; + + /// + /// A short description for the line ending for: QNX pre-POSIX implementation (version < 4). + /// + public static string RS_Description { get; set; } = "RS"; + + /// + /// A short description for the line ending for: Acorn BBC and RISC OS spooled text output. + /// + public static string LFCR_Description { get; set; } = "LF+CR"; + + /// + /// A short description for the line ending for: IBM mainframe systems, including z/OS (OS/390) and i5/OS (OS/400). + /// + public static string NL_Description { get; set; } = "NL"; + + /// + /// A short description for the line ending for: Atari 8-bit machines. + /// + public static string ATASCII_Description { get; set; } = "ATASCII"; + + /// + /// A short description for the line ending for: ZX80 and ZX81 (Home computers from Sinclair Research Ltd). + /// + public static string NEWLINE_Description { get; set; } = "NEWLINE"; + + /// + /// A short description for the line ending for: An unknown line ending or nothing. + /// + public static string Unknown_Description { get; set; } = "Unknown"; + + /// + /// A short description for mixed line endings. + /// + public static string Mixed_Description { get; set; } = "Mixed"; + + /// + /// A short description for the line ending for: Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems (Unicode). + /// + public static string UCRLF_Description { get; set; } = "Unicode CR+LF"; + + /// + /// A short description for the line ending for: Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others (Unicode). + /// + public static string ULF_Description { get; set; } = "Unicode LF"; + + /// + /// A short description for the line ending for: Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9 (Unicode). + /// + public static string UCR_Description { get; set; } = "Unicode CR"; /// - /// A class for detecting a new line type of a text file. + /// A short description for the line ending for: Acorn BBC and RISC OS spooled text output (Unicode). /// - public static class FileLineType + public static string ULFCR_Description { get; set; } = "Unicode LF+CR"; + #endregion + + #region FileLineEndingsAsString + /// + /// Gets the file line ending as a string representation. + /// + /// The enumeration value. + /// A string containing the line ending characters. + public static string GetFileLineEndingString(FileLineTypes fileLineTypes) { - #region LineEndingLocalizeableDescriptions - /// - /// A short description for the line ending for: Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems. - /// - public static string CRLF_Description { get; set; } = "CR+LF"; - - /// - /// A short description for the line ending for: Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others. - /// - public static string LF_Description { get; set; } = "LF"; - - /// - /// A short description for the line ending for: Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9. - /// - public static string CR_Description { get; set; } = "CR"; - - /// - /// A short description for the line ending for: QNX pre-POSIX implementation (version < 4). - /// - public static string RS_Description { get; set; } = "RS"; - - /// - /// A short description for the line ending for: Acorn BBC and RISC OS spooled text output. - /// - public static string LFCR_Description { get; set; } = "LF+CR"; - - /// - /// A short description for the line ending for: IBM mainframe systems, including z/OS (OS/390) and i5/OS (OS/400). - /// - public static string NL_Description { get; set; } = "NL"; - - /// - /// A short description for the line ending for: Atari 8-bit machines. - /// - public static string ATASCII_Description { get; set; } = "ATASCII"; - - /// - /// A short description for the line ending for: ZX80 and ZX81 (Home computers from Sinclair Research Ltd). - /// - public static string NEWLINE_Description { get; set; } = "NEWLINE"; - - /// - /// A short description for the line ending for: An unknown line ending or nothing. - /// - public static string Unknown_Description { get; set; } = "Unknown"; - - /// - /// A short description for mixed line endings. - /// - public static string Mixed_Description { get; set; } = "Mixed"; - - /// - /// A short description for the line ending for: Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems (Unicode). - /// - public static string UCRLF_Description { get; set; } = "Unicode CR+LF"; - - /// - /// A short description for the line ending for: Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others (Unicode). - /// - public static string ULF_Description { get; set; } = "Unicode LF"; - - /// - /// A short description for the line ending for: Commodore 8-bit machines (C64, C128), Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS, MIT Lisp Machine and OS-9 (Unicode). - /// - public static string UCR_Description { get; set; } = "Unicode CR"; - - /// - /// A short description for the line ending for: Acorn BBC and RISC OS spooled text output (Unicode). - /// - public static string ULFCR_Description { get; set; } = "Unicode LF+CR"; - #endregion - - #region FileLineEndingsAsString - /// - /// Gets the file line ending as a string representation. - /// - /// The enumeration value. - /// A string containing the line ending characters. - public static string GetFileLineEndingString(FileLineTypes fileLineTypes) + // a simple switch..case structure.. + switch(fileLineTypes) { - // a simple switch..case structure.. - switch(fileLineTypes) - { - case FileLineTypes.CRLF: - return "\r\n"; + case FileLineTypes.CRLF: + return "\r\n"; - case FileLineTypes.LF: - return "\n"; + case FileLineTypes.LF: + return "\n"; - case FileLineTypes.CR: - return "\r"; + case FileLineTypes.CR: + return "\r"; - case FileLineTypes.RS: - return ((char) 0x1E).ToString(); + case FileLineTypes.RS: + return ((char) 0x1E).ToString(); - case FileLineTypes.LFCR: - return "\n\r"; + case FileLineTypes.LFCR: + return "\n\r"; - case FileLineTypes.NL: - return ((char) 0x15).ToString(); + case FileLineTypes.NL: + return ((char) 0x15).ToString(); - case FileLineTypes.ATASCII: - return ((char) 155).ToString(); + case FileLineTypes.ATASCII: + return ((char) 155).ToString(); - case FileLineTypes.NEWLINE: - return ((char) 0x76).ToString(); + case FileLineTypes.NEWLINE: + return ((char) 0x76).ToString(); - case FileLineTypes.Unknown: - return Environment.NewLine; + case FileLineTypes.Unknown: + return Environment.NewLine; - case FileLineTypes.Mixed: - return Environment.NewLine; + case FileLineTypes.Mixed: + return Environment.NewLine; - case FileLineTypes.UCRLF: - return "\r\n"; + case FileLineTypes.UCRLF: + return "\r\n"; - case FileLineTypes.ULF: - return "\n"; + case FileLineTypes.ULF: + return "\n"; - case FileLineTypes.UCR: - return "\r"; + case FileLineTypes.UCR: + return "\r"; - case FileLineTypes.ULFCR: - return "\n\r"; + case FileLineTypes.ULFCR: + return "\n\r"; - default: return Environment.NewLine; - } + default: return Environment.NewLine; } - #endregion - - #region EnumerationDescriptions - /// - /// Sets a description for a given enumeration. This method is for localization purposes. - /// - /// A value to set a description for. - /// The description to set for a value. - /// True if the description was successfully set; otherwise false. - public static bool SetLineEndingDescriptionByEnumeration(FileLineTypes fileLineTypes, string description) + } + #endregion + + #region EnumerationDescriptions + /// + /// Sets a description for a given enumeration. This method is for localization purposes. + /// + /// A value to set a description for. + /// The description to set for a value. + /// True if the description was successfully set; otherwise false. + public static bool SetLineEndingDescriptionByEnumeration(FileLineTypes fileLineTypes, string description) + { + // a simple switch..case structure.. + switch(fileLineTypes) { - // a simple switch..case structure.. - switch(fileLineTypes) - { - case FileLineTypes.CRLF: - CRLF_Description = description; return true; + case FileLineTypes.CRLF: + CRLF_Description = description; return true; - case FileLineTypes.LF: - LF_Description = description; return true; + case FileLineTypes.LF: + LF_Description = description; return true; - case FileLineTypes.CR: - CR_Description = description; return true; + case FileLineTypes.CR: + CR_Description = description; return true; - case FileLineTypes.RS: - RS_Description = description; return true; + case FileLineTypes.RS: + RS_Description = description; return true; - case FileLineTypes.LFCR: - LFCR_Description = description; return true; + case FileLineTypes.LFCR: + LFCR_Description = description; return true; - case FileLineTypes.NL: - NL_Description = description; return true; + case FileLineTypes.NL: + NL_Description = description; return true; - case FileLineTypes.ATASCII: - ATASCII_Description = description; return true; + case FileLineTypes.ATASCII: + ATASCII_Description = description; return true; - case FileLineTypes.NEWLINE: - NEWLINE_Description = description; return true; + case FileLineTypes.NEWLINE: + NEWLINE_Description = description; return true; - case FileLineTypes.Unknown: - Unknown_Description = description; return true; + case FileLineTypes.Unknown: + Unknown_Description = description; return true; - case FileLineTypes.Mixed: - Mixed_Description = description; return true; + case FileLineTypes.Mixed: + Mixed_Description = description; return true; - case FileLineTypes.UCRLF: - UCRLF_Description = description; return true; + case FileLineTypes.UCRLF: + UCRLF_Description = description; return true; - case FileLineTypes.ULF: - ULF_Description = description; return true; + case FileLineTypes.ULF: + ULF_Description = description; return true; - case FileLineTypes.UCR: - UCR_Description = description; return true; + case FileLineTypes.UCR: + UCR_Description = description; return true; - case FileLineTypes.ULFCR: - ULFCR_Description = description; return true; + case FileLineTypes.ULFCR: + ULFCR_Description = description; return true; - default: return false; - } + default: return false; } + } - /// - /// Gets the description of the FileLineTypes enumeration value using either custom description or the name of the enumeration value. - /// - /// A FileLineTypes enumeration value to get the description for. - /// A flag indicating if name of the enumeration value should be returned. - /// A description for the given enumeration value. - public static string GetLineEndingDescriptionByEnumeration(FileLineTypes fileLineTypes, bool useEnumName) + /// + /// Gets the description of the FileLineTypes enumeration value using either custom description or the name of the enumeration value. + /// + /// A FileLineTypes enumeration value to get the description for. + /// A flag indicating if name of the enumeration value should be returned. + /// A description for the given enumeration value. + public static string GetLineEndingDescriptionByEnumeration(FileLineTypes fileLineTypes, bool useEnumName) + { + // the name of the enumeration was requested.. + if (useEnumName) { - // the name of the enumeration was requested.. - if (useEnumName) - { - // ..so do return it.. - return Enum.GetName(typeof(FileLineTypes), fileLineTypes); - } + // ..so do return it.. + return Enum.GetName(typeof(FileLineTypes), fileLineTypes); + } - // a simple switch..case structure.. - switch (fileLineTypes) - { - case FileLineTypes.CRLF: - return CRLF_Description; + // a simple switch..case structure.. + switch (fileLineTypes) + { + case FileLineTypes.CRLF: + return CRLF_Description; - case FileLineTypes.LF: - return LF_Description; + case FileLineTypes.LF: + return LF_Description; - case FileLineTypes.CR: - return CR_Description; + case FileLineTypes.CR: + return CR_Description; - case FileLineTypes.RS: - return RS_Description; + case FileLineTypes.RS: + return RS_Description; - case FileLineTypes.LFCR: - return LFCR_Description; + case FileLineTypes.LFCR: + return LFCR_Description; - case FileLineTypes.NL: - return NL_Description; + case FileLineTypes.NL: + return NL_Description; - case FileLineTypes.ATASCII: - return ATASCII_Description; + case FileLineTypes.ATASCII: + return ATASCII_Description; - case FileLineTypes.NEWLINE: - return NEWLINE_Description; + case FileLineTypes.NEWLINE: + return NEWLINE_Description; - case FileLineTypes.Unknown: - return Unknown_Description; + case FileLineTypes.Unknown: + return Unknown_Description; - case FileLineTypes.Mixed: - return Mixed_Description; + case FileLineTypes.Mixed: + return Mixed_Description; - case FileLineTypes.UCRLF: - return UCRLF_Description; + case FileLineTypes.UCRLF: + return UCRLF_Description; - case FileLineTypes.ULF: - return ULF_Description; + case FileLineTypes.ULF: + return ULF_Description; - case FileLineTypes.UCR: - return UCR_Description; + case FileLineTypes.UCR: + return UCR_Description; - case FileLineTypes.ULFCR: - return ULFCR_Description; + case FileLineTypes.ULFCR: + return ULFCR_Description; - default: return Unknown_Description; - } + default: return Unknown_Description; } - #endregion - - /// - /// A flag indicating whether the GetFileLineTypes method should return a name of the enumeration value or a custom description defined by a property. - /// - public static bool UseEnumNames { get; set; } = false; - - /// - /// Gets the file line types of a given memory stream. - /// - /// The memory stream to be used to check for the line endings. - /// An flag indicating if the less common line endings should also be checked. - /// A collection of line ending key value pairs with their enumeration values and their names. - public static IEnumerable> GetFileLineTypes(MemoryStream stream, bool useLessCommon) - { - // construct an enumeration of the "common" line ending enumerations.. - FileLineTypes fileLineTypes = + } + #endregion + + /// + /// A flag indicating whether the GetFileLineTypes method should return a name of the enumeration value or a custom description defined by a property. + /// + public static bool UseEnumNames { get; set; } = false; + + /// + /// Gets the file line types of a given memory stream. + /// + /// The memory stream to be used to check for the line endings. + /// An flag indicating if the less common line endings should also be checked. + /// A collection of line ending key value pairs with their enumeration values and their names. + public static IEnumerable> GetFileLineTypes(MemoryStream stream, bool useLessCommon) + { + // construct an enumeration of the "common" line ending enumerations.. + FileLineTypes fileLineTypes = FileLineTypes.CR | FileLineTypes.CRLF | FileLineTypes.LF | @@ -391,27 +391,27 @@ public static IEnumerable> GetFileLineTypes( FileLineTypes.ULF | FileLineTypes.ULFCR; - // if the less common line endings are required.. - if (useLessCommon) - { - // add them to the enumeration.. - fileLineTypes |= FileLineTypes.NEWLINE | FileLineTypes.NL | FileLineTypes.RS | FileLineTypes.ATASCII; - } - - // call the suitable overload.. - return GetFileLineTypes(stream, fileLineTypes); + // if the less common line endings are required.. + if (useLessCommon) + { + // add them to the enumeration.. + fileLineTypes |= FileLineTypes.NEWLINE | FileLineTypes.NL | FileLineTypes.RS | FileLineTypes.ATASCII; } - /// - /// Gets the file line types of a given memory stream. - /// - /// The byte array to be used to check for the line endings. - /// An flag indicating if the less common line endings should also be checked. - /// A collection of line ending key value pairs with their enumeration values and their names. - public static IEnumerable> GetFileLineTypes(byte[] buffer, bool useLessCommon) - { - // construct an enumeration of the "common" line ending enumerations.. - FileLineTypes fileLineTypes = // the default set.. + // call the suitable overload.. + return GetFileLineTypes(stream, fileLineTypes); + } + + /// + /// Gets the file line types of a given memory stream. + /// + /// The byte array to be used to check for the line endings. + /// An flag indicating if the less common line endings should also be checked. + /// A collection of line ending key value pairs with their enumeration values and their names. + public static IEnumerable> GetFileLineTypes(byte[] buffer, bool useLessCommon) + { + // construct an enumeration of the "common" line ending enumerations.. + FileLineTypes fileLineTypes = // the default set.. FileLineTypes.CR | FileLineTypes.CRLF | FileLineTypes.LF | @@ -421,48 +421,48 @@ public static IEnumerable> GetFileLineTypes( FileLineTypes.ULF | FileLineTypes.ULFCR; - // if the less common line endings are required.. - if (useLessCommon) - { - // add them to the enumeration.. - fileLineTypes |= FileLineTypes.NEWLINE | FileLineTypes.NL | FileLineTypes.RS | FileLineTypes.ATASCII; - } - - // call the suitable overload.. - return GetFileLineTypes(buffer, fileLineTypes); + // if the less common line endings are required.. + if (useLessCommon) + { + // add them to the enumeration.. + fileLineTypes |= FileLineTypes.NEWLINE | FileLineTypes.NL | FileLineTypes.RS | FileLineTypes.ATASCII; } + // call the suitable overload.. + return GetFileLineTypes(buffer, fileLineTypes); + } - /// - /// Gets the file line types of a text and a given encoding. - /// - /// The text of which contents to check for the line endings. - /// The encoding of the text. - /// The types of line endings wanted to be included in the search. - /// A collection of line ending key value pairs with their enumeration values and their names. - public static IEnumerable> GetFileLineTypes( - string contents, System.Text.Encoding encoding, - FileLineTypes fileLineTypes = // the default set.. - FileLineTypes.CR | - FileLineTypes.CRLF | - FileLineTypes.LF | - FileLineTypes.LFCR | - FileLineTypes.UCR | - FileLineTypes.UCRLF | - FileLineTypes.ULF | - FileLineTypes.ULFCR) - { - return GetFileLineTypes(encoding.GetBytes(contents)); - } - /// - /// Gets the file line types of a given byte array. - /// - /// The byte array to be used to check for the line endings. - /// The types of line endings wanted to be included in the search. - /// A collection of line ending key value pairs with their enumeration values and their names. - public static IEnumerable> GetFileLineTypes(byte[] buffer, - FileLineTypes fileLineTypes = // the default set.. + /// + /// Gets the file line types of a text and a given encoding. + /// + /// The text of which contents to check for the line endings. + /// The encoding of the text. + /// The types of line endings wanted to be included in the search. + /// A collection of line ending key value pairs with their enumeration values and their names. + public static IEnumerable> GetFileLineTypes( + string contents, System.Text.Encoding encoding, + FileLineTypes fileLineTypes = // the default set.. + FileLineTypes.CR | + FileLineTypes.CRLF | + FileLineTypes.LF | + FileLineTypes.LFCR | + FileLineTypes.UCR | + FileLineTypes.UCRLF | + FileLineTypes.ULF | + FileLineTypes.ULFCR) + { + return GetFileLineTypes(encoding.GetBytes(contents)); + } + + /// + /// Gets the file line types of a given byte array. + /// + /// The byte array to be used to check for the line endings. + /// The types of line endings wanted to be included in the search. + /// A collection of line ending key value pairs with their enumeration values and their names. + public static IEnumerable> GetFileLineTypes(byte[] buffer, + FileLineTypes fileLineTypes = // the default set.. FileLineTypes.CR | FileLineTypes.CRLF | FileLineTypes.LF | @@ -471,21 +471,21 @@ public static IEnumerable> GetFileLineTypes( FileLineTypes.UCRLF | FileLineTypes.ULF | FileLineTypes.ULFCR) + { + using (MemoryStream memoryStream = buffer == null || buffer.Length == 0 ? new MemoryStream() : new MemoryStream(buffer)) { - using (MemoryStream memoryStream = buffer == null || buffer.Length == 0 ? new MemoryStream() : new MemoryStream(buffer)) - { - return GetFileLineTypes(memoryStream, fileLineTypes); - } + return GetFileLineTypes(memoryStream, fileLineTypes); } + } - /// - /// Gets the file line types of a given memory stream. - /// - /// The memory stream to be used to check for the line endings. - /// The types of line endings wanted to be included in the search. - /// A collection of line ending key value pairs with their enumeration values and their names. - public static IEnumerable> GetFileLineTypes(MemoryStream stream, - FileLineTypes fileLineTypes = // the default set.. + /// + /// Gets the file line types of a given memory stream. + /// + /// The memory stream to be used to check for the line endings. + /// The types of line endings wanted to be included in the search. + /// A collection of line ending key value pairs with their enumeration values and their names. + public static IEnumerable> GetFileLineTypes(MemoryStream stream, + FileLineTypes fileLineTypes = // the default set.. FileLineTypes.CR | FileLineTypes.CRLF | FileLineTypes.LF | @@ -494,385 +494,384 @@ public static IEnumerable> GetFileLineTypes( FileLineTypes.UCRLF | FileLineTypes.ULF | FileLineTypes.ULFCR) - { - // do note that this is the "master" method of the overloads, so the logic is going to be weird.. - List> result = new List>(); + { + // do note that this is the "master" method of the overloads, so the logic is going to be weird.. + List> result = new List>(); - // the contents of the given memory stream is requires as a byte array.. - byte[] contentsBytes = stream.ToArray(); + // the contents of the given memory stream is requires as a byte array.. + byte[] contentsBytes = stream.ToArray(); - // indicators if a negative or positive index for the byte array - // search was given.. - bool eof1, eof2, eof3; + // indicators if a negative or positive index for the byte array + // search was given.. + bool eof1, eof2, eof3; - // initialize the loop variable.. - int i = 0; + // initialize the loop variable.. + int i = 0; - // loop through the bytes in the array.. - while (i < contentsBytes.Length) + // loop through the bytes in the array.. + while (i < contentsBytes.Length) + { + // comparison of CR+LF without Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x0D, 0x0A, }, out eof1)) { - // comparison of CR+LF without Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x0D, 0x0A }, out eof1)) + if (eof1) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } - - i += 2; // increase the loop variable by the amount of bytes used in the comparison.. - - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.CRLF) && fileLineTypes.HasFlag(FileLineTypes.CRLF)) - { - result.Add( - new KeyValuePair(FileLineTypes.CRLF, GetLineEndingDescriptionByEnumeration(FileLineTypes.CRLF, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; } - // comparison of LF+CR without Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x0A, 0x0D }, out eof1)) - { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } - - i += 2; // increase the loop variable by the amount of bytes used in the comparison.. - - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.LFCR) && fileLineTypes.HasFlag(FileLineTypes.LFCR)) - { - result.Add( - new KeyValuePair(FileLineTypes.LFCR, GetLineEndingDescriptionByEnumeration(FileLineTypes.LFCR, UseEnumNames))); - } + i += 2; // increase the loop variable by the amount of bytes used in the comparison.. - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.CRLF) && fileLineTypes.HasFlag(FileLineTypes.CRLF)) + { + result.Add( + new KeyValuePair(FileLineTypes.CRLF, GetLineEndingDescriptionByEnumeration(FileLineTypes.CRLF, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of LF without Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x0A }, out eof1) && - !ContainsBytes(i + 1, contentsBytes, new byte[] { 0x0D }, out eof2) && - !ContainsBytes(i - 1, contentsBytes, new byte[] { 0x0D }, out eof3)) + // comparison of LF+CR without Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x0A, 0x0D, }, out eof1)) + { + if (eof1) // check for an overflow of the byte array.. { - if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. - { - // one or more of the indexes was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } - - i++; // increase the loop variable by the amount of bytes used in the comparison.. + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.LF) && fileLineTypes.HasFlag(FileLineTypes.LF)) - { - result.Add( - new KeyValuePair(FileLineTypes.LF, GetLineEndingDescriptionByEnumeration(FileLineTypes.LF, UseEnumNames))); - } + i += 2; // increase the loop variable by the amount of bytes used in the comparison.. - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.LFCR) && fileLineTypes.HasFlag(FileLineTypes.LFCR)) + { + result.Add( + new KeyValuePair(FileLineTypes.LFCR, GetLineEndingDescriptionByEnumeration(FileLineTypes.LFCR, UseEnumNames))); } - // comparison of CR without Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x0D }, out eof1) && - !ContainsBytes(i + 1, contentsBytes, new byte[] { 0x0A }, out eof2) && - !ContainsBytes(i - 1, contentsBytes, new byte[] { 0x0A }, out eof3)) + continue; // match found so do continue the loop.. + } + + // comparison of LF without Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x0A, }, out eof1) && + !ContainsBytes(i + 1, contentsBytes, new byte[] { 0x0D, }, out eof2) && + !ContainsBytes(i - 1, contentsBytes, new byte[] { 0x0D, }, out eof3)) + { + if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. { - if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. - { - // one or more of the indexes was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // one or more of the indexes was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i++; // increase the loop variable by the amount of bytes used in the comparison.. + i++; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.CR) && fileLineTypes.HasFlag(FileLineTypes.CR)) - { - result.Add( - new KeyValuePair(FileLineTypes.CR, GetLineEndingDescriptionByEnumeration(FileLineTypes.CR, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.LF) && fileLineTypes.HasFlag(FileLineTypes.LF)) + { + result.Add( + new KeyValuePair(FileLineTypes.LF, GetLineEndingDescriptionByEnumeration(FileLineTypes.LF, UseEnumNames))); } - // comparison of CR+LF with Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0D, 0x00, 0x0A }, out eof1)) + continue; // match found so do continue the loop.. + } + + // comparison of CR without Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x0D, }, out eof1) && + !ContainsBytes(i + 1, contentsBytes, new byte[] { 0x0A, }, out eof2) && + !ContainsBytes(i - 1, contentsBytes, new byte[] { 0x0A, }, out eof3)) + { + if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // one or more of the indexes was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i += 4; // increase the loop variable by the amount of bytes used in the comparison.. + i++; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.UCRLF) && fileLineTypes.HasFlag(FileLineTypes.UCRLF)) - { - result.Add( - new KeyValuePair(FileLineTypes.UCRLF, GetLineEndingDescriptionByEnumeration(FileLineTypes.UCRLF, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.CR) && fileLineTypes.HasFlag(FileLineTypes.CR)) + { + result.Add( + new KeyValuePair(FileLineTypes.CR, GetLineEndingDescriptionByEnumeration(FileLineTypes.CR, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of LF+CR with Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0A, 0x00, 0x0D }, out eof1)) + // comparison of CR+LF with Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0D, 0x00, 0x0A, }, out eof1)) + { + if (eof1) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i += 4; // increase the loop variable by the amount of bytes used in the comparison.. + i += 4; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.ULFCR) && fileLineTypes.HasFlag(FileLineTypes.ULFCR)) - { - result.Add( - new KeyValuePair(FileLineTypes.ULFCR, GetLineEndingDescriptionByEnumeration(FileLineTypes.ULFCR, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.UCRLF) && fileLineTypes.HasFlag(FileLineTypes.UCRLF)) + { + result.Add( + new KeyValuePair(FileLineTypes.UCRLF, GetLineEndingDescriptionByEnumeration(FileLineTypes.UCRLF, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of LF with Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0A }, out eof1) && - !ContainsBytes(i + 2, contentsBytes, new byte[] { 0x00, 0x0D }, out eof2) && - !ContainsBytes(i - 2, contentsBytes, new byte[] { 0x00, 0x0D }, out eof3)) + // comparison of LF+CR with Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0A, 0x00, 0x0D, }, out eof1)) + { + if (eof1) // check for an overflow of the byte array.. { - if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. - { - // one or more of the indexes was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i += 2; // increase the loop variable by the amount of bytes used in the comparison.. + i += 4; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.ULF) && fileLineTypes.HasFlag(FileLineTypes.ULF)) - { - result.Add( - new KeyValuePair(FileLineTypes.ULF, GetLineEndingDescriptionByEnumeration(FileLineTypes.ULF, UseEnumNames))); - } - - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.ULFCR) && fileLineTypes.HasFlag(FileLineTypes.ULFCR)) + { + result.Add( + new KeyValuePair(FileLineTypes.ULFCR, GetLineEndingDescriptionByEnumeration(FileLineTypes.ULFCR, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of CR with Unicode.. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0D }, out eof1) && - !ContainsBytes(i + 2, contentsBytes, new byte[] { 0x00, 0x0A }, out eof2) && - !ContainsBytes(i - 2, contentsBytes, new byte[] { 0x00, 0x0A }, out eof3)) + // comparison of LF with Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0A, }, out eof1) && + !ContainsBytes(i + 2, contentsBytes, new byte[] { 0x00, 0x0D, }, out eof2) && + !ContainsBytes(i - 2, contentsBytes, new byte[] { 0x00, 0x0D, }, out eof3)) + { + if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. { - if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. - { - // one or more of the indexes was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // one or more of the indexes was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i += 2; // increase the loop variable by the amount of bytes used in the comparison.. + i += 2; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.UCR) && fileLineTypes.HasFlag(FileLineTypes.UCR)) - { - result.Add( - new KeyValuePair(FileLineTypes.UCR, GetLineEndingDescriptionByEnumeration(FileLineTypes.UCR, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.ULF) && fileLineTypes.HasFlag(FileLineTypes.ULF)) + { + result.Add( + new KeyValuePair(FileLineTypes.ULF, GetLineEndingDescriptionByEnumeration(FileLineTypes.ULF, UseEnumNames))); } - // comparison of RS (see: FileLineTypes.RS description..).. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x1E }, out eof1)) + continue; // match found so do continue the loop.. + } + + // comparison of CR with Unicode.. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x00, 0x0D, }, out eof1) && + !ContainsBytes(i + 2, contentsBytes, new byte[] { 0x00, 0x0A, }, out eof2) && + !ContainsBytes(i - 2, contentsBytes, new byte[] { 0x00, 0x0A, }, out eof3)) + { + if (eof1 || eof2 || eof3) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // one or more of the indexes was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i++; // increase the loop variable by the amount of bytes used in the comparison.. + i += 2; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.RS) && fileLineTypes.HasFlag(FileLineTypes.RS)) - { - result.Add( - new KeyValuePair(FileLineTypes.RS, GetLineEndingDescriptionByEnumeration(FileLineTypes.RS, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.UCR) && fileLineTypes.HasFlag(FileLineTypes.UCR)) + { + result.Add( + new KeyValuePair(FileLineTypes.UCR, GetLineEndingDescriptionByEnumeration(FileLineTypes.UCR, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of NL (see: FileLineTypes.NL description..).. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x15 }, out eof1)) + // comparison of RS (see: FileLineTypes.RS description..).. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x1E, }, out eof1)) + { + if (eof1) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i++; // increase the loop variable by the amount of bytes used in the comparison.. + i++; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.NL) && fileLineTypes.HasFlag(FileLineTypes.NL)) - { - result.Add( - new KeyValuePair(FileLineTypes.NL, GetLineEndingDescriptionByEnumeration(FileLineTypes.NL, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.RS) && fileLineTypes.HasFlag(FileLineTypes.RS)) + { + result.Add( + new KeyValuePair(FileLineTypes.RS, GetLineEndingDescriptionByEnumeration(FileLineTypes.RS, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of ATASCII (see: FileLineTypes.ATASCII description..).. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x9B }, out eof1)) + // comparison of NL (see: FileLineTypes.NL description..).. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x15, }, out eof1)) + { + if (eof1) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i++; // increase the loop variable by the amount of bytes used in the comparison.. + i++; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.ATASCII) && fileLineTypes.HasFlag(FileLineTypes.ATASCII)) - { - result.Add( - new KeyValuePair(FileLineTypes.ATASCII, GetLineEndingDescriptionByEnumeration(FileLineTypes.ATASCII, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.NL) && fileLineTypes.HasFlag(FileLineTypes.NL)) + { + result.Add( + new KeyValuePair(FileLineTypes.NL, GetLineEndingDescriptionByEnumeration(FileLineTypes.NL, UseEnumNames))); } + continue; // match found so do continue the loop.. + } - // comparison of NEWLINE (see: FileLineTypes.NEWLINE description..).. - if (ContainsBytes(i, contentsBytes, new byte[] { 0x76 }, out eof1)) + // comparison of ATASCII (see: FileLineTypes.ATASCII description..).. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x9B, }, out eof1)) + { + if (eof1) // check for an overflow of the byte array.. { - if (eof1) // check for an overflow of the byte array.. - { - // the index was outside the byte array so do - // increase the loop variable by one and continue.. - i++; - continue; - } + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - i++; // increase the loop variable by the amount of bytes used in the comparison.. + i++; // increase the loop variable by the amount of bytes used in the comparison.. - // check that the result value doesn't already contain the given enumeration and string pair.. - if (!result.Exists(f => f.Key == FileLineTypes.NEWLINE) && fileLineTypes.HasFlag(FileLineTypes.NEWLINE)) - { - result.Add( - new KeyValuePair(FileLineTypes.NEWLINE, GetLineEndingDescriptionByEnumeration(FileLineTypes.NEWLINE, UseEnumNames))); - } - continue; // match found so do continue the loop.. + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.ATASCII) && fileLineTypes.HasFlag(FileLineTypes.ATASCII)) + { + result.Add( + new KeyValuePair(FileLineTypes.ATASCII, GetLineEndingDescriptionByEnumeration(FileLineTypes.ATASCII, UseEnumNames))); } - i++; // the loop must not be infinite so increase the loop variable by one.. + continue; // match found so do continue the loop.. } - // if nothing was found assume CR+LF.. - if (result.Count == 0) + // comparison of NEWLINE (see: FileLineTypes.NEWLINE description..).. + if (ContainsBytes(i, contentsBytes, new byte[] { 0x76, }, out eof1)) { - result.Add( - new KeyValuePair(FileLineTypes.CRLF, GetLineEndingDescriptionByEnumeration(FileLineTypes.CRLF, UseEnumNames))); - } + if (eof1) // check for an overflow of the byte array.. + { + // the index was outside the byte array so do + // increase the loop variable by one and continue.. + i++; + continue; + } - // if multiple items was found, assume mixed line endings.. - if (result.Count() > 1) - { - result.Add( - new KeyValuePair(FileLineTypes.Mixed, GetLineEndingDescriptionByEnumeration(FileLineTypes.Mixed, UseEnumNames))); + i++; // increase the loop variable by the amount of bytes used in the comparison.. + + // check that the result value doesn't already contain the given enumeration and string pair.. + if (!result.Exists(f => f.Key == FileLineTypes.NEWLINE) && fileLineTypes.HasFlag(FileLineTypes.NEWLINE)) + { + result.Add( + new KeyValuePair(FileLineTypes.NEWLINE, GetLineEndingDescriptionByEnumeration(FileLineTypes.NEWLINE, UseEnumNames))); + } + continue; // match found so do continue the loop.. } + i++; // the loop must not be infinite so increase the loop variable by one.. + } - // return the result.. - return result; + // if nothing was found assume CR+LF.. + if (result.Count == 0) + { + result.Add( + new KeyValuePair(FileLineTypes.CRLF, GetLineEndingDescriptionByEnumeration(FileLineTypes.CRLF, UseEnumNames))); } - /// - /// Checks if the given is outside of the boundaries of the byte array. - /// - /// The index to check. - /// The content to check. - /// The match to check. - /// Returns true if the index in addition for the length is out if range within the byte array; otherwise false. - private static bool ArrayOutOfRange(int index, byte[] content, byte[] match) + // if multiple items was found, assume mixed line endings.. + if (result.Count() > 1) { - // comparison with the index.. - if (index + match.Length >= content.Length || index < 0) - { - return true; // out of range.. - } + result.Add( + new KeyValuePair(FileLineTypes.Mixed, GetLineEndingDescriptionByEnumeration(FileLineTypes.Mixed, UseEnumNames))); + } - // within range.. - return false; + // return the result.. + return result; + } + + /// + /// Checks if the given is outside of the boundaries of the byte array. + /// + /// The index to check. + /// The content to check. + /// The match to check. + /// Returns true if the index in addition for the length is out if range within the byte array; otherwise false. + private static bool ArrayOutOfRange(int index, byte[] content, byte[] match) + { + // comparison with the index.. + if (index + match.Length >= content.Length || index < 0) + { + return true; // out of range.. } - /// - /// Determines whether the specified index in the given contents contains the given match byte array. - /// - /// The index where to compare the with the byte array. - /// The contents of the base byte array. - /// The match byte array which to compare with the byte array. - /// A variable indicating if the comparison would have been outside the boundaries of the byte array. - /// - /// true if the specified index contains bytes; otherwise, false. - /// - private static bool ContainsBytes(int index, byte[] content, byte[] match, out bool eof) + // within range.. + return false; + } + + /// + /// Determines whether the specified index in the given contents contains the given match byte array. + /// + /// The index where to compare the with the byte array. + /// The contents of the base byte array. + /// The match byte array which to compare with the byte array. + /// A variable indicating if the comparison would have been outside the boundaries of the byte array. + /// + /// true if the specified index contains bytes; otherwise, false. + /// + private static bool ContainsBytes(int index, byte[] content, byte[] match, out bool eof) + { + try { - try + // see if the given parameters are withing range.. + if (ArrayOutOfRange(index, content, match)) { - // see if the given parameters are withing range.. - if (ArrayOutOfRange(index, content, match)) - { - // set the EOF flag value.. - eof = true; - return false; // ..and return false.. - } - else + // set the EOF flag value.. + eof = true; + return false; // ..and return false.. + } + else + { + // check if the given match parameter is found from the + // content parameter's value with the given index.. + int matchIndex = 0; // a variable to hold the indexer for the match parameter.. + bool resultBool = true; // an assumption of true.. + for (int i = index; i < content.Length; i++) { - // check if the given match parameter is found from the - // content parameter's value with the given index.. - int matchIndex = 0; // a variable to hold the indexer for the match parameter.. - bool resultBool = true; // an assumption of true.. - for (int i = index; i < content.Length; i++) + // if the indexer variable for the match parameter + // exceeds the boundaries of the match parameter byte array.. + if (matchIndex >= match.Length) { - // if the indexer variable for the match parameter - // exceeds the boundaries of the match parameter byte array.. - if (matchIndex >= match.Length) - { - break; // ..break the loop.. - } - - // append boolean algebra to the result variable.. - resultBool &= content[i] == match[matchIndex++]; + break; // ..break the loop.. } - eof = false; // set the EOF flag value.. - return resultBool; // return the result.. + + // append boolean algebra to the result variable.. + resultBool &= content[i] == match[matchIndex++]; } + eof = false; // set the EOF flag value.. + return resultBool; // return the result.. } - catch // an exception occurred.. - { - eof = false; // ..set the EOF flag value.. - return false; // ..and return false.. - } + } + catch // an exception occurred.. + { + eof = false; // ..set the EOF flag value.. + return false; // ..and return false.. } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MathUtils/MathUtils.cs b/ScriptNotepad/UtilityClasses/MathUtils/MathUtils.cs index 38c77fa0..aba7fefe 100644 --- a/ScriptNotepad/UtilityClasses/MathUtils/MathUtils.cs +++ b/ScriptNotepad/UtilityClasses/MathUtils/MathUtils.cs @@ -26,33 +26,32 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Linq; -namespace ScriptNotepad.UtilityClasses.MathUtils +namespace ScriptNotepad.UtilityClasses.MathUtils; + +/// +/// Some mathematical utilities. +/// +public static class MathUtils { /// - /// Some mathematical utilities. + /// Determines the maximum value of the given parameters. + /// + /// The type of the object which maximum value to get. + /// The values of type T which maximum value to get. + /// T. + public static T Max(params T[] values) + { + return values.Max(); + } + + /// + /// Determines the minimum value of the given parameters. /// - public static class MathUtils + /// The type of the object which minimum value to get. + /// The values of type T which minimum value to get. + /// T. + public static T Min(params T[] values) { - /// - /// Determines the maximum value of the given parameters. - /// - /// The type of the object which maximum value to get. - /// The values of type T which maximum value to get. - /// T. - public static T Max(params T[] values) - { - return values.Max(); - } - - /// - /// Determines the minimum value of the given parameters. - /// - /// The type of the object which minimum value to get. - /// The values of type T which minimum value to get. - /// T. - public static T Min(params T[] values) - { - return values.Min(); - } + return values.Min(); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MenuHelpers/ContextMenuStyles.cs b/ScriptNotepad/UtilityClasses/MenuHelpers/ContextMenuStyles.cs index ebc977ef..0136004c 100644 --- a/ScriptNotepad/UtilityClasses/MenuHelpers/ContextMenuStyles.cs +++ b/ScriptNotepad/UtilityClasses/MenuHelpers/ContextMenuStyles.cs @@ -28,90 +28,89 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using VPKSoft.LangLib; -namespace ScriptNotepad.UtilityClasses.MenuHelpers +namespace ScriptNotepad.UtilityClasses.MenuHelpers; + +/// +/// A class to add to the context menu a style mark selection sub menu. +/// +public class ContextMenuStyles { /// - /// A class to add to the context menu a style mark selection sub menu. + /// Creates the style menu. /// - public class ContextMenuStyles + /// The menu strip to create the style menu to. + /// The event handler to mark text using a style. + /// The event handler to clear a style mark. + /// The event handler to clear all style marks. + public static void CreateStyleMenu(ContextMenuStrip menuStrip, EventHandler menuClickMark, + EventHandler menuClickClearMark, EventHandler menuClearAllMarks) { - /// - /// Creates the style menu. - /// - /// The menu strip to create the style menu to. - /// The event handler to mark text using a style. - /// The event handler to clear a style mark. - /// The event handler to clear all style marks. - public static void CreateStyleMenu(ContextMenuStrip menuStrip, EventHandler menuClickMark, - EventHandler menuClickClearMark, EventHandler menuClearAllMarks) - { - // add the style menu to the given context menu LOCALIZED.. - menuStrip.Items.Add(new ToolStripSeparator()); - - var toolStripDropDown = new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleSet", - "Style|A menu item text to indicate marking / un-marking text using some style")); - - menuStrip.Items.Add(toolStripDropDown); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleClearAll", - "Clear all styles|A menu item text to indicate clearing all style marks"), null, - menuClearAllMarks)); - - toolStripDropDown.DropDownItems.Add(new ToolStripSeparator()); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleSet1", - "Mark using the first style|A menu item text to indicate marking text using style 1"), null, - menuClickMark) {Tag = "9"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleSet2", - "Mark using the seconds style|A menu item text to indicate marking text using style 2"), null, - menuClickMark) {Tag = "10"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleSet3", - "Mark using the third style|A menu item text to indicate marking text using style 3"), null, - menuClickMark) {Tag = "11"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleSet4", - "Mark using the fourth style|A menu item text to indicate marking text using style 4"), null, - menuClickMark) {Tag = "12"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleSet5", - "Mark using the fifth style|A menu item text to indicate marking text using style 5"), null, - menuClickMark) {Tag = "13"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripSeparator()); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleClear1", - "Clear style one|A menu item text to indicate clearing the text style 1 marks"), null, - menuClickClearMark) {Tag = "9"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleClear2", - "Clear style two|A menu item text to indicate clearing the text style 2 marks"), null, - menuClickClearMark) {Tag = "10"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleClear3", - "Clear style three|A menu item text to indicate clearing the text style 3 marks"), null, - menuClickClearMark) {Tag = "11"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleClear4", - "Clear style four|A menu item text to indicate clearing the text style 4 marks"), null, - menuClickClearMark) {Tag = "12"}); - - toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( - DBLangEngine.GetStatMessage("msgStyleClear5", - "Clear style five|A menu item text to indicate clearing the text style 5 marks"), null, - menuClickClearMark) {Tag = "13"}); - } + // add the style menu to the given context menu LOCALIZED.. + menuStrip.Items.Add(new ToolStripSeparator()); + + var toolStripDropDown = new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleSet", + "Style|A menu item text to indicate marking / un-marking text using some style")); + + menuStrip.Items.Add(toolStripDropDown); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleClearAll", + "Clear all styles|A menu item text to indicate clearing all style marks"), null, + menuClearAllMarks)); + + toolStripDropDown.DropDownItems.Add(new ToolStripSeparator()); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleSet1", + "Mark using the first style|A menu item text to indicate marking text using style 1"), null, + menuClickMark) {Tag = "9", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleSet2", + "Mark using the seconds style|A menu item text to indicate marking text using style 2"), null, + menuClickMark) {Tag = "10", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleSet3", + "Mark using the third style|A menu item text to indicate marking text using style 3"), null, + menuClickMark) {Tag = "11", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleSet4", + "Mark using the fourth style|A menu item text to indicate marking text using style 4"), null, + menuClickMark) {Tag = "12", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleSet5", + "Mark using the fifth style|A menu item text to indicate marking text using style 5"), null, + menuClickMark) {Tag = "13", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripSeparator()); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleClear1", + "Clear style one|A menu item text to indicate clearing the text style 1 marks"), null, + menuClickClearMark) {Tag = "9", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleClear2", + "Clear style two|A menu item text to indicate clearing the text style 2 marks"), null, + menuClickClearMark) {Tag = "10", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleClear3", + "Clear style three|A menu item text to indicate clearing the text style 3 marks"), null, + menuClickClearMark) {Tag = "11", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleClear4", + "Clear style four|A menu item text to indicate clearing the text style 4 marks"), null, + menuClickClearMark) {Tag = "12", }); + + toolStripDropDown.DropDownItems.Add(new ToolStripMenuItem( + DBLangEngine.GetStatMessage("msgStyleClear5", + "Clear style five|A menu item text to indicate clearing the text style 5 marks"), null, + menuClickClearMark) {Tag = "13", }); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MenuHelpers/RecentFilesMenuBuilder.cs b/ScriptNotepad/UtilityClasses/MenuHelpers/RecentFilesMenuBuilder.cs index b3ed54d9..07000aba 100644 --- a/ScriptNotepad/UtilityClasses/MenuHelpers/RecentFilesMenuBuilder.cs +++ b/ScriptNotepad/UtilityClasses/MenuHelpers/RecentFilesMenuBuilder.cs @@ -31,71 +31,51 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Entities; using ScriptNotepad.UtilityClasses.Common; -namespace ScriptNotepad.UtilityClasses.MenuHelpers +namespace ScriptNotepad.UtilityClasses.MenuHelpers; + +/// +/// A class for creating a recent file menu for a Windows Forms application. +/// +public static class RecentFilesMenuBuilder { /// - /// A class for creating a recent file menu for a Windows Forms application. + /// A localizable text for a menu item which would open all recent files. /// - public static class RecentFilesMenuBuilder - { - /// - /// A localizable text for a menu item which would open all recent files. - /// - public static string MenuOpenAllRecentText { get; set; } = "Open all recent files..."; - - /// - /// Creates a recent files menu to a given parent menu. - /// - /// The menu item to add the recent files list. - /// A name of the session to which the history documents belong to. - /// Maximum count of recent file entries to add to the given . - /// A flag indicating whether the menu should contain an item to open all recent files. - /// A list of tool strip items to hide if there are no recent files. - public static void CreateRecentFilesMenu(ToolStripMenuItem menuItem, FileSession session, - int maxCount, bool addMenuOpenAll, params ToolStripItem[] hideItems) - { - // dispose of the previous menu items.. - DisposeRecentFilesMenu(menuItem); - - // get the recent files from the database.. - var recentFiles = ScriptNotepadDbContext.DbContext.RecentFiles - .OrderByDescending(f => f.ClosedDateTime).Where(f => - f.Session.SessionName == session.SessionName && !ScriptNotepadDbContext.DbContext.FileSaves.Any(s => - !s.IsHistory && s.Session.SessionName == f.Session.SessionName && - s.FileNameFull == f.FileNameFull)).Take(maxCount); - - if (addMenuOpenAll) - { - List recentFilesAll = recentFiles.ToList(); - - if (recentFilesAll.Count > 1) - { - // create a menu item for all the recent files.. - DataToolStripMenuItem menuItemRecentFile = - new DataToolStripMenuItem( - string.IsNullOrWhiteSpace(MenuOpenAllRecentText) - ? "Open all recent files..." - : MenuOpenAllRecentText) {Data = recentFilesAll}; - - // set the user given additional data for the menu item.. + public static string MenuOpenAllRecentText { get; set; } = "Open all recent files..."; - // subscribe the click event.. - menuItemRecentFile.Click += MenuItemRecentFile_Click; + /// + /// Creates a recent files menu to a given parent menu. + /// + /// The menu item to add the recent files list. + /// A name of the session to which the history documents belong to. + /// Maximum count of recent file entries to add to the given . + /// A flag indicating whether the menu should contain an item to open all recent files. + /// A list of tool strip items to hide if there are no recent files. + public static void CreateRecentFilesMenu(ToolStripMenuItem menuItem, FileSession session, + int maxCount, bool addMenuOpenAll, params ToolStripItem[] hideItems) + { + // dispose of the previous menu items.. + DisposeRecentFilesMenu(menuItem); - // add the menu item to the recent files menu.. - menuItem.DropDownItems.Add(menuItemRecentFile); + // get the recent files from the database.. + var recentFiles = ScriptNotepadDbContext.DbContext.RecentFiles + .OrderByDescending(f => f.ClosedDateTime).Where(f => + f.Session.SessionName == session.SessionName && !ScriptNotepadDbContext.DbContext.FileSaves.Any(s => + !s.IsHistory && s.Session.SessionName == f.Session.SessionName && + s.FileNameFull == f.FileNameFull)).Take(maxCount); - // add a separator menu item to the recent files menu.. - menuItem.DropDownItems.Add(new ToolStripSeparator()); - } - } + if (addMenuOpenAll) + { + List recentFilesAll = recentFiles.ToList(); - // loop through the results.. - foreach (var recentFile in recentFiles) + if (recentFilesAll.Count > 1) { - // create a menu item for the encoding.. + // create a menu item for all the recent files.. DataToolStripMenuItem menuItemRecentFile = - new DataToolStripMenuItem(recentFile.ToString()) {Data = recentFile}; + new DataToolStripMenuItem( + string.IsNullOrWhiteSpace(MenuOpenAllRecentText) + ? "Open all recent files..." + : MenuOpenAllRecentText) {Data = recentFilesAll, }; // set the user given additional data for the menu item.. @@ -104,126 +84,145 @@ public static void CreateRecentFilesMenu(ToolStripMenuItem menuItem, FileSession // add the menu item to the recent files menu.. menuItem.DropDownItems.Add(menuItemRecentFile); - } - // the recent file menu should only be visible if there are any drop down items.. - menuItem.Visible = menuItem.DropDownItems.Count > 0; - - // hide or show the items which are "depended" of the visibility of the - // recent files menu.. - foreach (ToolStripItem item in hideItems) - { - item.Visible = menuItem.DropDownItems.Count > 0; + // add a separator menu item to the recent files menu.. + menuItem.DropDownItems.Add(new ToolStripSeparator()); } } - /// - /// Handles the Click event of a recent file menu item control. - /// - /// The source of the event. - /// The instance containing the event data. - private static void MenuItemRecentFile_Click(object sender, EventArgs e) + // loop through the results.. + foreach (var recentFile in recentFiles) { - // get the clicked item.. - var item = (DataToolStripMenuItem)sender; + // create a menu item for the encoding.. + DataToolStripMenuItem menuItemRecentFile = + new DataToolStripMenuItem(recentFile.ToString()) {Data = recentFile, }; - // this shouldn't happen, but just in case.. - if (item.Data == null) - { - // ..so just return.. - return; - } + // set the user given additional data for the menu item.. - // the menu item contains a single recent file.. - if (item.Data.GetType() == typeof(RecentFile)) - { - // raise the event if subscribed.. - RecentFileMenuClicked?.Invoke(sender, // the recent file for the event.. - new RecentFilesMenuClickEventArgs() { RecentFile = (RecentFile)item.Data, RecentFiles = null }); - } - // the menu item contains a list of recent files.. - else if (item.Data.GetType() == typeof(List)) - { - // raise the event if subscribed.. - RecentFileMenuClicked?.Invoke(sender, // the recent file list for the event.. - new RecentFilesMenuClickEventArgs() { RecentFile = null, RecentFiles = (List)item.Data }); - } + // subscribe the click event.. + menuItemRecentFile.Click += MenuItemRecentFile_Click; + + // add the menu item to the recent files menu.. + menuItem.DropDownItems.Add(menuItemRecentFile); } - /// - /// Disposes the recent file menu constructed via the method. - /// - /// The parent tool strip menu item. - public static void DisposeRecentFilesMenu(ToolStripMenuItem parent) + // the recent file menu should only be visible if there are any drop down items.. + menuItem.Visible = menuItem.DropDownItems.Count > 0; + + // hide or show the items which are "depended" of the visibility of the + // recent files menu.. + foreach (ToolStripItem item in hideItems) { - List disposeList = new List(); - foreach (var item in parent.DropDownItems) - { - // only accept types of ToolStripMenuItem.. - if (item.GetType() != typeof(ToolStripMenuItem)) - { - continue; - } + item.Visible = menuItem.DropDownItems.Count > 0; + } + } - // cast the object as ToolStripMenuItem.. - var recentFileMenuItem = (ToolStripMenuItem)item; + /// + /// Handles the Click event of a recent file menu item control. + /// + /// The source of the event. + /// The instance containing the event data. + private static void MenuItemRecentFile_Click(object sender, EventArgs e) + { + // get the clicked item.. + var item = (DataToolStripMenuItem)sender; - // unsubscribe the event handler.. - recentFileMenuItem.Click -= MenuItemRecentFile_Click; + // this shouldn't happen, but just in case.. + if (item.Data == null) + { + // ..so just return.. + return; + } - // clear the drop down menu item.. - parent.DropDownItems.Clear(); + // the menu item contains a single recent file.. + if (item.Data.GetType() == typeof(RecentFile)) + { + // raise the event if subscribed.. + RecentFileMenuClicked?.Invoke(sender, // the recent file for the event.. + new RecentFilesMenuClickEventArgs() { RecentFile = (RecentFile)item.Data, RecentFiles = null, }); + } + // the menu item contains a list of recent files.. + else if (item.Data.GetType() == typeof(List)) + { + // raise the event if subscribed.. + RecentFileMenuClicked?.Invoke(sender, // the recent file list for the event.. + new RecentFilesMenuClickEventArgs() { RecentFile = null, RecentFiles = (List)item.Data, }); + } + } - // add the menu item to the list of ToolStripMenuItems to disposed of.. - disposeList.Add(recentFileMenuItem); + /// + /// Disposes the recent file menu constructed via the method. + /// + /// The parent tool strip menu item. + public static void DisposeRecentFilesMenu(ToolStripMenuItem parent) + { + List disposeList = new List(); + foreach (var item in parent.DropDownItems) + { + // only accept types of ToolStripMenuItem.. + if (item.GetType() != typeof(ToolStripMenuItem)) + { + continue; } - // clear the drop down items from the parent menu item.. + // cast the object as ToolStripMenuItem.. + var recentFileMenuItem = (ToolStripMenuItem)item; + + // unsubscribe the event handler.. + recentFileMenuItem.Click -= MenuItemRecentFile_Click; + + // clear the drop down menu item.. parent.DropDownItems.Clear(); - // loop through the list of ToolStripMenuItems to disposed of.. - for (int i = 0; i < disposeList.Count; i++) + // add the menu item to the list of ToolStripMenuItems to disposed of.. + disposeList.Add(recentFileMenuItem); + } + + // clear the drop down items from the parent menu item.. + parent.DropDownItems.Clear(); + + // loop through the list of ToolStripMenuItems to disposed of.. + for (int i = 0; i < disposeList.Count; i++) + { + // dispose.. + using (disposeList[i]) { - // dispose.. - using (disposeList[i]) - { - // null assignment isn't necessary, but the using clause - // would look a little "orphan" without that.. - disposeList[i] = null; - } + // null assignment isn't necessary, but the using clause + // would look a little "orphan" without that.. + disposeList[i] = null; } - - // no reason to display an empty menu which should have drop down items.. - parent.Visible = false; } - /// - /// A delegate for the RecentFileMenuClicked event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnRecentFileMenuClicked(object sender, RecentFilesMenuClickEventArgs e); - - /// - /// Occurs when a recent file menu item was clicked. - /// - public static event OnRecentFileMenuClicked RecentFileMenuClicked; + // no reason to display an empty menu which should have drop down items.. + parent.Visible = false; } /// - /// Event arguments for the RecentFileMenuClicked event. + /// A delegate for the RecentFileMenuClicked event. /// - /// - public class RecentFilesMenuClickEventArgs : EventArgs - { - /// - /// Gets the of the clicked recent file menu item. - /// - public RecentFile RecentFile { get; internal set; } - - /// - /// Gets a list of the all of the clicked recent file menu item to open all the recent files. - /// - public List RecentFiles { get; internal set; } - } + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnRecentFileMenuClicked(object sender, RecentFilesMenuClickEventArgs e); + + /// + /// Occurs when a recent file menu item was clicked. + /// + public static event OnRecentFileMenuClicked RecentFileMenuClicked; } + +/// +/// Event arguments for the RecentFileMenuClicked event. +/// +/// +public class RecentFilesMenuClickEventArgs : EventArgs +{ + /// + /// Gets the of the clicked recent file menu item. + /// + public RecentFile RecentFile { get; internal set; } + + /// + /// Gets a list of the all of the clicked recent file menu item to open all the recent files. + /// + public List RecentFiles { get; internal set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MenuHelpers/TabMenuBuilder.cs b/ScriptNotepad/UtilityClasses/MenuHelpers/TabMenuBuilder.cs index 32ee0571..e60e7cfe 100644 --- a/ScriptNotepad/UtilityClasses/MenuHelpers/TabMenuBuilder.cs +++ b/ScriptNotepad/UtilityClasses/MenuHelpers/TabMenuBuilder.cs @@ -28,102 +28,101 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using VPKSoft.ScintillaTabbedTextControl; -namespace ScriptNotepad.UtilityClasses.MenuHelpers +namespace ScriptNotepad.UtilityClasses.MenuHelpers; + +class TabMenuBuilder : ErrorHandlingBase, IDisposable { - class TabMenuBuilder : ErrorHandlingBase, IDisposable + /// + /// Initializes a new instance of the class. + /// + /// The main menu item to the add the open forms within the . + /// The main form's class instance. + public TabMenuBuilder(ToolStripMenuItem mainItem, ScintillaTabbedTextControl tabbedTextControl) { - /// - /// Initializes a new instance of the class. - /// - /// The main menu item to the add the open forms within the . - /// The main form's class instance. - public TabMenuBuilder(ToolStripMenuItem mainItem, ScintillaTabbedTextControl tabbedTextControl) - { - // save the Tab menu for further use.. - this.mainItem = mainItem; + // save the Tab menu for further use.. + this.mainItem = mainItem; - this.tabbedTextControl = tabbedTextControl; + this.tabbedTextControl = tabbedTextControl; - // subscribe to the Tab menu's opening event.. - mainItem.DropDownOpening += MainItem_DropDownOpening; - } + // subscribe to the Tab menu's opening event.. + mainItem.DropDownOpening += MainItem_DropDownOpening; + } - private void MainItem_DropDownOpening(object sender, EventArgs e) - { - CreateMenuOpenTabs(); - } + private void MainItem_DropDownOpening(object sender, EventArgs e) + { + CreateMenuOpenTabs(); + } - /// - /// Clears the previous drop-down items from the main menu item. - /// - private void ClearPreviousMenu() + /// + /// Clears the previous drop-down items from the main menu item. + /// + private void ClearPreviousMenu() + { + // reverse loop.. + for (int i = mainItem.DropDownItems.Count - 1; i >= 0; i--) { - // reverse loop.. - for (int i = mainItem.DropDownItems.Count - 1; i >= 0; i--) - { - // un-subscribe the click event handler.. - mainItem.DropDownItems[i].Click -= Item_Click; - } - - // clear the items.. - mainItem.DropDownItems.Clear(); + // un-subscribe the click event handler.. + mainItem.DropDownItems[i].Click -= Item_Click; } - /// - /// Creates the menu of the open forms within the . - /// - internal void CreateMenuOpenTabs() - { - // clear the previously created menu.. - ClearPreviousMenu(); + // clear the items.. + mainItem.DropDownItems.Clear(); + } + /// + /// Creates the menu of the open forms within the . + /// + internal void CreateMenuOpenTabs() + { + // clear the previously created menu.. + ClearPreviousMenu(); - // loop through the open tabs in the ScintillaTabbedTextControl.. - foreach (ScintillaTabbedDocument document in tabbedTextControl.Documents) - { - // create a new ToolStripMenuItem for the tab.. - ToolStripMenuItem item = new ToolStripMenuItem(document.FileNameNotPath) - {Tag = document, Checked = document.Equals(tabbedTextControl.CurrentDocument)}; - // subscribe to the click event.. - item.Click += Item_Click; + // loop through the open tabs in the ScintillaTabbedTextControl.. + foreach (ScintillaTabbedDocument document in tabbedTextControl.Documents) + { + // create a new ToolStripMenuItem for the tab.. + ToolStripMenuItem item = new ToolStripMenuItem(document.FileNameNotPath) + {Tag = document, Checked = document.Equals(tabbedTextControl.CurrentDocument), }; - // ad the item to the main menu item's DropDownItems collection.. - mainItem.DropDownItems.Add(item); - } + // subscribe to the click event.. + item.Click += Item_Click; - mainItem.Enabled = tabbedTextControl.DocumentsCount > 0; + // ad the item to the main menu item's DropDownItems collection.. + mainItem.DropDownItems.Add(item); } + mainItem.Enabled = tabbedTextControl.DocumentsCount > 0; + } - private void Item_Click(object sender, EventArgs e) - { - var menu = (ToolStripMenuItem) sender; - var document = (ScintillaTabbedDocument) menu.Tag; - int docIndex = tabbedTextControl.Documents.FindIndex(f => f.ID == document.ID); - if (docIndex != -1) - { - tabbedTextControl.ActivateDocument(docIndex); - } - } - public void Dispose() + private void Item_Click(object sender, EventArgs e) + { + var menu = (ToolStripMenuItem) sender; + var document = (ScintillaTabbedDocument) menu.Tag; + int docIndex = tabbedTextControl.Documents.FindIndex(f => f.ID == document.ID); + if (docIndex != -1) { - // clear the previously created menu.. - ClearPreviousMenu(); - - // unsubscribe the events subscribed by this class instance.. - mainItem.DropDownOpening -= MainItem_DropDownOpening; + tabbedTextControl.ActivateDocument(docIndex); } + } - /// - /// A field to hold the main menu item for the open Tabs within the . - /// - private readonly ToolStripMenuItem mainItem; + public void Dispose() + { + // clear the previously created menu.. + ClearPreviousMenu(); - /// - /// A field to hold the main menu item for the open Tabs within the . - /// - private readonly ScintillaTabbedTextControl tabbedTextControl; + // unsubscribe the events subscribed by this class instance.. + mainItem.DropDownOpening -= MainItem_DropDownOpening; } -} + + /// + /// A field to hold the main menu item for the open Tabs within the . + /// + private readonly ToolStripMenuItem mainItem; + + /// + /// A field to hold the main menu item for the open Tabs within the . + /// + private readonly ScintillaTabbedTextControl tabbedTextControl; +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MenuHelpers/WinFormsFormMenuBuilder.cs b/ScriptNotepad/UtilityClasses/MenuHelpers/WinFormsFormMenuBuilder.cs index f50ceb61..20e6ac95 100644 --- a/ScriptNotepad/UtilityClasses/MenuHelpers/WinFormsFormMenuBuilder.cs +++ b/ScriptNotepad/UtilityClasses/MenuHelpers/WinFormsFormMenuBuilder.cs @@ -27,129 +27,89 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Windows.Forms; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.MenuHelpers +namespace ScriptNotepad.UtilityClasses.MenuHelpers; + +/// +/// A class to help build an application-wide menu for all the visible forms within the application. +/// Implements the +/// +/// +public class WinFormsFormMenuBuilder : ErrorHandlingBase, IDisposable { /// - /// A class to help build an application-wide menu for all the visible forms within the application. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public class WinFormsFormMenuBuilder : ErrorHandlingBase, IDisposable + /// The main menu item to the add the open forms within the . + public WinFormsFormMenuBuilder(ToolStripMenuItem mainItem) { - /// - /// Initializes a new instance of the class. - /// - /// The main menu item to the add the open forms within the . - public WinFormsFormMenuBuilder(ToolStripMenuItem mainItem) - { - // save the window menu for further use.. - this.mainItem = mainItem; + // save the window menu for further use.. + this.mainItem = mainItem; - // subscribe to the window menu's opening event.. - mainItem.DropDownOpening += MainItem_DropDownOpening; + // subscribe to the window menu's opening event.. + mainItem.DropDownOpening += MainItem_DropDownOpening; - // create a timer to poll the menu changes.. - Timer = new Timer {Interval = 500, Enabled = true}; + // create a timer to poll the menu changes.. + Timer = new Timer {Interval = 500, Enabled = true, }; - // subscribe to the timer event.. - Timer.Tick += Timer_Tick; - } + // subscribe to the timer event.. + Timer.Tick += Timer_Tick; + } - // this timer will monitor the open form amount of the application.. - private void Timer_Tick(object sender, EventArgs e) - { - Timer.Enabled = false; + // this timer will monitor the open form amount of the application.. + private void Timer_Tick(object sender, EventArgs e) + { + Timer.Enabled = false; - // enable/disable the window menu based on the value whether the application has - // any other open forms than the main form.. - mainItem.Enabled = HasOpenForms; + // enable/disable the window menu based on the value whether the application has + // any other open forms than the main form.. + mainItem.Enabled = HasOpenForms; - Timer.Enabled = true; - } + Timer.Enabled = true; + } - /// - /// Gets or sets the timer used to update the enabled state of 's window menu. - /// - private Timer Timer { get; } + /// + /// Gets or sets the timer used to update the enabled state of 's window menu. + /// + private Timer Timer { get; } - /// - /// A field to hold the main menu item for the opened forms within the . - /// - private readonly ToolStripMenuItem mainItem; + /// + /// A field to hold the main menu item for the opened forms within the . + /// + private readonly ToolStripMenuItem mainItem; - private void MainItem_DropDownOpening(object sender, EventArgs e) - { - // create a menu of the opened forms within the Application.. - CreateMenuOpenForms(); - } + private void MainItem_DropDownOpening(object sender, EventArgs e) + { + // create a menu of the opened forms within the Application.. + CreateMenuOpenForms(); + } - /// - /// Clears the previous drop-down items from the main menu item. - /// - private void ClearPreviousMenu() + /// + /// Clears the previous drop-down items from the main menu item. + /// + private void ClearPreviousMenu() + { + // reverse loop.. + for (int i = mainItem.DropDownItems.Count - 1; i >= 0; i--) { - // reverse loop.. - for (int i = mainItem.DropDownItems.Count - 1; i >= 0; i--) - { - // un-subscribe the click event handler.. - mainItem.DropDownItems[i].Click -= Item_Click; - } - - // clear the items.. - mainItem.DropDownItems.Clear(); + // un-subscribe the click event handler.. + mainItem.DropDownItems[i].Click -= Item_Click; } - /// - /// Gets the value indicating whether the has opened forms other than the main form. - /// - private bool HasOpenForms - { - get - { - // a way to get a explicit type for a var variable definition.. - - bool result = false; - - // if there is a main form, do get its instance.. - Form formMain = FormMain.Instance; - - // loop through the open forms within the application.. - foreach (Form openForm in Application.OpenForms) - { - // the main form will not be added to the list of open forms.. - if (openForm.Equals(formMain)) - { - // ..so do continue.. - continue; - } - - // hidden forms will not be added to the list of open form.. - if (!openForm.Visible) - { - continue; - } - - // set the result to true.. - result = true; - - // break after the result is set.. - break; - } - - return result; - } - } + // clear the items.. + mainItem.DropDownItems.Clear(); + } - /// - /// Creates the menu of the open forms within the . - /// - private void CreateMenuOpenForms() + /// + /// Gets the value indicating whether the has opened forms other than the main form. + /// + private bool HasOpenForms + { + get { - // clear the previously created menu.. - ClearPreviousMenu(); - // a way to get a explicit type for a var variable definition.. + bool result = false; + // if there is a main form, do get its instance.. Form formMain = FormMain.Instance; @@ -169,64 +129,103 @@ private void CreateMenuOpenForms() continue; } - // create a new ToolStripMenuItem for the form.. - ToolStripMenuItem item = new ToolStripMenuItem(openForm.Text) {Tag = openForm}; - - // subscribe to the click event.. - item.Click += Item_Click; + // set the result to true.. + result = true; - // ad the item to the main menu item's DropDownItems collection.. - mainItem.DropDownItems.Add(item); + // break after the result is set.. + break; } + + return result; } + } + + /// + /// Creates the menu of the open forms within the . + /// + private void CreateMenuOpenForms() + { + // clear the previously created menu.. + ClearPreviousMenu(); + + // a way to get a explicit type for a var variable definition.. + + // if there is a main form, do get its instance.. + Form formMain = FormMain.Instance; - // an event that occurs when a user clicks the form menu item.. - private void Item_Click(object sender, EventArgs e) + // loop through the open forms within the application.. + foreach (Form openForm in Application.OpenForms) { - // get the sending ToolStripMenuItem.. - var menu = (ToolStripMenuItem) sender; + // the main form will not be added to the list of open forms.. + if (openForm.Equals(formMain)) + { + // ..so do continue.. + continue; + } - // get the Form in question.. - var form = (Form) menu.Tag; + // hidden forms will not be added to the list of open form.. + if (!openForm.Visible) + { + continue; + } - // display the form.. - form.Show(); + // create a new ToolStripMenuItem for the form.. + ToolStripMenuItem item = new ToolStripMenuItem(openForm.Text) {Tag = openForm, }; - // bring the form to the front.. - form.BringToFront(); - } + // subscribe to the click event.. + item.Click += Item_Click; - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); + // ad the item to the main menu item's DropDownItems collection.. + mainItem.DropDownItems.Add(item); } + } + + // an event that occurs when a user clicks the form menu item.. + private void Item_Click(object sender, EventArgs e) + { + // get the sending ToolStripMenuItem.. + var menu = (ToolStripMenuItem) sender; - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) + // get the Form in question.. + var form = (Form) menu.Tag; + + // display the form.. + form.Show(); + + // bring the form to the front.. + form.BringToFront(); + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - // disable the form check timer.. - Timer.Enabled = false; + // disable the form check timer.. + Timer.Enabled = false; - // clear the previously created menu.. - ClearPreviousMenu(); + // clear the previously created menu.. + ClearPreviousMenu(); - // unsubscribe the events subscribed by this class instance.. - mainItem.DropDownOpening -= MainItem_DropDownOpening; + // unsubscribe the events subscribed by this class instance.. + mainItem.DropDownOpening -= MainItem_DropDownOpening; - using (Timer) - { - Timer.Tick -= Timer_Tick; - } + using (Timer) + { + Timer.Tick -= Timer_Tick; } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MiscForms/FormFileDiffView.cs b/ScriptNotepad/UtilityClasses/MiscForms/FormFileDiffView.cs index aed2c13f..8ad907a0 100644 --- a/ScriptNotepad/UtilityClasses/MiscForms/FormFileDiffView.cs +++ b/ScriptNotepad/UtilityClasses/MiscForms/FormFileDiffView.cs @@ -29,111 +29,110 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.PosLib; using static ScintillaDiff.ScintillaDiffStyles; -namespace ScriptNotepad.UtilityClasses.MiscForms +namespace ScriptNotepad.UtilityClasses.MiscForms; + +/// +/// A form to display differences between two files. +/// Implements the +/// +/// +public partial class FormFileDiffView : DBLangEngineWinforms { /// - /// A form to display differences between two files. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormFileDiffView : DBLangEngineWinforms + public FormFileDiffView() { - /// - /// Initializes a new instance of the class. - /// - public FormFileDiffView() - { - // Add this form to be positioned.. - PositionForms.Add(this); - - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + // Add this form to be positioned.. + PositionForms.Add(this); - InitializeComponent(); + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + InitializeComponent(); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - - ThisInstance = this; + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. } - /// - /// Gets or sets a value indicating whether the application is going to be closed. - /// - public static bool ApplicationClosing { get; set; } - - /// - /// Keep this class a singleton. - /// - private static FormFileDiffView ThisInstance { get; set; } - - /// - /// Displays the form with given file contents. - /// - /// The first file's contents to use with the diff. - /// The second file's contents to use with the diff. - public static void Execute(string diffOne, string diffTwo) - { - if (ThisInstance == null) - { - ThisInstance = new FormFileDiffView(); - } + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - ThisInstance.diffControl.TextLeft = diffOne; - ThisInstance.diffControl.TextRight = diffTwo; + ThisInstance = this; + } - ThisInstance.tsbPreviousDiff.Enabled = ThisInstance.diffControl.CanGoPrevious; - ThisInstance.tsbNextDiff.Enabled = ThisInstance.diffControl.CanGoNext; + /// + /// Gets or sets a value indicating whether the application is going to be closed. + /// + public static bool ApplicationClosing { get; set; } - if (!ThisInstance.Visible) - { - ThisInstance.Show(); - } - } + /// + /// Keep this class a singleton. + /// + private static FormFileDiffView ThisInstance { get; set; } - // set the mode of the diff viewer.. - private void TsbSplitView_Click(object sender, EventArgs e) + /// + /// Displays the form with given file contents. + /// + /// The first file's contents to use with the diff. + /// The second file's contents to use with the diff. + public static void Execute(string diffOne, string diffTwo) + { + if (ThisInstance == null) { - var button = (ToolStripButton) sender; - diffControl.DiffStyle = button.Checked ? DiffStyle.DiffSideBySide : DiffStyle.DiffList; + ThisInstance = new FormFileDiffView(); } - // navigate to the previous difference.. - private void TsbPreviousDiff_Click(object sender, EventArgs e) - { - diffControl.Previous(); - tsbPreviousDiff.Enabled = diffControl.CanGoPrevious; - tsbNextDiff.Enabled = diffControl.CanGoNext; - } + ThisInstance.diffControl.TextLeft = diffOne; + ThisInstance.diffControl.TextRight = diffTwo; - // navigate to the next difference.. - private void TsbNextDiff_Click(object sender, EventArgs e) - { - diffControl.Next(); - tsbPreviousDiff.Enabled = diffControl.CanGoPrevious; - tsbNextDiff.Enabled = diffControl.CanGoNext; - } + ThisInstance.tsbPreviousDiff.Enabled = ThisInstance.diffControl.CanGoPrevious; + ThisInstance.tsbNextDiff.Enabled = ThisInstance.diffControl.CanGoNext; - private void FormFileDiffView_FormClosing(object sender, FormClosingEventArgs e) + if (!ThisInstance.Visible) { - if (!ApplicationClosing) - { - e.Cancel = true; - Hide(); - } + ThisInstance.Show(); } + } + + // set the mode of the diff viewer.. + private void TsbSplitView_Click(object sender, EventArgs e) + { + var button = (ToolStripButton) sender; + diffControl.DiffStyle = button.Checked ? DiffStyle.DiffSideBySide : DiffStyle.DiffList; + } + + // navigate to the previous difference.. + private void TsbPreviousDiff_Click(object sender, EventArgs e) + { + diffControl.Previous(); + tsbPreviousDiff.Enabled = diffControl.CanGoPrevious; + tsbNextDiff.Enabled = diffControl.CanGoNext; + } + + // navigate to the next difference.. + private void TsbNextDiff_Click(object sender, EventArgs e) + { + diffControl.Next(); + tsbPreviousDiff.Enabled = diffControl.CanGoPrevious; + tsbNextDiff.Enabled = diffControl.CanGoNext; + } - private void TsbSwapContents_Click(object sender, EventArgs e) + private void FormFileDiffView_FormClosing(object sender, FormClosingEventArgs e) + { + if (!ApplicationClosing) { - diffControl.SwapDiff(); + e.Cancel = true; + Hide(); } } -} + + private void TsbSwapContents_Click(object sender, EventArgs e) + { + diffControl.SwapDiff(); + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/MiscForms/FormSnippetRunner.cs b/ScriptNotepad/UtilityClasses/MiscForms/FormSnippetRunner.cs index b205ba67..91bbd8ab 100644 --- a/ScriptNotepad/UtilityClasses/MiscForms/FormSnippetRunner.cs +++ b/ScriptNotepad/UtilityClasses/MiscForms/FormSnippetRunner.cs @@ -17,256 +17,255 @@ using ScriptNotepad.UtilityClasses.TextManipulation.Xml; using VPKSoft.LangLib; -namespace ScriptNotepad.UtilityClasses.MiscForms +namespace ScriptNotepad.UtilityClasses.MiscForms; + +/// +/// A floating form to run code snippets or internal text manipulation methods. +/// Implements the +/// +/// +public partial class FormSnippetRunner : DBLangEngineWinforms { /// - /// A floating form to run code snippets or internal text manipulation methods. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormSnippetRunner : DBLangEngineWinforms + private FormSnippetRunner() { - /// - /// Initializes a new instance of the class. - /// - private FormSnippetRunner() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - DBLangEngine.NameSpaces.Add("CustomControls"); + DBLangEngine.NameSpaces.Add("CustomControls"); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - // subscribe the disposed event.. - Disposed += formSnippetRunner_Disposed; - FormSettings.Settings.ShowRunSnippetToolbar = true; - } + // subscribe the disposed event.. + Disposed += formSnippetRunner_Disposed; + FormSettings.Settings.ShowRunSnippetToolbar = true; + } - internal static List Callbacks { get; } = new(); + internal static List Callbacks { get; } = new(); - private static FormSnippetRunner _instance; + private static FormSnippetRunner _instance; - #region InternalProperties - /// - /// Gets or sets the value indicating whether the search combo box is focused. - /// - /// The value indicating whether the search combo box is focused. - internal bool SearchFocused + #region InternalProperties + /// + /// Gets or sets the value indicating whether the search combo box is focused. + /// + /// The value indicating whether the search combo box is focused. + internal bool SearchFocused + { + get => cmbCommands.Focused; + set { - get => cmbCommands.Focused; - set + if (value) { - if (value) - { - cmbCommands.Focus(); - } + cmbCommands.Focus(); } } + } - /// - /// Gets a singleton instance of this form. - /// - internal static FormSnippetRunner Instance - { - get - { - return _instance ??= new FormSnippetRunner(); - } - } - #endregion - - #region PrivateProperties - /// - /// Gets or sets the instance. - /// - /// The instance. - private static StaticMessageLocalizationProvider Translation { get; } = StaticMessageLocalizationProvider.Instance; - - /// - /// Gets the main form instance of the application. - /// - /// The main form instance of the application. - FormMain FormMain => FormMain.Instance; - #endregion - - #region InternalEvents - private async void FormSnippetRunner_KeyDown(object sender, KeyEventArgs e) + /// + /// Gets a singleton instance of this form. + /// + internal static FormSnippetRunner Instance + { + get { - if (e.Control && !e.Alt && !e.Shift && e.KeyCode == Keys.Return) - { - await RunCommand(); - e.SuppressKeyPress = true; - } + return _instance ??= new FormSnippetRunner(); } + } + #endregion - private async void ibRunCommand_Click(object sender, EventArgs e) - { - await RunCommand(); - } + #region PrivateProperties + /// + /// Gets or sets the instance. + /// + /// The instance. + private static StaticMessageLocalizationProvider Translation { get; } = StaticMessageLocalizationProvider.Instance; - private void formSnippetRunner_Disposed(object sender, EventArgs e) - { - // unsubscribe the disposed event.. - Disposed -= formSnippetRunner_Disposed; - _instance = null; - } + /// + /// Gets the main form instance of the application. + /// + /// The main form instance of the application. + FormMain FormMain => FormMain.Instance; + #endregion - private void pnClose_Click(object sender, EventArgs e) + #region InternalEvents + private async void FormSnippetRunner_KeyDown(object sender, KeyEventArgs e) + { + if (e.Control && !e.Alt && !e.Shift && e.KeyCode == Keys.Return) { - FormSettings.Settings.ShowRunSnippetToolbar = false; - Close(); + await RunCommand(); + e.SuppressKeyPress = true; } + } - private void cmbCommands_SelectedValueChanged(object sender, EventArgs e) - { - IndicateError(false); - } + private async void ibRunCommand_Click(object sender, EventArgs e) + { + await RunCommand(); + } - private void FormSnippetRunner_Shown(object sender, EventArgs e) - { - cmbCommands.Items.Clear(); + private void formSnippetRunner_Disposed(object sender, EventArgs e) + { + // unsubscribe the disposed event.. + Disposed -= formSnippetRunner_Disposed; + _instance = null; + } - var items = new List(); - items.AddRange(ScriptNotepadDbContext.DbContext.CodeSnippets.Cast().ToArray()); + private void pnClose_Click(object sender, EventArgs e) + { + FormSettings.Settings.ShowRunSnippetToolbar = false; + Close(); + } - items.Add(new JsonMultilineConvert - { - MethodName = Translation.GetMessage("msgUtilTextPrettifyJson", - "Prettify Json|A message indicating a function to format Json as human-readable.") - }); + private void cmbCommands_SelectedValueChanged(object sender, EventArgs e) + { + IndicateError(false); + } - items.Add(new JsonSingleLineConvert - { - MethodName = Translation.GetMessage("msgUtilTextJsonToOneLine", - "Json to one line|A message indicating a function to human-readable Json to one line.") - }); + private void FormSnippetRunner_Shown(object sender, EventArgs e) + { + cmbCommands.Items.Clear(); - items.Add(new DuplicateLines - { - MethodName = Translation.GetMessage("msgUtilTextRemoveDuplicateLines", - "Remove duplicate lines|A message indicating a function to remove duplicate lines from a file.") - }); + var items = new List(); + items.AddRange(ScriptNotepadDbContext.DbContext.CodeSnippets.Cast().ToArray()); - items.Add(new XmlMultilineConvert - { - MethodName = Translation.GetMessage("msgUtilTextPrettifyXML", - "Prettify XML|A message indicating a function to format XML as human-readable.") - }); + items.Add(new JsonMultilineConvert + { + MethodName = Translation.GetMessage("msgUtilTextPrettifyJson", + "Prettify Json|A message indicating a function to format Json as human-readable."), + }); - items.Add(new XmlSingleLineConvert - { - MethodName = Translation.GetMessage("msgUtilTextXMLToOneLine", - "XML to one line|A message indicating a function to human-readable XML to one line.") - }); + items.Add(new JsonSingleLineConvert + { + MethodName = Translation.GetMessage("msgUtilTextJsonToOneLine", + "Json to one line|A message indicating a function to human-readable Json to one line."), + }); - items.Add(new StringToBase64 - { - MethodName = Translation.GetMessage("msgUtilTextBase64ToString", - "Selected base64 to string|A message indicating a function to convert selected base64 data to string.") - }); + items.Add(new DuplicateLines + { + MethodName = Translation.GetMessage("msgUtilTextRemoveDuplicateLines", + "Remove duplicate lines|A message indicating a function to remove duplicate lines from a file."), + }); - items.Add(new Base64ToString - { - MethodName = Translation.GetMessage("msgUtilStringToBase64", - "Selected string to base64|A message indicating a function to convert human-readable text into a base64 encoded data string.") - }); + items.Add(new XmlMultilineConvert + { + MethodName = Translation.GetMessage("msgUtilTextPrettifyXML", + "Prettify XML|A message indicating a function to format XML as human-readable."), + }); - foreach (var callback in Callbacks) - { - items.Add(callback); - } + items.Add(new XmlSingleLineConvert + { + MethodName = Translation.GetMessage("msgUtilTextXMLToOneLine", + "XML to one line|A message indicating a function to human-readable XML to one line."), + }); - items = items.OrderBy(f => f.ToString()).ToList(); + items.Add(new StringToBase64 + { + MethodName = Translation.GetMessage("msgUtilTextBase64ToString", + "Selected base64 to string|A message indicating a function to convert selected base64 data to string."), + }); + + items.Add(new Base64ToString + { + MethodName = Translation.GetMessage("msgUtilStringToBase64", + "Selected string to base64|A message indicating a function to convert human-readable text into a base64 encoded data string."), + }); - cmbCommands.Items.AddRange(items.ToArray()); + foreach (var callback in Callbacks) + { + items.Add(callback); } - #endregion - #region PrivateMethods + items = items.OrderBy(f => f.ToString()).ToList(); + + cmbCommands.Items.AddRange(items.ToArray()); + } + #endregion - private void IndicateError(bool error) + #region PrivateMethods + + private void IndicateError(bool error) + { + if (cmbCommands.InvokeRequired) { - if (cmbCommands.InvokeRequired) - { - cmbCommands.Invoke(new MethodInvoker(() => - { - cmbCommands.Font = - error - ? new Font(cmbCommands.Font, FontStyle.Bold) - : new Font(cmbCommands.Font, FontStyle.Regular); - cmbCommands.ForeColor = error ? Color.Red : Color.Black; - })); - } - else + cmbCommands.Invoke(new MethodInvoker(() => { cmbCommands.Font = error ? new Font(cmbCommands.Font, FontStyle.Bold) : new Font(cmbCommands.Font, FontStyle.Regular); cmbCommands.ForeColor = error ? Color.Red : Color.Black; - } + })); + } + else + { + cmbCommands.Font = + error + ? new Font(cmbCommands.Font, FontStyle.Bold) + : new Font(cmbCommands.Font, FontStyle.Regular); + cmbCommands.ForeColor = error ? Color.Red : Color.Black; } + } - private async Task RunCommand() + private async Task RunCommand() + { + if (cmbCommands.SelectedItem != null && FormMain.ActiveScintilla != null) { - if (cmbCommands.SelectedItem != null && FormMain.ActiveScintilla != null) + if (cmbCommands.SelectedItem is CodeSnippet codeSnippet) { - if (cmbCommands.SelectedItem is CodeSnippet codeSnippet) + if (codeSnippet.ScriptTextManipulationType == ScriptSnippetType.Text) { - if (codeSnippet.ScriptTextManipulationType == ScriptSnippetType.Text) - { - var result = await CsScriptRunnerText.RunScriptText(codeSnippet.ScriptContents, - FormMain.ActiveScintilla.Text); - - if (result.Value) - { - FormMain.ActiveScintilla.Text = result.Key; - } - - IndicateError(!result.Value); - } + var result = await CsScriptRunnerText.RunScriptText(codeSnippet.ScriptContents, + FormMain.ActiveScintilla.Text); - if (codeSnippet.ScriptTextManipulationType == ScriptSnippetType.Lines) + if (result.Value) { - var result = await CsScriptRunnerText.RunScriptLines(codeSnippet.ScriptContents, - FormMain.ActiveScintilla.Lines.Select(f => f.Text).ToList()); - - if (result.Value) - { - FormMain.ActiveScintilla.Text = result.Key; - } - IndicateError(!result.Value); + FormMain.ActiveScintilla.Text = result.Key; } + + IndicateError(!result.Value); } - if (cmbCommands.SelectedItem is ITextManipulationCommand command) + if (codeSnippet.ScriptTextManipulationType == ScriptSnippetType.Lines) { - if (command.PreferSelectedText) - { - FormMain.ActiveScintilla.SelectionReplaceWithValue( - command.Manipulate(FormMain.ActiveScintilla.SelectedText)); - } - else + var result = await CsScriptRunnerText.RunScriptLines(codeSnippet.ScriptContents, + FormMain.ActiveScintilla.Lines.Select(f => f.Text).ToList()); + + if (result.Value) { - FormMain.ActiveScintilla.Text = command.Manipulate(FormMain.ActiveScintilla.Text); + FormMain.ActiveScintilla.Text = result.Key; } + IndicateError(!result.Value); } + } - if (cmbCommands.SelectedItem is ITextManipulationCallback callback) + if (cmbCommands.SelectedItem is ITextManipulationCommand command) + { + if (command.PreferSelectedText) { - callback.CallbackAction?.Invoke(); + FormMain.ActiveScintilla.SelectionReplaceWithValue( + command.Manipulate(FormMain.ActiveScintilla.SelectedText)); } + else + { + FormMain.ActiveScintilla.Text = command.Manipulate(FormMain.ActiveScintilla.Text); + } + } + + if (cmbCommands.SelectedItem is ITextManipulationCallback callback) + { + callback.CallbackAction?.Invoke(); } } - #endregion } -} + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Process/ProcessElevation.cs b/ScriptNotepad/UtilityClasses/Process/ProcessElevation.cs index 37d91329..8e37ffbb 100644 --- a/ScriptNotepad/UtilityClasses/Process/ProcessElevation.cs +++ b/ScriptNotepad/UtilityClasses/Process/ProcessElevation.cs @@ -26,20 +26,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Security.Principal; -namespace ScriptNotepad.UtilityClasses.Process +namespace ScriptNotepad.UtilityClasses.Process; + +/// +/// A class for detecting if the process is running elevated. +/// +public static class ProcessElevation { /// - /// A class for detecting if the process is running elevated. + /// Gets a value indicating whether the current process is running with elevated privileges. /// - public static class ProcessElevation + public static bool IsElevated { - /// - /// Gets a value indicating whether the current process is running with elevated privileges. - /// - public static bool IsElevated - { - // (C): https://www.cyotek.com/blog/detecting-if-an-application-is-running-as-an-elevated-process-and-spawning-a-new-process-using-elevated-permissions - get => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); - } + // (C): https://www.cyotek.com/blog/detecting-if-an-application-is-running-as-an-elevated-process-and-spawning-a-new-process-using-elevated-permissions + get => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageHelper.cs b/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageHelper.cs index 85d753a2..b35398dc 100644 --- a/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageHelper.cs +++ b/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageHelper.cs @@ -31,286 +31,285 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using static VPKSoft.ScintillaLexers.LexerEnumerations; -namespace ScriptNotepad.UtilityClasses.ProgrammingLanguages +namespace ScriptNotepad.UtilityClasses.ProgrammingLanguages; + +/// +/// A class to help build a programming language selection menu. +/// +[SuppressMessage("ReSharper", "StringLiteralTypo")] +public class ProgrammingLanguageHelper: IDisposable { /// - /// A class to help build a programming language selection menu. + /// Creates the programming language selection menu. /// - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public class ProgrammingLanguageHelper: IDisposable + /// The menu strip to create the programming language menu to. + /// A flag indicating whether to categorize the programming languages in to drop-down menu items based on the language name first character. + public ProgrammingLanguageHelper(ToolStripMenuItem languageMenuStrip, bool withFirstChar) { - /// - /// Creates the programming language selection menu. - /// - /// The menu strip to create the programming language menu to. - /// A flag indicating whether to categorize the programming languages in to drop-down menu items based on the language name first character. - public ProgrammingLanguageHelper(ToolStripMenuItem languageMenuStrip, bool withFirstChar) - { - menuStrip = languageMenuStrip; + menuStrip = languageMenuStrip; - // dispose of the possible previous menu.. - DisposePreviousMenu(); + // dispose of the possible previous menu.. + DisposePreviousMenu(); - menuClickLanguage = delegate(object sender, EventArgs args) - { - var lexer = (LexerType) ((ToolStripMenuItem) sender).Tag; - LanguageMenuClick?.Invoke(sender, new ProgrammingLanguageMenuClickEventArgs() {LexerType = lexer}); - }; + menuClickLanguage = delegate(object sender, EventArgs args) + { + var lexer = (LexerType) ((ToolStripMenuItem) sender).Tag; + LanguageMenuClick?.Invoke(sender, new ProgrammingLanguageMenuClickEventArgs() {LexerType = lexer, }); + }; - // get the listed programming languages and their starting characters.. - var languages = LexersList - .Select(f => (f.programmingLanguageName, f.lexerType, f.programmingLanguageName.ToUpperInvariant()[0])) - .OrderBy(f => f.Item3.ToString()).ThenBy(f => f.programmingLanguageName.ToLowerInvariant()); + // get the listed programming languages and their starting characters.. + var languages = LexersList + .Select(f => (f.programmingLanguageName, f.lexerType, f.programmingLanguageName.ToUpperInvariant()[0])) + .OrderBy(f => f.Item3.ToString()).ThenBy(f => f.programmingLanguageName.ToLowerInvariant()); - // initialize a list of used characters to be used if the withFirstChar parameter is set to true.. - List<(char startChar, ToolStripMenuItem charItem)> usedCharMenus = new List<(char startChar, ToolStripMenuItem charItem)>(); + // initialize a list of used characters to be used if the withFirstChar parameter is set to true.. + List<(char startChar, ToolStripMenuItem charItem)> usedCharMenus = new List<(char startChar, ToolStripMenuItem charItem)>(); - // loop through the list of languages.. - foreach (var language in languages) + // loop through the list of languages.. + foreach (var language in languages) + { + // if the parameter is set to true.. + if (withFirstChar) { - // if the parameter is set to true.. - if (withFirstChar) + // find the starting char category menu item.. + int idx = usedCharMenus.FindIndex(f => f.startChar == language.Item3); + if (idx == -1) { - // find the starting char category menu item.. - int idx = usedCharMenus.FindIndex(f => f.startChar == language.Item3); - if (idx == -1) - { - // if not found, then create a new char category menu item.. - usedCharMenus.Add((language.Item3, new ToolStripMenuItem(language.Item3.ToString()))); - idx = usedCharMenus.FindIndex(f => f.startChar == language.Item3); + // if not found, then create a new char category menu item.. + usedCharMenus.Add((language.Item3, new ToolStripMenuItem(language.Item3.ToString()))); + idx = usedCharMenus.FindIndex(f => f.startChar == language.Item3); - // add the character menu to the given tool strip menu item's drop down menu collection.. - languageMenuStrip.DropDownItems.Add(usedCharMenus[idx].charItem); - } + // add the character menu to the given tool strip menu item's drop down menu collection.. + languageMenuStrip.DropDownItems.Add(usedCharMenus[idx].charItem); + } - // add the language menu to the category menu item's drop down menu collection.. - usedCharMenus[idx].charItem.DropDownItems - .Add(new ToolStripMenuItem(language.programmingLanguageName, null, menuClickLanguage) - {Tag = language.lexerType, CheckOnClick = true}); - } - else - { - // add the language menu to the given tool strip menu item's drop down menu collection.. - languageMenuStrip.DropDownItems - .Add(new ToolStripMenuItem(language.programmingLanguageName, null, menuClickLanguage) - {Tag = language.lexerType, CheckOnClick = true}); - } + // add the language menu to the category menu item's drop down menu collection.. + usedCharMenus[idx].charItem.DropDownItems + .Add(new ToolStripMenuItem(language.programmingLanguageName, null, menuClickLanguage) + {Tag = language.lexerType, CheckOnClick = true, }); + } + else + { + // add the language menu to the given tool strip menu item's drop down menu collection.. + languageMenuStrip.DropDownItems + .Add(new ToolStripMenuItem(language.programmingLanguageName, null, menuClickLanguage) + {Tag = language.lexerType, CheckOnClick = true, }); } } + } - /// - /// Finds and checks the menu item(s) with the given . - /// - /// Type of the lexer of which corresponding menu item(s) to check. - public void CheckLanguage(LexerType lexerType) + /// + /// Finds and checks the menu item(s) with the given . + /// + /// Type of the lexer of which corresponding menu item(s) to check. + public void CheckLanguage(LexerType lexerType) + { + ToolStripMenuItem checkMainMenuItem = null; + foreach (ToolStripMenuItem menuItem in menuStrip.DropDownItems) { - ToolStripMenuItem checkMainMenuItem = null; - foreach (ToolStripMenuItem menuItem in menuStrip.DropDownItems) + foreach (ToolStripMenuItem subMenuItem in menuItem.DropDownItems) { - foreach (ToolStripMenuItem subMenuItem in menuItem.DropDownItems) - { - // check or un-check the menu item.. - if (subMenuItem.Tag != null && subMenuItem.Tag.GetType() == typeof(LexerType)) - { - var menuLexerType = (LexerType) subMenuItem.Tag; - - subMenuItem.Checked = menuLexerType == lexerType; - if (menuLexerType == lexerType) - { - // this gets unchecked in drop down styled menu, so save it for later.. - checkMainMenuItem = menuItem; - } - } - else - { - subMenuItem.Checked = false; - } - } - // check or un-check the menu item.. - if (menuItem.Tag != null && menuItem.Tag.GetType() == typeof(LexerType)) + if (subMenuItem.Tag != null && subMenuItem.Tag.GetType() == typeof(LexerType)) { - var menuLexerType = (LexerType) menuItem.Tag; + var menuLexerType = (LexerType) subMenuItem.Tag; - menuItem.Checked = menuLexerType == lexerType; + subMenuItem.Checked = menuLexerType == lexerType; + if (menuLexerType == lexerType) + { + // this gets unchecked in drop down styled menu, so save it for later.. + checkMainMenuItem = menuItem; + } } else { - menuItem.Checked = false; + subMenuItem.Checked = false; } } - // if a menu item was assigned to be checked.. - if (checkMainMenuItem != null) + // check or un-check the menu item.. + if (menuItem.Tag != null && menuItem.Tag.GetType() == typeof(LexerType)) { - // ..check it.. - checkMainMenuItem.Checked = true; - } - } + var menuLexerType = (LexerType) menuItem.Tag; - /// - /// Disposes of the previous programming language menu. - /// - private void DisposePreviousMenu() - { - foreach (ToolStripMenuItem menuItem in menuStrip.DropDownItems) + menuItem.Checked = menuLexerType == lexerType; + } + else { - foreach (ToolStripMenuItem subMenuItem in menuItem.DropDownItems) - { - // unsubscribe the click event.. - subMenuItem.Click -= menuClickLanguage; - } - menuItem.DropDownItems.Clear(); - - // unsubscribe the click event.. - menuItem.Click -= menuClickLanguage; + menuItem.Checked = false; } - menuStrip.DropDownItems.Clear(); } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + // if a menu item was assigned to be checked.. + if (checkMainMenuItem != null) { - Dispose(true); - GC.SuppressFinalize(this); + // ..check it.. + checkMainMenuItem.Checked = true; } + } - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) + /// + /// Disposes of the previous programming language menu. + /// + private void DisposePreviousMenu() + { + foreach (ToolStripMenuItem menuItem in menuStrip.DropDownItems) { - if (disposing) + foreach (ToolStripMenuItem subMenuItem in menuItem.DropDownItems) { - DisposePreviousMenu(); + // unsubscribe the click event.. + subMenuItem.Click -= menuClickLanguage; } + menuItem.DropDownItems.Clear(); + + // unsubscribe the click event.. + menuItem.Click -= menuClickLanguage; } + menuStrip.DropDownItems.Clear(); + } + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + DisposePreviousMenu(); + } + } - private readonly ToolStripMenuItem menuStrip; - /// - /// A click handler for the menu programming language items. - /// - private readonly EventHandler menuClickLanguage; - /// A delegate for the event. - /// The sender. - /// The instance containing the event data. - public delegate void OnLanguageMenuClick(object sender, ProgrammingLanguageMenuClickEventArgs e); + private readonly ToolStripMenuItem menuStrip; - /// - /// Occurs when the user clicked a programming language menu item. - /// - public event OnLanguageMenuClick LanguageMenuClick; + /// + /// A click handler for the menu programming language items. + /// + private readonly EventHandler menuClickLanguage; - /// - /// Gets or sets the with the specified lexer type. - /// - /// Type of the lexer. - /// System.String. - public string this[LexerType lexerType] - { - // no need to validate anything.. - get => LexersList.FirstOrDefault(f => f.lexerType == lexerType).programmingLanguageName; + /// A delegate for the event. + /// The sender. + /// The instance containing the event data. + public delegate void OnLanguageMenuClick(object sender, ProgrammingLanguageMenuClickEventArgs e); + + /// + /// Occurs when the user clicked a programming language menu item. + /// + public event OnLanguageMenuClick LanguageMenuClick; + + /// + /// Gets or sets the with the specified lexer type. + /// + /// Type of the lexer. + /// System.String. + public string this[LexerType lexerType] + { + // no need to validate anything.. + get => LexersList.FirstOrDefault(f => f.lexerType == lexerType).programmingLanguageName; - set + set + { + // validate the name for the language.. + if (string.IsNullOrWhiteSpace(value)) { - // validate the name for the language.. - if (string.IsNullOrWhiteSpace(value)) - { - return; - } + return; + } - // find the index for the language from the list of lexer types and their names.. - int idx = LexersList.FindIndex(f => f.lexerType == lexerType); - if (idx != -1) // if an index was found.. - { - // ..set the new value.. - LexersList[idx] = (lexerType, value); - } + // find the index for the language from the list of lexer types and their names.. + int idx = LexersList.FindIndex(f => f.lexerType == lexerType); + if (idx != -1) // if an index was found.. + { + // ..set the new value.. + LexersList[idx] = (lexerType, value); } } + } - /// - /// A list of localizable lexer names with their corresponding enumeration values. - /// - public List<(LexerType lexerType, string - programmingLanguageName)> LexersList { get; set; } = - new List<(LexerType lexerType, string programmingLanguageName)> - (new[] - { - (LexerType.Batch, - DBLangEngine.GetStatMessage("msgProgrammingBatch", - "Batch script file|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Cpp, - DBLangEngine.GetStatMessage("msgProgrammingCpp", - "C++ programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Cs, - DBLangEngine.GetStatMessage("msgProgrammingCs", - "C# programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.HTML, - DBLangEngine.GetStatMessage("msgProgrammingHtml", - "HTML (Hypertext Markup Language)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.INI, - DBLangEngine.GetStatMessage("msgProgrammingIni", - "INI properties file|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Nsis, - DBLangEngine.GetStatMessage("msgProgrammingNsis", - "NSIS (Nullsoft Scriptable Install System)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Pascal, - DBLangEngine.GetStatMessage("msgProgrammingPascal", - "Pascal programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.PHP, - DBLangEngine.GetStatMessage("msgProgrammingPHP", - "PHP programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.INI, - DBLangEngine.GetStatMessage("msgProgrammingIni2", - "Properties file (INI)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Python, - DBLangEngine.GetStatMessage("msgProgrammingPython", - "Python programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.SQL, - DBLangEngine.GetStatMessage("msgProgrammingSQL", - "SQL (Structured Query Language)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Text, - DBLangEngine.GetStatMessage("msgProgrammingText", - "Plain text document|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Unknown, - DBLangEngine.GetStatMessage("msgProgrammingUnknown", - "Unknown|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.WindowsPowerShell, - DBLangEngine.GetStatMessage("msgProgrammingWindowsPowerShell", - "WindowsPowerShell|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Xml, - DBLangEngine.GetStatMessage("msgProgrammingXML", - "XML (eXtensible Markup Language)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.YAML, - DBLangEngine.GetStatMessage("msgProgrammingYAML", - "YAML (YAML Ain't Markup Language)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Text, - DBLangEngine.GetStatMessage("msgProgrammingText2", - "Text document (plain)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Java, - DBLangEngine.GetStatMessage("msgProgrammingJava", - "Java programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.JavaScript, - DBLangEngine.GetStatMessage("msgProgrammingJavaScript", - "JavaScript programming language|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Css, - DBLangEngine.GetStatMessage("msgProgrammingCss", - "Cascading Style Sheets (CSS)|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.InnoSetup, - DBLangEngine.GetStatMessage("msgProgrammingInnoSetup", - "InnoSetup installer script|A programming, markup, setting, script or other file and/or language/text")), - (LexerType.Json, + /// + /// A list of localizable lexer names with their corresponding enumeration values. + /// + public List<(LexerType lexerType, string + programmingLanguageName)> LexersList { get; set; } = + new List<(LexerType lexerType, string programmingLanguageName)> + (new[] + { + (LexerType.Batch, + DBLangEngine.GetStatMessage("msgProgrammingBatch", + "Batch script file|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Cpp, + DBLangEngine.GetStatMessage("msgProgrammingCpp", + "C++ programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Cs, + DBLangEngine.GetStatMessage("msgProgrammingCs", + "C# programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.HTML, + DBLangEngine.GetStatMessage("msgProgrammingHtml", + "HTML (Hypertext Markup Language)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.INI, + DBLangEngine.GetStatMessage("msgProgrammingIni", + "INI properties file|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Nsis, + DBLangEngine.GetStatMessage("msgProgrammingNsis", + "NSIS (Nullsoft Scriptable Install System)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Pascal, + DBLangEngine.GetStatMessage("msgProgrammingPascal", + "Pascal programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.PHP, + DBLangEngine.GetStatMessage("msgProgrammingPHP", + "PHP programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.INI, + DBLangEngine.GetStatMessage("msgProgrammingIni2", + "Properties file (INI)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Python, + DBLangEngine.GetStatMessage("msgProgrammingPython", + "Python programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.SQL, + DBLangEngine.GetStatMessage("msgProgrammingSQL", + "SQL (Structured Query Language)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Text, + DBLangEngine.GetStatMessage("msgProgrammingText", + "Plain text document|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Unknown, + DBLangEngine.GetStatMessage("msgProgrammingUnknown", + "Unknown|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.WindowsPowerShell, + DBLangEngine.GetStatMessage("msgProgrammingWindowsPowerShell", + "WindowsPowerShell|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Xml, + DBLangEngine.GetStatMessage("msgProgrammingXML", + "XML (eXtensible Markup Language)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.YAML, + DBLangEngine.GetStatMessage("msgProgrammingYAML", + "YAML (YAML Ain't Markup Language)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Text, + DBLangEngine.GetStatMessage("msgProgrammingText2", + "Text document (plain)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Java, + DBLangEngine.GetStatMessage("msgProgrammingJava", + "Java programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.JavaScript, + DBLangEngine.GetStatMessage("msgProgrammingJavaScript", + "JavaScript programming language|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Css, + DBLangEngine.GetStatMessage("msgProgrammingCss", + "Cascading Style Sheets (CSS)|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.InnoSetup, + DBLangEngine.GetStatMessage("msgProgrammingInnoSetup", + "InnoSetup installer script|A programming, markup, setting, script or other file and/or language/text")), + (LexerType.Json, DBLangEngine.GetStatMessage("msgProgrammingJson", "Json (JavaScript Object Notation)|A programming, markup, setting, script or other file and/or language/text")), - }); - } -} + }); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageMenuClickEventArgs.cs b/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageMenuClickEventArgs.cs index 86ffbcd8..3ba1ffb3 100644 --- a/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageMenuClickEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/ProgrammingLanguages/ProgrammingLanguageMenuClickEventArgs.cs @@ -26,18 +26,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using static VPKSoft.ScintillaLexers.LexerEnumerations; -namespace ScriptNotepad.UtilityClasses.ProgrammingLanguages +namespace ScriptNotepad.UtilityClasses.ProgrammingLanguages; + +/// +/// A class for event arguments to the event. +/// Implements the +/// +/// +public class ProgrammingLanguageMenuClickEventArgs: EventArgs { /// - /// A class for event arguments to the event. - /// Implements the + /// Gets or sets the type of the lexer. /// - /// - public class ProgrammingLanguageMenuClickEventArgs: EventArgs - { - /// - /// Gets or sets the type of the lexer. - /// - public LexerType LexerType { get; set; } - } -} + public LexerType LexerType { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaFold.cs b/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaFold.cs index 72eceae2..eaf378c1 100644 --- a/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaFold.cs +++ b/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaFold.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,80 +28,79 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.ScintillaHelpers +namespace ScriptNotepad.UtilityClasses.ScintillaHelpers; + +/// +/// A class to save and restore the folding state of the document. +/// +public static class ScintillaFold { /// - /// A class to save and restore the folding state of the document. + /// Saves the folding state of the document. /// - public static class ScintillaFold + /// The document. + /// A string containing the folding state data. + public static string SaveFolding(this Scintilla scintilla) { - /// - /// Saves the folding state of the document. - /// - /// The document. - /// A string containing the folding state data. - public static string SaveFolding(this Scintilla scintilla) + try { - try + var builder = new StringBuilder(); + for (int i = 0; i < scintilla.Lines.Count; i++) { - var builder = new StringBuilder(); - for (int i = 0; i < scintilla.Lines.Count; i++) + if (!scintilla.Lines[i].Expanded) { - if (!scintilla.Lines[i].Expanded) - { - builder.AppendFormat("{0}|{1};", i, - scintilla.Lines[i].Expanded); // this is useless for now, but keep the possibility open.. - } + builder.AppendFormat("{0}|{1};", i, + scintilla.Lines[i].Expanded); // this is useless for now, but keep the possibility open.. } + } - var result = builder.ToString().TrimEnd(';'); + var result = builder.ToString().TrimEnd(';'); - return result; - } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return string.Empty; - } + return result; + } + catch (Exception ex) + { + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return string.Empty; } + } - /// - /// Restores the folding state of the document. - /// - /// The document. - /// The string containing the folding state data. - public static void RestoreFolding(this Scintilla scintilla, string foldSave) + /// + /// Restores the folding state of the document. + /// + /// The document. + /// The string containing the folding state data. + public static void RestoreFolding(this Scintilla scintilla, string foldSave) + { + try { - try + if (string.IsNullOrWhiteSpace(foldSave)) { - if (string.IsNullOrWhiteSpace(foldSave)) - { - return; - } + return; + } - var saveValues = foldSave.Split(';').Select(f => new {Array = f.Split('|')}).Select(f => new - { - Line = int.Parse(f.Array[0]), - Expanded = bool.Parse(f.Array[1]) // this is useless for now, but keep the possibility open.. - }).ToList(); + var saveValues = foldSave.Split(';').Select(f => new {Array = f.Split('|'), }).Select(f => new + { + Line = int.Parse(f.Array[0]), + Expanded = bool.Parse(f.Array[1]), // this is useless for now, but keep the possibility open.. + }).ToList(); - for (int i = scintilla.Lines.Count - 1; i >= 0; i--) + for (int i = scintilla.Lines.Count - 1; i >= 0; i--) + { + var save = saveValues.FirstOrDefault(f => f.Line == i); + if (save != null && !save.Expanded) { - var save = saveValues.FirstOrDefault(f => f.Line == i); - if (save != null && !save.Expanded) - { - scintilla.Lines[i].FoldLine(FoldAction.Contract); - } - else - { - scintilla.Lines[i].FoldLine(FoldAction.Expand); - } + scintilla.Lines[i].FoldLine(FoldAction.Contract); + } + else + { + scintilla.Lines[i].FoldLine(FoldAction.Expand); } } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - } + } + catch (Exception ex) + { + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaLines.cs b/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaLines.cs index 110e7c0e..0083b53b 100644 --- a/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaLines.cs +++ b/ScriptNotepad/UtilityClasses/ScintillaHelpers/ScintillaLines.cs @@ -27,54 +27,53 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Collections.Generic; using ScintillaNET; -namespace ScriptNotepad.UtilityClasses.ScintillaHelpers +namespace ScriptNotepad.UtilityClasses.ScintillaHelpers; + +/// +/// A helper class to manipulate a Scintilla document lines as a list of strings. +/// +public static class ScintillaLines { /// - /// A helper class to manipulate a Scintilla document lines as a list of strings. + /// Gets the lines of a Scintilla as list of strings. /// - public static class ScintillaLines + /// The Scintilla to get the line contents from. + /// A list of strings of the lines of a Scintilla. + public static List GetLinesAsList(Scintilla scintilla) { - /// - /// Gets the lines of a Scintilla as list of strings. - /// - /// The Scintilla to get the line contents from. - /// A list of strings of the lines of a Scintilla. - public static List GetLinesAsList(Scintilla scintilla) + List result = new List(); + for (int i = 0; i < scintilla.Lines.Count; i++) { - List result = new List(); - for (int i = 0; i < scintilla.Lines.Count; i++) - { - result.Add(scintilla.Lines[i].Text); - } - return result; + result.Add(scintilla.Lines[i].Text); } + return result; + } - /// - /// Sets the lines of a Scintilla document from a given list of strings. - /// - /// A Scintilla document of which lines to set. - /// A list of strings to be used to set the Scintilla document's contents from. - /// A line ending string to append to a string with no line ending. - public static void SetLinesFromList(Scintilla scintilla, List lines, string lineEnding) + /// + /// Sets the lines of a Scintilla document from a given list of strings. + /// + /// A Scintilla document of which lines to set. + /// A list of strings to be used to set the Scintilla document's contents from. + /// A line ending string to append to a string with no line ending. + public static void SetLinesFromList(Scintilla scintilla, List lines, string lineEnding) + { + // ensure that the lines have a line ending.. + for (int i = 0; i < lines.Count; i++) { - // ensure that the lines have a line ending.. - for (int i = 0; i < lines.Count; i++) + // check for a possible line endings (not sure if the "\r\n" is valid).. + if (lines[i].EndsWith("\n") || + lines[i].EndsWith("\r") || + lines[i].EndsWith("\n\r") || + lines[i].EndsWith("\r\n")) { - // check for a possible line endings (not sure if the "\r\n" is valid).. - if (lines[i].EndsWith("\n") || - lines[i].EndsWith("\r") || - lines[i].EndsWith("\n\r") || - lines[i].EndsWith("\r\n")) - { - continue; // a line ending was found so do continue.. - } - - // a line ending wasn't found so give it a line ending.. - lines[i] = lines[i] + lineEnding; + continue; // a line ending was found so do continue.. } - // concatenate the lines and set the contents of the Scintilla document.. - scintilla.Text = string.Concat(lines); + // a line ending wasn't found so give it a line ending.. + lines[i] = lines[i] + lineEnding; } + + // concatenate the lines and set the contents of the Scintilla document.. + scintilla.Text = string.Concat(lines); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ScintillaNETUtils/ScintillaContextMenu.cs b/ScriptNotepad/UtilityClasses/ScintillaNETUtils/ScintillaContextMenu.cs index fb3f5308..ec9b8c33 100644 --- a/ScriptNotepad/UtilityClasses/ScintillaNETUtils/ScintillaContextMenu.cs +++ b/ScriptNotepad/UtilityClasses/ScintillaNETUtils/ScintillaContextMenu.cs @@ -33,363 +33,362 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // (C)::Loosely based on the article: https://github.com/jacobslusser/ScintillaNET/issues/334 -namespace ScriptNotepad.UtilityClasses.ScintillaNETUtils +namespace ScriptNotepad.UtilityClasses.ScintillaNETUtils; + +/// +/// A class used internally by the class for data passing. +/// +public class ToolStripTagItem { /// - /// A class used internally by the class for data passing. + /// Gets or sets the function identifier as an integer. /// - public class ToolStripTagItem - { - /// - /// Gets or sets the function identifier as an integer. - /// - public int FunctionId { get; set; } - - /// - /// Gets or sets the . - /// - public Scintilla Scintilla { get; set; } - - /// - /// Gets or sets the object that contains additional data for the . - /// - public object Tag { get; set; } - - /// - /// Gets or sets the object that contains additional data for the . - /// - public object Tag0 { get; set; } - } + public int FunctionId { get; set; } + + /// + /// Gets or sets the . + /// + public Scintilla Scintilla { get; set; } + + /// + /// Gets or sets the object that contains additional data for the . + /// + public object Tag { get; set; } + + /// + /// Gets or sets the object that contains additional data for the . + /// + public object Tag0 { get; set; } +} + +/// +/// A helper class to create a modifiable context a menu to a class. +/// +public class ScintillaContextMenu +{ + /// + /// Gets or sets the text for undo tool strip menu item for localization. + /// + public static string TextUndo { get; set; } = "Undo"; + + /// + /// Gets or sets the text for redo tool strip menu item for localization. + /// + public static string TextRedo { get; set; } = "Redo"; + + /// + /// Gets or sets the text for copy tool strip menu item for localization. + /// + public static string TextCopy { get; set; } = "Copy"; + + + /// + /// Gets or sets the text for cut tool strip menu item for localization. + /// + public static string TextCut { get; set; } = "Cut"; /// - /// A helper class to create a modifiable context a menu to a class. + /// Gets or sets the text for paste tool strip menu item for localization. /// - public class ScintillaContextMenu + public static string TextPaste { get; set; } = "Paste"; + + /// + /// Gets or sets the text for delete tool strip menu item for localization. + /// + public static string TextDelete { get; set; } = "Delete"; + + /// + /// Gets or sets the text for select all tool strip menu item for localization. + /// + public static string TextSelectAll { get; set; } = "Select All"; + + /// + /// Gets or sets the text for picking a color from a hex string value for a tool strip menu item for localization. + /// + public static string TextHexadecimalColor { get; set; } = "Pick a color"; + + /// + /// Gets or sets the text for inserting a special character to the document. + /// + public static string TextInsertSpecialCharacter { get; set; } = "Insert special character..."; + + + /// + /// Localizes the texts used to build the with the method. + /// This should be called before any context menu strips have been created but after the has been initialized. + /// + public static void LocalizeTexts() { - /// - /// Gets or sets the text for undo tool strip menu item for localization. - /// - public static string TextUndo { get; set; } = "Undo"; - - /// - /// Gets or sets the text for redo tool strip menu item for localization. - /// - public static string TextRedo { get; set; } = "Redo"; - - /// - /// Gets or sets the text for copy tool strip menu item for localization. - /// - public static string TextCopy { get; set; } = "Copy"; - - - /// - /// Gets or sets the text for cut tool strip menu item for localization. - /// - public static string TextCut { get; set; } = "Cut"; - - /// - /// Gets or sets the text for paste tool strip menu item for localization. - /// - public static string TextPaste { get; set; } = "Paste"; - - /// - /// Gets or sets the text for delete tool strip menu item for localization. - /// - public static string TextDelete { get; set; } = "Delete"; - - /// - /// Gets or sets the text for select all tool strip menu item for localization. - /// - public static string TextSelectAll { get; set; } = "Select All"; - - /// - /// Gets or sets the text for picking a color from a hex string value for a tool strip menu item for localization. - /// - public static string TextHexadecimalColor { get; set; } = "Pick a color"; - - /// - /// Gets or sets the text for inserting a special character to the document. - /// - public static string TextInsertSpecialCharacter { get; set; } = "Insert special character..."; - - - /// - /// Localizes the texts used to build the with the method. - /// This should be called before any context menu strips have been created but after the has been initialized. - /// - public static void LocalizeTexts() - { - TextUndo = DBLangEngine.GetStatMessage("msgContextUndo", - "Undo|A message for a context menu to describe an undo action"); + TextUndo = DBLangEngine.GetStatMessage("msgContextUndo", + "Undo|A message for a context menu to describe an undo action"); - TextRedo = DBLangEngine.GetStatMessage("msgContextRedo", - "Redo|A message for a context menu to describe a redo action"); + TextRedo = DBLangEngine.GetStatMessage("msgContextRedo", + "Redo|A message for a context menu to describe a redo action"); - TextCut = DBLangEngine.GetStatMessage("msgContextCut", - "Cut|A message for a context menu to describe a cut action"); + TextCut = DBLangEngine.GetStatMessage("msgContextCut", + "Cut|A message for a context menu to describe a cut action"); - TextCopy = DBLangEngine.GetStatMessage("msgContextCopy", - "Copy|A message for a context menu to describe a copy action"); + TextCopy = DBLangEngine.GetStatMessage("msgContextCopy", + "Copy|A message for a context menu to describe a copy action"); - TextPaste = DBLangEngine.GetStatMessage("msgContextPaste", - "Paste|A message for a context menu to describe a paste action"); + TextPaste = DBLangEngine.GetStatMessage("msgContextPaste", + "Paste|A message for a context menu to describe a paste action"); - TextDelete = DBLangEngine.GetStatMessage("msgContextDelete", - "Delete|A message for a context menu to describe a delete text action"); + TextDelete = DBLangEngine.GetStatMessage("msgContextDelete", + "Delete|A message for a context menu to describe a delete text action"); - TextSelectAll = DBLangEngine.GetStatMessage("msgContextSelectAll", - "Select All|A message for a context menu to describe a select all text action"); + TextSelectAll = DBLangEngine.GetStatMessage("msgContextSelectAll", + "Select All|A message for a context menu to describe a select all text action"); - TextHexadecimalColor = DBLangEngine.GetStatMessage("msgPickAColor", - "Pick a color|A message for a context menu to describe a hexadecimal color in the text file converted to a color"); + TextHexadecimalColor = DBLangEngine.GetStatMessage("msgPickAColor", + "Pick a color|A message for a context menu to describe a hexadecimal color in the text file converted to a color"); - TextInsertSpecialCharacter = DBLangEngine.GetStatMessage("msgInsertSpecialCharacter", - "Insert special character...|A message for a context menu to describe drop down menu items to insert a special character into the document"); - } + TextInsertSpecialCharacter = DBLangEngine.GetStatMessage("msgInsertSpecialCharacter", + "Insert special character...|A message for a context menu to describe drop down menu items to insert a special character into the document"); + } - /// - /// Creates the basic localized context menu strip for a given . - /// - /// The Scintilla to add the to. - /// An action which is called when the menu invokes undo action for the . - /// An action which is called when the menu invokes redo action for the . - /// The created . - public static ContextMenuStrip CreateBasicContextMenuStrip(Scintilla scintilla, Action onUndo, Action onRedo) - { - // initialize a new instance of a ContextMenuStrip class with Tag property - // value of the given Scintilla instance as a parameter.. - ContextMenuStrip contextMenu = new ContextMenuStrip() {Tag = scintilla}; + /// + /// Creates the basic localized context menu strip for a given . + /// + /// The Scintilla to add the to. + /// An action which is called when the menu invokes undo action for the . + /// An action which is called when the menu invokes redo action for the . + /// The created . + public static ContextMenuStrip CreateBasicContextMenuStrip(Scintilla scintilla, Action onUndo, Action onRedo) + { + // initialize a new instance of a ContextMenuStrip class with Tag property + // value of the given Scintilla instance as a parameter.. + ContextMenuStrip contextMenu = new ContextMenuStrip() {Tag = scintilla, }; - // create an undo ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextUndo, null, - (sender, e) => - { - var tagItem = ((ToolStripTagItem) ((ToolStripItem) sender).Tag); - tagItem.Scintilla.Undo(); - onUndo(tagItem.Scintilla); - }) - {Tag = new ToolStripTagItem {FunctionId = 0, Scintilla = scintilla}}); - - // create a redo ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextRedo, null, - (sender, e) => - { - var tagItem = ((ToolStripTagItem) ((ToolStripItem) sender).Tag); - tagItem.Scintilla.Redo(); - onRedo(tagItem.Scintilla); - }) - {Tag = new ToolStripTagItem {FunctionId = 1, Scintilla = scintilla}}); - - // create a tool strip separator.. - contextMenu.Items.Add(new ToolStripSeparator()); - - // create a copy ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextCopy, null, - (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.Copy()) - {Tag = new ToolStripTagItem {FunctionId = 7, Scintilla = scintilla}}); - - // create a cut ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextCut, null, - (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.Cut()) - {Tag = new ToolStripTagItem {FunctionId = 2, Scintilla = scintilla}}); - - // create a paste ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextPaste, null, - (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.Paste()) - {Tag = new ToolStripTagItem {FunctionId = 3, Scintilla = scintilla}}); - - // create a delete ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextDelete, null, - (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.ReplaceSelection("")) - {Tag = new ToolStripTagItem {FunctionId = 4, Scintilla = scintilla}}); - - // create a tool strip separator.. - contextMenu.Items.Add(new ToolStripSeparator()); - - // create a select all ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextSelectAll, null, - (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.SelectAll()) - {Tag = new ToolStripTagItem {FunctionId = 5, Scintilla = scintilla}}); - - // create a tool strip separator.. - contextMenu.Items.Add(new ToolStripSeparator()); - - // create a color convert ToolStripMenuItem.. - contextMenu.Items.Add(new ToolStripMenuItem(TextHexadecimalColor, null, (sender, args) => + // create an undo ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextUndo, null, + (sender, e) => { - var word = scintilla.GetWordFromPosition(scintilla.CurrentPosition); - if (Regex.IsMatch(word, "^[A-Fa-f0-9]*$")) - { - Color color = Color.Empty; - if (word.Length == 8) - { - color = Color.FromArgb(Convert.ToInt32(word.Substring(0, 2), 16), - Convert.ToInt32(word.Substring(2, 2), 16), - Convert.ToInt32(word.Substring(4, 2), 16), - Convert.ToInt32(word.Substring(6, 2), 16)); - } - else if (word.Length == 6) - { - color = Color.FromArgb(0xFF, - Convert.ToInt32(word.Substring(0, 2), 16), - Convert.ToInt32(word.Substring(2, 2), 16), - Convert.ToInt32(word.Substring(4, 2), 16)); - } - - FormPickAColor.Execute(color); - } + var tagItem = ((ToolStripTagItem) ((ToolStripItem) sender).Tag); + tagItem.Scintilla.Undo(); + onUndo(tagItem.Scintilla); + }) + {Tag = new ToolStripTagItem {FunctionId = 0, Scintilla = scintilla, }, }); + + // create a redo ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextRedo, null, + (sender, e) => + { + var tagItem = ((ToolStripTagItem) ((ToolStripItem) sender).Tag); + tagItem.Scintilla.Redo(); + onRedo(tagItem.Scintilla); }) + {Tag = new ToolStripTagItem {FunctionId = 1, Scintilla = scintilla, }, }); + + // create a tool strip separator.. + contextMenu.Items.Add(new ToolStripSeparator()); + + // create a copy ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextCopy, null, + (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.Copy()) + {Tag = new ToolStripTagItem {FunctionId = 7, Scintilla = scintilla, }, }); + + // create a cut ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextCut, null, + (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.Cut()) + {Tag = new ToolStripTagItem {FunctionId = 2, Scintilla = scintilla, }, }); + + // create a paste ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextPaste, null, + (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.Paste()) + {Tag = new ToolStripTagItem {FunctionId = 3, Scintilla = scintilla, }, }); + + // create a delete ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextDelete, null, + (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.ReplaceSelection("")) + {Tag = new ToolStripTagItem {FunctionId = 4, Scintilla = scintilla, }, }); + + // create a tool strip separator.. + contextMenu.Items.Add(new ToolStripSeparator()); + + // create a select all ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextSelectAll, null, + (sender, e) => ((ToolStripTagItem) ((ToolStripItem) sender).Tag).Scintilla.SelectAll()) + {Tag = new ToolStripTagItem {FunctionId = 5, Scintilla = scintilla, }, }); + + // create a tool strip separator.. + contextMenu.Items.Add(new ToolStripSeparator()); + + // create a color convert ToolStripMenuItem.. + contextMenu.Items.Add(new ToolStripMenuItem(TextHexadecimalColor, null, (sender, args) => + { + var word = scintilla.GetWordFromPosition(scintilla.CurrentPosition); + if (Regex.IsMatch(word, "^[A-Fa-f0-9]*$")) { - Tag = new ToolStripTagItem {FunctionId = 6, Scintilla = scintilla} - }); + Color color = Color.Empty; + if (word.Length == 8) + { + color = Color.FromArgb(Convert.ToInt32(word.Substring(0, 2), 16), + Convert.ToInt32(word.Substring(2, 2), 16), + Convert.ToInt32(word.Substring(4, 2), 16), + Convert.ToInt32(word.Substring(6, 2), 16)); + } + else if (word.Length == 6) + { + color = Color.FromArgb(0xFF, + Convert.ToInt32(word.Substring(0, 2), 16), + Convert.ToInt32(word.Substring(2, 2), 16), + Convert.ToInt32(word.Substring(4, 2), 16)); + } - // ^[A-Fa-f0-9]*$ + FormPickAColor.Execute(color); + } + }) + { + Tag = new ToolStripTagItem {FunctionId = 6, Scintilla = scintilla, }, + }); - // create a tool strip separator.. - contextMenu.Items.Add(new ToolStripSeparator()); + // ^[A-Fa-f0-9]*$ - // create a tool strip menu to add a special character from a list of drop down - // items.. - ToolStripMenuItem item = new ToolStripMenuItem(TextInsertSpecialCharacter) - {Tag = new ToolStripTagItem {FunctionId = 1000, Scintilla = scintilla}}; + // create a tool strip separator.. + contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add(item); + // create a tool strip menu to add a special character from a list of drop down + // items.. + ToolStripMenuItem item = new ToolStripMenuItem(TextInsertSpecialCharacter) + {Tag = new ToolStripTagItem {FunctionId = 1000, Scintilla = scintilla, }, }; + contextMenu.Items.Add(item); - // add the copyright sign (©).. - item.DropDownItems.Add(new ToolStripMenuItem("©", null, OnSpecialCharacterClick) - {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "©"}}); - // add the trademark sign (™).. - item.DropDownItems.Add(new ToolStripMenuItem("™", null, OnSpecialCharacterClick) - {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "™"}}); + // add the copyright sign (©).. + item.DropDownItems.Add(new ToolStripMenuItem("©", null, OnSpecialCharacterClick) + {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "©", }, }); - // add the registered sign (®).. - item.DropDownItems.Add(new ToolStripMenuItem("®", null, OnSpecialCharacterClick) - {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "®"}}); + // add the trademark sign (™).. + item.DropDownItems.Add(new ToolStripMenuItem("™", null, OnSpecialCharacterClick) + {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "™", }, }); - // add the degree sign sign (°).. - item.DropDownItems.Add(new ToolStripMenuItem("°", null, OnSpecialCharacterClick) - {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "°"}}); + // add the registered sign (®).. + item.DropDownItems.Add(new ToolStripMenuItem("®", null, OnSpecialCharacterClick) + {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "®", }, }); - // add the bullet sign sign (•).. - item.DropDownItems.Add(new ToolStripMenuItem("•", null, OnSpecialCharacterClick) - {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "•"}}); + // add the degree sign sign (°).. + item.DropDownItems.Add(new ToolStripMenuItem("°", null, OnSpecialCharacterClick) + {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "°", }, }); - // set the Scintilla's ContextMenuStrip property value to the just - // created ContextMenuStrip instance.. - scintilla.ContextMenuStrip = contextMenu; + // add the bullet sign sign (•).. + item.DropDownItems.Add(new ToolStripMenuItem("•", null, OnSpecialCharacterClick) + {Tag = new ToolStripTagItem() {Scintilla = scintilla, Tag0 = "•", }, }); - // subscribe the opening event for the context menu to enable or disable - // the basic menu items depending on the state of the Scintilla instance.. - scintilla.ContextMenuStrip.Opening += ContextMenuStrip_Opening; + // set the Scintilla's ContextMenuStrip property value to the just + // created ContextMenuStrip instance.. + scintilla.ContextMenuStrip = contextMenu; - // return the just created ContextMenuStrip instance.. - return contextMenu; - } + // subscribe the opening event for the context menu to enable or disable + // the basic menu items depending on the state of the Scintilla instance.. + scintilla.ContextMenuStrip.Opening += ContextMenuStrip_Opening; - /// - /// Handles the event. - /// - /// The sender of the event. - /// The instance containing the event data. - private static void OnSpecialCharacterClick(object sender, EventArgs e) - { - // get the ToolStripMenuItem.. - var item = (ToolStripMenuItem) sender; + // return the just created ContextMenuStrip instance.. + return contextMenu; + } + + /// + /// Handles the event. + /// + /// The sender of the event. + /// The instance containing the event data. + private static void OnSpecialCharacterClick(object sender, EventArgs e) + { + // get the ToolStripMenuItem.. + var item = (ToolStripMenuItem) sender; - // get the ToolStripTagItem saved into the menu item's Tag property.. - var tagItem = (ToolStripTagItem) item.Tag; + // get the ToolStripTagItem saved into the menu item's Tag property.. + var tagItem = (ToolStripTagItem) item.Tag; - // "insert" the special character to the Scintilla document.. - tagItem.Scintilla.ReplaceSelection((string)tagItem.Tag0); - } + // "insert" the special character to the Scintilla document.. + tagItem.Scintilla.ReplaceSelection((string)tagItem.Tag0); + } - /// - /// Unsubscribes the events added to the created context menu item. - /// - /// An instance to a class of which event subscriptions to unsubscribe. - public static void UnsubscribeEvents(Scintilla scintilla) + /// + /// Unsubscribes the events added to the created context menu item. + /// + /// An instance to a class of which event subscriptions to unsubscribe. + public static void UnsubscribeEvents(Scintilla scintilla) + { + // only if not null.. + if (scintilla.ContextMenuStrip != null) { - // only if not null.. - if (scintilla.ContextMenuStrip != null) - { - // ..unsubscribe the event(s).. - scintilla.ContextMenuStrip.Opening -= ContextMenuStrip_Opening; + // ..unsubscribe the event(s).. + scintilla.ContextMenuStrip.Opening -= ContextMenuStrip_Opening; - for (int i = 0; i < scintilla.ContextMenuStrip.Items.Count; i++) + for (int i = 0; i < scintilla.ContextMenuStrip.Items.Count; i++) + { + // the must be an easier way (i.e. save the item to a property !).. + if (scintilla.ContextMenuStrip.Items[i].GetType() == typeof(ToolStripMenuItem) && + scintilla.ContextMenuStrip.Items[i].Tag != null && + scintilla.ContextMenuStrip.Items[i].Tag.GetType() == typeof(ToolStripTagItem) && + ((ToolStripTagItem) scintilla.ContextMenuStrip.Items[i].Tag).FunctionId == 1000) { - // the must be an easier way (i.e. save the item to a property !).. - if (scintilla.ContextMenuStrip.Items[i].GetType() == typeof(ToolStripMenuItem) && - scintilla.ContextMenuStrip.Items[i].Tag != null && - scintilla.ContextMenuStrip.Items[i].Tag.GetType() == typeof(ToolStripTagItem) && - ((ToolStripTagItem) scintilla.ContextMenuStrip.Items[i].Tag).FunctionId == 1000) + foreach (ToolStripMenuItem item in ((ToolStripMenuItem)scintilla.ContextMenuStrip.Items[i]).DropDownItems) { - foreach (ToolStripMenuItem item in ((ToolStripMenuItem)scintilla.ContextMenuStrip.Items[i]).DropDownItems) - { - // ..unsubscribe the event(s).. - item.Click -= OnSpecialCharacterClick; - } - - // clear the sub-items.. - ((ToolStripMenuItem)scintilla.ContextMenuStrip.Items[i]).DropDownItems.Clear(); + // ..unsubscribe the event(s).. + item.Click -= OnSpecialCharacterClick; } + + // clear the sub-items.. + ((ToolStripMenuItem)scintilla.ContextMenuStrip.Items[i]).DropDownItems.Clear(); } } } + } - /// - /// Handles the Opening event of the ContextMenuStrip control. This enables or disables the basic context menu items for the . - /// - /// The source of the event. - /// The instance containing the event data. - private static void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) - { - // get the ContextMenuStrip instance from the sender.. - ContextMenuStrip contextMenu = (ContextMenuStrip) sender; + /// + /// Handles the Opening event of the ContextMenuStrip control. This enables or disables the basic context menu items for the . + /// + /// The source of the event. + /// The instance containing the event data. + private static void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) + { + // get the ContextMenuStrip instance from the sender.. + ContextMenuStrip contextMenu = (ContextMenuStrip) sender; - // loop through the context menu strip items.. - for (int i = 0; i < contextMenu.Items.Count; i++) + // loop through the context menu strip items.. + for (int i = 0; i < contextMenu.Items.Count; i++) + { + // if the item is constructed by this class the item's Tag contains a ToolStripTagItem class instance.. + if (contextMenu.Items[i].Tag != null && contextMenu.Items[i].Tag.GetType() == typeof(ToolStripTagItem)) { - // if the item is constructed by this class the item's Tag contains a ToolStripTagItem class instance.. - if (contextMenu.Items[i].Tag != null && contextMenu.Items[i].Tag.GetType() == typeof(ToolStripTagItem)) - { - // get the ToolStripTagItem class instance.. - ToolStripTagItem tagItem = (ToolStripTagItem) contextMenu.Items[i].Tag; + // get the ToolStripTagItem class instance.. + ToolStripTagItem tagItem = (ToolStripTagItem) contextMenu.Items[i].Tag; - // based on the ToolStripTagItem class instance property of FunctionId and the state of - // the Scintilla enable or disable the ToolStripMenuItems accordingly.. - switch (tagItem.FunctionId) - { - // if the Scintilla instance can undo, then the undo item is enabled.. - case 0: contextMenu.Items[i].Enabled = tagItem.Scintilla.CanUndo; break; + // based on the ToolStripTagItem class instance property of FunctionId and the state of + // the Scintilla enable or disable the ToolStripMenuItems accordingly.. + switch (tagItem.FunctionId) + { + // if the Scintilla instance can undo, then the undo item is enabled.. + case 0: contextMenu.Items[i].Enabled = tagItem.Scintilla.CanUndo; break; - // if the Scintilla instance can redo, then the redo item is enabled.. - case 1: contextMenu.Items[i].Enabled = tagItem.Scintilla.CanRedo; break; + // if the Scintilla instance can redo, then the redo item is enabled.. + case 1: contextMenu.Items[i].Enabled = tagItem.Scintilla.CanRedo; break; - // if the Scintilla instance has text selected then the cut item is enabled.. - case 2: contextMenu.Items[i].Enabled = tagItem.Scintilla.SelectedText.Length > 0; break; + // if the Scintilla instance has text selected then the cut item is enabled.. + case 2: contextMenu.Items[i].Enabled = tagItem.Scintilla.SelectedText.Length > 0; break; - // if the Scintilla instance can paste text from the clipboard, then the paste item is enabled.. - case 3: contextMenu.Items[i].Enabled = tagItem.Scintilla.CanPaste; break; + // if the Scintilla instance can paste text from the clipboard, then the paste item is enabled.. + case 3: contextMenu.Items[i].Enabled = tagItem.Scintilla.CanPaste; break; - // if the Scintilla instance has text selected then the delete item is enabled.. - case 4: contextMenu.Items[i].Enabled = tagItem.Scintilla.SelectedText.Length > 0; break; + // if the Scintilla instance has text selected then the delete item is enabled.. + case 4: contextMenu.Items[i].Enabled = tagItem.Scintilla.SelectedText.Length > 0; break; - // if the Scintilla instance has any text, then the select all item is enabled.. - case 5: contextMenu.Items[i].Enabled = tagItem.Scintilla.Text.Length > 0; break; + // if the Scintilla instance has any text, then the select all item is enabled.. + case 5: contextMenu.Items[i].Enabled = tagItem.Scintilla.Text.Length > 0; break; - // if the text under the Scintilla's selection might indicate a color, then the color drop down item is.. - case 6: - contextMenu.Items[i].Enabled = Regex.IsMatch( - tagItem.Scintilla.GetWordFromPosition(tagItem.Scintilla.CurrentPosition), - "^[A-Fa-f0-9]*$"); break; + // if the text under the Scintilla's selection might indicate a color, then the color drop down item is.. + case 6: + contextMenu.Items[i].Enabled = Regex.IsMatch( + tagItem.Scintilla.GetWordFromPosition(tagItem.Scintilla.CurrentPosition), + "^[A-Fa-f0-9]*$"); break; - // if the Scintilla instance has text selected then the copy item is enabled.. - case 7: contextMenu.Items[i].Enabled = tagItem.Scintilla.SelectedText.Length > 0; break; - } + // if the Scintilla instance has text selected then the copy item is enabled.. + case 7: contextMenu.Items[i].Enabled = tagItem.Scintilla.SelectedText.Length > 0; break; } } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ScintillaUtils/SelectionReplace.cs b/ScriptNotepad/UtilityClasses/ScintillaUtils/SelectionReplace.cs index bc7a3200..fb1a9e3d 100644 --- a/ScriptNotepad/UtilityClasses/ScintillaUtils/SelectionReplace.cs +++ b/ScriptNotepad/UtilityClasses/ScintillaUtils/SelectionReplace.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,33 +26,32 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; -namespace ScriptNotepad.UtilityClasses.ScintillaUtils +namespace ScriptNotepad.UtilityClasses.ScintillaUtils; + +/// +/// An utility to change the value. +/// +public static class SelectionReplace { /// - /// An utility to change the value. + /// Replaces the with specified value. /// - public static class SelectionReplace + /// The scintilla. + /// The value to replace the selected text with. + public static void SelectionReplaceWithValue(this Scintilla scintilla, string value) { - /// - /// Replaces the with specified value. - /// - /// The scintilla. - /// The value to replace the selected text with. - public static void SelectionReplaceWithValue(this Scintilla scintilla, string value) + if (scintilla.SelectedText.Length > 0) { - if (scintilla.SelectedText.Length > 0) - { - var start = scintilla.SelectionStart; - var end = scintilla.SelectionEnd; - var length = end - start; - - end = start + value.Length; - - scintilla.Text = scintilla.Text.Remove(start, length); - scintilla.Text = scintilla.Text.Insert(start, value); - scintilla.SelectionStart = start; - scintilla.SelectionEnd = end; - } + var start = scintilla.SelectionStart; + var end = scintilla.SelectionEnd; + var length = end - start; + + end = start + value.Length; + + scintilla.Text = scintilla.Text.Remove(start, length); + scintilla.Text = scintilla.Text.Insert(start, value); + scintilla.SelectionStart = start; + scintilla.SelectionEnd = end; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/ScintillaUtils/SetStyleBraceMatch.cs b/ScriptNotepad/UtilityClasses/ScintillaUtils/SetStyleBraceMatch.cs index 1d7d41d4..c97596be 100644 --- a/ScriptNotepad/UtilityClasses/ScintillaUtils/SetStyleBraceMatch.cs +++ b/ScriptNotepad/UtilityClasses/ScintillaUtils/SetStyleBraceMatch.cs @@ -27,37 +27,36 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using ScriptNotepad.Settings; -namespace ScriptNotepad.UtilityClasses.ScintillaUtils +namespace ScriptNotepad.UtilityClasses.ScintillaUtils; + +/// +/// A helper class to set the brace highlighting. +/// +public class SetStyleBraceMatch { /// - /// A helper class to set the brace highlighting. + /// Set the brace highlight style if set in the class. /// - public class SetStyleBraceMatch + /// The class instance of which brace highlighting to set. + public static void SetStyle(Scintilla scintilla) { - /// - /// Set the brace highlight style if set in the class. - /// - /// The class instance of which brace highlighting to set. - public static void SetStyle(Scintilla scintilla) + // failure is not accepted within this class.. + if (scintilla == null) + { + return; + } + + // not in the settings, so do return.. + if (!FormSettings.Settings.HighlightBraces) { - // failure is not accepted within this class.. - if (scintilla == null) - { - return; - } - - // not in the settings, so do return.. - if (!FormSettings.Settings.HighlightBraces) - { - return; - } - - scintilla.Styles[Style.BraceLight].ForeColor = FormSettings.Settings.BraceHighlightForegroundColor; - scintilla.Styles[Style.BraceLight].BackColor = FormSettings.Settings.BraceHighlightBackgroundColor; - scintilla.Styles[Style.BraceBad].BackColor = FormSettings.Settings.BraceBadHighlightForegroundColor; - - scintilla.Styles[Style.BraceLight].Italic = FormSettings.Settings.HighlightBracesItalic; - scintilla.Styles[Style.BraceLight].Bold = FormSettings.Settings.HighlightBracesBold; + return; } + + scintilla.Styles[Style.BraceLight].ForeColor = FormSettings.Settings.BraceHighlightForegroundColor; + scintilla.Styles[Style.BraceLight].BackColor = FormSettings.Settings.BraceHighlightBackgroundColor; + scintilla.Styles[Style.BraceBad].BackColor = FormSettings.Settings.BraceBadHighlightForegroundColor; + + scintilla.Styles[Style.BraceLight].Italic = FormSettings.Settings.HighlightBracesItalic; + scintilla.Styles[Style.BraceLight].Bold = FormSettings.Settings.HighlightBracesBold; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgress.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgress.cs index 0fa66b28..1c03d086 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgress.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgress.cs @@ -29,150 +29,149 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.SearchText; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace +namespace ScriptNotepad.UtilityClasses.SearchAndReplace; + +/// +/// A dialog to report various length process states. +/// Implements the +/// +/// +public partial class FormDialogSearchReplaceProgress : DBLangEngineWinforms { /// - /// A dialog to report various length process states. - /// Implements the + /// Gets or sets the action to run in the background. /// - /// - public partial class FormDialogSearchReplaceProgress : DBLangEngineWinforms + private Action Action { get; set; } + + /// + /// Gets or sets the text searcher to be used with the search. + /// + private TextSearcherAndReplacer TextSearcher { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The action to perform in a . + /// The text searcher class instance. + public FormDialogSearchReplaceProgress(Action action, TextSearcherAndReplacer textSearcher) { - /// - /// Gets or sets the action to run in the background. - /// - private Action Action { get; set; } - - /// - /// Gets or sets the text searcher to be used with the search. - /// - private TextSearcherAndReplacer TextSearcher { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The action to perform in a . - /// The text searcher class instance. - public FormDialogSearchReplaceProgress(Action action, TextSearcherAndReplacer textSearcher) + if (!ConstructorHelper()) { - if (!ConstructorHelper()) - { - return; - } + return; + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - textSearcher.SearchProgress += SearchOpenDocuments_SearchProgress; - TextSearcher = textSearcher; + textSearcher.SearchProgress += SearchOpenDocuments_SearchProgress; + TextSearcher = textSearcher; - Action = action; + Action = action; - ShowDialog(); - } + ShowDialog(); + } - /// - /// Initializes a new instance of the class. - /// - public FormDialogSearchReplaceProgress() - { - // a constructor for localization purposes only.. - ConstructorHelper(); - } + /// + /// Initializes a new instance of the class. + /// + public FormDialogSearchReplaceProgress() + { + // a constructor for localization purposes only.. + ConstructorHelper(); + } - /// - /// A helper for multiple constructors. - /// - /// - /// true if the execution can continue after this call (no localization process), false otherwise. - private bool ConstructorHelper() - { - InitializeComponent(); + /// + /// A helper for multiple constructors. + /// + /// + /// true if the execution can continue after this call (no localization process), false otherwise. + private bool ConstructorHelper() + { + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return false; // After localization don't do anything more.. - } + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - return true; + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return false; // After localization don't do anything more.. } + return true; + } + - /// - /// Handles the SearchProgress event of the SearchOpenDocuments control. - /// - /// The source of the event. - /// The instance containing the event data. - private void SearchOpenDocuments_SearchProgress(object sender, TextSearcherEventArgs e) + /// + /// Handles the SearchProgress event of the SearchOpenDocuments control. + /// + /// The source of the event. + /// The instance containing the event data. + private void SearchOpenDocuments_SearchProgress(object sender, TextSearcherEventArgs e) + { + // invocation is required as this is coming from another thread.. + pbMain.Invoke(new MethodInvoker(delegate { pbMain.Value = e.Percentage; })); + lbProgressDesc.Invoke(new MethodInvoker(delegate { - // invocation is required as this is coming from another thread.. - pbMain.Invoke(new MethodInvoker(delegate { pbMain.Value = e.Percentage; })); - lbProgressDesc.Invoke(new MethodInvoker(delegate - { - lbProgressDesc.Text = DBLangEngine.GetMessage("msgSearchProgress", - "File: {0}, Progress: {1}|A message describing a search or replace progress with a file name and a progress percentage", - e.FileName, e.Percentage); - })); - } + lbProgressDesc.Text = DBLangEngine.GetMessage("msgSearchProgress", + "File: {0}, Progress: {1}|A message describing a search or replace progress with a file name and a progress percentage", + e.FileName, e.Percentage); + })); + } - // just run the action with the BackgroundWorker's DoWork event.. - private void BwMain_DoWork(object sender, DoWorkEventArgs e) - { - Action(); - } + // just run the action with the BackgroundWorker's DoWork event.. + private void BwMain_DoWork(object sender, DoWorkEventArgs e) + { + Action(); + } - // run the BackgroundWorker on the dialog shown event.. - private void FormDialogCommonProgress_Shown(object sender, EventArgs e) - { - // this form needs to be the top most as it is a dialog.. - TopMost = true; - BringToFront(); + // run the BackgroundWorker on the dialog shown event.. + private void FormDialogCommonProgress_Shown(object sender, EventArgs e) + { + // this form needs to be the top most as it is a dialog.. + TopMost = true; + BringToFront(); - // run the BackgroundWorker to do the search and replace.. - bwMain.RunWorkerAsync(); - } + // run the BackgroundWorker to do the search and replace.. + bwMain.RunWorkerAsync(); + } - // the BackgroundWorker worker has completed running the action, so allow the dialog to be closed.. - private void BwMain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) - { - NoReactOnClosing = true; - Invoke(new MethodInvoker(delegate { DialogResult = DialogResult.OK; })); - } + // the BackgroundWorker worker has completed running the action, so allow the dialog to be closed.. + private void BwMain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + NoReactOnClosing = true; + Invoke(new MethodInvoker(delegate { DialogResult = DialogResult.OK; })); + } - // the dialog is closing.. - private void FormDialogSearchReplaceProgress_FormClosing(object sender, FormClosingEventArgs e) + // the dialog is closing.. + private void FormDialogSearchReplaceProgress_FormClosing(object sender, FormClosingEventArgs e) + { + // if the flag is set, allow the dialog to close.. + if (NoReactOnClosing) { - // if the flag is set, allow the dialog to close.. - if (NoReactOnClosing) - { - return; - } + return; + } - // set the flag for the next round.. - NoReactOnClosing = true; + // set the flag for the next round.. + NoReactOnClosing = true; - // cancel the Close(); .. - e.Cancel = true; + // cancel the Close(); .. + e.Cancel = true; - // cancel the TextSearcherAndReplacer processing.. - TextSearcher.Canceled = true; + // cancel the TextSearcherAndReplacer processing.. + TextSearcher.Canceled = true; - // indicate that the dialogs background processing has been cancelled.. - Cancelled = true; - } + // indicate that the dialogs background processing has been cancelled.. + Cancelled = true; + } - /// - /// Gets or sets a value indicating whether the code in the form's closing event should be run. - /// - private bool NoReactOnClosing { get; set; } + /// + /// Gets or sets a value indicating whether the code in the form's closing event should be run. + /// + private bool NoReactOnClosing { get; set; } - /// - /// Gets or sets a value indicating whether this search or replace was cancelled. - /// - /// true if cancelled; otherwise, false. - public bool Cancelled { get; set; } - } -} + /// + /// Gets or sets a value indicating whether this search or replace was cancelled. + /// + /// true if cancelled; otherwise, false. + public bool Cancelled { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgressFiles.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgressFiles.cs index 1edd13ef..827dfe30 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgressFiles.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormDialogSearchReplaceProgressFiles.cs @@ -31,285 +31,284 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.SearchText; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace +namespace ScriptNotepad.UtilityClasses.SearchAndReplace; + +/// +/// A dialog to display search results of files and the search and/or replace progress being done to the files. +/// Implements the +/// +/// +public partial class FormDialogSearchReplaceProgressFiles : DBLangEngineWinforms { /// - /// A dialog to display search results of files and the search and/or replace progress being done to the files. - /// Implements the + /// Initializes a new instance of the class. This is just for localization. /// - /// - public partial class FormDialogSearchReplaceProgressFiles : DBLangEngineWinforms + public FormDialogSearchReplaceProgressFiles() { - /// - /// Initializes a new instance of the class. This is just for localization. - /// - public FormDialogSearchReplaceProgressFiles() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); } + } - /// - /// A delegate for the event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnRequestNextAction(object sender, ProgressRequestActionEventArgs e); + /// + /// A delegate for the event. + /// + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnRequestNextAction(object sender, ProgressRequestActionEventArgs e); - /// - /// Occurs when the form requests for a next action for the next file processing. - /// - public event OnRequestNextAction RequestNextAction; + /// + /// Occurs when the form requests for a next action for the next file processing. + /// + public event OnRequestNextAction RequestNextAction; - /// - /// A field to save the delegate for the event as this form also unsubscribes the event handler on disposal. - /// - private readonly OnRequestNextAction requestNextAction; + /// + /// A field to save the delegate for the event as this form also unsubscribes the event handler on disposal. + /// + private readonly OnRequestNextAction requestNextAction; - /// - /// Gets or sets an instance to the . - /// - private DirectoryCrawler Crawler { get; } + /// + /// Gets or sets an instance to the . + /// + private DirectoryCrawler Crawler { get; } - /// - /// Initializes a new instance of the class. - /// - /// An instance for the class initialized elsewhere. - /// A delegate for the event as this class also unsubscribes the event handler. - public FormDialogSearchReplaceProgressFiles(DirectoryCrawler crawler, OnRequestNextAction requestNextAction) - { - InitializeComponent(); + /// + /// Initializes a new instance of the class. + /// + /// An instance for the class initialized elsewhere. + /// A delegate for the event as this class also unsubscribes the event handler. + public FormDialogSearchReplaceProgressFiles(DirectoryCrawler crawler, OnRequestNextAction requestNextAction) + { + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - // subscribe the disposed event.. - Disposed += FormDialogSearchReplaceProgressFiles_Disposed; + // subscribe the disposed event.. + Disposed += FormDialogSearchReplaceProgressFiles_Disposed; - // save the delegate for the RequestNextAction so it can be unsubscribed on this form's disposal.. - this.requestNextAction = requestNextAction; + // save the delegate for the RequestNextAction so it can be unsubscribed on this form's disposal.. + this.requestNextAction = requestNextAction; - // subscribe the event with the delegate given in the parameter.. - RequestNextAction += requestNextAction; + // subscribe the event with the delegate given in the parameter.. + RequestNextAction += requestNextAction; - // subscribe to the ReportProgress event of the DirectoryCrawler instance.. - crawler.ReportProgress += Crawler_ReportProgress; + // subscribe to the ReportProgress event of the DirectoryCrawler instance.. + crawler.ReportProgress += Crawler_ReportProgress; - // save the directory crawler instance.. - Crawler = crawler; + // save the directory crawler instance.. + Crawler = crawler; - // show this form as a dialog.. - ShowDialog(); - } + // show this form as a dialog.. + ShowDialog(); + } - /// - /// Gets or sets the either the previous or the current instance of class. - /// - private TextSearcherAndReplacer SearchAndReplacer { get; set; } - - /// - /// Handles the ReportProgress event of the class. - /// - /// The source of the event. - /// The instance containing the event data. - private void Crawler_ReportProgress(object sender, DirectoryCrawlerEventArgs e) + /// + /// Gets or sets the either the previous or the current instance of class. + /// + private TextSearcherAndReplacer SearchAndReplacer { get; set; } + + /// + /// Handles the ReportProgress event of the class. + /// + /// The source of the event. + /// The instance containing the event data. + private void Crawler_ReportProgress(object sender, DirectoryCrawlerEventArgs e) + { + // try as program should go down with this.. + try { - // try as program should go down with this.. - try + // there is a 99.999xx% change of the event to be raised from a another thread.. + lbStatus.Invoke(new MethodInvoker(delegate { - // there is a 99.999xx% change of the event to be raised from a another thread.. - lbStatus.Invoke(new MethodInvoker(delegate + // check if a directory is being processed.. + if (!string.IsNullOrEmpty(e.CurrentDirectory)) { - // check if a directory is being processed.. - if (!string.IsNullOrEmpty(e.CurrentDirectory)) - { - // ..and set the status text accordingly.. - lbStatus.Text = DBLangEngine.GetMessage("msgProcessingDirectory", - "Processing directory: '{0}'...|A message indicating that a directory with a given name is being processed somehow", - e.CurrentDirectory); - } - })); - - // AGAIN: there is a 99.999xx% change of the event to be raised from a another thread.. - lbStatus2.Invoke(new MethodInvoker(delegate - { - // check if a file is currently being processed.. - if (!string.IsNullOrEmpty(e.FileName)) - { - // ..and set the status text accordingly.. - lbStatus2.Text = DBLangEngine.GetMessage("msgProcessingFile", - "Processing file: '{0}'...|A message indicating that a file with a given name is being processed somehow", - e.FileName); - } - else - { - // ..no file is currently being processed.. - lbStatus2.Text = string.Empty; - } - })); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } + // ..and set the status text accordingly.. + lbStatus.Text = DBLangEngine.GetMessage("msgProcessingDirectory", + "Processing directory: '{0}'...|A message indicating that a directory with a given name is being processed somehow", + e.CurrentDirectory); + } + })); - // try as program should go down with this.. - try + // AGAIN: there is a 99.999xx% change of the event to be raised from a another thread.. + lbStatus2.Invoke(new MethodInvoker(delegate { - // if the DirectoryCrawler instance has found a file name to process.. + // check if a file is currently being processed.. if (!string.IsNullOrEmpty(e.FileName)) { - // create a new instance of the ProgressRequestActionEventArgs class.. - var args = new ProgressRequestActionEventArgs - {Canceled = false, FileName = e.FileName, SearchAndReplacer = SearchAndReplacer}; - - // raise the event if subscribed.. actually an exception should be raised if not subscribed in this case.. - RequestNextAction?.Invoke(this, args); - - // if the file has requested to be skipped to just continue the "crawling".. - if (args.SkipFile) - { - return; - } - - // first unsubscribe the SearchProgress event of the previous TextSearcherAndReplacer class instance.. - if (SearchAndReplacer != null) - { - // ..after a null check.. - SearchAndReplacer.SearchProgress -= SearchOpenDocuments_SearchProgress; - } - - // save the TextSearcherAndReplacer class instance from the event arguments.. - SearchAndReplacer = args.SearchAndReplacer; - - // subscribe the SearchProgress event for the TextSearcherAndReplacer class instance.. - if (SearchAndReplacer != null) - { - // ..after a null check.. - SearchAndReplacer.SearchProgress += SearchOpenDocuments_SearchProgress; - } - - // invoke the action to "this thread" from the event arguments.. - args.Action?.Invoke(); + // ..and set the status text accordingly.. + lbStatus2.Text = DBLangEngine.GetMessage("msgProcessingFile", + "Processing file: '{0}'...|A message indicating that a file with a given name is being processed somehow", + e.FileName); } else { - // no file is currently being processed so do set the progress bar value to zero.. - pbMain.Invoke(new MethodInvoker(delegate { pbMain.Value = 0; })); + // ..no file is currently being processed.. + lbStatus2.Text = string.Empty; } - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } + })); } - - /// - /// This event is fired when the class instance reports internal progress. - /// - /// The sender of the event. - /// The instance containing the event data. - public void SearchOpenDocuments_SearchProgress(object sender, TextSearcherEventArgs e) + catch (Exception ex) { - // as this event is fired from another thread, do invoke.. - pbMain.Invoke(new MethodInvoker(delegate - { - // ..set the progress bar value to the value given from the TextSearcherAndReplacer class instance.. - pbMain.Value = e.Percentage; - })); + // log the exception.. + ExceptionLogger.LogError(ex); } - /// - /// Handles the Disposed event of the FormDialogSearchReplaceProgressFiles control. - /// - /// The source of the event. - /// The instance containing the event data. - private void FormDialogSearchReplaceProgressFiles_Disposed(object sender, EventArgs e) + // try as program should go down with this.. + try { - // unsubscribe the events which subscriptions where made in the "code" (does not include *.Designer.cs).. - RequestNextAction -= requestNextAction; - Disposed -= FormDialogSearchReplaceProgressFiles_Disposed; - Crawler.ReportProgress -= Crawler_ReportProgress; - if (SearchAndReplacer != null) // this one requires a null check.. + // if the DirectoryCrawler instance has found a file name to process.. + if (!string.IsNullOrEmpty(e.FileName)) { - SearchAndReplacer.SearchProgress -= SearchOpenDocuments_SearchProgress; + // create a new instance of the ProgressRequestActionEventArgs class.. + var args = new ProgressRequestActionEventArgs + {Canceled = false, FileName = e.FileName, SearchAndReplacer = SearchAndReplacer, }; + + // raise the event if subscribed.. actually an exception should be raised if not subscribed in this case.. + RequestNextAction?.Invoke(this, args); + + // if the file has requested to be skipped to just continue the "crawling".. + if (args.SkipFile) + { + return; + } + + // first unsubscribe the SearchProgress event of the previous TextSearcherAndReplacer class instance.. + if (SearchAndReplacer != null) + { + // ..after a null check.. + SearchAndReplacer.SearchProgress -= SearchOpenDocuments_SearchProgress; + } + + // save the TextSearcherAndReplacer class instance from the event arguments.. + SearchAndReplacer = args.SearchAndReplacer; + + // subscribe the SearchProgress event for the TextSearcherAndReplacer class instance.. + if (SearchAndReplacer != null) + { + // ..after a null check.. + SearchAndReplacer.SearchProgress += SearchOpenDocuments_SearchProgress; + } + + // invoke the action to "this thread" from the event arguments.. + args.Action?.Invoke(); + } + else + { + // no file is currently being processed so do set the progress bar value to zero.. + pbMain.Invoke(new MethodInvoker(delegate { pbMain.Value = 0; })); } } - - /// - /// Handles the Shown event of the FormDialogSearchReplaceProgressFiles control. - /// - /// The source of the event. - /// The instance containing the event data. - private void FormDialogSearchReplaceProgressFiles_Shown(object sender, EventArgs e) + catch (Exception ex) { - // this form needs to be the top most as it is a dialog.. - TopMost = true; - BringToFront(); - - // run the BackgroundWorker so the directory "crawling" can start.. - bwMain.RunWorkerAsync(); + // log the exception.. + ExceptionLogger.LogError(ex); } + } - /// - /// Gets or sets a value indicating whether this form is allowed to close. - /// - private bool AllowClose { get; set; } - - /// - /// Handles the RunWorkerCompleted event of the bwMain control. - /// - /// The source of the event. - /// The instance containing the event data. - private void BwMain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + /// + /// This event is fired when the class instance reports internal progress. + /// + /// The sender of the event. + /// The instance containing the event data. + public void SearchOpenDocuments_SearchProgress(object sender, TextSearcherEventArgs e) + { + // as this event is fired from another thread, do invoke.. + pbMain.Invoke(new MethodInvoker(delegate { - // all the work is done, so do allow this dialog to close.. - AllowClose = true; - // ..and close the dialog.. - Close(); - } + // ..set the progress bar value to the value given from the TextSearcherAndReplacer class instance.. + pbMain.Value = e.Percentage; + })); + } - /// - /// Handles the DoWork event of the bwMain control. - /// - /// The source of the event. - /// The instance containing the event data. - private void BwMain_DoWork(object sender, DoWorkEventArgs e) + /// + /// Handles the Disposed event of the FormDialogSearchReplaceProgressFiles control. + /// + /// The source of the event. + /// The instance containing the event data. + private void FormDialogSearchReplaceProgressFiles_Disposed(object sender, EventArgs e) + { + // unsubscribe the events which subscriptions where made in the "code" (does not include *.Designer.cs).. + RequestNextAction -= requestNextAction; + Disposed -= FormDialogSearchReplaceProgressFiles_Disposed; + Crawler.ReportProgress -= Crawler_ReportProgress; + if (SearchAndReplacer != null) // this one requires a null check.. { - // search the directory and possibly it's subdirectories for files.. - Crawler.GetCrawlResult(); + SearchAndReplacer.SearchProgress -= SearchOpenDocuments_SearchProgress; } + } - /// - /// Handles the FormClosing event of the FormDialogSearchReplaceProgressFiles control. - /// - /// The source of the event. - /// The instance containing the event data. - private void FormDialogSearchReplaceProgressFiles_FormClosing(object sender, FormClosingEventArgs e) + /// + /// Handles the Shown event of the FormDialogSearchReplaceProgressFiles control. + /// + /// The source of the event. + /// The instance containing the event data. + private void FormDialogSearchReplaceProgressFiles_Shown(object sender, EventArgs e) + { + // this form needs to be the top most as it is a dialog.. + TopMost = true; + BringToFront(); + + // run the BackgroundWorker so the directory "crawling" can start.. + bwMain.RunWorkerAsync(); + } + + /// + /// Gets or sets a value indicating whether this form is allowed to close. + /// + private bool AllowClose { get; set; } + + /// + /// Handles the RunWorkerCompleted event of the bwMain control. + /// + /// The source of the event. + /// The instance containing the event data. + private void BwMain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + // all the work is done, so do allow this dialog to close.. + AllowClose = true; + // ..and close the dialog.. + Close(); + } + + /// + /// Handles the DoWork event of the bwMain control. + /// + /// The source of the event. + /// The instance containing the event data. + private void BwMain_DoWork(object sender, DoWorkEventArgs e) + { + // search the directory and possibly it's subdirectories for files.. + Crawler.GetCrawlResult(); + } + + /// + /// Handles the FormClosing event of the FormDialogSearchReplaceProgressFiles control. + /// + /// The source of the event. + /// The instance containing the event data. + private void FormDialogSearchReplaceProgressFiles_FormClosing(object sender, FormClosingEventArgs e) + { + // don't allow the user to close the form.. + if (e.CloseReason == CloseReason.UserClosing) { - // don't allow the user to close the form.. - if (e.CloseReason == CloseReason.UserClosing) + // ..instead indicate classes working in the background worker to stop.. + if (SearchAndReplacer != null) { - // ..instead indicate classes working in the background worker to stop.. - if (SearchAndReplacer != null) - { - SearchAndReplacer.Canceled = true; - } - Crawler.Canceled = true; - - // sometimes this false accuses of the user.. - e.Cancel = !AllowClose; + SearchAndReplacer.Canceled = true; } + Crawler.Canceled = true; + + // sometimes this false accuses of the user.. + e.Cancel = !AllowClose; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchAndReplace.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchAndReplace.cs index 953cc3b5..1138704f 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchAndReplace.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchAndReplace.cs @@ -42,363 +42,495 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.SearchText; using static ScriptNotepad.UtilityClasses.ApplicationHelpers.ApplicationActivateDeactivate; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace +namespace ScriptNotepad.UtilityClasses.SearchAndReplace; + +/// +/// A search and replace dialog for the ScriptNotepad software. +/// +/// +public partial class FormSearchAndReplace : DBLangEngineWinforms { + #region MassiveConstructor /// - /// A search and replace dialog for the ScriptNotepad software. + /// Initializes a new instance of the class. /// - /// - public partial class FormSearchAndReplace : DBLangEngineWinforms + private FormSearchAndReplace() { - #region MassiveConstructor - /// - /// Initializes a new instance of the class. - /// - private FormSearchAndReplace() + // don't allow other instances.. + if (_formSearchAndReplace != null) { - // don't allow other instances.. - if (_formSearchAndReplace != null) - { - return; - } + return; + } - // Add this form to be positioned.. - PositionForms.Add(this); + // Add this form to be positioned.. + PositionForms.Add(this); - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - AllowTransparency = true; + AllowTransparency = true; - // get the open documents on the main form.. - Documents = GetDocuments(true); + // get the open documents on the main form.. + Documents = GetDocuments(true); - // get the current document.. - CurrentDocument = GetCurrentDocument(); + // get the current document.. + CurrentDocument = GetCurrentDocument(); - // localize the tool tips.. - ttMain.SetToolTip(rbSimpleExtended, DBLangEngine.GetMessage("msgSimpleExtendedDesc", "? = one character, * = multiple characters, # = digit, % = single digit|A message describing the usage of the simple extended search algorithm (meant for demented persons, such as me).")); - ttMain.SetToolTip(rbSimpleExtended2, DBLangEngine.GetMessage("msgSimpleExtendedDesc", "? = one character, * = multiple characters, # = digit, % = single digit|A message describing the usage of the simple extended search algorithm (meant for demented persons, such as me).")); - ttMain.SetToolTip(rbSimpleExtended3, DBLangEngine.GetMessage("msgSimpleExtendedDesc", "? = one character, * = multiple characters, # = digit, % = single digit|A message describing the usage of the simple extended search algorithm (meant for demented persons, such as me).")); + // localize the tool tips.. + ttMain.SetToolTip(rbSimpleExtended, DBLangEngine.GetMessage("msgSimpleExtendedDesc", "? = one character, * = multiple characters, # = digit, % = single digit|A message describing the usage of the simple extended search algorithm (meant for demented persons, such as me).")); + ttMain.SetToolTip(rbSimpleExtended2, DBLangEngine.GetMessage("msgSimpleExtendedDesc", "? = one character, * = multiple characters, # = digit, % = single digit|A message describing the usage of the simple extended search algorithm (meant for demented persons, such as me).")); + ttMain.SetToolTip(rbSimpleExtended3, DBLangEngine.GetMessage("msgSimpleExtendedDesc", "? = one character, * = multiple characters, # = digit, % = single digit|A message describing the usage of the simple extended search algorithm (meant for demented persons, such as me).")); - // subscribe to an event which is raised upon application activation.. - ApplicationDeactivated += FormSearchAndReplace_ApplicationDeactivated; - ApplicationActivated += FormSearchAndReplace_ApplicationActivated; + // subscribe to an event which is raised upon application activation.. + ApplicationDeactivated += FormSearchAndReplace_ApplicationDeactivated; + ApplicationActivated += FormSearchAndReplace_ApplicationActivated; - // get the search text history from the database.. - SearchHistory = SearchAndReplaceHistoryHelper.GetEntriesByLimit(SearchAndReplaceSearchType.All, - SearchAndReplaceType.Search, FormSettings.Settings.FileSearchHistoriesLimit, - FormSettings.Settings.CurrentSessionEntity).ToList(); + // get the search text history from the database.. + SearchHistory = SearchAndReplaceHistoryHelper.GetEntriesByLimit(SearchAndReplaceSearchType.All, + SearchAndReplaceType.Search, FormSettings.Settings.FileSearchHistoriesLimit, + FormSettings.Settings.CurrentSessionEntity).ToList(); - // get the replace text history from the database.. - ReplaceHistory = SearchAndReplaceHistoryHelper.GetEntriesByLimit(SearchAndReplaceSearchType.All, - SearchAndReplaceType.Replace, FormSettings.Settings.FileSearchHistoriesLimit, - FormSettings.Settings.CurrentSessionEntity).ToList(); + // get the replace text history from the database.. + ReplaceHistory = SearchAndReplaceHistoryHelper.GetEntriesByLimit(SearchAndReplaceSearchType.All, + SearchAndReplaceType.Replace, FormSettings.Settings.FileSearchHistoriesLimit, + FormSettings.Settings.CurrentSessionEntity).ToList(); - // set the combo boxed auto-complete state.. - SetAutoCompleteState(FormSettings.Settings.AutoCompleteEnabled); + // set the combo boxed auto-complete state.. + SetAutoCompleteState(FormSettings.Settings.AutoCompleteEnabled); - // get the filter used in the search and/or replace in files.. - FilterHistory = MiscellaneousTextEntryHelper.GetEntriesByLimit(MiscellaneousTextType.FileExtensionList, - FormSettings.Settings.FileSearchHistoriesLimit, FormSettings.Settings.CurrentSessionEntity).ToList(); + // get the filter used in the search and/or replace in files.. + FilterHistory = MiscellaneousTextEntryHelper.GetEntriesByLimit(MiscellaneousTextType.FileExtensionList, + FormSettings.Settings.FileSearchHistoriesLimit, FormSettings.Settings.CurrentSessionEntity).ToList(); - // get the path(s) used in the search and/or replace in files.. - PathHistory = MiscellaneousTextEntryHelper.GetEntriesByLimit(MiscellaneousTextType.Path, - FormSettings.Settings.FileSearchHistoriesLimit, FormSettings.Settings.CurrentSessionEntity).ToList(); + // get the path(s) used in the search and/or replace in files.. + PathHistory = MiscellaneousTextEntryHelper.GetEntriesByLimit(MiscellaneousTextType.Path, + FormSettings.Settings.FileSearchHistoriesLimit, FormSettings.Settings.CurrentSessionEntity).ToList(); - // set the user assigned color for the mark.. - btMarkColor.BackColor = FormSettings.Settings.MarkSearchReplaceColor; - } - #endregion + // set the user assigned color for the mark.. + btMarkColor.BackColor = FormSettings.Settings.MarkSearchReplaceColor; + } + #endregion + + #region WndProc + /// Processes Windows messages. + /// The Windows to process. + protected override void WndProc(ref Message m) + { + WndProcApplicationActivateHelper(this, ref m); + + base.WndProc(ref m); + } + #endregion - #region WndProc - /// Processes Windows messages. - /// The Windows to process. - protected override void WndProc(ref Message m) + #region PublicProperties + // the search history texts.. + private List searchHistory = new List(); + + /// + /// Gets or sets the search history texts. + /// + public List SearchHistory + { + get => searchHistory; + + set { - WndProcApplicationActivateHelper(this, ref m); + // sort the list as sorted in the database.. + value = value.OrderByDescending(f => f.Added).ThenBy(f => f.SearchOrReplaceText.ToLowerInvariant()) + .ToList(); + + // save the value.. + searchHistory = value; - base.WndProc(ref m); + // fill the combo boxes.. + ReListSearchHistory(); } - #endregion + } - #region PublicProperties - // the search history texts.. - private List searchHistory = new List(); + // the search filter history values.. + private List filterHistory = new List(); - /// - /// Gets or sets the search history texts. - /// - public List SearchHistory - { - get => searchHistory; + /// + /// Gets or sets the search filter history values. + /// + public List FilterHistory + { + get => filterHistory; - set - { - // sort the list as sorted in the database.. - value = value.OrderByDescending(f => f.Added).ThenBy(f => f.SearchOrReplaceText.ToLowerInvariant()) - .ToList(); + set + { + // sort the list as sorted in the database.. + value = value.OrderByDescending(f => f.Added).ThenBy(f => f.TextValue.ToLowerInvariant()) + .ToList(); - // save the value.. - searchHistory = value; + // save the value.. + filterHistory = value; - // fill the combo boxes.. - ReListSearchHistory(); - } + // fill the combo boxes.. + ReListFilterHistory(); } + } - // the search filter history values.. - private List filterHistory = new List(); + // the search and/or replace path values.. + private List pathHistory = new List(); - /// - /// Gets or sets the search filter history values. - /// - public List FilterHistory - { - get => filterHistory; + /// + /// Gets or sets the search and/or replace path values. + /// + public List PathHistory + { + get => pathHistory; - set - { - // sort the list as sorted in the database.. - value = value.OrderByDescending(f => f.Added).ThenBy(f => f.TextValue.ToLowerInvariant()) - .ToList(); + set + { + // sort the list as sorted in the database.. + value = value.OrderByDescending(f => f.Added).ThenBy(f => f.TextValue.ToLowerInvariant()) + .ToList(); - // save the value.. - filterHistory = value; + // save the value.. + pathHistory = value; - // fill the combo boxes.. - ReListFilterHistory(); - } + // fill the combo boxes.. + ReListPathHistory(); } + } - // the search and/or replace path values.. - private List pathHistory = new List(); + // the replace history texts.. + private List replaceHistory = new List(); - /// - /// Gets or sets the search and/or replace path values. - /// - public List PathHistory - { - get => pathHistory; + /// + /// Gets or sets the replace history texts. + /// + public List ReplaceHistory + { + get => replaceHistory; - set - { - // sort the list as sorted in the database.. - value = value.OrderByDescending(f => f.Added).ThenBy(f => f.TextValue.ToLowerInvariant()) - .ToList(); + set + { + // sort the list as sorted in the database.. + value = value.OrderByDescending(f => f.Added).ThenBy(f => f.SearchOrReplaceText.ToLowerInvariant()) + .ToList(); - // save the value.. - pathHistory = value; + // save the value.. + replaceHistory = value; - // fill the combo boxes.. - ReListPathHistory(); - } + // fill the combo boxes.. + ReListReplaceHistory(); } + } + - // the replace history texts.. - private List replaceHistory = new List(); + // value for the SelectionChangedFromMainForm property.. + private bool selectionChangedFromMainForm = true; - /// - /// Gets or sets the replace history texts. - /// - public List ReplaceHistory + /// + /// Gets or set a value indicating whether the active document's selection was changed from the application main form. + /// + public bool SelectionChangedFromMainForm + { + get => selectionChangedFromMainForm; + set { - get => replaceHistory; + cbInSelection2.Enabled = value; + cbInSelection4.Enabled = value; + selectionChangedFromMainForm = value; - set + if (!selectionChangedFromMainForm) { - // sort the list as sorted in the database.. - value = value.OrderByDescending(f => f.Added).ThenBy(f => f.SearchOrReplaceText.ToLowerInvariant()) - .ToList(); - - // save the value.. - replaceHistory = value; - - // fill the combo boxes.. - ReListReplaceHistory(); + cbInSelection2.Enabled = false; + cbInSelection2.Checked = false; + cbInSelection4.Enabled = false; + cbInSelection4.Checked = false; } } + } + #endregion + #region PublicStaticProperties + /// + /// Gets or sets a value indicating whether to reset the search area upon instance creation or not. + /// + public static bool ResetSearchArea { get; set; } = true; - // value for the SelectionChangedFromMainForm property.. - private bool selectionChangedFromMainForm = true; + /// + /// The form search and replace instance holder. + /// + private static FormSearchAndReplace _formSearchAndReplace; - /// - /// Gets or set a value indicating whether the active document's selection was changed from the application main form. - /// - public bool SelectionChangedFromMainForm + /// + /// Gets the instance of a dialog. + /// + public static FormSearchAndReplace Instance + { + get { - get => selectionChangedFromMainForm; - set + if (_formSearchAndReplace == null) { - cbInSelection2.Enabled = value; - cbInSelection4.Enabled = value; - selectionChangedFromMainForm = value; - - if (!selectionChangedFromMainForm) - { - cbInSelection2.Enabled = false; - cbInSelection2.Checked = false; - cbInSelection4.Enabled = false; - cbInSelection4.Checked = false; - } + var form = new FormSearchAndReplace(); + _formSearchAndReplace = form; } + + return _formSearchAndReplace; } - #endregion + } + #endregion - #region PublicStaticProperties - /// - /// Gets or sets a value indicating whether to reset the search area upon instance creation or not. - /// - public static bool ResetSearchArea { get; set; } = true; + #region PublicStaticMethods + /// + /// Sets the state of the auto-complete mode for the combo boxes on the dialog. + /// + /// if set to true the auto-complete should be enabled. + public void SetAutoCompleteState(bool enabled) + { + cmbFind.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + cmbFind.AutoCompleteSource = enabled ? AutoCompleteSource.ListItems : AutoCompleteSource.None; + cmbReplace.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + cmbFind2.AutoCompleteSource = enabled ? AutoCompleteSource.ListItems : AutoCompleteSource.None; + cmbFind3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + cmbReplace3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + cmbFilters3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + cmbDirectory3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + cmbFind4.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; + } + + /// + /// Shows the form with the search tab page opened. + /// + /// A parent form for this search dialog. + /// A text to use fill the search box with. + public static void ShowSearch(Form parentForm, string searchString = "") + { + if (!Instance.ShownWithParent) + { + Instance.ShownWithParent = true; + Instance.Show(parentForm); + } + else + { + Instance.Show(); + } - /// - /// The form search and replace instance holder. - /// - private static FormSearchAndReplace _formSearchAndReplace; + Instance.PreviousVisible = true; + Instance.tcMain.SelectTab(0); - /// - /// Gets the instance of a dialog. - /// - public static FormSearchAndReplace Instance + // set the search string if not empty.. + if (searchString != string.Empty) { - get - { - if (_formSearchAndReplace == null) - { - var form = new FormSearchAndReplace(); - _formSearchAndReplace = form; - } + Instance.cmbFind.Text = searchString; + } - return _formSearchAndReplace; - } + Instance.cmbFind.Focus(); + } + + /// + /// Shows the form with the replace tab page opened. + /// + /// A parent form for this search dialog. + /// A text to use fill the search box with. + public static void ShowReplace(Form parentForm, string searchString = "") + { + if (!Instance.ShownWithParent) + { + Instance.ShownWithParent = true; + Instance.Show(parentForm); } - #endregion - - #region PublicStaticMethods - /// - /// Sets the state of the auto-complete mode for the combo boxes on the dialog. - /// - /// if set to true the auto-complete should be enabled. - public void SetAutoCompleteState(bool enabled) - { - cmbFind.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - cmbFind.AutoCompleteSource = enabled ? AutoCompleteSource.ListItems : AutoCompleteSource.None; - cmbReplace.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - cmbFind2.AutoCompleteSource = enabled ? AutoCompleteSource.ListItems : AutoCompleteSource.None; - cmbFind3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - cmbReplace3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - cmbFilters3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - cmbDirectory3.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - cmbFind4.AutoCompleteMode = enabled ? AutoCompleteMode.Suggest : AutoCompleteMode.None; - } - - /// - /// Shows the form with the search tab page opened. - /// - /// A parent form for this search dialog. - /// A text to use fill the search box with. - public static void ShowSearch(Form parentForm, string searchString = "") + else { - if (!Instance.ShownWithParent) - { - Instance.ShownWithParent = true; - Instance.Show(parentForm); - } - else - { - Instance.Show(); - } + Instance.Show(); + } - Instance.PreviousVisible = true; - Instance.tcMain.SelectTab(0); + Instance.PreviousVisible = true; + Instance.tcMain.SelectTab(1); - // set the search string if not empty.. - if (searchString != string.Empty) - { - Instance.cmbFind.Text = searchString; - } + // set the search string if not empty.. + if (searchString != string.Empty) + { + Instance.cmbFind2.Text = searchString; + } + + Instance.cmbFind2.Focus(); + } - Instance.cmbFind.Focus(); + /// + /// Shows the form with the find (and replace) in files tab page opened. + /// + /// A parent form for this search dialog. + /// A text to use fill the search box with. + public static void ShowFindInFiles(Form parentForm, string searchString = "") + { + if (!Instance.ShownWithParent) + { + Instance.ShownWithParent = true; + Instance.Show(parentForm); + } + else + { + Instance.Show(); } - /// - /// Shows the form with the replace tab page opened. - /// - /// A parent form for this search dialog. - /// A text to use fill the search box with. - public static void ShowReplace(Form parentForm, string searchString = "") + Instance.PreviousVisible = true; + Instance.tcMain.SelectTab(2); + + // set the search string if not empty.. + if (searchString != string.Empty) { - if (!Instance.ShownWithParent) - { - Instance.ShownWithParent = true; - Instance.Show(parentForm); - } - else - { - Instance.Show(); - } + Instance.cmbFind3.Text = searchString; + } - Instance.PreviousVisible = true; - Instance.tcMain.SelectTab(1); + Instance.cmbFind3.Focus(); + } - // set the search string if not empty.. - if (searchString != string.Empty) - { - Instance.cmbFind2.Text = searchString; - } + /// + /// Shows the form with the mark tab page opened. + /// + /// A parent form for this search dialog. + /// A text to use fill the search box with. + public static void ShowMarkMatches(Form parentForm, string searchString = "") + { + if (!Instance.ShownWithParent) + { + Instance.ShownWithParent = true; + Instance.Show(parentForm); + } + else + { + Instance.Show(); + } + + Instance.PreviousVisible = true; + Instance.tcMain.SelectTab(3); - Instance.cmbFind2.Focus(); + // set the search string if not empty.. + if (searchString != string.Empty) + { + Instance.cmbFind4.Text = searchString; } - /// - /// Shows the form with the find (and replace) in files tab page opened. - /// - /// A parent form for this search dialog. - /// A text to use fill the search box with. - public static void ShowFindInFiles(Form parentForm, string searchString = "") + Instance.cmbFind4.Focus(); + } + + /// + /// Creates an instance of the dialog for localization. + /// + // ReSharper disable once ObjectCreationAsStatement + public static void CreateLocalizationInstance() => new FormSearchAndReplace(); + #endregion + + #region PublicMethods + /// + /// Advances the search to the next or to the previous result if available and the form is visible and there are some search conditions. + /// + public void Advance(bool forward) + { + // the form is not visible, so do return.. + if (!Visible) { - if (!Instance.ShownWithParent) + return; + } + + if (tcMain.TabIndex == 0 || tcMain.TabIndex == 1) + { + if (forward) { - Instance.ShownWithParent = true; - Instance.Show(parentForm); + Forward(); } else { - Instance.Show(); + Backward(); } + } + } - Instance.PreviousVisible = true; - Instance.tcMain.SelectTab(2); - // set the search string if not empty.. - if (searchString != string.Empty) - { - Instance.cmbFind3.Text = searchString; - } + /// + /// Re-lists the search history combo boxes contents. + /// + public void ReListSearchHistory() + { + // clear the combo boxes.. + cmbFind.Items.Clear(); + cmbFind2.Items.Clear(); + cmbFind3.Items.Clear(); + + // fill the combo boxes.. + // ReSharper disable once CoVariantArrayConversion + cmbFind.Items.AddRange(searchHistory.ToArray()); + // ReSharper disable once CoVariantArrayConversion + cmbFind2.Items.AddRange(searchHistory.ToArray()); + // ReSharper disable once CoVariantArrayConversion + cmbFind3.Items.AddRange(searchHistory.ToArray()); + // ReSharper disable once CoVariantArrayConversion + cmbFind4.Items.AddRange(searchHistory.ToArray()); + } - Instance.cmbFind3.Focus(); - } + /// + /// Re-lists the search and/or replace history filter combo boxes contents. + /// + public void ReListFilterHistory() + { + // clear the combo boxes.. + cmbFilters3.Items.Clear(); + + // fill the combo boxes.. + // ReSharper disable once CoVariantArrayConversion + cmbFilters3.Items.AddRange(filterHistory.ToArray()); + } + + /// + /// Re-lists the search and/or replace directory combo boxes contents. + /// + public void ReListPathHistory() + { + // clear the combo boxes.. + cmbDirectory3.Items.Clear(); + + // fill the combo boxes.. + // ReSharper disable once CoVariantArrayConversion + cmbDirectory3.Items.AddRange(pathHistory.ToArray()); + } + + /// + /// Re-lists the replace history combo boxes contents. + /// + public void ReListReplaceHistory() + { + // clear the combo boxes.. + cmbReplace.Items.Clear(); + cmbReplace3.Items.Clear(); + + // fill the combo boxes.. + // ReSharper disable once CoVariantArrayConversion + cmbReplace.Items.AddRange(replaceHistory.ToArray()); + // ReSharper disable once CoVariantArrayConversion + cmbReplace3.Items.AddRange(replaceHistory.ToArray()); + } + + /// + /// Gets or sets a value indicating whether this instance has been visible previously. + /// + private bool PreviousVisible { get; set; } - /// - /// Shows the form with the mark tab page opened. - /// - /// A parent form for this search dialog. - /// A text to use fill the search box with. - public static void ShowMarkMatches(Form parentForm, string searchString = "") + /// + /// Toggles the visible state of this form. + /// + /// if set to true the form should be shown. + /// A parent form for this search dialog. + public void ToggleVisible(Form parentForm, bool shouldShow) + { + if (!Visible && shouldShow && !UserClosed && PreviousVisible) { if (!Instance.ShownWithParent) { @@ -410,1825 +542,1692 @@ public static void ShowMarkMatches(Form parentForm, string searchString = "") Instance.Show(); } - Instance.PreviousVisible = true; - Instance.tcMain.SelectTab(3); - - // set the search string if not empty.. - if (searchString != string.Empty) + if (tcMain.SelectedTab.Equals(tabFind)) { - Instance.cmbFind4.Text = searchString; + cmbFind.Focus(); } - - Instance.cmbFind4.Focus(); - } - - /// - /// Creates an instance of the dialog for localization. - /// - // ReSharper disable once ObjectCreationAsStatement - public static void CreateLocalizationInstance() => new FormSearchAndReplace(); - #endregion - - #region PublicMethods - /// - /// Advances the search to the next or to the previous result if available and the form is visible and there are some search conditions. - /// - public void Advance(bool forward) - { - // the form is not visible, so do return.. - if (!Visible) + else if (tcMain.SelectedTab.Equals(tabReplace)) { - return; + cmbFind2.Focus(); } - - if (tcMain.TabIndex == 0 || tcMain.TabIndex == 1) + else if (tcMain.SelectedTab.Equals(tabFindInFiles)) { - if (forward) - { - Forward(); - } - else - { - Backward(); - } + cmbFind3.Focus(); + } + else if (tcMain.SelectedTab.Equals(tabMarkMatches)) + { + cmbFind4.Focus(); } } - - - /// - /// Re-lists the search history combo boxes contents. - /// - public void ReListSearchHistory() + else if (Visible && !shouldShow) { - // clear the combo boxes.. - cmbFind.Items.Clear(); - cmbFind2.Items.Clear(); - cmbFind3.Items.Clear(); - - // fill the combo boxes.. - // ReSharper disable once CoVariantArrayConversion - cmbFind.Items.AddRange(searchHistory.ToArray()); - // ReSharper disable once CoVariantArrayConversion - cmbFind2.Items.AddRange(searchHistory.ToArray()); - // ReSharper disable once CoVariantArrayConversion - cmbFind3.Items.AddRange(searchHistory.ToArray()); - // ReSharper disable once CoVariantArrayConversion - cmbFind4.Items.AddRange(searchHistory.ToArray()); + Close(); + UserClosed = false; } + } + #endregion - /// - /// Re-lists the search and/or replace history filter combo boxes contents. - /// - public void ReListFilterHistory() - { - // clear the combo boxes.. - cmbFilters3.Items.Clear(); + #region PublicEvents + /// + /// A delegate for the event. + /// + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnRequestDocuments(object sender, ScintillaDocumentEventArgs e); - // fill the combo boxes.. - // ReSharper disable once CoVariantArrayConversion - cmbFilters3.Items.AddRange(filterHistory.ToArray()); - } + /// + /// Occurs when the search and replace dialog requests access to the open documents on the main form. + /// + public event OnRequestDocuments RequestDocuments; + #endregion - /// - /// Re-lists the search and/or replace directory combo boxes contents. - /// - public void ReListPathHistory() - { - // clear the combo boxes.. - cmbDirectory3.Items.Clear(); + #region PrivateAndInternalProperties + /// + /// Gets or sets a value indicating whether the Show() method has already called with a parent form. + /// + private bool ShownWithParent { get; set; } - // fill the combo boxes.. - // ReSharper disable once CoVariantArrayConversion - cmbDirectory3.Items.AddRange(pathHistory.ToArray()); - } + /// + /// Gets or sets the value whether this form was previously closed by a user. + /// + private bool UserClosed { get; set; } - /// - /// Re-lists the replace history combo boxes contents. - /// - public void ReListReplaceHistory() - { - // clear the combo boxes.. - cmbReplace.Items.Clear(); - cmbReplace3.Items.Clear(); + /// + /// Gets or sets the documents containing in the main form. + /// + internal List<(Scintilla scintilla, string fileName)> Documents { get; set; } = new List<(Scintilla scintilla, string fileName)>(); - // fill the combo boxes.. - // ReSharper disable once CoVariantArrayConversion - cmbReplace.Items.AddRange(replaceHistory.ToArray()); - // ReSharper disable once CoVariantArrayConversion - cmbReplace3.Items.AddRange(replaceHistory.ToArray()); - } + private (Scintilla scintilla, string fileName) currentDocument; - /// - /// Gets or sets a value indicating whether this instance has been visible previously. - /// - private bool PreviousVisible { get; set; } + /// + /// Gets or sets the currently active document in the main form. + /// + private (Scintilla scintilla, string fileName) CurrentDocument + { + get => currentDocument; - /// - /// Toggles the visible state of this form. - /// - /// if set to true the form should be shown. - /// A parent form for this search dialog. - public void ToggleVisible(Form parentForm, bool shouldShow) + set { - if (!Visible && shouldShow && !UserClosed && PreviousVisible) + if (currentDocument != value && currentDocument.scintilla != null) { - if (!Instance.ShownWithParent) - { - Instance.ShownWithParent = true; - Instance.Show(parentForm); - } - else - { - Instance.Show(); - } - - if (tcMain.SelectedTab.Equals(tabFind)) - { - cmbFind.Focus(); - } - else if (tcMain.SelectedTab.Equals(tabReplace)) - { - cmbFind2.Focus(); - } - else if (tcMain.SelectedTab.Equals(tabFindInFiles)) - { - cmbFind3.Focus(); - } - else if (tcMain.SelectedTab.Equals(tabMarkMatches)) - { - cmbFind4.Focus(); - } + CreateSingleSearchReplaceAlgorithm(value); } - else if (Visible && !shouldShow) - { - Close(); - UserClosed = false; - } - } - #endregion - - #region PublicEvents - /// - /// A delegate for the event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnRequestDocuments(object sender, ScintillaDocumentEventArgs e); - - /// - /// Occurs when the search and replace dialog requests access to the open documents on the main form. - /// - public event OnRequestDocuments RequestDocuments; - #endregion - - #region PrivateAndInternalProperties - /// - /// Gets or sets a value indicating whether the Show() method has already called with a parent form. - /// - private bool ShownWithParent { get; set; } - - /// - /// Gets or sets the value whether this form was previously closed by a user. - /// - private bool UserClosed { get; set; } - - /// - /// Gets or sets the documents containing in the main form. - /// - internal List<(Scintilla scintilla, string fileName)> Documents { get; set; } = new List<(Scintilla scintilla, string fileName)>(); - - private (Scintilla scintilla, string fileName) currentDocument; - - /// - /// Gets or sets the currently active document in the main form. - /// - private (Scintilla scintilla, string fileName) CurrentDocument - { - get => currentDocument; - - set - { - if (currentDocument != value && currentDocument.scintilla != null) - { - CreateSingleSearchReplaceAlgorithm(value); - } - currentDocument = value; - } + currentDocument = value; } + } - /// - /// Gets or sets the instance used to search and replace with either open or closed documents. - /// - /// The search open documents. - private TextSearcherAndReplacer SearchReplaceDocuments { get; set; } + /// + /// Gets or sets the instance used to search and replace with either open or closed documents. + /// + /// The search open documents. + private TextSearcherAndReplacer SearchReplaceDocuments { get; set; } - /// - /// Gets or sets a value indicating whether to allow the singleton instance to be disposed of. - /// - public static bool AllowInstanceDispose { get; set; } = false; + /// + /// Gets or sets a value indicating whether to allow the singleton instance to be disposed of. + /// + public static bool AllowInstanceDispose { get; set; } = false; - /// - /// Gets the current search type. - /// - private TextSearcherEnums.SearchType SearchType + /// + /// Gets the current search type. + /// + private TextSearcherEnums.SearchType SearchType + { + get { - get + // based on the currently active tab, return the correct value.. + if (rbNormal.Checked && tcMain.SelectedTab.Equals(tabFind) || + rbNormal2.Checked && tcMain.SelectedTab.Equals(tabReplace) || + rbNormal3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || + rbNormal4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) { - // based on the currently active tab, return the correct value.. - if (rbNormal.Checked && tcMain.SelectedTab.Equals(tabFind) || - rbNormal2.Checked && tcMain.SelectedTab.Equals(tabReplace) || - rbNormal3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || - rbNormal4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) - { - return TextSearcherEnums.SearchType.Normal; - } - - // based on the currently active tab, return the correct value.. - if (rbExtented.Checked && tcMain.SelectedTab.Equals(tabFind) || - rbExtented2.Checked && tcMain.SelectedTab.Equals(tabReplace) || - rbExtented3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || - rbExtented4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) - { - return TextSearcherEnums.SearchType.Extended; - } - - // based on the currently active tab, return the correct value.. - if (rbRegEx.Checked && tcMain.SelectedTab.Equals(tabFind) || - rbRegEx2.Checked && tcMain.SelectedTab.Equals(tabReplace) || - rbRegEx3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || - rbRegEx4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) - { - return TextSearcherEnums.SearchType.RegularExpression; - } - - // based on the currently active tab, return the correct value.. - if (rbSimpleExtended.Checked && tcMain.SelectedTab.Equals(tabFind) || - rbSimpleExtended2.Checked && tcMain.SelectedTab.Equals(tabReplace) || - rbSimpleExtended3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || - rbSimpleExtended4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) - { - return TextSearcherEnums.SearchType.SimpleExtended; - } - - // return the default value (NOTE: the code should never reach this point!).. return TextSearcherEnums.SearchType.Normal; } - } - - /// - /// Gets the search type translated into the database format. - /// - /// The search type database. - private SearchAndReplaceSearchType SearchTypeDatabase - { - get + + // based on the currently active tab, return the correct value.. + if (rbExtented.Checked && tcMain.SelectedTab.Equals(tabFind) || + rbExtented2.Checked && tcMain.SelectedTab.Equals(tabReplace) || + rbExtented3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || + rbExtented4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) { - switch (SearchType) - { - case TextSearcherEnums.SearchType.Normal: return SearchAndReplaceSearchType.Normal; - case TextSearcherEnums.SearchType.Extended: return SearchAndReplaceSearchType.Extended; - case TextSearcherEnums.SearchType.RegularExpression: return SearchAndReplaceSearchType.RegularExpression; - case TextSearcherEnums.SearchType.SimpleExtended: return SearchAndReplaceSearchType.SimpleExtended; - } - return SearchAndReplaceSearchType.Normal; + return TextSearcherEnums.SearchType.Extended; } - } - /// - /// Gets the search text. - /// - private string SearchText - { - get + // based on the currently active tab, return the correct value.. + if (rbRegEx.Checked && tcMain.SelectedTab.Equals(tabFind) || + rbRegEx2.Checked && tcMain.SelectedTab.Equals(tabReplace) || + rbRegEx3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || + rbRegEx4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) { - if (tcMain.SelectedTab.Equals(tabFind)) - { - return cmbFind.Text; - } - - if (tcMain.SelectedTab.Equals(tabReplace)) - { - return cmbFind2.Text; - } - - if (tcMain.SelectedTab.Equals(tabFindInFiles)) - { - return cmbFind3.Text; - } - - if (tcMain.SelectedTab.Equals(tabMarkMatches)) - { - return cmbFind4.Text; - } - - return string.Empty; + return TextSearcherEnums.SearchType.RegularExpression; } - } - /// - /// Gets the replace text. - /// - private string ReplaceText - { - get + // based on the currently active tab, return the correct value.. + if (rbSimpleExtended.Checked && tcMain.SelectedTab.Equals(tabFind) || + rbSimpleExtended2.Checked && tcMain.SelectedTab.Equals(tabReplace) || + rbSimpleExtended3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles) || + rbSimpleExtended4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches)) { - if (tcMain.SelectedTab.Equals(tabFind)) - { - return string.Empty; - } - - if (tcMain.SelectedTab.Equals(tabReplace)) - { - return cmbReplace.Text; - } - - if (tcMain.SelectedTab.Equals(tabFindInFiles)) - { - return cmbReplace3.Text; - } - - return string.Empty; + return TextSearcherEnums.SearchType.SimpleExtended; } - } - - /// - /// A value indicating whether the should suspend it self from executing any code. - /// - private bool SuspendTransparencyChangeEvent { get; set; } - #endregion + // return the default value (NOTE: the code should never reach this point!).. + return TextSearcherEnums.SearchType.Normal; + } + } - #region PrivateMethods - /// - /// Gets ta value indicating whether the search and/or replace algorithm is correctly set. - /// - /// A value indicating whether the current method is a search method or a replace method.- - /// True if the search and/or replace algorithm is correctly set; otherwise false. - private bool ValidSearchAndReplace(bool replacing) + /// + /// Gets the search type translated into the database format. + /// + /// The search type database. + private SearchAndReplaceSearchType SearchTypeDatabase + { + get { - if (CurrentDocument.scintilla == null) + switch (SearchType) { - return false; + case TextSearcherEnums.SearchType.Normal: return SearchAndReplaceSearchType.Normal; + case TextSearcherEnums.SearchType.Extended: return SearchAndReplaceSearchType.Extended; + case TextSearcherEnums.SearchType.RegularExpression: return SearchAndReplaceSearchType.RegularExpression; + case TextSearcherEnums.SearchType.SimpleExtended: return SearchAndReplaceSearchType.SimpleExtended; } + return SearchAndReplaceSearchType.Normal; + } + } + /// + /// Gets the search text. + /// + private string SearchText + { + get + { if (tcMain.SelectedTab.Equals(tabFind)) { - return cmbFind.Text != string.Empty; - } - + return cmbFind.Text; + } + if (tcMain.SelectedTab.Equals(tabReplace)) { - if (replacing && (cmbReplace.Text == string.Empty | cmbFind2.Text == string.Empty)) - { - return false; - } - - return cmbFind2.Text != string.Empty; + return cmbFind2.Text; } if (tcMain.SelectedTab.Equals(tabFindInFiles)) { - return ((cmbFind3.Text != string.Empty && !replacing) || - (cmbReplace3.Text != string.Empty && replacing)) && - cmbFilters3.Text.Trim() != string.Empty && cmbDirectory3.Text != string.Empty; + return cmbFind3.Text; } if (tcMain.SelectedTab.Equals(tabMarkMatches)) { - return cmbFind4.Text != string.Empty; + return cmbFind4.Text; } - return false; + return string.Empty; } + } - /// - /// Gets a value indicating whether the match case is checked. - /// - /// true if the match case is checked; otherwise, false. - private bool MatchCaseSet => - cbMatchCase.Checked && tcMain.SelectedTab.Equals(tabFind) || - cbMatchCase2.Checked && tcMain.SelectedTab.Equals(tabReplace) || - cbMatchCase3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles); - - /// - /// Saves the search text(s) to the database. - /// - private void SaveSearchText() + /// + /// Gets the replace text. + /// + private string ReplaceText + { + get { - if (SearchText == string.Empty) // no empty strings.. + if (tcMain.SelectedTab.Equals(tabFind)) { - return; + return string.Empty; + } + + if (tcMain.SelectedTab.Equals(tabReplace)) + { + return cmbReplace.Text; } - var inserted = SearchAndReplaceHistoryHelper.AddOrUpdateAndReplaceHistory(SearchText, SearchTypeDatabase, - SearchAndReplaceType.Search, MatchCaseSet, FormSettings.Settings.CurrentSessionEntity); - - // conditional insert to the list.. - if (inserted != null && !SearchHistory.Exists(f => - f.SearchAndReplaceSearchType == inserted.SearchAndReplaceSearchType && - f.SearchOrReplaceText == inserted.SearchOrReplaceText)) + if (tcMain.SelectedTab.Equals(tabFindInFiles)) { - SearchHistory.Add(inserted); - ReListSearchHistory(); + return cmbReplace3.Text; } + + return string.Empty; + } + } + + + /// + /// A value indicating whether the should suspend it self from executing any code. + /// + private bool SuspendTransparencyChangeEvent { get; set; } + #endregion + + #region PrivateMethods + /// + /// Gets ta value indicating whether the search and/or replace algorithm is correctly set. + /// + /// A value indicating whether the current method is a search method or a replace method.- + /// True if the search and/or replace algorithm is correctly set; otherwise false. + private bool ValidSearchAndReplace(bool replacing) + { + if (CurrentDocument.scintilla == null) + { + return false; + } + + if (tcMain.SelectedTab.Equals(tabFind)) + { + return cmbFind.Text != string.Empty; } - /// - /// Saves the search text(s) to the database. - /// - private void SaveFilters() + if (tcMain.SelectedTab.Equals(tabReplace)) { - if (cmbFilters3.Text.Trim() == string.Empty) // no empty strings.. + if (replacing && (cmbReplace.Text == string.Empty | cmbFind2.Text == string.Empty)) { - return; + return false; } - - var inserted = MiscellaneousTextEntryHelper.AddUniqueMiscellaneousText(cmbFilters3.Text.Trim(), - MiscellaneousTextType.FileExtensionList, FormSettings.Settings.CurrentSessionEntity); + return cmbFind2.Text != string.Empty; + } + if (tcMain.SelectedTab.Equals(tabFindInFiles)) + { + return ((cmbFind3.Text != string.Empty && !replacing) || + (cmbReplace3.Text != string.Empty && replacing)) && + cmbFilters3.Text.Trim() != string.Empty && cmbDirectory3.Text != string.Empty; + } - // conditional insert to the list.. - if (inserted != null && !FilterHistory.Exists(f => - f.TextType == inserted.TextType && f.TextValue == inserted.TextValue)) - { - FilterHistory.Add(inserted); - ReListFilterHistory(); - } + if (tcMain.SelectedTab.Equals(tabMarkMatches)) + { + return cmbFind4.Text != string.Empty; } - /// - /// Saves the search and/or replace paths to the database. - /// - private void SavePaths() + return false; + } + + /// + /// Gets a value indicating whether the match case is checked. + /// + /// true if the match case is checked; otherwise, false. + private bool MatchCaseSet => + cbMatchCase.Checked && tcMain.SelectedTab.Equals(tabFind) || + cbMatchCase2.Checked && tcMain.SelectedTab.Equals(tabReplace) || + cbMatchCase3.Checked && tcMain.SelectedTab.Equals(tabFindInFiles); + + /// + /// Saves the search text(s) to the database. + /// + private void SaveSearchText() + { + if (SearchText == string.Empty) // no empty strings.. { - if (cmbDirectory3.Text.Trim() == string.Empty) // no empty strings.. - { - return; - } + return; + } - var inserted = MiscellaneousTextEntryHelper.AddUniqueMiscellaneousText(cmbDirectory3.Text, - MiscellaneousTextType.Path, FormSettings.Settings.CurrentSessionEntity); + var inserted = SearchAndReplaceHistoryHelper.AddOrUpdateAndReplaceHistory(SearchText, SearchTypeDatabase, + SearchAndReplaceType.Search, MatchCaseSet, FormSettings.Settings.CurrentSessionEntity); - // conditional insert to the list.. - if (inserted != null && !FilterHistory.Exists(f => - f.TextType == inserted.TextType && f.TextValue == inserted.TextValue)) - { - PathHistory.Add(inserted); - ReListPathHistory(); - } + // conditional insert to the list.. + if (inserted != null && !SearchHistory.Exists(f => + f.SearchAndReplaceSearchType == inserted.SearchAndReplaceSearchType && + f.SearchOrReplaceText == inserted.SearchOrReplaceText)) + { + SearchHistory.Add(inserted); + ReListSearchHistory(); } + } - /// - /// Saves the replace text(s) to the database. - /// - private void SaveReplaceText() + /// + /// Saves the search text(s) to the database. + /// + private void SaveFilters() + { + if (cmbFilters3.Text.Trim() == string.Empty) // no empty strings.. { - if (ReplaceText == string.Empty) // no empty strings.. - { - return; - } + return; + } + - var inserted = SearchAndReplaceHistoryHelper.AddOrUpdateAndReplaceHistory(ReplaceText, SearchTypeDatabase, - SearchAndReplaceType.Replace, MatchCaseSet, FormSettings.Settings.CurrentSessionEntity); + var inserted = MiscellaneousTextEntryHelper.AddUniqueMiscellaneousText(cmbFilters3.Text.Trim(), + MiscellaneousTextType.FileExtensionList, FormSettings.Settings.CurrentSessionEntity); - // conditional insert to the list.. - if (inserted != null && !ReplaceHistory.Exists(f => - f.SearchAndReplaceSearchType == inserted.SearchAndReplaceSearchType && - f.SearchOrReplaceText == inserted.SearchOrReplaceText)) - { - ReplaceHistory.Add(inserted); - ReListReplaceHistory(); - } + + // conditional insert to the list.. + if (inserted != null && !FilterHistory.Exists(f => + f.TextType == inserted.TextType && f.TextValue == inserted.TextValue)) + { + FilterHistory.Add(inserted); + ReListFilterHistory(); } + } - /// - /// Updates the search contents in case the user has manipulated the active document contents. - /// - /// The new contents. - /// Name of the file in the active tab. - internal void UpdateSearchContents(string newContents, string fileName) + /// + /// Saves the search and/or replace paths to the database. + /// + private void SavePaths() + { + if (cmbDirectory3.Text.Trim() == string.Empty) // no empty strings.. { - // the search form must be visible.. - if (Visible) - { - // only create the algorithm if the the passed scintilla actually contains a ScintillaNET control.. - if (newContents != null) - { - // get the default controls for the search algorithm.. - string cmbFindString = null; + return; + } - // get the controls matching the active tab.. - if (tcMain.SelectedTab.Equals(tabFind)) - { - cmbFindString = cmbFind.Text; - } - if (tcMain.SelectedTab.Equals(tabReplace)) - { - cmbFindString = cmbFind2.Text; - } + var inserted = MiscellaneousTextEntryHelper.AddUniqueMiscellaneousText(cmbDirectory3.Text, + MiscellaneousTextType.Path, FormSettings.Settings.CurrentSessionEntity); - // validate that there is a search algorithm and it's for the current document.. - if (SearchReplaceDocuments != null && SearchReplaceDocuments.FileName == fileName && - SearchReplaceDocuments.OriginalSearchString == cmbFindString) - { - // save the previous search position.. - var previousPos = SearchReplaceDocuments.SearchStart; + // conditional insert to the list.. + if (inserted != null && !FilterHistory.Exists(f => + f.TextType == inserted.TextType && f.TextValue == inserted.TextValue)) + { + PathHistory.Add(inserted); + ReListPathHistory(); + } + } + + /// + /// Saves the replace text(s) to the database. + /// + private void SaveReplaceText() + { + if (ReplaceText == string.Empty) // no empty strings.. + { + return; + } - // set the new contents.. - SearchReplaceDocuments.SearchText = newContents; + var inserted = SearchAndReplaceHistoryHelper.AddOrUpdateAndReplaceHistory(ReplaceText, SearchTypeDatabase, + SearchAndReplaceType.Replace, MatchCaseSet, FormSettings.Settings.CurrentSessionEntity); - // set the search position back to the search algorithm if the value is still valid.. - if (previousPos < newContents.Length) - { - SearchReplaceDocuments.SearchStart = previousPos; - } - } - } - } + // conditional insert to the list.. + if (inserted != null && !ReplaceHistory.Exists(f => + f.SearchAndReplaceSearchType == inserted.SearchAndReplaceSearchType && + f.SearchOrReplaceText == inserted.SearchOrReplaceText)) + { + ReplaceHistory.Add(inserted); + ReListReplaceHistory(); } + } - /// - /// Creates the single search and/or replace algorithm for a given contents and file name. - /// - /// A contents of a document of file and a file name of the document to create the search algorithm from. - private void CreateSingleSearchReplaceAlgorithm((string contents, string fileName) contents) + /// + /// Updates the search contents in case the user has manipulated the active document contents. + /// + /// The new contents. + /// Name of the file in the active tab. + internal void UpdateSearchContents(string newContents, string fileName) + { + // the search form must be visible.. + if (Visible) { // only create the algorithm if the the passed scintilla actually contains a ScintillaNET control.. - if (contents.contents != null) + if (newContents != null) { - if (SearchReplaceDocuments != null) + // get the default controls for the search algorithm.. + string cmbFindString = null; + + // get the controls matching the active tab.. + if (tcMain.SelectedTab.Equals(tabFind)) { - using (SearchReplaceDocuments) // dispose of the previous algorithm.. - { - // ..and unsubscribe the search/replace progress event.. - SearchReplaceDocuments.SearchProgress -= SearchOpenDocuments_SearchProgress; - } + cmbFindString = cmbFind.Text; + } + if (tcMain.SelectedTab.Equals(tabReplace)) + { + cmbFindString = cmbFind2.Text; } - // invoke as this method might be called from a thread.. - Invoke(new MethodInvoker(delegate + // validate that there is a search algorithm and it's for the current document.. + if (SearchReplaceDocuments != null && SearchReplaceDocuments.FileName == fileName && + SearchReplaceDocuments.OriginalSearchString == cmbFindString) { - // get the default controls for the search algorithm.. - string cmbFindString = cmbFind.Text; - bool cbWrapAroundChecked = cbWrapAround.Checked; - bool cbMatchCaseChecked = cbMatchCase.Checked; - bool cbMatchWholeWordChecked = cbMatchWholeWord.Checked; - - // get the controls matching the active tab.. - if (tcMain.SelectedTab.Equals(tabReplace)) - { - cmbFindString = cmbFind2.Text; - cbWrapAroundChecked = cbWrapAround2.Checked; - cbMatchCaseChecked = cbMatchCase2.Checked; - cbMatchWholeWordChecked = cbMatchWholeWord2.Checked; - } - else if (tcMain.SelectedTab.Equals(tabFindInFiles)) - { - cmbFindString = cmbFind3.Text; - cbWrapAroundChecked = false; // no wrap-around with files.. - cbMatchCaseChecked = cbMatchCase3.Checked; - cbMatchWholeWordChecked = cbMatchWholeWord3.Checked; - } - else if (tcMain.SelectedTab.Equals(tabMarkMatches)) + // save the previous search position.. + var previousPos = SearchReplaceDocuments.SearchStart; + + // set the new contents.. + SearchReplaceDocuments.SearchText = newContents; + + // set the search position back to the search algorithm if the value is still valid.. + if (previousPos < newContents.Length) { - cmbFindString = cmbFind4.Text; - cbWrapAroundChecked = false; // no wrap-around with marks.. - cbMatchCaseChecked = cbMatchCase4.Checked; - cbMatchWholeWordChecked = cbMatchWholeWord4.Checked; + SearchReplaceDocuments.SearchStart = previousPos; } - - // create the search and replace algorithm.. - SearchReplaceDocuments = - new TextSearcherAndReplacer( - contents.contents, cmbFindString, - SearchType) - { - WrapAround = cbWrapAroundChecked, - IgnoreCase = !cbMatchCaseChecked, - FileName = contents.fileName, - WholeWord = cbMatchWholeWordChecked, - FileNameNoPath = Path.GetFileName(contents.fileName), - }; - - // subscribe the search progress event.. - SearchReplaceDocuments.SearchProgress += SearchOpenDocuments_SearchProgress; - })); + } } } + } - - /// - /// Creates the single search and/or replace algorithm for a given document. - /// - /// The scintilla and its file name to create the search algorithm from. - internal void CreateSingleSearchReplaceAlgorithm((Scintilla scintilla, string fileName) scintilla) + /// + /// Creates the single search and/or replace algorithm for a given contents and file name. + /// + /// A contents of a document of file and a file name of the document to create the search algorithm from. + private void CreateSingleSearchReplaceAlgorithm((string contents, string fileName) contents) + { + // only create the algorithm if the the passed scintilla actually contains a ScintillaNET control.. + if (contents.contents != null) { - // no need for an exception.. - if (!IsHandleCreated) + if (SearchReplaceDocuments != null) { - return; + using (SearchReplaceDocuments) // dispose of the previous algorithm.. + { + // ..and unsubscribe the search/replace progress event.. + SearchReplaceDocuments.SearchProgress -= SearchOpenDocuments_SearchProgress; + } } + // invoke as this method might be called from a thread.. Invoke(new MethodInvoker(delegate { - // get a value if only the selection is required to be used as text for the algorithm.. - bool selection = - cbInSelection4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches) || - cbInSelection2.Checked && tcMain.SelectedTab.Equals(tabReplace); + // get the default controls for the search algorithm.. + string cmbFindString = cmbFind.Text; + bool cbWrapAroundChecked = cbWrapAround.Checked; + bool cbMatchCaseChecked = cbMatchCase.Checked; + bool cbMatchWholeWordChecked = cbMatchWholeWord.Checked; - if (scintilla.scintilla != null) + // get the controls matching the active tab.. + if (tcMain.SelectedTab.Equals(tabReplace)) + { + cmbFindString = cmbFind2.Text; + cbWrapAroundChecked = cbWrapAround2.Checked; + cbMatchCaseChecked = cbMatchCase2.Checked; + cbMatchWholeWordChecked = cbMatchWholeWord2.Checked; + } + else if (tcMain.SelectedTab.Equals(tabFindInFiles)) + { + cmbFindString = cmbFind3.Text; + cbWrapAroundChecked = false; // no wrap-around with files.. + cbMatchCaseChecked = cbMatchCase3.Checked; + cbMatchWholeWordChecked = cbMatchWholeWord3.Checked; + } + else if (tcMain.SelectedTab.Equals(tabMarkMatches)) { - CreateSingleSearchReplaceAlgorithm(( - selection ? scintilla.scintilla.SelectedText : scintilla.scintilla.Text, - scintilla.fileName)); + cmbFindString = cmbFind4.Text; + cbWrapAroundChecked = false; // no wrap-around with marks.. + cbMatchCaseChecked = cbMatchCase4.Checked; + cbMatchWholeWordChecked = cbMatchWholeWord4.Checked; } + + // create the search and replace algorithm.. + SearchReplaceDocuments = + new TextSearcherAndReplacer( + contents.contents, cmbFindString, + SearchType) + { + WrapAround = cbWrapAroundChecked, + IgnoreCase = !cbMatchCaseChecked, + FileName = contents.fileName, + WholeWord = cbMatchWholeWordChecked, + FileNameNoPath = Path.GetFileName(contents.fileName), + }; + + // subscribe the search progress event.. + SearchReplaceDocuments.SearchProgress += SearchOpenDocuments_SearchProgress; })); } + } + - /// - /// Searches to backward direction. - /// - private void Backward() + /// + /// Creates the single search and/or replace algorithm for a given document. + /// + /// The scintilla and its file name to create the search algorithm from. + internal void CreateSingleSearchReplaceAlgorithm((Scintilla scintilla, string fileName) scintilla) + { + // no need for an exception.. + if (!IsHandleCreated) { - SaveSearchText(); // save the used search text to the database.. - var result = SearchReplaceDocuments?.Backward(); - if (result.HasValue && !result.Equals(TextSearcherAndReplacer.Empty)) - { - GetCurrentDocument().scintilla.SelectionStart = result.Value.position; - GetCurrentDocument().scintilla.SelectionEnd = result.Value.position + result.Value.length; - GetCurrentDocument().scintilla.ScrollCaret(); + return; + } - // set the flag to indicate a the selection was changed from this form.. - SelectionChangedFromMainForm = false; + Invoke(new MethodInvoker(delegate + { + // get a value if only the selection is required to be used as text for the algorithm.. + bool selection = + cbInSelection4.Checked && tcMain.SelectedTab.Equals(tabMarkMatches) || + cbInSelection2.Checked && tcMain.SelectedTab.Equals(tabReplace); - SetStatus(Color.ForestGreen, - DBLangEngine.GetMessage("msgSearchFound", - "Find: found at {0}.|A message (in a status strip label) describing that the search text was found at a position with the search and replace dialog", - result.Value.position)); - } - else + if (scintilla.scintilla != null) { - SetStatus(Color.Red, - DBLangEngine.GetMessage("msgSearchNotFound", - "Find: not found.|A message (in a status strip label) describing that the search text wasn't found with the search and replace dialog")); + CreateSingleSearchReplaceAlgorithm(( + selection ? scintilla.scintilla.SelectedText : scintilla.scintilla.Text, + scintilla.fileName)); } - } + })); + } - /// - /// Searches to forward direction. - /// - private void Forward() + /// + /// Searches to backward direction. + /// + private void Backward() + { + SaveSearchText(); // save the used search text to the database.. + var result = SearchReplaceDocuments?.Backward(); + if (result.HasValue && !result.Equals(TextSearcherAndReplacer.Empty)) { - SaveSearchText(); // save the used search text to the database.. - var result = SearchReplaceDocuments?.Forward(); - if (result.HasValue && !result.Equals(TextSearcherAndReplacer.Empty)) - { - GetCurrentDocument().scintilla.SelectionStart = result.Value.position; - GetCurrentDocument().scintilla.SelectionEnd = result.Value.position + result.Value.length; - GetCurrentDocument().scintilla.ScrollCaret(); + GetCurrentDocument().scintilla.SelectionStart = result.Value.position; + GetCurrentDocument().scintilla.SelectionEnd = result.Value.position + result.Value.length; + GetCurrentDocument().scintilla.ScrollCaret(); - // set the flag to indicate a the selection was changed from this form.. - SelectionChangedFromMainForm = false; + // set the flag to indicate a the selection was changed from this form.. + SelectionChangedFromMainForm = false; - SetStatus(Color.ForestGreen, - DBLangEngine.GetMessage("msgSearchFound", - "Find: found at {0}.|A message (in a status strip label) describing that the search text was found at a position with the search and replace dialog", - result.Value.position)); - } - else - { - SetStatus(Color.Red, - DBLangEngine.GetMessage("msgSearchNotFound", - "Find: not found.|A message (in a status strip label) describing that the search text wasn't found with the search and replace dialog")); - } + SetStatus(Color.ForestGreen, + DBLangEngine.GetMessage("msgSearchFound", + "Find: found at {0}.|A message (in a status strip label) describing that the search text was found at a position with the search and replace dialog", + result.Value.position)); } + else + { + SetStatus(Color.Red, + DBLangEngine.GetMessage("msgSearchNotFound", + "Find: not found.|A message (in a status strip label) describing that the search text wasn't found with the search and replace dialog")); + } + } - /// - /// Searches all the found files for a match. - /// - private void FindAllInFiles() + /// + /// Searches to forward direction. + /// + private void Forward() + { + SaveSearchText(); // save the used search text to the database.. + var result = SearchReplaceDocuments?.Forward(); + if (result.HasValue && !result.Equals(TextSearcherAndReplacer.Empty)) { - SaveSearchText(); // save the used search text to the database.. - SaveReplaceText(); // save the used replace text to the database.. - SaveFilters(); // save the used file extension filter to the database.. - SavePaths(); // save the path used in the search into the database.. + GetCurrentDocument().scintilla.SelectionStart = result.Value.position; + GetCurrentDocument().scintilla.SelectionEnd = result.Value.position + result.Value.length; + GetCurrentDocument().scintilla.ScrollCaret(); + + // set the flag to indicate a the selection was changed from this form.. + SelectionChangedFromMainForm = false; - // make a list suitable for the FormSearchResultTree class instance.. - List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)> results = - new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)>(); + SetStatus(Color.ForestGreen, + DBLangEngine.GetMessage("msgSearchFound", + "Find: found at {0}.|A message (in a status strip label) describing that the search text was found at a position with the search and replace dialog", + result.Value.position)); + } + else + { + SetStatus(Color.Red, + DBLangEngine.GetMessage("msgSearchNotFound", + "Find: not found.|A message (in a status strip label) describing that the search text wasn't found with the search and replace dialog")); + } + } - // create a new instance of the DirectoryCrawler class by user given "arguments".. - DirectoryCrawler crawler = new DirectoryCrawler(cmbDirectory3.Text, DirectoryCrawler.SearchTypeMatch.Regex, - cmbFilters3.Text, cbInSubFolders.Checked); + /// + /// Searches all the found files for a match. + /// + private void FindAllInFiles() + { + SaveSearchText(); // save the used search text to the database.. + SaveReplaceText(); // save the used replace text to the database.. + SaveFilters(); // save the used file extension filter to the database.. + SavePaths(); // save the path used in the search into the database.. - // create a invisible scintilla control for the process.. - Scintilla contents = new Scintilla {Visible = false}; + // make a list suitable for the FormSearchResultTree class instance.. + List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)> results = + new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)>(); - // invocations to the control can't be made if the control has no handle.. - Controls.Add(contents); + // create a new instance of the DirectoryCrawler class by user given "arguments".. + DirectoryCrawler crawler = new DirectoryCrawler(cmbDirectory3.Text, DirectoryCrawler.SearchTypeMatch.Regex, + cmbFilters3.Text, cbInSubFolders.Checked); - // ReSharper disable once ObjectCreationAsStatement + // create a invisible scintilla control for the process.. + Scintilla contents = new Scintilla {Visible = false, }; - // initialize a new FormDialogSearchReplaceProgressFiles dialog form with the - // DirectoryCrawler class instance as parameter and a delegate for the - // FormDialogSearchReplaceProgressFiles.RequestNextAction.. - new FormDialogSearchReplaceProgressFiles(crawler, - // no name for this delegate.. - (_, args) => + // invocations to the control can't be made if the control has no handle.. + Controls.Add(contents); + + // ReSharper disable once ObjectCreationAsStatement + + // initialize a new FormDialogSearchReplaceProgressFiles dialog form with the + // DirectoryCrawler class instance as parameter and a delegate for the + // FormDialogSearchReplaceProgressFiles.RequestNextAction.. + new FormDialogSearchReplaceProgressFiles(crawler, + // no name for this delegate.. + (_, args) => + { + // check the settings for a maximum search file size.. + if ((new FileInfo(args.FileName)).Length > FormSettings.Settings.FileSearchMaxSizeMb * 1000000) { - // check the settings for a maximum search file size.. - if ((new FileInfo(args.FileName)).Length > FormSettings.Settings.FileSearchMaxSizeMb * 1000000) - { - // .. and if exceeded, skip the file.. - args.SkipFile = true; - } - else // ..otherwise do continue.. + // .. and if exceeded, skip the file.. + args.SkipFile = true; + } + else // ..otherwise do continue.. + { + // invoke the Scintilla to get new contents of the new file.. + contents.Invoke(new MethodInvoker(delegate { - // invoke the Scintilla to get new contents of the new file.. - contents.Invoke(new MethodInvoker(delegate - { - // just read all the text in the file and set it to the Scintilla.. - contents.Text = File.ReadAllText(args.FileName); + // just read all the text in the file and set it to the Scintilla.. + contents.Text = File.ReadAllText(args.FileName); - // by not doing this the memory consumption might get HIGH.. - contents.EmptyUndoBuffer(); + // by not doing this the memory consumption might get HIGH.. + contents.EmptyUndoBuffer(); - // create a new search algorithm for the file and it's contents.. - CreateSingleSearchReplaceAlgorithm((contents, args.FileName)); - })); + // create a new search algorithm for the file and it's contents.. + CreateSingleSearchReplaceAlgorithm((contents, args.FileName)); + })); - // set the new TextSearcherAndReplacer class instance to the event's argument.. - args.SearchAndReplacer = SearchReplaceDocuments; + // set the new TextSearcherAndReplacer class instance to the event's argument.. + args.SearchAndReplacer = SearchReplaceDocuments; - // set the action to run for the file in the FormDialogSearchReplaceProgressFiles class instance.. - args.Action = () => - { - results.AddRange(ToTreeResult(SearchReplaceDocuments?.FindAll(100), contents, - args.FileName, false)); - }; - } - }); + // set the action to run for the file in the FormDialogSearchReplaceProgressFiles class instance.. + args.Action = () => + { + results.AddRange(ToTreeResult(SearchReplaceDocuments?.FindAll(100), contents, + args.FileName, false)); + }; + } + }); - // no need to display an empty tree view; so the comparison.. - if (results.Count > 0) - { - // create the FormSearchResultTree class instance.. - var tree = new FormSearchResultTree(); - - // display the tree.. - tree.Show(); - - // set the search results for the FormSearchResultTree class instance.. - tree.SearchResults = results; - } + // no need to display an empty tree view; so the comparison.. + if (results.Count > 0) + { + // create the FormSearchResultTree class instance.. + var tree = new FormSearchResultTree(); - // set the Scintilla free (!).. - using (contents) - { - Controls.Remove(contents); - } + // display the tree.. + tree.Show(); - // indicate the count value to the user.. - SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, - DBLangEngine.GetMessage("msgSearchFoundCountFiles", - "Found: {0} in {1} files|A message describing a count of search or replace results in multiple files", - results.Count, results.Select(f => f.fileName).Distinct().Count())); + // set the search results for the FormSearchResultTree class instance.. + tree.SearchResults = results; } - /// - /// Searches all the found files for a match and replaces the matches with the given replace text. - /// - private void ReplaceAllInFiles() + // set the Scintilla free (!).. + using (contents) { - SaveSearchText(); // save the used search text to the database.. - SaveReplaceText(); // save the used replace text to the database.. - SaveFilters(); // save the used file extension filter to the database.. - SavePaths(); // save the path used in the search into the database.. + Controls.Remove(contents); + } + + // indicate the count value to the user.. + SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, + DBLangEngine.GetMessage("msgSearchFoundCountFiles", + "Found: {0} in {1} files|A message describing a count of search or replace results in multiple files", + results.Count, results.Select(f => f.fileName).Distinct().Count())); + } + + /// + /// Searches all the found files for a match and replaces the matches with the given replace text. + /// + private void ReplaceAllInFiles() + { + SaveSearchText(); // save the used search text to the database.. + SaveReplaceText(); // save the used replace text to the database.. + SaveFilters(); // save the used file extension filter to the database.. + SavePaths(); // save the path used in the search into the database.. - string toReplaceWith = cmbReplace3.Text; + string toReplaceWith = cmbReplace3.Text; - // create a new instance of the DirectoryCrawler class by user given "arguments".. - DirectoryCrawler crawler = new DirectoryCrawler(cmbDirectory3.Text, DirectoryCrawler.SearchTypeMatch.Regex, - cmbFilters3.Text, cbInSubFolders.Checked); + // create a new instance of the DirectoryCrawler class by user given "arguments".. + DirectoryCrawler crawler = new DirectoryCrawler(cmbDirectory3.Text, DirectoryCrawler.SearchTypeMatch.Regex, + cmbFilters3.Text, cbInSubFolders.Checked); - // create a invisible scintilla control for the process.. - Scintilla contents = new Scintilla {Visible = false}; + // create a invisible scintilla control for the process.. + Scintilla contents = new Scintilla {Visible = false, }; - // invocations to the control can't be made if the control has no handle.. - Controls.Add(contents); + // invocations to the control can't be made if the control has no handle.. + Controls.Add(contents); - int replaceCount = 0; - int filesAffected = 0; + int replaceCount = 0; + int filesAffected = 0; - // ReSharper disable once ObjectCreationAsStatement + // ReSharper disable once ObjectCreationAsStatement - // initialize a new FormDialogSearchReplaceProgressFiles dialog form with the - // DirectoryCrawler class instance as parameter and a delegate for the - // FormDialogSearchReplaceProgressFiles.RequestNextAction.. - new FormDialogSearchReplaceProgressFiles(crawler, - // no name for this delegate.. - (_, args) => + // initialize a new FormDialogSearchReplaceProgressFiles dialog form with the + // DirectoryCrawler class instance as parameter and a delegate for the + // FormDialogSearchReplaceProgressFiles.RequestNextAction.. + new FormDialogSearchReplaceProgressFiles(crawler, + // no name for this delegate.. + (_, args) => + { + // check the settings for a maximum search file size.. + if ((new FileInfo(args.FileName)).Length > FormSettings.Settings.FileSearchMaxSizeMb * 1000000) { - // check the settings for a maximum search file size.. - if ((new FileInfo(args.FileName)).Length > FormSettings.Settings.FileSearchMaxSizeMb * 1000000) - { - // .. and if exceeded, skip the file.. - args.SkipFile = true; - } - else // ..otherwise do continue.. + // .. and if exceeded, skip the file.. + args.SkipFile = true; + } + else // ..otherwise do continue.. + { + // invoke the Scintilla to get new contents of the new file.. + contents.Invoke(new MethodInvoker(delegate { - // invoke the Scintilla to get new contents of the new file.. - contents.Invoke(new MethodInvoker(delegate - { - // just read all the text in the file and set it to the Scintilla.. - contents.Text = File.ReadAllText(args.FileName); + // just read all the text in the file and set it to the Scintilla.. + contents.Text = File.ReadAllText(args.FileName); - // by not doing this the memory consumption might get HIGH.. - contents.EmptyUndoBuffer(); + // by not doing this the memory consumption might get HIGH.. + contents.EmptyUndoBuffer(); - // create a new search algorithm for the file and it's contents.. - CreateSingleSearchReplaceAlgorithm((contents, args.FileName)); - })); + // create a new search algorithm for the file and it's contents.. + CreateSingleSearchReplaceAlgorithm((contents, args.FileName)); + })); - // set the new TextSearcherAndReplacer class instance to the event's argument.. - args.SearchAndReplacer = SearchReplaceDocuments; + // set the new TextSearcherAndReplacer class instance to the event's argument.. + args.SearchAndReplacer = SearchReplaceDocuments; - // set the action to run for the file in the FormDialogSearchReplaceProgressFiles class instance.. - args.Action = () => + // set the action to run for the file in the FormDialogSearchReplaceProgressFiles class instance.. + args.Action = () => + { + var replacements = SearchReplaceDocuments?.ReplaceAll(toReplaceWith, 100); + if (replacements.HasValue) { - var replacements = SearchReplaceDocuments?.ReplaceAll(toReplaceWith, 100); - if (replacements.HasValue) + if (replacements.Value.count > 0) { - if (replacements.Value.count > 0) - { - File.WriteAllText(args.FileName, replacements.Value.newContents); - filesAffected++; - - replaceCount += replacements.Value.count; - } - } - }; - } - }); + File.WriteAllText(args.FileName, replacements.Value.newContents); + filesAffected++; - // set the Scintilla free (!).. - using (contents) - { - Controls.Remove(contents); - } + replaceCount += replacements.Value.count; + } + } + }; + } + }); - // indicate the replacement count.. - SetStatus(replaceCount > 0 ? Color.ForestGreen : Color.Red, - ssLbStatus.Text = DBLangEngine.GetMessage("msgReplacementsMadeFilesAmount", - "Replaced {0} occurrences in {1} files.|A message indicating and amount of replacements made to files in the files system and how many files were affected.", - replaceCount, filesAffected)); + // set the Scintilla free (!).. + using (contents) + { + Controls.Remove(contents); } - /// - /// Marks all occurrences of a text of the active document with user defined color. - /// - private void MarkAll() - { - SaveSearchText(); // save the used search text to the database.. + // indicate the replacement count.. + SetStatus(replaceCount > 0 ? Color.ForestGreen : Color.Red, + ssLbStatus.Text = DBLangEngine.GetMessage("msgReplacementsMadeFilesAmount", + "Replaced {0} occurrences in {1} files.|A message indicating and amount of replacements made to files in the files system and how many files were affected.", + replaceCount, filesAffected)); + } - // make a list suitable for the search results.. - List<(int position, int length, string foundString)> results = - new List<(int position, int length, string foundString)>(); + /// + /// Marks all occurrences of a text of the active document with user defined color. + /// + private void MarkAll() + { + SaveSearchText(); // save the used search text to the database.. - if (cbClearPreviousMarks4.Checked) - { - ClearAllMarks(); - } + // make a list suitable for the search results.. + List<(int position, int length, string foundString)> results = + new List<(int position, int length, string foundString)>(); + + if (cbClearPreviousMarks4.Checked) + { + ClearAllMarks(); + } - // a necessary null check.. - if (CurrentDocument.scintilla != null) + // a necessary null check.. + if (CurrentDocument.scintilla != null) + { + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSearchReplaceProgress(delegate { - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSearchReplaceProgress(delegate + // create a new search algorithm for the current document.. + Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); + + // search for all the matches in the current document.. + if (SearchReplaceDocuments != null) { - // create a new search algorithm for the current document.. - Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); + results.AddRange(SearchReplaceDocuments?.FindAll(100).ToList()); - // search for all the matches in the current document.. - if (SearchReplaceDocuments != null) - { - results.AddRange(SearchReplaceDocuments?.FindAll(100).ToList()); + // reset the search algorithm.. + SearchReplaceDocuments?.ResetSearch(); + } - // reset the search algorithm.. - SearchReplaceDocuments?.ResetSearch(); - } + }, SearchReplaceDocuments); - }, SearchReplaceDocuments); + if (results.Count > 0) + { + int num = 25; - if (results.Count > 0) + // clear the previous marks if requested.. + if (cbClearPreviousMarks4.Checked) { - int num = 25; - - // clear the previous marks if requested.. - if (cbClearPreviousMarks4.Checked) - { - // Remove all uses of our indicator - CurrentDocument.scintilla.IndicatorCurrent = num; - CurrentDocument.scintilla.IndicatorClearRange(0, CurrentDocument.scintilla.TextLength); - } - - // Update indicator appearance - CurrentDocument.scintilla.Indicators[num].Style = IndicatorStyle.StraightBox; - CurrentDocument.scintilla.Indicators[num].Under = true; - CurrentDocument.scintilla.Indicators[num].ForeColor = FormSettings.Settings.MarkSearchReplaceColor; - CurrentDocument.scintilla.Indicators[num].OutlineAlpha = 255; - CurrentDocument.scintilla.Indicators[num].Alpha = 255; + // Remove all uses of our indicator CurrentDocument.scintilla.IndicatorCurrent = num; + CurrentDocument.scintilla.IndicatorClearRange(0, CurrentDocument.scintilla.TextLength); + } + // Update indicator appearance + CurrentDocument.scintilla.Indicators[num].Style = IndicatorStyle.StraightBox; + CurrentDocument.scintilla.Indicators[num].Under = true; + CurrentDocument.scintilla.Indicators[num].ForeColor = FormSettings.Settings.MarkSearchReplaceColor; + CurrentDocument.scintilla.Indicators[num].OutlineAlpha = 255; + CurrentDocument.scintilla.Indicators[num].Alpha = 255; + CurrentDocument.scintilla.IndicatorCurrent = num; - foreach (var result in results) - { - // Mark the search results with the current indicator - CurrentDocument.scintilla.IndicatorFillRange( - cbInSelection4.Checked - ? CurrentDocument.scintilla.SelectionStart + result.position - : result.position, result.length); - } + + foreach (var result in results) + { + // Mark the search results with the current indicator + CurrentDocument.scintilla.IndicatorFillRange( + cbInSelection4.Checked + ? CurrentDocument.scintilla.SelectionStart + result.position + : result.position, result.length); } - // indicate the count value to the user.. - SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, - DBLangEngine.GetMessage("msgSearchFoundCount", - "Found: {0}|A message describing a count of search or replace results", results.Count)); } + // indicate the count value to the user.. + SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, + DBLangEngine.GetMessage("msgSearchFoundCount", + "Found: {0}|A message describing a count of search or replace results", results.Count)); } + } - /// - /// Clears all marks marked with the method. - /// - private void ClearAllMarks() + /// + /// Clears all marks marked with the method. + /// + private void ClearAllMarks() + { + if (CurrentDocument.scintilla != null) { - if (CurrentDocument.scintilla != null) - { - CurrentDocument.scintilla.IndicatorCurrent = 25; - CurrentDocument.scintilla.IndicatorClearRange(0, CurrentDocument.scintilla.TextLength); - } + CurrentDocument.scintilla.IndicatorCurrent = 25; + CurrentDocument.scintilla.IndicatorClearRange(0, CurrentDocument.scintilla.TextLength); } + } - /// - /// Sets the status strip label text with a given color. - /// - /// The color of the status strip label. - /// The text for the status strip label. - private void SetStatus(Color color, string text) - { - ssLbStatus.ForeColor = color; - ssLbStatus.Text = text; - } + /// + /// Sets the status strip label text with a given color. + /// + /// The color of the status strip label. + /// The text for the status strip label. + private void SetStatus(Color color, string text) + { + ssLbStatus.ForeColor = color; + ssLbStatus.Text = text; + } - /// - /// Gets the documents open in the main form. - /// - /// If set to true all the open documents are returned. - /// The document(s) currently opened on the main form. - private List<(Scintilla scintilla, string fileName)> GetDocuments(bool allDocuments) - { - // create a ScintillaDocumentEventArgs class instance.. - ScintillaDocumentEventArgs scintillaDocumentEventArgs = - new ScintillaDocumentEventArgs - { - // set the value whether all the open documents are requested.. - RequestAllDocuments = allDocuments - }; + /// + /// Gets the documents open in the main form. + /// + /// If set to true all the open documents are returned. + /// The document(s) currently opened on the main form. + private List<(Scintilla scintilla, string fileName)> GetDocuments(bool allDocuments) + { + // create a ScintillaDocumentEventArgs class instance.. + ScintillaDocumentEventArgs scintillaDocumentEventArgs = + new ScintillaDocumentEventArgs + { + // set the value whether all the open documents are requested.. + RequestAllDocuments = allDocuments, + }; - // if the event is subscribed, raise the event.. - RequestDocuments?.Invoke(this, scintillaDocumentEventArgs); + // if the event is subscribed, raise the event.. + RequestDocuments?.Invoke(this, scintillaDocumentEventArgs); - // return the result.. - return scintillaDocumentEventArgs.Documents; - } + // return the result.. + return scintillaDocumentEventArgs.Documents; + } - /// - /// Gets the current document active in the main form. - /// - /// A Scintilla document currently active in the main form. - private (Scintilla scintilla, string fileName) GetCurrentDocument() - { - return GetDocuments(false).Count > 0 ? - GetDocuments(false)[0] : (null, null); - } + /// + /// Gets the current document active in the main form. + /// + /// A Scintilla document currently active in the main form. + private (Scintilla scintilla, string fileName) GetCurrentDocument() + { + return GetDocuments(false).Count > 0 ? + GetDocuments(false)[0] : (null, null); + } - /// - /// Toggles the transparency based on the saved transparency settings of the form. - /// - /// A value indicating whether the form is activated. - private void TransparencyToggle(bool activated) - { - // suspend the change event.. - SuspendTransparencyChangeEvent = true; + /// + /// Toggles the transparency based on the saved transparency settings of the form. + /// + /// A value indicating whether the form is activated. + private void TransparencyToggle(bool activated) + { + // suspend the change event.. + SuspendTransparencyChangeEvent = true; - try - { + try + { - // set the enabled value of the transparency setting group boxes to disabled.. - cbTransparency.Checked = true; - cbTransparency2.Checked = true; - cbTransparency3.Checked = true; + // set the enabled value of the transparency setting group boxes to disabled.. + cbTransparency.Checked = true; + cbTransparency2.Checked = true; + cbTransparency3.Checked = true; - // set the enabled value of the transparency setting group boxes to enabled.. - gpTransparency.Enabled = true; - gpTransparency2.Enabled = true; - gpTransparency3.Enabled = true; + // set the enabled value of the transparency setting group boxes to enabled.. + gpTransparency.Enabled = true; + gpTransparency2.Enabled = true; + gpTransparency3.Enabled = true; - // transparency is disabled.. - if (FormSettings.Settings.SearchBoxTransparency == 0) - { - // set the enabled value of the transparency setting group boxes to disabled.. - cbTransparency.Checked = false; - cbTransparency2.Checked = false; - cbTransparency3.Checked = false; + // transparency is disabled.. + if (FormSettings.Settings.SearchBoxTransparency == 0) + { + // set the enabled value of the transparency setting group boxes to disabled.. + cbTransparency.Checked = false; + cbTransparency2.Checked = false; + cbTransparency3.Checked = false; - gpTransparency.Enabled = false; - gpTransparency2.Enabled = false; - gpTransparency3.Enabled = false; + gpTransparency.Enabled = false; + gpTransparency2.Enabled = false; + gpTransparency3.Enabled = false; - // set the opacity value to 100%.. - Opacity = 1; - } - // transparency is enabled while active.. - else if (FormSettings.Settings.SearchBoxTransparency == 1) - { - rbTransparencyOnLosingFocus.Checked = true; - rbTransparencyOnLosingFocus2.Checked = true; - rbTransparencyOnLosingFocus3.Checked = true; - // set the opacity value to based on the active property.. - Opacity = activated ? 1 : FormSettings.Settings.SearchBoxOpacity; - } - else if (FormSettings.Settings.SearchBoxTransparency == 2) - { - rbTransparencyAlways.Checked = true; - rbTransparencyAlways2.Checked = true; - rbTransparencyAlways3.Checked = true; - Opacity = FormSettings.Settings.SearchBoxOpacity; - } + // set the opacity value to 100%.. + Opacity = 1; } - catch (Exception ex) + // transparency is enabled while active.. + else if (FormSettings.Settings.SearchBoxTransparency == 1) { - // log the exception.. - ExceptionLogger.LogError(ex); + rbTransparencyOnLosingFocus.Checked = true; + rbTransparencyOnLosingFocus2.Checked = true; + rbTransparencyOnLosingFocus3.Checked = true; + // set the opacity value to based on the active property.. + Opacity = activated ? 1 : FormSettings.Settings.SearchBoxOpacity; } - - SuspendTransparencyChangeEvent = false; - } - - /// - /// Creates a result list for the to display the results. - /// - /// A collection of search result created by the class instance. - /// A class instance to be used to fill the return value with. - /// The file name to be used with the result value with. - /// A flag indicating whether the is an opened file in the application. - /// A list of results created with the given parameters for the class instance. - private - List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)> ToTreeResult(IEnumerable<(int posion, int length, string foundString)> searchResults, - Scintilla scintilla, string fileName, bool isFileOpen) - { - List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)> result = - new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)>(); - - // loop trough the search result to create a little more complex list of them ;-) with the given parameters.. - foreach (var searchResult in searchResults) + else if (FormSettings.Settings.SearchBoxTransparency == 2) { - Invoke(new MethodInvoker(delegate - { - result.Add((fileName, scintilla.LineFromPosition(searchResult.posion), searchResult.posion, - searchResult.length, scintilla.Lines[scintilla.LineFromPosition(searchResult.posion)].Text, - isFileOpen)); - })); + rbTransparencyAlways.Checked = true; + rbTransparencyAlways2.Checked = true; + rbTransparencyAlways3.Checked = true; + Opacity = FormSettings.Settings.SearchBoxOpacity; } - - // return the result.. - return result; } - #endregion - - #region PrivateEvents - // the user wants to change the color of the mark tab page.. - private void BtMarkColor_Click(object sender, EventArgs e) + catch (Exception ex) { - if (cdColors.ShowDialog() == DialogResult.OK) - { - Button button = (Button) sender; - button.BackColor = cdColors.Color; - - // save the user assigned color.. - FormSettings.Settings.MarkSearchReplaceColor = cdColors.Color; - } + // log the exception.. + ExceptionLogger.LogError(ex); } - // occurs when the application is activated.. - private void FormSearchAndReplace_ApplicationDeactivated(object sender, EventArgs e) + SuspendTransparencyChangeEvent = false; + } + + /// + /// Creates a result list for the to display the results. + /// + /// A collection of search result created by the class instance. + /// A class instance to be used to fill the return value with. + /// The file name to be used with the result value with. + /// A flag indicating whether the is an opened file in the application. + /// A list of results created with the given parameters for the class instance. + private + List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)> ToTreeResult(IEnumerable<(int posion, int length, string foundString)> searchResults, + Scintilla scintilla, string fileName, bool isFileOpen) + { + List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)> result = + new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)>(); + + // loop trough the search result to create a little more complex list of them ;-) with the given parameters.. + foreach (var searchResult in searchResults) { - if (Visible) + Invoke(new MethodInvoker(delegate { - TopMost = false; - } + result.Add((fileName, scintilla.LineFromPosition(searchResult.posion), searchResult.posion, + searchResult.length, scintilla.Lines[scintilla.LineFromPosition(searchResult.posion)].Text, + isFileOpen)); + })); } - private void FormSearchAndReplace_ApplicationActivated(object sender, EventArgs e) + // return the result.. + return result; + } + #endregion + + #region PrivateEvents + // the user wants to change the color of the mark tab page.. + private void BtMarkColor_Click(object sender, EventArgs e) + { + if (cdColors.ShowDialog() == DialogResult.OK) { - if (Visible) - { - TopMost = true; - } + Button button = (Button) sender; + button.BackColor = cdColors.Color; + + // save the user assigned color.. + FormSettings.Settings.MarkSearchReplaceColor = cdColors.Color; } + } - // a user wishes to search to the backward direction.. - private void btFindPrevious_Click(object sender, EventArgs e) + // occurs when the application is activated.. + private void FormSearchAndReplace_ApplicationDeactivated(object sender, EventArgs e) + { + if (Visible) { - Backward(); + TopMost = false; } + } - // a user wishes to search to the forward direction.. - private void btFindNext_Click(object sender, EventArgs e) + private void FormSearchAndReplace_ApplicationActivated(object sender, EventArgs e) + { + if (Visible) { - Forward(); + TopMost = true; } + } - /// - /// This event is fired when the class instance reports internal progress. - /// - /// The sender of the event. - /// The instance containing the event data. - private void SearchOpenDocuments_SearchProgress(object sender, TextSearcherEventArgs e) - { - // as this event is fired from another thread, do invoke.. - Invoke(new MethodInvoker(delegate - { - // set the status message.. - ssLbStatus.Text = DBLangEngine.GetMessage("msgSearchProgress", - "File: {0}, Progress: {1}|A message describing a search or replace progress with a file name and a progress percentage", - e.FileNameNoPath, e.Percentage); + // a user wishes to search to the backward direction.. + private void btFindPrevious_Click(object sender, EventArgs e) + { + Backward(); + } - // set the progress bar value.. - pbSearchProgress.Value = e.Percentage; - })); - } + // a user wishes to search to the forward direction.. + private void btFindNext_Click(object sender, EventArgs e) + { + Forward(); + } - // prevent the singleton instance of disposing it self if not allowed by AllowInstanceDispose property.. - private void FormSearchAndReplace_FormClosing(object sender, FormClosingEventArgs e) + /// + /// This event is fired when the class instance reports internal progress. + /// + /// The sender of the event. + /// The instance containing the event data. + private void SearchOpenDocuments_SearchProgress(object sender, TextSearcherEventArgs e) + { + // as this event is fired from another thread, do invoke.. + Invoke(new MethodInvoker(delegate { - // as this form acts a bit different, do save the positioning here.. - PositionForms.SavePosition(this); + // set the status message.. + ssLbStatus.Text = DBLangEngine.GetMessage("msgSearchProgress", + "File: {0}, Progress: {1}|A message describing a search or replace progress with a file name and a progress percentage", + e.FileNameNoPath, e.Percentage); + + // set the progress bar value.. + pbSearchProgress.Value = e.Percentage; + })); + } - // save the flag indicating whether the form was closed by the user.. - UserClosed = e.CloseReason == CloseReason.UserClosing; + // prevent the singleton instance of disposing it self if not allowed by AllowInstanceDispose property.. + private void FormSearchAndReplace_FormClosing(object sender, FormClosingEventArgs e) + { + // as this form acts a bit different, do save the positioning here.. + PositionForms.SavePosition(this); - e.Cancel = !AllowInstanceDispose; - if (!AllowInstanceDispose) - { - // set the value to the property.. - PreviousVisible = Visible; - Hide(); - } - } + // save the flag indicating whether the form was closed by the user.. + UserClosed = e.CloseReason == CloseReason.UserClosing; - // the form was allowed to close, so do unsubscribe any events subscribed manually.. - private void FormSearchAndReplace_FormClosed(object sender, FormClosedEventArgs e) + e.Cancel = !AllowInstanceDispose; + if (!AllowInstanceDispose) { - // unsubscribe from an event which is raised upon application activation.. - ApplicationDeactivated -= FormSearchAndReplace_ApplicationDeactivated; - ApplicationActivated -= FormSearchAndReplace_ApplicationActivated; + // set the value to the property.. + PreviousVisible = Visible; + Hide(); } + } - // a new search class is constructed if the search or replace conditions have changed.. - private void SearchAndReplaceCondition_Changed(object sender, EventArgs e) - { - if (CurrentDocument.scintilla != null) - { - CreateSingleSearchReplaceAlgorithm(CurrentDocument); - } - - // set the navigation control states to enabled/disabled depending on the search condition.. - AppendValidation(); - } + // the form was allowed to close, so do unsubscribe any events subscribed manually.. + private void FormSearchAndReplace_FormClosed(object sender, FormClosedEventArgs e) + { + // unsubscribe from an event which is raised upon application activation.. + ApplicationDeactivated -= FormSearchAndReplace_ApplicationDeactivated; + ApplicationActivated -= FormSearchAndReplace_ApplicationActivated; + } - /// - /// Set the navigation control states to enabled/disabled depending on the search condition. - /// - private void AppendValidation() + // a new search class is constructed if the search or replace conditions have changed.. + private void SearchAndReplaceCondition_Changed(object sender, EventArgs e) + { + if (CurrentDocument.scintilla != null) { - btFindNext.Enabled = ValidSearchAndReplace(false); - btFindPrevious.Enabled = ValidSearchAndReplace(false); - btCount.Enabled = ValidSearchAndReplace(false); - btFindAllInAll.Enabled = ValidSearchAndReplace(false); - btFindAllCurrent.Enabled = ValidSearchAndReplace(false); + CreateSingleSearchReplaceAlgorithm(CurrentDocument); + } - btFindPrevious2.Enabled = ValidSearchAndReplace(false); - btFindNext2.Enabled = ValidSearchAndReplace(false); - btReplace.Enabled = ValidSearchAndReplace(true); - btReplaceAll.Enabled = ValidSearchAndReplace(true); - btReplaceAllInAll.Enabled = ValidSearchAndReplace(true); + // set the navigation control states to enabled/disabled depending on the search condition.. + AppendValidation(); + } - btFindAllInFiles.Enabled = ValidSearchAndReplace(false); - btReplaceAllInFiles.Enabled = ValidSearchAndReplace(true); + /// + /// Set the navigation control states to enabled/disabled depending on the search condition. + /// + private void AppendValidation() + { + btFindNext.Enabled = ValidSearchAndReplace(false); + btFindPrevious.Enabled = ValidSearchAndReplace(false); + btCount.Enabled = ValidSearchAndReplace(false); + btFindAllInAll.Enabled = ValidSearchAndReplace(false); + btFindAllCurrent.Enabled = ValidSearchAndReplace(false); + + btFindPrevious2.Enabled = ValidSearchAndReplace(false); + btFindNext2.Enabled = ValidSearchAndReplace(false); + btReplace.Enabled = ValidSearchAndReplace(true); + btReplaceAll.Enabled = ValidSearchAndReplace(true); + btReplaceAllInAll.Enabled = ValidSearchAndReplace(true); + + btFindAllInFiles.Enabled = ValidSearchAndReplace(false); + btReplaceAllInFiles.Enabled = ValidSearchAndReplace(true); + + // indicate an invalid filter.. + cmbFilters3.BackColor = DirectoryCrawler.ValidateExtensionRegexp(cmbFilters3.Text) + ? SystemColors.Window + : Color.Red; + + btMarkAll.Enabled = ValidSearchAndReplace(false); + } - // indicate an invalid filter.. - cmbFilters3.BackColor = DirectoryCrawler.ValidateExtensionRegexp(cmbFilters3.Text) - ? SystemColors.Window - : Color.Red; + // a user wishes to count all the matching strings of the currently active document.. + private void BtCount_Click(object sender, EventArgs e) + { + SaveSearchText(); // save the used search text to the database.. - btMarkAll.Enabled = ValidSearchAndReplace(false); - } + int count = 0; // set the occurrence count variable.. - // a user wishes to count all the matching strings of the currently active document.. - private void BtCount_Click(object sender, EventArgs e) + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSearchReplaceProgress(delegate { - SaveSearchText(); // save the used search text to the database.. - - int count = 0; // set the occurrence count variable.. + // search all the occurrences.. + var result = SearchReplaceDocuments?.FindAll(100); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSearchReplaceProgress(delegate - { - // search all the occurrences.. - var result = SearchReplaceDocuments?.FindAll(100); + Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); - Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); - - SearchReplaceDocuments?.ResetSearch(); + SearchReplaceDocuments?.ResetSearch(); - // save the count value.. - if (result != null) - { - count = result.Count(); - } - }, SearchReplaceDocuments); + // save the count value.. + if (result != null) + { + count = result.Count(); + } + }, SearchReplaceDocuments); - // indicate the count value to the user.. - SetStatus(count > 0 ? Color.RoyalBlue : Color.Red, - DBLangEngine.GetMessage("msgSearchFoundCount", - "Found: {0}|A message describing a count of search or replace results", count)); - } + // indicate the count value to the user.. + SetStatus(count > 0 ? Color.RoyalBlue : Color.Red, + DBLangEngine.GetMessage("msgSearchFoundCount", + "Found: {0}|A message describing a count of search or replace results", count)); + } - // get the previous tab index - private int previousTabIndex; + // get the previous tab index + private int previousTabIndex; - /// - /// Gets the previous search text used on the different tab compared to the current one. - /// - private string PreviousSearchText + /// + /// Gets the previous search text used on the different tab compared to the current one. + /// + private string PreviousSearchText + { + get { - get + switch (previousTabIndex) { - switch (previousTabIndex) - { - case 0: return cmbFind.Text; - case 1: return cmbFind2.Text; - case 2: return cmbFind3.Text; - case 3: return cmbFind4.Text; - } - - return string.Empty; + case 0: return cmbFind.Text; + case 1: return cmbFind2.Text; + case 2: return cmbFind3.Text; + case 3: return cmbFind4.Text; } + + return string.Empty; } + } - // indicate the current search or replace function => active tab.. - private void TcMain_TabIndexChanged(object sender, EventArgs e) + // indicate the current search or replace function => active tab.. + private void TcMain_TabIndexChanged(object sender, EventArgs e) + { + Text = tcMain.SelectedTab.Text; + if (tcMain.SelectedTab.Equals(tabFind)) { - Text = tcMain.SelectedTab.Text; - if (tcMain.SelectedTab.Equals(tabFind)) + if (previousTabIndex != tcMain.SelectedIndex) { - if (previousTabIndex != tcMain.SelectedIndex) - { - cmbFind.Text = PreviousSearchText; - } - cmbFind.Focus(); - } - else if (tcMain.SelectedTab.Equals(tabReplace)) + cmbFind.Text = PreviousSearchText; + } + cmbFind.Focus(); + } + else if (tcMain.SelectedTab.Equals(tabReplace)) + { + if (previousTabIndex != tcMain.SelectedIndex) { - if (previousTabIndex != tcMain.SelectedIndex) - { - cmbFind2.Text = PreviousSearchText; - } - cmbFind2.Focus(); + cmbFind2.Text = PreviousSearchText; } - else if (tcMain.SelectedTab.Equals(tabFindInFiles)) + cmbFind2.Focus(); + } + else if (tcMain.SelectedTab.Equals(tabFindInFiles)) + { + if (previousTabIndex != tcMain.SelectedIndex) { - if (previousTabIndex != tcMain.SelectedIndex) - { - cmbFind3.Text = PreviousSearchText; - } - cmbFind3.Focus(); + cmbFind3.Text = PreviousSearchText; } - else if (tcMain.SelectedTab.Equals(tabMarkMatches)) + cmbFind3.Focus(); + } + else if (tcMain.SelectedTab.Equals(tabMarkMatches)) + { + if (previousTabIndex != tcMain.SelectedIndex) { - if (previousTabIndex != tcMain.SelectedIndex) - { - cmbFind4.Text = PreviousSearchText; - } - cmbFind4.Focus(); + cmbFind4.Text = PreviousSearchText; } + cmbFind4.Focus(); + } - // save the tab index.. - previousTabIndex = tcMain.SelectedIndex; + // save the tab index.. + previousTabIndex = tcMain.SelectedIndex; - // set the navigation control states to enabled/disabled depending on the search condition.. - AppendValidation(); - } + // set the navigation control states to enabled/disabled depending on the search condition.. + AppendValidation(); + } - // the form is activated.. - private void FormSearchAndReplace_NeedReloadDocuments(object sender, EventArgs e) - { - // get the documents as they might have changed.. - Documents = GetDocuments(true); - CurrentDocument = GetCurrentDocument(); + // the form is activated.. + private void FormSearchAndReplace_NeedReloadDocuments(object sender, EventArgs e) + { + // get the documents as they might have changed.. + Documents = GetDocuments(true); + CurrentDocument = GetCurrentDocument(); - // set the transparency value.. - TransparencyToggle(true); + // set the transparency value.. + TransparencyToggle(true); - // set the navigation control states to enabled/disabled depending on the search condition.. - AppendValidation(); - } + // set the navigation control states to enabled/disabled depending on the search condition.. + AppendValidation(); + } - // the form is deactivated so set the transparency value.. - private void FormSearchAndReplace_Deactivate(object sender, EventArgs e) - { - TransparencyToggle(false); + // the form is deactivated so set the transparency value.. + private void FormSearchAndReplace_Deactivate(object sender, EventArgs e) + { + TransparencyToggle(false); - // set the navigation control states to enabled/disabled depending on the search condition.. - AppendValidation(); - } + // set the navigation control states to enabled/disabled depending on the search condition.. + AppendValidation(); + } - // a user wishes to close the form.. - private void BtClose_Click(object sender, EventArgs e) - { - // ..so lets obey.. - Close(); - } + // a user wishes to close the form.. + private void BtClose_Click(object sender, EventArgs e) + { + // ..so lets obey.. + Close(); + } - private void BtMarkAll_Click(object sender, EventArgs e) - { - MarkAll(); - } + private void BtMarkAll_Click(object sender, EventArgs e) + { + MarkAll(); + } - private void BtnClearAllMarks_Click(object sender, EventArgs e) - { - ClearAllMarks(); - } + private void BtnClearAllMarks_Click(object sender, EventArgs e) + { + ClearAllMarks(); + } - // A users wishes to find all occurrences within the active document.. - private void BtFindAllCurrent_Click(object sender, EventArgs e) - { - SaveSearchText(); // save the used search text to the database.. + // A users wishes to find all occurrences within the active document.. + private void BtFindAllCurrent_Click(object sender, EventArgs e) + { + SaveSearchText(); // save the used search text to the database.. - // make a list suitable for the FormSearchResultTree class instance.. - List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)> results = - new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)>(); + // make a list suitable for the FormSearchResultTree class instance.. + List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)> results = + new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)>(); - // a necessary null check.. - if (CurrentDocument.scintilla != null) + // a necessary null check.. + if (CurrentDocument.scintilla != null) + { + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSearchReplaceProgress(delegate { - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSearchReplaceProgress(delegate - { - // create a new search algorithm for the current document.. - Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); - - // search for all the matches in the current document.. - var result = SearchReplaceDocuments?.FindAll(100); + // create a new search algorithm for the current document.. + Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); - // reset the search algorithm.. - SearchReplaceDocuments?.ResetSearch(); + // search for all the matches in the current document.. + var result = SearchReplaceDocuments?.FindAll(100); - // get the results in a suitable format for the FormSearchResultTree class instance.. - results.AddRange(ToTreeResult(result, CurrentDocument.scintilla, CurrentDocument.fileName, true)); + // reset the search algorithm.. + SearchReplaceDocuments?.ResetSearch(); - }, SearchReplaceDocuments); - } + // get the results in a suitable format for the FormSearchResultTree class instance.. + results.AddRange(ToTreeResult(result, CurrentDocument.scintilla, CurrentDocument.fileName, true)); - // no need to display an empty tree view; so the comparison.. - if (results.Count > 0) - { - // create the FormSearchResultTree class instance.. - var tree = new FormSearchResultTree(); + }, SearchReplaceDocuments); + } - // display the tree.. - tree.Show(); + // no need to display an empty tree view; so the comparison.. + if (results.Count > 0) + { + // create the FormSearchResultTree class instance.. + var tree = new FormSearchResultTree(); - // set the search results for the FormSearchResultTree class instance.. - tree.SearchResults = results; - } + // display the tree.. + tree.Show(); - // indicate the count value to the user.. - SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, - DBLangEngine.GetMessage("msgSearchFoundCount", - "Found: {0}|A message describing a count of search or replace results", results.Count)); + // set the search results for the FormSearchResultTree class instance.. + tree.SearchResults = results; } - // A users wishes to find all occurrences within all the opened documents.. - private void BtFindAllInAll_Click(object sender, EventArgs e) - { - SaveSearchText(); // save the used search text to the database.. + // indicate the count value to the user.. + SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, + DBLangEngine.GetMessage("msgSearchFoundCount", + "Found: {0}|A message describing a count of search or replace results", results.Count)); + } - // make a list suitable for the FormSearchResultTree class instance.. - List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)> results = - new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)>(); + // A users wishes to find all occurrences within all the opened documents.. + private void BtFindAllInAll_Click(object sender, EventArgs e) + { + SaveSearchText(); // save the used search text to the database.. - // loop through all the open documents.. - foreach (var document in Documents) - { - // an instance reference is required in case the user wishes to cancel the search process - // before completion.. - var form = new FormDialogSearchReplaceProgress(delegate - { - // create a new search algorithm for the document.. - Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(document); })); + // make a list suitable for the FormSearchResultTree class instance.. + List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)> results = + new List<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)>(); - // search for all the matches in the document.. - var result = SearchReplaceDocuments?.FindAll(100); + // loop through all the open documents.. + foreach (var document in Documents) + { + // an instance reference is required in case the user wishes to cancel the search process + // before completion.. + var form = new FormDialogSearchReplaceProgress(delegate + { + // create a new search algorithm for the document.. + Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(document); })); - // reset the search algorithm.. - SearchReplaceDocuments?.ResetSearch(); + // search for all the matches in the document.. + var result = SearchReplaceDocuments?.FindAll(100); - // get the results in a suitable format for the FormSearchResultTree class instance.. - results.AddRange(ToTreeResult(result, document.scintilla, document.fileName, true)); + // reset the search algorithm.. + SearchReplaceDocuments?.ResetSearch(); - }, SearchReplaceDocuments); + // get the results in a suitable format for the FormSearchResultTree class instance.. + results.AddRange(ToTreeResult(result, document.scintilla, document.fileName, true)); - // if the user canceled then break the loop.. - if (form.Cancelled) - { - break; - } - } + }, SearchReplaceDocuments); - // no need to display an empty tree view; so the comparison.. - if (results.Count > 0) + // if the user canceled then break the loop.. + if (form.Cancelled) { - // create the FormSearchResultTree class instance.. - var tree = new FormSearchResultTree(); + break; + } + } - // display the tree.. - tree.Show(); + // no need to display an empty tree view; so the comparison.. + if (results.Count > 0) + { + // create the FormSearchResultTree class instance.. + var tree = new FormSearchResultTree(); - // set the search results for the FormSearchResultTree class instance.. - tree.SearchResults = results; - } + // display the tree.. + tree.Show(); - // indicate the count value to the user.. - SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, - DBLangEngine.GetMessage("msgSearchFoundCountFiles", - "Found: {0} in {1} files|A message describing a count of search or replace results in multiple files", - results.Count, results.Select(f => f.fileName).Distinct().Count())); + // set the search results for the FormSearchResultTree class instance.. + tree.SearchResults = results; } - // A users wishes to replace all occurrences within all the opened documents.. - private void BtReplaceAllInAll_Click(object sender, EventArgs e) - { - SaveSearchText(); // save the used search text to the database.. - SaveReplaceText(); // save the used replace text to the database.. + // indicate the count value to the user.. + SetStatus(results.Count > 0 ? Color.RoyalBlue : Color.Red, + DBLangEngine.GetMessage("msgSearchFoundCountFiles", + "Found: {0} in {1} files|A message describing a count of search or replace results in multiple files", + results.Count, results.Select(f => f.fileName).Distinct().Count())); + } + + // A users wishes to replace all occurrences within all the opened documents.. + private void BtReplaceAllInAll_Click(object sender, EventArgs e) + { + SaveSearchText(); // save the used search text to the database.. + SaveReplaceText(); // save the used replace text to the database.. - // make a suitable for the results.. - List<(string newContents, int count, string fileName, string fileNameNoPath)> results = - new List<(string newContents, int count, string fileName, string fileNameNoPath)>(); + // make a suitable for the results.. + List<(string newContents, int count, string fileName, string fileNameNoPath)> results = + new List<(string newContents, int count, string fileName, string fileNameNoPath)>(); - int fileCount = 0; + int fileCount = 0; - string replaceString = cmbReplace.Text; + string replaceString = cmbReplace.Text; - // loop through all the open documents.. - foreach (var document in Documents) + // loop through all the open documents.. + foreach (var document in Documents) + { + // an instance reference is required in case the user wishes to cancel the search process + // before completion.. + var form = new FormDialogSearchReplaceProgress(delegate { - // an instance reference is required in case the user wishes to cancel the search process - // before completion.. - var form = new FormDialogSearchReplaceProgress(delegate - { - // create a new search algorithm for the document.. - CreateSingleSearchReplaceAlgorithm(document); + // create a new search algorithm for the document.. + CreateSingleSearchReplaceAlgorithm(document); - // search for all the matches in the document.. - var result = SearchReplaceDocuments?.ReplaceAll(replaceString, 100); + // search for all the matches in the document.. + var result = SearchReplaceDocuments?.ReplaceAll(replaceString, 100); - if (result != null) + if (result != null) + { + // invoke as running in another thread.. + document.scintilla.Invoke(new MethodInvoker(delegate { - // invoke as running in another thread.. - document.scintilla.Invoke(new MethodInvoker(delegate - { - document.scintilla.Text = result.Value.newContents; - })); + document.scintilla.Text = result.Value.newContents; + })); - results.Add((result.Value.newContents, result.Value.count, SearchReplaceDocuments.FileName, SearchReplaceDocuments.FileNameNoPath)); + results.Add((result.Value.newContents, result.Value.count, SearchReplaceDocuments.FileName, SearchReplaceDocuments.FileNameNoPath)); - if (result.Value.count > 0) - { - fileCount++; - } + if (result.Value.count > 0) + { + fileCount++; } + } - // reset the search algorithm.. - SearchReplaceDocuments?.ResetSearch(); + // reset the search algorithm.. + SearchReplaceDocuments?.ResetSearch(); - }, SearchReplaceDocuments); + }, SearchReplaceDocuments); - // if the user canceled then break the loop.. - if (form.Cancelled) - { - break; - } + // if the user canceled then break the loop.. + if (form.Cancelled) + { + break; } - - // set the count value of replaced occurrences and file count on the status strip.. - SetStatus(results.Sum(f => f.count) > 0 ? Color.RoyalBlue : Color.Red, - DBLangEngine.GetMessage("msgSearchReplaceCountWithFiles", - "Replaced {0} occurrences from {1} files|A message describing a count of occurrences replaced and in how many files", - results.Sum(f => f.count), fileCount)); } - // a user wishes to replace the current search result in the current document.. - private void BtReplace_Click(object sender, EventArgs e) - { - SaveSearchText(); // save the used search text to the database.. - SaveReplaceText(); // save the used replace text to the database.. + // set the count value of replaced occurrences and file count on the status strip.. + SetStatus(results.Sum(f => f.count) > 0 ? Color.RoyalBlue : Color.Red, + DBLangEngine.GetMessage("msgSearchReplaceCountWithFiles", + "Replaced {0} occurrences from {1} files|A message describing a count of occurrences replaced and in how many files", + results.Sum(f => f.count), fileCount)); + } - // ..so do replace the selection gotten via call to Forward() or Backward() method.. - if (CurrentDocument.scintilla != null && CurrentDocument.scintilla.SelectedText.Length > 0) - { - CurrentDocument.scintilla?.ReplaceSelection(cmbReplace.Text); - } + // a user wishes to replace the current search result in the current document.. + private void BtReplace_Click(object sender, EventArgs e) + { + SaveSearchText(); // save the used search text to the database.. + SaveReplaceText(); // save the used replace text to the database.. - // a necessary null check.. - if (CurrentDocument.scintilla != null) - { - // re-create the search algorithm as its internal contents have not changed.. - CreateSingleSearchReplaceAlgorithm(CurrentDocument); - } + // ..so do replace the selection gotten via call to Forward() or Backward() method.. + if (CurrentDocument.scintilla != null && CurrentDocument.scintilla.SelectedText.Length > 0) + { + CurrentDocument.scintilla?.ReplaceSelection(cmbReplace.Text); } - // a user wishes to replace all occurrences in the current document.. - private void BtReplaceAll_Click(object sender, EventArgs e) + // a necessary null check.. + if (CurrentDocument.scintilla != null) { - SaveSearchText(); // save the used search text to the database.. - SaveReplaceText(); // save the used replace text to the database.. + // re-create the search algorithm as its internal contents have not changed.. + CreateSingleSearchReplaceAlgorithm(CurrentDocument); + } + } - // get the text to replace the occurrences with.. - string replaceStr = cmbReplace.Text; + // a user wishes to replace all occurrences in the current document.. + private void BtReplaceAll_Click(object sender, EventArgs e) + { + SaveSearchText(); // save the used search text to the database.. + SaveReplaceText(); // save the used replace text to the database.. - // create a variable for the result returned from the - // ReplaceAll() call.. - (string newContents, int count)? result = (string.Empty, 0); + // get the text to replace the occurrences with.. + string replaceStr = cmbReplace.Text; + // create a variable for the result returned from the + // ReplaceAll() call.. + (string newContents, int count)? result = (string.Empty, 0); - // ReSharper disable once ObjectCreationAsStatement - new FormDialogSearchReplaceProgress(delegate - { - // create a new search algorithm for the current document.. - Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); - // get the replace results.. - result = SearchReplaceDocuments?.ReplaceAll(replaceStr, 100); + // ReSharper disable once ObjectCreationAsStatement + new FormDialogSearchReplaceProgress(delegate + { + // create a new search algorithm for the current document.. + Invoke(new MethodInvoker(delegate { CreateSingleSearchReplaceAlgorithm(CurrentDocument); })); + + // get the replace results.. + result = SearchReplaceDocuments?.ReplaceAll(replaceStr, 100); - // reset the search algorithm.. - SearchReplaceDocuments?.ResetSearch(); - }, SearchReplaceDocuments); + // reset the search algorithm.. + SearchReplaceDocuments?.ResetSearch(); + }, SearchReplaceDocuments); - // validate that there is a result.. - if (result.HasValue) - { - // get a value if only the selection is required to be used as text for the algorithm.. - bool selection = cbInSelection2.Checked && tcMain.SelectedTab.Equals(tabReplace); + // validate that there is a result.. + if (result.HasValue) + { + // get a value if only the selection is required to be used as text for the algorithm.. + bool selection = cbInSelection2.Checked && tcMain.SelectedTab.Equals(tabReplace); - // set the new contents for the current document.. - if (selection) - { - CurrentDocument.scintilla.ReplaceSelection(result?.newContents); - } - else - { - CurrentDocument.scintilla.Text = result?.newContents; - } + // set the new contents for the current document.. + if (selection) + { + CurrentDocument.scintilla.ReplaceSelection(result?.newContents); + } + else + { + CurrentDocument.scintilla.Text = result?.newContents; + } - int count = result?.count ?? 0; + int count = result?.count ?? 0; - // set the count value of replaced occurrences on the status strip.. - SetStatus(count > 0 ? Color.ForestGreen : Color.Red, DBLangEngine.GetMessage("msgSearchReplaceCount", - "Replaced: {0}|A message describing a count of occurrences replaced", result?.count)); - } + // set the count value of replaced occurrences on the status strip.. + SetStatus(count > 0 ? Color.ForestGreen : Color.Red, DBLangEngine.GetMessage("msgSearchReplaceCount", + "Replaced: {0}|A message describing a count of occurrences replaced", result?.count)); } + } - private void TransparencySettings_Changed(object sender, EventArgs e) + private void TransparencySettings_Changed(object sender, EventArgs e) + { + // if suspended, return.. + if (SuspendTransparencyChangeEvent) { - // if suspended, return.. - if (SuspendTransparencyChangeEvent) - { - return; - } + return; + } - // suspend "self".. - SuspendTransparencyChangeEvent = true; - - // ReSharper disable once InconsistentNaming - RadioButton _rbTransparencyAlways = rbTransparencyAlways; - // ReSharper disable once InconsistentNaming - TrackBar _tbOpacity = tbOpacity; - // ReSharper disable once InconsistentNaming - CheckBox _cbTransparency = cbTransparency; - if (sender.Equals(cbTransparency2) || - sender.Equals(rbTransparencyAlways2) || - sender.Equals(rbTransparencyOnLosingFocus2) || - sender.Equals(tbOpacity2)) - { - _rbTransparencyAlways = rbTransparencyAlways2; - _tbOpacity = tbOpacity2; - _cbTransparency = cbTransparency2; - } - else if (sender.Equals(cbTransparency3) || + // suspend "self".. + SuspendTransparencyChangeEvent = true; + + // ReSharper disable once InconsistentNaming + RadioButton _rbTransparencyAlways = rbTransparencyAlways; + // ReSharper disable once InconsistentNaming + TrackBar _tbOpacity = tbOpacity; + // ReSharper disable once InconsistentNaming + CheckBox _cbTransparency = cbTransparency; + if (sender.Equals(cbTransparency2) || + sender.Equals(rbTransparencyAlways2) || + sender.Equals(rbTransparencyOnLosingFocus2) || + sender.Equals(tbOpacity2)) + { + _rbTransparencyAlways = rbTransparencyAlways2; + _tbOpacity = tbOpacity2; + _cbTransparency = cbTransparency2; + } + else if (sender.Equals(cbTransparency3) || sender.Equals(rbTransparencyAlways3) || sender.Equals(rbTransparencyOnLosingFocus3) || sender.Equals(tbOpacity3)) - { - _rbTransparencyAlways = rbTransparencyAlways3; - _tbOpacity = tbOpacity3; - _cbTransparency = cbTransparency3; - } - else if (sender.Equals(cbTransparency4) || - sender.Equals(rbTransparencyAlways4) || - sender.Equals(rbTransparencyOnLosingFocus4) || - sender.Equals(tbOpacity4)) - { - _rbTransparencyAlways = rbTransparencyAlways4; - _tbOpacity = tbOpacity4; - _cbTransparency = cbTransparency4; - } + { + _rbTransparencyAlways = rbTransparencyAlways3; + _tbOpacity = tbOpacity3; + _cbTransparency = cbTransparency3; + } + else if (sender.Equals(cbTransparency4) || + sender.Equals(rbTransparencyAlways4) || + sender.Equals(rbTransparencyOnLosingFocus4) || + sender.Equals(tbOpacity4)) + { + _rbTransparencyAlways = rbTransparencyAlways4; + _tbOpacity = tbOpacity4; + _cbTransparency = cbTransparency4; + } - if (_cbTransparency.Checked) - { - FormSettings.Settings.SearchBoxTransparency = _rbTransparencyAlways.Checked ? 2 : 1; - } - else - { - FormSettings.Settings.SearchBoxTransparency = 0; - } + if (_cbTransparency.Checked) + { + FormSettings.Settings.SearchBoxTransparency = _rbTransparencyAlways.Checked ? 2 : 1; + } + else + { + FormSettings.Settings.SearchBoxTransparency = 0; + } - FormSettings.Settings.SearchBoxOpacity = _tbOpacity.Value / 100.0; + FormSettings.Settings.SearchBoxOpacity = _tbOpacity.Value / 100.0; - // toggle the transparency control states.. - TransparencyToggle(ActiveForm != null && ActiveForm.Equals(this)); + // toggle the transparency control states.. + TransparencyToggle(ActiveForm != null && ActiveForm.Equals(this)); - // resume "self".. - SuspendTransparencyChangeEvent = false; - } + // resume "self".. + SuspendTransparencyChangeEvent = false; + } + + // searches for a text occurrences in multiple files on the file system.. + private void BtFindAllInFiles_Click(object sender, EventArgs e) + { + FindAllInFiles(); + } + + // replaces a text occurrences in multiple files on the file system.. + private void BtReplaceAllInFiles_Click(object sender, EventArgs e) + { + ReplaceAllInFiles(); + } + + // set the folder via the Ookii.Dialogs.WinForms.VistaFolderBrowserDialog class.. + private void BtSelectFolder_Click(object sender, EventArgs e) + { + var dialog = new VistaFolderBrowserDialog + { + Description = DBLangEngine.GetMessage("msgDirectoryDialogFindInFiles", + "Select a folder to search from|A message describing that the user should select a folder where search files from"), + UseDescriptionForTitle = true, + }; - // searches for a text occurrences in multiple files on the file system.. - private void BtFindAllInFiles_Click(object sender, EventArgs e) + if (Directory.Exists(cmbDirectory3.Text)) { - FindAllInFiles(); + dialog.SelectedPath = cmbDirectory3.Text; } - // replaces a text occurrences in multiple files on the file system.. - private void BtReplaceAllInFiles_Click(object sender, EventArgs e) + if (dialog.ShowDialog() == DialogResult.OK) { - ReplaceAllInFiles(); + cmbDirectory3.Text = dialog.SelectedPath; + SavePaths(); // save the path used in the search into the database.. } + } - // set the folder via the Ookii.Dialogs.WinForms.VistaFolderBrowserDialog class.. - private void BtSelectFolder_Click(object sender, EventArgs e) + /// + /// Some keyboard shortcuts for the search and replace dialog. + /// + /// The sender of the event. + /// The instance containing the event data. + private void FormSearchAndReplace_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.F3) { - var dialog = new VistaFolderBrowserDialog + if (e.OnlyShift() || e.NoModifierKeysDown()) { - Description = DBLangEngine.GetMessage("msgDirectoryDialogFindInFiles", - "Select a folder to search from|A message describing that the user should select a folder where search files from"), - UseDescriptionForTitle = true, - }; + // find the next result if available.. + Advance(!e.OnlyShift()); - if (Directory.Exists(cmbDirectory3.Text)) - { - dialog.SelectedPath = cmbDirectory3.Text; + // this is handled.. + e.Handled = true; + return; } + } + + // escape key was pressed, so the dialog can be closed.. + if (e.KeyCode == Keys.Escape && e.NoModifierKeysDown()) + { + e.Handled = true; + Close(); + return; + } - if (dialog.ShowDialog() == DialogResult.OK) + // the return key was pressed when a combo box was dropped down so suppress that.. + if (e.KeyCode == Keys.Return && ActiveControl is ComboBox comboBox) + { + if (comboBox.DroppedDown) { - cmbDirectory3.Text = dialog.SelectedPath; - SavePaths(); // save the path used in the search into the database.. + e.SuppressKeyPress = true; + return; } } - /// - /// Some keyboard shortcuts for the search and replace dialog. - /// - /// The sender of the event. - /// The instance containing the event data. - private void FormSearchAndReplace_KeyDown(object sender, KeyEventArgs e) + // use the return key to search either to forwards or to backwards direction.. + if (e.KeyCode == Keys.Return) { - if (e.KeyCode == Keys.F3) + // if the find tab is active.. + if (tcMain.SelectedTab.Equals(tabFind)) { - if (e.OnlyShift() || e.NoModifierKeysDown()) + if (btFindNext.Enabled && e.NoModifierKeysDown()) { - // find the next result if available.. - Advance(!e.OnlyShift()); - - // this is handled.. - e.Handled = true; - return; + // the return key was pressed with no modifiers, so search forwards.. + Forward(); + } + else if (btFindPrevious.Enabled && e.ModifierKeysDown(false, true, false)) + { + // the return key was pressed with the Control key down, so search backwards.. + Backward(); } - } - // escape key was pressed, so the dialog can be closed.. - if (e.KeyCode == Keys.Escape && e.NoModifierKeysDown()) - { + // flag the event as handled.. e.Handled = true; - Close(); - return; } - - // the return key was pressed when a combo box was dropped down so suppress that.. - if (e.KeyCode == Keys.Return && ActiveControl is ComboBox comboBox) + // if the search and replace tab is active.. + else if (tcMain.SelectedTab.Equals(tabReplace)) { - if (comboBox.DroppedDown) + if (btFindNext2.Enabled && e.NoModifierKeysDown()) + { + // the return key was pressed with no modifiers, so search forwards.. + Forward(); + } + else if (btFindPrevious2.Enabled && e.ModifierKeysDown(false, true, false)) { - e.SuppressKeyPress = true; - return; + // the return key was pressed with the Control key down, so search backwards.. + Backward(); } - } - // use the return key to search either to forwards or to backwards direction.. - if (e.KeyCode == Keys.Return) + // flag the event as handled.. + e.Handled = true; + } + // if the find (and replace) in files tab is active.. + else if (tcMain.SelectedTab.Equals(tabReplace)) { - // if the find tab is active.. - if (tcMain.SelectedTab.Equals(tabFind)) + if (btFindAllInFiles.Enabled && e.NoModifierKeysDown()) { - if (btFindNext.Enabled && e.NoModifierKeysDown()) - { - // the return key was pressed with no modifiers, so search forwards.. - Forward(); - } - else if (btFindPrevious.Enabled && e.ModifierKeysDown(false, true, false)) - { - // the return key was pressed with the Control key down, so search backwards.. - Backward(); - } - - // flag the event as handled.. - e.Handled = true; + // the return key was pressed with no modifiers, so find all in files.. + FindAllInFiles(); } - // if the search and replace tab is active.. - else if (tcMain.SelectedTab.Equals(tabReplace)) + else if (btReplaceAllInFiles.Enabled && e.OnlyControl()) { - if (btFindNext2.Enabled && e.NoModifierKeysDown()) - { - // the return key was pressed with no modifiers, so search forwards.. - Forward(); - } - else if (btFindPrevious2.Enabled && e.ModifierKeysDown(false, true, false)) - { - // the return key was pressed with the Control key down, so search backwards.. - Backward(); - } - - // flag the event as handled.. - e.Handled = true; + // the return key was pressed with the Control key down, replace all in files.. + ReplaceAllInFiles(); } - // if the find (and replace) in files tab is active.. - else if (tcMain.SelectedTab.Equals(tabReplace)) - { - if (btFindAllInFiles.Enabled && e.NoModifierKeysDown()) - { - // the return key was pressed with no modifiers, so find all in files.. - FindAllInFiles(); - } - else if (btReplaceAllInFiles.Enabled && e.OnlyControl()) - { - // the return key was pressed with the Control key down, replace all in files.. - ReplaceAllInFiles(); - } - // flag the event as handled.. - e.Handled = true; + // flag the event as handled.. + e.Handled = true; + } + // if the mark tab is active.. + else if (tcMain.SelectedTab.Equals(tabMarkMatches)) + { + if (btMarkAll.Enabled && e.NoModifierKeysDown()) + { + // the return key was pressed with no modifiers, so mark the search result of the active document.. + MarkAll(); } - // if the mark tab is active.. - else if (tcMain.SelectedTab.Equals(tabMarkMatches)) + else if (btnClearAllMarks.Enabled && e.OnlyControl()) { - if (btMarkAll.Enabled && e.NoModifierKeysDown()) - { - // the return key was pressed with no modifiers, so mark the search result of the active document.. - MarkAll(); - } - else if (btnClearAllMarks.Enabled && e.OnlyControl()) - { - // the return key was pressed with the Control key down, replace all in files.. - ClearAllMarks(); - } - - // flag the event as handled.. - e.Handled = true; + // the return key was pressed with the Control key down, replace all in files.. + ClearAllMarks(); } + + // flag the event as handled.. + e.Handled = true; } } - #endregion } -} + #endregion +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchResultTree.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchResultTree.cs index 47d45ed7..52b7c3cb 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchResultTree.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/FormSearchResultTree.cs @@ -34,527 +34,526 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.PosLib; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace +namespace ScriptNotepad.UtilityClasses.SearchAndReplace; + +/// +/// A form the to display search results if multiple findings are to be reported. +/// Implements the +/// +/// +public partial class FormSearchResultTree : DBLangEngineWinforms { /// - /// A form the to display search results if multiple findings are to be reported. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormSearchResultTree : DBLangEngineWinforms + public FormSearchResultTree() { - /// - /// Initializes a new instance of the class. - /// - public FormSearchResultTree() - { - // Add this form to be positioned.. - PositionForms.Add(this); + // Add this form to be positioned.. + PositionForms.Add(this); - // add positioning.. - PositionCore.Bind(ApplicationType.WinForms); + // add positioning.. + PositionCore.Bind(ApplicationType.WinForms); - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - ttMain.SetToolTip(pnPreviousResult, - DBLangEngine.GetMessage("msgPreviousResult", - "Previous result|A tool-tip message describing that the button would go to the previous search result")); + ttMain.SetToolTip(pnPreviousResult, + DBLangEngine.GetMessage("msgPreviousResult", + "Previous result|A tool-tip message describing that the button would go to the previous search result")); - ttMain.SetToolTip(pnNextResult, - DBLangEngine.GetMessage("msgNextResult", - "Advance result|A tool-tip message describing that the button would go to the next search result")); + ttMain.SetToolTip(pnNextResult, + DBLangEngine.GetMessage("msgNextResult", + "Advance result|A tool-tip message describing that the button would go to the next search result")); - ttMain.SetToolTip(pnClose, - DBLangEngine.GetMessage("msgButtonClose", - "Close|A message describing a tool-tip for a button which would close something")); + ttMain.SetToolTip(pnClose, + DBLangEngine.GetMessage("msgButtonClose", + "Close|A message describing a tool-tip for a button which would close something")); - // don't allow multiple instances of this.. - if (PreviousInstance != null) + // don't allow multiple instances of this.. + if (PreviousInstance != null) + { + if (PreviousInstance.IsDocked) { - if (PreviousInstance.IsDocked) - { - RequestDockReleaseMainForm?.Invoke(PreviousInstance, new EventArgs()); - } - else - { - PreviousInstance?.Close(); - } + RequestDockReleaseMainForm?.Invoke(PreviousInstance, new EventArgs()); + } + else + { + PreviousInstance?.Close(); } - - // save this as the new previous instance.. - PreviousInstance = this; } - /// - /// Gets or sets the previous instance of this class. - /// - public static FormSearchResultTree PreviousInstance { get; set; } + // save this as the new previous instance.. + PreviousInstance = this; + } - // the search results for the tree view.. - private IEnumerable<(string fileName, int lineNumber, int startLocation, int length, string lineContent, bool isFileOpen)> - searchResults; + /// + /// Gets or sets the previous instance of this class. + /// + public static FormSearchResultTree PreviousInstance { get; set; } - /// - /// Gets or sets the search results for the tree view. - /// - public IEnumerable<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool isFileOpen)> SearchResults - { - // just return the value.. - get => searchResults; + // the search results for the tree view.. + private IEnumerable<(string fileName, int lineNumber, int startLocation, int length, string lineContent, bool isFileOpen)> + searchResults; - set + /// + /// Gets or sets the search results for the tree view. + /// + public IEnumerable<(string fileName, int lineNumber, int startLocation, int length, string lineContents, bool isFileOpen)> SearchResults + { + // just return the value.. + get => searchResults; + + set + { + // value changed.. + if (!Equals(value, searchResults)) { - // value changed.. - if (!Equals(value, searchResults)) - { - // save the value.. - searchResults = value; + // save the value.. + searchResults = value; - // build the tree view.. - CreateTree(); - } + // build the tree view.. + CreateTree(); } } + } - /// - /// Gets or sets a value indicating whether not to perform owner drawing for the control. - /// - /// true if the owner drawing is disabled; otherwise, false. - private bool NoDraw { get; set; } + /// + /// Gets or sets a value indicating whether not to perform owner drawing for the control. + /// + /// true if the owner drawing is disabled; otherwise, false. + private bool NoDraw { get; set; } - /// - /// Creates the tree view based on the property value. - /// - private void CreateTree() - { - SuspendLayout(); // suspend the layout of the form.. - tvMain.BeginUpdate(); // the tree can be large, so suspend the draw.. - NoDraw = true; - tvMain.Nodes.Clear(); // clear the previous nodes.. - string fileName = string.Empty; - - // initialize a variable for the 0-level node (a file).. - TreeNode upperNode = null; + /// + /// Creates the tree view based on the property value. + /// + private void CreateTree() + { + SuspendLayout(); // suspend the layout of the form.. + tvMain.BeginUpdate(); // the tree can be large, so suspend the draw.. + NoDraw = true; + tvMain.Nodes.Clear(); // clear the previous nodes.. + string fileName = string.Empty; + + // initialize a variable for the 0-level node (a file).. + TreeNode upperNode = null; - // loop through the search results.. - foreach (var searchResult in SearchResults) + // loop through the search results.. + foreach (var searchResult in SearchResults) + { + // if the file name in the search result has changed, create a new primary node for the file.. + if (fileName != searchResult.fileName) { - // if the file name in the search result has changed, create a new primary node for the file.. - if (fileName != searchResult.fileName) - { - int count = searchResults.Count(f => f.fileName == searchResult.fileName); - // create the primary node.. - upperNode = tvMain.Nodes.Add(searchResult.fileName, - DBLangEngine.GetMessage("msgFileNameMatchCount", - "File: '{0}', matches: {1}|A message describing a file name and a count number of search matches", - Path.GetFileName(searchResult.fileName), count), 0); + int count = searchResults.Count(f => f.fileName == searchResult.fileName); + // create the primary node.. + upperNode = tvMain.Nodes.Add(searchResult.fileName, + DBLangEngine.GetMessage("msgFileNameMatchCount", + "File: '{0}', matches: {1}|A message describing a file name and a count number of search matches", + Path.GetFileName(searchResult.fileName), count), 0); - upperNode.Tag = searchResult; // save the result to the tag.. + upperNode.Tag = searchResult; // save the result to the tag.. - // save the file name so the comparison of the file name change can be done.. - fileName = searchResult.fileName; - } + // save the file name so the comparison of the file name change can be done.. + fileName = searchResult.fileName; + } - // add the search result to the primary node.. - var subNode = upperNode?.Nodes.Add(searchResult.fileName, DBLangEngine.GetMessage("msgSearchResultLine", - "Line: {0}, contents '{1}'.|A message describing a search result with a line number and the line's contents.", - searchResult.lineNumber, searchResult.lineContents), 1, 1); + // add the search result to the primary node.. + var subNode = upperNode?.Nodes.Add(searchResult.fileName, DBLangEngine.GetMessage("msgSearchResultLine", + "Line: {0}, contents '{1}'.|A message describing a search result with a line number and the line's contents.", + searchResult.lineNumber, searchResult.lineContents), 1, 1); - // save the file name so the comparison of the file name change can be done.. - if (subNode != null) - { - subNode.Tag = searchResult; - } + // save the file name so the comparison of the file name change can be done.. + if (subNode != null) + { + subNode.Tag = searchResult; } - NoDraw = false; - tvMain.EndUpdate(); // END: the tree can be large, so suspend the draw.. - ResumeLayout(); // END: suspend the layout of the form.. } + NoDraw = false; + tvMain.EndUpdate(); // END: the tree can be large, so suspend the draw.. + ResumeLayout(); // END: suspend the layout of the form.. + } + + /// + /// Selects the next occurrence within the tree view. + /// + public void NextOccurrence() + { + SelectNode(tvMain, true); + } + + /// + /// Selects the previous occurrence within the tree view. + /// + public void PreviousOccurrence() + { + SelectNode(tvMain, false); + } - /// - /// Selects the next occurrence within the tree view. - /// - public void NextOccurrence() + /// + /// Closes the tree view and its form. + /// + public void CloseTree() + { + if (IsDocked) { - SelectNode(tvMain, true); + RequestDockReleaseMainForm?.Invoke(this, new EventArgs()); } - - /// - /// Selects the previous occurrence within the tree view. - /// - public void PreviousOccurrence() + else { - SelectNode(tvMain, false); + Close(); } + } + + /// + /// A delegate for the SearchResultSelected event. + /// + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnSearchResultClick(object sender, SearchResultTreeViewClickEventArgs e); - /// - /// Closes the tree view and its form. - /// - public void CloseTree() + /// + /// Occurs when a search result was clicked. + /// + public static event OnSearchResultClick SearchResultSelected; + + /// + /// Gets or sets the an event handler if the form requests to dock in the main form. + /// + public static event EventHandler RequestDockMainForm; + + /// + /// Gets or sets the an event handler if the form requests the docking to the main form to be released. + /// + public static event EventHandler RequestDockReleaseMainForm; + + // the form is requesting to dock in to the main form.. + private void FormSearchResultTree_Shown(object sender, EventArgs e) + { + // if the setting value is true then.. + if (FormSettings.Settings.DockSearchTreeForm) { - if (IsDocked) - { - RequestDockReleaseMainForm?.Invoke(this, new EventArgs()); - } - else - { - Close(); - } + // ..raise the event if subscribed.. + RequestDockMainForm?.Invoke(this, new EventArgs()); } - - /// - /// A delegate for the SearchResultSelected event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnSearchResultClick(object sender, SearchResultTreeViewClickEventArgs e); - - /// - /// Occurs when a search result was clicked. - /// - public static event OnSearchResultClick SearchResultSelected; - - /// - /// Gets or sets the an event handler if the form requests to dock in the main form. - /// - public static event EventHandler RequestDockMainForm; - - /// - /// Gets or sets the an event handler if the form requests the docking to the main form to be released. - /// - public static event EventHandler RequestDockReleaseMainForm; - - // the form is requesting to dock in to the main form.. - private void FormSearchResultTree_Shown(object sender, EventArgs e) + else if (Height < FormMain.Instance.Height * 20 / 100) { - // if the setting value is true then.. - if (FormSettings.Settings.DockSearchTreeForm) - { - // ..raise the event if subscribed.. - RequestDockMainForm?.Invoke(this, new EventArgs()); - } - else if (Height < FormMain.Instance.Height * 20 / 100) - { - Height = FormMain.Instance.Height * 20 / 100; - } + Height = FormMain.Instance.Height * 20 / 100; } + } - // a flag indicating whether this instance is docked to the main form.. - private bool isDocked; + // a flag indicating whether this instance is docked to the main form.. + private bool isDocked; - /// - /// Gets or sets a value indicating whether this instance is docked to the main form. - /// - public bool IsDocked - { - get => isDocked; + /// + /// Gets or sets a value indicating whether this instance is docked to the main form. + /// + public bool IsDocked + { + get => isDocked; - set - { - lbSearchResultDesc.Visible = value; - pnClose.Visible = value; - isDocked = value; - } + set + { + lbSearchResultDesc.Visible = value; + pnClose.Visible = value; + isDocked = value; } + } + + /// + /// Gets or sets the absolute index of the selected node within the three branches. + /// + private int SelectedNodeIndex { get; set; } = 1; - /// - /// Gets or sets the absolute index of the selected node within the three branches. - /// - private int SelectedNodeIndex { get; set; } = 1; - - /// - /// Selects the previous or the next node of a tree view based on the given direction. - /// - /// An instance to class to be used with the method. - /// if set to true the selection goes forward. - private void SelectNode(TreeView treeView, bool forward) + /// + /// Selects the previous or the next node of a tree view based on the given direction. + /// + /// An instance to class to be used with the method. + /// if set to true the selection goes forward. + private void SelectNode(TreeView treeView, bool forward) + { + if (forward) // forward.. { - if (forward) // forward.. - { - SelectNextNode(treeView); - } - else - { - // backward.. - SelectPreviousNode(treeView); - } + SelectNextNode(treeView); } + else + { + // backward.. + SelectPreviousNode(treeView); + } + } - /// - /// Selects the next node within a tree view. - /// - /// The tree view which next node to select. - private void SelectNextNode(TreeView treeView) + /// + /// Selects the next node within a tree view. + /// + /// The tree view which next node to select. + private void SelectNextNode(TreeView treeView) + { + int count = treeView.GetNodeCount(true); + + if (SelectedNodeIndex == count - 1) { - int count = treeView.GetNodeCount(true); + SelectedNodeIndex = 1; + } - if (SelectedNodeIndex == count - 1) + int counter = 0; + for (int i = 0; i < treeView.Nodes.Count; i++) + { + for (int j = 0; j < treeView.Nodes[i].Nodes.Count; j++) { - SelectedNodeIndex = 1; - } + counter++; - int counter = 0; - for (int i = 0; i < treeView.Nodes.Count; i++) - { - for (int j = 0; j < treeView.Nodes[i].Nodes.Count; j++) + if (counter == SelectedNodeIndex) { - counter++; - - if (counter == SelectedNodeIndex) - { - treeView.SelectedNode = treeView.Nodes[i].Nodes[j]; - SelectedNodeIndex++; - return; - } + treeView.SelectedNode = treeView.Nodes[i].Nodes[j]; + SelectedNodeIndex++; + return; } } - - SelectedNodeIndex = 1; - SelectNextNode(treeView); } - /// - /// Selects the previous node of a give . - /// - /// The tree view which previous node to select. - private void SelectPreviousNode(TreeView treeView) - { - int counter = treeView.GetNodeCount(true); + SelectedNodeIndex = 1; + SelectNextNode(treeView); + } + + /// + /// Selects the previous node of a give . + /// + /// The tree view which previous node to select. + private void SelectPreviousNode(TreeView treeView) + { + int counter = treeView.GetNodeCount(true); - for (int i = treeView.Nodes.Count - 1; i >= 0; i--) + for (int i = treeView.Nodes.Count - 1; i >= 0; i--) + { + for (int j = treeView.Nodes[i].Nodes.Count - 1; j >= 0; j--) { - for (int j = treeView.Nodes[i].Nodes.Count - 1; j >= 0; j--) + if (counter == SelectedNodeIndex) { - if (counter == SelectedNodeIndex) - { - treeView.SelectedNode = treeView.Nodes[i].Nodes[j]; - SelectedNodeIndex--; - return; - } - - counter--; + treeView.SelectedNode = treeView.Nodes[i].Nodes[j]; + SelectedNodeIndex--; + return; } - } - SelectedNodeIndex = treeView.GetNodeCount(true); - SelectPreviousNode(treeView); + counter--; + } } - // a method to handle the "tiny" button clicks.. - private void TinyButton_Click(object sender, EventArgs e) + SelectedNodeIndex = treeView.GetNodeCount(true); + SelectPreviousNode(treeView); + } + + // a method to handle the "tiny" button clicks.. + private void TinyButton_Click(object sender, EventArgs e) + { + // the search result window is requested to be closed.. + if (sender.Equals(pnClose)) { - // the search result window is requested to be closed.. - if (sender.Equals(pnClose)) - { - CloseTree(); - } - // a user wishes to navigate to a next or to a previous search result.. - else if (sender.Equals(pnNextResult) || sender.Equals(pnPreviousResult)) - { - SelectNode(tvMain, sender.Equals(pnNextResult)); - } + CloseTree(); + } + // a user wishes to navigate to a next or to a previous search result.. + else if (sender.Equals(pnNextResult) || sender.Equals(pnPreviousResult)) + { + SelectNode(tvMain, sender.Equals(pnNextResult)); } + } - /// - /// Finds the "true" index of a give within a given . - /// - /// The tree view to which the belongs to. - /// The node which "true" index to get. - /// An index for the node if the operation was successful; otherwise false. - private int FindNodeTrueIndex(TreeView treeView, TreeNode node) + /// + /// Finds the "true" index of a give within a given . + /// + /// The tree view to which the belongs to. + /// The node which "true" index to get. + /// An index for the node if the operation was successful; otherwise false. + private int FindNodeTrueIndex(TreeView treeView, TreeNode node) + { + int counter = 0; + for (int i = 0; i < treeView.Nodes.Count; i++) { - int counter = 0; - for (int i = 0; i < treeView.Nodes.Count; i++) + for (int j = 0; j < treeView.Nodes[i].Nodes.Count; j++) { - for (int j = 0; j < treeView.Nodes[i].Nodes.Count; j++) - { - counter++; + counter++; - if (node.Equals(treeView.Nodes[i].Nodes[j])) - { - return counter; - } + if (node.Equals(treeView.Nodes[i].Nodes[j])) + { + return counter; } - - counter++; } - return -1; + counter++; } - /// - /// Handles the AfterSelect event of the TvMain control. - /// - /// The source of the event. - /// The instance containing the event data. - private void TvMain_AfterSelect(object sender, TreeViewEventArgs e) + return -1; + } + + /// + /// Handles the AfterSelect event of the TvMain control. + /// + /// The source of the event. + /// The instance containing the event data. + private void TvMain_AfterSelect(object sender, TreeViewEventArgs e) + { + // the parent node does not need to be handled.. + if (e.Node.Level == 0) { - // the parent node does not need to be handled.. - if (e.Node.Level == 0) - { - return; - } + return; + } - // if the node was selected by the user, the node index needs updating.. - SelectedNodeIndex = FindNodeTrueIndex((TreeView) sender, e.Node); + // if the node was selected by the user, the node index needs updating.. + SelectedNodeIndex = FindNodeTrueIndex((TreeView) sender, e.Node); - // get the tag of the clicked tree view node.. - var clickResult = - ((string fileName, int lineNumber, int startLocation, int length, string lineContents, bool isFileOpen)) - e.Node.Tag; + // get the tag of the clicked tree view node.. + var clickResult = + ((string fileName, int lineNumber, int startLocation, int length, string lineContents, bool isFileOpen)) + e.Node.Tag; - // raise the click event if subscribed.. - SearchResultSelected?.Invoke(this, new SearchResultTreeViewClickEventArgs { SearchResult = clickResult }); + // raise the click event if subscribed.. + SearchResultSelected?.Invoke(this, new SearchResultTreeViewClickEventArgs { SearchResult = clickResult, }); - // set the value back to the node's tag.. - e.Node.Tag = clickResult; - } + // set the value back to the node's tag.. + e.Node.Tag = clickResult; + } - /// - /// Sets the tree view data for a file name to . - /// - /// Name of the file which flag to set. - /// if set to true the file in the tree view is set as opened, false otherwise. - public void SetFileOpened(string fileName, bool value) + /// + /// Sets the tree view data for a file name to . + /// + /// Name of the file which flag to set. + /// if set to true the file in the tree view is set as opened, false otherwise. + public void SetFileOpened(string fileName, bool value) + { + SuspendLayout(); // suspend the layout of the form.. + tvMain.BeginUpdate(); // the tree can be large, so suspend the draw.. + NoDraw = true; + + for (int i = 0; i < tvMain.Nodes.Count; i++) { - SuspendLayout(); // suspend the layout of the form.. - tvMain.BeginUpdate(); // the tree can be large, so suspend the draw.. - NoDraw = true; + var node = + ((string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)) (tvMain.Nodes[i].Tag); - for (int i = 0; i < tvMain.Nodes.Count; i++) + if (node.fileName == fileName) { - var node = - ((string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)) (tvMain.Nodes[i].Tag); - - if (node.fileName == fileName) - { - node.isFileOpen = value; + node.isFileOpen = value; - tvMain.Nodes[i].Tag = node; + tvMain.Nodes[i].Tag = node; - for (int j = 0; j < tvMain.Nodes[i].Nodes.Count; j++) - { - var subNode = - ((string fileName, int lineNumber, int startLocation, int length, string lineContents, bool - isFileOpen)) (tvMain.Nodes[i].Nodes[j].Tag); - - subNode.isFileOpen = value; + for (int j = 0; j < tvMain.Nodes[i].Nodes.Count; j++) + { + var subNode = + ((string fileName, int lineNumber, int startLocation, int length, string lineContents, bool + isFileOpen)) (tvMain.Nodes[i].Nodes[j].Tag); - tvMain.Nodes[i].Nodes[j].Tag = subNode; - } + subNode.isFileOpen = value; + tvMain.Nodes[i].Nodes[j].Tag = subNode; } - } - NoDraw = false; - tvMain.EndUpdate(); // END: the tree can be large, so suspend the draw.. - ResumeLayout(); // END: suspend the layout of the form.. - } - - // (C):: https://social.msdn.microsoft.com/Forums/windows/en-US/7e7b25bd-7adf-43c1-8546-08a308084cf5/any-way-to-change-the-highlight-color-for-an-inactive-not-focused-treeview-control?forum=winforms - /// - /// A - /// delegate method. Called - /// when the tree view node gets drawn. This handler keeps - /// highlighting the selected node even when the control does not - /// have focus. - /// - /// - /// The instance that called the event. - /// - /// - /// The tree node event. - /// - /// - /// Set the property to - /// so this event handler - /// gets called. - /// - private void DrawTreeNodeHighlightSelectedEvenWithoutFocus(object sender, DrawTreeNodeEventArgs e) - { - if (NoDraw) - { - return; } + } - Color foreColor; - if (e.Node == ((TreeView)sender).SelectedNode) - { - // is selected, draw a highlighted text rectangle under the text.. - foreColor = SystemColors.HighlightText; - e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); - ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds, foreColor, SystemColors.Highlight); - } - else - { - foreColor = (e.Node.ForeColor == Color.Empty) ? ((TreeView)sender).ForeColor : e.Node.ForeColor; - e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds); - } + NoDraw = false; + tvMain.EndUpdate(); // END: the tree can be large, so suspend the draw.. + ResumeLayout(); // END: suspend the layout of the form.. + } - TextRenderer.DrawText( - e.Graphics, - e.Node.Text, - e.Node.NodeFont ?? e.Node.TreeView.Font, - e.Bounds, - foreColor, - TextFormatFlags.GlyphOverhangPadding); + // (C):: https://social.msdn.microsoft.com/Forums/windows/en-US/7e7b25bd-7adf-43c1-8546-08a308084cf5/any-way-to-change-the-highlight-color-for-an-inactive-not-focused-treeview-control?forum=winforms + /// + /// A + /// delegate method. Called + /// when the tree view node gets drawn. This handler keeps + /// highlighting the selected node even when the control does not + /// have focus. + /// + /// + /// The instance that called the event. + /// + /// + /// The tree node event. + /// + /// + /// Set the property to + /// so this event handler + /// gets called. + /// + private void DrawTreeNodeHighlightSelectedEvenWithoutFocus(object sender, DrawTreeNodeEventArgs e) + { + if (NoDraw) + { + return; } - /// - /// Handles the DrawNode event of the TvMain control. - /// - /// The source of the event. - /// The instance containing the event data. - private void TvMain_DrawNode(object sender, DrawTreeNodeEventArgs e) + Color foreColor; + if (e.Node == ((TreeView)sender).SelectedNode) { - DrawTreeNodeHighlightSelectedEvenWithoutFocus(sender, e); + // is selected, draw a highlighted text rectangle under the text.. + foreColor = SystemColors.HighlightText; + e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); + ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds, foreColor, SystemColors.Highlight); } + else + { + foreColor = (e.Node.ForeColor == Color.Empty) ? ((TreeView)sender).ForeColor : e.Node.ForeColor; + e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds); + } + + TextRenderer.DrawText( + e.Graphics, + e.Node.Text, + e.Node.NodeFont ?? e.Node.TreeView.Font, + e.Bounds, + foreColor, + TextFormatFlags.GlyphOverhangPadding); + } + + /// + /// Handles the DrawNode event of the TvMain control. + /// + /// The source of the event. + /// The instance containing the event data. + private void TvMain_DrawNode(object sender, DrawTreeNodeEventArgs e) + { + DrawTreeNodeHighlightSelectedEvenWithoutFocus(sender, e); + } - /// - /// Handles the KeyDown event of the FormSearchResultTree control for navigating within the tree view. - /// - /// The source of the event. - /// The instance containing the event data. - private void FormSearchResultTree_KeyDown(object sender, KeyEventArgs e) + /// + /// Handles the KeyDown event of the FormSearchResultTree control for navigating within the tree view. + /// + /// The source of the event. + /// The instance containing the event data. + private void FormSearchResultTree_KeyDown(object sender, KeyEventArgs e) + { + // a user wishes to navigate within the FormSearchResultTree.. + if (e.OnlyAlt() && e.KeyCodeIn(Keys.Left, Keys.Right, Keys.X)) { - // a user wishes to navigate within the FormSearchResultTree.. - if (e.OnlyAlt() && e.KeyCodeIn(Keys.Left, Keys.Right, Keys.X)) + // validate that there is an instance of the FormSearchResultTree which is visible.. + if (Visible) { - // validate that there is an instance of the FormSearchResultTree which is visible.. - if (Visible) + // Alt+Left navigates to the previous tree node within the form.. + if (e.KeyCode == Keys.Left) { - // Alt+Left navigates to the previous tree node within the form.. - if (e.KeyCode == Keys.Left) - { - PreviousOccurrence(); - } - // Alt+Right navigates to the next tree node within the form.. - else if (e.KeyCode == Keys.Right) - { - NextOccurrence(); - } - // Alt+X closes the FormSearchResultTree instance.. - else - { - CloseTree(); - } - - // this is handled.. - e.Handled = true; + PreviousOccurrence(); } + // Alt+Right navigates to the next tree node within the form.. + else if (e.KeyCode == Keys.Right) + { + NextOccurrence(); + } + // Alt+X closes the FormSearchResultTree instance.. + else + { + CloseTree(); + } + + // this is handled.. + e.Handled = true; } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/HighLight.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/HighLight.cs index 15b01b42..a70508a4 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/HighLight.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/HighLight.cs @@ -27,68 +27,67 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Drawing; using ScintillaNET; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace.Misc +namespace ScriptNotepad.UtilityClasses.SearchAndReplace.Misc; + +/// +/// A helper class to highlight words with a given color. +/// +public class Highlight { /// - /// A helper class to highlight words with a given color. + /// Highlights a given word (string) with a given color and given alpha values. /// - public class Highlight + /// The scintilla of which words to highlight. + /// The indicator number for the .Indicators 0-7 could be in use by a lexer so use a higher value. + /// The text to highlight. + /// The color to use for the highlight. + /// A flag indicating whether the previous markings marked with the should be cleared. + /// The transparency value of the indicator. + /// The transparency value of the indicator outline. + /// (C): https://github.com/jacobslusser/ScintillaNET/wiki/Find-and-Highlight-Words + public static void HighlightWords(Scintilla scintilla, int num, string text, Color color, bool clearPreviousMarks = true, byte alpha = 255, byte outlineAlpha = 255) { - /// - /// Highlights a given word (string) with a given color and given alpha values. - /// - /// The scintilla of which words to highlight. - /// The indicator number for the .Indicators 0-7 could be in use by a lexer so use a higher value. - /// The text to highlight. - /// The color to use for the highlight. - /// A flag indicating whether the previous markings marked with the should be cleared. - /// The transparency value of the indicator. - /// The transparency value of the indicator outline. - /// (C): https://github.com/jacobslusser/ScintillaNET/wiki/Find-and-Highlight-Words - public static void HighlightWords(Scintilla scintilla, int num, string text, Color color, bool clearPreviousMarks = true, byte alpha = 255, byte outlineAlpha = 255) + if (string.IsNullOrEmpty(text)) + return; + + // clear the previous marks if requested.. + if (clearPreviousMarks) { - if (string.IsNullOrEmpty(text)) - return; + // Remove all uses of our indicator + scintilla.IndicatorCurrent = num; + scintilla.IndicatorClearRange(0, scintilla.TextLength); + } - // clear the previous marks if requested.. - if (clearPreviousMarks) - { - // Remove all uses of our indicator - scintilla.IndicatorCurrent = num; - scintilla.IndicatorClearRange(0, scintilla.TextLength); - } + // Update indicator appearance + scintilla.Indicators[num].Style = IndicatorStyle.StraightBox; + scintilla.Indicators[num].Under = true; + scintilla.Indicators[num].ForeColor = color; + scintilla.Indicators[num].OutlineAlpha = alpha; + scintilla.Indicators[num].Alpha = outlineAlpha; - // Update indicator appearance - scintilla.Indicators[num].Style = IndicatorStyle.StraightBox; - scintilla.Indicators[num].Under = true; - scintilla.Indicators[num].ForeColor = color; - scintilla.Indicators[num].OutlineAlpha = alpha; - scintilla.Indicators[num].Alpha = outlineAlpha; + // Search the document + scintilla.TargetStart = 0; + scintilla.TargetEnd = scintilla.TextLength; + scintilla.SearchFlags = SearchFlags.None; + while (scintilla.SearchInTarget(text) != -1) + { + // Mark the search results with the current indicator + scintilla.IndicatorFillRange(scintilla.TargetStart, scintilla.TargetEnd - scintilla.TargetStart); - // Search the document - scintilla.TargetStart = 0; + // Search the remainder of the document + scintilla.TargetStart = scintilla.TargetEnd; scintilla.TargetEnd = scintilla.TextLength; - scintilla.SearchFlags = SearchFlags.None; - while (scintilla.SearchInTarget(text) != -1) - { - // Mark the search results with the current indicator - scintilla.IndicatorFillRange(scintilla.TargetStart, scintilla.TargetEnd - scintilla.TargetStart); - - // Search the remainder of the document - scintilla.TargetStart = scintilla.TargetEnd; - scintilla.TargetEnd = scintilla.TextLength; - } } + } - /// - /// Clears the given style form a . - /// - /// The scintilla to clear the style from. - /// The number of the style to clear. - public static void ClearStyle(Scintilla scintilla, int num) - { - scintilla.IndicatorCurrent = num; - scintilla.IndicatorClearRange(0, scintilla.TextLength); - } + /// + /// Clears the given style form a . + /// + /// The scintilla to clear the style from. + /// The number of the style to clear. + public static void ClearStyle(Scintilla scintilla, int num) + { + scintilla.IndicatorCurrent = num; + scintilla.IndicatorClearRange(0, scintilla.TextLength); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/SearchResultTreeViewClickEventArgs.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/SearchResultTreeViewClickEventArgs.cs index f1f031a3..6f324b19 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/SearchResultTreeViewClickEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/Misc/SearchResultTreeViewClickEventArgs.cs @@ -24,23 +24,22 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.SearchAndReplace.Misc +namespace ScriptNotepad.UtilityClasses.SearchAndReplace.Misc; + +/// +/// Event arguments for the search result form to request the application to do something with the search result. +/// Implements the +/// +/// +public class SearchResultTreeViewClickEventArgs : EventArgs { /// - /// Event arguments for the search result form to request the application to do something with the search result. - /// Implements the + /// Gets or sets the search result passed by the form. /// - /// - public class SearchResultTreeViewClickEventArgs : EventArgs + /// The search results. + public (string fileName, int lineNumber, int startLocation, int length, string lineContents, bool isFileOpen) SearchResult { - /// - /// Gets or sets the search result passed by the form. - /// - /// The search results. - public (string fileName, int lineNumber, int startLocation, int length, string lineContents, bool isFileOpen) SearchResult - { - get; - set; - } + get; + set; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/ProgressRequestActionEventArgs.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/ProgressRequestActionEventArgs.cs index b6613233..332c0347 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/ProgressRequestActionEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/ProgressRequestActionEventArgs.cs @@ -26,39 +26,38 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.SearchText; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace +namespace ScriptNotepad.UtilityClasses.SearchAndReplace; + +/// +/// A class for the class to request an action for the next file. +/// Implements the +/// +/// +public class ProgressRequestActionEventArgs: EventArgs { /// - /// A class for the class to request an action for the next file. - /// Implements the + /// Gets or sets the action to process next. /// - /// - public class ProgressRequestActionEventArgs: EventArgs - { - /// - /// Gets or sets the action to process next. - /// - public Action Action { get; set; } + public Action Action { get; set; } - /// - /// Gets or sets a value indicating whether to skip processing of the file. - /// - public bool SkipFile { get; set; } = false; + /// + /// Gets or sets a value indicating whether to skip processing of the file. + /// + public bool SkipFile { get; set; } = false; - /// - /// Gets or sets the name of the file for to be processed next. - /// - public string FileName { get; set; } + /// + /// Gets or sets the name of the file for to be processed next. + /// + public string FileName { get; set; } - /// - /// Gets or sets a value indicating whether this is canceled; - /// I.e. no more processing is being done within the form instance. - /// - public bool Canceled { get; set; } + /// + /// Gets or sets a value indicating whether this is canceled; + /// I.e. no more processing is being done within the form instance. + /// + public bool Canceled { get; set; } - /// - /// Gets or sets the current instance of the class. - /// - public TextSearcherAndReplacer SearchAndReplacer { get; set; } - } -} + /// + /// Gets or sets the current instance of the class. + /// + public TextSearcherAndReplacer SearchAndReplacer { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SearchAndReplace/ScintillaDocumentEventArgs.cs b/ScriptNotepad/UtilityClasses/SearchAndReplace/ScintillaDocumentEventArgs.cs index f96b2d8d..a026082a 100644 --- a/ScriptNotepad/UtilityClasses/SearchAndReplace/ScintillaDocumentEventArgs.cs +++ b/ScriptNotepad/UtilityClasses/SearchAndReplace/ScintillaDocumentEventArgs.cs @@ -27,22 +27,21 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using System.Collections.Generic; -namespace ScriptNotepad.UtilityClasses.SearchAndReplace +namespace ScriptNotepad.UtilityClasses.SearchAndReplace; + +/// +/// Event arguments for the search and replace dialog to be able to interact with the main form. +/// +/// +public class ScintillaDocumentEventArgs: EventArgs { /// - /// Event arguments for the search and replace dialog to be able to interact with the main form. + /// Gets or sets a value indicating whether all the open documents are requested. + /// + public bool RequestAllDocuments { get; set; } = false; + + /// + /// Gets or sets the documents requested by an event. /// - /// - public class ScintillaDocumentEventArgs: EventArgs - { - /// - /// Gets or sets a value indicating whether all the open documents are requested. - /// - public bool RequestAllDocuments { get; set; } = false; - - /// - /// Gets or sets the documents requested by an event. - /// - public List<(Scintilla scintilla, string fileName)> Documents { get; set; } = new List<(Scintilla scintilla, string fileName)>(); - } -} + public List<(Scintilla scintilla, string fileName)> Documents { get; set; } = new List<(Scintilla scintilla, string fileName)>(); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/Session/FormDialogSessionManage.cs b/ScriptNotepad/UtilityClasses/Session/FormDialogSessionManage.cs index e05b6a52..c875d535 100644 --- a/ScriptNotepad/UtilityClasses/Session/FormDialogSessionManage.cs +++ b/ScriptNotepad/UtilityClasses/Session/FormDialogSessionManage.cs @@ -33,106 +33,169 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; using VPKSoft.MessageBoxExtended; -namespace ScriptNotepad.UtilityClasses.Session +namespace ScriptNotepad.UtilityClasses.Session; + +/// +/// A dialog to manage sessions within the software. +/// +/// +public partial class FormDialogSessionManage : DBLangEngineWinforms { /// - /// A dialog to manage sessions within the software. + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogSessionManage : DBLangEngineWinforms + public FormDialogSessionManage() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogSessionManage() + InitializeComponent(); + + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + + if (Utils.ShouldLocalize() != null) { - InitializeComponent(); + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + ttMain.SetToolTip(pbDeleteSelectedSession, + DBLangEngine.GetMessage("msgDeleteSession", "Delete selected session|A message indicating an action to delete a session from the database")); - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + ttMain.SetToolTip(pbRenameSelectedSession, + DBLangEngine.GetMessage("msgRenameSession", "Rename selected session|A message indicating an action to rename a session in the database")); - ttMain.SetToolTip(pbDeleteSelectedSession, - DBLangEngine.GetMessage("msgDeleteSession", "Delete selected session|A message indicating an action to delete a session from the database")); + ttMain.SetToolTip(pbAddNewSessionWithName, + DBLangEngine.GetMessage("msgAddSessionWithName", "Add a new named session|A message indicating an action to add a new session to the database")); + } - ttMain.SetToolTip(pbRenameSelectedSession, - DBLangEngine.GetMessage("msgRenameSession", "Rename selected session|A message indicating an action to rename a session in the database")); + /// + /// Displays the session management dialog for session management. + /// + public static void Execute() + { + // create a new instance of "this" dialog.. + FormDialogSessionManage formDialogSessionManage = new FormDialogSessionManage(); - ttMain.SetToolTip(pbAddNewSessionWithName, - DBLangEngine.GetMessage("msgAddSessionWithName", "Add a new named session|A message indicating an action to add a new session to the database")); - } + // display the dialog.. + formDialogSessionManage.ShowDialog(); + } - /// - /// Displays the session management dialog for session management. - /// - public static void Execute() + /// + /// Handles the Shown event of the FormDialogSessionManage control. + /// + /// The source of the event. + /// The instance containing the event data. + private void FormDialogSessionManage_Shown(object sender, EventArgs e) + { + // list the sessions to the combo box.. + ListSessions(); + } + + /// + /// Lists the sessions in the database. + /// + private void ListSessions() + { + cmbSessions.Items.Clear(); + + // list the sessions to the combo box.. + foreach (FileSession session in ScriptNotepadDbContext.DbContext.FileSessions) { - // create a new instance of "this" dialog.. - FormDialogSessionManage formDialogSessionManage = new FormDialogSessionManage(); + cmbSessions.Items.Add(session); + } - // display the dialog.. - formDialogSessionManage.ShowDialog(); + // set the combo box index if there are any sessions in the list.. + if (cmbSessions.Items.Count > 0) + { + cmbSessions.SelectedIndex = 0; } + } - /// - /// Handles the Shown event of the FormDialogSessionManage control. - /// - /// The source of the event. - /// The instance containing the event data. - private void FormDialogSessionManage_Shown(object sender, EventArgs e) + /// + /// Handles the Click event of the pbAddNewSessionWithName control. + /// + /// The source of the event. + /// The instance containing the event data. + private void pbAddNewSessionWithName_Click(object sender, EventArgs e) + { + // a user wishes to add a new session with a name.. + if (ValidateSessionName(tbAddNewSessionWithName, true)) { + ScriptNotepadDbContext.DbContext.FileSessions.Add(new FileSession + {SessionName = tbAddNewSessionWithName.Text.Trim(' '), }); + + ScriptNotepadDbContext.DbContext.SaveChanges(); + // list the sessions to the combo box.. ListSessions(); - } - /// - /// Lists the sessions in the database. - /// - private void ListSessions() + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgSessionCreateSuccess", + "The session was successfully created.|A message indicating a successful session creation."), + DBLangEngine.GetMessage("msgSuccess", "Success|A message indicating a successful operation."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); + } + else { - cmbSessions.Items.Clear(); + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgWarningInvalidSessionName", + "The session name '{0}' is either invalid or already exists in the database|The given session name is invalid (white space or null) or the given session name already exists in the database", tbAddNewSessionWithName.Text), + DBLangEngine.GetMessage("msgWarning", "Warning|A message warning of some kind problem."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); + } + } - // list the sessions to the combo box.. - foreach (FileSession session in ScriptNotepadDbContext.DbContext.FileSessions) - { - cmbSessions.Items.Add(session); - } + /// + /// Validates the name of the session. + /// + /// The text box to use for validation. + /// If set to true the session name in the given text box may not exists within the current sessions in the database. + /// An optional ID number for the session to validate. + /// True if the session name was validate successfully; otherwise false. + private bool ValidateSessionName(TextBox textBox, bool canNotExist, int id = -1) + { + bool result = + !( + string.IsNullOrWhiteSpace(textBox.Text) || + ScriptNotepadDbContext.DbContext.FileSessions.Any(f => f.SessionName.ToLowerInvariant().Trim(' ') == textBox.Text.ToLowerInvariant().Trim(' ')) && canNotExist); - // set the combo box index if there are any sessions in the list.. - if (cmbSessions.Items.Count > 0) - { - cmbSessions.SelectedIndex = 0; - } + if (id != -1) + { + result &= + !ScriptNotepadDbContext.DbContext.FileSessions.Any(f => f.SessionName.ToLowerInvariant().Trim(' ') == textBox.Text.ToLowerInvariant().Trim(' ') && f.Id == id); } - /// - /// Handles the Click event of the pbAddNewSessionWithName control. - /// - /// The source of the event. - /// The instance containing the event data. - private void pbAddNewSessionWithName_Click(object sender, EventArgs e) + return result; + } + + /// + /// Handles the Click event of the pbRenameSelectedSession control. + /// + /// The source of the event. + /// The instance containing the event data. + private void pbRenameSelectedSession_Click(object sender, EventArgs e) + { + if (cmbSessions.SelectedItem != null) { - // a user wishes to add a new session with a name.. - if (ValidateSessionName(tbAddNewSessionWithName, true)) + var session = (FileSession)cmbSessions.SelectedItem; + + if (ValidateSessionName(tbRenameSession, false, session.Id)) { - ScriptNotepadDbContext.DbContext.FileSessions.Add(new FileSession - {SessionName = tbAddNewSessionWithName.Text.Trim(' ')}); + // set the session name to the instance.. + session.SessionName = tbRenameSession.Text.Trim(' '); ScriptNotepadDbContext.DbContext.SaveChanges(); - // list the sessions to the combo box.. - ListSessions(); + // set the session to the settings as it's saved as string using the session name.. + FormSettings.Settings.CurrentSessionEntity = session; + + // set the instance back to the combo box.. + cmbSessions.SelectedItem = session; MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgSessionCreateSuccess", - "The session was successfully created.|A message indicating a successful session creation."), + DBLangEngine.GetMessage("msgSessionRenameSuccess", + "The session was successfully renamed.|A message indicating a successful session rename."), DBLangEngine.GetMessage("msgSuccess", "Success|A message indicating a successful operation."), MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); } @@ -140,118 +203,54 @@ private void pbAddNewSessionWithName_Click(object sender, EventArgs e) { MessageBoxExtended.Show( DBLangEngine.GetMessage("msgWarningInvalidSessionName", - "The session name '{0}' is either invalid or already exists in the database|The given session name is invalid (white space or null) or the given session name already exists in the database", tbAddNewSessionWithName.Text), + "The session name '{0}' is either invalid or already exists in the database|The given session name is invalid (white space or null) or the given session name already exists in the database", tbRenameSession.Text), DBLangEngine.GetMessage("msgWarning", "Warning|A message warning of some kind problem."), MessageBoxButtonsExtended.OK, MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); } } + } - /// - /// Validates the name of the session. - /// - /// The text box to use for validation. - /// If set to true the session name in the given text box may not exists within the current sessions in the database. - /// An optional ID number for the session to validate. - /// True if the session name was validate successfully; otherwise false. - private bool ValidateSessionName(TextBox textBox, bool canNotExist, int id = -1) + private void pbDeleteSelectedSession_Click(object sender, EventArgs e) + { + if (cmbSessions.SelectedItem != null) { - bool result = - !( - string.IsNullOrWhiteSpace(textBox.Text) || - ScriptNotepadDbContext.DbContext.FileSessions.Any(f => f.SessionName.ToLowerInvariant().Trim(' ') == textBox.Text.ToLowerInvariant().Trim(' ')) && canNotExist); + FileSession session = (FileSession)cmbSessions.SelectedItem; - if (id != -1) + if (session.Id == 1) // Id == 1 is the default.. { - result &= - !ScriptNotepadDbContext.DbContext.FileSessions.Any(f => f.SessionName.ToLowerInvariant().Trim(' ') == textBox.Text.ToLowerInvariant().Trim(' ') && f.Id == id); - } - - return result; - } - - /// - /// Handles the Click event of the pbRenameSelectedSession control. - /// - /// The source of the event. - /// The instance containing the event data. - private void pbRenameSelectedSession_Click(object sender, EventArgs e) - { - if (cmbSessions.SelectedItem != null) - { - var session = (FileSession)cmbSessions.SelectedItem; - - if (ValidateSessionName(tbRenameSession, false, session.Id)) - { - // set the session name to the instance.. - session.SessionName = tbRenameSession.Text.Trim(' '); - - ScriptNotepadDbContext.DbContext.SaveChanges(); - - // set the session to the settings as it's saved as string using the session name.. - FormSettings.Settings.CurrentSessionEntity = session; - - // set the instance back to the combo box.. - cmbSessions.SelectedItem = session; + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgDefaultSessionCanNotDelete", + "The default session can not be deleted.|A message informing that the default session can not be deleted."), + DBLangEngine.GetMessage("msgInformation", "Information|A message title describing of some kind information."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgSessionRenameSuccess", - "The session was successfully renamed.|A message indicating a successful session rename."), - DBLangEngine.GetMessage("msgSuccess", "Success|A message indicating a successful operation."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); - } - else - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgWarningInvalidSessionName", - "The session name '{0}' is either invalid or already exists in the database|The given session name is invalid (white space or null) or the given session name already exists in the database", tbRenameSession.Text), - DBLangEngine.GetMessage("msgWarning", "Warning|A message warning of some kind problem."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Warning, ExtendedDefaultButtons.Button1); - } } - } - - private void pbDeleteSelectedSession_Click(object sender, EventArgs e) - { - if (cmbSessions.SelectedItem != null) + else if (session.SessionName == FormSettings.Settings.CurrentSessionEntity.SessionName) { - FileSession session = (FileSession)cmbSessions.SelectedItem; - - if (session.Id == 1) // Id == 1 is the default.. - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgDefaultSessionCanNotDelete", - "The default session can not be deleted.|A message informing that the default session can not be deleted."), - DBLangEngine.GetMessage("msgInformation", "Information|A message title describing of some kind information."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); - - } - else if (session.SessionName == FormSettings.Settings.CurrentSessionEntity.SessionName) - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgCurrentSessionCanNotDelete", + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgCurrentSessionCanNotDelete", "The currently active session can not be deleted.|A message informing that the currently active session can not be deleted."), - DBLangEngine.GetMessage("msgInformation", "Information|A message title describing of some kind information."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); - } - else + DBLangEngine.GetMessage("msgInformation", "Information|A message title describing of some kind information."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); + } + else + { + if (MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgConfirmDeleteEntireSession", + "Please confirm you want to delete an entire session '{0}' from the database. This operation can not be undone. Continue?|A confirmation dialog if the user wishes to delete an entire session from the database. (NO POSSIBILITY TO UNDO!).", session.SessionName), + DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog."), + MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2) == DialogResultExtended.Yes) { - if (MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgConfirmDeleteEntireSession", - "Please confirm you want to delete an entire session '{0}' from the database. This operation can not be undone. Continue?|A confirmation dialog if the user wishes to delete an entire session from the database. (NO POSSIBILITY TO UNDO!).", session.SessionName), - DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog."), - MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2) == DialogResultExtended.Yes) + if (FileSessionHelper.DeleteEntireSession(session)) { - if (FileSessionHelper.DeleteEntireSession(session)) - { - MessageBoxExtended.Show( - DBLangEngine.GetMessage("msgSessionDeleteSuccess", + MessageBoxExtended.Show( + DBLangEngine.GetMessage("msgSessionDeleteSuccess", "The session was successfully deleted.|A message indicating a successful session delete."), - DBLangEngine.GetMessage("msgSuccess", "Success|A message indicating a successful operation."), - MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); - } + DBLangEngine.GetMessage("msgSuccess", "Success|A message indicating a successful operation."), + MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1); } } } } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SessionHelpers/CloseFormUtils.cs b/ScriptNotepad/UtilityClasses/SessionHelpers/CloseFormUtils.cs index c4e8f2e9..46aa5e0e 100644 --- a/ScriptNotepad/UtilityClasses/SessionHelpers/CloseFormUtils.cs +++ b/ScriptNotepad/UtilityClasses/SessionHelpers/CloseFormUtils.cs @@ -27,39 +27,38 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Collections.Generic; using System.Windows.Forms; -namespace ScriptNotepad.UtilityClasses.SessionHelpers +namespace ScriptNotepad.UtilityClasses.SessionHelpers; + +/// +/// A utility class to close all forms of the software in case the session is ending. +/// +public static class CloseFormUtils { /// - /// A utility class to close all forms of the software in case the session is ending. + /// Closes all the open forms except the given form to exclude . /// - public static class CloseFormUtils + /// The Form class instance to excluded from being closed. + public static void CloseOpenForms(Form excludeForm) { - /// - /// Closes all the open forms except the given form to exclude . - /// - /// The Form class instance to excluded from being closed. - public static void CloseOpenForms(Form excludeForm) - { - // create a list of forms to be closed.. - List
forms = new List(); + // create a list of forms to be closed.. + List forms = new List(); - // set the contents for the lost of forms to be closed.. - foreach (Form form in Application.OpenForms) + // set the contents for the lost of forms to be closed.. + foreach (Form form in Application.OpenForms) + { + // ..with the exception o.. + if (!form.Equals(excludeForm)) { - // ..with the exception o.. - if (!form.Equals(excludeForm)) - { - forms.Add(form); - } + forms.Add(form); } + } - // loop through the list of forms to be closed.. - // ReSharper disable once ForCanBeConvertedToForeach - for (int i = 0; i < forms.Count; i++) - { - // ..and close them.. - forms[i].Close(); - } + // loop through the list of forms to be closed.. + // ReSharper disable once ForCanBeConvertedToForeach + for (int i = 0; i < forms.Count; i++) + { + // ..and close them.. + forms[i].Close(); } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SessionHelpers/SessionMenuBuilder.cs b/ScriptNotepad/UtilityClasses/SessionHelpers/SessionMenuBuilder.cs index c8888e4f..281d37e7 100644 --- a/ScriptNotepad/UtilityClasses/SessionHelpers/SessionMenuBuilder.cs +++ b/ScriptNotepad/UtilityClasses/SessionHelpers/SessionMenuBuilder.cs @@ -29,129 +29,127 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.Database.Entity.Context; using ScriptNotepad.Database.Entity.Entities; -namespace ScriptNotepad.UtilityClasses.SessionHelpers +namespace ScriptNotepad.UtilityClasses.SessionHelpers; + +/// +/// A class to help to build a menu for sessions within the software (). +/// +public class SessionMenuBuilder { /// - /// A class to help to build a menu for sessions within the software (). + /// Creates the session menu to a given parent tool strip menu item. /// - public class SessionMenuBuilder + /// The parent tool strip menu item to create the session menu to. + /// The currently active session. + public static void CreateSessionMenu(ToolStripMenuItem parent, FileSession currentSession) { - /// - /// Creates the session menu to a given parent tool strip menu item. - /// - /// The parent tool strip menu item to create the session menu to. - /// The currently active session. - public static void CreateSessionMenu(ToolStripMenuItem parent, FileSession currentSession) - { - // first dispose the previous menu.. - DisposeSessionMenu(); + // first dispose the previous menu.. + DisposeSessionMenu(); - foreach (var session in ScriptNotepadDbContext.DbContext.FileSessions) + foreach (var session in ScriptNotepadDbContext.DbContext.FileSessions) + { + var item = new ToolStripMenuItem { - var item = new ToolStripMenuItem - { - Text = session.SessionName, - Tag = session, CheckOnClick = true, - Checked = session.SessionName == currentSession.SessionName, - }; + Text = session.SessionName, + Tag = session, CheckOnClick = true, + Checked = session.SessionName == currentSession.SessionName, + }; - item.Click += SessionMenuItem_Click; - item.Checked = session.SessionName == currentSession.SessionName; + item.Click += SessionMenuItem_Click; + item.Checked = session.SessionName == currentSession.SessionName; - CurrentMenu.Add(item); + CurrentMenu.Add(item); - parent.DropDownItems.Add(item); - } + parent.DropDownItems.Add(item); } + } - /// - /// Gets or sets the current menu items in the session parent menu. - /// - private static List CurrentMenu { get; } = new List(); + /// + /// Gets or sets the current menu items in the session parent menu. + /// + private static List CurrentMenu { get; } = new List(); - /// - /// Disposes the session menu. - /// - public static void DisposeSessionMenu() + /// + /// Disposes the session menu. + /// + public static void DisposeSessionMenu() + { + // create a list of tool strip menu items to dispose of.. + List disposeList = new List(); + foreach (var item in CurrentMenu) { - // create a list of tool strip menu items to dispose of.. - List disposeList = new List(); - foreach (var item in CurrentMenu) + // only accept types of ToolStripMenuItem.. + if (item.GetType() != typeof(ToolStripMenuItem)) { - // only accept types of ToolStripMenuItem.. - if (item.GetType() != typeof(ToolStripMenuItem)) - { - continue; - } - - // cast the object as ToolStripMenuItem.. - var sessionMenuItem = item; - - disposeList.Add(sessionMenuItem); + continue; } - // clear the drop down items from the parent menu item.. - CurrentMenu.Clear(); + // cast the object as ToolStripMenuItem.. + var sessionMenuItem = item; - // loop through the list of ToolStripMenuItems to disposed of.. - // ReSharper disable once ForCanBeConvertedToForeach - for (int i = 0; i < disposeList.Count; i++) - { - // dispose.. - using (disposeList[i]) - { - // unsubscribe the internal event.. - disposeList[i].Click -= SessionMenuItem_Click; - } - } + disposeList.Add(sessionMenuItem); } - // a user clicked a drop-down menu item in the sessions menu.. - private static void SessionMenuItem_Click(object sender, EventArgs e) + // clear the drop down items from the parent menu item.. + CurrentMenu.Clear(); + + // loop through the list of ToolStripMenuItems to disposed of.. + // ReSharper disable once ForCanBeConvertedToForeach + for (int i = 0; i < disposeList.Count; i++) { - // toggle the checked state of the session in the sessions menu.. - foreach (var item in CurrentMenu) + // dispose.. + using (disposeList[i]) { - item.Checked = item.Equals(sender); + // unsubscribe the internal event.. + disposeList[i].Click -= SessionMenuItem_Click; } + } + } - // get the data from the clicked menu item.. - ToolStripMenuItem menuItem = (ToolStripMenuItem)sender; - var session = (FileSession)menuItem.Tag; - - // raise the event if subscribed.. - SessionMenuClicked?.Invoke(sender, new SessionMenuClickEventArgs { Session = session, Data = null }); + // a user clicked a drop-down menu item in the sessions menu.. + private static void SessionMenuItem_Click(object sender, EventArgs e) + { + // toggle the checked state of the session in the sessions menu.. + foreach (var item in CurrentMenu) + { + item.Checked = item.Equals(sender); } - /// - /// A delegate for the SessionMenuClicked event. - /// - /// The sender of the event. - /// The instance containing the event data. - public delegate void OnSessionMenuClicked(object sender, SessionMenuClickEventArgs e); - - /// - /// Occurs when a session menu item was clicked. - /// - public static event OnSessionMenuClicked SessionMenuClicked; + // get the data from the clicked menu item.. + ToolStripMenuItem menuItem = (ToolStripMenuItem)sender; + var session = (FileSession)menuItem.Tag; + + // raise the event if subscribed.. + SessionMenuClicked?.Invoke(sender, new SessionMenuClickEventArgs { Session = session, Data = null, }); } /// - /// Event arguments for the SessionMenuClicked event. + /// A delegate for the SessionMenuClicked event. /// - /// - public class SessionMenuClickEventArgs : EventArgs - { - /// - /// Gets the session of the clicked session menu item. - /// - public FileSession Session { get; internal set; } - - /// - /// Gets the data associated with the session menu item. - /// - public object Data { get; internal set; } - } + /// The sender of the event. + /// The instance containing the event data. + public delegate void OnSessionMenuClicked(object sender, SessionMenuClickEventArgs e); + + /// + /// Occurs when a session menu item was clicked. + /// + public static event OnSessionMenuClicked SessionMenuClicked; } +/// +/// Event arguments for the SessionMenuClicked event. +/// +/// +public class SessionMenuClickEventArgs : EventArgs +{ + /// + /// Gets the session of the clicked session menu item. + /// + public FileSession Session { get; internal set; } + + /// + /// Gets the data associated with the session menu item. + /// + public object Data { get; internal set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/SpellCheck/TabbedDocumentSpellCheck.cs b/ScriptNotepad/UtilityClasses/SpellCheck/TabbedDocumentSpellCheck.cs index 4d9ea15a..2bcb2a92 100644 --- a/ScriptNotepad/UtilityClasses/SpellCheck/TabbedDocumentSpellCheck.cs +++ b/ScriptNotepad/UtilityClasses/SpellCheck/TabbedDocumentSpellCheck.cs @@ -33,100 +33,83 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.ScintillaTabbedTextControl; using VPKSoft.Utils; -namespace ScriptNotepad.UtilityClasses.SpellCheck +namespace ScriptNotepad.UtilityClasses.SpellCheck; + +/// +/// A helper class for the for spell checking. +/// +public class TabbedDocumentSpellCheck: ErrorHandlingBase, IDisposable { /// - /// A helper class for the for spell checking. + /// Initializes a new instance of the class. /// - public class TabbedDocumentSpellCheck: ErrorHandlingBase, IDisposable + /// The to attach the spell checker. + /// Specifies whether the dictionary files should be loaded to the instance. + public TabbedDocumentSpellCheck(ScintillaTabbedDocument document, bool loadDictionaryFiles) { - /// - /// Initializes a new instance of the class. - /// - /// The to attach the spell checker. - /// Specifies whether the dictionary files should be loaded to the instance. - public TabbedDocumentSpellCheck(ScintillaTabbedDocument document, bool loadDictionaryFiles) + // verify the settings and the fact that the document doesn't already have this instance.. + if (FormSettings.Settings.EditorUseSpellChecking && + File.Exists(FormSettings.Settings.EditorHunspellDictionaryFile) && + File.Exists(FormSettings.Settings.EditorHunspellAffixFile) && + document.Tag0 == null) { - // verify the settings and the fact that the document doesn't already have this instance.. - if (FormSettings.Settings.EditorUseSpellChecking && - File.Exists(FormSettings.Settings.EditorHunspellDictionaryFile) && - File.Exists(FormSettings.Settings.EditorHunspellAffixFile) && - document.Tag0 == null) + try { - try + SpellCheck = new ScintillaSpellCheck(document.Scintilla, + FormSettings.Settings.EditorHunspellDictionaryFile, + FormSettings.Settings.EditorHunspellAffixFile, + UserDictionaryFile, + UserIgnoreWordFile) { - SpellCheck = new ScintillaSpellCheck(document.Scintilla, - FormSettings.Settings.EditorHunspellDictionaryFile, - FormSettings.Settings.EditorHunspellAffixFile, - UserDictionaryFile, - UserIgnoreWordFile) - { - MenuIgnoreText = DBLangEngine.GetStatMessage("msgSpellCheckIgnoreWordMenuText", - "Ignore word \"{0}\".|A context menu item for spell checking to ignore a word"), - MenuAddToDictionaryText = DBLangEngine.GetStatMessage( - "msgSpellCheckAddWordToDictionaryText", - "Add word \"{0}\" to the dictionary.|A context menu item for spell checking to add a word to the dictionary"), - MenuDictionaryTopItemText = DBLangEngine.GetStatMessage("msgSpellChecking", - "Spell checking|A message displayed in a spelling correct menu's top item."), - ShowDictionaryTopMenuItem = true, - AddBottomSeparator = true, - ShowIgnoreMenu = true, - ShowAddToDictionaryMenu = true, - ScintillaIndicatorColor = FormSettings.Settings.EditorSpellCheckColor, - }; - - if (!loadDictionaryFiles) - { - SpellCheck.Dictionary = null; - } - - // add this instance to the document's Tag0 property.. - document.Tag0 = this; - - // subscribe to the event where a user wishes to correct a - // misspelled word via the context menu.. - SpellCheck.UserWordReplace += SpellCheck_UserWordReplace; - - // subscribe to the Scintilla text changed event.. - document.Scintilla.TextChanged += Scintilla_TextChanged; - - // subscribe the event when a user is requesting a word to be added to the personal dictionary.. - SpellCheck.WordAddDictionaryRequested += SpellCheck_WordAddDictionaryOrIgnoreRequested; - - // subscribe to the event when a user is requesting to add a word to personal ignore list.. - SpellCheck.WordIgnoreRequested += SpellCheck_WordAddDictionaryOrIgnoreRequested; - - // save the Scintilla instance to unsubscribe the events.. - Scintilla = document.Scintilla; - - // spell check the document for the first time.. - SpellCheck?.SpellCheckScintillaFast(); - - // save the time of the latest spell check.. - LastSpellCheck = DateTime.Now; - } - catch (Exception ex) + MenuIgnoreText = DBLangEngine.GetStatMessage("msgSpellCheckIgnoreWordMenuText", + "Ignore word \"{0}\".|A context menu item for spell checking to ignore a word"), + MenuAddToDictionaryText = DBLangEngine.GetStatMessage( + "msgSpellCheckAddWordToDictionaryText", + "Add word \"{0}\" to the dictionary.|A context menu item for spell checking to add a word to the dictionary"), + MenuDictionaryTopItemText = DBLangEngine.GetStatMessage("msgSpellChecking", + "Spell checking|A message displayed in a spelling correct menu's top item."), + ShowDictionaryTopMenuItem = true, + AddBottomSeparator = true, + ShowIgnoreMenu = true, + ShowAddToDictionaryMenu = true, + ScintillaIndicatorColor = FormSettings.Settings.EditorSpellCheckColor, + }; + + if (!loadDictionaryFiles) { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - - try - { - ExceptionLogger.LogMessage($"Spell check state: '{FormSettings.Settings.EditorUseSpellChecking}'."); - ExceptionLogger.LogMessage( - $"File exists ({File.Exists(FormSettings.Settings.EditorHunspellDictionaryFile)}): '{FormSettings.Settings.EditorHunspellDictionaryFile}'."); - ExceptionLogger.LogMessage( - $"File exists ({File.Exists(FormSettings.Settings.EditorHunspellAffixFile)}): '{FormSettings.Settings.EditorHunspellAffixFile}'."); - ExceptionLogger.LogMessage($"Document Tag0: '{document.Tag0}'."); - } - catch (Exception ex2) - { - ExceptionLogger.LogError(ex2); - } + SpellCheck.Dictionary = null; } + + // add this instance to the document's Tag0 property.. + document.Tag0 = this; + + // subscribe to the event where a user wishes to correct a + // misspelled word via the context menu.. + SpellCheck.UserWordReplace += SpellCheck_UserWordReplace; + + // subscribe to the Scintilla text changed event.. + document.Scintilla.TextChanged += Scintilla_TextChanged; + + // subscribe the event when a user is requesting a word to be added to the personal dictionary.. + SpellCheck.WordAddDictionaryRequested += SpellCheck_WordAddDictionaryOrIgnoreRequested; + + // subscribe to the event when a user is requesting to add a word to personal ignore list.. + SpellCheck.WordIgnoreRequested += SpellCheck_WordAddDictionaryOrIgnoreRequested; + + // save the Scintilla instance to unsubscribe the events.. + Scintilla = document.Scintilla; + + // spell check the document for the first time.. + SpellCheck?.SpellCheckScintillaFast(); + + // save the time of the latest spell check.. + LastSpellCheck = DateTime.Now; } - else + catch (Exception ex) { + // log the exception.. + ExceptionLogAction?.Invoke(ex); + try { ExceptionLogger.LogMessage($"Spell check state: '{FormSettings.Settings.EditorUseSpellChecking}'."); @@ -136,209 +119,225 @@ public TabbedDocumentSpellCheck(ScintillaTabbedDocument document, bool loadDicti $"File exists ({File.Exists(FormSettings.Settings.EditorHunspellAffixFile)}): '{FormSettings.Settings.EditorHunspellAffixFile}'."); ExceptionLogger.LogMessage($"Document Tag0: '{document.Tag0}'."); } - catch (Exception ex) + catch (Exception ex2) { - ExceptionLogger.LogError(ex); + ExceptionLogger.LogError(ex2); } } } - - private void SpellCheck_WordAddDictionaryOrIgnoreRequested(object sender, WordHandleEventArgs e) + else { - // check if the word was requested to be added to the dictionary.. - if (e.AddToDictionary) - { - e.ScintillaSpellCheck.AddToUserDictionary(e.Word); - SpellCheckEnabled = true; // indicate to force a spell check.. - DoSpellCheck(); + try + { + ExceptionLogger.LogMessage($"Spell check state: '{FormSettings.Settings.EditorUseSpellChecking}'."); + ExceptionLogger.LogMessage( + $"File exists ({File.Exists(FormSettings.Settings.EditorHunspellDictionaryFile)}): '{FormSettings.Settings.EditorHunspellDictionaryFile}'."); + ExceptionLogger.LogMessage( + $"File exists ({File.Exists(FormSettings.Settings.EditorHunspellAffixFile)}): '{FormSettings.Settings.EditorHunspellAffixFile}'."); + ExceptionLogger.LogMessage($"Document Tag0: '{document.Tag0}'."); } - // check if the word was requested to be added to the ignore word list.. - else if (e.AddToIgnore) + catch (Exception ex) { - e.ScintillaSpellCheck.AddToUserIgnoreList(e.Word); - SpellCheckEnabled = true; // indicate to force a spell check.. - DoSpellCheck(); + ExceptionLogger.LogError(ex); } } + } - /// - /// Gets or sets the user dictionary file. - /// - public static string UserDictionaryFile { get; set; } = - Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "user_dictionary.dic"); - - /// - /// Gets or sets the user ignore word file. - /// - public static string UserIgnoreWordFile { get; set; } = - Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "user_dictionary.ignore"); - - /// - /// Gets or set the instance this class has event subscription for. - /// - private Scintilla Scintilla { get; } - - /// - /// Runs a spell check for the document. - /// - public void DoSpellCheck() + private void SpellCheck_WordAddDictionaryOrIgnoreRequested(object sender, WordHandleEventArgs e) + { + // check if the word was requested to be added to the dictionary.. + if (e.AddToDictionary) + { + e.ScintillaSpellCheck.AddToUserDictionary(e.Word); + SpellCheckEnabled = true; // indicate to force a spell check.. + DoSpellCheck(); + } + // check if the word was requested to be added to the ignore word list.. + else if (e.AddToIgnore) { - // prevent the spell checking to take place if it's - // explicitly disabled or there is no need no redo the - // spell checking.. - if (!ShouldSpellCheck || !Enabled) - { - return; - } + e.ScintillaSpellCheck.AddToUserIgnoreList(e.Word); + SpellCheckEnabled = true; // indicate to force a spell check.. + DoSpellCheck(); + } + } - // spell check the document.. - SpellCheck?.SpellCheckScintillaFast(); + /// + /// Gets or sets the user dictionary file. + /// + public static string UserDictionaryFile { get; set; } = + Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "user_dictionary.dic"); - // reset the value of the flag.. - SpellCheckEnabled = false; + /// + /// Gets or sets the user ignore word file. + /// + public static string UserIgnoreWordFile { get; set; } = + Path.Combine(Paths.GetAppSettingsFolder(Misc.AppType.Winforms), "user_dictionary.ignore"); - // reset the time of the latest spell check.. - LastSpellCheck = DateTime.Now; - } + /// + /// Gets or set the instance this class has event subscription for. + /// + private Scintilla Scintilla { get; } - /// - /// Handles the TextChanged event of the Scintilla control. - /// - /// The source of the event. - /// The instance containing the event data. - private void Scintilla_TextChanged(object sender, EventArgs e) + /// + /// Runs a spell check for the document. + /// + public void DoSpellCheck() + { + // prevent the spell checking to take place if it's + // explicitly disabled or there is no need no redo the + // spell checking.. + if (!ShouldSpellCheck || !Enabled) { - // reset the time of the latest spell check.. - LastSpellCheck = DateTime.Now; + return; + } - if (TextChangedViaSpellCheck) - { - return; - } + // spell check the document.. + SpellCheck?.SpellCheckScintillaFast(); - // reset the value of the flag.. - SpellCheckEnabled = true; - } + // reset the value of the flag.. + SpellCheckEnabled = false; - /// - /// Handles the UserWordReplace event of the SpellCheck control. - /// - /// The source of the event. - /// The instance containing the event data. - private void SpellCheck_UserWordReplace(object sender, WordHandleEventArgs e) - { - // if the user changed the text of a Scintilla via the spell check context - // menu to correct a word, then there is no reason to spell check the document again after the text has been changed.. - TextChangedViaSpellCheck = true; - } + // reset the time of the latest spell check.. + LastSpellCheck = DateTime.Now; + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + /// + /// Handles the TextChanged event of the Scintilla control. + /// + /// The source of the event. + /// The instance containing the event data. + private void Scintilla_TextChanged(object sender, EventArgs e) + { + // reset the time of the latest spell check.. + LastSpellCheck = DateTime.Now; + + if (TextChangedViaSpellCheck) { - Dispose(true); - GC.SuppressFinalize(this); + return; } - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) + // reset the value of the flag.. + SpellCheckEnabled = true; + } + + /// + /// Handles the UserWordReplace event of the SpellCheck control. + /// + /// The source of the event. + /// The instance containing the event data. + private void SpellCheck_UserWordReplace(object sender, WordHandleEventArgs e) + { + // if the user changed the text of a Scintilla via the spell check context + // menu to correct a word, then there is no reason to spell check the document again after the text has been changed.. + TextChangedViaSpellCheck = true; + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - // unsubscribe to the event where a user wishes to correct a - // misspelled word via the context menu.. - SpellCheck.UserWordReplace -= SpellCheck_UserWordReplace; + // unsubscribe to the event where a user wishes to correct a + // misspelled word via the context menu.. + SpellCheck.UserWordReplace -= SpellCheck_UserWordReplace; - // unsubscribe to the Scintilla text changed event.. - Scintilla.TextChanged -= Scintilla_TextChanged; + // unsubscribe to the Scintilla text changed event.. + Scintilla.TextChanged -= Scintilla_TextChanged; - SpellCheck.WordAddDictionaryRequested -= SpellCheck_WordAddDictionaryOrIgnoreRequested; + SpellCheck.WordAddDictionaryRequested -= SpellCheck_WordAddDictionaryOrIgnoreRequested; - SpellCheck.WordIgnoreRequested -= SpellCheck_WordAddDictionaryOrIgnoreRequested; + SpellCheck.WordIgnoreRequested -= SpellCheck_WordAddDictionaryOrIgnoreRequested; - // save the user's dictionary to a file.. - SpellCheck.SaveUserDictionaryToFile(UserDictionaryFile); + // save the user's dictionary to a file.. + SpellCheck.SaveUserDictionaryToFile(UserDictionaryFile); - // save the user's ignore word list to a file.. - SpellCheck.SaveUserWordIgnoreListToFile(UserIgnoreWordFile); + // save the user's ignore word list to a file.. + SpellCheck.SaveUserWordIgnoreListToFile(UserIgnoreWordFile); - // dispose of the ScintillaSpellCheck class.. - using (SpellCheck) - { - SpellCheck = null; // empty using clause is ugly :-( - } + // dispose of the ScintillaSpellCheck class.. + using (SpellCheck) + { + SpellCheck = null; // empty using clause is ugly :-( } } + } - private int textChangedViaSpellCheck = -1; + private int textChangedViaSpellCheck = -1; - /// - /// Gets or sets a value indicating if the text was changed via spelling correction. - /// - private bool TextChangedViaSpellCheck + /// + /// Gets or sets a value indicating if the text was changed via spelling correction. + /// + private bool TextChangedViaSpellCheck + { + get { - get - { - // this value returns true for a two times if set to true.. - var result = textChangedViaSpellCheck >= 0; + // this value returns true for a two times if set to true.. + var result = textChangedViaSpellCheck >= 0; - // decrease the value.. - textChangedViaSpellCheck--; + // decrease the value.. + textChangedViaSpellCheck--; - return result; - } - set => textChangedViaSpellCheck = value ? 2 : 0; + return result; } + set => textChangedViaSpellCheck = value ? 2 : 0; + } - // a field for the Enabled property.. - private bool enabled = true; + // a field for the Enabled property.. + private bool enabled = true; - /// - /// Gets or set a value whether the spell checking is enabled. - /// - public bool Enabled - { - get => enabled; + /// + /// Gets or set a value whether the spell checking is enabled. + /// + public bool Enabled + { + get => enabled; - set + set + { + if (value != enabled) { - if (value != enabled) + SpellCheckEnabled = value; + enabled = value; + if (!value) { - SpellCheckEnabled = value; - enabled = value; - if (!value) - { - SpellCheck.ClearSpellCheck(); - } + SpellCheck.ClearSpellCheck(); } } } - - /// - /// A flag indicating whether the text was changed via a spelling correction or another way. - /// - private bool SpellCheckEnabled { get; set; } = true; - - /// - /// Gets or sets the last time to document was spell checked for. - /// - public DateTime LastSpellCheck = DateTime.Now; - - /// - /// Gets a value whether a spell check should be done. - /// - public bool ShouldSpellCheck => - (DateTime.Now - LastSpellCheck).TotalMilliseconds > FormSettings.Settings.EditorSpellCheckInactivity && - SpellCheckEnabled && !TextChangedViaSpellCheck; - - /// - /// Gets or sets the class instance. - /// - /// The spell check. - public ScintillaSpellCheck SpellCheck { get; set; } } -} + + /// + /// A flag indicating whether the text was changed via a spelling correction or another way. + /// + private bool SpellCheckEnabled { get; set; } = true; + + /// + /// Gets or sets the last time to document was spell checked for. + /// + public DateTime LastSpellCheck = DateTime.Now; + + /// + /// Gets a value whether a spell check should be done. + /// + public bool ShouldSpellCheck => + (DateTime.Now - LastSpellCheck).TotalMilliseconds > FormSettings.Settings.EditorSpellCheckInactivity && + SpellCheckEnabled && !TextChangedViaSpellCheck; + + /// + /// Gets or sets the class instance. + /// + /// The spell check. + public ScintillaSpellCheck SpellCheck { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/StreamHelpers/StreamStringHelpers.cs b/ScriptNotepad/UtilityClasses/StreamHelpers/StreamStringHelpers.cs index 3f4d7828..247a3758 100644 --- a/ScriptNotepad/UtilityClasses/StreamHelpers/StreamStringHelpers.cs +++ b/ScriptNotepad/UtilityClasses/StreamHelpers/StreamStringHelpers.cs @@ -24,36 +24,35 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.StreamHelpers +namespace ScriptNotepad.UtilityClasses.StreamHelpers; + +/// +/// A class to help with MemoryStreams and strings. +/// +public static class StreamStringHelpers { /// - /// A class to help with MemoryStreams and strings. + /// Returns the contents of a give as a string. /// - public static class StreamStringHelpers + /// The memory stream which contents to be returned as a string. + /// The encoding to be used to convert a memory stream to text. + /// + public static string MemoryStreamToText(MemoryStream memoryStream, System.Text.Encoding encoding) { - /// - /// Returns the contents of a give as a string. - /// - /// The memory stream which contents to be returned as a string. - /// The encoding to be used to convert a memory stream to text. - /// - public static string MemoryStreamToText(MemoryStream memoryStream, System.Text.Encoding encoding) - { - return encoding.GetString(memoryStream.ToArray()); - } + return encoding.GetString(memoryStream.ToArray()); + } - /// - /// Converts the encoding of a given string. - /// - /// The encoding to convert from. - /// The encoding to convert to. - /// The contents which encoding should be changed. - /// A string converted to the encoding . - public static string ConvertEncoding(System.Text.Encoding encodingFrom, System.Text.Encoding encodingTo, string contents) - { - byte[] bytes = encodingFrom.GetBytes(contents); - bytes = System.Text.Encoding.Convert(encodingFrom, encodingTo, bytes); - return encodingTo.GetString(bytes); - } + /// + /// Converts the encoding of a given string. + /// + /// The encoding to convert from. + /// The encoding to convert to. + /// The contents which encoding should be changed. + /// A string converted to the encoding . + public static string ConvertEncoding(System.Text.Encoding encodingFrom, System.Text.Encoding encodingTo, string contents) + { + byte[] bytes = encodingFrom.GetBytes(contents); + bytes = System.Text.Encoding.Convert(encodingFrom, encodingTo, bytes); + return encodingTo.GetString(bytes); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Base64Convert.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Base64Convert.cs index 4537a528..2a713714 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Base64Convert.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Base64Convert.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,35 +26,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.base64; -namespace ScriptNotepad.UtilityClasses.TextManipulation +namespace ScriptNotepad.UtilityClasses.TextManipulation; + +/// +/// A class to convert base64 encoded string data. +/// +public static class Base64Convert { + private static readonly Base64ToString Base64ToString = new(); + + private static readonly StringToBase64 StringToBase64 = new(); + + /// + /// Converts the specified string value into base64 encoded data string. + /// + /// The value to convert. + /// The specified string converted into base64 encoded data string. + public static string ToBase64(this string value) + { + return StringToBase64.Manipulate(value); + } + /// - /// A class to convert base64 encoded string data. + /// Converts the specified base64 encoded string data into string a string value. /// - public static class Base64Convert + /// The value to convert. + /// The specified base64 encoded string data converted into string a string value. + public static string FromBase64(this string value) { - private static readonly Base64ToString Base64ToString = new(); - - private static readonly StringToBase64 StringToBase64 = new(); - - /// - /// Converts the specified string value into base64 encoded data string. - /// - /// The value to convert. - /// The specified string converted into base64 encoded data string. - public static string ToBase64(this string value) - { - return StringToBase64.Manipulate(value); - } - - /// - /// Converts the specified base64 encoded string data into string a string value. - /// - /// The value to convert. - /// The specified base64 encoded string data converted into string a string value. - public static string FromBase64(this string value) - { - return Base64ToString.Manipulate(value); - } + return Base64ToString.Manipulate(value); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextLinesManipulationCommandBase.cs b/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextLinesManipulationCommandBase.cs index 111cf87b..9e543354 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextLinesManipulationCommandBase.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextLinesManipulationCommandBase.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,45 +28,44 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Linq; using ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; -namespace ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses +namespace ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; + +/// +/// A base class for all the simple text manipulation utility classes. +/// Implements the +/// +/// +public abstract class TextLinesManipulationCommandBase: ITextLinesManipulationCommand { /// - /// A base class for all the simple text manipulation utility classes. - /// Implements the + /// Manipulates the specified text value. /// - /// - public abstract class TextLinesManipulationCommandBase: ITextLinesManipulationCommand - { - /// - /// Manipulates the specified text value. - /// - /// The lines to manipulate. - /// The encoding used in the - /// A string containing the manipulated text. - /// - /// The may contain line separator character(s). - public abstract string Manipulate(IList lines, Encoding textEncoding); + /// The lines to manipulate. + /// The encoding used in the + /// A string containing the manipulated text. + /// + /// The may contain line separator character(s). + public abstract string Manipulate(IList lines, Encoding textEncoding); - /// - /// Determines whether the collection has new line characters at the end of the string. - /// - /// The lines to check for new line characters. - /// bool. - public static bool HasLineFeeds(IList lines) - { - return lines.Any(f => f.EndsWith('\n') || f.EndsWith('\r')); - } + /// + /// Determines whether the collection has new line characters at the end of the string. + /// + /// The lines to check for new line characters. + /// bool. + public static bool HasLineFeeds(IList lines) + { + return lines.Any(f => f.EndsWith('\n') || f.EndsWith('\r')); + } - /// - /// Gets or sets the name of the method manipulating the text. - /// - /// The name of the method manipulating the text. - public string MethodName { get; set; } + /// + /// Gets or sets the name of the method manipulating the text. + /// + /// The name of the method manipulating the text. + public string MethodName { get; set; } - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public abstract override string ToString(); - } -} + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public abstract override string ToString(); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCallbackBase.cs b/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCallbackBase.cs index 598a4ef4..bb38b882 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCallbackBase.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCallbackBase.cs @@ -1,33 +1,32 @@ using ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; -namespace ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses +namespace ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; + +/// +/// Class TextManipulationCallbackBase. +/// Implements the +/// +/// +public class TextManipulationCallbackBase: ITextManipulationCallback { /// - /// Class TextManipulationCallbackBase. - /// Implements the + /// Gets or sets the callback action. /// - /// - public class TextManipulationCallbackBase: ITextManipulationCallback - { - /// - /// Gets or sets the callback action. - /// - /// The callback action. - public Action CallbackAction { get; set; } + /// The callback action. + public Action CallbackAction { get; set; } - /// - /// Gets or sets the name of the method manipulating the text. - /// - /// The name of the method manipulating the text. - public string MethodName { get; set; } + /// + /// Gets or sets the name of the method manipulating the text. + /// + /// The name of the method manipulating the text. + public string MethodName { get; set; } - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return MethodName; - } + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return MethodName; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCommandBase.cs b/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCommandBase.cs index 4bc473cb..d5ae8317 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCommandBase.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/BaseClasses/TextManipulationCommandBase.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,38 +27,37 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; -namespace ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses +namespace ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; + +/// +/// A base class for all the simple text manipulation utility classes. +/// Implements the +/// +/// +public abstract class TextManipulationCommandBase: ITextManipulationCommand { /// - /// A base class for all the simple text manipulation utility classes. - /// Implements the + /// Manipulates the specified text value. /// - /// - public abstract class TextManipulationCommandBase: ITextManipulationCommand - { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public abstract string Manipulate(string value); + /// The value to manipulate. + /// A string containing the manipulated text. + public abstract string Manipulate(string value); - /// - /// Gets or sets a value indicating whether prefer selected text of the control for the command. - /// - /// true if to prefer selected text of the control for the command; otherwise, false. - public abstract bool PreferSelectedText { get; set; } + /// + /// Gets or sets a value indicating whether prefer selected text of the control for the command. + /// + /// true if to prefer selected text of the control for the command; otherwise, false. + public abstract bool PreferSelectedText { get; set; } - /// - /// Gets or sets the name of the method manipulating the text. - /// - /// The name of the method manipulating the text. - public string MethodName { get; set; } + /// + /// Gets or sets the name of the method manipulating the text. + /// + /// The name of the method manipulating the text. + public string MethodName { get; set; } - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public abstract override string ToString(); - } -} + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public abstract override string ToString(); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/DuplicateLines.cs b/ScriptNotepad/UtilityClasses/TextManipulation/DuplicateLines.cs index 8ad2b38b..7f6a1c2d 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/DuplicateLines.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/DuplicateLines.cs @@ -31,115 +31,114 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.LinesAndBinary; using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; -namespace ScriptNotepad.UtilityClasses.TextManipulation +namespace ScriptNotepad.UtilityClasses.TextManipulation; + +/// +/// A class for handling duplicate lines within a +/// Implements the +/// +/// +public class DuplicateLines: TextManipulationCommandBase { /// - /// A class for handling duplicate lines within a - /// Implements the + /// Removes the duplicate lines from a given control. /// - /// - public class DuplicateLines: TextManipulationCommandBase + /// The control. + /// The type of string comparison. + /// The type of the line ending in the control. + public static void RemoveDuplicateLines(Scintilla scintilla, StringComparison stringComparison, FileLineTypes fileLineTypes) { - /// - /// Removes the duplicate lines from a given control. - /// - /// The control. - /// The type of string comparison. - /// The type of the line ending in the control. - public static void RemoveDuplicateLines(Scintilla scintilla, StringComparison stringComparison, FileLineTypes fileLineTypes) + try { - try - { - scintilla.Text = Manipulate(scintilla.Text, stringComparison, fileLineTypes); - } - catch (Exception ex) - { - // log the exception if the action has a value.. - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - } + scintilla.Text = Manipulate(scintilla.Text, stringComparison, fileLineTypes); + } + catch (Exception ex) + { + // log the exception if the action has a value.. + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); } + } - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// The type of string comparison. - /// The type of the line ending in the control. - /// A string containing the manipulated text. - public static string Manipulate(string value, StringComparison stringComparison, FileLineTypes fileLineTypes) + /// + /// Manipulates the specified text value. + /// + /// The value to manipulate. + /// The type of string comparison. + /// The type of the line ending in the control. + /// A string containing the manipulated text. + public static string Manipulate(string value, StringComparison stringComparison, FileLineTypes fileLineTypes) + { + try { - try - { - var lines = new List(); - using var reader = new StringReader(value); + var lines = new List(); + using var reader = new StringReader(value); - string readLine; + string readLine; - while ((readLine = reader.ReadLine()) != null) - { - lines.Add(readLine); - } + while ((readLine = reader.ReadLine()) != null) + { + lines.Add(readLine); + } - var linesNew = new List(); + var linesNew = new List(); - foreach (var line in lines) + foreach (var line in lines) + { + if (!linesNew.Exists(f => f.Equals(line, stringComparison))) { - if (!linesNew.Exists(f => f.Equals(line, stringComparison))) - { - linesNew.Add(line); - } + linesNew.Add(line); } + } - string lineSeparator = Environment.NewLine; - - if (fileLineTypes.HasFlag(FileLineTypes.CRLF)) - { - lineSeparator = "\r\n"; - } - else if (fileLineTypes.HasFlag(FileLineTypes.LF)) - { - lineSeparator = "\n"; - } - else if (fileLineTypes.HasFlag(FileLineTypes.CR)) - { - lineSeparator = "\r"; - } + string lineSeparator = Environment.NewLine; - return string.Join(lineSeparator, linesNew); + if (fileLineTypes.HasFlag(FileLineTypes.CRLF)) + { + lineSeparator = "\r\n"; } - catch (Exception ex) + else if (fileLineTypes.HasFlag(FileLineTypes.LF)) { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return value; + lineSeparator = "\n"; + } + else if (fileLineTypes.HasFlag(FileLineTypes.CR)) + { + lineSeparator = "\r"; } - } - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - /// - public override string Manipulate(string value) + return string.Join(lineSeparator, linesNew); + } + catch (Exception ex) { - var types = FileLineType.GetFileLineTypes(new MemoryStream(Encoding.UTF8.GetBytes(value))); + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return value; + } + } - var fileLineTypes = types.Select(f => f.Key).Aggregate((result, flag) => result | flag); + /// + /// Manipulates the specified text value. + /// + /// The value to manipulate. + /// A string containing the manipulated text. + /// + public override string Manipulate(string value) + { + var types = FileLineType.GetFileLineTypes(new MemoryStream(Encoding.UTF8.GetBytes(value))); - return Manipulate(value, StringComparison.Ordinal, fileLineTypes); - } + var fileLineTypes = types.Select(f => f.Key).Aggregate((result, flag) => result | flag); - /// - public override bool PreferSelectedText { get; set; } = false; + return Manipulate(value, StringComparison.Ordinal, fileLineTypes); + } - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return MethodName; - } + /// + public override bool PreferSelectedText { get; set; } = false; + + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return MethodName; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/IMethodName.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/IMethodName.cs index 3bac41a5..f54dbc0e 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/IMethodName.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/IMethodName.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -24,17 +24,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ #endregion -namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces +namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; + +/// +/// An interface with a text manipulation method name. +/// +public interface IMethodName { /// - /// An interface with a text manipulation method name. + /// Gets or sets the name of the method manipulating the text. /// - public interface IMethodName - { - /// - /// Gets or sets the name of the method manipulating the text. - /// - /// The name of the method manipulating the text. - string MethodName { get; set; } - } -} + /// The name of the method manipulating the text. + string MethodName { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextLinesManipulationCommand.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextLinesManipulationCommand.cs index 5f2837b8..2f7ad643 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextLinesManipulationCommand.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextLinesManipulationCommand.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,20 +26,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Collections.Generic; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces +namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; + +/// +/// An interface to manipulate text with classes implementing this interface. +/// +interface ITextLinesManipulationCommand: IMethodName { /// - /// An interface to manipulate text with classes implementing this interface. + /// Manipulates the specified text value. /// - interface ITextLinesManipulationCommand: IMethodName - { - /// - /// Manipulates the specified text value. - /// - /// The lines to manipulate. - /// The encoding used in the - /// A string containing the manipulated text. - /// The may contain line separator character(s). - string Manipulate(IList lines, Encoding textEncoding); - } -} + /// The lines to manipulate. + /// The encoding used in the + /// A string containing the manipulated text. + /// The may contain line separator character(s). + string Manipulate(IList lines, Encoding textEncoding); +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCallback.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCallback.cs index af9eedad..c2731897 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCallback.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCallback.cs @@ -1,11 +1,10 @@ -namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces +namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; + +interface ITextManipulationCallback: IMethodName { - interface ITextManipulationCallback: IMethodName - { - /// - /// Gets or sets the callback action. - /// - /// The callback action. - Action CallbackAction { get; set; } - } -} + /// + /// Gets or sets the callback action. + /// + /// The callback action. + Action CallbackAction { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCommand.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCommand.cs index f63e7636..a813c0b0 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCommand.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Interfaces/ITextManipulationCommand.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,24 +26,23 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces +namespace ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; + +/// +/// An interface to manipulate text with classes implementing this interface. +/// +public interface ITextManipulationCommand: IMethodName { /// - /// An interface to manipulate text with classes implementing this interface. + /// Manipulates the specified text value. + /// + /// The value to manipulate. + /// A string containing the manipulated text. + string Manipulate(string value); + + /// + /// Gets or sets a value indicating whether prefer selected text of the control for the command. /// - public interface ITextManipulationCommand: IMethodName - { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - string Manipulate(string value); - - /// - /// Gets or sets a value indicating whether prefer selected text of the control for the command. - /// - /// true if to prefer selected text of the control for the command; otherwise, false. - bool PreferSelectedText { get; set; } - } -} + /// true if to prefer selected text of the control for the command; otherwise, false. + bool PreferSelectedText { get; set; } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonMultilineConvert.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonMultilineConvert.cs index 1cb9b6f2..e2a26d36 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonMultilineConvert.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonMultilineConvert.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,45 +28,44 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Json +namespace ScriptNotepad.UtilityClasses.TextManipulation.Json; + +/// +/// A class to convert single-line JSON to formatted JSON. +/// Implements the +/// +/// +public class JsonMultilineConvert: TextManipulationCommandBase { /// - /// A class to convert single-line JSON to formatted JSON. - /// Implements the + /// Manipulates the specified text value. /// - /// - public class JsonMultilineConvert: TextManipulationCommandBase + /// The value to manipulate. + /// A string containing the manipulated text. + public override string Manipulate(string value) { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public override string Manipulate(string value) + try { - try - { - var result = JToken.Parse(value).ToString(); + var result = JToken.Parse(value).ToString(); - return result; - } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return value; - } + return result; } - - /// - public override bool PreferSelectedText { get; set; } = false; - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() + catch (Exception ex) { - return MethodName; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return value; } } -} + + /// + public override bool PreferSelectedText { get; set; } = false; + + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return MethodName; + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonSingleLineConvert.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonSingleLineConvert.cs index 0f42e54b..466c05dd 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonSingleLineConvert.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Json/JsonSingleLineConvert.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -30,45 +30,44 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; using ScriptNotepad.UtilityClasses.TextManipulation.Interfaces; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Json +namespace ScriptNotepad.UtilityClasses.TextManipulation.Json; + +/// +/// A class to convert formatted JSON to a single-line JSOn. +/// Implements the +/// +/// +public class JsonSingleLineConvert: TextManipulationCommandBase { /// - /// A class to convert formatted JSON to a single-line JSOn. - /// Implements the + /// Manipulates the specified text value. /// - /// - public class JsonSingleLineConvert: TextManipulationCommandBase + /// The value to manipulate. + /// A string containing the manipulated text. + public override string Manipulate(string value) { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public override string Manipulate(string value) + try { - try - { - var result = JToken.Parse(value).ToString(Formatting.None); + var result = JToken.Parse(value).ToString(Formatting.None); - return result; - } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return value; - } + return result; } - - /// - public override bool PreferSelectedText { get; set; } = false; - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() + catch (Exception ex) { - return MethodName; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return value; } } -} + + /// + public override bool PreferSelectedText { get; set; } = false; + + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return MethodName; + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/JsonPrettify.cs b/ScriptNotepad/UtilityClasses/TextManipulation/JsonPrettify.cs index 8074ec33..d8a7a7c8 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/JsonPrettify.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/JsonPrettify.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,35 +26,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.Json; -namespace ScriptNotepad.UtilityClasses.TextManipulation +namespace ScriptNotepad.UtilityClasses.TextManipulation; + +/// +/// A class for Json text utilities. +/// +public static class JsonUtils { + private static readonly JsonMultilineConvert JsonMultilineConvert = new(); + + private static readonly JsonSingleLineConvert JsonSingleLineConvert = new(); + + /// + /// Prettifies a specified Json text. + /// + /// The value to prettify. + /// Intended Json text. + public static string JsonPrettify(this string value) + { + return JsonMultilineConvert.Manipulate(value); + } + /// - /// A class for Json text utilities. + /// Uglifies a specified Json text (he-hee). /// - public static class JsonUtils + /// The value. + /// System.String. + public static string JsonUglify(this string value) { - private static readonly JsonMultilineConvert JsonMultilineConvert = new(); - - private static readonly JsonSingleLineConvert JsonSingleLineConvert = new(); - - /// - /// Prettifies a specified Json text. - /// - /// The value to prettify. - /// Intended Json text. - public static string JsonPrettify(this string value) - { - return JsonMultilineConvert.Manipulate(value); - } - - /// - /// Uglifies a specified Json text (he-hee). - /// - /// The value. - /// System.String. - public static string JsonUglify(this string value) - { - return JsonSingleLineConvert.Manipulate(value); - } + return JsonSingleLineConvert.Manipulate(value); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/ScintillaLinesToStringList.cs b/ScriptNotepad/UtilityClasses/TextManipulation/ScintillaLinesToStringList.cs index cb12436f..96ea3959 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/ScintillaLinesToStringList.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/ScintillaLinesToStringList.cs @@ -28,36 +28,35 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScintillaNET; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.TextManipulation +namespace ScriptNotepad.UtilityClasses.TextManipulation; + +/// +/// A class to convert the collection to a list of strings. +/// Implements the +/// +/// +public class ScintillaLinesToStringList : ErrorHandlingBase { /// - /// A class to convert the collection to a list of strings. - /// Implements the + /// Gets the scintilla lines as string list. /// - /// - public class ScintillaLinesToStringList : ErrorHandlingBase + /// The class instance to get the lines from. + /// A collection containing the control's lines. + public static List GetScintillaLinesAsStringList(Scintilla scintilla) { - /// - /// Gets the scintilla lines as string list. - /// - /// The class instance to get the lines from. - /// A collection containing the control's lines. - public static List GetScintillaLinesAsStringList(Scintilla scintilla) + List result = new List(); + try { - List result = new List(); - try - { - foreach (var line in scintilla.Lines) - { - result.Add(line.Text); - } - } - catch (Exception ex) + foreach (var line in scintilla.Lines) { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); + result.Add(line.Text); } - return result; } + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + } + return result; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/StringHelpers.cs b/ScriptNotepad/UtilityClasses/TextManipulation/StringHelpers.cs index a4f0a416..c9b484fb 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/StringHelpers.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/StringHelpers.cs @@ -26,105 +26,104 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Globalization; -namespace ScriptNotepad.UtilityClasses.TextManipulation +namespace ScriptNotepad.UtilityClasses.TextManipulation; + +/// +/// Some helper methods for strings. +/// +public static class StringHelpers { /// - /// Some helper methods for strings. + /// Returns a copy of this object converted to style based on using the casing rules of the culture determined from the . /// - public static class StringHelpers + /// The string to convert. + /// The comparison to detect the string conversion from. + /// The string equivalent to the style based on using the casing rules of the culture determined from the of the current string. + public static string ToComparisonVariant(this string str, StringComparison comparison) { - /// - /// Returns a copy of this object converted to style based on using the casing rules of the culture determined from the . - /// - /// The string to convert. - /// The comparison to detect the string conversion from. - /// The string equivalent to the style based on using the casing rules of the culture determined from the of the current string. - public static string ToComparisonVariant(this string str, StringComparison comparison) + switch (comparison) { - switch (comparison) - { - case StringComparison.CurrentCulture: - return str.ToString(CultureInfo.CurrentCulture); - - case StringComparison.CurrentCultureIgnoreCase: - return str.ToLower(CultureInfo.CurrentCulture); + case StringComparison.CurrentCulture: + return str.ToString(CultureInfo.CurrentCulture); - case StringComparison.InvariantCulture: - return str.ToString(CultureInfo.InvariantCulture); + case StringComparison.CurrentCultureIgnoreCase: + return str.ToLower(CultureInfo.CurrentCulture); - case StringComparison.InvariantCultureIgnoreCase: - return str.ToLowerInvariant(); + case StringComparison.InvariantCulture: + return str.ToString(CultureInfo.InvariantCulture); - case StringComparison.Ordinal: - return str; + case StringComparison.InvariantCultureIgnoreCase: + return str.ToLowerInvariant(); - case StringComparison.OrdinalIgnoreCase: - return str.ToLower(); - } + case StringComparison.Ordinal: + return str; - return str; + case StringComparison.OrdinalIgnoreCase: + return str.ToLower(); } - /// - /// Reverses the specified string. - /// - /// The string to reverse. - /// A string reversed character by character compared to the original string. - public static string Reverse(this string str) + return str; + } + + /// + /// Reverses the specified string. + /// + /// The string to reverse. + /// A string reversed character by character compared to the original string. + public static string Reverse(this string str) + { + var result = string.Empty; + for (int i = str.Length - 1; i >= 0; i--) { - var result = string.Empty; - for (int i = str.Length - 1; i >= 0; i--) - { - result += str[i]; - } + result += str[i]; + } + return result; + } + + /// + /// Retrieves a substring from this instance. + /// The substring starts at a specified character position and continues to the end or to the start of the string + /// depending on the sign of the index. + /// + /// The string. + /// The zero-based starting or ending character position of a substring in this instance. + /// A string that is equivalent to the substring that begins at or ends to the in this instance, or if is equal to the length of this instance or in case of an invalid index. + public static string SafeSubString(this string str, int startIndex) + { + try + { + var result = startIndex >= 0 ? + str.Substring(startIndex) : + str.Substring(str.Length + startIndex); return result; } - - /// - /// Retrieves a substring from this instance. - /// The substring starts at a specified character position and continues to the end or to the start of the string - /// depending on the sign of the index. - /// - /// The string. - /// The zero-based starting or ending character position of a substring in this instance. - /// A string that is equivalent to the substring that begins at or ends to the in this instance, or if is equal to the length of this instance or in case of an invalid index. - public static string SafeSubString(this string str, int startIndex) + catch { - try - { - var result = startIndex >= 0 ? - str.Substring(startIndex) : - str.Substring(str.Length + startIndex); - return result; - } - catch - { - return string.Empty; - } + return string.Empty; } + } - /// - /// Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length. - /// If the length is specified as negative the the length is decreased from the specified character position. - /// - /// The string. - /// The zero-based starting character position of a substring in this instance. - /// The number of characters in the substring. Also negative lengths is allowed and the start index is the decremented by the length. - /// A string that is equivalent to the substring of length that begins at in this instance or at at decremented by a given negative length , or if is equal to the length of this instance and is zero. - public static string SafeSubString(this string str, int startIndex, int length) + /// + /// Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length. + /// If the length is specified as negative the the length is decreased from the specified character position. + /// + /// The string. + /// The zero-based starting character position of a substring in this instance. + /// The number of characters in the substring. Also negative lengths is allowed and the start index is the decremented by the length. + /// A string that is equivalent to the substring of length that begins at in this instance or at at decremented by a given negative length , or if is equal to the length of this instance and is zero. + public static string SafeSubString(this string str, int startIndex, int length) + { + try + { + var result = length >= 0 ? + str.Substring(startIndex, length) : + str.Substring(startIndex + length, -length); + return result; + } + catch { - try - { - var result = length >= 0 ? - str.Substring(startIndex, length) : - str.Substring(startIndex + length, -length); - return result; - } - catch - { - return string.Empty; - } + return string.Empty; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/FormDialogQuerySortTextStyle.cs b/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/FormDialogQuerySortTextStyle.cs index dedea83e..01620c64 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/FormDialogQuerySortTextStyle.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/FormDialogQuerySortTextStyle.cs @@ -37,546 +37,545 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using VPKSoft.LangLib; -namespace ScriptNotepad.UtilityClasses.TextManipulation.TextSorting +namespace ScriptNotepad.UtilityClasses.TextManipulation.TextSorting; + +/// +/// A dialog to query advanced text sorting parameters. +/// Implements the +/// +/// +public partial class FormDialogQuerySortTextStyle : DBLangEngineWinforms { /// - /// A dialog to query advanced text sorting parameters. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public partial class FormDialogQuerySortTextStyle : DBLangEngineWinforms + public FormDialogQuerySortTextStyle() { - /// - /// Initializes a new instance of the class. - /// - public FormDialogQuerySortTextStyle() - { - InitializeComponent(); + InitializeComponent(); - DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. + DBLangEngine.DBName = "lang.sqlite"; // Do the VPKSoft.LangLib == translation.. - if (Utils.ShouldLocalize() != null) - { - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); - return; // After localization don't do anything more.. - } + if (Utils.ShouldLocalize() != null) + { + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages", Utils.ShouldLocalize(), false); + return; // After localization don't do anything more.. + } - // initialize the language/localization database.. - DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); + // initialize the language/localization database.. + DBLangEngine.InitializeLanguage("ScriptNotepad.Localization.Messages"); - ListSortStyles(); + ListSortStyles(); - btSort.Enabled = listCheckSortStyles.Items.Count > 0; + btSort.Enabled = listCheckSortStyles.Items.Count > 0; - #region NoDesignerVisibility - pictureBox1.AllowDrop = true; - pictureBox2.AllowDrop = true; - #endregion + #region NoDesignerVisibility + pictureBox1.AllowDrop = true; + pictureBox2.AllowDrop = true; + #endregion - var savedRegexs = ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Where(f => - f.TextType == MiscellaneousTextType.RegexSorting && - f.Session.Id == FormSettings.Settings.CurrentSessionEntity.Id).OrderBy(f => f.Added); + var savedRegexs = ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Where(f => + f.TextType == MiscellaneousTextType.RegexSorting && + f.Session.Id == FormSettings.Settings.CurrentSessionEntity.Id).OrderBy(f => f.Added); - foreach (var savedRegex in savedRegexs) - { - tbRegex.Items.Add(savedRegex.TextValue); - } + foreach (var savedRegex in savedRegexs) + { + tbRegex.Items.Add(savedRegex.TextValue); } + } - #region PrivateMethods - /// - /// Undo the document changes if possible. - /// - private void Undo() + #region PrivateMethods + /// + /// Undo the document changes if possible. + /// + private void Undo() + { + if (Scintilla.CanUndo) { - if (Scintilla.CanUndo) - { - FormMain.Undo(); - } + FormMain.Undo(); + } + + btUndo.Enabled = Scintilla.CanUndo; + } - btUndo.Enabled = Scintilla.CanUndo; + /// + /// Lists the current text sorting "styles". + /// + private void ListSortStyles() + { + foreach (var value in Enum.GetValues(typeof(SortTextStyle))) + { + listSortStylesAvailable.Items.Add(new SortText((SortTextStyle) value)); } + } - /// - /// Lists the current text sorting "styles". - /// - private void ListSortStyles() + /// + /// Checks if a give style exists in the check list box. + /// + /// An instance to a class to check for. + /// true if the given style exists in the check list box, false otherwise. + private bool SortStyleExists(SortText sortText) + { + foreach (var item in listCheckSortStyles.Items) { - foreach (var value in Enum.GetValues(typeof(SortTextStyle))) + var itemData = (SortText) item; + if (itemData == sortText) { - listSortStylesAvailable.Items.Add(new SortText((SortTextStyle) value)); + return true; } } - /// - /// Checks if a give style exists in the check list box. - /// - /// An instance to a class to check for. - /// true if the given style exists in the check list box, false otherwise. - private bool SortStyleExists(SortText sortText) + return false; + } + + /// + /// Checks if a is valid to be dropped to the check list box. + /// + /// A that contains the event data. + /// true if the is valid to be dropped to the check list box, false otherwise. + private bool CheckListCanDrop(DragEventArgs e) + { + var data = (SortText) e.Data.GetData(typeof(SortText)); + + if (DragDropOrigin != null && DragDropOrigin.Equals(listCheckSortStyles)) { - foreach (var item in listCheckSortStyles.Items) + var checkListBox = listCheckSortStyles; + int index = checkListBox.IndexFromPoint(checkListBox.PointToClient(new Point(e.X, e.Y))); + if (checkListBox.Items.IndexOf(data) == index) { - var itemData = (SortText) item; - if (itemData == sortText) - { - return true; - } + return false; } - - return false; + return true; } - /// - /// Checks if a is valid to be dropped to the check list box. - /// - /// A that contains the event data. - /// true if the is valid to be dropped to the check list box, false otherwise. - private bool CheckListCanDrop(DragEventArgs e) + if (e.Data.GetDataPresent(typeof(SortText))) { - var data = (SortText) e.Data.GetData(typeof(SortText)); - - if (DragDropOrigin != null && DragDropOrigin.Equals(listCheckSortStyles)) + if (!e.Data.GetDataPresent(typeof(SortText))) { - var checkListBox = listCheckSortStyles; - int index = checkListBox.IndexFromPoint(checkListBox.PointToClient(new Point(e.X, e.Y))); - if (checkListBox.Items.IndexOf(data) == index) - { - return false; - } - return true; + return false; } - if (e.Data.GetDataPresent(typeof(SortText))) + if (SortStyleExists(data)) { - if (!e.Data.GetDataPresent(typeof(SortText))) - { - return false; - } + return false; - if (SortStyleExists(data)) - { - return false; - - } } - - return true; } - private void SaveRegex(string regex) - { - if (!ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Any(f => + return true; + } + + private void SaveRegex(string regex) + { + if (!ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Any(f => f.TextType == MiscellaneousTextType.RegexSorting && f.Session.Id == FormSettings.Settings.CurrentSessionEntity.Id && f.TextValue == regex)) + { + ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Add(new MiscellaneousTextEntry { - ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Add(new MiscellaneousTextEntry - { - TextType = MiscellaneousTextType.RegexSorting, - Session = FormSettings.Settings.CurrentSessionEntity, - TextValue = regex, - }); - ScriptNotepadDbContext.DbContext.SaveChanges(); - } + TextType = MiscellaneousTextType.RegexSorting, + Session = FormSettings.Settings.CurrentSessionEntity, + TextValue = regex, + }); + ScriptNotepadDbContext.DbContext.SaveChanges(); } + } - /// - /// Moves an available sorting item to the check list box of sorting styles to use. - /// - private void MoveToSortCheckListBox() + /// + /// Moves an available sorting item to the check list box of sorting styles to use. + /// + private void MoveToSortCheckListBox() + { + if (listSortStylesAvailable.SelectedItem == null) { - if (listSortStylesAvailable.SelectedItem == null) - { - return; - } + return; + } - var sortText = (SortText)listSortStylesAvailable.SelectedItem; + var sortText = (SortText)listSortStylesAvailable.SelectedItem; - if (sortText.SortTextStyle == SortTextStyle.SubString) + if (sortText.SortTextStyle == SortTextStyle.SubString) + { + sortText = new SortText(sortText.SortTextStyle, sortText.Descending) { - sortText = new SortText(sortText.SortTextStyle, sortText.Descending) - { - ExtraData1 = (int)nudSubStringRange1.Value, ExtraData2 = (int)nudSubStringRange2.Value, - }; - } + ExtraData1 = (int)nudSubStringRange1.Value, ExtraData2 = (int)nudSubStringRange2.Value, + }; + } - if (sortText.SortTextStyle == SortTextStyle.Regex) + if (sortText.SortTextStyle == SortTextStyle.Regex) + { + sortText = new SortText(sortText.SortTextStyle, sortText.Descending) { - sortText = new SortText(sortText.SortTextStyle, sortText.Descending) - { - ExtraData1 = tbRegex.Text, - }; - - if (!sortText.IsValidRegex) - { - return; - } - - SaveRegex(tbRegex.Text); - } + ExtraData1 = tbRegex.Text, + }; - if (SortStyleExists(sortText)) + if (!sortText.IsValidRegex) { return; } - if (listCheckSortStyles.SelectedIndex != -1) - { - listCheckSortStyles.Items.Insert(listCheckSortStyles.SelectedIndex, sortText); - } - else - { - listCheckSortStyles.Items.Add(sortText); - } - btSort.Enabled = listCheckSortStyles.Items.Count > 0; + SaveRegex(tbRegex.Text); } - #endregion - #region EventHandlers - private void listCheckSortStyles_ItemCheck(object sender, ItemCheckEventArgs e) + if (SortStyleExists(sortText)) { - var checkListBox = (CheckedListBox) sender; - var sortText = (SortText) checkListBox.Items[e.Index]; - sortText.Descending = e.NewValue == CheckState.Checked; + return; } - private void listSortStylesAvailable_MouseDown(object sender, MouseEventArgs e) + if (listCheckSortStyles.SelectedIndex != -1) { - StartDragAvailableListBox = true; - MouseDownPointAvailableListBox = e.Location; + listCheckSortStyles.Items.Insert(listCheckSortStyles.SelectedIndex, sortText); } - - private void listCheckSortStyles_MouseDown(object sender, MouseEventArgs e) - { - StartDragCheckListBox = true; - StartDragAvailableListBox = false; - MouseDownPointCheckListBox = e.Location; - } - - private void FormDialogQuerySortTextStyle_MouseUp(object sender, MouseEventArgs e) + else { - DragDropOrigin = null; - StartDragCheckListBox = false; - StartDragAvailableListBox = false; + listCheckSortStyles.Items.Add(sortText); } + btSort.Enabled = listCheckSortStyles.Items.Count > 0; + } + #endregion - private void listCheckSortStyles_DragEnterOver(object sender, DragEventArgs e) - { - e.Effect = CheckListCanDrop(e) ? DragDropEffects.Copy : DragDropEffects.None; - } + #region EventHandlers + private void listCheckSortStyles_ItemCheck(object sender, ItemCheckEventArgs e) + { + var checkListBox = (CheckedListBox) sender; + var sortText = (SortText) checkListBox.Items[e.Index]; + sortText.Descending = e.NewValue == CheckState.Checked; + } - private void FormDialogQuerySortTextStyle_DragEnterOver(object sender, DragEventArgs e) - { - e.Effect = DragDropEffects.Move; - } + private void listSortStylesAvailable_MouseDown(object sender, MouseEventArgs e) + { + StartDragAvailableListBox = true; + MouseDownPointAvailableListBox = e.Location; + } - private void listCheckSortStyles_DragDrop(object sender, DragEventArgs e) - { - var checkListBox = (CheckedListBox) sender; - int index = checkListBox.IndexFromPoint(checkListBox.PointToClient(new Point(e.X, e.Y))); - if (CheckListCanDrop(e)) - { - var sortText = (SortText) e.Data.GetData(typeof(SortText)); + private void listCheckSortStyles_MouseDown(object sender, MouseEventArgs e) + { + StartDragCheckListBox = true; + StartDragAvailableListBox = false; + MouseDownPointCheckListBox = e.Location; + } - if (checkListBox.Equals(DragDropOrigin)) - { - checkListBox.Items.Remove(sortText); - } + private void FormDialogQuerySortTextStyle_MouseUp(object sender, MouseEventArgs e) + { + DragDropOrigin = null; + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } - if (index != -1) - { - checkListBox.Items.Insert(index, sortText); - } - else - { - checkListBox.Items.Add(sortText); - } - btSort.Enabled = listCheckSortStyles.Items.Count > 0; - } + private void listCheckSortStyles_DragEnterOver(object sender, DragEventArgs e) + { + e.Effect = CheckListCanDrop(e) ? DragDropEffects.Copy : DragDropEffects.None; + } - DragDropOrigin = null; - StartDragCheckListBox = false; - StartDragAvailableListBox = false; - } + private void FormDialogQuerySortTextStyle_DragEnterOver(object sender, DragEventArgs e) + { + e.Effect = DragDropEffects.Move; + } - private void FormDialogQuerySortTextStyle_DragDrop(object sender, DragEventArgs e) + private void listCheckSortStyles_DragDrop(object sender, DragEventArgs e) + { + var checkListBox = (CheckedListBox) sender; + int index = checkListBox.IndexFromPoint(checkListBox.PointToClient(new Point(e.X, e.Y))); + if (CheckListCanDrop(e)) { - if (listCheckSortStyles.Equals(DragDropOrigin)) + var sortText = (SortText) e.Data.GetData(typeof(SortText)); + + if (checkListBox.Equals(DragDropOrigin)) + { + checkListBox.Items.Remove(sortText); + } + + if (index != -1) + { + checkListBox.Items.Insert(index, sortText); + } + else { - var data = (SortText) e.Data.GetData(typeof(SortText)); - listCheckSortStyles.Items.Remove(data); + checkListBox.Items.Add(sortText); } + btSort.Enabled = listCheckSortStyles.Items.Count > 0; + } - DragDropOrigin = null; - StartDragCheckListBox = false; - StartDragAvailableListBox = false; + DragDropOrigin = null; + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } + + private void FormDialogQuerySortTextStyle_DragDrop(object sender, DragEventArgs e) + { + if (listCheckSortStyles.Equals(DragDropOrigin)) + { + var data = (SortText) e.Data.GetData(typeof(SortText)); + listCheckSortStyles.Items.Remove(data); } - private void listCheckSortStyles_Leave(object sender, EventArgs e) + DragDropOrigin = null; + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } + + private void listCheckSortStyles_Leave(object sender, EventArgs e) + { + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } + + private void listCheckSortStyles_MouseMove(object sender, MouseEventArgs e) + { + if (!StartDragCheckListBox || MouseDownPointCheckListBox.X == e.X && MouseDownPointCheckListBox.Y == e.Y) { - StartDragCheckListBox = false; - StartDragAvailableListBox = false; + return; } - private void listCheckSortStyles_MouseMove(object sender, MouseEventArgs e) + var checkListBox = (CheckedListBox) sender; + int index = checkListBox.IndexFromPoint(new Point(e.X, e.Y)); + if (index != -1 && checkListBox.Items.Count > 0) { - if (!StartDragCheckListBox || MouseDownPointCheckListBox.X == e.X && MouseDownPointCheckListBox.Y == e.Y) - { - return; - } + DragDropOrigin = checkListBox; + checkListBox.DoDragDrop(checkListBox.Items[index], DragDropEffects.All); + } + } - var checkListBox = (CheckedListBox) sender; - int index = checkListBox.IndexFromPoint(new Point(e.X, e.Y)); - if (index != -1 && checkListBox.Items.Count > 0) - { - DragDropOrigin = checkListBox; - checkListBox.DoDragDrop(checkListBox.Items[index], DragDropEffects.All); - } + private void listSortStylesAvailable_MouseMove(object sender, MouseEventArgs e) + { + if (!StartDragAvailableListBox || MouseDownPointAvailableListBox.X == e.X && MouseDownPointAvailableListBox.Y == e.Y) + { + return; } - private void listSortStylesAvailable_MouseMove(object sender, MouseEventArgs e) + var listBox = (ListBox) sender; + int index = listBox.IndexFromPoint(new Point(e.X, e.Y)); + if (index != -1) { - if (!StartDragAvailableListBox || MouseDownPointAvailableListBox.X == e.X && MouseDownPointAvailableListBox.Y == e.Y) + DragDropOrigin = listBox; + + var item = (SortText)listBox.Items[index]; + + if (item.SortTextStyle == SortTextStyle.SubString) { - return; + item = new SortText(item.SortTextStyle, item.Descending) + {ExtraData1 = (int)nudSubStringRange1.Value, ExtraData2 = (int)nudSubStringRange2.Value, }; } - - var listBox = (ListBox) sender; - int index = listBox.IndexFromPoint(new Point(e.X, e.Y)); - if (index != -1) + else if (item.SortTextStyle == SortTextStyle.Regex) { - DragDropOrigin = listBox; + item = new SortText(item.SortTextStyle, item.Descending) + {ExtraData1 = tbRegex.Text, }; - var item = (SortText)listBox.Items[index]; - - if (item.SortTextStyle == SortTextStyle.SubString) - { - item = new SortText(item.SortTextStyle, item.Descending) - {ExtraData1 = (int)nudSubStringRange1.Value, ExtraData2 = (int)nudSubStringRange2.Value}; - } - else if (item.SortTextStyle == SortTextStyle.Regex) + if (!item.IsValidRegex) { - item = new SortText(item.SortTextStyle, item.Descending) - {ExtraData1 = tbRegex.Text}; - - if (!item.IsValidRegex) - { - return; - } - - SaveRegex(tbRegex.Text); + return; } - listBox.DoDragDrop(item, DragDropEffects.Copy); + SaveRegex(tbRegex.Text); } + + listBox.DoDragDrop(item, DragDropEffects.Copy); } + } - private void btSort_Click(object sender, EventArgs e) + private void btSort_Click(object sender, EventArgs e) + { + foreach (var item in listCheckSortStyles.Items) { - foreach (var item in listCheckSortStyles.Items) - { - var itemData = (SortText) item; - SortLines.Sort(Scintilla, itemData, FormSettings.Settings.TextCurrentComparison); - } - - btUndo.Enabled = Scintilla.CanUndo; - StartDragCheckListBox = false; - StartDragAvailableListBox = false; + var itemData = (SortText) item; + SortLines.Sort(Scintilla, itemData, FormSettings.Settings.TextCurrentComparison); } - private void btUndo_Click(object sender, EventArgs e) + btUndo.Enabled = Scintilla.CanUndo; + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } + + private void btUndo_Click(object sender, EventArgs e) + { + Undo(); + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } + + private void FormDialogQuerySortTextStyle_KeyDown(object sender, KeyEventArgs e) + { + if (e.ModifierKeysDown(false, true, false) && e.KeyCode == Keys.Z) { Undo(); - StartDragCheckListBox = false; - StartDragAvailableListBox = false; + e.SuppressKeyPress = true; } + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } - private void FormDialogQuerySortTextStyle_KeyDown(object sender, KeyEventArgs e) - { - if (e.ModifierKeysDown(false, true, false) && e.KeyCode == Keys.Z) - { - Undo(); - e.SuppressKeyPress = true; - } - StartDragCheckListBox = false; - StartDragAvailableListBox = false; - } + private void listSortStylesAvailable_DoubleClick(object sender, EventArgs e) + { + MoveToSortCheckListBox(); + } - private void listSortStylesAvailable_DoubleClick(object sender, EventArgs e) + + private void listSortStylesAvailable_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Space && e.NoModifierKeysDown()) { + e.SuppressKeyPress = true; MoveToSortCheckListBox(); } + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } - - private void listSortStylesAvailable_KeyDown(object sender, KeyEventArgs e) + private void listCheckSortStyles_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Delete && e.NoModifierKeysDown()) { - if (e.KeyCode == Keys.Space && e.NoModifierKeysDown()) + e.SuppressKeyPress = true; + if (listCheckSortStyles.SelectedItem != null) { - e.SuppressKeyPress = true; - MoveToSortCheckListBox(); + listCheckSortStyles.Items.Remove(listCheckSortStyles.SelectedItem); } - StartDragCheckListBox = false; - StartDragAvailableListBox = false; } + StartDragCheckListBox = false; + StartDragAvailableListBox = false; + } - private void listCheckSortStyles_KeyDown(object sender, KeyEventArgs e) + private void listSortStylesAvailable_SelectedValueChanged(object sender, EventArgs e) + { + var listBox = (ListBox) sender; + var textStyle = (SortText)listBox.SelectedItem; + if (textStyle.SortTextStyle == SortTextStyle.SubString) { - if (e.KeyCode == Keys.Delete && e.NoModifierKeysDown()) - { - e.SuppressKeyPress = true; - if (listCheckSortStyles.SelectedItem != null) - { - listCheckSortStyles.Items.Remove(listCheckSortStyles.SelectedItem); - } - } - StartDragCheckListBox = false; - StartDragAvailableListBox = false; + tlpSubStringRange.Visible = true; + tlpRegex.Visible = false; + tlpMain.SetCellPosition(tlpSubStringRange, new TableLayoutPanelCellPosition(0, 3)); + tlpMain.SetCellPosition(tlpRegex, new TableLayoutPanelCellPosition(0, 4)); } - - private void listSortStylesAvailable_SelectedValueChanged(object sender, EventArgs e) + else if (textStyle.SortTextStyle == SortTextStyle.Regex) { - var listBox = (ListBox) sender; - var textStyle = (SortText)listBox.SelectedItem; - if (textStyle.SortTextStyle == SortTextStyle.SubString) - { - tlpSubStringRange.Visible = true; - tlpRegex.Visible = false; - tlpMain.SetCellPosition(tlpSubStringRange, new TableLayoutPanelCellPosition(0, 3)); - tlpMain.SetCellPosition(tlpRegex, new TableLayoutPanelCellPosition(0, 4)); - } - else if (textStyle.SortTextStyle == SortTextStyle.Regex) - { - tlpSubStringRange.Visible = false; - tlpRegex.Visible = true; - tlpMain.SetCellPosition(tlpSubStringRange, new TableLayoutPanelCellPosition(0, 4)); - tlpMain.SetCellPosition(tlpRegex, new TableLayoutPanelCellPosition(0, 3)); - } - else - { - tlpSubStringRange.Visible = false; - tlpRegex.Visible = false; - } - - tlpSubStringRange.Visible = textStyle.SortTextStyle == SortTextStyle.SubString; + tlpSubStringRange.Visible = false; + tlpRegex.Visible = true; + tlpMain.SetCellPosition(tlpSubStringRange, new TableLayoutPanelCellPosition(0, 4)); + tlpMain.SetCellPosition(tlpRegex, new TableLayoutPanelCellPosition(0, 3)); + } + else + { + tlpSubStringRange.Visible = false; + tlpRegex.Visible = false; } - private void nudSubStringRange2_ValueChanged(object sender, EventArgs e) + tlpSubStringRange.Visible = textStyle.SortTextStyle == SortTextStyle.SubString; + } + + private void nudSubStringRange2_ValueChanged(object sender, EventArgs e) + { + var textStyle = (SortText)listCheckSortStyles.SelectedItem; + if (textStyle != null) { - var textStyle = (SortText)listCheckSortStyles.SelectedItem; - if (textStyle != null) - { - textStyle.ExtraData1 = (int)nudSubStringRange1.Value; - textStyle.ExtraData2 = (int)nudSubStringRange2.Value; - listCheckSortStyles.RefreshItems(); - } + textStyle.ExtraData1 = (int)nudSubStringRange1.Value; + textStyle.ExtraData2 = (int)nudSubStringRange2.Value; + listCheckSortStyles.RefreshItems(); } - #endregion + } + #endregion - #region PrivateProperties - private object DragDropOrigin { get; set; } + #region PrivateProperties + private object DragDropOrigin { get; set; } - private bool StartDragCheckListBox { get; set; } + private bool StartDragCheckListBox { get; set; } - private Point MouseDownPointCheckListBox { get; set; } + private Point MouseDownPointCheckListBox { get; set; } - private bool StartDragAvailableListBox { get; set; } + private bool StartDragAvailableListBox { get; set; } - private Point MouseDownPointAvailableListBox { get; set; } + private Point MouseDownPointAvailableListBox { get; set; } - private Scintilla Scintilla { get; set; } + private Scintilla Scintilla { get; set; } - private FormMain FormMain { get; set; } - #endregion + private FormMain FormMain { get; set; } + #endregion - #region PublicMethods - /// - /// Shows the form as a modal dialog box. - /// - /// The scintilla control which contents to sort. - /// An instance to the Form for an undo operation call. - /// One of the values. - /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). - // ReSharper disable once UnusedMember.Global - public static DialogResult ShowDialog(Scintilla scintilla, FormMain formMain) - { - return ShowDialog(null, scintilla, formMain, 1, 1); - } + #region PublicMethods + /// + /// Shows the form as a modal dialog box. + /// + /// The scintilla control which contents to sort. + /// An instance to the Form for an undo operation call. + /// One of the values. + /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). + // ReSharper disable once UnusedMember.Global + public static DialogResult ShowDialog(Scintilla scintilla, FormMain formMain) + { + return ShowDialog(null, scintilla, formMain, 1, 1); + } - /// - /// Shows the form as a modal dialog box with the specified owner. - /// - /// Any object that implements that represents the top-level window that will own the modal dialog box. - /// The scintilla control which contents to sort. - /// An instance to the Form for an undo operation call. - /// One of the values. - /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). - public static DialogResult ShowDialog(IWin32Window owner, Scintilla scintilla, FormMain formMain) - { - return ShowDialog(owner, scintilla, formMain, 1, 1); - } + /// + /// Shows the form as a modal dialog box with the specified owner. + /// + /// Any object that implements that represents the top-level window that will own the modal dialog box. + /// The scintilla control which contents to sort. + /// An instance to the Form for an undo operation call. + /// One of the values. + /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). + public static DialogResult ShowDialog(IWin32Window owner, Scintilla scintilla, FormMain formMain) + { + return ShowDialog(owner, scintilla, formMain, 1, 1); + } - /// - /// Shows the form as a modal dialog box with the specified owner. - /// - /// Any object that implements that represents the top-level window that will own the modal dialog box. - /// The scintilla control which contents to sort. - /// An instance to the Form for an undo operation call. - /// A starting position of a possible one line selection within a document. - /// A length of a possible one line selection within a document. - /// One of the values. - /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). - public static DialogResult ShowDialog(IWin32Window owner, Scintilla scintilla, FormMain formMain, int stringStart, int stringLength) - { - var form = new FormDialogQuerySortTextStyle - { - Scintilla = scintilla, - btUndo = {Enabled = scintilla.CanUndo}, - FormMain = formMain, - nudSubStringRange1 = {Value = stringStart}, - nudSubStringRange2 = {Value = stringLength} - }; + /// + /// Shows the form as a modal dialog box with the specified owner. + /// + /// Any object that implements that represents the top-level window that will own the modal dialog box. + /// The scintilla control which contents to sort. + /// An instance to the Form for an undo operation call. + /// A starting position of a possible one line selection within a document. + /// A length of a possible one line selection within a document. + /// One of the values. + /// The form being shown is already visible.-or- The form being shown is disabled.-or- The form being shown is not a top-level window.-or- The form being shown as a dialog box is already a modal form.-or-The current process is not running in user interactive mode (for more information, see ). + public static DialogResult ShowDialog(IWin32Window owner, Scintilla scintilla, FormMain formMain, int stringStart, int stringLength) + { + var form = new FormDialogQuerySortTextStyle + { + Scintilla = scintilla, + btUndo = {Enabled = scintilla.CanUndo, }, + FormMain = formMain, + nudSubStringRange1 = {Value = stringStart, }, + nudSubStringRange2 = {Value = stringLength, }, + }; - return form.ShowDialog(owner); - } - #endregion + return form.ShowDialog(owner); + } + #endregion - private void tbRegex_TextChanged(object sender, EventArgs e) + private void tbRegex_TextChanged(object sender, EventArgs e) + { + var textStyle = (SortText)listCheckSortStyles.SelectedItem; + if (textStyle != null) { - var textStyle = (SortText)listCheckSortStyles.SelectedItem; - if (textStyle != null) - { - textStyle.ExtraData1 = tbRegex.Text; - listCheckSortStyles.RefreshItems(); - } + textStyle.ExtraData1 = tbRegex.Text; + listCheckSortStyles.RefreshItems(); } + } - private void lbRegex_Click(object sender, EventArgs e) + private void lbRegex_Click(object sender, EventArgs e) + { + try { - try - { - System.Diagnostics.Process.Start("https://regex101.com"); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogger.LogError(ex); - } + System.Diagnostics.Process.Start("https://regex101.com"); + } + catch (Exception ex) + { + // log the exception.. + ExceptionLogger.LogError(ex); } } +} +/// +/// A sub-class allowing the items within the list to be refreshed. +/// Implements the +/// +/// +internal class RefreshCheckListBox : CheckedListBox +{ /// - /// A sub-class allowing the items within the list to be refreshed. - /// Implements the + /// Parses all items again and gets new text strings for the items. /// - /// - internal class RefreshCheckListBox : CheckedListBox + public new void RefreshItems() { - /// - /// Parses all items again and gets new text strings for the items. - /// - public new void RefreshItems() - { - base.RefreshItems(); - } + base.RefreshItems(); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/SortLines.cs b/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/SortLines.cs index 1f0b2770..df251290 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/SortLines.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/TextSorting/SortLines.cs @@ -31,518 +31,517 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using VPKSoft.LangLib; -namespace ScriptNotepad.UtilityClasses.TextManipulation.TextSorting +namespace ScriptNotepad.UtilityClasses.TextManipulation.TextSorting; + +/// +/// A class for sorting lines within a control. +/// Implements the +/// +/// +public class SortLines: ErrorHandlingBase { /// - /// A class for sorting lines within a control. - /// Implements the + /// Gets or sets the default sort function for the Sort method. /// - /// - public class SortLines: ErrorHandlingBase - { - /// - /// Gets or sets the default sort function for the Sort method. - /// - public static Func, SortTextStyle, bool, IEnumerable> - DefaultSortFunc { get; set; } = - delegate(IEnumerable lines, SortTextStyle sortTextStyle, bool descending) - { - lines = - descending ? lines + public static Func, SortTextStyle, bool, IEnumerable> + DefaultSortFunc { get; set; } = + delegate(IEnumerable lines, SortTextStyle sortTextStyle, bool descending) + { + lines = + descending ? lines .OrderByDescending(f => f.ToComparisonVariant((StringComparison) sortTextStyle)) : lines .OrderBy(f => f.ToComparisonVariant((StringComparison) sortTextStyle)); - return lines; - }; - - /// - /// A method to sort the contents of a control. - /// - /// The scintilla control which contents to sort. - /// The type of string comparison to use with the sort. - /// A value indicating whether to sort in descending order. - public static void Sort(Scintilla scintilla, StringComparison stringComparison, bool descending) - { - Sort(scintilla, stringComparison, descending, DefaultSortFunc); - } + return lines; + }; - /// - /// A method to sort the contents of a control. - /// - /// The scintilla control which contents to sort. - /// The type of string comparison to use with the sort. - /// A value indicating whether to sort in descending order. - /// A Func to to do the actual string sorting. - /// Optional parameter array in case the sort method function requires parameters. - public static void Sort(Scintilla scintilla, StringComparison stringComparison, bool descending, - Func, SortTextStyle, bool, IEnumerable> sortFunc, params object[] funcParameters) + /// + /// A method to sort the contents of a control. + /// + /// The scintilla control which contents to sort. + /// The type of string comparison to use with the sort. + /// A value indicating whether to sort in descending order. + public static void Sort(Scintilla scintilla, StringComparison stringComparison, bool descending) + { + Sort(scintilla, stringComparison, descending, DefaultSortFunc); + } + + /// + /// A method to sort the contents of a control. + /// + /// The scintilla control which contents to sort. + /// The type of string comparison to use with the sort. + /// A value indicating whether to sort in descending order. + /// A Func to to do the actual string sorting. + /// Optional parameter array in case the sort method function requires parameters. + public static void Sort(Scintilla scintilla, StringComparison stringComparison, bool descending, + Func, SortTextStyle, bool, IEnumerable> sortFunc, params object[] funcParameters) + { + try { - try + // if text is selected, do the ordering with a bit more complex algorithm.. + if (scintilla.SelectedText.Length > 0) { - // if text is selected, do the ordering with a bit more complex algorithm.. - if (scintilla.SelectedText.Length > 0) - { - // save the selection start into a variable.. - int selStart = scintilla.SelectionStart; - - // save the start line index of the selection into a variable.. - int startLine = scintilla.LineFromPosition(selStart); - - // adjust the selection start to match the actual line start of the selection.. - selStart = scintilla.Lines[startLine].Position; - - // save the selection end into a variable.. - int selEnd = scintilla.SelectionEnd; - - // save the end line index of the selection into a variable.. - int endLine = scintilla.LineFromPosition(selEnd); - - // adjust the selection end to match the actual line end of the selection.. - selEnd = scintilla.Lines[endLine].EndPosition; - - // reset the selection with the "corrected" values.. - scintilla.SelectionStart = selStart; - scintilla.SelectionEnd = selEnd; - - // get the lines in the selection and order the lines alphabetically with LINQ.. - var lines = sortFunc( - scintilla.Lines.Where(f => f.Index >= startLine && f.Index <= endLine).Select(f => f.Text), - (SortTextStyle) stringComparison, descending); - - // replace the modified selection with the sorted lines.. - scintilla.ReplaceSelection(string.Join("", lines)); - - // get the "new" selection start.. - selStart = scintilla.Lines[startLine].Position; - - // get the "new" selection end.. - selEnd = scintilla.Lines[endLine].EndPosition; - - // set the "new" selection.. - scintilla.SelectionStart = selStart; - scintilla.SelectionEnd = selEnd; - } - // somehow the whole document is easier.. - else - { - // just LINQ it to sorted list.. - var lines = sortFunc( - scintilla.Lines.OrderBy(f => f.Text.ToComparisonVariant(stringComparison)).Select(f => f.Text), - (SortTextStyle) stringComparison, descending); - - // set the text.. - scintilla.Text = string.Concat(lines); - } + // save the selection start into a variable.. + int selStart = scintilla.SelectionStart; + + // save the start line index of the selection into a variable.. + int startLine = scintilla.LineFromPosition(selStart); + + // adjust the selection start to match the actual line start of the selection.. + selStart = scintilla.Lines[startLine].Position; + + // save the selection end into a variable.. + int selEnd = scintilla.SelectionEnd; + + // save the end line index of the selection into a variable.. + int endLine = scintilla.LineFromPosition(selEnd); + + // adjust the selection end to match the actual line end of the selection.. + selEnd = scintilla.Lines[endLine].EndPosition; + + // reset the selection with the "corrected" values.. + scintilla.SelectionStart = selStart; + scintilla.SelectionEnd = selEnd; + + // get the lines in the selection and order the lines alphabetically with LINQ.. + var lines = sortFunc( + scintilla.Lines.Where(f => f.Index >= startLine && f.Index <= endLine).Select(f => f.Text), + (SortTextStyle) stringComparison, descending); + + // replace the modified selection with the sorted lines.. + scintilla.ReplaceSelection(string.Join("", lines)); + + // get the "new" selection start.. + selStart = scintilla.Lines[startLine].Position; + + // get the "new" selection end.. + selEnd = scintilla.Lines[endLine].EndPosition; + + // set the "new" selection.. + scintilla.SelectionStart = selStart; + scintilla.SelectionEnd = selEnd; } - catch (Exception ex) + // somehow the whole document is easier.. + else { - // log the exception if the action has a value.. - ExceptionLogAction?.Invoke(ex); + // just LINQ it to sorted list.. + var lines = sortFunc( + scintilla.Lines.OrderBy(f => f.Text.ToComparisonVariant(stringComparison)).Select(f => f.Text), + (SortTextStyle) stringComparison, descending); + + // set the text.. + scintilla.Text = string.Concat(lines); } } + catch (Exception ex) + { + // log the exception if the action has a value.. + ExceptionLogAction?.Invoke(ex); + } + } - /// - /// A method to sort the contents of a control. - /// - /// The scintilla control which contents to sort. - /// The sort text. - /// The type of string comparison to use with the sort. - /// Optional parameter array in case the sort method function requires parameters. - public static void Sort(Scintilla scintilla, SortText sortText, StringComparison stringComparison, - params object[] funcParameters) + /// + /// A method to sort the contents of a control. + /// + /// The scintilla control which contents to sort. + /// The sort text. + /// The type of string comparison to use with the sort. + /// Optional parameter array in case the sort method function requires parameters. + public static void Sort(Scintilla scintilla, SortText sortText, StringComparison stringComparison, + params object[] funcParameters) + { + if ((int) sortText.SortTextStyle >= (int) StringComparison.CurrentCulture && + (int) sortText.SortTextStyle < (int) StringComparison.OrdinalIgnoreCase) { - if ((int) sortText.SortTextStyle >= (int) StringComparison.CurrentCulture && - (int) sortText.SortTextStyle < (int) StringComparison.OrdinalIgnoreCase) + Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending); + } + else // lambda functions here for the other sorting styles.. + { + if (sortText.SortTextStyle == SortTextStyle.Length) { - Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending); + // sort by length.. + Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, + delegate(IEnumerable lines, SortTextStyle style, bool descending) + { + var result = descending + ? lines.OrderByDescending(f => f.Length) + : lines.OrderBy(f => f.Length); + return result; + }); + return; } - else // lambda functions here for the other sorting styles.. + + if (sortText.SortTextStyle == SortTextStyle.LowerFirst || + sortText.SortTextStyle == SortTextStyle.UpperFirst) { - if (sortText.SortTextStyle == SortTextStyle.Length) - { - // sort by length.. - Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, - delegate(IEnumerable lines, SortTextStyle style, bool descending) - { - var result = descending - ? lines.OrderByDescending(f => f.Length) - : lines.OrderBy(f => f.Length); - return result; - }); - return; - } - - if (sortText.SortTextStyle == SortTextStyle.LowerFirst || - sortText.SortTextStyle == SortTextStyle.UpperFirst) - { - // sort by explicit lower or upper case characters firs.. - Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, - delegate(IEnumerable lines, SortTextStyle style, bool descending) - { - var enumerable = lines as string[] ?? lines.ToArray(); - - var orphan = enumerable.Where(f => f.ToLower() == f && f.ToUpper() == f).ToList(); - var lower = enumerable.Where(f => f.ToLower() == f && f.ToUpper() != f).ToList(); - var upper = enumerable.Where(f => f.ToUpper() == f && f.ToLower() != f).ToList(); - - lower = - descending - ? lower.OrderByDescending(f => f.ToComparisonVariant(stringComparison)).ToList() - : lower.OrderBy(f => f.ToComparisonVariant(stringComparison)).ToList(); - - upper = descending - ? upper.OrderByDescending(f => f.ToComparisonVariant(stringComparison)).ToList() - : upper.OrderBy(f => f.ToComparisonVariant(stringComparison)).ToList(); - - orphan = descending - ? orphan.OrderByDescending(f => f.ToComparisonVariant(stringComparison)).ToList() - : orphan.OrderBy(f => f.ToComparisonVariant(stringComparison)).ToList(); - - var result = new List(); - - if (sortText.SortTextStyle == SortTextStyle.LowerFirst) - { - result.AddRange(lower); - result.AddRange(upper); - } - else - { - result.AddRange(upper); - result.AddRange(lower); - } - - result.AddRange(orphan); - - return result; - }); - } - - if (sortText.SortTextStyle == SortTextStyle.SubString) - { - Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, - delegate(IEnumerable lines, SortTextStyle style, bool descending) + // sort by explicit lower or upper case characters firs.. + Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, + delegate(IEnumerable lines, SortTextStyle style, bool descending) + { + var enumerable = lines as string[] ?? lines.ToArray(); + + var orphan = enumerable.Where(f => f.ToLower() == f && f.ToUpper() == f).ToList(); + var lower = enumerable.Where(f => f.ToLower() == f && f.ToUpper() != f).ToList(); + var upper = enumerable.Where(f => f.ToUpper() == f && f.ToLower() != f).ToList(); + + lower = + descending + ? lower.OrderByDescending(f => f.ToComparisonVariant(stringComparison)).ToList() + : lower.OrderBy(f => f.ToComparisonVariant(stringComparison)).ToList(); + + upper = descending + ? upper.OrderByDescending(f => f.ToComparisonVariant(stringComparison)).ToList() + : upper.OrderBy(f => f.ToComparisonVariant(stringComparison)).ToList(); + + orphan = descending + ? orphan.OrderByDescending(f => f.ToComparisonVariant(stringComparison)).ToList() + : orphan.OrderBy(f => f.ToComparisonVariant(stringComparison)).ToList(); + + var result = new List(); + + if (sortText.SortTextStyle == SortTextStyle.LowerFirst) { - return sortText.Descending - ? lines.OrderByDescending(f => f.ToComparisonVariant(stringComparison).SafeSubString( - (int) sortText.ExtraData1 - 1, - (int) sortText.ExtraData2)) - : lines.OrderBy(f => f.ToComparisonVariant(stringComparison).SafeSubString( - (int)sortText.ExtraData1 - 1, - (int)sortText.ExtraData2)); - }); - } - - if (sortText.SortTextStyle == SortTextStyle.Regex) - { - Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, - delegate(IEnumerable lines, SortTextStyle style, bool descending) + result.AddRange(lower); + result.AddRange(upper); + } + else { - var regex = new Regex(sortText.ExtraData1.ToString(), RegexOptions.Compiled); - - return sortText.Descending - ? lines.OrderByDescending(f => - regex.Match(f).Value.ToComparisonVariant(stringComparison)) - : lines.OrderByDescending(f => - regex.Match(f).Value.ToComparisonVariant(stringComparison)); - }); - } + result.AddRange(upper); + result.AddRange(lower); + } + + result.AddRange(orphan); + + return result; + }); + } + + if (sortText.SortTextStyle == SortTextStyle.SubString) + { + Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, + delegate(IEnumerable lines, SortTextStyle style, bool descending) + { + return sortText.Descending + ? lines.OrderByDescending(f => f.ToComparisonVariant(stringComparison).SafeSubString( + (int) sortText.ExtraData1 - 1, + (int) sortText.ExtraData2)) + : lines.OrderBy(f => f.ToComparisonVariant(stringComparison).SafeSubString( + (int)sortText.ExtraData1 - 1, + (int)sortText.ExtraData2)); + }); + } + + if (sortText.SortTextStyle == SortTextStyle.Regex) + { + Sort(scintilla, (StringComparison) sortText.SortTextStyle, sortText.Descending, + delegate(IEnumerable lines, SortTextStyle style, bool descending) + { + var regex = new Regex(sortText.ExtraData1.ToString(), RegexOptions.Compiled); + + return sortText.Descending + ? lines.OrderByDescending(f => + regex.Match(f).Value.ToComparisonVariant(stringComparison)) + : lines.OrderByDescending(f => + regex.Match(f).Value.ToComparisonVariant(stringComparison)); + }); } } } +} +/// +/// An enumeration for a text sorting style. +/// +public enum SortTextStyle +{ /// - /// An enumeration for a text sorting style. + /// Compare strings using culture-sensitive sort rules and the current culture. /// - public enum SortTextStyle - { - /// - /// Compare strings using culture-sensitive sort rules and the current culture. - /// - CurrentCulture, - - /// - /// Compare strings using culture-sensitive sort rules, the current culture, and ignoring the case of the strings being compared. - /// - CurrentCultureIgnoreCase, - - /// - /// Compare strings using culture-sensitive sort rules and the invariant culture. - /// - InvariantCulture, - - /// - /// Compare strings using culture-sensitive sort rules, the invariant culture, and ignoring the case of the strings being compared. - /// - InvariantCultureIgnoreCase, - /// - /// Compare strings using ordinal (binary) sort rules. - /// - Ordinal, - - /// - /// Compare strings using ordinal (binary) sort rules and ignoring the case of the strings being compared. - /// - OrdinalIgnoreCase, - - /// - /// Compare strings by their length. - /// - Length, - - /// - /// First compare complete upper-case strings. - /// - UpperFirst, - - /// - /// First compare complete lower-case strings. - /// - LowerFirst, - - /// - /// Compare only sub-string values for sorting. - /// - SubString, + CurrentCulture, + + /// + /// Compare strings using culture-sensitive sort rules, the current culture, and ignoring the case of the strings being compared. + /// + CurrentCultureIgnoreCase, + + /// + /// Compare strings using culture-sensitive sort rules and the invariant culture. + /// + InvariantCulture, + + /// + /// Compare strings using culture-sensitive sort rules, the invariant culture, and ignoring the case of the strings being compared. + /// + InvariantCultureIgnoreCase, + /// + /// Compare strings using ordinal (binary) sort rules. + /// + Ordinal, + + /// + /// Compare strings using ordinal (binary) sort rules and ignoring the case of the strings being compared. + /// + OrdinalIgnoreCase, + + /// + /// Compare strings by their length. + /// + Length, + + /// + /// First compare complete upper-case strings. + /// + UpperFirst, + + /// + /// First compare complete lower-case strings. + /// + LowerFirst, + + /// + /// Compare only sub-string values for sorting. + /// + SubString, - /// - /// Compare regular expression matches yo sort strings. - /// - Regex, - } + /// + /// Compare regular expression matches yo sort strings. + /// + Regex, +} +/// +/// A class to indicate a single text sorting style. +/// Implements the +/// +/// +public class SortText: ErrorHandlingBase +{ /// - /// A class to indicate a single text sorting style. - /// Implements the + /// Initializes a new instance of the class. /// - /// - public class SortText: ErrorHandlingBase + /// The sort text style. + /// if set to true the sort order will be descending. + public SortText(SortTextStyle sortTextStyle, bool descending) { - /// - /// Initializes a new instance of the class. - /// - /// The sort text style. - /// if set to true the sort order will be descending. - public SortText(SortTextStyle sortTextStyle, bool descending) - { - Descending = descending; - SortTextStyle = sortTextStyle; + Descending = descending; + SortTextStyle = sortTextStyle; - if (SortTextStyle == SortTextStyle.SubString) - { - ExtraData1 = 1; - ExtraData2 = 1; - } + if (SortTextStyle == SortTextStyle.SubString) + { + ExtraData1 = 1; + ExtraData2 = 1; } + } - /// - /// Initializes a new instance of the class. - /// - /// The sort text style. - public SortText(SortTextStyle sortTextStyle) - { - Descending = false; - SortTextStyle = sortTextStyle; + /// + /// Initializes a new instance of the class. + /// + /// The sort text style. + public SortText(SortTextStyle sortTextStyle) + { + Descending = false; + SortTextStyle = sortTextStyle; - if (SortTextStyle == SortTextStyle.SubString) - { - ExtraData1 = 1; - ExtraData2 = 1; - } + if (SortTextStyle == SortTextStyle.SubString) + { + ExtraData1 = 1; + ExtraData2 = 1; } + } - /// - /// Gets a display name for this . - /// - public string DisplayName + /// + /// Gets a display name for this . + /// + public string DisplayName + { + get { - get + switch (SortTextStyle) { - switch (SortTextStyle) - { - case SortTextStyle.CurrentCulture: - return DBLangEngine.GetStatMessage("msgCurrentCulture", - "Current culture|A short explanation for the System.StringComparison.CurrentCulture enumeration value"); - case SortTextStyle.CurrentCultureIgnoreCase: - return DBLangEngine.GetStatMessage("msgCurrentCultureIgnoreCase", - "Current culture (no case)|A short explanation for the System.StringComparison.CurrentCultureIgnoreCase enumeration value"); - case SortTextStyle.InvariantCulture: - return DBLangEngine.GetStatMessage("msgInvariantCulture", - "Invariant|A short explanation for the System.StringComparison.InvariantCulture enumeration value"); - case SortTextStyle.InvariantCultureIgnoreCase: - return DBLangEngine.GetStatMessage("msgInvariantCultureIgnoreCase", - "Invariant (no case)|A short explanation for the System.StringComparison.InvariantCultureIgnoreCase enumeration value"); - case SortTextStyle.Ordinal: - return DBLangEngine.GetStatMessage("msgOrdinalCulture", - "Ordinal|A short explanation for the System.StringComparison.Ordinal enumeration value"); - case SortTextStyle.OrdinalIgnoreCase: - return DBLangEngine.GetStatMessage("msgOrdinalCultureIgnoreCase", - "Ordinal (no case)|A short explanation for the System.StringComparison.OrdinalIgnoreCase enumeration value"); - case SortTextStyle.Length: - return DBLangEngine.GetStatMessage("msgStringComparisonLength", - "Length|A short explanation for a text comparison (sorting by length)"); - case SortTextStyle.UpperFirst: - return DBLangEngine.GetStatMessage("msgStringComparisonUpperFirst", - "Upper first|A short explanation for a text comparison (completely upper-case strings are compared first)"); - case SortTextStyle.LowerFirst: - return DBLangEngine.GetStatMessage("msgStringComparisonLowerFirst", - "Lower first|A short explanation for a text comparison (completely lower-case strings are compared first)"); - case SortTextStyle.SubString: - return DBLangEngine.GetStatMessage("msgStringComparisonSubString", - "Substring|A short explanation for a text substring comparison"); - case SortTextStyle.Regex: - return DBLangEngine.GetStatMessage("msgStringComparisonRegex", - "Regular expression|A short explanation for a text regular expression comparison"); - default: - return DBLangEngine.GetStatMessage("msgUnknown", - "Unknown|A short message to describe an unknown or undefined value"); - } + case SortTextStyle.CurrentCulture: + return DBLangEngine.GetStatMessage("msgCurrentCulture", + "Current culture|A short explanation for the System.StringComparison.CurrentCulture enumeration value"); + case SortTextStyle.CurrentCultureIgnoreCase: + return DBLangEngine.GetStatMessage("msgCurrentCultureIgnoreCase", + "Current culture (no case)|A short explanation for the System.StringComparison.CurrentCultureIgnoreCase enumeration value"); + case SortTextStyle.InvariantCulture: + return DBLangEngine.GetStatMessage("msgInvariantCulture", + "Invariant|A short explanation for the System.StringComparison.InvariantCulture enumeration value"); + case SortTextStyle.InvariantCultureIgnoreCase: + return DBLangEngine.GetStatMessage("msgInvariantCultureIgnoreCase", + "Invariant (no case)|A short explanation for the System.StringComparison.InvariantCultureIgnoreCase enumeration value"); + case SortTextStyle.Ordinal: + return DBLangEngine.GetStatMessage("msgOrdinalCulture", + "Ordinal|A short explanation for the System.StringComparison.Ordinal enumeration value"); + case SortTextStyle.OrdinalIgnoreCase: + return DBLangEngine.GetStatMessage("msgOrdinalCultureIgnoreCase", + "Ordinal (no case)|A short explanation for the System.StringComparison.OrdinalIgnoreCase enumeration value"); + case SortTextStyle.Length: + return DBLangEngine.GetStatMessage("msgStringComparisonLength", + "Length|A short explanation for a text comparison (sorting by length)"); + case SortTextStyle.UpperFirst: + return DBLangEngine.GetStatMessage("msgStringComparisonUpperFirst", + "Upper first|A short explanation for a text comparison (completely upper-case strings are compared first)"); + case SortTextStyle.LowerFirst: + return DBLangEngine.GetStatMessage("msgStringComparisonLowerFirst", + "Lower first|A short explanation for a text comparison (completely lower-case strings are compared first)"); + case SortTextStyle.SubString: + return DBLangEngine.GetStatMessage("msgStringComparisonSubString", + "Substring|A short explanation for a text substring comparison"); + case SortTextStyle.Regex: + return DBLangEngine.GetStatMessage("msgStringComparisonRegex", + "Regular expression|A short explanation for a text regular expression comparison"); + default: + return DBLangEngine.GetStatMessage("msgUnknown", + "Unknown|A short message to describe an unknown or undefined value"); } } + } - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + var result = DisplayName; + if (SortTextStyle == SortTextStyle.SubString) { - var result = DisplayName; - if (SortTextStyle == SortTextStyle.SubString) - { - result += " [" + ExtraData1 + ", " + ExtraData2 + "]"; - } - - if (SortTextStyle == SortTextStyle.Regex) - { - result += ": '" + ExtraData1 + "'"; - } + result += " [" + ExtraData1 + ", " + ExtraData2 + "]"; + } - return result; + if (SortTextStyle == SortTextStyle.Regex) + { + result += ": '" + ExtraData1 + "'"; } - /// - /// Gets or sets the extra data 1 used by few of the sort algorithms. - /// - public object ExtraData1 { get; set; } + return result; + } - /// - /// Gets or sets the extra data 2 used by few of the sort algorithms. - /// - public object ExtraData2 { get; set; } + /// + /// Gets or sets the extra data 1 used by few of the sort algorithms. + /// + public object ExtraData1 { get; set; } - /// - /// Gets a value indicating whether this instance indicates a and the Regex is valid. - /// - public bool IsValidRegex + /// + /// Gets or sets the extra data 2 used by few of the sort algorithms. + /// + public object ExtraData2 { get; set; } + + /// + /// Gets a value indicating whether this instance indicates a and the Regex is valid. + /// + public bool IsValidRegex + { + get { - get + if (SortTextStyle != SortTextStyle.Regex) { - if (SortTextStyle != SortTextStyle.Regex) - { - return true; - } - - if (string.IsNullOrEmpty(ExtraData1.ToString())) - { - return false; - } - - try - { - // ReSharper disable once ObjectCreationAsStatement, this is intentional.. - new Regex(ExtraData1.ToString()); - } - catch (Exception ex) - { - // log the exception.. - ExceptionLogAction?.Invoke(ex); - return false; - } - return true; } - } - /// - /// Gets the sorting style for this class instance. - /// - public SortTextStyle SortTextStyle { get; } - - /// - /// A value indicating whether to use descending sorting for the text. - /// - public bool Descending { get; set; } - - /// - /// Implements the == operator. - /// - /// The sort1. - /// The sort2. - /// The result of the operator. - public static bool operator == (SortText sort1, SortText sort2) - { - if (Equals(sort1, null) && Equals(sort2, null)) + if (string.IsNullOrEmpty(ExtraData1.ToString())) { - return true; + return false; } - if (Equals(sort1, null) || Equals(sort2, null)) + try + { + // ReSharper disable once ObjectCreationAsStatement, this is intentional.. + new Regex(ExtraData1.ToString()); + } + catch (Exception ex) { + // log the exception.. + ExceptionLogAction?.Invoke(ex); return false; } - return sort1.Descending == sort2.Descending && sort1.SortTextStyle == sort2.SortTextStyle && - sort1.ExtraData1 == sort2.ExtraData1 && sort1.ExtraData2 == sort2.ExtraData2; + return true; } + } - /// - /// Implements the != operator. - /// - /// The sort1. - /// The sort1. - /// The result of the operator. - public static bool operator != (SortText sort1, SortText sort2) - { - return !(sort1 == sort2); - } + /// + /// Gets the sorting style for this class instance. + /// + public SortTextStyle SortTextStyle { get; } - /// - /// Determines whether the specified is equal to this instance. - /// - /// The other. - /// true if the specified is equal to this instance, false otherwise. - protected bool Equals(SortText other) + /// + /// A value indicating whether to use descending sorting for the text. + /// + public bool Descending { get; set; } + + /// + /// Implements the == operator. + /// + /// The sort1. + /// The sort2. + /// The result of the operator. + public static bool operator == (SortText sort1, SortText sort2) + { + if (Equals(sort1, null) && Equals(sort2, null)) { - return SortTextStyle == other.SortTextStyle && Descending == other.Descending && - other.ExtraData1 == ExtraData1 && other.ExtraData2 == ExtraData2; + return true; } - /// - /// Determines whether the specified is equal to this instance. - /// - /// The object to compare with the current object. - /// true if the specified is equal to this instance; otherwise, false. - public override bool Equals(object obj) + if (Equals(sort1, null) || Equals(sort2, null)) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; - return Equals((SortText) obj); + return false; } - /// - /// Returns a hash code for this instance. - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - public override int GetHashCode() + return sort1.Descending == sort2.Descending && sort1.SortTextStyle == sort2.SortTextStyle && + sort1.ExtraData1 == sort2.ExtraData1 && sort1.ExtraData2 == sort2.ExtraData2; + } + + /// + /// Implements the != operator. + /// + /// The sort1. + /// The sort1. + /// The result of the operator. + public static bool operator != (SortText sort1, SortText sort2) + { + return !(sort1 == sort2); + } + + /// + /// Determines whether the specified is equal to this instance. + /// + /// The other. + /// true if the specified is equal to this instance, false otherwise. + protected bool Equals(SortText other) + { + return SortTextStyle == other.SortTextStyle && Descending == other.Descending && + other.ExtraData1 == ExtraData1 && other.ExtraData2 == ExtraData2; + } + + /// + /// Determines whether the specified is equal to this instance. + /// + /// The object to compare with the current object. + /// true if the specified is equal to this instance; otherwise, false. + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != GetType()) return false; + return Equals((SortText) obj); + } + + /// + /// Returns a hash code for this instance. + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + public override int GetHashCode() + { + unchecked { - unchecked - { - return (int) SortTextStyle * 397; - } + return (int) SortTextStyle * 397; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlMultilineConvert.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlMultilineConvert.cs index 0a3bd7d5..76586c3e 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlMultilineConvert.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlMultilineConvert.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,35 +26,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Xml +namespace ScriptNotepad.UtilityClasses.TextManipulation.Xml; + +/// +/// A class to convert single-line XML to formatted XML. +/// Implements the +/// +/// +public class XmlMultilineConvert: TextManipulationCommandBase { /// - /// A class to convert single-line XML to formatted XML. - /// Implements the + /// Manipulates the specified text value. + /// + /// The value to manipulate. + /// A string containing the manipulated text. + public override string Manipulate(string value) + { + return XmlTidy.Tidy(value, true); + } + + /// + public override bool PreferSelectedText { get; set; } = false; + + /// + /// Returns a that represents this instance. /// - /// - public class XmlMultilineConvert: TextManipulationCommandBase + /// A that represents this instance. + public override string ToString() { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public override string Manipulate(string value) - { - return XmlTidy.Tidy(value, true); - } - - /// - public override bool PreferSelectedText { get; set; } = false; - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return MethodName; - } + return MethodName; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlSingleLineConvert.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlSingleLineConvert.cs index f05c837a..a1d1ca3d 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlSingleLineConvert.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlSingleLineConvert.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,35 +26,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Xml +namespace ScriptNotepad.UtilityClasses.TextManipulation.Xml; + +/// +/// A class to convert formatted XML to a single-line XML. +/// Implements the +/// +/// +public class XmlSingleLineConvert: TextManipulationCommandBase { /// - /// A class to convert formatted XML to a single-line XML. - /// Implements the + /// Manipulates the specified text value. + /// + /// The value to manipulate. + /// A string containing the manipulated text. + public override string Manipulate(string value) + { + return XmlTidy.Tidy(value, false); + } + + /// + public override bool PreferSelectedText { get; set; } = false; + + /// + /// Returns a that represents this instance. /// - /// - public class XmlSingleLineConvert: TextManipulationCommandBase + /// A that represents this instance. + public override string ToString() { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public override string Manipulate(string value) - { - return XmlTidy.Tidy(value, false); - } - - /// - public override bool PreferSelectedText { get; set; } = false; - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() - { - return MethodName; - } + return MethodName; } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlTidy.cs b/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlTidy.cs index 51bd723e..a534bfd9 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlTidy.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/Xml/XmlTidy.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -28,66 +28,65 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Xml; using ScriptNotepad.UtilityClasses.ErrorHandling; -namespace ScriptNotepad.UtilityClasses.TextManipulation.Xml +namespace ScriptNotepad.UtilityClasses.TextManipulation.Xml; + +/// +/// An utility class to clean up XML data. +/// +internal static class XmlTidy { /// - /// An utility class to clean up XML data. + /// Tidies the specified XML string value. /// - internal static class XmlTidy + /// The XML string value. + /// if set to true return the XML as multiline. + /// The specified XML string formatted. + public static string Tidy(string value, bool multiLine) { - /// - /// Tidies the specified XML string value. - /// - /// The XML string value. - /// if set to true return the XML as multiline. - /// The specified XML string formatted. - public static string Tidy(string value, bool multiLine) + try { - try - { - var doc = new XmlDocument(); + var doc = new XmlDocument(); - // Only support for utf-8 and utf-16 encodings. - var utf16 = value.Contains("encoding=\"utf-16\""); + // Only support for utf-8 and utf-16 encodings. + var utf16 = value.Contains("encoding=\"utf-16\""); - // Check if the XML contains the encoding data. - var regex = new Regex(@"<\?xml version=\"".*?\"" encoding=\"".*?\""\?>"); + // Check if the XML contains the encoding data. + var regex = new Regex(@"<\?xml version=\"".*?\"" encoding=\"".*?\""\?>"); - var hasEncoding = regex.IsMatch(value); + var hasEncoding = regex.IsMatch(value); - doc.LoadXml(value); + doc.LoadXml(value); - var memoryStream = new MemoryStream(); + var memoryStream = new MemoryStream(); - Encoding encoding = utf16 ? new UnicodeEncoding(false, false) : new UTF8Encoding(false); + Encoding encoding = utf16 ? new UnicodeEncoding(false, false) : new UTF8Encoding(false); - // Set the XML "formatting" as requested. - var settings = multiLine - ? new XmlWriterSettings { Indent = true, IndentChars = "\t", Encoding = encoding } - : new XmlWriterSettings { Encoding = encoding }; + // Set the XML "formatting" as requested. + var settings = multiLine + ? new XmlWriterSettings { Indent = true, IndentChars = "\t", Encoding = encoding, } + : new XmlWriterSettings { Encoding = encoding, }; - using var writer = XmlWriter.Create(memoryStream, settings); + using var writer = XmlWriter.Create(memoryStream, settings); - doc.Save(writer); + doc.Save(writer); - writer.Close(); + writer.Close(); - var result = encoding.GetString(memoryStream.ToArray()); + var result = encoding.GetString(memoryStream.ToArray()); - // Remove the encoding data if the original value didn't contain it. - if (!hasEncoding) - { - result = regex.Replace(result, string.Empty); - result = result.TrimStart('\n', '\r'); - } - - return result; - } - catch (Exception ex) + // Remove the encoding data if the original value didn't contain it. + if (!hasEncoding) { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return value; + result = regex.Replace(result, string.Empty); + result = result.TrimStart('\n', '\r'); } + + return result; + } + catch (Exception ex) + { + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return value; } } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/XmlPrettify.cs b/ScriptNotepad/UtilityClasses/TextManipulation/XmlPrettify.cs index 78f685d8..13deb58e 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/XmlPrettify.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/XmlPrettify.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,36 +26,35 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.TextManipulation.Xml; -namespace ScriptNotepad.UtilityClasses.TextManipulation +namespace ScriptNotepad.UtilityClasses.TextManipulation; + +/// +/// A class for XML text utilities. +/// +public static class XmlUtils { + private static readonly XmlMultilineConvert XmlMultilineConvert = new(); + + private static readonly XmlSingleLineConvert XmlSingleLineConvert = new(); + + /// + /// Prettifies a specified XML text. + /// + /// The value to prettify. + /// Intended XML text. + public static string XmlPrettify(this string value) + { + return XmlMultilineConvert.Manipulate(value); + } + + /// - /// A class for XML text utilities. + /// Uglifies a specified XML text (he-hee). /// - public static class XmlUtils + /// The value. + /// System.String. + public static string XmlUglify(this string value) { - private static readonly XmlMultilineConvert XmlMultilineConvert = new(); - - private static readonly XmlSingleLineConvert XmlSingleLineConvert = new(); - - /// - /// Prettifies a specified XML text. - /// - /// The value to prettify. - /// Intended XML text. - public static string XmlPrettify(this string value) - { - return XmlMultilineConvert.Manipulate(value); - } - - - /// - /// Uglifies a specified XML text (he-hee). - /// - /// The value. - /// System.String. - public static string XmlUglify(this string value) - { - return XmlSingleLineConvert.Manipulate(value); - } + return XmlSingleLineConvert.Manipulate(value); } -} +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/base64/Base64ToString.cs b/ScriptNotepad/UtilityClasses/TextManipulation/base64/Base64ToString.cs index a977e684..47d088f0 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/base64/Base64ToString.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/base64/Base64ToString.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,43 +27,42 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; -namespace ScriptNotepad.UtilityClasses.TextManipulation.base64 +namespace ScriptNotepad.UtilityClasses.TextManipulation.base64; + +/// +/// A class to convert an UTF-8 encoded text data into a base64 encoded data. +/// Implements the +/// +/// +internal class Base64ToString: TextManipulationCommandBase { /// - /// A class to convert an UTF-8 encoded text data into a base64 encoded data. - /// Implements the + /// Manipulates the specified text value. /// - /// - internal class Base64ToString: TextManipulationCommandBase + /// The value to manipulate. + /// A string containing the manipulated text. + public override string Manipulate(string value) { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public override string Manipulate(string value) + try { - try - { - return Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); - } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return value; - } + return Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); } - - /// - public override bool PreferSelectedText { get; set; } = true; - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() + catch (Exception ex) { - return MethodName; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return value; } } -} + + /// + public override bool PreferSelectedText { get; set; } = true; + + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return MethodName; + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulation/base64/StringToBase64.cs b/ScriptNotepad/UtilityClasses/TextManipulation/base64/StringToBase64.cs index 14f58a0a..6e4919fd 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulation/base64/StringToBase64.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulation/base64/StringToBase64.cs @@ -2,7 +2,7 @@ /* MIT License -Copyright(c) 2021 Petteri Kautonen +Copyright(c) 2022 Petteri Kautonen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,45 +27,44 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using ScriptNotepad.UtilityClasses.ErrorHandling; using ScriptNotepad.UtilityClasses.TextManipulation.BaseClasses; -namespace ScriptNotepad.UtilityClasses.TextManipulation.base64 +namespace ScriptNotepad.UtilityClasses.TextManipulation.base64; + +/// +/// A class to convert a base64 encoded data into UTF-8 encoded string. +/// Implements the +/// +/// +public class StringToBase64: TextManipulationCommandBase { /// - /// A class to convert a base64 encoded data into UTF-8 encoded string. - /// Implements the + /// Manipulates the specified text value. /// - /// - public class StringToBase64: TextManipulationCommandBase + /// The value to manipulate. + /// A string containing the manipulated text. + public override string Manipulate(string value) { - /// - /// Manipulates the specified text value. - /// - /// The value to manipulate. - /// A string containing the manipulated text. - public override string Manipulate(string value) + try { - try - { - var bytes = Convert.FromBase64String(value); + var bytes = Convert.FromBase64String(value); - return Encoding.UTF8.GetString(bytes); - } - catch (Exception ex) - { - ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); - return value; - } + return Encoding.UTF8.GetString(bytes); } - - /// - public override bool PreferSelectedText { get; set; } = true; - - /// - /// Returns a that represents this instance. - /// - /// A that represents this instance. - public override string ToString() + catch (Exception ex) { - return MethodName; + ErrorHandlingBase.ExceptionLogAction?.Invoke(ex); + return value; } } -} + + /// + public override bool PreferSelectedText { get; set; } = true; + + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return MethodName; + } +} \ No newline at end of file diff --git a/ScriptNotepad/UtilityClasses/TextManipulationUtils/WordWrapToSize.cs b/ScriptNotepad/UtilityClasses/TextManipulationUtils/WordWrapToSize.cs index a2e5d92a..2c56c462 100644 --- a/ScriptNotepad/UtilityClasses/TextManipulationUtils/WordWrapToSize.cs +++ b/ScriptNotepad/UtilityClasses/TextManipulationUtils/WordWrapToSize.cs @@ -26,73 +26,72 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Collections.Generic; -namespace ScriptNotepad.UtilityClasses.TextManipulationUtils +namespace ScriptNotepad.UtilityClasses.TextManipulationUtils; + +/// +/// A helper class to wrap text into lines with given length. +/// (C): https://www.rosettacode.org/wiki/Word_wrap#C.23 (GNU Free Documentation License 1.2 / https://www.gnu.org/licenses/old-licenses/fdl-1.2.txt) +/// +public static class WordWrapToSize { /// - /// A helper class to wrap text into lines with given length. - /// (C): https://www.rosettacode.org/wiki/Word_wrap#C.23 (GNU Free Documentation License 1.2 / https://www.gnu.org/licenses/old-licenses/fdl-1.2.txt) + /// Wraps the specified text into lines with the maximum length of . /// - public static class WordWrapToSize + /// The text to wrap. + /// The maximum width of the line. + /// System.String. + public static string Wrap(string text, int lineWidth) { - /// - /// Wraps the specified text into lines with the maximum length of . - /// - /// The text to wrap. - /// The maximum width of the line. - /// System.String. - public static string Wrap(string text, int lineWidth) - { - text = RemoveLineEndings(text); - return string.Join(string.Empty, - Wrap( - text.Split(new[] {' '}, // changed this to a white space (VPKSoft).. - StringSplitOptions - .RemoveEmptyEntries), - lineWidth)); - } + text = RemoveLineEndings(text); + return string.Join(string.Empty, + Wrap( + text.Split(new[] {' ', }, // changed this to a white space (VPKSoft).. + StringSplitOptions + .RemoveEmptyEntries), + lineWidth)); + } - /// - /// Removes the line endings from a given string replacing the line endings with a white space character. - /// - /// The string to remove the line endings from. - /// System.String. - private static string RemoveLineEndings(string toRemoveFrom) - { - toRemoveFrom = toRemoveFrom.Replace("\r\n", " "); - toRemoveFrom = toRemoveFrom.Replace("\n\r", " "); - toRemoveFrom = toRemoveFrom.Replace("\r", " "); - toRemoveFrom = toRemoveFrom.Replace("\n", " "); - return toRemoveFrom; - } + /// + /// Removes the line endings from a given string replacing the line endings with a white space character. + /// + /// The string to remove the line endings from. + /// System.String. + private static string RemoveLineEndings(string toRemoveFrom) + { + toRemoveFrom = toRemoveFrom.Replace("\r\n", " "); + toRemoveFrom = toRemoveFrom.Replace("\n\r", " "); + toRemoveFrom = toRemoveFrom.Replace("\r", " "); + toRemoveFrom = toRemoveFrom.Replace("\n", " "); + return toRemoveFrom; + } - /// - /// Wraps the specified words into lines. - /// - /// The words to wrap. - /// The width of the line. - /// IEnumerable<System.String>. - private static IEnumerable Wrap(IEnumerable words, - int lineWidth) + /// + /// Wraps the specified words into lines. + /// + /// The words to wrap. + /// The width of the line. + /// IEnumerable<System.String>. + private static IEnumerable Wrap(IEnumerable words, + int lineWidth) + { + var currentWidth = 0; + foreach (var word in words) { - var currentWidth = 0; - foreach (var word in words) + if (currentWidth != 0) { - if (currentWidth != 0) + if (currentWidth + word.Length < lineWidth) + { + currentWidth++; + yield return " "; + } + else { - if (currentWidth + word.Length < lineWidth) - { - currentWidth++; - yield return " "; - } - else - { - currentWidth = 0; - yield return Environment.NewLine; - } + currentWidth = 0; + yield return Environment.NewLine; } - currentWidth += word.Length; - yield return word; } + currentWidth += word.Length; + yield return word; } } -} +} \ No newline at end of file