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, false False false false (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, false False false false (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