From dcdd47d60c87f47755cded492e255bd13fe97f31 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 08:54:46 +0200 Subject: [PATCH 01/26] removing DarkMode in preparation for .net 10 --- src/LogExpert.Core/Config/ColorMode.cs | 76 ------------- .../Controls/LogWindow/LogWindow.cs | 103 +----------------- .../Controls/LogWindow/LogWindowPublic.cs | 65 ++++++----- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 52 --------- .../Dialogs/LogTabWindow/LogTabWindow.cs | 103 ------------------ src/LogExpert.UI/Entities/PaintHelper.cs | 41 ++++--- 6 files changed, 53 insertions(+), 387 deletions(-) delete mode 100644 src/LogExpert.Core/Config/ColorMode.cs diff --git a/src/LogExpert.Core/Config/ColorMode.cs b/src/LogExpert.Core/Config/ColorMode.cs deleted file mode 100644 index 02a0c876..00000000 --- a/src/LogExpert.Core/Config/ColorMode.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Drawing; - -namespace LogExpert.Core.Config; - -public static class ColorMode -{ - // Bright Theme - // https://paletton.com/#uid=15-0u0k00sH00kJ0pq+00RL00RL - private static readonly Color BrightBookmarkDefaultSystemColor = SystemColors.Control; // Important: only supports SystemColors - private static readonly Color LessBrightBackgroundColor = Color.FromArgb(208, 205, 206); - private static readonly Color BrightBackgroundColor = Color.FromArgb(221, 221, 221); - private static readonly Color BrighterBackgroundColor = Color.White; - private static readonly Color BrightForeColor = Color.Black; - - // Dark Theme - // https://paletton.com/#uid=15-0u0k005U0670008J003Y003Y - private static readonly Color DarkBookmarkDefaultSystemColor = SystemColors.ControlDarkDark; // Important: only supports SystemColors - private static readonly Color LessLessDarkBackgroundColor = Color.FromArgb(90, 90, 90); - private static readonly Color LessDarkBackgroundColor = Color.FromArgb(67, 67, 67); - private static readonly Color DarkBackgroundColor = Color.FromArgb(45, 45, 45); - private static readonly Color DarkerBackgroundColor = Color.FromArgb(30, 30, 30); - private static readonly Color DarkForeColor = Color.White; - - // Default - public static Color BackgroundColor = BrightBackgroundColor; - public static Color DockBackgroundColor = BrighterBackgroundColor; - public static Color BookmarksDefaultBackgroundColor = BrightBookmarkDefaultSystemColor; - public static Color ForeColor = BrightForeColor; - public static Color MenuBackgroundColor = BrighterBackgroundColor; - public static Color HoverMenuBackgroundColor = LessBrightBackgroundColor; - public static Color ActiveTabColor = BrighterBackgroundColor; - public static Color InactiveTabColor = LessBrightBackgroundColor; - public static Color TabsBackgroundStripColor = LessBrightBackgroundColor; - - public static bool DarkModeEnabled; - - public static void LoadColorMode (bool darkMode) - { - if (darkMode) - { - SetDarkMode(); - } - else - { - SetBrightMode(); - } - } - - private static void SetDarkMode () - { - BackgroundColor = DarkBackgroundColor; - ForeColor = DarkForeColor; - MenuBackgroundColor = DarkerBackgroundColor; - DockBackgroundColor = LessDarkBackgroundColor; - HoverMenuBackgroundColor = LessDarkBackgroundColor; - BookmarksDefaultBackgroundColor = DarkBookmarkDefaultSystemColor; - TabsBackgroundStripColor = LessDarkBackgroundColor; - ActiveTabColor = LessLessDarkBackgroundColor; - InactiveTabColor = LessDarkBackgroundColor; - DarkModeEnabled = true; - } - - private static void SetBrightMode () - { - BackgroundColor = BrightBackgroundColor; - ForeColor = BrightForeColor; - MenuBackgroundColor = BrighterBackgroundColor; - DockBackgroundColor = BrighterBackgroundColor; - BookmarksDefaultBackgroundColor = BrightBookmarkDefaultSystemColor; - HoverMenuBackgroundColor = LessBrightBackgroundColor; - TabsBackgroundStripColor = BrighterBackgroundColor; - ActiveTabColor = BrighterBackgroundColor; - InactiveTabColor = LessBrightBackgroundColor; - DarkModeEnabled = false; - } -} diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index c593387e..f755c20e 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -13,7 +13,6 @@ using LogExpert.Core.Interface; using LogExpert.Dialogs; using LogExpert.UI.Dialogs; -using LogExpert.UI.Extensions.Forms; using LogExpert.UI.Interface; using NLog; @@ -228,7 +227,7 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp _panelOpenButtonImage = Resources.Resources.Arrow_menu_open; _panelCloseButtonImage = Resources.Resources.Arrow_menu_close; - Settings settings = configManager.Settings; + var settings = configManager.Settings; if (settings.AppBounds.Right > 0) { @@ -256,110 +255,10 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp _bookmarkProvider.AllBookmarksRemoved += OnBookmarkProviderAllBookmarksRemoved; ResumeLayout(); - - ChangeTheme(Controls); } - #endregion - - #region ColorTheme - - [SupportedOSPlatform("windows")] - public void ChangeTheme (Control.ControlCollection container) - { - #region ApplyColorToAllControls - foreach (Control component in container) - { - if (component.Controls != null && component.Controls.Count > 0) - { - ChangeTheme(component.Controls); - component.BackColor = ColorMode.BackgroundColor; - component.ForeColor = ColorMode.ForeColor; - } - else - { - component.BackColor = ColorMode.BackgroundColor; - component.ForeColor = ColorMode.ForeColor; - } - - } - #endregion - - #region DataGridView - - // Main DataGridView - dataGridView.BackgroundColor = ColorMode.DockBackgroundColor; - dataGridView.ColumnHeadersDefaultCellStyle.BackColor = ColorMode.BackgroundColor; - dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = ColorMode.ForeColor; - dataGridView.EnableHeadersVisualStyles = false; - - // Filter dataGridView - filterGridView.BackgroundColor = ColorMode.DockBackgroundColor; - filterGridView.ColumnHeadersDefaultCellStyle.BackColor = ColorMode.BackgroundColor; - filterGridView.ColumnHeadersDefaultCellStyle.ForeColor = ColorMode.ForeColor; - filterGridView.EnableHeadersVisualStyles = false; - - // Colors for menu - dataGridContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - bookmarkContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - columnContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - editModeContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - filterContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - filterListContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - - foreach (ToolStripItem item in dataGridContextMenuStrip.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - foreach (ToolStripItem item in bookmarkContextMenuStrip.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - foreach (ToolStripItem item in columnContextMenuStrip.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - foreach (ToolStripItem item in editModeContextMenuStrip.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - foreach (ToolStripItem item in filterContextMenuStrip.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - foreach (ToolStripItem item in filterListContextMenuStrip.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - // Colors for menu - filterContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - - for (var y = 0; y < filterContextMenuStrip.Items.Count; y++) - { - ToolStripItem item = filterContextMenuStrip.Items[y]; - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - #endregion DataGridView - - filterComboBox.BackColor = ColorMode.DockBackgroundColor; - } - #endregion #region Delegates diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs index 601f3064..cd01695c 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs @@ -47,7 +47,7 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) { if (!IsTempFile) { - ILogLineColumnizer columnizer = FindColumnizer(); + var columnizer = FindColumnizer(); if (columnizer != null) { if (_reloadMemento == null) @@ -120,7 +120,7 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) { if (Preferences.AutoPick) { - ILogLineColumnizer newColumnizer = ColumnizerPicker.FindBetterColumnizer(FileName, _logFileReader, CurrentColumnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + var newColumnizer = ColumnizerPicker.FindBetterColumnizer(FileName, _logFileReader, CurrentColumnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); if (newColumnizer != null) { @@ -186,7 +186,7 @@ public string SavePersistenceData (bool force) try { - PersistenceData persistenceData = GetPersistenceData(); + var persistenceData = GetPersistenceData(); if (ForcedPersistenceFileName == null) { @@ -236,7 +236,7 @@ public PersistenceData GetPersistenceData () List filterList = [_filterParams]; persistenceData.FilterParamsList = filterList; - foreach (FilterPipe filterPipe in _filterPipeList) + foreach (var filterPipe in _filterPipeList) { FilterTabData data = new() { @@ -334,7 +334,7 @@ public void PreselectColumnizer (string columnizerName) //TODO this needs to be refactored var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + var columnizer = ColumnizerPicker.FindColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); PreSelectColumnizer(ColumnizerPicker.CloneColumnizer(columnizer, directory)); } @@ -369,12 +369,12 @@ public IColumn GetCellValue (int rowIndex, int columnIndex) try { - IColumnizedLogLine cols = GetColumnsForLine(rowIndex); + var cols = GetColumnsForLine(rowIndex); if (cols != null && cols.ColumnValues != null) { if (columnIndex <= cols.ColumnValues.Length + 1) { - IColumn value = cols.ColumnValues[columnIndex - 2]; + var value = cols.ColumnValues[columnIndex - 2]; if (value != null && value.DisplayValue != null) { @@ -407,27 +407,26 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV return; } - ILogLine line = _logFileReader.GetLogLineWithWait(rowIndex).Result; + var line = _logFileReader.GetLogLineWithWait(rowIndex).Result; if (line != null) { - HighlightEntry entry = FindFirstNoWordMatchHilightEntry(line); + var entry = FindFirstNoWordMatchHilightEntry(line); e.Graphics.SetClip(e.CellBounds); if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - Color backColor = ColorMode.BackgroundColor; + var backColor = e.CellStyle.SelectionBackColor; Brush brush; if (gridView.Focused) { - brush = new SolidBrush(e.CellStyle.SelectionBackColor); + brush = new SolidBrush(backColor); } else { - Color color = backColor; - brush = new SolidBrush(color); + brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray } e.Graphics.FillRectangle(brush, e.CellBounds); @@ -435,7 +434,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV } else { - Color bgColor = ColorMode.DockBackgroundColor; + var bgColor = Color.White; if (!DebugOptions.DisableWordHighlight) { @@ -476,7 +475,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV Brush brush = new SolidBrush(BookmarkColor); e.Graphics.FillRectangle(brush, r); brush.Dispose(); - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); + var bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); if (bookmark.Text.Length > 0) { @@ -485,7 +484,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); + Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); //dark orange Font font = new("Courier New", Preferences.FontSize, FontStyle.Bold); e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); @@ -517,7 +516,7 @@ public HighlightEntry FindHighlightEntry (ITextValue line, bool noWordMatches) // first check the temp entries lock (_tempHighlightEntryListLock) { - foreach (HighlightEntry entry in _tempHighlightEntryList) + foreach (var entry in _tempHighlightEntryList) { if (noWordMatches && entry.IsWordMatch) { @@ -533,7 +532,7 @@ public HighlightEntry FindHighlightEntry (ITextValue line, bool noWordMatches) lock (_currentHighlightGroupLock) { - foreach (HighlightEntry entry in _currentHighlightGroup.HighlightEntryList) + foreach (var entry in _currentHighlightGroup.HighlightEntryList) { if (noWordMatches && entry.IsWordMatch) { @@ -627,7 +626,7 @@ public void StartSearch () { _guiStateArgs.MenuEnabled = false; GuiStateUpdate(this, _guiStateArgs); - SearchParams searchParams = _parentLogTabWin.SearchParams; + var searchParams = _parentLogTabWin.SearchParams; if ((searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed) { @@ -847,11 +846,11 @@ public void AddBookmarkOverlays () if (_bookmarkProvider.IsBookmarkAtLine(i)) { - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(i); + var bookmark = _bookmarkProvider.GetBookmarkForLine(i); if (bookmark.Text.Length > 0) { //BookmarkOverlay overlay = new BookmarkOverlay(); - BookmarkOverlay overlay = bookmark.Overlay; + var overlay = bookmark.Overlay; overlay.Bookmark = bookmark; Rectangle r; @@ -934,7 +933,7 @@ public void ToggleBookmark (int lineNum) { if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) { - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); + var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); if (string.IsNullOrEmpty(bookmark.Text) == false) { @@ -958,7 +957,7 @@ public void SetBookmarkFromTrigger (int lineNum, string comment) { lock (_bookmarkLock) { - ILogLine line = _logFileReader.GetLogLine(lineNum); + var line = _logFileReader.GetLogLine(lineNum); if (line == null) { return; @@ -1233,7 +1232,7 @@ public void CopyMarkedLinesToTab () var fStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read); var writer = new StreamWriter(fStream, Encoding.Unicode); - DataObject data = dataGridView.GetClipboardContent(); + var data = dataGridView.GetClipboardContent(); var text = data.GetText(TextDataFormat.Text); writer.Write(text); @@ -1400,7 +1399,7 @@ public int FindTimestampLine (int lineNum, DateTime timestamp, bool roundToSecon if (foundLine >= 0) { // go backwards to the first occurence of the hit - DateTime foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); + var foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); while (foundTimestamp.CompareTo(timestamp) == 0 && foundLine >= 0) { foundLine--; @@ -1424,7 +1423,7 @@ public int FindTimestampLine_Internal (int lineNum, int rangeStart, int rangeEnd { _logger.Debug("FindTimestampLine_Internal(): timestamp={0}, lineNum={1}, rangeStart={2}, rangeEnd={3}", timestamp, lineNum, rangeStart, rangeEnd); var refLine = lineNum; - DateTime currentTimestamp = GetTimestampForLine(ref refLine, roundToSeconds); + var currentTimestamp = GetTimestampForLine(ref refLine, roundToSeconds); if (currentTimestamp.CompareTo(timestamp) == 0) { return lineNum; @@ -1481,7 +1480,7 @@ public DateTime GetTimestampForLine (ref int lineNum, bool roundToSeconds) } _logger.Debug($"GetTimestampForLine({lineNum}) enter"); - DateTime timeStamp = DateTime.MinValue; + var timeStamp = DateTime.MinValue; var lookBack = false; if (lineNum >= 0 && lineNum < dataGridView.RowCount) { @@ -1493,7 +1492,7 @@ public DateTime GetTimestampForLine (ref int lineNum, bool roundToSeconds) } lookBack = true; - ILogLine logLine = _logFileReader.GetLogLine(lineNum); + var logLine = _logFileReader.GetLogLine(lineNum); if (logLine == null) { return DateTime.MinValue; @@ -1534,14 +1533,14 @@ public DateTime GetTimestampForLineForward (ref int lineNum, bool roundToSeconds return DateTime.MinValue; } - DateTime timeStamp = DateTime.MinValue; + var timeStamp = DateTime.MinValue; var lookFwd = false; if (lineNum >= 0 && lineNum < dataGridView.RowCount) { while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum < dataGridView.RowCount) { lookFwd = true; - ILogLine logLine = _logFileReader.GetLogLine(lineNum); + var logLine = _logFileReader.GetLogLine(lineNum); if (logLine == null) { timeStamp = DateTime.MinValue; @@ -1731,7 +1730,7 @@ public void ImportBookmarkList () // Add (or replace) to existing bookmark list var bookmarkAdded = false; - foreach (Bookmark b in newBookmarks.Values) + foreach (var b in newBookmarks.Values) { if (!_bookmarkProvider.BookmarkList.ContainsKey(b.LineNum)) { @@ -1740,7 +1739,7 @@ public void ImportBookmarkList () } else { - Bookmark existingBookmark = _bookmarkProvider.BookmarkList[b.LineNum]; + var existingBookmark = _bookmarkProvider.BookmarkList[b.LineNum]; existingBookmark.Text = b.Text; // replace existing bookmark for that line, preserving the overlay OnBookmarkTextChanged(b); @@ -1782,7 +1781,7 @@ public void HandleChangedFilterListWorker () { var index = filterListBox.SelectedIndex; filterListBox.Items.Clear(); - foreach (FilterParams filterParam in ConfigManager.Settings.FilterList) + foreach (var filterParam in ConfigManager.Settings.FilterList) { filterListBox.Items.Add(filterParam); } diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index d471c587..8653c766 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -5,7 +5,6 @@ using LogExpert.Core.Enums; using LogExpert.Core.Interface; using LogExpert.UI.Entities; -using LogExpert.UI.Extensions.Forms; using LogExpert.UI.Interface; using NLog; @@ -39,57 +38,6 @@ public BookmarkWindow () bookmarkDataGridView.CellValueNeeded += OnBoomarkDataGridViewCellValueNeeded; bookmarkDataGridView.CellPainting += OnBoomarkDataGridViewCellPainting; - - ChangeTheme(Controls); - } - - #endregion - - #region ColorTheme - - public void ChangeTheme (Control.ControlCollection container) - { - #region ApplyColorToAllControls - - foreach (Control component in container) - { - if (component.Controls != null && component.Controls.Count > 0) - { - ChangeTheme(component.Controls); - component.BackColor = ColorMode.BackgroundColor; - component.ForeColor = ColorMode.ForeColor; - } - else - { - component.BackColor = ColorMode.BackgroundColor; - component.ForeColor = ColorMode.ForeColor; - } - - } - - #endregion - - #region DataGridView - - BackColor = ColorMode.DockBackgroundColor; - - // Main DataGridView - bookmarkDataGridView.BackgroundColor = ColorMode.DockBackgroundColor; - bookmarkDataGridView.ColumnHeadersDefaultCellStyle.BackColor = ColorMode.BackgroundColor; - bookmarkDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = ColorMode.ForeColor; - bookmarkDataGridView.EnableHeadersVisualStyles = false; - - // Colors for menu - contextMenuStrip1.Renderer = new ExtendedMenuStripRenderer(); - - for (var y = 0; y < contextMenuStrip1.Items.Count; y++) - { - var item = contextMenuStrip1.Items[y]; - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - #endregion DataGridView } #endregion diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index 6ae4d6e3..e1ac9cfa 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -6,8 +6,6 @@ using LogExpert.Core.Entities; using LogExpert.Core.Interface; using LogExpert.Dialogs; -using LogExpert.UI.Extensions; -using LogExpert.UI.Extensions.Forms; using NLog; @@ -164,107 +162,6 @@ public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNu #endregion - #region ColorTheme - - [SupportedOSPlatform("windows")] - public void ChangeTheme (Control.ControlCollection container) - { - ColorMode.LoadColorMode(ConfigManager.Settings.Preferences.DarkMode); - NativeMethods.UseImmersiveDarkMode(Handle, ColorMode.DarkModeEnabled); - - #region ApplyColorToAllControls - foreach (Control component in container) - { - if (component.Controls != null && component.Controls.Count > 0) - { - ChangeTheme(component.Controls); - component.BackColor = ColorMode.BackgroundColor; - component.ForeColor = ColorMode.ForeColor; - } - else - { - component.BackColor = ColorMode.BackgroundColor; - component.ForeColor = ColorMode.ForeColor; - } - - if (component is MenuStrip menu) - { - foreach (ToolStripMenuItem item in menu.Items) - { - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.BackgroundColor; - - try - { - for (var x = 0; x < item.DropDownItems.Count; x++) - { - var children = item.DropDownItems[x]; - children.ForeColor = ColorMode.ForeColor; - children.BackColor = ColorMode.MenuBackgroundColor; - - if (children is ToolStripDropDownItem toolstripDropDownItem) - { - for (var y = 0; y < toolstripDropDownItem.DropDownItems.Count; y++) - { - var subChildren = toolstripDropDownItem.DropDownItems[y]; - subChildren.ForeColor = ColorMode.ForeColor; - subChildren.BackColor = ColorMode.MenuBackgroundColor; - } - } - } - } - catch (Exception ex) - { - _logger.Error(ex, "An error occured while applying style dynamically to all Controls under LogTabWindow:"); - } - } - } - } - #endregion - - // Colors for selected menus - mainMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - - // Dock special color - dockPanel.DockBackColor = ColorMode.DockBackgroundColor; - - // Remove toolstrip bottom border - buttonToolStrip.Renderer = new ToolStripRendererExtension(); - - #region Tabs - tabContextMenuStrip.Renderer = new ExtendedMenuStripRenderer(); - - // Tabs menu - for (var y = 0; y < tabContextMenuStrip.Items.Count; y++) - { - var item = tabContextMenuStrip.Items[y]; - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - // Tabs line - dockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = ColorMode.TabsBackgroundStripColor; - dockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = ColorMode.TabsBackgroundStripColor; - - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = ColorMode.TabsBackgroundStripColor; - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = ColorMode.TabsBackgroundStripColor; - - // Tabs - dockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = ColorMode.ActiveTabColor; - dockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = ColorMode.ActiveTabColor; - dockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = ColorMode.ForeColor; - - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = ColorMode.ActiveTabColor; - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = ColorMode.ActiveTabColor; - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = ColorMode.ForeColor; - - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = ColorMode.InactiveTabColor; - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = ColorMode.InactiveTabColor; - dockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = ColorMode.ForeColor; - #endregion Tabs - } - #endregion - #region Delegates private delegate void AddFileTabsDelegate (string[] fileNames); diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index c1f9c9e5..b0e783d6 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -1,7 +1,6 @@ using System.Runtime.Versioning; using LogExpert.Core.Classes.Highlight; -using LogExpert.Core.Config; using LogExpert.Core.Entities; using LogExpert.Dialogs; using LogExpert.UI.Controls; @@ -35,16 +34,16 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri return; } - ILogLine line = logPaintCtx.GetLogLine(rowIndex); + var line = logPaintCtx.GetLogLine(rowIndex); if (line != null) { - HighlightEntry entry = logPaintCtx.FindHighlightEntry(line, true); + var entry = logPaintCtx.FindHighlightEntry(line, true); e.Graphics.SetClip(e.CellBounds); if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - Color backColor = e.CellStyle.SelectionBackColor; + var backColor = e.CellStyle.SelectionBackColor; Brush brush; if (gridView.Focused) @@ -53,8 +52,7 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri } else { - var color = Color.FromArgb(255, 170, 170, 170); - brush = new SolidBrush(color); + brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray } e.Graphics.FillRectangle(brush, e.CellBounds); @@ -62,7 +60,8 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri } else { - Color bgColor = ColorMode.DockBackgroundColor; + var bgColor = Color.White; + if (!DebugOptions.DisableWordHighlight) { if (entry != null) @@ -93,7 +92,7 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri if (e.ColumnIndex == 0) { - Bookmark bookmark = logPaintCtx.GetBookmarkForLine(rowIndex); + var bookmark = logPaintCtx.GetBookmarkForLine(rowIndex); if (bookmark != null) { Rectangle r; // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); @@ -111,7 +110,7 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri }; Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - Font font = logPaintCtx.MonospacedFont; + var font = logPaintCtx.MonospacedFont; e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); brush2.Dispose(); } @@ -317,7 +316,7 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr { var value = e.Value ?? string.Empty; - IList matchList = logPaintCtx.FindHighlightMatches(value as ILogLine); + var matchList = logPaintCtx.FindHighlightMatches(value as ILogLine); // too many entries per line seem to cause problems with the GDI while (matchList.Count > 50) { @@ -356,8 +355,8 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr var leftPad = e.CellStyle.Padding.Left; RectangleF rect = new(e.CellBounds.Left + leftPad, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height); - Rectangle borderWidths = BorderWidths(e.AdvancedBorderStyle); - Rectangle valBounds = e.CellBounds; + var borderWidths = BorderWidths(e.AdvancedBorderStyle); + var valBounds = e.CellBounds; valBounds.Offset(borderWidths.X, borderWidths.Y); valBounds.Width -= borderWidths.Right; valBounds.Height -= borderWidths.Bottom; @@ -369,7 +368,7 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr } - TextFormatFlags flags = + var flags = TextFormatFlags.Left | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix @@ -383,15 +382,15 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr // TextFormatFlags.SingleLine //TextRenderer.DrawText(e.Graphics, e.Value as String, e.CellStyle.Font, valBounds, Color.FromKnownColor(KnownColor.Black), flags); - Point wordPos = valBounds.Location; + var wordPos = valBounds.Location; Size proposedSize = new(valBounds.Width, valBounds.Height); - Rectangle r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); + var r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); e.Graphics.SetClip(e.CellBounds); - foreach (HighlightMatchEntry matchEntry in matchList) + foreach (var matchEntry in matchList) { - Font font = matchEntry != null && matchEntry.HighlightEntry.IsBold + var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? logPaintCtx.BoldFont : logPaintCtx.NormalFont; @@ -408,11 +407,11 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr } } - Size wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); + var wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); wordSize.Height = e.CellBounds.Height; Rectangle wordRect = new(wordPos, wordSize); - Color foreColor = matchEntry.HighlightEntry.ForegroundColor; + var foreColor = matchEntry.HighlightEntry.ForegroundColor; if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) { if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) @@ -456,7 +455,7 @@ private static IList MergeHighlightMatchEntries (IList MergeHighlightMatchEntries (IList mergedList = []; if (entryArray.Length > 0) { - HighlightEntry currentEntry = entryArray[0]; + var currentEntry = entryArray[0]; var lastStartPos = 0; var pos = 0; for (; pos < entryArray.Length; ++pos) From d9512cb548b99287f74dee3e4791e27983b01289 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 09:02:46 +0200 Subject: [PATCH 02/26] more colors --- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 19 +++++++++---------- .../Dialogs/LogTabWindow/LogTabWindow.cs | 2 -- src/LogExpert.UI/Entities/PaintHelper.cs | 3 ++- .../Forms/LineToolStripSeparatorExtension.cs | 9 ++++----- 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 8653c766..2c5096e1 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -200,7 +200,7 @@ protected override void OnPaint (PaintEventArgs e) { if (!splitContainer1.Visible) { - Rectangle r = ClientRectangle; + var r = ClientRectangle; e.Graphics.FillRectangle(SystemBrushes.FromSystemColor(ColorMode.BookmarksDefaultBackgroundColor), r); StringFormat sf = new() @@ -229,9 +229,9 @@ private void SetFont (string fontName, float fontSize) bookmarkDataGridView.Refresh(); } - private void CommentPainting (BufferedDataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) + private void CommentPainting (BufferedDataGridView gridView, DataGridViewCellPaintingEventArgs e) { - Color backColor = ColorMode.DockBackgroundColor; + var backColor = e.CellStyle.SelectionBackColor; if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { @@ -244,8 +244,7 @@ private void CommentPainting (BufferedDataGridView gridView, int rowIndex, DataG else { // _logger.logDebug("CellPaint No Focus"); - var color = Color.FromArgb(255, 170, 170, 170); - brush = new SolidBrush(color); + brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray } e.Graphics.FillRectangle(brush, e.CellBounds); @@ -253,7 +252,7 @@ private void CommentPainting (BufferedDataGridView gridView, int rowIndex, DataG } else { - e.CellStyle.BackColor = backColor; + e.CellStyle.BackColor = Color.White; e.PaintBackground(e.CellBounds, false); } @@ -294,7 +293,7 @@ private void CurrentRowChanged (int rowIndex) } else { - Bookmark bookmark = bookmarkData.Bookmarks[rowIndex]; + var bookmark = bookmarkData.Bookmarks[rowIndex]; bookmarkTextBox.Text = bookmark.Text; bookmarkTextBox.Enabled = true; } @@ -362,7 +361,7 @@ private void OnBoomarkDataGridViewCellValueNeeded (object sender, DataGridViewCe return; } - Bookmark bookmarkForLine = bookmarkData.Bookmarks[e.RowIndex]; + var bookmarkForLine = bookmarkData.Bookmarks[e.RowIndex]; var lineNum = bookmarkForLine.LineNum; if (e.ColumnIndex == 1) { @@ -454,7 +453,7 @@ private void bookmarkTextBox_TextChanged (object sender, EventArgs e) return; } - Bookmark bookmark = bookmarkData.Bookmarks[rowIndex]; + var bookmark = bookmarkData.Bookmarks[rowIndex]; bookmark.Text = bookmarkTextBox.Text; logView?.RefreshLogView(); } @@ -488,7 +487,7 @@ private void bookmarkDataGridView_CellToolTipTextNeeded (object sender, return; } - Bookmark bookmark = bookmarkData.Bookmarks[e.RowIndex]; + var bookmark = bookmarkData.Bookmarks[e.RowIndex]; if (!string.IsNullOrEmpty(bookmark.Text)) { e.ToolTipText = bookmark.Text; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index e1ac9cfa..88889378 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -82,8 +82,6 @@ public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNu mainMenuStrip.Location = new Point(0, 0); externalToolsToolStrip.Location = new Point(0, 54); - ChangeTheme(Controls); - _startupFileNames = fileNames; _instanceNumber = instanceNumber; _showInstanceNumbers = showInstanceNumbers; diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index b0e783d6..b438a93a 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -336,7 +336,8 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr var he = new HighlightEntry { SearchText = column.FullValue, - ForegroundColor = groundEntry?.ForegroundColor ?? ColorMode.ForeColor, + //TODO change to white if the background color is darker + ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, IsRegEx = false, IsCaseSensitive = false, diff --git a/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs b/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs index 4e7d5752..134f8843 100644 --- a/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs +++ b/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs @@ -1,13 +1,11 @@ -using System.Runtime.Versioning; - -using LogExpert.Core.Config; +using System.Runtime.Versioning; namespace LogExpert.UI.Extensions.Forms; [SupportedOSPlatform("windows")] internal class LineToolStripSeparatorExtension : ToolStripSeparator { - public LineToolStripSeparatorExtension() + public LineToolStripSeparatorExtension () { Paint += OnExtendedToolStripSeparatorPaint; } @@ -21,7 +19,8 @@ private void OnExtendedToolStripSeparatorPaint (object sender, PaintEventArgs e) // Choose the colors for drawing. // I've used Color.White as the foreColor. - Color foreColor = ColorMode.ForeColor; + //TODO change to white if the background color is darker; + Color foreColor = Color.FromKnownColor(KnownColor.Black); // Color.Teal as the backColor. Color backColor = ColorMode.BackgroundColor; From 6b3d97d2f56cfaf8f5f069c1304ecee562e306fe Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 09:10:18 +0200 Subject: [PATCH 03/26] removing more darkmode stuff --- .../Controls/LogWindow/LogWindow.designer.cs | 29 ++-- .../LogTabWindow/LogTabWindow.designer.cs | 135 +++++++++--------- .../Forms/LineToolStripSeparatorExtension.cs | 35 ----- .../Extensions/Forms/MenuSelectedColors.cs | 31 ---- .../Extensions/Forms/MenuStripExtension.cs | 9 -- .../Forms/MenuToolStripSeparatorExtension.cs | 39 ----- .../Forms/ToolStripRendererExtension.cs | 15 -- 7 files changed, 81 insertions(+), 212 deletions(-) delete mode 100644 src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs delete mode 100644 src/LogExpert.UI/Extensions/Forms/MenuSelectedColors.cs delete mode 100644 src/LogExpert.UI/Extensions/Forms/MenuStripExtension.cs delete mode 100644 src/LogExpert.UI/Extensions/Forms/MenuToolStripSeparatorExtension.cs delete mode 100644 src/LogExpert.UI/Extensions/Forms/ToolStripRendererExtension.cs diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs index 27d15a90..c49e42bf 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs @@ -1,5 +1,4 @@ using LogExpert.Dialogs; -using LogExpert.UI.Extensions.Forms; using System; using System.Drawing; using System.IO; @@ -46,21 +45,21 @@ private void InitializeComponent() dataGridContextMenuStrip = new ContextMenuStrip(components); copyToolStripMenuItem = new ToolStripMenuItem(); copyToTabToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator1 = new MenuToolStripSeparatorExtension(); + menuToolStripSeparator1 = new ToolStripSeparator(); scrollAllTabsToTimestampToolStripMenuItem = new ToolStripMenuItem(); syncTimestampsToToolStripMenuItem = new ToolStripMenuItem(); freeThisWindowFromTimeSyncToolStripMenuItem = new ToolStripMenuItem(); locateLineInOriginalFileToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator2 = new MenuToolStripSeparatorExtension(); + menuToolStripSeparator2 = new ToolStripSeparator(); toggleBoomarkToolStripMenuItem = new ToolStripMenuItem(); bookmarkCommentToolStripMenuItem = new ToolStripMenuItem(); markEditModeToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator3 = new MenuToolStripSeparatorExtension(); + menuToolStripSeparator3 = new ToolStripSeparator(); tempHighlightsToolStripMenuItem = new ToolStripMenuItem(); removeAllToolStripMenuItem = new ToolStripMenuItem(); makePermanentToolStripMenuItem = new ToolStripMenuItem(); markCurrentFilterRangeToolStripMenuItem = new ToolStripMenuItem(); - pluginSeparator = new MenuToolStripSeparatorExtension(); + pluginSeparator = new ToolStripSeparator(); timeSpreadingControl = new TimeSpreadingControl(); advancedBackPanel = new Panel(); advancedFilterSplitContainer = new SplitContainer(); @@ -112,14 +111,14 @@ private void InitializeComponent() deleteBookmarksToolStripMenuItem = new ToolStripMenuItem(); columnContextMenuStrip = new ContextMenuStrip(components); freezeLeftColumnsUntilHereToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator4 = new MenuToolStripSeparatorExtension(); + menuToolStripSeparator4 = new ToolStripSeparator(); moveToLastColumnToolStripMenuItem = new ToolStripMenuItem(); moveLeftToolStripMenuItem = new ToolStripMenuItem(); moveRightToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator5 = new MenuToolStripSeparatorExtension(); + menuToolStripSeparator5 = new ToolStripSeparator(); hideColumnToolStripMenuItem = new ToolStripMenuItem(); restoreColumnsToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator6 = new MenuToolStripSeparatorExtension(); + menuToolStripSeparator6 = new ToolStripSeparator(); allColumnsToolStripMenuItem = new ToolStripMenuItem(); editModeContextMenuStrip = new ContextMenuStrip(components); editModecopyToolStripMenuItem = new ToolStripMenuItem(); @@ -1294,12 +1293,12 @@ private void InitializeComponent() private System.Windows.Forms.CheckBox filterCaseSensitiveCheckBox; private System.Windows.Forms.Button filterSearchButton; private System.Windows.Forms.Panel panelBackgroundAdvancedFilterSplitContainer; - private MenuToolStripSeparatorExtension pluginSeparator; - private MenuToolStripSeparatorExtension menuToolStripSeparator1; - private MenuToolStripSeparatorExtension menuToolStripSeparator2; - private MenuToolStripSeparatorExtension menuToolStripSeparator3; - private MenuToolStripSeparatorExtension menuToolStripSeparator4; - private MenuToolStripSeparatorExtension menuToolStripSeparator5; - private MenuToolStripSeparatorExtension menuToolStripSeparator6; + private ToolStripSeparator pluginSeparator; + private ToolStripSeparator menuToolStripSeparator1; + private ToolStripSeparator menuToolStripSeparator2; + private ToolStripSeparator menuToolStripSeparator3; + private ToolStripSeparator menuToolStripSeparator4; + private ToolStripSeparator menuToolStripSeparator5; + private ToolStripSeparator menuToolStripSeparator6; } } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs index 3821a872..88684eb7 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs @@ -1,7 +1,6 @@ -using System.Windows.Forms; +using System.Windows.Forms; using LogExpert.Core.Enums; using LogExpert.Dialogs; -using LogExpert.UI.Extensions.Forms; using WeifenLuo.WinFormsUI.Docking; namespace LogExpert.UI.Controls.LogTabWindow @@ -63,15 +62,15 @@ private void InitializeComponent() closeFileToolStripMenuItem = new ToolStripMenuItem(); reloadToolStripMenuItem = new ToolStripMenuItem(); newFromClipboardToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension1 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator1 = new ToolStripSeparator(); multiFileToolStripMenuItem = new ToolStripMenuItem(); multiFileEnabledStripMenuItem = new ToolStripMenuItem(); multifileMaskToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension2 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator2 = new ToolStripSeparator(); loadProjectToolStripMenuItem = new ToolStripMenuItem(); saveProjectToolStripMenuItem = new ToolStripMenuItem(); exportBookmarksToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension3 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator3 = new ToolStripSeparator(); lastUsedToolStripMenuItem = new ToolStripMenuItem(); exitToolStripMenuItem = new ToolStripMenuItem(); viewNavigateToolStripMenuItem = new ToolStripMenuItem(); @@ -84,35 +83,35 @@ private void InitializeComponent() jumpToPrevToolStripMenuItem = new ToolStripMenuItem(); showBookmarkListToolStripMenuItem = new ToolStripMenuItem(); columnFinderToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension5 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator5 = new ToolStripSeparator(); toolStripEncodingMenuItem = new ToolStripMenuItem(); toolStripEncodingASCIIItem = new ToolStripMenuItem(); toolStripEncodingANSIItem = new ToolStripMenuItem(); toolStripEncodingISO88591Item = new ToolStripMenuItem(); toolStripEncodingUTF8Item = new ToolStripMenuItem(); toolStripEncodingUTF16Item = new ToolStripMenuItem(); - menuToolStripSeparatorExtension6 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator6 = new ToolStripSeparator(); timeshiftToolStripMenuItem = new ToolStripMenuItem(); timeshiftMenuTextBox = new ToolStripTextBox(); - menuToolStripSeparatorExtension4 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator4 = new ToolStripSeparator(); copyMarkedLinesIntoNewTabToolStripMenuItem = new ToolStripMenuItem(); optionToolStripMenuItem = new ToolStripMenuItem(); columnizerToolStripMenuItem = new ToolStripMenuItem(); hilightingToolStripMenuItem1 = new ToolStripMenuItem(); - menuToolStripSeparatorExtension7 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator7 = new ToolStripSeparator(); settingsToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension9 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator9 = new ToolStripSeparator(); cellSelectModeToolStripMenuItem = new ToolStripMenuItem(); alwaysOnTopToolStripMenuItem = new ToolStripMenuItem(); hideLineColumnToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension8 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator8 = new ToolStripSeparator(); lockInstanceToolStripMenuItem = new ToolStripMenuItem(); toolsToolStripMenuItem = new ToolStripMenuItem(); configureToolStripMenuItem = new ToolStripMenuItem(); - configureToolStripSeparator = new MenuToolStripSeparatorExtension(); + configureToolStripSeparator = new ToolStripSeparator(); helpToolStripMenuItem = new ToolStripMenuItem(); showHelpToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension11 = new MenuToolStripSeparatorExtension(); + ToolStripSeparator11 = new ToolStripSeparator(); aboutToolStripMenuItem = new ToolStripMenuItem(); debugToolStripMenuItem = new ToolStripMenuItem(); dumpLogBufferInfoToolStripMenuItem = new ToolStripMenuItem(); @@ -133,18 +132,18 @@ private void InitializeComponent() externalToolsToolStrip = new ToolStrip(); buttonToolStrip = new ToolStrip(); toolStripButtonOpen = new ToolStripButton(); - lineToolStripSeparatorExtension1 = new LineToolStripSeparatorExtension(); + lineToolStripSeparatorExtension1 = new ToolStripSeparator(); toolStripButtonSearch = new ToolStripButton(); toolStripButtonFilter = new ToolStripButton(); - lineToolStripSeparatorExtension2 = new LineToolStripSeparatorExtension(); + lineToolStripSeparatorExtension2 = new ToolStripSeparator(); toolStripButtonBookmark = new ToolStripButton(); toolStripButtonUp = new ToolStripButton(); toolStripButtonDown = new ToolStripButton(); - lineToolStripSeparatorExtension3 = new LineToolStripSeparatorExtension(); + lineToolStripSeparatorExtension3 = new ToolStripSeparator(); toolStripButtonBubbles = new ToolStripButton(); - lineToolStripSeparatorExtension4 = new LineToolStripSeparatorExtension(); + lineToolStripSeparatorExtension4 = new ToolStripSeparator(); toolStripButtonTail = new ToolStripButton(); - lineToolStripSeparatorExtension5 = new LineToolStripSeparatorExtension(); + lineToolStripSeparatorExtension5 = new ToolStripSeparator(); groupsComboBoxHighlightGroups = new ToolStripComboBox(); checkBoxFollowTail = new CheckBox(); tabContextMenuStrip = new ContextMenuStrip(components); @@ -232,7 +231,7 @@ private void InitializeComponent() // // fileToolStripMenuItem // - fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { openToolStripMenuItem, openURIToolStripMenuItem, closeFileToolStripMenuItem, reloadToolStripMenuItem, newFromClipboardToolStripMenuItem, menuToolStripSeparatorExtension1, multiFileToolStripMenuItem, menuToolStripSeparatorExtension2, loadProjectToolStripMenuItem, saveProjectToolStripMenuItem, exportBookmarksToolStripMenuItem, menuToolStripSeparatorExtension3, lastUsedToolStripMenuItem, exitToolStripMenuItem }); + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { openToolStripMenuItem, openURIToolStripMenuItem, closeFileToolStripMenuItem, reloadToolStripMenuItem, newFromClipboardToolStripMenuItem, ToolStripSeparator1, multiFileToolStripMenuItem, ToolStripSeparator2, loadProjectToolStripMenuItem, saveProjectToolStripMenuItem, exportBookmarksToolStripMenuItem, ToolStripSeparator3, lastUsedToolStripMenuItem, exitToolStripMenuItem }); fileToolStripMenuItem.Name = "fileToolStripMenuItem"; fileToolStripMenuItem.Size = new System.Drawing.Size(37, 19); fileToolStripMenuItem.Text = "File"; @@ -284,10 +283,10 @@ private void InitializeComponent() newFromClipboardToolStripMenuItem.ToolTipText = "Creates a new tab with content from clipboard"; newFromClipboardToolStripMenuItem.Click += OnNewFromClipboardToolStripMenuItemClick; // - // menuToolStripSeparatorExtension1 + // ToolStripSeparator1 // - menuToolStripSeparatorExtension1.Name = "menuToolStripSeparatorExtension1"; - menuToolStripSeparatorExtension1.Size = new System.Drawing.Size(250, 6); + ToolStripSeparator1.Name = "ToolStripSeparator1"; + ToolStripSeparator1.Size = new System.Drawing.Size(250, 6); // // multiFileToolStripMenuItem // @@ -318,10 +317,10 @@ private void InitializeComponent() multifileMaskToolStripMenuItem.Text = "File name mask..."; multifileMaskToolStripMenuItem.Click += OnMultiFileMaskToolStripMenuItemClick; // - // menuToolStripSeparatorExtension2 + // ToolStripSeparator2 // - menuToolStripSeparatorExtension2.Name = "menuToolStripSeparatorExtension2"; - menuToolStripSeparatorExtension2.Size = new System.Drawing.Size(250, 6); + ToolStripSeparator2.Name = "ToolStripSeparator2"; + ToolStripSeparator2.Size = new System.Drawing.Size(250, 6); // // loadProjectToolStripMenuItem // @@ -347,10 +346,10 @@ private void InitializeComponent() exportBookmarksToolStripMenuItem.ToolTipText = "Write a list of bookmarks and their comments to a CSV file"; exportBookmarksToolStripMenuItem.Click += OnExportBookmarksToolStripMenuItemClick; // - // menuToolStripSeparatorExtension3 + // ToolStripSeparator3 // - menuToolStripSeparatorExtension3.Name = "menuToolStripSeparatorExtension3"; - menuToolStripSeparatorExtension3.Size = new System.Drawing.Size(250, 6); + ToolStripSeparator3.Name = "ToolStripSeparator3"; + ToolStripSeparator3.Size = new System.Drawing.Size(250, 6); // // lastUsedToolStripMenuItem // @@ -369,7 +368,7 @@ private void InitializeComponent() // // viewNavigateToolStripMenuItem // - viewNavigateToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { goToLineToolStripMenuItem, searchToolStripMenuItem, filterToolStripMenuItem, bookmarksToolStripMenuItem, columnFinderToolStripMenuItem, menuToolStripSeparatorExtension5, toolStripEncodingMenuItem, menuToolStripSeparatorExtension6, timeshiftToolStripMenuItem, timeshiftMenuTextBox, menuToolStripSeparatorExtension4, copyMarkedLinesIntoNewTabToolStripMenuItem }); + viewNavigateToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { goToLineToolStripMenuItem, searchToolStripMenuItem, filterToolStripMenuItem, bookmarksToolStripMenuItem, columnFinderToolStripMenuItem, ToolStripSeparator5, toolStripEncodingMenuItem, ToolStripSeparator6, timeshiftToolStripMenuItem, timeshiftMenuTextBox, ToolStripSeparator4, copyMarkedLinesIntoNewTabToolStripMenuItem }); viewNavigateToolStripMenuItem.Name = "viewNavigateToolStripMenuItem"; viewNavigateToolStripMenuItem.Size = new System.Drawing.Size(96, 19); viewNavigateToolStripMenuItem.Text = "View/Navigate"; @@ -458,10 +457,10 @@ private void InitializeComponent() columnFinderToolStripMenuItem.Text = "Column finder"; columnFinderToolStripMenuItem.Click += OnColumnFinderToolStripMenuItemClick; // - // menuToolStripSeparatorExtension5 + // ToolStripSeparator5 // - menuToolStripSeparatorExtension5.Name = "menuToolStripSeparatorExtension5"; - menuToolStripSeparatorExtension5.Size = new System.Drawing.Size(186, 6); + ToolStripSeparator5.Name = "ToolStripSeparator5"; + ToolStripSeparator5.Size = new System.Drawing.Size(186, 6); // // toolStripEncodingMenuItem // @@ -517,10 +516,10 @@ private void InitializeComponent() toolStripEncodingUTF16Item.Text = "Unicode"; toolStripEncodingUTF16Item.Click += OnUTF16ToolStripMenuItemClick; // - // menuToolStripSeparatorExtension6 + // ToolStripSeparator6 // - menuToolStripSeparatorExtension6.Name = "menuToolStripSeparatorExtension6"; - menuToolStripSeparatorExtension6.Size = new System.Drawing.Size(186, 6); + ToolStripSeparator6.Name = "ToolStripSeparator6"; + ToolStripSeparator6.Size = new System.Drawing.Size(186, 6); // // timeshiftToolStripMenuItem // @@ -542,10 +541,10 @@ private void InitializeComponent() timeshiftMenuTextBox.ToolTipText = "Time offset (hh:mm:ss.fff)"; timeshiftMenuTextBox.KeyDown += OnTimeShiftMenuTextBoxKeyDown; // - // menuToolStripSeparatorExtension4 + // ToolStripSeparator4 // - menuToolStripSeparatorExtension4.Name = "menuToolStripSeparatorExtension4"; - menuToolStripSeparatorExtension4.Size = new System.Drawing.Size(186, 6); + ToolStripSeparator4.Name = "ToolStripSeparator4"; + ToolStripSeparator4.Size = new System.Drawing.Size(186, 6); // // copyMarkedLinesIntoNewTabToolStripMenuItem // @@ -558,7 +557,7 @@ private void InitializeComponent() // // optionToolStripMenuItem // - optionToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { columnizerToolStripMenuItem, hilightingToolStripMenuItem1, menuToolStripSeparatorExtension7, settingsToolStripMenuItem, menuToolStripSeparatorExtension9, cellSelectModeToolStripMenuItem, alwaysOnTopToolStripMenuItem, hideLineColumnToolStripMenuItem, menuToolStripSeparatorExtension8, lockInstanceToolStripMenuItem }); + optionToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { columnizerToolStripMenuItem, hilightingToolStripMenuItem1, ToolStripSeparator7, settingsToolStripMenuItem, ToolStripSeparator9, cellSelectModeToolStripMenuItem, alwaysOnTopToolStripMenuItem, hideLineColumnToolStripMenuItem, ToolStripSeparator8, lockInstanceToolStripMenuItem }); optionToolStripMenuItem.Name = "optionToolStripMenuItem"; optionToolStripMenuItem.Size = new System.Drawing.Size(61, 19); optionToolStripMenuItem.Text = "Options"; @@ -579,10 +578,10 @@ private void InitializeComponent() hilightingToolStripMenuItem1.Text = "Highlighting and triggers..."; hilightingToolStripMenuItem1.Click += OnHighlightingToolStripMenuItemClick; // - // menuToolStripSeparatorExtension7 + // ToolStripSeparator7 // - menuToolStripSeparatorExtension7.Name = "menuToolStripSeparatorExtension7"; - menuToolStripSeparatorExtension7.Size = new System.Drawing.Size(221, 6); + ToolStripSeparator7.Name = "ToolStripSeparator7"; + ToolStripSeparator7.Size = new System.Drawing.Size(221, 6); // // settingsToolStripMenuItem // @@ -592,10 +591,10 @@ private void InitializeComponent() settingsToolStripMenuItem.Text = "Settings..."; settingsToolStripMenuItem.Click += OnSettingsToolStripMenuItemClick; // - // menuToolStripSeparatorExtension9 + // ToolStripSeparator9 // - menuToolStripSeparatorExtension9.Name = "menuToolStripSeparatorExtension9"; - menuToolStripSeparatorExtension9.Size = new System.Drawing.Size(221, 6); + ToolStripSeparator9.Name = "ToolStripSeparator9"; + ToolStripSeparator9.Size = new System.Drawing.Size(221, 6); // // cellSelectModeToolStripMenuItem // @@ -622,10 +621,10 @@ private void InitializeComponent() hideLineColumnToolStripMenuItem.Text = "Hide line column"; hideLineColumnToolStripMenuItem.Click += OnHideLineColumnToolStripMenuItemClick; // - // menuToolStripSeparatorExtension8 + // ToolStripSeparator8 // - menuToolStripSeparatorExtension8.Name = "menuToolStripSeparatorExtension8"; - menuToolStripSeparatorExtension8.Size = new System.Drawing.Size(221, 6); + ToolStripSeparator8.Name = "ToolStripSeparator8"; + ToolStripSeparator8.Size = new System.Drawing.Size(221, 6); // // lockInstanceToolStripMenuItem // @@ -658,7 +657,7 @@ private void InitializeComponent() // // helpToolStripMenuItem // - helpToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { showHelpToolStripMenuItem, menuToolStripSeparatorExtension11, aboutToolStripMenuItem }); + helpToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { showHelpToolStripMenuItem, ToolStripSeparator11, aboutToolStripMenuItem }); helpToolStripMenuItem.Name = "helpToolStripMenuItem"; helpToolStripMenuItem.Size = new System.Drawing.Size(44, 19); helpToolStripMenuItem.Text = "Help"; @@ -671,10 +670,10 @@ private void InitializeComponent() showHelpToolStripMenuItem.Text = "Show help"; showHelpToolStripMenuItem.Click += OnShowHelpToolStripMenuItemClick; // - // menuToolStripSeparatorExtension11 + // ToolStripSeparator11 // - menuToolStripSeparatorExtension11.Name = "menuToolStripSeparatorExtension11"; - menuToolStripSeparatorExtension11.Size = new System.Drawing.Size(145, 6); + ToolStripSeparator11.Name = "ToolStripSeparator11"; + ToolStripSeparator11.Size = new System.Drawing.Size(145, 6); // // aboutToolStripMenuItem // @@ -1273,22 +1272,22 @@ private void InitializeComponent() private ToolStripMenuItem columnFinderToolStripMenuItem; private DockPanel dockPanel; private ToolStripMenuItem tabRenameToolStripMenuItem; - private LineToolStripSeparatorExtension lineToolStripSeparatorExtension1; - private LineToolStripSeparatorExtension lineToolStripSeparatorExtension2; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension1; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension2; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension3; - private LineToolStripSeparatorExtension lineToolStripSeparatorExtension3; - private LineToolStripSeparatorExtension lineToolStripSeparatorExtension4; - private LineToolStripSeparatorExtension lineToolStripSeparatorExtension5; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension5; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension6; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension4; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension7; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension9; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension8; - private MenuToolStripSeparatorExtension configureToolStripSeparator; - private MenuToolStripSeparatorExtension menuToolStripSeparatorExtension11; + private ToolStripSeparator lineToolStripSeparatorExtension1; + private ToolStripSeparator lineToolStripSeparatorExtension2; + private ToolStripSeparator ToolStripSeparator1; + private ToolStripSeparator ToolStripSeparator2; + private ToolStripSeparator ToolStripSeparator3; + private ToolStripSeparator lineToolStripSeparatorExtension3; + private ToolStripSeparator lineToolStripSeparatorExtension4; + private ToolStripSeparator lineToolStripSeparatorExtension5; + private ToolStripSeparator ToolStripSeparator5; + private ToolStripSeparator ToolStripSeparator6; + private ToolStripSeparator ToolStripSeparator4; + private ToolStripSeparator ToolStripSeparator7; + private ToolStripSeparator ToolStripSeparator9; + private ToolStripSeparator ToolStripSeparator8; + private ToolStripSeparator configureToolStripSeparator; + private ToolStripSeparator ToolStripSeparator11; } } diff --git a/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs b/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs deleted file mode 100644 index 134f8843..00000000 --- a/src/LogExpert.UI/Extensions/Forms/LineToolStripSeparatorExtension.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Runtime.Versioning; - -namespace LogExpert.UI.Extensions.Forms; - -[SupportedOSPlatform("windows")] -internal class LineToolStripSeparatorExtension : ToolStripSeparator -{ - public LineToolStripSeparatorExtension () - { - Paint += OnExtendedToolStripSeparatorPaint; - } - - private void OnExtendedToolStripSeparatorPaint (object sender, PaintEventArgs e) - { - // Get the separator's width and height. - var toolStripSeparator = (ToolStripSeparator)sender; - var width = toolStripSeparator.Width; - var height = toolStripSeparator.Height; - - // Choose the colors for drawing. - // I've used Color.White as the foreColor. - //TODO change to white if the background color is darker; - Color foreColor = Color.FromKnownColor(KnownColor.Black); - // Color.Teal as the backColor. - Color backColor = ColorMode.BackgroundColor; - - // Fill the background. - using SolidBrush backbrush = new(backColor); - e.Graphics.FillRectangle(backbrush, 0, 0, width, height); - - // Draw the line. - using Pen pen = new(foreColor); - e.Graphics.DrawLine(pen, width / 2, 4, width / 2, height - 4); - } -} diff --git a/src/LogExpert.UI/Extensions/Forms/MenuSelectedColors.cs b/src/LogExpert.UI/Extensions/Forms/MenuSelectedColors.cs deleted file mode 100644 index bc3544e5..00000000 --- a/src/LogExpert.UI/Extensions/Forms/MenuSelectedColors.cs +++ /dev/null @@ -1,31 +0,0 @@ -using LogExpert.Core.Config; - -using System.Runtime.Versioning; - -namespace LogExpert.UI.Extensions.Forms; - -[SupportedOSPlatform("windows")] -internal class MenuSelectedColors : ProfessionalColorTable -{ - public override Color ImageMarginGradientBegin => ColorMode.MenuBackgroundColor; - - public override Color ImageMarginGradientMiddle => ColorMode.MenuBackgroundColor; - - public override Color ImageMarginGradientEnd => ColorMode.MenuBackgroundColor; - - public override Color ToolStripDropDownBackground => ColorMode.MenuBackgroundColor; - - public override Color MenuBorder => ColorMode.MenuBackgroundColor; - - public override Color MenuItemBorder => ColorMode.MenuBackgroundColor; - - public override Color MenuItemSelected => ColorMode.HoverMenuBackgroundColor; - - public override Color MenuItemSelectedGradientBegin => ColorMode.HoverMenuBackgroundColor; - - public override Color MenuItemSelectedGradientEnd => ColorMode.HoverMenuBackgroundColor; - - public override Color MenuItemPressedGradientBegin => ColorMode.MenuBackgroundColor; - - public override Color MenuItemPressedGradientEnd => ColorMode.MenuBackgroundColor; -} \ No newline at end of file diff --git a/src/LogExpert.UI/Extensions/Forms/MenuStripExtension.cs b/src/LogExpert.UI/Extensions/Forms/MenuStripExtension.cs deleted file mode 100644 index e54a1796..00000000 --- a/src/LogExpert.UI/Extensions/Forms/MenuStripExtension.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Runtime.Versioning; - -namespace LogExpert.UI.Extensions.Forms; - -[SupportedOSPlatform("windows")] -internal class ExtendedMenuStripRenderer : ToolStripProfessionalRenderer -{ - public ExtendedMenuStripRenderer() : base(new MenuSelectedColors()) { } -} diff --git a/src/LogExpert.UI/Extensions/Forms/MenuToolStripSeparatorExtension.cs b/src/LogExpert.UI/Extensions/Forms/MenuToolStripSeparatorExtension.cs deleted file mode 100644 index 3f5f26f1..00000000 --- a/src/LogExpert.UI/Extensions/Forms/MenuToolStripSeparatorExtension.cs +++ /dev/null @@ -1,39 +0,0 @@ -using LogExpert.Core.Config; - -using System.Runtime.Versioning; - -namespace LogExpert.UI.Extensions.Forms; - -[SupportedOSPlatform("windows")] -internal class MenuToolStripSeparatorExtension : ToolStripSeparator -{ - public MenuToolStripSeparatorExtension() - { - Paint += OnExtendedToolStripSeparatorPaint; - } - - private void OnExtendedToolStripSeparatorPaint(object? sender, PaintEventArgs e) - { - if (sender == null) - { - return; - } - - // Get the separator's width and height. - var toolStripSeparator = sender as ToolStripSeparator; - var width = toolStripSeparator.Width; - var height = toolStripSeparator.Height; - - // Choose the colors for drawing. - // I've used Color.White as the foreColor. - Color foreColor = ColorMode.ForeColor; - // Color.Teal as the backColor. - Color backColor = ColorMode.MenuBackgroundColor; - - // Fill the background. - e.Graphics.FillRectangle(new SolidBrush(backColor), 0, 0, width, height); - - // Draw the line. - e.Graphics.DrawLine(new Pen(foreColor), 4, height / 2, width - 4, height / 2); - } -} diff --git a/src/LogExpert.UI/Extensions/Forms/ToolStripRendererExtension.cs b/src/LogExpert.UI/Extensions/Forms/ToolStripRendererExtension.cs deleted file mode 100644 index 191d5988..00000000 --- a/src/LogExpert.UI/Extensions/Forms/ToolStripRendererExtension.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Runtime.Versioning; - -namespace LogExpert.UI.Extensions.Forms; - -[SupportedOSPlatform("windows")] -internal class ToolStripRendererExtension : ToolStripSystemRenderer -{ - public ToolStripRendererExtension() { } - - protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) - { - // Commented on purpose to avoid drawing the border that appears visible in Dark Mode (not visible in Bright mode) - //base.OnRenderToolStripBorder(e); - } -} From a00f7ef4a7b7fa04f603d484e00330e33b3967b6 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 09:15:10 +0200 Subject: [PATCH 04/26] completed removing dark mode --- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 2c5096e1..54e0f11e 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -72,14 +72,17 @@ public void SetColumnizer (ILogLineColumnizer columnizer) bookmarkDataGridView.Columns[0].Width = 20; } - DataGridViewTextBoxColumn commentColumn = new(); - commentColumn.HeaderText = "Bookmark Comment"; - commentColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; - commentColumn.Resizable = DataGridViewTriState.NotSet; - commentColumn.DividerWidth = 1; - commentColumn.ReadOnly = true; - commentColumn.Width = 250; - commentColumn.MinimumWidth = 130; + DataGridViewTextBoxColumn commentColumn = new() + { + HeaderText = "Bookmark Comment", + AutoSizeMode = DataGridViewAutoSizeColumnMode.None, + Resizable = DataGridViewTriState.NotSet, + DividerWidth = 1, + ReadOnly = true, + Width = 250, + MinimumWidth = 130 + }; + bookmarkDataGridView.Columns.Insert(1, commentColumn); ShowCommentColumn(commentColumnCheckBox.Checked); ResizeColumns(); @@ -111,6 +114,7 @@ public void UpdateView () public void BookmarkTextChanged (Bookmark bookmark) { var rowIndex = bookmarkDataGridView.CurrentCellAddress.Y; + if (rowIndex == -1) { return; @@ -201,7 +205,7 @@ protected override void OnPaint (PaintEventArgs e) if (!splitContainer1.Visible) { var r = ClientRectangle; - e.Graphics.FillRectangle(SystemBrushes.FromSystemColor(ColorMode.BookmarksDefaultBackgroundColor), r); + e.Graphics.FillRectangle(SystemBrushes.ControlLight, r); StringFormat sf = new() { From f768551c2abe5780a62c1db0236fb37d0264ea3c Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 10:16:18 +0200 Subject: [PATCH 05/26] optimizations --- src/LogExpert.Core/Config/ColorEntry.cs | 16 +- .../Controls/BufferedDataGridView.cs | 36 ++--- src/LogExpert.UI/Controls/ColorComboBox.cs | 42 ++--- .../Controls/LogWindow/LogWindow.cs | 2 +- .../LogWindow/LogWindowEventHandlers.cs | 53 +++--- .../Controls/LogWindow/LogWindowPrivate.cs | 152 +++++++++--------- .../Controls/LogWindow/LogWindowPublic.cs | 2 +- .../LogWindow/PatternWindow.Designer.cs | 22 +-- .../Controls/LogWindow/PatternWindow.cs | 97 +++++------ .../LogWindow/TimeSpreadigControl.Designer.cs | 12 +- .../Controls/LogWindow/TimeSpreadigControl.cs | 46 +++--- .../Dialogs/BookmarkWindow.Designer.cs | 32 ++-- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 34 ++-- .../LogTabWindow/LogTabWindowPrivate.cs | 78 +++++---- src/LogExpert.UI/Entities/PaintHelper.cs | 1 - 15 files changed, 306 insertions(+), 319 deletions(-) diff --git a/src/LogExpert.Core/Config/ColorEntry.cs b/src/LogExpert.Core/Config/ColorEntry.cs index ceeaf244..521f2ae7 100644 --- a/src/LogExpert.Core/Config/ColorEntry.cs +++ b/src/LogExpert.Core/Config/ColorEntry.cs @@ -7,21 +7,11 @@ namespace LogExpert.Core.Config; [Serializable] -public class ColorEntry +public class ColorEntry (string fileName, Color color) { - #region cTor + public Color Color { get; } = color; - public ColorEntry(string fileName, Color color) - { - FileName = fileName; - Color = color; - } - - #endregion - - public Color Color { get; } - - public string FileName { get; } + public string FileName { get; } = fileName; #region Fields diff --git a/src/LogExpert.UI/Controls/BufferedDataGridView.cs b/src/LogExpert.UI/Controls/BufferedDataGridView.cs index cc249ece..41f6da11 100644 --- a/src/LogExpert.UI/Controls/BufferedDataGridView.cs +++ b/src/LogExpert.UI/Controls/BufferedDataGridView.cs @@ -17,13 +17,13 @@ internal partial class BufferedDataGridView : DataGridView private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly Brush _brush; - private readonly Color _bubbleColor = Color.FromArgb(160, 250, 250, 0); + private readonly Color _bubbleColor = Color.FromArgb(160, 250, 250, 0); //yellow private readonly Font _font = new("Arial", 10); private readonly SortedList _overlayList = []; private readonly Pen _pen; - private readonly Brush _textBrush = new SolidBrush(Color.FromArgb(200, 0, 0, 90)); + private readonly Brush _textBrush = new SolidBrush(Color.FromArgb(200, 0, 0, 90)); //dark blue private BookmarkOverlay _draggedOverlay; private Point _dragStartPoint; @@ -46,15 +46,9 @@ public BufferedDataGridView () #endregion - #region Delegates - - public delegate void OverlayDoubleClickedEventHandler (object sender, OverlayEventArgs e); - - #endregion - #region Events - public event OverlayDoubleClickedEventHandler OverlayDoubleClicked; + public event EventHandler OverlayDoubleClicked; #endregion @@ -112,15 +106,15 @@ protected override void OnEditingControlShowing (DataGridViewEditingControlShowi e.Control.KeyDown -= OnControlKeyDown; e.Control.KeyDown += OnControlKeyDown; var editControl = (DataGridViewTextBoxEditingControl)e.Control; - e.Control.PreviewKeyDown -= Control_PreviewKeyDown; - e.Control.PreviewKeyDown += Control_PreviewKeyDown; + e.Control.PreviewKeyDown -= OnControlPreviewKeyDown; + e.Control.PreviewKeyDown += OnControlPreviewKeyDown; editControl.ContextMenuStrip = EditModeMenuStrip; } protected override void OnMouseDown (MouseEventArgs e) { - BookmarkOverlay overlay = GetOverlayForPosition(e.Location); + var overlay = GetOverlayForPosition(e.Location); if (overlay != null) { if (e.Button == MouseButtons.Right) @@ -171,7 +165,7 @@ protected override void OnMouseMove (MouseEventArgs e) } else { - BookmarkOverlay overlay = GetOverlayForPosition(e.Location); + var overlay = GetOverlayForPosition(e.Location); Cursor = overlay != null ? Cursors.Hand : Cursors.Default; base.OnMouseMove(e); } @@ -179,7 +173,7 @@ protected override void OnMouseMove (MouseEventArgs e) protected override void OnMouseDoubleClick (MouseEventArgs e) { - BookmarkOverlay overlay = GetOverlayForPosition(e.Location); + var overlay = GetOverlayForPosition(e.Location); if (overlay != null) { if (e.Button == MouseButtons.Left) @@ -201,7 +195,7 @@ private BookmarkOverlay GetOverlayForPosition (Point pos) { lock (_overlayList) { - foreach (BookmarkOverlay overlay in _overlayList.Values) + foreach (var overlay in _overlayList.Values) { if (overlay.BubbleRect.Contains(pos)) { @@ -215,9 +209,9 @@ private BookmarkOverlay GetOverlayForPosition (Point pos) private void PaintOverlays (PaintEventArgs e) { - BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current; + var currentContext = BufferedGraphicsManager.Current; - using BufferedGraphics myBuffer = currentContext.Allocate(CreateGraphics(), ClientRectangle); + using var myBuffer = currentContext.Allocate(CreateGraphics(), ClientRectangle); lock (_overlayList) { _overlayList.Clear(); @@ -246,9 +240,9 @@ private void PaintOverlays (PaintEventArgs e) lock (_overlayList) { - foreach (BookmarkOverlay overlay in _overlayList.Values) + foreach (var overlay in _overlayList.Values) { - SizeF textSize = myBuffer.Graphics.MeasureString(overlay.Bookmark.Text, _font, 300); + var textSize = myBuffer.Graphics.MeasureString(overlay.Bookmark.Text, _font, 300); Rectangle rectBubble = new(overlay.Position, new Size((int)textSize.Width, (int)textSize.Height)); rectBubble.Offset(60, -(rectBubble.Height + 40)); rectBubble.Inflate(3, 3); @@ -277,7 +271,7 @@ private void PaintOverlays (PaintEventArgs e) #region Events handler - private void Control_PreviewKeyDown (object sender, PreviewKeyDownEventArgs e) + private void OnControlPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) { if ((e.KeyCode == Keys.C || e.KeyCode == Keys.Insert) && e.Control) { @@ -290,7 +284,7 @@ private void Control_PreviewKeyDown (object sender, PreviewKeyDownEventArgs e) private void OnControlKeyDown (object sender, KeyEventArgs e) { - if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) + if (e.KeyCode is Keys.Up or Keys.Down) { if (EditingControl != null) { diff --git a/src/LogExpert.UI/Controls/ColorComboBox.cs b/src/LogExpert.UI/Controls/ColorComboBox.cs index 71feb634..40ea6d4d 100644 --- a/src/LogExpert.UI/Controls/ColorComboBox.cs +++ b/src/LogExpert.UI/Controls/ColorComboBox.cs @@ -1,4 +1,4 @@ -using System.Drawing.Drawing2D; +using System.Drawing.Drawing2D; using System.Runtime.Versioning; namespace LogExpert.UI.Controls; @@ -14,31 +14,31 @@ internal class ColorComboBox : ComboBox #region cTor - public ColorComboBox() + public ColorComboBox () { DrawMode = DrawMode.OwnerDrawFixed; DrawItem += OnColorComboBoxDrawItem; // add color presets if (!DesignMode) { - Items.Add(_customColor); - Items.Add(Color.Black); - Items.Add(Color.White); - Items.Add(Color.Gray); - Items.Add(Color.DarkGray); - Items.Add(Color.Blue); - Items.Add(Color.LightBlue); - Items.Add(Color.DarkBlue); - Items.Add(Color.Green); - Items.Add(Color.LightGreen); - Items.Add(Color.DarkGreen); - Items.Add(Color.Olive); - Items.Add(Color.Red); - Items.Add(Color.Pink); - Items.Add(Color.Purple); - Items.Add(Color.IndianRed); - Items.Add(Color.DarkCyan); - Items.Add(Color.Yellow); + _ = Items.Add(_customColor); + _ = Items.Add(Color.Black); + _ = Items.Add(Color.White); + _ = Items.Add(Color.Gray); + _ = Items.Add(Color.DarkGray); + _ = Items.Add(Color.Blue); + _ = Items.Add(Color.LightBlue); + _ = Items.Add(Color.DarkBlue); + _ = Items.Add(Color.Green); + _ = Items.Add(Color.LightGreen); + _ = Items.Add(Color.DarkGreen); + _ = Items.Add(Color.Olive); + _ = Items.Add(Color.Red); + _ = Items.Add(Color.Pink); + _ = Items.Add(Color.Purple); + _ = Items.Add(Color.IndianRed); + _ = Items.Add(Color.DarkCyan); + _ = Items.Add(Color.Yellow); } } @@ -63,7 +63,7 @@ public Color CustomColor #region Events handler - private void OnColorComboBoxDrawItem(object sender, DrawItemEventArgs e) + private void OnColorComboBoxDrawItem (object sender, DrawItemEventArgs e) { e.DrawBackground(); if (e.Index >= 0) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index f755c20e..eb2c9b96 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -160,7 +160,7 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp ForcePersistenceLoading = forcePersistenceLoading; dataGridView.CellValueNeeded += OnDataGridViewCellValueNeeded; - dataGridView.CellPainting += OnDataGridView_CellPainting; + dataGridView.CellPainting += OnDataGridViewCellPainting; filterGridView.CellValueNeeded += OnFilterGridViewCellValueNeeded; filterGridView.CellPainting += OnFilterGridViewCellPainting; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index 2b8e367a..245a18e7 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -276,11 +276,11 @@ private void OnDataGridViewCellValuePushed (object sender, DataGridViewCellValue return; } - ILogLine line = _logFileReader.GetLogLine(e.RowIndex); + var line = _logFileReader.GetLogLine(e.RowIndex); var offset = CurrentColumnizer.GetTimeOffset(); CurrentColumnizer.SetTimeOffset(0); ColumnizerCallbackObject.SetLineNum(e.RowIndex); - IColumnizedLogLine cols = CurrentColumnizer.SplitLine(ColumnizerCallbackObject, line); + var cols = CurrentColumnizer.SplitLine(ColumnizerCallbackObject, line); CurrentColumnizer.SetTimeOffset(offset); if (cols.ColumnValues.Length <= e.ColumnIndex - 2) { @@ -392,11 +392,11 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti } var lineNum = _filterResultList[e.RowIndex]; - ILogLine line = _logFileReader.GetLogLineWithWait(lineNum).Result; + var line = _logFileReader.GetLogLineWithWait(lineNum).Result; if (line != null) { - HighlightEntry entry = FindFirstNoWordMatchHilightEntry(line); + var entry = FindFirstNoWordMatchHilightEntry(line); e.Graphics.SetClip(e.CellBounds); if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { @@ -407,8 +407,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti } else { - var color = Color.FromArgb(255, 170, 170, 170); - brush = new SolidBrush(color); + brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray } e.Graphics.FillRectangle(brush, e.CellBounds); @@ -416,7 +415,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti } else { - Color bgColor = Color.White; + var bgColor = Color.White; // paint direct filter hits with different bg color //if (this.filterParams.SpreadEnabled && this.filterHitList.Contains(lineNum)) //{ @@ -461,7 +460,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti e.Graphics.FillRectangle(brush, r); brush.Dispose(); - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); + var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); if (bookmark.Text.Length > 0) { @@ -845,8 +844,8 @@ private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e var isAdded = false; if (PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins.Count > 0) { - IList lines = GetSelectedContent(); - foreach (IContextMenuEntry entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) + var lines = GetSelectedContent(); + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) { LogExpertCallback callback = new(this); var menuText = entry.GetMenuText(lines.Count, CurrentColumnizer, callback.GetLogLine(lines[0])); @@ -859,7 +858,7 @@ private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e menuText = menuText[1..]; } - ToolStripItem item = dataGridContextMenuStrip.Items.Add(menuText, null, OnHandlePluginContextMenu); + var item = dataGridContextMenuStrip.Items.Add(menuText, null, OnHandlePluginContextMenu); item.Tag = new ContextMenuPluginEventArgs(entry, lines, CurrentColumnizer, callback); item.Enabled = !disabled; isAdded = true; @@ -876,13 +875,13 @@ private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e if (CurrentColumnizer.IsTimeshiftImplemented()) { - IList list = _parentLogTabWin.GetListOfOpenFiles(); + var list = _parentLogTabWin.GetListOfOpenFiles(); syncTimestampsToToolStripMenuItem.Enabled = true; syncTimestampsToToolStripMenuItem.DropDownItems.Clear(); EventHandler ev = OnHandleSyncContextMenu; Font italicFont = new(syncTimestampsToToolStripMenuItem.Font.FontFamily, syncTimestampsToToolStripMenuItem.Font.Size, FontStyle.Italic); - foreach (WindowFileEntry fileEntry in list) + foreach (var fileEntry in list) { if (fileEntry.LogWindow != this) { @@ -914,7 +913,7 @@ private void OnHandlePluginContextMenu (object sender, EventArgs args) if (sender is ToolStripItem item) { var menuArgs = item.Tag as ContextMenuPluginEventArgs; - IList logLines = menuArgs.LogLines; + var logLines = menuArgs.LogLines; menuArgs.Entry.MenuSelected(logLines.Count, menuArgs.Columnizer, menuArgs.Callback.GetLogLine(logLines[0])); } } @@ -958,7 +957,7 @@ private void OnScrollAllTabsToTimestampToolStripMenuItemClick (object sender, Ev if (currentLine > 0 && currentLine < dataGridView.RowCount) { var lineNum = currentLine; - DateTime timeStamp = GetTimestampForLine(ref lineNum, false); + var timeStamp = GetTimestampForLine(ref lineNum, false); if (timeStamp.Equals(DateTime.MinValue)) // means: invalid { return; @@ -1083,7 +1082,7 @@ private void OnFilterGridViewCellContextMenuStripNeeded (object sender, DataGrid [SupportedOSPlatform("windows")] private void OnColumnContextMenuStripOpening (object sender, CancelEventArgs e) { - Control ctl = columnContextMenuStrip.SourceControl; + var ctl = columnContextMenuStrip.SourceControl; var gridView = ctl as BufferedDataGridView; var frozen = false; if (_freezeStateMap.TryGetValue(ctl, out var value)) @@ -1106,26 +1105,26 @@ private void OnColumnContextMenuStripOpening (object sender, CancelEventArgs e) } - DataGridViewColumn col = gridView.Columns[_selectedCol]; + var col = gridView.Columns[_selectedCol]; moveLeftToolStripMenuItem.Enabled = col != null && col.DisplayIndex > 0; moveRightToolStripMenuItem.Enabled = col != null && col.DisplayIndex < gridView.Columns.Count - 1; if (gridView.Columns.Count - 1 > _selectedCol) { // DataGridViewColumn colRight = gridView.Columns[this.selectedCol + 1]; - DataGridViewColumn colRight = gridView.Columns.GetNextColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); + var colRight = gridView.Columns.GetNextColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); moveRightToolStripMenuItem.Enabled = colRight != null && colRight.Frozen == col.Frozen; } if (_selectedCol > 0) { //DataGridViewColumn colLeft = gridView.Columns[this.selectedCol - 1]; - DataGridViewColumn colLeft = gridView.Columns.GetPreviousColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); + var colLeft = gridView.Columns.GetPreviousColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); moveLeftToolStripMenuItem.Enabled = colLeft != null && colLeft.Frozen == col.Frozen; } - DataGridViewColumn colLast = gridView.Columns[gridView.Columns.Count - 1]; + var colLast = gridView.Columns[gridView.Columns.Count - 1]; moveToLastColumnToolStripMenuItem.Enabled = colLast != null && colLast.Frozen == col.Frozen; // Fill context menu with column names @@ -1157,7 +1156,7 @@ private void OnHandleColumnItemContextMenu (object sender, EventArgs args) [SupportedOSPlatform("windows")] private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick (object sender, EventArgs e) { - Control ctl = columnContextMenuStrip.SourceControl; + var ctl = columnContextMenuStrip.SourceControl; var frozen = false; if (_freezeStateMap.TryGetValue(ctl, out var value)) @@ -1178,7 +1177,7 @@ private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick (object sender, private void OnMoveToLastColumnToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; + var col = gridView.Columns[_selectedCol]; if (col != null) { col.DisplayIndex = gridView.Columns.Count - 1; @@ -1189,7 +1188,7 @@ private void OnMoveToLastColumnToolStripMenuItemClick (object sender, EventArgs private void OnMoveLeftToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; + var col = gridView.Columns[_selectedCol]; if (col != null && col.DisplayIndex > 0) { col.DisplayIndex -= 1; @@ -1200,7 +1199,7 @@ private void OnMoveLeftToolStripMenuItemClick (object sender, EventArgs e) private void OnMoveRightToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; + var col = gridView.Columns[_selectedCol]; if (col != null && col.DisplayIndex < gridView.Columns.Count - 1) { col.DisplayIndex = col.DisplayIndex + 1; @@ -1211,7 +1210,7 @@ private void OnMoveRightToolStripMenuItemClick (object sender, EventArgs e) private void OnHideColumnToolStripMenuItemClick (object sender, EventArgs e) { var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; + var col = gridView.Columns[_selectedCol]; col.Visible = false; } @@ -1415,7 +1414,7 @@ private void OnToggleHighlightPanelButtonClick (object sender, EventArgs e) private void OnSaveFilterButtonClick (object sender, EventArgs e) { - FilterParams newParams = _filterParams.Clone(); + var newParams = _filterParams.Clone(); newParams.Color = Color.FromKnownColor(KnownColor.Black); ConfigManager.Settings.FilterList.Add(newParams); OnFilterListChanged(this); @@ -1478,7 +1477,7 @@ private void OnFilterListBoxMouseDoubleClick (object sender, MouseEventArgs e) if (filterListBox.SelectedIndex >= 0) { var filterParams = (FilterParams)filterListBox.Items[filterListBox.SelectedIndex]; - FilterParams newParams = filterParams.Clone(); + var newParams = filterParams.Clone(); //newParams.historyList = ConfigManager.Settings.filterHistoryList; _filterParams = newParams; ReInitFilterParams(_filterParams); diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs index e484a366..b972f7a3 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs @@ -61,7 +61,7 @@ private void CreateDefaultViewStyle () dataGridViewCellStyleMainGrid.SelectionBackColor = SystemColors.Highlight; dataGridViewCellStyleMainGrid.SelectionForeColor = SystemColors.HighlightText; - Color highlightColor = SystemColors.Highlight; + var highlightColor = SystemColors.Highlight; //Color is smaller than 128, means its darker var isDark = (highlightColor.R * 0.2126) + (highlightColor.G * 0.7152) + (highlightColor.B * 0.0722) < 255 / 2; @@ -113,7 +113,7 @@ private bool LoadPersistenceOptions () try { - PersistenceData persistenceData = ForcedPersistenceFileName == null + var persistenceData = ForcedPersistenceFileName == null ? Persister.LoadPersistenceDataOptionsOnly(FileName, Preferences) : Persister.LoadPersistenceDataOptionsOnlyFromFixedFile(ForcedPersistenceFileName); @@ -210,7 +210,7 @@ private void LoadPersistenceData () try { - PersistenceData persistenceData = ForcedPersistenceFileName == null + var persistenceData = ForcedPersistenceFileName == null ? Persister.LoadPersistenceData(FileName, Preferences) : Persister.LoadPersistenceDataFromFixedFile(ForcedPersistenceFileName); @@ -298,9 +298,9 @@ private void RestoreFilters (PersistenceData persistenceData) private void RestoreFilterTabs (PersistenceData persistenceData) { - foreach (FilterTabData data in persistenceData.FilterTabDataList) + foreach (var data in persistenceData.FilterTabDataList) { - FilterParams persistFilterParams = data.FilterParams; + var persistFilterParams = data.FilterParams; ReInitFilterParams(persistFilterParams); List filterResultList = []; //List lastFilterResultList = new List(); @@ -479,7 +479,7 @@ private void SetGuiAfterLoading () SyncTimestampDisplay(); } - Settings settings = ConfigManager.Settings; + var settings = ConfigManager.Settings; ShowLineColumn(!settings.HideLineColumn); } @@ -489,7 +489,7 @@ private void SetGuiAfterLoading () private ILogLineColumnizer FindColumnizer () { - ILogLineColumnizer columnizer = Preferences.MaskPrio + var columnizer = Preferences.MaskPrio ? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)) ?? _parentLogTabWin.GetColumnizerHistoryEntry(FileName) : _parentLogTabWin.GetColumnizerHistoryEntry(FileName) ?? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)); @@ -800,7 +800,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) var filterLineAdded = false; for (var i = filterStart; i < e.LineCount; ++i) { - ILogLine line = _logFileReader.GetLogLine(i); + var line = _logFileReader.GetLogLine(i); if (line == null) { return; @@ -823,7 +823,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) //pipeFx.BeginInvoke(i, null, null); ProcessFilterPipes(i); - IList matchingList = FindMatchingHilightEntries(line); + var matchingList = FindMatchingHilightEntries(line); LaunchHighlightPlugins(matchingList, i); GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); if (setBookmark) @@ -868,10 +868,10 @@ private void CheckFilterAndHighlight (LogEventArgs e) for (var i = startLine; i < e.LineCount; ++i) { - ILogLine line = _logFileReader.GetLogLine(i); + var line = _logFileReader.GetLogLine(i); if (line != null) { - IList matchingList = FindMatchingHilightEntries(line); + var matchingList = FindMatchingHilightEntries(line); LaunchHighlightPlugins(matchingList, i); GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); @@ -913,11 +913,11 @@ private void LaunchHighlightPlugins (IList matchingList, int lin LineNum = lineNum }; - foreach (HighlightEntry entry in matchingList) + foreach (var entry in matchingList) { if (entry.IsActionEntry && entry.ActionEntry.PluginName != null) { - IKeywordAction plugin = PluginRegistry.PluginRegistry.Instance.FindKeywordActionPluginByName(entry.ActionEntry.PluginName); + var plugin = PluginRegistry.PluginRegistry.Instance.FindKeywordActionPluginByName(entry.ActionEntry.PluginName); if (plugin != null) { ActionPluginExecuteFx fx = plugin.Execute; @@ -956,7 +956,7 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) { _logger.Info("SetColumnizerInternal(): {0}", columnizer.GetName()); - ILogLineColumnizer oldColumnizer = CurrentColumnizer; + var oldColumnizer = CurrentColumnizer; var oldColumnizerIsXmlType = CurrentColumnizer is ILogLineXmlColumnizer; var oldColumnizerIsPreProcess = CurrentColumnizer is IPreProcessColumnizer; var mustReload = false; @@ -990,8 +990,8 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) } } - Type oldColType = _filterParams.CurrentColumnizer?.GetType(); - Type newColType = columnizer?.GetType(); + var oldColType = _filterParams.CurrentColumnizer?.GetType(); + var newColType = columnizer?.GetType(); if (oldColType != newColType && _filterParams.ColumnRestrict && _filterParams.IsFilterTail) { @@ -1076,7 +1076,7 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) SyncTimestampDisplay(); } - Settings settings = ConfigManager.Settings; + var settings = ConfigManager.Settings; ShowLineColumn(!settings.HideLineColumn); ShowTimeSpread(Preferences.ShowTimeSpread && columnizer.IsTimeshiftImplemented()); } @@ -1133,7 +1133,7 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered column ??= Column.EmptyColumn; - IList matchList = FindHighlightMatches(column); + var matchList = FindHighlightMatches(column); // too many entries per line seem to cause problems with the GDI while (matchList.Count > 50) { @@ -1165,8 +1165,8 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered //var leftPad = e.CellStyle.Padding.Left; //RectangleF rect = new(e.CellBounds.Left + leftPad, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height); - Rectangle borderWidths = PaintHelper.BorderWidths(e.AdvancedBorderStyle); - Rectangle valBounds = e.CellBounds; + var borderWidths = PaintHelper.BorderWidths(e.AdvancedBorderStyle); + var valBounds = e.CellBounds; valBounds.Offset(borderWidths.X, borderWidths.Y); valBounds.Width -= borderWidths.Right; valBounds.Height -= borderWidths.Bottom; @@ -1177,7 +1177,7 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered valBounds.Height -= e.CellStyle.Padding.Vertical; } - TextFormatFlags flags = + var flags = TextFormatFlags.Left | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix @@ -1193,26 +1193,26 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered //TextRenderer.DrawText(e.Graphics, e.Value as String, e.CellStyle.Font, valBounds, Color.FromKnownColor(KnownColor.Black), flags); - Point wordPos = valBounds.Location; + var wordPos = valBounds.Location; Size proposedSize = new(valBounds.Width, valBounds.Height); - Rectangle r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); + var r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); e.Graphics.SetClip(e.CellBounds); - foreach (HighlightMatchEntry matchEntry in matchList) + foreach (var matchEntry in matchList) { - Font font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? BoldFont : NormalFont; + var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? BoldFont : NormalFont; Brush bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty ? new SolidBrush(matchEntry.HighlightEntry.BackgroundColor) : null; var matchWord = column.DisplayValue.Substring(matchEntry.StartPos, matchEntry.Length); - Size wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); + var wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); wordSize.Height = e.CellBounds.Height; Rectangle wordRect = new(wordPos, wordSize); - Color foreColor = matchEntry.HighlightEntry.ForegroundColor; + var foreColor = matchEntry.HighlightEntry.ForegroundColor; if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) { if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) @@ -1236,7 +1236,7 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered /// /// List of all highlight matches for the current cell /// The entry that is used as the default. - /// List of HilightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. + /// List of HighlightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. private IList MergeHighlightMatchEntries (IList matchList, HighlightMatchEntry groundEntry) { // Fill an area with lenth of whole text with a default hilight entry @@ -1248,7 +1248,7 @@ private IList MergeHighlightMatchEntries (IList MergeHighlightMatchEntries (IList 0) { - HighlightEntry currentEntry = entryArray[0]; + var currentEntry = entryArray[0]; var lastStartPos = 0; var pos = 0; @@ -1357,7 +1357,7 @@ private IList FindMatchingHilightEntries (ITextValue line) { lock (_currentHighlightGroupLock) { - foreach (HighlightEntry entry in _currentHighlightGroup.HighlightEntryList) + foreach (var entry in _currentHighlightGroup.HighlightEntryList) { if (CheckHighlightEntryMatch(entry, line)) { @@ -1372,11 +1372,11 @@ private IList FindMatchingHilightEntries (ITextValue line) private void GetHighlightEntryMatches (ITextValue line, IList hilightEntryList, IList resultList) { - foreach (HighlightEntry entry in hilightEntryList) + foreach (var entry in hilightEntryList) { if (entry.IsWordMatch) { - MatchCollection matches = entry.Regex.Matches(line.Text); + var matches = entry.Regex.Matches(line.Text); foreach (Match match in matches) { HighlightMatchEntry me = new() @@ -1411,7 +1411,7 @@ private void GetHilightActions (IList matchingList, out bool noL noLed = stopTail = setBookmark = false; bookmarkComment = string.Empty; - foreach (HighlightEntry entry in matchingList) + foreach (var entry in matchingList) { if (entry.IsLedSwitch) { @@ -1503,7 +1503,7 @@ private void SyncTimestampDisplayWorker () if (lineNum >= 0 && lineNum < dataGridView.RowCount) { var refLine = lineNum; - DateTime timeStamp = GetTimestampForLine(ref refLine, true); + var timeStamp = GetTimestampForLine(ref refLine, true); if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) { _guiStateArgs.Timestamp = timeStamp; @@ -1511,7 +1511,7 @@ private void SyncTimestampDisplayWorker () if (_shouldCallTimeSync) { refLine = lineNum; - DateTime exactTimeStamp = GetTimestampForLine(ref refLine, false); + var exactTimeStamp = GetTimestampForLine(ref refLine, false); SyncOtherWindows(exactTimeStamp); _shouldCallTimeSync = false; } @@ -1529,9 +1529,9 @@ private void SyncTimestampDisplayWorker () } var refLine = row1; - DateTime timeStamp1 = GetTimestampForLine(ref refLine, false); + var timeStamp1 = GetTimestampForLine(ref refLine, false); refLine = row2; - DateTime timeStamp2 = GetTimestampForLine(ref refLine, false); + var timeStamp2 = GetTimestampForLine(ref refLine, false); //TimeSpan span = TimeSpan.FromTicks(timeStamp2.Ticks - timeStamp1.Ticks); DateTime diff; if (timeStamp1.Ticks > timeStamp2.Ticks) @@ -1645,7 +1645,7 @@ private int Search (SearchParams searchParams) } } - ILogLine line = _logFileReader.GetLogLine(lineNum); + var line = _logFileReader.GetLogLine(lineNum); if (line == null) { return -1; @@ -1808,10 +1808,10 @@ private void SelectPrevHighlightLine () while (lineNum > 0) { lineNum--; - ILogLine line = _logFileReader.GetLogLine(lineNum); + var line = _logFileReader.GetLogLine(lineNum); if (line != null) { - HighlightEntry entry = FindHilightEntry(line); + var entry = FindHilightEntry(line); if (entry != null) { SelectLine(lineNum, false, true); @@ -1828,10 +1828,10 @@ private void SelectNextHighlightLine () while (lineNum < _logFileReader.LineCount) { lineNum++; - ILogLine line = _logFileReader.GetLogLine(lineNum); + var line = _logFileReader.GetLogLine(lineNum); if (line != null) { - HighlightEntry entry = FindHilightEntry(line); + var entry = FindHilightEntry(line); if (entry != null) { SelectLine(lineNum, false, true); @@ -1884,7 +1884,7 @@ private void ShiftBookmarks (int offset) private void ShiftRowHeightList (int offset) { SortedList newList = []; - foreach (RowHeightEntry entry in _rowHeightList.Values) + foreach (var entry in _rowHeightList.Values) { var line = entry.LineNum - offset; if (line >= 0) @@ -1901,7 +1901,7 @@ private void ShiftFilterPipes (int offset) { lock (_filterPipeList) { - foreach (FilterPipe pipe in _filterPipeList) + foreach (var pipe in _filterPipeList) { pipe.ShiftLineNums(offset); } @@ -1913,7 +1913,7 @@ private void LoadFilterPipes () { lock (_filterPipeList) { - foreach (FilterPipe pipe in _filterPipeList) + foreach (var pipe in _filterPipeList) { pipe.RecreateTempFile(); } @@ -1932,7 +1932,7 @@ private void DisconnectFilterPipes () { lock (_filterPipeList) { - foreach (FilterPipe pipe in _filterPipeList) + foreach (var pipe in _filterPipeList) { pipe.ClearLineList(); } @@ -2070,7 +2070,7 @@ private async void FilterSearch (string text) _progressEventArgs.Visible = true; SendProgressBarUpdate(); - Settings settings = ConfigManager.Settings; + var settings = ConfigManager.Settings; //FilterFx fx = settings.preferences.multiThreadFilter ? MultiThreadedFilter : new FilterFx(Filter); FilterFxAction = settings.Preferences.MultiThreadFilter ? MultiThreadedFilter : Filter; @@ -2127,7 +2127,7 @@ private void Filter (FilterParams filterParams, List filterResultLines, Lis ColumnizerCallback callback = new(this); while (true) { - ILogLine line = _logFileReader.GetLogLine(lineNum); + var line = _logFileReader.GetLogLine(lineNum); if (line == null) { break; @@ -2227,7 +2227,7 @@ private void AddFilterLine (int lineNum, bool immediate, FilterParams filterPara lock (_filterResultList) { filterHitList.Add(lineNum); - IList filterResult = GetAdditionalFilterResults(filterParams, lineNum, lastFilterLinesList); + var filterResult = GetAdditionalFilterResults(filterParams, lineNum, lastFilterLinesList); filterResultLines.AddRange(filterResult); count = filterResultLines.Count; lastFilterLinesList.AddRange(filterResult); @@ -2753,7 +2753,7 @@ private void WritePipeToTab (FilterPipe pipe, IList lineNumberList, string break; } - ILogLine line = _logFileReader.GetLogLine(i); + var line = _logFileReader.GetLogLine(i); if (CurrentColumnizer is ILogLineXmlColumnizer) { callback.LineNum = i; @@ -2786,7 +2786,7 @@ private void WriteFilterToTabFinished (FilterPipe pipe, string name, Persistence preProcessColumnizer = CurrentColumnizer; } - LogWindow newWin = _parentLogTabWin.AddFilterTab(pipe, title, preProcessColumnizer); + var newWin = _parentLogTabWin.AddFilterTab(pipe, title, preProcessColumnizer); newWin.FilterPipe = pipe; pipe.OwnLogWindow = newWin; if (persistenceData != null) @@ -2818,7 +2818,7 @@ internal void WritePipeTab (IList lineEntryList, string title) }; pipe.Closed += OnPipeDisconnected; pipe.OpenFile(); - foreach (LineEntry entry in lineEntryList) + foreach (var entry in lineEntryList) { pipe.WriteToPipe(entry.LogLine, entry.LineNum); } @@ -2831,7 +2831,7 @@ internal void WritePipeTab (IList lineEntryList, string title) private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) { newWin.WaitForLoadingFinished(); - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.ColumnizerName, + var columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); if (columnizer != null) { @@ -2849,7 +2849,7 @@ private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) [SupportedOSPlatform("windows")] private void ProcessFilterPipes (int lineNum) { - ILogLine searchLine = _logFileReader.GetLogLine(lineNum); + var searchLine = _logFileReader.GetLogLine(lineNum); if (searchLine == null) { return; @@ -2862,7 +2862,7 @@ private void ProcessFilterPipes (int lineNum) IList deleteList = []; lock (_filterPipeList) { - foreach (FilterPipe pipe in _filterPipeList) + foreach (var pipe in _filterPipeList) { if (pipe.IsStopped) { @@ -2872,7 +2872,7 @@ private void ProcessFilterPipes (int lineNum) //long startTime = Environment.TickCount; if (Util.TestFilterCondition(pipe.FilterParams, searchLine, callback)) { - IList filterResult = + var filterResult = GetAdditionalFilterResults(pipe.FilterParams, lineNum, pipe.LastLinesHistoryList); pipe.OpenFile(); foreach (var line in filterResult) @@ -2883,7 +2883,7 @@ private void ProcessFilterPipes (int lineNum) pipe.LastLinesHistoryList.RemoveAt(0); } - ILogLine textLine = _logFileReader.GetLogLine(line); + var textLine = _logFileReader.GetLogLine(line); var fileOk = pipe.WriteToPipe(textLine, line); if (!fileOk) { @@ -2899,7 +2899,7 @@ private void ProcessFilterPipes (int lineNum) } } - foreach (FilterPipe pipe in deleteList) + foreach (var pipe in deleteList) { _filterPipeList.Remove(pipe); } @@ -2910,7 +2910,7 @@ private void CopyMarkedLinesToClipboard () { if (_guiStateArgs.CellSelectMode) { - DataObject data = dataGridView.GetClipboardContent(); + var data = dataGridView.GetClipboardContent(); Clipboard.SetDataObject(data); } else @@ -2932,7 +2932,7 @@ private void CopyMarkedLinesToClipboard () foreach (var lineNum in lineNumList) { - ILogLine line = _logFileReader.GetLogLine(lineNum); + var line = _logFileReader.GetLogLine(lineNum); if (xmlColumnizer != null) { callback.LineNum = lineNum; @@ -3087,7 +3087,7 @@ private void ApplyFrozenState (BufferedDataGridView gridView) dict.Add(col.DisplayIndex, col); } - foreach (DataGridViewColumn col in dict.Values) + foreach (var col in dict.Values) { col.Frozen = _freezeStateMap.ContainsKey(gridView) && _freezeStateMap[gridView]; var sel = col.HeaderCell.Selected; @@ -3238,7 +3238,7 @@ private void AddBlockTargetLinesToDict (Dictionary dict, PatternBlock //Well keep this for the moment because there is some other commented code which calls this one private PatternBlock FindExistingBlock (PatternBlock block, List blockList) { - foreach (PatternBlock searchBlock in blockList) + foreach (var searchBlock in blockList) { if (((block.StartLine > searchBlock.StartLine && block.StartLine < searchBlock.EndLine) || (block.EndLine > searchBlock.StartLine && block.EndLine < searchBlock.EndLine)) && @@ -3431,7 +3431,7 @@ private int FindSimilarLine (int srcLine, int startLine, Dictionary pr Regex regex = null; Regex regex2 = null; string msgToFind = null; - CultureInfo culture = CultureInfo.CurrentCulture; + var culture = CultureInfo.CurrentCulture; var num = _logFileReader.LineCount; for (var i = startLine; i < num; ++i) @@ -3489,10 +3489,10 @@ private int FindSimilarLine (int srcLine, int startLine, Dictionary pr private string GetMsgForLine (int i) { - ILogLine line = _logFileReader.GetLogLine(i); - ILogLineColumnizer columnizer = CurrentColumnizer; + var line = _logFileReader.GetLogLine(i); + var columnizer = CurrentColumnizer; ColumnizerCallback callback = new(this); - IColumnizedLogLine cols = columnizer.SplitLine(callback, line); + var cols = columnizer.SplitLine(callback, line); return cols.ColumnValues.Last().FullValue; } @@ -3507,7 +3507,7 @@ private void ChangeRowHeight (bool decrease) if (decrease) { - if (!_rowHeightList.TryGetValue(rowNum, out RowHeightEntry? entry)) + if (!_rowHeightList.TryGetValue(rowNum, out var entry)) { return; } @@ -3523,7 +3523,7 @@ private void ChangeRowHeight (bool decrease) else { RowHeightEntry entry; - if (!_rowHeightList.TryGetValue(rowNum, out RowHeightEntry? value)) + if (!_rowHeightList.TryGetValue(rowNum, out var value)) { entry = new RowHeightEntry { @@ -3552,7 +3552,7 @@ private void ChangeRowHeight (bool decrease) private int GetRowHeight (int rowNum) { - return _rowHeightList.TryGetValue(rowNum, out RowHeightEntry? value) + return _rowHeightList.TryGetValue(rowNum, out var value) ? value.Height : _lineHeight; } @@ -3603,7 +3603,7 @@ private void MarkCurrentFilterRange () _filterParams.RangeSearchText = filterRangeComboBox.Text; ColumnizerCallback callback = new(this); RangeFinder rangeFinder = new(_filterParams, callback); - Core.Entities.Range range = rangeFinder.FindRange(dataGridView.CurrentCellAddress.Y); + var range = rangeFinder.FindRange(dataGridView.CurrentCellAddress.Y); if (range != null) { SetCellSelectionMode(false); @@ -3657,7 +3657,7 @@ private void SetBookmarksForSelectedFilterLines () private void SetDefaultHighlightGroup () { - HighlightGroup group = _parentLogTabWin.FindHighlightGroupByFileMask(FileName); + var group = _parentLogTabWin.FindHighlightGroupByFileMask(FileName); if (group != null) { SetCurrentHighlightGroup(group.GroupName); @@ -3680,7 +3680,7 @@ private void FireCancelHandlers () { lock (_cancelHandlerList) { - foreach (Core.Interface.IBackgroundProcessCancelHandler handler in _cancelHandlerList) + foreach (var handler in _cancelHandlerList) { handler.EscapePressed(); } @@ -3714,7 +3714,7 @@ private void AddSlaveToTimesync (LogWindow slave) var currentLineNum = dataGridView.CurrentCellAddress.Y; var refLine = currentLineNum; - DateTime timeStamp = GetTimestampForLine(ref refLine, true); + var timeStamp = GetTimestampForLine(ref refLine, true); if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) { TimeSyncList.CurrentTimestamp = timeStamp; @@ -3771,7 +3771,7 @@ private void RemoveAllSearchHighlightEntries () lock (_tempHighlightEntryListLock) { List newList = []; - foreach (HighlightEntry he in _tempHighlightEntryList) + foreach (var he in _tempHighlightEntryList) { if (!he.IsSearchHit) { @@ -3803,7 +3803,7 @@ private DataGridViewColumn GetColumnByName (BufferedDataGridView dataGridView, s private void SelectColumn () { var colName = columnComboBox.SelectedItem as string; - DataGridViewColumn col = GetColumnByName(dataGridView, colName); + var col = GetColumnByName(dataGridView, colName); if (col != null && !col.Frozen) { dataGridView.FirstDisplayedScrollingColumnIndex = col.Index; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs index cd01695c..8d4d36a0 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs @@ -499,7 +499,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV } } - public void OnDataGridView_CellPainting (object sender, DataGridViewCellPaintingEventArgs e) + public void OnDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) { var gridView = (BufferedDataGridView)sender; CellPainting(gridView, e.RowIndex, e); diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs index bd148048..a40a078f 100644 --- a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs @@ -204,7 +204,7 @@ private void InitializeComponent() this.setRangeButton.TabIndex = 12; this.setRangeButton.Text = "Set range"; this.setRangeButton.UseVisualStyleBackColor = true; - this.setRangeButton.Click += new System.EventHandler(this.setRangeButton_Click); + this.setRangeButton.Click += new System.EventHandler(this.OnSetRangeButtonClick); // // label7 // @@ -224,7 +224,7 @@ private void InitializeComponent() this.recalcButton.TabIndex = 6; this.recalcButton.Text = "Recalc"; this.recalcButton.UseVisualStyleBackColor = true; - this.recalcButton.Click += new System.EventHandler(this.recalcButton_Click); + this.recalcButton.Click += new System.EventHandler(this.OnRecalcButtonClick); // // label6 // @@ -337,11 +337,11 @@ private void InitializeComponent() this.patternHitsDataGridView.Size = new System.Drawing.Size(289, 83); this.patternHitsDataGridView.TabIndex = 1; this.patternHitsDataGridView.VirtualMode = true; - this.patternHitsDataGridView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.patternHitsDataGridView_MouseDoubleClick); - this.patternHitsDataGridView.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.patternHitsDataGridView_CellValueNeeded); - this.patternHitsDataGridView.ColumnDividerDoubleClick += new System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventHandler(this.patternHitsDataGridView_ColumnDividerDoubleClick); - this.patternHitsDataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.patternHitsDataGridView_CellPainting); - this.patternHitsDataGridView.CurrentCellChanged += new System.EventHandler(this.patternHitsDataGridView_CurrentCellChanged); + this.patternHitsDataGridView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.OnPatternHitsDataGridViewMouseDoubleClick); + this.patternHitsDataGridView.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.OnPatternHitsDataGridViewCellValueNeeded); + this.patternHitsDataGridView.ColumnDividerDoubleClick += new System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventHandler(this.OnPatternHitsDataGridViewColumnDividerDoubleClick); + this.patternHitsDataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.OnPatternHitsDataGridViewCellPainting); + this.patternHitsDataGridView.CurrentCellChanged += new System.EventHandler(this.OnPatternHitsDataGridViewCurrentCellChanged); // // contentDataGridView // @@ -365,10 +365,10 @@ private void InitializeComponent() this.contentDataGridView.Size = new System.Drawing.Size(491, 83); this.contentDataGridView.TabIndex = 0; this.contentDataGridView.VirtualMode = true; - this.contentDataGridView.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.contentDataGridView_CellValueNeeded); - this.contentDataGridView.ColumnDividerDoubleClick += new System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventHandler(this.contentDataGridView_ColumnDividerDoubleClick); - this.contentDataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.contentDataGridView_CellPainting); - this.contentDataGridView.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.contentDataGridView_CellMouseDoubleClick); + this.contentDataGridView.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.OnContentDataGridViewCellValueNeeded); + this.contentDataGridView.ColumnDividerDoubleClick += new System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventHandler(this.OnContentDataGridViewColumnDividerDoubleClick); + this.contentDataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.OnContentDataGridViewCellPainting); + this.contentDataGridView.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.OnContentDataGridViewCellMouseDoubleClick); // // PatternWindow // diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs index 84614aef..f704e3e8 100644 --- a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs @@ -29,7 +29,7 @@ public PatternWindow () public PatternWindow (LogWindow logWindow) { - this._logWindow = logWindow; + _logWindow = logWindow; InitializeComponent(); recalcButton.Enabled = false; } @@ -68,13 +68,13 @@ public int Weight public void SetBlockList (List flatBlockList, PatternArgs patternArgs) { - this._patternArgs = patternArgs; + _patternArgs = patternArgs; _blockList.Clear(); List singeList = []; //int blockId = -1; for (var i = 0; i < flatBlockList.Count; ++i) { - PatternBlock block = flatBlockList[i]; + var block = flatBlockList[i]; singeList.Add(block); //if (block.blockId != blockId) //{ @@ -105,21 +105,25 @@ public void SetColumnizer (ILogLineColumnizer columnizer) patternHitsDataGridView.Columns[0].Width = 20; contentDataGridView.Columns[0].Width = 20; - DataGridViewTextBoxColumn blockInfoColumn = new(); - blockInfoColumn.HeaderText = "Weight"; - blockInfoColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - blockInfoColumn.Resizable = DataGridViewTriState.False; - blockInfoColumn.DividerWidth = 1; - blockInfoColumn.ReadOnly = true; - blockInfoColumn.Width = 50; - - DataGridViewTextBoxColumn contentInfoColumn = new(); - contentInfoColumn.HeaderText = "Diff"; - contentInfoColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - contentInfoColumn.Resizable = DataGridViewTriState.False; - contentInfoColumn.DividerWidth = 1; - contentInfoColumn.ReadOnly = true; - contentInfoColumn.Width = 50; + DataGridViewTextBoxColumn blockInfoColumn = new() + { + HeaderText = "Weight", + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.False, + DividerWidth = 1, + ReadOnly = true, + Width = 50 + }; + + DataGridViewTextBoxColumn contentInfoColumn = new() + { + HeaderText = "Diff", + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.False, + DividerWidth = 1, + ReadOnly = true, + Width = 50 + }; patternHitsDataGridView.Columns.Insert(1, blockInfoColumn); contentDataGridView.Columns.Insert(1, contentInfoColumn); @@ -128,8 +132,8 @@ public void SetColumnizer (ILogLineColumnizer columnizer) public void SetFont (string fontName, float fontSize) { Font font = new(new FontFamily(fontName), fontSize); - var lineSpacing = font.FontFamily.GetLineSpacing(FontStyle.Regular); - var lineSpacingPixel = font.Size * lineSpacing / font.FontFamily.GetEmHeight(FontStyle.Regular); + //var lineSpacing = font.FontFamily.GetLineSpacing(FontStyle.Regular); + //var lineSpacingPixel = font.Size * lineSpacing / font.FontFamily.GetEmHeight(FontStyle.Regular); patternHitsDataGridView.DefaultCellStyle.Font = font; contentDataGridView.DefaultCellStyle.Font = font; @@ -183,14 +187,16 @@ private int GetLineForContentGrid (int rowIndex) #region Events handler - private void patternHitsDataGridView_CellValueNeeded (object sender, DataGridViewCellValueEventArgs e) + private void OnPatternHitsDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { if (_currentList == null || e.RowIndex < 0) { return; } + var rowIndex = GetLineForHitGrid(e.RowIndex); var colIndex = e.ColumnIndex; + if (colIndex == 1) { e.Value = _currentList[e.RowIndex].Weigth; @@ -206,7 +212,7 @@ private void patternHitsDataGridView_CellValueNeeded (object sender, DataGridVie } } - private void patternHitsDataGridView_CellPainting (object sender, DataGridViewCellPaintingEventArgs e) + private void OnPatternHitsDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) { if (_currentList == null || e.RowIndex < 0) { @@ -217,18 +223,20 @@ private void patternHitsDataGridView_CellPainting (object sender, DataGridViewCe { e.PaintBackground(e.CellBounds, false); var selCount = _patternArgs.EndLine - _patternArgs.StartLine; - var maxWeight = _patternArgs.MaxDiffInBlock * selCount + selCount; + var maxWeight = (_patternArgs.MaxDiffInBlock * selCount) + selCount; + if (maxWeight > 0) { var width = (int)((int)e.Value / (double)maxWeight * e.CellBounds.Width); Rectangle rect = new(e.CellBounds.X, e.CellBounds.Y, width, e.CellBounds.Height); var alpha = 90 + (int)((int)e.Value / (double)maxWeight * 165); - var color = Color.FromArgb(alpha, 170, 180, 150); - Brush brush = new SolidBrush(color); + + Brush brush = new SolidBrush(Color.FromArgb(alpha, 170, 180, 150));//gray green rect.Inflate(-2, -1); e.Graphics.FillRectangle(brush, rect); brush.Dispose(); } + e.PaintContent(e.CellBounds); e.Handled = true; } @@ -240,7 +248,7 @@ private void patternHitsDataGridView_CellPainting (object sender, DataGridViewCe } } - private void patternHitsDataGridView_MouseDoubleClick (object sender, MouseEventArgs e) + private void OnPatternHitsDataGridViewMouseDoubleClick (object sender, MouseEventArgs e) { //if (this.currentList == null || patternHitsDataGridView.CurrentRow == null) // return; @@ -249,7 +257,7 @@ private void patternHitsDataGridView_MouseDoubleClick (object sender, MouseEvent //this.logWindow.SelectLogLine(rowIndex); } - private void patternHitsDataGridView_CurrentCellChanged (object sender, EventArgs e) + private void OnPatternHitsDataGridViewCurrentCellChanged (object sender, EventArgs e) { if (_currentList == null || patternHitsDataGridView.CurrentRow == null) { @@ -269,25 +277,21 @@ private void patternHitsDataGridView_CurrentCellChanged (object sender, EventArg blockLinesLabel.Text = "" + contentDataGridView.RowCount; } - private void contentDataGridView_CellValueNeeded (object sender, DataGridViewCellValueEventArgs e) + private void OnContentDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { if (_currentBlock == null || e.RowIndex < 0) { return; } + var rowIndex = GetLineForContentGrid(e.RowIndex); var colIndex = e.ColumnIndex; + if (colIndex == 1) { - QualityInfo qi; - if (_currentBlock.QualityInfoList.TryGetValue(rowIndex, out qi)) - { - e.Value = qi.Quality; - } - else - { - e.Value = ""; - } + e.Value = _currentBlock.QualityInfoList.TryGetValue(rowIndex, out var qi) + ? qi.Quality + : string.Empty; } else { @@ -295,33 +299,36 @@ private void contentDataGridView_CellValueNeeded (object sender, DataGridViewCel { colIndex--; // adjust the inserted column } + e.Value = _logWindow.GetCellValue(rowIndex, colIndex); } } - private void contentDataGridView_CellPainting (object sender, DataGridViewCellPaintingEventArgs e) + private void OnContentDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) { if (_currentBlock == null || e.RowIndex < 0) { return; } + var gridView = (BufferedDataGridView)sender; var rowIndex = GetLineForContentGrid(e.RowIndex); _logWindow.CellPainting(gridView, rowIndex, e); } - private void contentDataGridView_CellMouseDoubleClick (object sender, DataGridViewCellMouseEventArgs e) + private void OnContentDataGridViewCellMouseDoubleClick (object sender, DataGridViewCellMouseEventArgs e) { if (_currentBlock == null || contentDataGridView.CurrentRow == null) { return; } + var rowIndex = GetLineForContentGrid(contentDataGridView.CurrentRow.Index); _logWindow.SelectLogLine(rowIndex); } - private void recalcButton_Click (object sender, EventArgs e) + private void OnRecalcButtonClick (object sender, EventArgs e) { _patternArgs.Fuzzy = fuzzyKnobControl.Value; _patternArgs.MaxDiffInBlock = maxDiffKnobControl.Value; @@ -332,26 +339,24 @@ private void recalcButton_Click (object sender, EventArgs e) setRangeButton.Enabled = false; } - private void closeButton_Click (object sender, EventArgs e) + private void OnCloseButtonClick (object sender, EventArgs e) { Close(); } - private void contentDataGridView_ColumnDividerDoubleClick (object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) + private void OnContentDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { e.Handled = true; contentDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } - private void patternHitsDataGridView_ColumnDividerDoubleClick (object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) + private void OnPatternHitsDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { e.Handled = true; patternHitsDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } - private void setRangeButton_Click (object sender, EventArgs e) + private void OnSetRangeButtonClick (object sender, EventArgs e) { _logWindow.PatternStatisticSelectRange(_patternArgs); recalcButton.Enabled = true; diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs index ba25f3c3..4a0cc7fb 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs @@ -34,12 +34,12 @@ private void InitializeComponent() // this.Name = "TimeSpreadingControl"; this.Size = new System.Drawing.Size(26, 324); - this.MouseLeave += new System.EventHandler(this.TimeSpreadingControl_MouseLeave); - this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.TimeSpreadingControl_MouseMove); - this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.TimeSpreadingControl_MouseDown); - this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.TimeSpreadingControl_MouseUp); - this.SizeChanged += new System.EventHandler(this.TimeSpreadingControl_SizeChanged); - this.MouseEnter += new System.EventHandler(this.TimeSpreadingControl_MouseEnter); + this.MouseLeave += new System.EventHandler(this.OnTimeSpreadingControlMouseLeave); + this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.OnTimeSpreadingControlMouseMove); + this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.OnTimeSpreadingControlMouseDown); + this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.OnTimeSpreadingControlMouseUp); + this.SizeChanged += new System.EventHandler(this.OnTimeSpreadingControlSizeChanged); + this.MouseEnter += new System.EventHandler(this.OnTimeSpreadingControlMouseEnter); this.ResumeLayout(false); } diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs index 7aea14ed..11d7e81d 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs @@ -65,8 +65,8 @@ internal TimeSpreadCalculator TimeSpreadCalc { //timeSpreadCalc.CalcDone -= timeSpreadCalc_CalcDone; _timeSpreadCalc = value; - _timeSpreadCalc.CalcDone += TimeSpreadCalc_CalcDone; - _timeSpreadCalc.StartCalc += TimeSpreadCalc_StartCalc; + _timeSpreadCalc.CalcDone += OnTimeSpreadCalcCalcDone; + _timeSpreadCalc.StartCalc += OnTimeSpreadCalcStartCalc; } } @@ -82,7 +82,7 @@ protected override void OnPaint (PaintEventArgs e) if (DesignMode) { Brush bgBrush = new SolidBrush(Color.FromKnownColor(KnownColor.LightSkyBlue)); - Rectangle rect = ClientRectangle; + var rect = ClientRectangle; rect.Inflate(0, -_edgeOffset); e.Graphics.FillRectangle(bgBrush, rect); bgBrush.Dispose(); @@ -100,7 +100,7 @@ protected override void OnPaint (PaintEventArgs e) private SpreadEntry GetEntryForMouse (MouseEventArgs e) { - List list = TimeSpreadCalc.DiffList; + var list = TimeSpreadCalc.DiffList; var y = e.Y - _edgeOffset; if (y < 0) { @@ -144,14 +144,14 @@ private void OnLineSelected (SelectLineEventArgs e) #region Events handler - private void TimeSpreadCalc_CalcDone (object sender, EventArgs e) + private void OnTimeSpreadCalcCalcDone (object sender, EventArgs e) { _logger.Debug("timeSpreadCalc_CalcDone()"); lock (_monitor) { Invalidate(); - Rectangle rect = ClientRectangle; + var rect = ClientRectangle; rect.Size = new Size(rect.Width, rect.Height - _edgeOffset * 3); if (rect.Height < 1) @@ -165,7 +165,7 @@ private void TimeSpreadCalc_CalcDone (object sender, EventArgs e) gfx.FillRectangle(bgBrush, rect); bgBrush.Dispose(); - List list = TimeSpreadCalc.DiffList; + var list = TimeSpreadCalc.DiffList; int step; if (list.Count >= _displayHeight) @@ -185,7 +185,7 @@ private void TimeSpreadCalc_CalcDone (object sender, EventArgs e) { for (var i = 0; i < list.Count; i += step) { - SpreadEntry entry = list[i]; + var entry = list[i]; var color = ReverseAlpha ? entry.Value : 255 - entry.Value; if (color > 255) @@ -210,12 +210,12 @@ private void TimeSpreadCalc_CalcDone (object sender, EventArgs e) BeginInvoke(new MethodInvoker(Refresh)); } - private void TimeSpreadCalc_StartCalc (object sender, EventArgs e) + private void OnTimeSpreadCalcStartCalc (object sender, EventArgs e) { lock (_monitor) { Invalidate(); - Rectangle rect = ClientRectangle; + var rect = ClientRectangle; rect.Size = new Size(rect.Width, rect.Height - _edgeOffset * 3); if (rect.Height < 1) @@ -230,9 +230,11 @@ private void TimeSpreadCalc_StartCalc (object sender, EventArgs e) Brush fgBrush = new SolidBrush(ForeColor); //gfx.FillRectangle(bgBrush, rect); - StringFormat format = new(StringFormatFlags.DirectionVertical | StringFormatFlags.NoWrap); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Center; + StringFormat format = new(StringFormatFlags.DirectionVertical | StringFormatFlags.NoWrap) + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Center + }; RectangleF rectf = new(rect.Left, rect.Top, rect.Width, rect.Height); @@ -245,7 +247,7 @@ private void TimeSpreadCalc_StartCalc (object sender, EventArgs e) BeginInvoke(new MethodInvoker(Refresh)); } - private void TimeSpreadingControl_SizeChanged (object sender, EventArgs e) + private void OnTimeSpreadingControlSizeChanged (object sender, EventArgs e) { if (TimeSpreadCalc != null) { @@ -254,15 +256,15 @@ private void TimeSpreadingControl_SizeChanged (object sender, EventArgs e) } } - private void TimeSpreadingControl_MouseDown (object sender, MouseEventArgs e) + private void OnTimeSpreadingControlMouseDown (object sender, MouseEventArgs e) { } - private void TimeSpreadingControl_MouseUp (object sender, MouseEventArgs e) + private void OnTimeSpreadingControlMouseUp (object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { - SpreadEntry entry = GetEntryForMouse(e); + var entry = GetEntryForMouse(e); if (entry == null) { return; @@ -272,17 +274,17 @@ private void TimeSpreadingControl_MouseUp (object sender, MouseEventArgs e) } } - private void TimeSpreadingControl_MouseEnter (object sender, EventArgs e) + private void OnTimeSpreadingControlMouseEnter (object sender, EventArgs e) { _toolTip.Active = true; } - private void TimeSpreadingControl_MouseLeave (object sender, EventArgs e) + private void OnTimeSpreadingControlMouseLeave (object sender, EventArgs e) { _toolTip.Active = false; } - private void TimeSpreadingControl_MouseMove (object sender, MouseEventArgs e) + private void OnTimeSpreadingControlMouseMove (object sender, MouseEventArgs e) { if (e.Y == _lastMouseY) { @@ -295,7 +297,7 @@ private void TimeSpreadingControl_MouseMove (object sender, MouseEventArgs e) return; } - SpreadEntry entry = GetEntryForMouse(e); + var entry = GetEntryForMouse(e); if (entry == null) { @@ -303,7 +305,7 @@ private void TimeSpreadingControl_MouseMove (object sender, MouseEventArgs e) } _lastMouseY = e.Y; - var dts = entry.Timestamp.ToString("dd.MM.yyyy HH:mm:ss"); + var dts = $"{entry.Timestamp:dd.MM.yyyy HH:mm:ss}"; _toolTip.SetToolTip(this, "Line " + (entry.LineNum + 1) + "\n" + dts); } diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.Designer.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.Designer.cs index c7310c5f..9467414c 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.Designer.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.Designer.cs @@ -53,14 +53,14 @@ private void InitializeComponent() { this.deleteBookmarkssToolStripMenuItem.Name = "deleteBookmarkssToolStripMenuItem"; this.deleteBookmarkssToolStripMenuItem.Size = new System.Drawing.Size(185, 22); this.deleteBookmarkssToolStripMenuItem.Text = "Delete bookmarks(s)"; - this.deleteBookmarkssToolStripMenuItem.Click += new System.EventHandler(this.deleteBookmarksToolStripMenuItem_Click); + this.deleteBookmarkssToolStripMenuItem.Click += new System.EventHandler(this.OnDeleteBookmarksToolStripMenuItemClick); // // removeCommentsToolStripMenuItem // this.removeCommentsToolStripMenuItem.Name = "removeCommentsToolStripMenuItem"; this.removeCommentsToolStripMenuItem.Size = new System.Drawing.Size(185, 22); this.removeCommentsToolStripMenuItem.Text = "Remove comment(s)"; - this.removeCommentsToolStripMenuItem.Click += new System.EventHandler(this.removeCommentsToolStripMenuItem_Click); + this.removeCommentsToolStripMenuItem.Click += new System.EventHandler(this.OnRemoveCommentsToolStripMenuItemClick); // // bookmarkTextBox // @@ -73,7 +73,7 @@ private void InitializeComponent() { this.bookmarkTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.bookmarkTextBox.Size = new System.Drawing.Size(194, 114); this.bookmarkTextBox.TabIndex = 0; - this.bookmarkTextBox.TextChanged += new System.EventHandler(this.bookmarkTextBox_TextChanged); + this.bookmarkTextBox.TextChanged += new System.EventHandler(this.OnBookmarkTextBoxTextChanged); // // splitContainer1 // @@ -119,17 +119,17 @@ private void InitializeComponent() { this.bookmarkDataGridView.Size = new System.Drawing.Size(517, 158); this.bookmarkDataGridView.TabIndex = 0; this.bookmarkDataGridView.VirtualMode = true; - this.bookmarkDataGridView.Enter += new System.EventHandler(this.bookmarkGridView_Enter); - this.bookmarkDataGridView.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.bookmarkDataGridView_CellDoubleClick); - this.bookmarkDataGridView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.boomarkDataGridView_MouseDoubleClick); - this.bookmarkDataGridView.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.bookmarkDataGridView_PreviewKeyDown); - this.bookmarkDataGridView.Leave += new System.EventHandler(this.bookmarkGridView_Leave); - this.bookmarkDataGridView.ColumnDividerDoubleClick += new System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventHandler(this.boomarkDataGridView_ColumnDividerDoubleClick); - this.bookmarkDataGridView.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.bookmarkDataGridView_RowsAdded); - this.bookmarkDataGridView.SelectionChanged += new System.EventHandler(bookmarkDataGridView_SelectionChanged); - this.bookmarkDataGridView.CellToolTipTextNeeded += new System.Windows.Forms.DataGridViewCellToolTipTextNeededEventHandler(this.bookmarkDataGridView_CellToolTipTextNeeded); - this.bookmarkDataGridView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.bookmarkGridView_KeyDown); - this.bookmarkDataGridView.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.bookmarkDataGridView_RowsRemoved); + this.bookmarkDataGridView.Enter += new System.EventHandler(this.OnBookmarkGridViewEnter); + this.bookmarkDataGridView.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.OnBookmarkDataGridViewCellDoubleClick); + this.bookmarkDataGridView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.OnBoomarkDataGridViewMouseDoubleClick); + this.bookmarkDataGridView.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.OnBookmarkDataGridViewPreviewKeyDown); + this.bookmarkDataGridView.Leave += new System.EventHandler(this.OnBookmarkGridViewLeave); + this.bookmarkDataGridView.ColumnDividerDoubleClick += new System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventHandler(this.OnBoomarkDataGridViewColumnDividerDoubleClick); + this.bookmarkDataGridView.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.OnBookmarkDataGridViewRowsAdded); + this.bookmarkDataGridView.SelectionChanged += new System.EventHandler(OnBookmarkDataGridViewSelectionChanged); + this.bookmarkDataGridView.CellToolTipTextNeeded += new System.Windows.Forms.DataGridViewCellToolTipTextNeededEventHandler(this.OnBookmarkDataGridViewCellToolTipTextNeeded); + this.bookmarkDataGridView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnBookmarkGridViewKeyDown); + this.bookmarkDataGridView.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.OnBookmarkDataGridViewRowsRemoved); // // commentColumnCheckBox // @@ -141,7 +141,7 @@ private void InitializeComponent() { this.commentColumnCheckBox.TabIndex = 8; this.commentColumnCheckBox.Text = "Show comment column"; this.commentColumnCheckBox.UseVisualStyleBackColor = true; - this.commentColumnCheckBox.CheckedChanged += new System.EventHandler(this.commentColumnCheckBox_CheckedChanged); + this.commentColumnCheckBox.CheckedChanged += new System.EventHandler(this.OnCommentColumnCheckBoxCheckedChanged); // // label1 // @@ -172,7 +172,7 @@ private void InitializeComponent() { this.ShowInTaskbar = false; this.Text = "Bookmarks"; this.ClientSizeChanged += new System.EventHandler(this.BookmarkWindow_ClientSizeChanged); - this.SizeChanged += new System.EventHandler(this.BookmarkWindow_SizeChanged); + this.SizeChanged += new System.EventHandler(this.OnBookmarkWindowSizeChanged); this.contextMenuStrip1.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 54e0f11e..8a3518fa 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -19,7 +19,7 @@ internal partial class BookmarkWindow : DockContent, ISharedToolWindow, IBookmar { #region Fields - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly object paintLock = new(); private IBookmarkData bookmarkData; @@ -379,7 +379,7 @@ private void OnBoomarkDataGridViewCellValueNeeded (object sender, DataGridViewCe } - private void boomarkDataGridView_MouseDoubleClick (object sender, MouseEventArgs e) + private void OnBoomarkDataGridViewMouseDoubleClick (object sender, MouseEventArgs e) { // if (this.bookmarkDataGridView.CurrentRow != null) // { @@ -388,14 +388,14 @@ private void boomarkDataGridView_MouseDoubleClick (object sender, MouseEventArgs // } } - private void boomarkDataGridView_ColumnDividerDoubleClick (object sender, + private void OnBoomarkDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) { e.Handled = true; ResizeColumns(); } - private void bookmarkGridView_KeyDown (object sender, KeyEventArgs e) + private void OnBookmarkGridViewKeyDown (object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { @@ -424,22 +424,22 @@ private void bookmarkGridView_KeyDown (object sender, KeyEventArgs e) } } - private void bookmarkGridView_Enter (object sender, EventArgs e) + private void OnBookmarkGridViewEnter (object sender, EventArgs e) { InvalidateCurrentRow(bookmarkDataGridView); } - private void bookmarkGridView_Leave (object sender, EventArgs e) + private void OnBookmarkGridViewLeave (object sender, EventArgs e) { InvalidateCurrentRow(bookmarkDataGridView); } - private void deleteBookmarksToolStripMenuItem_Click (object sender, EventArgs e) + private void OnDeleteBookmarksToolStripMenuItemClick (object sender, EventArgs e) { DeleteSelectedBookmarks(); } - private void bookmarkTextBox_TextChanged (object sender, EventArgs e) + private void OnBookmarkTextBoxTextChanged (object sender, EventArgs e) { if (!bookmarkTextBox.Enabled) { @@ -462,7 +462,7 @@ private void bookmarkTextBox_TextChanged (object sender, EventArgs e) logView?.RefreshLogView(); } - private void bookmarkDataGridView_SelectionChanged (object sender, EventArgs e) + private void OnBookmarkDataGridViewSelectionChanged (object sender, EventArgs e) { if (bookmarkDataGridView.SelectedRows.Count != 1 || bookmarkDataGridView.SelectedRows[0].Index >= bookmarkData.Bookmarks.Count) @@ -475,7 +475,7 @@ private void bookmarkDataGridView_SelectionChanged (object sender, EventArgs e) } } - private void bookmarkDataGridView_PreviewKeyDown (object sender, PreviewKeyDownEventArgs e) + private void OnBookmarkDataGridViewPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.Tab) { @@ -483,7 +483,7 @@ private void bookmarkDataGridView_PreviewKeyDown (object sender, PreviewKeyDownE } } - private void bookmarkDataGridView_CellToolTipTextNeeded (object sender, + private void OnBookmarkDataGridViewCellToolTipTextNeeded (object sender, DataGridViewCellToolTipTextNeededEventArgs e) { if (e.ColumnIndex != 0 || e.RowIndex <= -1 || e.RowIndex >= bookmarkData.Bookmarks.Count) @@ -499,7 +499,7 @@ private void bookmarkDataGridView_CellToolTipTextNeeded (object sender, } } - private void bookmarkDataGridView_CellDoubleClick (object sender, DataGridViewCellEventArgs e) + private void OnBookmarkDataGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) { // Toggle bookmark when double-clicking on the first column if (e.ColumnIndex == 0 && e.RowIndex >= 0 && bookmarkDataGridView.CurrentRow != null) @@ -551,7 +551,7 @@ private void bookmarkDataGridView_CellDoubleClick (object sender, DataGridViewCe } } - private void removeCommentsToolStripMenuItem_Click (object sender, EventArgs e) + private void OnRemoveCommentsToolStripMenuItemClick (object sender, EventArgs e) { if ( MessageBox.Show("Really remove bookmark comments for selected lines?", "LogExpert", @@ -573,7 +573,7 @@ private void removeCommentsToolStripMenuItem_Click (object sender, EventArgs e) } } - private void commentColumnCheckBox_CheckedChanged (object sender, EventArgs e) + private void OnCommentColumnCheckBoxCheckedChanged (object sender, EventArgs e) { ShowCommentColumn(commentColumnCheckBox.Checked); } @@ -607,17 +607,17 @@ private void BookmarkWindow_ClientSizeChanged (object sender, EventArgs e) } } - private void bookmarkDataGridView_RowsAdded (object sender, DataGridViewRowsAddedEventArgs e) + private void OnBookmarkDataGridViewRowsAdded (object sender, DataGridViewRowsAddedEventArgs e) { HideIfNeeded(); } - private void bookmarkDataGridView_RowsRemoved (object sender, DataGridViewRowsRemovedEventArgs e) + private void OnBookmarkDataGridViewRowsRemoved (object sender, DataGridViewRowsRemovedEventArgs e) { HideIfNeeded(); } - private void BookmarkWindow_SizeChanged (object sender, EventArgs e) + private void OnBookmarkWindowSizeChanged (object sender, EventArgs e) { // if (!this.splitContainer1.Visible) // { diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs index 3f91c8ca..886052ac 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs @@ -44,7 +44,7 @@ private void PasteFromClipboard () } var title = "Clipboard"; - LogWindow.LogWindow logWindow = AddTempFileTab(fileName, title); + var logWindow = AddTempFileTab(fileName, title); if (logWindow.Tag is LogWindowData data) { SetTooltipText(logWindow, "Pasted on " + DateTime.Now); @@ -252,7 +252,7 @@ private LogWindow.LogWindow FindWindowForFile (string fileName) { lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { if (logWindow.FileName.ToUpperInvariant().Equals(fileName.ToUpperInvariant(), StringComparison.Ordinal)) { @@ -274,7 +274,7 @@ private string FindFilenameForSettings (string fileName) { if (fileName.EndsWith(".lxp")) { - PersistenceData persistenceData = Persister.LoadOptionsOnly(fileName); + var persistenceData = Persister.LoadOptionsOnly(fileName); if (persistenceData == null) { return fileName; @@ -282,7 +282,7 @@ private string FindFilenameForSettings (string fileName) if (!string.IsNullOrEmpty(persistenceData.FileName)) { - IFileSystemPlugin fs = PluginRegistry.PluginRegistry.Instance.FindFileSystemForUri(persistenceData.FileName); + var fs = PluginRegistry.PluginRegistry.Instance.FindFileSystemForUri(persistenceData.FileName); if (fs != null && !fs.GetType().Equals(typeof(LocalFileSystem))) { return persistenceData.FileName; @@ -359,7 +359,7 @@ private void ShowHighlightSettingsDialog () PreSelectedGroupName = groupsComboBoxHighlightGroups.Text }; - DialogResult res = dlg.ShowDialog(); + var res = dlg.ShowDialog(); if (res == DialogResult.OK) { @@ -376,7 +376,7 @@ private void FillHighlightComboBox () { var currentGroupName = groupsComboBoxHighlightGroups.Text; groupsComboBoxHighlightGroups.Items.Clear(); - foreach (HighlightGroup group in HighlightGroupList) + foreach (var group in HighlightGroupList) { groupsComboBoxHighlightGroups.Items.Add(group.GroupName); if (group.GroupName.Equals(currentGroupName, StringComparison.Ordinal)) @@ -451,11 +451,11 @@ private void LoadFiles (string[] names, bool invertLogic) return; } - MultiFileOption option = ConfigManager.Settings.Preferences.MultiFileOption; + var option = ConfigManager.Settings.Preferences.MultiFileOption; if (option == MultiFileOption.Ask) { MultiLoadRequestDialog dlg = new(); - DialogResult res = dlg.ShowDialog(); + var res = dlg.ShowDialog(); if (res == DialogResult.Yes) { @@ -492,7 +492,7 @@ private void LoadFiles (string[] names, bool invertLogic) private void SetColumnizerHistoryEntry (string fileName, ILogLineColumnizer columnizer) { - ColumnizerHistoryEntry entry = FindColumnizerHistoryEntry(fileName); + var entry = FindColumnizerHistoryEntry(fileName); if (entry != null) { _ = ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); @@ -509,7 +509,7 @@ private void SetColumnizerHistoryEntry (string fileName, ILogLineColumnizer colu private ColumnizerHistoryEntry FindColumnizerHistoryEntry (string fileName) { - foreach (ColumnizerHistoryEntry entry in ConfigManager.Settings.ColumnizerHistoryList) + foreach (var entry in ConfigManager.Settings.ColumnizerHistoryList) { if (entry.FileName.Equals(fileName, StringComparison.Ordinal)) { @@ -539,7 +539,7 @@ private void ChangeCurrentLogWindow (LogWindow.LogWindow newLogWindow) return; // do nothing if wishing to set the same window } - LogWindow.LogWindow oldLogWindow = _currentLogWindow; + var oldLogWindow = _currentLogWindow; _currentLogWindow = newLogWindow; var titleName = _showInstanceNumbers ? "LogExpert #" + _instanceNumber : "LogExpert"; @@ -714,7 +714,7 @@ private void StatusLineEventWorker (StatusLineEventArgs e) [SupportedOSPlatform("windows")] private Icon CreateLedIcon (int level, bool dirty, int tailState, int syncMode) { - Rectangle iconRect = _leds[0]; + var iconRect = _leds[0]; iconRect.Height = 16; // (DockPanel's damn hardcoded height) // this.leds[this.leds.Length - 1].Bottom; iconRect.Width = iconRect.Right + 6; Bitmap bmp = new(iconRect.Width, iconRect.Height); @@ -724,7 +724,7 @@ private Icon CreateLedIcon (int level, bool dirty, int tailState, int syncMode) for (var i = 0; i < _leds.Length; ++i) { - Rectangle ledRect = _leds[i]; + var ledRect = _leds[i]; ledRect.Offset(0, offsetFromTop); if (level >= _leds.Length - i) @@ -739,7 +739,7 @@ private Icon CreateLedIcon (int level, bool dirty, int tailState, int syncMode) var ledSize = 3; var ledGap = 1; - Rectangle lastLed = _leds[^1]; + var lastLed = _leds[^1]; Rectangle dirtyLed = new(lastLed.Right + 2, lastLed.Bottom - ledSize, ledSize, ledSize); Rectangle tailLed = new(dirtyLed.Location, dirtyLed.Size); tailLed.Offset(0, -(ledSize + ledGap)); @@ -818,7 +818,7 @@ private void FileNotFound (LogWindow.LogWindow logWin) private void FileRespawned (LogWindow.LogWindow logWin) { var data = logWin.Tag as LogWindowData; - Icon icon = GetIcon(0, data); + var icon = GetIcon(0, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); } @@ -831,7 +831,7 @@ private void ShowLedPeak (LogWindow.LogWindow logWin) data.DiffSum = DIFF_MAX; } - Icon icon = GetIcon(data.DiffSum, data); + var icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); } @@ -872,7 +872,7 @@ private void LedThreadProc () lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { var data = logWindow.Tag as LogWindowData; if (data.DiffSum > 0) @@ -883,7 +883,7 @@ private void LedThreadProc () data.DiffSum = 0; } - Icon icon = GetIcon(data.DiffSum, data); + var icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); } } @@ -903,7 +903,7 @@ private void SetTabIcon (LogWindow.LogWindow logWindow, Icon icon) private Icon GetIcon (int diff, LogWindowData data) { - Icon icon = + var icon = _ledIcons[ GetLevelFromDiff(diff), data.Dirty ? 1 : 0, Preferences.ShowTailState ? data.TailState : 3, data.SyncMode @@ -978,7 +978,7 @@ private void NotifyWindowsForChangedPrefs (SettingsFlags flags) lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { logWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, false, flags); } @@ -1031,10 +1031,10 @@ private void SetTabIcons (Preferences preferences) CreateIcons(); lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { var data = logWindow.Tag as LogWindowData; - Icon icon = GetIcon(data.DiffSum, data); + var icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); } } @@ -1043,18 +1043,15 @@ private void SetTabIcons (Preferences preferences) [SupportedOSPlatform("windows")] private void SetToolIcon (ToolEntry entry, ToolStripItem item) { - Icon icon = NativeMethods.LoadIconFromExe(entry.IconFile, entry.IconIndex); + var icon = NativeMethods.LoadIconFromExe(entry.IconFile, entry.IconIndex); + if (icon != null) { item.Image = icon.ToBitmap(); - if (item is ToolStripMenuItem) - { - item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; - } - else - { - item.DisplayStyle = ToolStripItemDisplayStyle.Image; - } + + item.DisplayStyle = item is ToolStripMenuItem + ? ToolStripItemDisplayStyle.ImageAndText + : ToolStripItemDisplayStyle.Image; NativeMethods.DestroyIcon(icon.Handle); icon.Dispose(); @@ -1078,8 +1075,8 @@ private void ToolButtonClick (ToolEntry toolEntry) if (CurrentLogWindow != null) { - ILogLine line = CurrentLogWindow.GetCurrentLine(); - ILogFileInfo info = CurrentLogWindow.GetCurrentFileInfo(); + var line = CurrentLogWindow.GetCurrentLine(); + var info = CurrentLogWindow.GetCurrentFileInfo(); if (line != null && info != null) { ArgParser parser = new(toolEntry.Args); @@ -1112,7 +1109,7 @@ private void StartTool (string cmd, string args, bool sysoutPipe, string columni if (sysoutPipe) { - ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + var columnizer = ColumnizerPicker.DecideColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); _logger.Info("Starting external tool with sysout redirection: {0} {1}", cmd, args); startInfo.UseShellExecute = false; @@ -1131,7 +1128,7 @@ private void StartTool (string cmd, string args, bool sysoutPipe, string columni SysoutPipe pipe = new(process.StandardOutput); - LogWindow.LogWindow logWin = AddTempFileTab(pipe.FileName, + var logWin = AddTempFileTab(pipe.FileName, CurrentLogWindow.IsTempFile ? CurrentLogWindow.TempTitleName : Util.GetNameFromPath(CurrentLogWindow.FileName) + "->E"); @@ -1163,7 +1160,7 @@ private void CloseAllTabs () IList
closeList = []; lock (_logWindowList) { - foreach (DockContent content in dockPanel.Contents) + foreach (var content in dockPanel.Contents.Cast()) { if (content is LogWindow.LogWindow window) { @@ -1172,12 +1169,13 @@ private void CloseAllTabs () } } - foreach (Form form in closeList) + foreach (var form in closeList) { form.Close(); } } + //TODO Reimplement private void SetTabColor (LogWindow.LogWindow logWindow, Color color) { //tabPage.BackLowColor = color; @@ -1191,7 +1189,7 @@ private void SetTabColor (LogWindow.LogWindow logWindow, Color color) [SupportedOSPlatform("windows")] private void LoadProject (string projectFileName, bool restoreLayout) { - ProjectData projectData = ProjectPersister.LoadProjectData(projectFileName); + var projectData = ProjectPersister.LoadProjectData(projectFileName); var hasLayoutData = projectData.TabLayoutXml != null; if (hasLayoutData && restoreLayout && _logWindowList.Count > 0) @@ -1259,7 +1257,7 @@ private void FillToolLauncherBar () externalToolsToolStrip.Items.Clear(); var num = 0; externalToolsToolStrip.SuspendLayout(); - foreach (ToolEntry tool in Preferences.ToolEntries) + foreach (var tool in Preferences.ToolEntries) { if (tool.IsFavourite) { @@ -1354,7 +1352,7 @@ private IDockContent DeserializeDockContent (string persistString) if (persistString.StartsWith(WindowTypes.LogWindow.ToString())) { var fileName = persistString[(WindowTypes.LogWindow.ToString().Length + 1)..]; - LogWindow.LogWindow win = FindWindowForFile(fileName); + var win = FindWindowForFile(fileName); if (win != null) { return win; diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index b438a93a..b186b787 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -11,7 +11,6 @@ namespace LogExpert.UI.Entities; //TOOD: This whole class should be refactored and rethought -//TODO: This class should not knoow ConfigManager? internal static class PaintHelper { #region Fields From b9684ac6a592a49001da22cc6184e56d2c8550c5 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 12:32:47 +0200 Subject: [PATCH 06/26] optimization --- .../EventArguments/BookmarkEventArgs.cs | 4 +- .../EventHandlers/EventHandlers.cs | 6 +- .../Controls/LogWindow/LogWindow.cs | 48 ++------ .../LogWindow/LogWindowEventHandlers.cs | 4 +- .../Controls/LogWindow/LogWindowPrivate.cs | 10 +- .../LogTabWindow/LogTabWindow.designer.cs | 13 +-- .../LogTabWindow/LogTabWindowEventHandlers.cs | 106 +++++++++++------- .../LogTabWindow/LogTabWindowPrivate.cs | 3 +- .../LogTabWindow/LogTabWindowPublic.cs | 26 ++--- src/LogExpert.UI/LogExpert.UI.csproj | 2 - 10 files changed, 109 insertions(+), 113 deletions(-) diff --git a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs index 869b34be..d2156111 100644 --- a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs +++ b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs @@ -1,8 +1,8 @@ -using LogExpert.Core.Entities; +using LogExpert.Core.Entities; namespace LogExpert.Core.EventArguments; -public class BookmarkEventArgs(Bookmark bookmark) : System.EventArgs +public class BookmarkEventArgs (Bookmark bookmark) : EventArgs { #region Properties diff --git a/src/LogExpert.Core/EventHandlers/EventHandlers.cs b/src/LogExpert.Core/EventHandlers/EventHandlers.cs index 63f44923..e9af888e 100644 --- a/src/LogExpert.Core/EventHandlers/EventHandlers.cs +++ b/src/LogExpert.Core/EventHandlers/EventHandlers.cs @@ -1,7 +1,7 @@ -using LogExpert.Core.Entities; +using LogExpert.Core.Entities; using LogExpert.Core.EventArguments; namespace LogExpert.Core.EventHandlers; -public delegate void ConfigChangedEventHandler(object sender, ConfigChangedEventArgs e); -public delegate void FileSizeChangedEventHandler(object sender, LogEventArgs e); +public delegate void ConfigChangedEventHandler (object sender, ConfigChangedEventArgs e); +public delegate void FileSizeChangedEventHandler (object sender, LogEventArgs e); diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index eb2c9b96..e0296d67 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -263,37 +263,13 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp #region Delegates - public delegate void BookmarkAddedEventHandler (object sender, EventArgs e); - - public delegate void BookmarkRemovedEventHandler (object sender, EventArgs e); - - public delegate void BookmarkTextChangedEventHandler (object sender, BookmarkEventArgs e); - - public delegate void ColumnizerChangedEventHandler (object sender, ColumnizerEventArgs e); - - public delegate void CurrentHighlightGroupChangedEventHandler (object sender, CurrentHighlightGroupChangedEventArgs e); - - public delegate void FileNotFoundEventHandler (object sender, EventArgs e); - - public delegate void FileRespawnedEventHandler (object sender, EventArgs e); - - public delegate void FilterListChangedEventHandler (object sender, FilterListChangedEventArgs e); - // used for filterTab restore public delegate void FilterRestoreFx (LogWindow newWin, PersistenceData persistenceData); - public delegate void GuiStateEventHandler (object sender, GuiStateArgs e); - - public delegate void ProgressBarEventHandler (object sender, ProgressEventArgs e); - public delegate void RestoreFiltersFx (PersistenceData persistenceData); public delegate bool ScrollToTimestampFx (DateTime timestamp, bool roundToSeconds, bool triggerSyncCall); - public delegate void StatusLineEventHandler (object sender, StatusLineEventArgs e); - - public delegate void SyncModeChangedEventHandler (object sender, SyncModeEventArgs e); - public delegate void TailFollowedEventHandler (object sender, EventArgs e); #endregion @@ -302,31 +278,31 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp public event FileSizeChangedEventHandler FileSizeChanged; - public event ProgressBarEventHandler ProgressBarUpdate; + public event EventHandler ProgressBarUpdate; - public event StatusLineEventHandler StatusLineEvent; + public event EventHandler StatusLineEvent; - public event GuiStateEventHandler GuiStateUpdate; + public event EventHandler GuiStateUpdate; public event TailFollowedEventHandler TailFollowed; - public event FileNotFoundEventHandler FileNotFound; + public event EventHandler FileNotFound; - public event FileRespawnedEventHandler FileRespawned; + public event EventHandler FileRespawned; - public event FilterListChangedEventHandler FilterListChanged; + public event EventHandler FilterListChanged; - public event CurrentHighlightGroupChangedEventHandler CurrentHighlightGroupChanged; + public event EventHandler CurrentHighlightGroupChanged; - public event BookmarkAddedEventHandler BookmarkAdded; + public event EventHandler BookmarkAdded; - public event BookmarkRemovedEventHandler BookmarkRemoved; + public event EventHandler BookmarkRemoved; - public event BookmarkTextChangedEventHandler BookmarkTextChanged; + public event EventHandler BookmarkTextChanged; - public event ColumnizerChangedEventHandler ColumnizerChanged; + public event EventHandler ColumnizerChanged; - public event SyncModeChangedEventHandler SyncModeChanged; + public event EventHandler SyncModeChanged; #endregion diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index 245a18e7..75941c23 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -67,12 +67,12 @@ protected void OnCurrentHighlightListChanged () protected void OnBookmarkAdded () { - BookmarkAdded?.Invoke(this, EventArgs.Empty); + BookmarkAdded?.Invoke(this, (BookmarkEventArgs)EventArgs.Empty); } protected void OnBookmarkRemoved () { - BookmarkRemoved?.Invoke(this, EventArgs.Empty); + BookmarkRemoved?.Invoke(this, (BookmarkEventArgs)EventArgs.Empty); } protected void OnBookmarkTextChanged (Bookmark bookmark) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs index b972f7a3..2fe5aa81 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs @@ -59,13 +59,13 @@ private void CreateDefaultViewStyle () dataGridViewCellStyleMainGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); dataGridViewCellStyleMainGrid.ForeColor = SystemColors.ControlText; dataGridViewCellStyleMainGrid.SelectionBackColor = SystemColors.Highlight; - dataGridViewCellStyleMainGrid.SelectionForeColor = SystemColors.HighlightText; + //dataGridViewCellStyleMainGrid.SelectionForeColor = SystemColors.HighlightText; var highlightColor = SystemColors.Highlight; //Color is smaller than 128, means its darker - var isDark = (highlightColor.R * 0.2126) + (highlightColor.G * 0.7152) + (highlightColor.B * 0.0722) < 255 / 2; + var isSelectionBackColorDark = (highlightColor.R * 0.2126) + (highlightColor.G * 0.7152) + (highlightColor.B * 0.0722) < 255 / 2; - if (isDark) + if (isSelectionBackColorDark) { dataGridViewCellStyleMainGrid.SelectionForeColor = Color.White; } @@ -83,9 +83,9 @@ private void CreateDefaultViewStyle () dataGridViewCellStyleFilterGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); dataGridViewCellStyleFilterGrid.ForeColor = SystemColors.ControlText; dataGridViewCellStyleFilterGrid.SelectionBackColor = SystemColors.Highlight; - dataGridViewCellStyleFilterGrid.SelectionForeColor = SystemColors.HighlightText; + //dataGridViewCellStyleFilterGrid.SelectionForeColor = SystemColors.HighlightText; - if (isDark) + if (isSelectionBackColorDark) { dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.White; } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs index 88684eb7..6dc8e85e 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs @@ -173,7 +173,7 @@ private void InitializeComponent() statusStrip.Location = new System.Drawing.Point(0, 954); statusStrip.Name = "statusStrip"; statusStrip.Padding = new Padding(3, 0, 23, 0); - statusStrip.Size = new System.Drawing.Size(1603, 63); + statusStrip.Size = new System.Drawing.Size(1603, 35); statusStrip.SizingGrip = false; statusStrip.TabIndex = 5; statusStrip.Text = "statusStrip1"; @@ -184,7 +184,7 @@ private void InitializeComponent() labelLines.BorderSides = ToolStripStatusLabelBorderSides.Left | ToolStripStatusLabelBorderSides.Top | ToolStripStatusLabelBorderSides.Right | ToolStripStatusLabelBorderSides.Bottom; labelLines.BorderStyle = Border3DStyle.SunkenOuter; labelLines.Name = "labelLines"; - labelLines.Size = new System.Drawing.Size(26, 58); + labelLines.Size = new System.Drawing.Size(26, 35); labelLines.Text = "0"; // // labelSize @@ -193,7 +193,7 @@ private void InitializeComponent() labelSize.BorderSides = ToolStripStatusLabelBorderSides.Left | ToolStripStatusLabelBorderSides.Top | ToolStripStatusLabelBorderSides.Right | ToolStripStatusLabelBorderSides.Bottom; labelSize.BorderStyle = Border3DStyle.SunkenOuter; labelSize.Name = "labelSize"; - labelSize.Size = new System.Drawing.Size(26, 58); + labelSize.Size = new System.Drawing.Size(26, 35); labelSize.Text = "0"; // // labelCurrentLine @@ -202,18 +202,18 @@ private void InitializeComponent() labelCurrentLine.BorderSides = ToolStripStatusLabelBorderSides.Left | ToolStripStatusLabelBorderSides.Top | ToolStripStatusLabelBorderSides.Right | ToolStripStatusLabelBorderSides.Bottom; labelCurrentLine.BorderStyle = Border3DStyle.SunkenOuter; labelCurrentLine.Name = "labelCurrentLine"; - labelCurrentLine.Size = new System.Drawing.Size(28, 58); + labelCurrentLine.Size = new System.Drawing.Size(28, 35); labelCurrentLine.Text = "L:"; // // loadProgessBar // loadProgessBar.Name = "loadProgessBar"; - loadProgessBar.Size = new System.Drawing.Size(83, 57); + loadProgessBar.Size = new System.Drawing.Size(83, 35); // // labelStatus // labelStatus.Name = "labelStatus"; - labelStatus.Size = new System.Drawing.Size(39, 58); + labelStatus.Size = new System.Drawing.Size(39, 35); labelStatus.Text = "Ready"; // // mainMenuStrip @@ -833,7 +833,6 @@ private void InitializeComponent() dockPanel.Dock = DockStyle.Fill; dockPanel.DockBackColor = System.Drawing.SystemColors.Control; dockPanel.DocumentStyle = DocumentStyle.DockingWindow; - dockPanel.ForeColor = System.Drawing.SystemColors.Control; dockPanel.Location = new System.Drawing.Point(0, 0); dockPanel.Margin = new Padding(0); dockPanel.Name = "dockPanel"; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index 16e7ed7e..09c742e3 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -44,7 +44,7 @@ private void OnLogTabWindowLoad (object sender, EventArgs e) if (ConfigManager.Settings.Preferences.OpenLastFiles && _startupFileNames == null) { - List tmpList = ObjectClone.Clone(ConfigManager.Settings.LastOpenFilesList); + var tmpList = ObjectClone.Clone(ConfigManager.Settings.LastOpenFilesList); foreach (var name in tmpList) { @@ -54,12 +54,16 @@ private void OnLogTabWindowLoad (object sender, EventArgs e) } } } + if (_startupFileNames != null) { LoadFiles(_startupFileNames, false); } - _ledThread = new Thread(LedThreadProc); - _ledThread.IsBackground = true; + + _ledThread = new Thread(LedThreadProc) + { + IsBackground = true + }; _ledThread.Start(); FillHighlightComboBox(); @@ -78,16 +82,16 @@ private void OnLogTabWindowClosing (object sender, CancelEventArgs e) _statusLineEventWakeupHandle.Set(); _ledThread.Join(); - IList deleteLogWindowList = new List(); + IList deleteLogWindowList = []; ConfigManager.Settings.AlwaysOnTop = TopMost && ConfigManager.Settings.Preferences.AllowOnlyOneInstance; SaveLastOpenFilesList(); - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { deleteLogWindowList.Add(logWindow); } - foreach (LogWindow.LogWindow logWindow in deleteLogWindowList) + foreach (var logWindow in deleteLogWindowList) { RemoveAndDisposeLogWindow(logWindow, true); } @@ -153,10 +157,12 @@ private void OnSelectFilterToolStripMenuItemClick (object sender, EventArgs e) } CurrentLogWindow.ColumnizerCallbackObject.LineNum = CurrentLogWindow.GetCurrentLineNum(); - FilterSelectorForm form = new(PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers, CurrentLogWindow.CurrentColumnizer, CurrentLogWindow.ColumnizerCallbackObject, ConfigManager); - form.Owner = this; - form.TopMost = TopMost; - DialogResult res = form.ShowDialog(); + FilterSelectorForm form = new(PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers, CurrentLogWindow.CurrentColumnizer, CurrentLogWindow.ColumnizerCallbackObject, ConfigManager) + { + Owner = this, + TopMost = TopMost + }; + var res = form.ShowDialog(); if (res == DialogResult.OK) { @@ -164,7 +170,7 @@ private void OnSelectFilterToolStripMenuItemClick (object sender, EventArgs e) { lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { if (logWindow.CurrentColumnizer.GetType() != form.SelectedColumnizer.GetType()) { @@ -196,7 +202,7 @@ private void OnSelectFilterToolStripMenuItemClick (object sender, EventArgs e) { lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { if (logWindow.CurrentColumnizer.GetType() == form.SelectedColumnizer.GetType()) { @@ -217,7 +223,7 @@ private void OnGoToLineToolStripMenuItemClick (object sender, EventArgs e) } GotoLineDialog dlg = new(this); - DialogResult res = dlg.ShowDialog(); + var res = dlg.ShowDialog(); if (res == DialogResult.OK) { var line = dlg.Line - 1; @@ -253,7 +259,8 @@ private void OnLogTabWindowDragEnter (object sender, DragEventArgs e) s += format; s += " , "; } - s = s.Substring(0, s.Length - 3); + + s = s[..^3]; _logger.Info(s); #endif } @@ -280,6 +287,7 @@ private void OnLogWindowDragDrop (object sender, DragEventArgs e) s += format; s += " , "; } + s = s[..^3]; _logger.Debug(s); #endif @@ -310,8 +318,11 @@ private void OnTimeShiftToolStripMenuItemCheckStateChanged (object sender, Event [SupportedOSPlatform("windows")] private void OnAboutToolStripMenuItemClick (object sender, EventArgs e) { - AboutBox aboutBox = new(); - aboutBox.TopMost = TopMost; + AboutBox aboutBox = new() + { + TopMost = TopMost + }; + aboutBox.ShowDialog(); } @@ -338,7 +349,7 @@ private void OnColumnizerChanged (object sender, ColumnizerEventArgs e) _bookmarkWindow?.SetColumnizer(e.Columnizer); } - private void OnBookmarkAdded (object sender, EventArgs e) + private void OnBookmarkAdded (object sender, BookmarkEventArgs e) { _bookmarkWindow.UpdateView(); } @@ -348,7 +359,7 @@ private void OnBookmarkTextChanged (object sender, BookmarkEventArgs e) _bookmarkWindow.BookmarkTextChanged(e.Bookmark); } - private void OnBookmarkRemoved (object sender, EventArgs e) + private void OnBookmarkRemoved (object sender, BookmarkEventArgs e) { _bookmarkWindow.UpdateView(); } @@ -448,7 +459,7 @@ private void OnFileSizeChanged (object sender, LogEventArgs e) { data.Dirty = true; } - Icon icon = GetIcon(diff, data); + var icon = GetIcon(diff, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); } } @@ -468,7 +479,7 @@ private void OnLogWindowFilterListChanged (object sender, FilterListChangedEvent { lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { if (logWindow != e.LogWindow) { @@ -498,7 +509,7 @@ private void OnTailFollowed (object sender, EventArgs e) { var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; data.Dirty = false; - Icon icon = GetIcon(data.DiffSum, data); + var icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); } } @@ -511,7 +522,7 @@ private void OnLogWindowSyncModeChanged (object sender, SyncModeEventArgs e) { var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; data.SyncMode = e.IsTimeSynced ? 1 : 0; - Icon icon = GetIcon(data.DiffSum, data); + var icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); } else @@ -574,7 +585,7 @@ private void OnReloadToolStripMenuItemClick (object sender, EventArgs e) if (CurrentLogWindow != null) { var data = CurrentLogWindow.Tag as LogWindowData; - Icon icon = GetIcon(0, data); + var icon = GetIcon(0, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), CurrentLogWindow, icon); CurrentLogWindow.Reload(); } @@ -680,7 +691,7 @@ private void OnHideLineColumnToolStripMenuItemClick (object sender, EventArgs e) ConfigManager.Settings.HideLineColumn = hideLineColumnToolStripMenuItem.Checked; lock (_logWindowList) { - foreach (LogWindow.LogWindow logWin in _logWindowList) + foreach (var logWin in _logWindowList) { logWin.ShowLineColumn(!ConfigManager.Settings.HideLineColumn); } @@ -708,11 +719,12 @@ private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) { if (content != dockPanel.ActiveContent && content is LogWindow.LogWindow) { - closeList.Add(content as Form); + closeList.Add(content); } } } - foreach (Form form in closeList) + + foreach (var form in closeList) { form.Close(); } @@ -729,15 +741,16 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) { var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; - var data = logWindow.Tag as LogWindowData; - - if (data == null) + if (logWindow.Tag is not LogWindowData data) { return; } - ColorDialog dlg = new(); - dlg.Color = data.Color; + ColorDialog dlg = new() + { + Color = data.Color + }; + if (dlg.ShowDialog() == DialogResult.OK) { data.Color = dlg.Color; @@ -745,7 +758,7 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) } List delList = []; - foreach (ColorEntry entry in ConfigManager.Settings.FileColors) + foreach (var entry in ConfigManager.Settings.FileColors) { if (entry.FileName.Equals(logWindow.FileName, StringComparison.Ordinal)) { @@ -753,10 +766,11 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) } } - foreach (ColorEntry entry in delList) + foreach (var entry in delList) { ConfigManager.Settings.FileColors.Remove(entry); } + ConfigManager.Settings.FileColors.Add(new ColorEntry(logWindow.FileName, dlg.Color)); while (ConfigManager.Settings.FileColors.Count > MAX_COLOR_HISTORY) @@ -777,9 +791,11 @@ private void OnLogTabWindowSizeChanged (object sender, EventArgs e) [SupportedOSPlatform("windows")] private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) { - SaveFileDialog dlg = new(); - dlg.DefaultExt = "lxj"; - dlg.Filter = @"LogExpert session (*.lxj)|*.lxj"; + SaveFileDialog dlg = new() + { + DefaultExt = "lxj", + Filter = @"LogExpert session (*.lxj)|*.lxj" + }; if (dlg.ShowDialog() == DialogResult.OK) { @@ -799,9 +815,11 @@ private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) } } - ProjectData projectData = new(); - projectData.MemberList = fileNames; - projectData.TabLayoutXml = SaveLayout(); + ProjectData projectData = new() + { + MemberList = fileNames, + TabLayoutXml = SaveLayout() + }; ProjectPersister.SaveProjectData(fileName, projectData); } } @@ -809,9 +827,11 @@ private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) [SupportedOSPlatform("windows")] private void OnLoadProjectToolStripMenuItemClick (object sender, EventArgs e) { - OpenFileDialog dlg = new(); - dlg.DefaultExt = "lxj"; - dlg.Filter = @"LogExpert sessions (*.lxj)|*.lxj"; + OpenFileDialog dlg = new() + { + DefaultExt = "lxj", + Filter = @"LogExpert sessions (*.lxj)|*.lxj" + }; if (dlg.ShowDialog() == DialogResult.OK) { @@ -1073,10 +1093,12 @@ private void OnTabRenameToolStripMenuItemClick (object sender, EventArgs e) { TabName = CurrentLogWindow.Text }; + if (DialogResult.OK == dlg.ShowDialog()) { CurrentLogWindow.Text = dlg.TabName; } + dlg.Dispose(); } } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs index 886052ac..da31f049 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs @@ -685,6 +685,7 @@ private void ProgressBarUpdateWorker (ProgressEventArgs e) } [SupportedOSPlatform("windows")] + //TODO Crossthread Exception when a log file has been filtered to a new tab! private void StatusLineEventWorker (StatusLineEventArgs e) { if (e != null) @@ -1160,7 +1161,7 @@ private void CloseAllTabs () IList closeList = []; lock (_logWindowList) { - foreach (var content in dockPanel.Contents.Cast()) + foreach (DockContent content in dockPanel.Contents) { if (content is LogWindow.LogWindow window) { diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs index 56d639ce..3751f2eb 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs @@ -28,7 +28,7 @@ public LogWindow.LogWindow AddTempFileTab (string fileName, string title) [SupportedOSPlatform("windows")] public LogWindow.LogWindow AddFilterTab (FilterPipe pipe, string title, ILogLineColumnizer preProcessColumnizer) { - LogWindow.LogWindow logWin = AddFileTab(pipe.FileName, true, title, false, preProcessColumnizer); + var logWin = AddFileTab(pipe.FileName, true, title, false, preProcessColumnizer); if (pipe.FilterParams.SearchText.Length > 0) { ToolTip tip = new(components); @@ -58,7 +58,7 @@ public LogWindow.LogWindow AddFileTabDeferred (string givenFileName, bool isTemp public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer, bool doNotAddToDockPanel = false) { var logFileName = FindFilenameForSettings(givenFileName); - LogWindow.LogWindow win = FindWindowForFile(logFileName); + var win = FindWindowForFile(logFileName); if (win != null) { if (!isTempFile) @@ -100,7 +100,7 @@ public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, st //data.tabPage.BorderColor = this.defaultTabBorderColor; if (!isTempFile) { - foreach (ColorEntry colorEntry in ConfigManager.Settings.FileColors) + foreach (var colorEntry in ConfigManager.Settings.FileColors) { if (colorEntry.FileName.ToUpperInvariant().Equals(logFileName.ToUpperInvariant(), StringComparison.Ordinal)) { @@ -164,7 +164,7 @@ public void OpenSearchDialog () dlg.TopMost = TopMost; SearchParams.HistoryList = ConfigManager.Settings.SearchHistoryList; dlg.SearchParams = SearchParams; - DialogResult res = dlg.ShowDialog(); + var res = dlg.ShowDialog(); if (res == DialogResult.OK && dlg.SearchParams != null && !string.IsNullOrWhiteSpace(dlg.SearchParams.SearchText)) { SearchParams = dlg.SearchParams; @@ -175,10 +175,10 @@ public void OpenSearchDialog () public ILogLineColumnizer GetColumnizerHistoryEntry (string fileName) { - ColumnizerHistoryEntry entry = FindColumnizerHistoryEntry(fileName); + var entry = FindColumnizerHistoryEntry(fileName); if (entry != null) { - foreach (ILogLineColumnizer columnizer in PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers) + foreach (var columnizer in PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers) { if (columnizer.GetName().Equals(entry.ColumnizerName, StringComparison.Ordinal)) { @@ -227,7 +227,7 @@ public void ScrollAllTabsToTimestamp (DateTime timestamp, LogWindow.LogWindow se { lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { if (logWindow != senderWindow) { @@ -242,7 +242,7 @@ public void ScrollAllTabsToTimestamp (DateTime timestamp, LogWindow.LogWindow se public ILogLineColumnizer FindColumnizerByFileMask (string fileName) { - foreach (ColumnizerMaskEntry entry in ConfigManager.Settings.Preferences.ColumnizerMaskList) + foreach (var entry in ConfigManager.Settings.Preferences.ColumnizerMaskList) { if (entry.Mask != null) { @@ -250,7 +250,7 @@ public ILogLineColumnizer FindColumnizerByFileMask (string fileName) { if (Regex.IsMatch(fileName, entry.Mask)) { - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(entry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + var columnizer = ColumnizerPicker.FindColumnizerByName(entry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); return columnizer; } } @@ -267,7 +267,7 @@ public ILogLineColumnizer FindColumnizerByFileMask (string fileName) public HighlightGroup FindHighlightGroupByFileMask (string fileName) { - foreach (HighlightMaskEntry entry in ConfigManager.Settings.Preferences.HighlightMaskList) + foreach (var entry in ConfigManager.Settings.Preferences.HighlightMaskList) { if (entry.Mask != null) { @@ -275,7 +275,7 @@ public HighlightGroup FindHighlightGroupByFileMask (string fileName) { if (Regex.IsMatch(fileName, entry.Mask)) { - HighlightGroup group = FindHighlightGroup(entry.HighlightGroupName); + var group = FindHighlightGroup(entry.HighlightGroupName); return group; } } @@ -332,7 +332,7 @@ public void FollowTailChanged (LogWindow.LogWindow logWindow, bool isEnabled, bo if (Preferences.ShowTailState) { - Icon icon = GetIcon(data.DiffSum, data); + var icon = GetIcon(data.DiffSum, data); BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); } } @@ -351,7 +351,7 @@ public IList GetListOfOpenFiles () IList list = []; lock (_logWindowList) { - foreach (LogWindow.LogWindow logWindow in _logWindowList) + foreach (var logWindow in _logWindowList) { list.Add(new WindowFileEntry(logWindow)); } diff --git a/src/LogExpert.UI/LogExpert.UI.csproj b/src/LogExpert.UI/LogExpert.UI.csproj index 145fbbc4..396fd4a3 100644 --- a/src/LogExpert.UI/LogExpert.UI.csproj +++ b/src/LogExpert.UI/LogExpert.UI.csproj @@ -26,9 +26,7 @@ - - From fadcd9a3769198cad7cb088b12ca609e572292cc Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 12:58:24 +0200 Subject: [PATCH 07/26] made splitter moveable, for higher dpi or different Screens --- .../Controls/LogWindow/LogWindow.cs | 2 +- .../Controls/LogWindow/LogWindow.designer.cs | 34 +++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index e0296d67..0727db36 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -30,7 +30,7 @@ internal partial class LogWindow : DockContent, ILogPaintContextUI, ILogView, IL private const int SPREAD_MAX = 99; private const int PROGRESS_BAR_MODULO = 1000; - private const int FILTER_ADVANCED_SPLITTER_DISTANCE = 150; + private const int FILTER_ADVANCED_SPLITTER_DISTANCE = 110; private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly Image _advancedButtonImage; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs index c49e42bf..2aceb815 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs @@ -32,10 +32,10 @@ protected override void Dispose(bool disposing) /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() + private void InitializeComponent () { components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LogWindow)); + var resources = new System.ComponentModel.ComponentResourceManager(typeof(LogWindow)); splitContainerLogWindow = new SplitContainer(); tableLayoutPanel1 = new TableLayoutPanel(); columnFinderPanel = new Panel(); @@ -439,7 +439,6 @@ private void InitializeComponent() // advancedFilterSplitContainer // advancedFilterSplitContainer.Dock = DockStyle.Fill; - advancedFilterSplitContainer.IsSplitterFixed = true; advancedFilterSplitContainer.Location = new Point(0, 0); advancedFilterSplitContainer.Margin = new Padding(0); advancedFilterSplitContainer.Name = "advancedFilterSplitContainer"; @@ -448,14 +447,15 @@ private void InitializeComponent() // advancedFilterSplitContainer.Panel1 // advancedFilterSplitContainer.Panel1.Controls.Add(pnlProFilter); - advancedFilterSplitContainer.Panel1MinSize = 100; + advancedFilterSplitContainer.Panel1MinSize = 50; // // advancedFilterSplitContainer.Panel2 // advancedFilterSplitContainer.Panel2.Controls.Add(panelBackgroundAdvancedFilterSplitContainer); - advancedFilterSplitContainer.Panel2MinSize = 200; + advancedFilterSplitContainer.Panel2MinSize = 50; advancedFilterSplitContainer.Size = new Size(1855, 561); - advancedFilterSplitContainer.SplitterDistance = 124; + advancedFilterSplitContainer.SplitterDistance = 110; + advancedFilterSplitContainer.Panel2Collapsed = true; advancedFilterSplitContainer.SplitterWidth = 2; advancedFilterSplitContainer.TabIndex = 2; // @@ -478,7 +478,7 @@ private void InitializeComponent() pnlProFilter.Controls.Add(btnFilterToTab); pnlProFilter.Location = new Point(0, 3); pnlProFilter.Name = "pnlProFilter"; - pnlProFilter.Size = new Size(1852, 117); + pnlProFilter.Size = new Size(1852, 80); pnlProFilter.TabIndex = 0; // // columnButton @@ -575,7 +575,7 @@ private void InitializeComponent() // // pnlProFilterLabel // - pnlProFilterLabel.BackgroundImage = LogExpert.Resources.Resources.Pro_Filter; + pnlProFilterLabel.BackgroundImage = (Image)resources.GetObject("pnlProFilterLabel.BackgroundImage"); pnlProFilterLabel.BackgroundImageLayout = ImageLayout.Center; pnlProFilterLabel.Location = new Point(5, 7); pnlProFilterLabel.Name = "pnlProFilterLabel"; @@ -646,13 +646,13 @@ private void InitializeComponent() panelBackgroundAdvancedFilterSplitContainer.Dock = DockStyle.Fill; panelBackgroundAdvancedFilterSplitContainer.Location = new Point(0, 0); panelBackgroundAdvancedFilterSplitContainer.Name = "panelBackgroundAdvancedFilterSplitContainer"; - panelBackgroundAdvancedFilterSplitContainer.Size = new Size(1855, 435); + panelBackgroundAdvancedFilterSplitContainer.Size = new Size(1855, 474); panelBackgroundAdvancedFilterSplitContainer.TabIndex = 7; // // btnToggleHighlightPanel // btnToggleHighlightPanel.Anchor = AnchorStyles.Top | AnchorStyles.Right; - btnToggleHighlightPanel.Image = LogExpert.Resources.Resources.Arrow_menu_open; + btnToggleHighlightPanel.Image = (Image)resources.GetObject("btnToggleHighlightPanel.Image"); btnToggleHighlightPanel.Location = new Point(1832, 1); btnToggleHighlightPanel.Name = "btnToggleHighlightPanel"; btnToggleHighlightPanel.Size = new Size(20, 21); @@ -679,7 +679,7 @@ private void InitializeComponent() // highlightSplitContainer.Panel2.Controls.Add(highlightSplitContainerBackPanel); highlightSplitContainer.Panel2MinSize = 350; - highlightSplitContainer.Size = new Size(1829, 432); + highlightSplitContainer.Size = new Size(1829, 471); highlightSplitContainer.SplitterDistance = 1475; highlightSplitContainer.TabIndex = 2; // @@ -713,7 +713,7 @@ private void InitializeComponent() filterGridView.ShowCellToolTips = false; filterGridView.ShowEditingIcon = false; filterGridView.ShowRowErrors = false; - filterGridView.Size = new Size(1473, 430); + filterGridView.Size = new Size(1473, 469); filterGridView.TabIndex = 1; filterGridView.VirtualMode = true; filterGridView.CellContextMenuStripNeeded += OnFilterGridViewCellContextMenuStripNeeded; @@ -765,7 +765,7 @@ private void InitializeComponent() highlightSplitContainerBackPanel.Dock = DockStyle.Fill; highlightSplitContainerBackPanel.Location = new Point(0, 0); highlightSplitContainerBackPanel.Name = "highlightSplitContainerBackPanel"; - highlightSplitContainerBackPanel.Size = new Size(348, 430); + highlightSplitContainerBackPanel.Size = new Size(348, 469); highlightSplitContainerBackPanel.TabIndex = 1; // // hideFilterListOnLoadCheckBox @@ -782,7 +782,7 @@ private void InitializeComponent() // // filterDownButton // - filterDownButton.BackgroundImage = LogExpert.Resources.Resources.ArrowDown; + filterDownButton.BackgroundImage = (Image)resources.GetObject("filterDownButton.BackgroundImage"); filterDownButton.BackgroundImageLayout = ImageLayout.Stretch; filterDownButton.Location = new Point(296, 85); filterDownButton.Name = "filterDownButton"; @@ -795,7 +795,7 @@ private void InitializeComponent() // // filterUpButton // - filterUpButton.BackgroundImage = LogExpert.Resources.Resources.ArrowUp; + filterUpButton.BackgroundImage = (Image)resources.GetObject("filterUpButton.BackgroundImage"); filterUpButton.BackgroundImageLayout = ImageLayout.Stretch; filterUpButton.Location = new Point(258, 85); filterUpButton.Name = "filterUpButton"; @@ -850,7 +850,7 @@ private void InitializeComponent() filterListBox.ItemHeight = 25; filterListBox.Location = new Point(0, 0); filterListBox.Name = "filterListBox"; - filterListBox.Size = new Size(252, 430); + filterListBox.Size = new Size(252, 469); filterListBox.TabIndex = 0; helpToolTip.SetToolTip(filterListBox, "Doubleclick to load a saved filter"); filterListBox.DrawItem += OnFilterListBoxDrawItem; @@ -1034,7 +1034,7 @@ private void InitializeComponent() columnContextMenuStrip.ImageScalingSize = new Size(24, 24); columnContextMenuStrip.Items.AddRange(new ToolStripItem[] { freezeLeftColumnsUntilHereToolStripMenuItem, menuToolStripSeparator4, moveToLastColumnToolStripMenuItem, moveLeftToolStripMenuItem, moveRightToolStripMenuItem, menuToolStripSeparator5, hideColumnToolStripMenuItem, restoreColumnsToolStripMenuItem, menuToolStripSeparator6, allColumnsToolStripMenuItem }); columnContextMenuStrip.Name = "columnContextMenuStrip"; - columnContextMenuStrip.Size = new Size(230, 198); + columnContextMenuStrip.Size = new Size(230, 176); columnContextMenuStrip.Opening += OnColumnContextMenuStripOpening; // // freezeLeftColumnsUntilHereToolStripMenuItem From e7e1bef801bd151b43fd02b7a4f03893a4c74ba5 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 16 Jun 2025 20:32:24 +0200 Subject: [PATCH 08/26] update after review --- src/LogExpert.Core/Config/ColorEntry.cs | 10 +-- .../EventArguments/BookmarkEventArgs.cs | 13 ++- src/LogExpert.UI/Controls/ColorComboBox.cs | 41 +++++----- .../LogWindow/LogWindowEventHandlers.cs | 4 +- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 80 +++++++++---------- .../LogTabWindow/LogTabWindowEventHandlers.cs | 5 +- src/LogExpert.UI/LogExpert.UI.csproj | 1 - 7 files changed, 81 insertions(+), 73 deletions(-) diff --git a/src/LogExpert.Core/Config/ColorEntry.cs b/src/LogExpert.Core/Config/ColorEntry.cs index 521f2ae7..022f98a2 100644 --- a/src/LogExpert.Core/Config/ColorEntry.cs +++ b/src/LogExpert.Core/Config/ColorEntry.cs @@ -7,13 +7,9 @@ namespace LogExpert.Core.Config; [Serializable] -public class ColorEntry (string fileName, Color color) +public class ColorEntry (string FileName, Color Color) { - public Color Color { get; } = color; + public Color Color { get; } = Color; - public string FileName { get; } = fileName; - - #region Fields - - #endregion + public string FileName { get; } = FileName; } \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs index d2156111..da0f9e7e 100644 --- a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs +++ b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs @@ -2,11 +2,20 @@ namespace LogExpert.Core.EventArguments; -public class BookmarkEventArgs (Bookmark bookmark) : EventArgs +public class BookmarkEventArgs : EventArgs { + public BookmarkEventArgs (Bookmark bookmark) + { + Bookmark = bookmark; + } + + public BookmarkEventArgs () { } + + public static new readonly BookmarkEventArgs Empty = new(); + #region Properties - public Bookmark Bookmark { get; } = bookmark; + public Bookmark Bookmark { get; } #endregion } \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/ColorComboBox.cs b/src/LogExpert.UI/Controls/ColorComboBox.cs index 40ea6d4d..3827b7fe 100644 --- a/src/LogExpert.UI/Controls/ColorComboBox.cs +++ b/src/LogExpert.UI/Controls/ColorComboBox.cs @@ -18,27 +18,30 @@ public ColorComboBox () { DrawMode = DrawMode.OwnerDrawFixed; DrawItem += OnColorComboBoxDrawItem; - // add color presets if (!DesignMode) { - _ = Items.Add(_customColor); - _ = Items.Add(Color.Black); - _ = Items.Add(Color.White); - _ = Items.Add(Color.Gray); - _ = Items.Add(Color.DarkGray); - _ = Items.Add(Color.Blue); - _ = Items.Add(Color.LightBlue); - _ = Items.Add(Color.DarkBlue); - _ = Items.Add(Color.Green); - _ = Items.Add(Color.LightGreen); - _ = Items.Add(Color.DarkGreen); - _ = Items.Add(Color.Olive); - _ = Items.Add(Color.Red); - _ = Items.Add(Color.Pink); - _ = Items.Add(Color.Purple); - _ = Items.Add(Color.IndianRed); - _ = Items.Add(Color.DarkCyan); - _ = Items.Add(Color.Yellow); + Items.AddRange( + [ + _customColor, + Color.Black, + Color.White, + Color.Gray, + Color.DarkGray, + Color.Blue, + Color.LightBlue, + Color.DarkBlue, + Color.Green, + Color.LightGreen, + Color.DarkGreen, + Color.Olive, + Color.Red, + Color.Pink, + Color.Purple, + Color.IndianRed, + Color.DarkCyan, + Color.Yellow + ] + ); } } diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index 75941c23..fe124965 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -67,12 +67,12 @@ protected void OnCurrentHighlightListChanged () protected void OnBookmarkAdded () { - BookmarkAdded?.Invoke(this, (BookmarkEventArgs)EventArgs.Empty); + BookmarkAdded?.Invoke(this, BookmarkEventArgs.Empty); } protected void OnBookmarkRemoved () { - BookmarkRemoved?.Invoke(this, (BookmarkEventArgs)EventArgs.Empty); + BookmarkRemoved?.Invoke(this, BookmarkEventArgs.Empty); } protected void OnBookmarkTextChanged (Bookmark bookmark) diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 8a3518fa..336d3f7d 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -22,9 +22,9 @@ internal partial class BookmarkWindow : DockContent, ISharedToolWindow, IBookmar private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly object paintLock = new(); - private IBookmarkData bookmarkData; - private ILogPaintContextUI logPaintContext; - private ILogView logView; + private IBookmarkData _bookmarkData; + private ILogPaintContextUI _logPaintContext; + private ILogView _logView; #endregion @@ -102,7 +102,7 @@ public void ResizeColumns () public void UpdateView () { - bookmarkDataGridView.RowCount = bookmarkData?.Bookmarks.Count ?? 0; + bookmarkDataGridView.RowCount = _bookmarkData?.Bookmarks.Count ?? 0; ResizeColumns(); bookmarkDataGridView.Refresh(); } @@ -120,7 +120,7 @@ public void BookmarkTextChanged (Bookmark bookmark) return; } - if (bookmarkData.Bookmarks[rowIndex] == bookmark) + if (_bookmarkData.Bookmarks[rowIndex] == bookmark) { bookmarkTextBox.Text = bookmark.Text; } @@ -130,22 +130,22 @@ public void BookmarkTextChanged (Bookmark bookmark) public void SelectBookmark (int lineNum) { - if (bookmarkData.IsBookmarkAtLine(lineNum)) + if (_bookmarkData.IsBookmarkAtLine(lineNum)) { - if (bookmarkDataGridView.Rows.GetRowCount(DataGridViewElementStates.None) < bookmarkData.Bookmarks.Count) + if (bookmarkDataGridView.Rows.GetRowCount(DataGridViewElementStates.None) < _bookmarkData.Bookmarks.Count) { // just for the case... There was an exception but I cannot find the cause UpdateView(); } - var row = bookmarkData.GetBookmarkIndexForLine(lineNum); + var row = _bookmarkData.GetBookmarkIndexForLine(lineNum); bookmarkDataGridView.CurrentCell = bookmarkDataGridView.Rows[row].Cells[0]; } } public void SetBookmarkData (IBookmarkData bookmarkData) { - this.bookmarkData = bookmarkData; + _bookmarkData = bookmarkData; bookmarkDataGridView.RowCount = bookmarkData?.Bookmarks.Count ?? 0; HideIfNeeded(); } @@ -171,16 +171,16 @@ public void SetCurrentFile (IFileViewContext ctx) _logger.Debug($"Current file changed to {ctx.LogView.FileName}"); lock (paintLock) { - logView = ctx.LogView; - logPaintContext = (ILogPaintContextUI)ctx.LogPaintContext; + _logView = ctx.LogView; + _logPaintContext = (ILogPaintContextUI)ctx.LogPaintContext; } SetColumnizer(ctx.LogView.CurrentColumnizer); } else { - logView = null; - logPaintContext = null; + _logView = null; + _logPaintContext = null; } UpdateView(); @@ -270,11 +270,11 @@ private void DeleteSelectedBookmarks () { if (row.Index != -1) { - lineNumList.Add(bookmarkData.Bookmarks[row.Index].LineNum); + lineNumList.Add(_bookmarkData.Bookmarks[row.Index].LineNum); } } - logView?.DeleteBookmarks(lineNumList); + _logView?.DeleteBookmarks(lineNumList); } private static void InvalidateCurrentRow (BufferedDataGridView gridView) @@ -297,7 +297,7 @@ private void CurrentRowChanged (int rowIndex) } else { - var bookmark = bookmarkData.Bookmarks[rowIndex]; + var bookmark = _bookmarkData.Bookmarks[rowIndex]; bookmarkTextBox.Text = bookmark.Text; bookmarkTextBox.Enabled = true; } @@ -319,7 +319,7 @@ private void HideIfNeeded () private void OnBoomarkDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) { - if (bookmarkData == null) + if (_bookmarkData == null) { return; } @@ -328,13 +328,13 @@ private void OnBoomarkDataGridViewCellPainting (object sender, DataGridViewCellP { try { - if (e.RowIndex < 0 || e.ColumnIndex < 0 || bookmarkData.Bookmarks.Count <= e.RowIndex) + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _bookmarkData.Bookmarks.Count <= e.RowIndex) { e.Handled = false; return; } - var lineNum = bookmarkData.Bookmarks[e.RowIndex].LineNum; + var lineNum = _bookmarkData.Bookmarks[e.RowIndex].LineNum; // if (e.ColumnIndex == 1) // { @@ -342,7 +342,7 @@ private void OnBoomarkDataGridViewCellPainting (object sender, DataGridViewCellP // } { // else - PaintHelper.CellPainting(logPaintContext, bookmarkDataGridView, lineNum, e); + PaintHelper.CellPainting(_logPaintContext, bookmarkDataGridView, lineNum, e); } } catch (Exception ex) @@ -354,18 +354,18 @@ private void OnBoomarkDataGridViewCellPainting (object sender, DataGridViewCellP private void OnBoomarkDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) { - if (bookmarkData == null) + if (_bookmarkData == null) { return; } - if (e.RowIndex < 0 || e.ColumnIndex < 0 || bookmarkData.Bookmarks.Count <= e.RowIndex) + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _bookmarkData.Bookmarks.Count <= e.RowIndex) { e.Value = string.Empty; return; } - var bookmarkForLine = bookmarkData.Bookmarks[e.RowIndex]; + var bookmarkForLine = _bookmarkData.Bookmarks[e.RowIndex]; var lineNum = bookmarkForLine.LineNum; if (e.ColumnIndex == 1) { @@ -374,7 +374,7 @@ private void OnBoomarkDataGridViewCellValueNeeded (object sender, DataGridViewCe else { var columnIndex = e.ColumnIndex > 1 ? e.ColumnIndex - 1 : e.ColumnIndex; - e.Value = logPaintContext.GetCellValue(lineNum, columnIndex); + e.Value = _logPaintContext.GetCellValue(lineNum, columnIndex); } } @@ -400,10 +400,10 @@ private void OnBookmarkGridViewKeyDown (object sender, KeyEventArgs e) if (e.KeyCode == Keys.Enter) { if (bookmarkDataGridView.CurrentCellAddress.Y >= 0 && - bookmarkDataGridView.CurrentCellAddress.Y < bookmarkData.Bookmarks.Count) + bookmarkDataGridView.CurrentCellAddress.Y < _bookmarkData.Bookmarks.Count) { - var lineNum = bookmarkData.Bookmarks[bookmarkDataGridView.CurrentCellAddress.Y].LineNum; - logView.SelectLogLine(lineNum); + var lineNum = _bookmarkData.Bookmarks[bookmarkDataGridView.CurrentCellAddress.Y].LineNum; + _logView.SelectLogLine(lineNum); } e.Handled = true; @@ -452,20 +452,20 @@ private void OnBookmarkTextBoxTextChanged (object sender, EventArgs e) return; } - if (bookmarkData.Bookmarks.Count <= rowIndex) + if (_bookmarkData.Bookmarks.Count <= rowIndex) { return; } - var bookmark = bookmarkData.Bookmarks[rowIndex]; + var bookmark = _bookmarkData.Bookmarks[rowIndex]; bookmark.Text = bookmarkTextBox.Text; - logView?.RefreshLogView(); + _logView?.RefreshLogView(); } private void OnBookmarkDataGridViewSelectionChanged (object sender, EventArgs e) { if (bookmarkDataGridView.SelectedRows.Count != 1 - || bookmarkDataGridView.SelectedRows[0].Index >= bookmarkData.Bookmarks.Count) + || bookmarkDataGridView.SelectedRows[0].Index >= _bookmarkData.Bookmarks.Count) { CurrentRowChanged(-1); } @@ -486,12 +486,12 @@ private void OnBookmarkDataGridViewPreviewKeyDown (object sender, PreviewKeyDown private void OnBookmarkDataGridViewCellToolTipTextNeeded (object sender, DataGridViewCellToolTipTextNeededEventArgs e) { - if (e.ColumnIndex != 0 || e.RowIndex <= -1 || e.RowIndex >= bookmarkData.Bookmarks.Count) + if (e.ColumnIndex != 0 || e.RowIndex <= -1 || e.RowIndex >= _bookmarkData.Bookmarks.Count) { return; } - var bookmark = bookmarkData.Bookmarks[e.RowIndex]; + var bookmark = _bookmarkData.Bookmarks[e.RowIndex]; if (!string.IsNullOrEmpty(bookmark.Text)) { e.ToolTipText = bookmark.Text; @@ -505,11 +505,11 @@ private void OnBookmarkDataGridViewCellDoubleClick (object sender, DataGridViewC if (e.ColumnIndex == 0 && e.RowIndex >= 0 && bookmarkDataGridView.CurrentRow != null) { var index = bookmarkDataGridView.CurrentRow.Index; - var lineNum = bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; - bookmarkData.ToggleBookmark(lineNum); + var lineNum = _bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; + _bookmarkData.ToggleBookmark(lineNum); // we don't ask for confirmation if the bookmark has an associated comment... - var boomarkCount = bookmarkData.Bookmarks.Count; + var boomarkCount = _bookmarkData.Bookmarks.Count; bookmarkDataGridView.RowCount = boomarkCount; if (index < boomarkCount) @@ -546,8 +546,8 @@ private void OnBookmarkDataGridViewCellDoubleClick (object sender, DataGridViewC if (bookmarkDataGridView.CurrentRow != null && e.RowIndex >= 0) { - var lineNum = bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; - logView.SelectAndEnsureVisible(lineNum, true); + var lineNum = _bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; + _logView.SelectAndEnsureVisible(lineNum, true); } } @@ -563,13 +563,13 @@ private void OnRemoveCommentsToolStripMenuItemClick (object sender, EventArgs e) { if (row.Index != -1) { - bookmarkData.Bookmarks[row.Index].Text = string.Empty; + _bookmarkData.Bookmarks[row.Index].Text = string.Empty; } } bookmarkTextBox.Text = string.Empty; bookmarkDataGridView.Refresh(); - logView.RefreshLogView(); + _logView.RefreshLogView(); } } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index 09c742e3..d7124015 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -756,6 +756,7 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) data.Color = dlg.Color; SetTabColor(logWindow, data.Color); } + List delList = []; foreach (var entry in ConfigManager.Settings.FileColors) @@ -768,7 +769,7 @@ private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) foreach (var entry in delList) { - ConfigManager.Settings.FileColors.Remove(entry); + _ = ConfigManager.Settings.FileColors.Remove(entry); } ConfigManager.Settings.FileColors.Add(new ColorEntry(logWindow.FileName, dlg.Color)); @@ -804,7 +805,7 @@ private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) lock (_logWindowList) { - foreach (DockContent content in dockPanel.Contents) + foreach (DockContent content in dockPanel.Contents.Cast()) { var logWindow = content as LogWindow.LogWindow; var persistenceFileName = logWindow?.SavePersistenceData(true); diff --git a/src/LogExpert.UI/LogExpert.UI.csproj b/src/LogExpert.UI/LogExpert.UI.csproj index 396fd4a3..7e634730 100644 --- a/src/LogExpert.UI/LogExpert.UI.csproj +++ b/src/LogExpert.UI/LogExpert.UI.csproj @@ -27,7 +27,6 @@ - From 6b0b6fe89b4ddc6dbd5f119591f9b68ad70c8b7d Mon Sep 17 00:00:00 2001 From: Hirogen Date: Wed, 18 Jun 2025 08:18:02 +0200 Subject: [PATCH 09/26] review comments --- global.json | 2 +- .../EventArguments/BookmarkEventArgs.cs | 13 ++----------- src/LogExpert.UI/Controls/LogWindow/LogWindow.cs | 4 ++-- .../Controls/LogWindow/LogWindowEventHandlers.cs | 4 ++-- .../LogTabWindow/LogTabWindowEventHandlers.cs | 4 ++-- 5 files changed, 9 insertions(+), 18 deletions(-) diff --git a/global.json b/global.json index b6b5c9f5..04639674 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "9.0.101" + "version": "v8.0.314" } } diff --git a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs index da0f9e7e..d2156111 100644 --- a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs +++ b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs @@ -2,20 +2,11 @@ namespace LogExpert.Core.EventArguments; -public class BookmarkEventArgs : EventArgs +public class BookmarkEventArgs (Bookmark bookmark) : EventArgs { - public BookmarkEventArgs (Bookmark bookmark) - { - Bookmark = bookmark; - } - - public BookmarkEventArgs () { } - - public static new readonly BookmarkEventArgs Empty = new(); - #region Properties - public Bookmark Bookmark { get; } + public Bookmark Bookmark { get; } = bookmark; #endregion } \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index df0a6cad..3b839b1c 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -291,9 +291,9 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp public event EventHandler CurrentHighlightGroupChanged; - public event EventHandler BookmarkAdded; + public event EventHandler BookmarkAdded; - public event EventHandler BookmarkRemoved; + public event EventHandler BookmarkRemoved; public event EventHandler BookmarkTextChanged; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index 0b650677..5a2b3ff7 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -68,12 +68,12 @@ protected void OnCurrentHighlightListChanged () protected void OnBookmarkAdded () { - BookmarkAdded?.Invoke(this, BookmarkEventArgs.Empty); + BookmarkAdded?.Invoke(this, EventArgs.Empty); } protected void OnBookmarkRemoved () { - BookmarkRemoved?.Invoke(this, BookmarkEventArgs.Empty); + BookmarkRemoved?.Invoke(this, EventArgs.Empty); } protected void OnBookmarkTextChanged (Bookmark bookmark) diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index e78b894e..80956103 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -350,7 +350,7 @@ private void OnColumnizerChanged (object sender, ColumnizerEventArgs e) _bookmarkWindow?.SetColumnizer(e.Columnizer); } - private void OnBookmarkAdded (object sender, BookmarkEventArgs e) + private void OnBookmarkAdded (object sender, EventArgs e) { _bookmarkWindow.UpdateView(); } @@ -360,7 +360,7 @@ private void OnBookmarkTextChanged (object sender, BookmarkEventArgs e) _bookmarkWindow.BookmarkTextChanged(e.Bookmark); } - private void OnBookmarkRemoved (object sender, BookmarkEventArgs e) + private void OnBookmarkRemoved (object sender, EventArgs e) { _bookmarkWindow.UpdateView(); } From fdf22604873fee9a298c24c093001e04eb6443bf Mon Sep 17 00:00:00 2001 From: Hirogen Date: Wed, 18 Jun 2025 08:56:55 +0200 Subject: [PATCH 10/26] review comments --- .../LogWindow/LogWindowEventHandlers.cs | 43 +----- .../Controls/LogWindow/LogWindowPublic.cs | 144 ++++++------------ .../Controls/LogWindow/PatternWindow.cs | 7 +- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 25 +-- .../LogTabWindow/LogTabWindowEventHandlers.cs | 11 +- src/LogExpert.UI/Entities/PaintHelper.cs | 63 ++++---- 6 files changed, 93 insertions(+), 200 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index 5a2b3ff7..25ffba61 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -392,6 +392,8 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti return; } + + var lineNum = _filterResultList[e.RowIndex]; var line = _logFileReader.GetLogLineWithWait(lineNum).Result; @@ -401,43 +403,17 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti e.Graphics.SetClip(e.CellBounds); if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - Brush brush; - if (gridView.Focused) - { - brush = new SolidBrush(e.CellStyle.SelectionBackColor); - } - else - { - brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray - } - + using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); } else { - var bgColor = Color.White; // paint direct filter hits with different bg color //if (this.filterParams.SpreadEnabled && this.filterHitList.Contains(lineNum)) //{ // bgColor = Color.FromArgb(255, 220, 220, 220); //} - if (!DebugOptions.DisableWordHighlight) - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - else - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - - e.CellStyle.BackColor = bgColor; + e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); e.PaintBackground(e.ClipBounds, false); } @@ -454,12 +430,11 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti { if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) { - Rectangle r = new(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); + Rectangle r;// = new(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); r = e.CellBounds; r.Inflate(-2, -2); - Brush brush = new SolidBrush(BookmarkColor); + using var brush = new SolidBrush(BookmarkColor); e.Graphics.FillRectangle(brush, r); - brush.Dispose(); var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); @@ -471,11 +446,9 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti Alignment = StringAlignment.Center }; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - Font font = new("Verdana", Preferences.FontSize, FontStyle.Bold); + using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); + using var font = new Font("Verdana", Preferences.FontSize, FontStyle.Bold); e.Graphics.DrawString("!", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); - font.Dispose(); - brush2.Dispose(); } } } diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs index 8d4d36a0..692adab8 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs @@ -62,8 +62,10 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) { isUsingDefaultColumnizer = true; } + PreSelectColumnizer(columnizer); } + SetDefaultHighlightGroup(); } @@ -86,7 +88,7 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) catch (LogFileException lfe) { _logger.Error(lfe); - MessageBox.Show("Cannot load file\n" + lfe.Message, "LogExpert"); + MessageBox.Show($"Cannot load file\n{lfe.Message}", "LogExpert"); _ = BeginInvoke(new FunctionWith1BoolParam(Close), true); _isLoadError = true; return; @@ -103,14 +105,7 @@ public void LoadFile (string fileName, EncodingOptions encodingOptions) CurrentColumnizer = _forcedColumnizerForLoading; } - if (CurrentColumnizer is IPreProcessColumnizer processColumnizer) - { - _logFileReader.PreProcessColumnizer = processColumnizer; - } - else - { - _logFileReader.PreProcessColumnizer = null; - } + _logFileReader.PreProcessColumnizer = CurrentColumnizer is IPreProcessColumnizer processColumnizer ? processColumnizer : null; RegisterLogFileReaderEvents(); _logger.Info($"Loading logfile: {fileName}"); @@ -141,7 +136,7 @@ public void LoadFilesAsMulti (string[] fileNames, EncodingOptions encodingOption foreach (var name in fileNames) { - _logger.Info("File: {0}", name); + _logger.Info($"File: {name}"); } if (_logFileReader != null) @@ -188,12 +183,9 @@ public string SavePersistenceData (bool force) { var persistenceData = GetPersistenceData(); - if (ForcedPersistenceFileName == null) - { - return Persister.SavePersistenceData(FileName, persistenceData, Preferences); - } - - return Persister.SavePersistenceDataWithFixedName(ForcedPersistenceFileName, persistenceData); + return ForcedPersistenceFileName == null + ? Persister.SavePersistenceData(FileName, persistenceData, Preferences) + : Persister.SavePersistenceDataWithFixedName(ForcedPersistenceFileName, persistenceData); } catch (IOException ex) { @@ -291,7 +283,7 @@ public void CloseLogWindow () if (IsTempFile) { - _logger.Info("Deleting temp file {0}", FileName); + _logger.Info($"Deleting temp file {FileName}"); try { @@ -299,7 +291,7 @@ public void CloseLogWindow () } catch (IOException e) { - _logger.Error(e, "Error while deleting temp file {0}: {1}", FileName, e); + _logger.Error(e, $"Error while deleting temp file {FileName}: {e}"); } } @@ -358,7 +350,7 @@ public IColumn GetCellValue (int rowIndex, int columnIndex) { return new Column { - FullValue = (rowIndex + 1).ToString() // line number + FullValue = $"{rowIndex + 1}" // line number }; } @@ -376,19 +368,14 @@ public IColumn GetCellValue (int rowIndex, int columnIndex) { var value = cols.ColumnValues[columnIndex - 2]; - if (value != null && value.DisplayValue != null) - { - return value; - } - return value; - } - - if (columnIndex == 2) - { - return cols.ColumnValues[^1]; + return value != null && value.DisplayValue != null + ? value + : value; } - return Column.EmptyColumn; + return columnIndex == 2 + ? cols.ColumnValues[^1] + : Column.EmptyColumn; } } catch @@ -416,43 +403,12 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - var backColor = e.CellStyle.SelectionBackColor; - - Brush brush; - - if (gridView.Focused) - { - brush = new SolidBrush(backColor); - } - else - { - brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray - } - + using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); } else { - var bgColor = Color.White; - - if (!DebugOptions.DisableWordHighlight) - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - else - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - - e.CellStyle.BackColor = bgColor; - + e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); e.PaintBackground(e.ClipBounds, false); } @@ -472,9 +428,9 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV Rectangle r; // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); r = e.CellBounds; r.Inflate(-2, -2); - Brush brush = new SolidBrush(BookmarkColor); + using var brush = new SolidBrush(BookmarkColor); e.Graphics.FillRectangle(brush, r); - brush.Dispose(); + var bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); if (bookmark.Text.Length > 0) @@ -484,12 +440,10 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); //dark orange - Font font = new("Courier New", Preferences.FontSize, FontStyle.Bold); - e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), - format); - font.Dispose(); - brush2.Dispose(); + + using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); //dark orange + using var font = new Font("Courier New", Preferences.FontSize, FontStyle.Bold); + e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); } } } @@ -628,14 +582,9 @@ public void StartSearch () GuiStateUpdate(this, _guiStateArgs); var searchParams = _parentLogTabWin.SearchParams; - if ((searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed) - { - searchParams.CurrentLine = dataGridView.CurrentCellAddress.Y + 1; - } - else - { - searchParams.CurrentLine = dataGridView.CurrentCellAddress.Y - 1; - } + searchParams.CurrentLine = (searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed + ? dataGridView.CurrentCellAddress.Y + 1 + : dataGridView.CurrentCellAddress.Y - 1; _currentSearchParams = searchParams; // remember for async "not found" messages @@ -1663,14 +1612,9 @@ public void PatternStatisticSelectRange (PatternArgs patternArgs) } else { - if (dataGridView.CurrentCellAddress.Y != -1) - { - patternArgs.StartLine = dataGridView.CurrentCellAddress.Y; - } - else - { - patternArgs.StartLine = 0; - } + patternArgs.StartLine = dataGridView.CurrentCellAddress.Y != -1 + ? dataGridView.CurrentCellAddress.Y + : 0; patternArgs.EndLine = dataGridView.RowCount - 1; } } @@ -1800,19 +1744,14 @@ public void SetCurrentHighlightGroup (string groupName) lock (_currentHighlightGroupLock) { _currentHighlightGroup = _parentLogTabWin.FindHighlightGroup(groupName); - if (_currentHighlightGroup == null) - { - if (_parentLogTabWin.HighlightGroupList.Count > 0) - { - _currentHighlightGroup = _parentLogTabWin.HighlightGroupList[0]; - } - else - { - _currentHighlightGroup = new HighlightGroup(); - } - } + + _currentHighlightGroup ??= _parentLogTabWin.HighlightGroupList.Count > 0 + ? _parentLogTabWin.HighlightGroupList[0] + : new HighlightGroup(); + _guiStateArgs.HighlightGroupName = _currentHighlightGroup.GroupName; } + SendGuiStateUpdate(); BeginInvoke(new MethodInvoker(RefreshAllGrids)); } @@ -1845,7 +1784,7 @@ public void AddOtherWindowToTimesync (LogWindow other) public void AddToTimeSync (LogWindow master) { - _logger.Info("Syncing window for {0} to {1}", Util.GetNameFromPath(FileName), Util.GetNameFromPath(master.FileName)); + _logger.Info($"Syncing window for {Util.GetNameFromPath(FileName)} to {Util.GetNameFromPath(master.FileName)}"); lock (_timeSyncListLock) { if (IsTimeSynced && master.TimeSyncList != TimeSyncList) @@ -1853,10 +1792,12 @@ public void AddToTimeSync (LogWindow master) { FreeFromTimeSync(); } + TimeSyncList = master.TimeSyncList; TimeSyncList.AddWindow(this); ScrollToTimestamp(TimeSyncList.CurrentTimestamp, false, false); } + OnSyncModeChanged(); } @@ -1866,12 +1807,13 @@ public void FreeFromTimeSync () { if (TimeSyncList != null) { - _logger.Info("De-Syncing window for {0}", Util.GetNameFromPath(FileName)); + _logger.Info($"De-Syncing window for {Util.GetNameFromPath(FileName)}"); TimeSyncList.WindowRemoved -= OnTimeSyncListWindowRemoved; TimeSyncList.RemoveWindow(this); TimeSyncList = null; } } + OnSyncModeChanged(); } @@ -1881,4 +1823,4 @@ public void RefreshLogView () } #endregion -} +} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs index f704e3e8..c8999ac2 100644 --- a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs @@ -72,6 +72,7 @@ public void SetBlockList (List flatBlockList, PatternArgs patternA _blockList.Clear(); List singeList = []; //int blockId = -1; + for (var i = 0; i < flatBlockList.Count; ++i) { var block = flatBlockList[i]; @@ -93,6 +94,7 @@ public void SetBlockList (List flatBlockList, PatternArgs patternA // singeList.Add(block); //} } + _blockList.Add(singeList); Invoke(new MethodInvoker(SetBlockListGuiStuff)); } @@ -231,10 +233,9 @@ private void OnPatternHitsDataGridViewCellPainting (object sender, DataGridViewC Rectangle rect = new(e.CellBounds.X, e.CellBounds.Y, width, e.CellBounds.Height); var alpha = 90 + (int)((int)e.Value / (double)maxWeight * 165); - Brush brush = new SolidBrush(Color.FromArgb(alpha, 170, 180, 150));//gray green + using var brush = new SolidBrush(Color.FromArgb(alpha, 170, 180, 150));//gray green rect.Inflate(-2, -1); e.Graphics.FillRectangle(brush, rect); - brush.Dispose(); } e.PaintContent(e.CellBounds); @@ -360,7 +361,7 @@ private void OnSetRangeButtonClick (object sender, EventArgs e) { _logWindow.PatternStatisticSelectRange(_patternArgs); recalcButton.Enabled = true; - rangeLabel.Text = "Start: " + _patternArgs.StartLine + "\r\nEnd: " + _patternArgs.EndLine; + rangeLabel.Text = $"Start: {_patternArgs.StartLine} \r\nEnd: {_patternArgs.EndLine}"; } #endregion diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 336d3f7d..61648116 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -235,24 +235,10 @@ private void SetFont (string fontName, float fontSize) private void CommentPainting (BufferedDataGridView gridView, DataGridViewCellPaintingEventArgs e) { - var backColor = e.CellStyle.SelectionBackColor; - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - Brush brush; - if (gridView.Focused) - { - // _logger.logDebug("CellPaint Focus"); - brush = new SolidBrush(backColor); - } - else - { - // _logger.logDebug("CellPaint No Focus"); - brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray - } - + using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); } else { @@ -297,8 +283,7 @@ private void CurrentRowChanged (int rowIndex) } else { - var bookmark = _bookmarkData.Bookmarks[rowIndex]; - bookmarkTextBox.Text = bookmark.Text; + bookmarkTextBox.Text = _bookmarkData.Bookmarks[rowIndex].Text; bookmarkTextBox.Enabled = true; } } @@ -553,12 +538,8 @@ private void OnBookmarkDataGridViewCellDoubleClick (object sender, DataGridViewC private void OnRemoveCommentsToolStripMenuItemClick (object sender, EventArgs e) { - if ( - MessageBox.Show("Really remove bookmark comments for selected lines?", "LogExpert", - MessageBoxButtons.YesNo) == - DialogResult.Yes) + if (MessageBox.Show("Really remove bookmark comments for selected lines?", "LogExpert", MessageBoxButtons.YesNo) == DialogResult.Yes) { - List lineNumList = []; foreach (DataGridViewRow row in bookmarkDataGridView.SelectedRows) { if (row.Index != -1) diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index 80956103..408bb9cd 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -79,20 +79,15 @@ private void OnLogTabWindowClosing (object sender, CancelEventArgs e) try { _shouldStop = true; - _statusLineEventHandle.Set(); - _statusLineEventWakeupHandle.Set(); + _ = _statusLineEventHandle.Set(); + _ = _statusLineEventWakeupHandle.Set(); _ledThread.Join(); IList deleteLogWindowList = []; ConfigManager.Settings.AlwaysOnTop = TopMost && ConfigManager.Settings.Preferences.AllowOnlyOneInstance; SaveLastOpenFilesList(); - foreach (var logWindow in _logWindowList) - { - deleteLogWindowList.Add(logWindow); - } - - foreach (var logWindow in deleteLogWindowList) + foreach (var logWindow in _logWindowList.ToArray()) { RemoveAndDisposeLogWindow(logWindow, true); } diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index b0fda7d1..ae67258b 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -40,41 +40,12 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - var backColor = e.CellStyle.SelectionBackColor; - Brush brush; - - if (gridView.Focused) - { - brush = new SolidBrush(backColor); - } - else - { - brush = new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //gray - } - + using var brush = GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); } else { - var bgColor = Color.White; - - if (!DebugOptions.DisableWordHighlight) - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - else - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - - e.CellStyle.BackColor = bgColor; + e.CellStyle.BackColor = GetBackColorFromHighlightEntry(entry); e.PaintBackground(e.ClipBounds, false); } @@ -119,6 +90,36 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri } } + public static Color GetBackColorFromHighlightEntry (HighlightEntry? entry) + { + var bgColor = Color.White; + + if (!DebugOptions.DisableWordHighlight) + { + if (entry != null) + { + bgColor = entry.BackgroundColor; + } + } + else + { + if (entry != null) + { + bgColor = entry.BackgroundColor; + } + } + + return bgColor; + } + + [SupportedOSPlatform("windows")] + public static Brush GetBrushForFocusedControl (bool focused, Color selectionColor) + { + return focused + ? new SolidBrush(selectionColor) + : new SolidBrush(Color.FromArgb(255, 170, 170, 170)); //Gray + } + [SupportedOSPlatform("windows")] public static DataGridViewTextBoxColumn CreateMarkerColumn () { From 41832fc7825b82951174d8cac9d4fdfdf1d6c8df Mon Sep 17 00:00:00 2001 From: Hirogen Date: Wed, 18 Jun 2025 09:14:09 +0200 Subject: [PATCH 11/26] review comments --- .../LogTabWindow/LogTabWindowEventHandlers.cs | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index 408bb9cd..b49b1cda 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -13,8 +13,6 @@ using LogExpert.UI.Dialogs; using LogExpert.UI.Extensions.LogWindow; -using WeifenLuo.WinFormsUI.Docking; - namespace LogExpert.UI.Controls.LogTabWindow; internal partial class LogTabWindow @@ -708,21 +706,17 @@ private void OnCloseThisTabToolStripMenuItemClick (object sender, EventArgs e) [SupportedOSPlatform("windows")] private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) { - IList closeList = []; + List closeList = []; lock (_logWindowList) { - foreach (DockContent content in dockPanel.Contents) - { - if (content != dockPanel.ActiveContent && content is LogWindow.LogWindow) - { - closeList.Add(content); - } - } + closeList = [.. dockPanel.Contents + .OfType() + .Where(content => content != dockPanel.ActiveContent)]; } - foreach (var form in closeList) + foreach (var logWindow in closeList) { - form.Close(); + logWindow.Close(); } } @@ -801,9 +795,8 @@ private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) lock (_logWindowList) { - foreach (DockContent content in dockPanel.Contents.Cast()) + foreach (var logWindow in dockPanel.Contents.OfType()) { - var logWindow = content as LogWindow.LogWindow; var persistenceFileName = logWindow?.SavePersistenceData(true); if (persistenceFileName != null) { From bf9111449a1fc27d38112e890c54375527560a6b Mon Sep 17 00:00:00 2001 From: Hirogen Date: Wed, 18 Jun 2025 09:26:00 +0200 Subject: [PATCH 12/26] small change --- src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs index 692adab8..5904c375 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs @@ -501,20 +501,20 @@ public HighlightEntry FindHighlightEntry (ITextValue line, bool noWordMatches) } } - public IList FindHighlightMatches (ITextValue column) + public IList FindHighlightMatches (ITextValue line) { IList resultList = []; - if (column != null) + if (line != null) { lock (_currentHighlightGroupLock) { - GetHighlightEntryMatches(column, _currentHighlightGroup.HighlightEntryList, resultList); + GetHighlightEntryMatches(line, _currentHighlightGroup.HighlightEntryList, resultList); } lock (_tempHighlightEntryList) { - GetHighlightEntryMatches(column, _tempHighlightEntryList, resultList); + GetHighlightEntryMatches(line, _tempHighlightEntryList, resultList); } } @@ -532,6 +532,7 @@ public void FollowTailChanged (bool isChecked, bool byTrigger) dataGridView.FirstDisplayedScrollingRowIndex = _logFileReader.LineCount - 1; } } + BeginInvoke(new MethodInvoker(dataGridView.Refresh)); //this.dataGridView.Refresh(); _parentLogTabWin.FollowTailChanged(this, isChecked, byTrigger); From 2fd45c9faa600d8a8aa8896a5abed2538abe693d Mon Sep 17 00:00:00 2001 From: Hirogen Date: Thu, 19 Jun 2025 19:42:11 +0200 Subject: [PATCH 13/26] review comments --- src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs | 4 ++-- .../Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs | 9 +++------ src/LogExpert.UI/Entities/PaintHelper.cs | 1 - 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs index c8999ac2..ea2fa9f8 100644 --- a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs @@ -275,7 +275,7 @@ private void OnPatternHitsDataGridViewCurrentCellChanged (object sender, EventAr contentDataGridView.RowCount = _currentBlock.TargetEnd - _currentBlock.TargetStart + 1; contentDataGridView.Refresh(); contentDataGridView.CurrentCell = contentDataGridView.Rows[0].Cells[0]; - blockLinesLabel.Text = "" + contentDataGridView.RowCount; + blockLinesLabel.Text = $"{contentDataGridView.RowCount}"; } private void OnContentDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) @@ -361,7 +361,7 @@ private void OnSetRangeButtonClick (object sender, EventArgs e) { _logWindow.PatternStatisticSelectRange(_patternArgs); recalcButton.Enabled = true; - rangeLabel.Text = $"Start: {_patternArgs.StartLine} \r\nEnd: {_patternArgs.EndLine}"; + rangeLabel.Text = $"Start: {_patternArgs.StartLine}\nEnd: {_patternArgs.EndLine}"; } #endregion diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs index b49b1cda..587414f2 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs @@ -706,13 +706,10 @@ private void OnCloseThisTabToolStripMenuItemClick (object sender, EventArgs e) [SupportedOSPlatform("windows")] private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) { - List closeList = []; - lock (_logWindowList) - { - closeList = [.. dockPanel.Contents + var closeList = dockPanel.Contents .OfType() - .Where(content => content != dockPanel.ActiveContent)]; - } + .Where(content => content != dockPanel.ActiveContent) + .ToList(); foreach (var logWindow in closeList) { diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index ae67258b..b68c53ca 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -11,7 +11,6 @@ namespace LogExpert.UI.Entities; //TOOD: This whole class should be refactored and rethought -//TODO: This class should not knoow ConfigManager? internal static class PaintHelper { #region Fields From 0bbe6cd799f3c04a6f9607ff6048c453215d98bb Mon Sep 17 00:00:00 2001 From: Hirogen Date: Thu, 19 Jun 2025 20:00:22 +0200 Subject: [PATCH 14/26] more review comments --- global.json | 4 ++-- src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs | 2 +- src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs | 2 +- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 2 +- src/LogExpert.UI/Entities/PaintHelper.cs | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/global.json b/global.json index 04639674..4c686a52 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "v8.0.314" + "version": "9.0.301" } -} +} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs index 25ffba61..9150a4a2 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs @@ -401,7 +401,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti { var entry = FindFirstNoWordMatchHilightEntry(line); e.Graphics.SetClip(e.CellBounds); - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs index 5904c375..5f1a9832 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs @@ -401,7 +401,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV var entry = FindFirstNoWordMatchHilightEntry(line); e.Graphics.SetClip(e.CellBounds); - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 61648116..5e6bad97 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -235,7 +235,7 @@ private void SetFont (string fontName, float fontSize) private void CommentPainting (BufferedDataGridView gridView, DataGridViewCellPaintingEventArgs e) { - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index b68c53ca..0454c5cd 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -37,7 +37,7 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri var entry = logPaintCtx.FindHighlightEntry(line, true); e.Graphics.SetClip(e.CellBounds); - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { using var brush = GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); From f096885f118dca3c095f919f1ae8bc9bda29d266 Mon Sep 17 00:00:00 2001 From: Patrick Bruner Date: Thu, 19 Jun 2025 20:57:32 +0200 Subject: [PATCH 15/26] Update test_dotnet.yml dotnet-version changed to 9.0.x --- .github/workflows/test_dotnet.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test_dotnet.yml b/.github/workflows/test_dotnet.yml index 57c53a4e..7e834ded 100644 --- a/.github/workflows/test_dotnet.yml +++ b/.github/workflows/test_dotnet.yml @@ -19,7 +19,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v4 with: - dotnet-version: 8.0.x + dotnet-version: 9.0.x - name: Restore dependencies run: dotnet restore working-directory: src From f700b5528288db6666bf5e175e0f6b038c2dd9fe Mon Sep 17 00:00:00 2001 From: Hirogen Date: Sat, 21 Jun 2025 18:09:11 +0200 Subject: [PATCH 16/26] recombined all the forms, so they can be refactored better, and there are no longer resx problems when opening a form and visual studio creates a resx file --- .../Extensions/LogLineExtensions.cs | 2 +- .../Controls/LogWindow/LogWindow.cs | 7322 +++++++++++++++++ .../Controls/LogWindow/LogWindow.resx | 109 +- .../LogWindow/LogWindowEventHandlers.cs | 1723 ---- .../LogWindow/LogWindowEventHandlers.resx | 120 - .../Controls/LogWindow/LogWindowPrivate.cs | 3820 --------- .../Controls/LogWindow/LogWindowPublic.cs | 1827 ---- .../Dialogs/LogTabWindow/LogTabWindow.cs | 2787 +++++++ .../LogTabWindow/LogTabWindowEventHandlers.cs | 1094 --- .../LogTabWindow/LogTabWindowPrivate.cs | 1375 ---- .../LogTabWindow/LogTabWindowPublic.cs | 364 - src/LogExpert.UI/LogExpert.UI.csproj | 17 - 12 files changed, 10138 insertions(+), 10422 deletions(-) delete mode 100644 src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs delete mode 100644 src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.resx delete mode 100644 src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs delete mode 100644 src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs delete mode 100644 src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs delete mode 100644 src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs delete mode 100644 src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs diff --git a/src/ColumnizerLib/Extensions/LogLineExtensions.cs b/src/ColumnizerLib/Extensions/LogLineExtensions.cs index de081a34..2cebb987 100644 --- a/src/ColumnizerLib/Extensions/LogLineExtensions.cs +++ b/src/ColumnizerLib/Extensions/LogLineExtensions.cs @@ -1,4 +1,4 @@ -namespace LogExpert.Extensions; +namespace LogExpert.Extensions; //TODO: Move this to LogExpert.UI, change to internal and fix tests public static class LogLineExtensions diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index 3b839b1c..ec8f669d 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -1,7 +1,14 @@ +using System.ComponentModel; +using System.Globalization; using System.Runtime.Versioning; +using System.Text; +using System.Text.RegularExpressions; +using LogExpert.Classes.Filter; using LogExpert.Core.Callback; +using LogExpert.Core.Classes; using LogExpert.Core.Classes.Bookmark; +using LogExpert.Core.Classes.Columnizer; using LogExpert.Core.Classes.Filter; using LogExpert.Core.Classes.Highlight; using LogExpert.Core.Classes.Log; @@ -11,7 +18,10 @@ using LogExpert.Core.EventArguments; using LogExpert.Core.Interface; using LogExpert.Dialogs; +using LogExpert.Extensions; using LogExpert.UI.Dialogs; +using LogExpert.UI.Entities; +using LogExpert.UI.Extensions; using LogExpert.UI.Interface; using NLog; @@ -560,4 +570,7316 @@ void ILogWindow.WritePipeTab (IList lineEntryList, string title) WritePipeTab(lineEntryList, title); } #endif + + #region Event Handlers + + [SupportedOSPlatform("windows")] + private void AutoResizeFilterBox () + { + filterSplitContainer.SplitterDistance = filterComboBox.Left + filterComboBox.GetMaxTextWidth(); + } + + #region Events handler + + protected void OnProgressBarUpdate (ProgressEventArgs e) + { + ProgressBarUpdate?.Invoke(this, e); + } + + protected void OnStatusLine (StatusLineEventArgs e) + { + StatusLineEvent?.Invoke(this, e); + } + + protected void OnGuiState (GuiStateArgs e) + { + GuiStateUpdate?.Invoke(this, e); + } + + protected void OnTailFollowed (EventArgs e) + { + TailFollowed?.Invoke(this, e); + } + + protected void OnFileNotFound (EventArgs e) + { + FileNotFound?.Invoke(this, e); + } + + protected void OnFileRespawned (EventArgs e) + { + FileRespawned?.Invoke(this, e); + } + + protected void OnFilterListChanged (LogWindow source) + { + FilterListChanged?.Invoke(this, new FilterListChangedEventArgs(source)); + } + + protected void OnCurrentHighlightListChanged () + { + CurrentHighlightGroupChanged?.Invoke(this, new CurrentHighlightGroupChangedEventArgs(this, _currentHighlightGroup)); + } + + protected void OnBookmarkAdded () + { + BookmarkAdded?.Invoke(this, EventArgs.Empty); + } + + protected void OnBookmarkRemoved () + { + BookmarkRemoved?.Invoke(this, EventArgs.Empty); + } + + protected void OnBookmarkTextChanged (Bookmark bookmark) + { + BookmarkTextChanged?.Invoke(this, new BookmarkEventArgs(bookmark)); + } + + protected void OnColumnizerChanged (ILogLineColumnizer columnizer) + { + ColumnizerChanged?.Invoke(this, new ColumnizerEventArgs(columnizer)); + } + + protected void OnRegisterCancelHandler (IBackgroundProcessCancelHandler handler) + { + lock (_cancelHandlerList) + { + _cancelHandlerList.Add(handler); + } + } + + protected void OnDeRegisterCancelHandler (IBackgroundProcessCancelHandler handler) + { + lock (_cancelHandlerList) + { + _cancelHandlerList.Remove(handler); + } + } + + [SupportedOSPlatform("windows")] + private void OnLogWindowLoad (object sender, EventArgs e) + { + var setLastColumnWidth = _parentLogTabWin.Preferences.SetLastColumnWidth; + var lastColumnWidth = _parentLogTabWin.Preferences.LastColumnWidth; + var fontName = _parentLogTabWin.Preferences.FontName; + var fontSize = _parentLogTabWin.Preferences.FontSize; + + PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, true, SettingsFlags.GuiOrColors); + } + + [SupportedOSPlatform("windows")] + private void OnLogWindowDisposed (object sender, EventArgs e) + { + _waitingForClose = true; + _parentLogTabWin.HighlightSettingsChanged -= OnParentHighlightSettingsChanged; + _logFileReader?.DeleteAllContent(); + + FreeFromTimeSync(); + } + + [SupportedOSPlatform("windows")] + private void OnLogFileReaderLoadingStarted (object sender, LoadFileEventArgs e) + { + Invoke(LoadingStarted, e); + } + + [SupportedOSPlatform("windows")] + private void OnLogFileReaderFinishedLoading (object sender, EventArgs e) + { + //Thread.CurrentThread.Name = "FinishedLoading event thread"; + _logger.Info(CultureInfo.InvariantCulture, "Finished loading."); + _isLoading = false; + _isDeadFile = false; + if (!_waitingForClose) + { + Invoke(new MethodInvoker(LoadingFinished)); + Invoke(new MethodInvoker(LoadPersistenceData)); + Invoke(new MethodInvoker(SetGuiAfterLoading)); + _loadingFinishedEvent.Set(); + _externaLoadingFinishedEvent.Set(); + _timeSpreadCalc.SetLineCount(_logFileReader.LineCount); + + if (_reloadMemento != null) + { + Invoke(new PositionAfterReloadFx(PositionAfterReload), _reloadMemento); + } + + if (filterTailCheckBox.Checked) + { + _logger.Info(CultureInfo.InvariantCulture, "Refreshing filter view because of reload."); + Invoke(new MethodInvoker(FilterSearch)); // call on proper thread + } + + HandleChangedFilterList(); + } + + _reloadMemento = null; + } + + [SupportedOSPlatform("windows")] + private void OnLogFileReaderFileNotFound (object sender, EventArgs e) + { + if (!IsDisposed && !Disposing) + { + _logger.Info(CultureInfo.InvariantCulture, "Handling file not found event."); + _isDeadFile = true; + BeginInvoke(new MethodInvoker(LogfileDead)); + } + } + + [SupportedOSPlatform("windows")] + private void OnLogFileReaderRespawned (object sender, EventArgs e) + { + BeginInvoke(new MethodInvoker(LogfileRespawned)); + } + + [SupportedOSPlatform("windows")] + private void OnLogWindowClosing (object sender, CancelEventArgs e) + { + if (Preferences.AskForClose) + { + if (MessageBox.Show("Sure to close?", "LogExpert", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + e.Cancel = true; + return; + } + } + + SavePersistenceData(false); + CloseLogWindow(); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) + { + e.Handled = true; + AutoResizeColumns(dataGridView); + } + + /** + * Event handler for the Load event from LogfileReader + */ + [SupportedOSPlatform("windows")] + private void OnLogFileReaderLoadFile (object sender, LoadFileEventArgs e) + { + if (e.NewFile) + { + _logger.Info(CultureInfo.InvariantCulture, "File created anew."); + + // File was new created (e.g. rollover) + _isDeadFile = false; + UnRegisterLogFileReaderEvents(); + dataGridView.CurrentCellChanged -= OnDataGridViewCurrentCellChanged; + MethodInvoker invoker = ReloadNewFile; + BeginInvoke(invoker); + //Thread loadThread = new Thread(new ThreadStart(ReloadNewFile)); + //loadThread.Start(); + _logger.Debug(CultureInfo.InvariantCulture, "Reloading invoked."); + } + else if (_isLoading) + { + BeginInvoke(UpdateProgress, e); + } + } + + private void OnFileSizeChanged (object sender, LogEventArgs e) + { + //OnFileSizeChanged(e); // now done in UpdateGrid() + _logger.Info(CultureInfo.InvariantCulture, "Got FileSizeChanged event. prevLines:{0}, curr lines: {1}", e.PrevLineCount, e.LineCount); + + // - now done in the thread that works on the event args list + //if (e.IsRollover) + //{ + // ShiftBookmarks(e.RolloverOffset); + // ShiftFilterPipes(e.RolloverOffset); + //} + + //UpdateGridCallback callback = new UpdateGridCallback(UpdateGrid); + //this.BeginInvoke(callback, new object[] { e }); + lock (_logEventArgsList) + { + _logEventArgsList.Add(e); + _logEventArgsEvent.Set(); + } + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) + { + var startCount = CurrentColumnizer?.GetColumnCount() ?? 0; + + e.Value = GetCellValue(e.RowIndex, e.ColumnIndex); + + // The new column could be find dynamically. + // Only support add new columns for now. + // TODO: Support reload all columns? + if (CurrentColumnizer != null && CurrentColumnizer.GetColumnCount() > startCount) + { + for (var i = startCount; i < CurrentColumnizer.GetColumnCount(); i++) + { + var colName = CurrentColumnizer.GetColumnNames()[i]; + dataGridView.Columns.Add(PaintHelper.CreateTitleColumn(colName)); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewCellValuePushed (object sender, DataGridViewCellValueEventArgs e) + { + if (!CurrentColumnizer.IsTimeshiftImplemented()) + { + return; + } + + var line = _logFileReader.GetLogLine(e.RowIndex); + var offset = CurrentColumnizer.GetTimeOffset(); + CurrentColumnizer.SetTimeOffset(0); + ColumnizerCallbackObject.SetLineNum(e.RowIndex); + var cols = CurrentColumnizer.SplitLine(ColumnizerCallbackObject, line); + CurrentColumnizer.SetTimeOffset(offset); + if (cols.ColumnValues.Length <= e.ColumnIndex - 2) + { + return; + } + + var oldValue = cols.ColumnValues[e.ColumnIndex - 2].FullValue; + var newValue = (string)e.Value; + //string oldValue = (string) this.dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; + CurrentColumnizer.PushValue(ColumnizerCallbackObject, e.ColumnIndex - 2, newValue, oldValue); + dataGridView.Refresh(); + TimeSpan timeSpan = new(CurrentColumnizer.GetTimeOffset() * TimeSpan.TicksPerMillisecond); + var span = timeSpan.ToString(); + var index = span.LastIndexOf('.'); + if (index > 0) + { + span = span.Substring(0, index + 4); + } + + SetTimeshiftValue(span); + SendGuiStateUpdate(); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewRowHeightInfoNeeded (object sender, DataGridViewRowHeightInfoNeededEventArgs e) + { + e.Height = GetRowHeight(e.RowIndex); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewCurrentCellChanged (object sender, EventArgs e) + { + if (dataGridView.CurrentRow != null) + { + _statusEventArgs.CurrentLineNum = dataGridView.CurrentRow.Index + 1; + SendStatusLineUpdate(); + if (syncFilterCheckBox.Checked) + { + SyncFilterGridPos(); + } + + if (CurrentColumnizer.IsTimeshiftImplemented() && Preferences.TimestampControl) + { + SyncTimestampDisplay(); + } + + //MethodInvoker invoker = new MethodInvoker(DisplayCurrentFileOnStatusline); + //invoker.BeginInvoke(null, null); + } + } + + private void OnDataGridViewCellEndEdit (object sender, DataGridViewCellEventArgs e) + { + StatusLineText(string.Empty); + } + + [SupportedOSPlatform("windows")] + private void OnEditControlKeyUp (object sender, KeyEventArgs e) + { + UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); + } + + [SupportedOSPlatform("windows")] + private void OnEditControlKeyPress (object sender, KeyPressEventArgs e) + { + UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); + } + + [SupportedOSPlatform("windows")] + private void OnEditControlClick (object sender, EventArgs e) + { + UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); + } + + [SupportedOSPlatform("windows")] + private void OnEditControlKeyDown (object sender, KeyEventArgs e) + { + UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewPaint (object sender, PaintEventArgs e) + { + if (ShowBookmarkBubbles) + { + AddBookmarkOverlays(); + } + } + + // ====================================================================================== + // Filter Grid stuff + // ====================================================================================== + + [SupportedOSPlatform("windows")] + private void OnFilterSearchButtonClick (object sender, EventArgs e) + { + FilterSearch(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) + { + var gridView = (BufferedDataGridView)sender; + + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) + { + e.Handled = false; + return; + } + + + + var lineNum = _filterResultList[e.RowIndex]; + var line = _logFileReader.GetLogLineWithWait(lineNum).Result; + + if (line != null) + { + var entry = FindFirstNoWordMatchHilightEntry(line); + e.Graphics.SetClip(e.CellBounds); + if (e.State.HasFlag(DataGridViewElementStates.Selected)) + { + using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); + e.Graphics.FillRectangle(brush, e.CellBounds); + } + else + { + // paint direct filter hits with different bg color + //if (this.filterParams.SpreadEnabled && this.filterHitList.Contains(lineNum)) + //{ + // bgColor = Color.FromArgb(255, 220, 220, 220); + //} + e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); + e.PaintBackground(e.ClipBounds, false); + } + + if (DebugOptions.DisableWordHighlight) + { + e.PaintContent(e.CellBounds); + } + else + { + PaintCell(e, filterGridView, false, entry); + } + + if (e.ColumnIndex == 0) + { + if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) + { + Rectangle r;// = new(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); + r = e.CellBounds; + r.Inflate(-2, -2); + using var brush = new SolidBrush(BookmarkColor); + e.Graphics.FillRectangle(brush, r); + + var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); + + if (bookmark.Text.Length > 0) + { + StringFormat format = new() + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Center + }; + + using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); + using var font = new Font("Verdana", Preferences.FontSize, FontStyle.Bold); + e.Graphics.DrawString("!", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); + } + } + } + + e.Paint(e.CellBounds, DataGridViewPaintParts.Border); + e.Handled = true; + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) + { + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) + { + e.Value = ""; + return; + } + + var lineNum = _filterResultList[e.RowIndex]; + e.Value = GetCellValue(lineNum, e.ColumnIndex); + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewRowHeightInfoNeeded (object sender, DataGridViewRowHeightInfoNeededEventArgs e) + { + e.Height = _lineHeight; + } + + [SupportedOSPlatform("windows")] + private void OnFilterComboBoxKeyDown (object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + FilterSearch(); + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewColumnDividerDoubleClick (object sender, + DataGridViewColumnDividerDoubleClickEventArgs e) + { + e.Handled = true; + AutoResizeColumnsFx fx = AutoResizeColumns; + BeginInvoke(fx, filterGridView); + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) + { + if (e.ColumnIndex == 0) + { + ToggleBookmark(); + return; + } + + if (filterGridView.CurrentRow != null && e.RowIndex >= 0) + { + var lineNum = _filterResultList[filterGridView.CurrentRow.Index]; + SelectAndEnsureVisible(lineNum, true); + } + } + + [SupportedOSPlatform("windows")] + private void OnRangeCheckBoxCheckedChanged (object sender, EventArgs e) + { + filterRangeComboBox.Enabled = rangeCheckBox.Checked; + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewScroll (object sender, ScrollEventArgs e) + { + if (e.ScrollOrientation == ScrollOrientation.VerticalScroll) + { + if (dataGridView.DisplayedRowCount(false) + dataGridView.FirstDisplayedScrollingRowIndex >= dataGridView.RowCount) + { + //this.guiStateArgs.FollowTail = true; + if (!_guiStateArgs.FollowTail) + { + FollowTailChanged(true, false); + } + + OnTailFollowed(EventArgs.Empty); + } + else + { + //this.guiStateArgs.FollowTail = false; + if (_guiStateArgs.FollowTail) + { + FollowTailChanged(false, false); + } + } + + SendGuiStateUpdate(); + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewKeyDown (object sender, KeyEventArgs e) + { + switch (e.KeyCode) + { + case Keys.Enter: + { + if (filterGridView.CurrentCellAddress.Y >= 0 && filterGridView.CurrentCellAddress.Y < _filterResultList.Count) + { + var lineNum = _filterResultList[filterGridView.CurrentCellAddress.Y]; + SelectLine(lineNum, false, true); + e.Handled = true; + } + + break; + } + case Keys.Tab when e.Modifiers == Keys.None: + dataGridView.Focus(); + e.Handled = true; + break; + } + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewKeyDown (object sender, KeyEventArgs e) + { + switch (e.KeyCode) + { + case Keys.Tab when e.Modifiers == Keys.None: + { + filterGridView.Focus(); + e.Handled = true; + break; + } + } + + //switch (e.KeyCode) + //{ + // case Keys.Tab when e.Modifiers == Keys.Control: + // //this.parentLogTabWin.SwitchTab(e.Shift); + // break; + //} + + _shouldCallTimeSync = true; + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) + { + if (e.KeyCode == Keys.Tab && e.Control) + { + e.IsInputKey = true; + } + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewCellContentDoubleClick (object sender, DataGridViewCellEventArgs e) + { + if (dataGridView.CurrentCell != null) + { + dataGridView.BeginEdit(false); + } + } + + [SupportedOSPlatform("windows")] + private void OnSyncFilterCheckBoxCheckedChanged (object sender, EventArgs e) + { + if (syncFilterCheckBox.Checked) + { + SyncFilterGridPos(); + } + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewLeave (object sender, EventArgs e) + { + InvalidateCurrentRow(dataGridView); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewEnter (object sender, EventArgs e) + { + InvalidateCurrentRow(dataGridView); + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewEnter (object sender, EventArgs e) + { + InvalidateCurrentRow(filterGridView); + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewLeave (object sender, EventArgs e) + { + InvalidateCurrentRow(filterGridView); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewResize (object sender, EventArgs e) + { + if (_logFileReader != null && dataGridView.RowCount > 0 && _guiStateArgs.FollowTail) + { + dataGridView.FirstDisplayedScrollingRowIndex = dataGridView.RowCount - 1; + } + } + + private void OnDataGridViewSelectionChanged (object sender, EventArgs e) + { + UpdateSelectionDisplay(); + } + + [SupportedOSPlatform("windows")] + private void OnSelectionChangedTriggerSignal (object sender, EventArgs e) + { + var selCount = 0; + try + { + _logger.Debug(CultureInfo.InvariantCulture, "Selection changed trigger"); + selCount = dataGridView.SelectedRows.Count; + if (selCount > 1) + { + StatusLineText(selCount + " selected lines"); + } + else + { + if (IsMultiFile) + { + MethodInvoker invoker = DisplayCurrentFileOnStatusline; + invoker.BeginInvoke(null, null); + } + else + { + StatusLineText(""); + } + } + } + catch (Exception ex) + { + _logger.Error(ex, "Error in selectionChangedTrigger_Signal selcount {0}", selCount); + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterKnobControlValueChanged (object sender, EventArgs e) + { + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterToTabButtonClick (object sender, EventArgs e) + { + FilterToTab(); + } + + private void OnPipeDisconnected (object sender, EventArgs e) + { + if (sender.GetType() == typeof(FilterPipe)) + { + lock (_filterPipeList) + { + _filterPipeList.Remove((FilterPipe)sender); + if (_filterPipeList.Count == 0) + // reset naming counter to 0 if no more open filter tabs for this source window + { + _filterPipeNameCounter = 0; + } + } + } + } + + [SupportedOSPlatform("windows")] + private void OnAdvancedButtonClick (object sender, EventArgs e) + { + _showAdvanced = !_showAdvanced; + ShowAdvancedFilterPanel(_showAdvanced); + } + + [SupportedOSPlatform("windows")] + private void OnFilterSplitContainerMouseDown (object sender, MouseEventArgs e) + { + ((SplitContainer)sender).IsSplitterFixed = true; + } + + [SupportedOSPlatform("windows")] + private void OnFilterSplitContainerMouseUp (object sender, MouseEventArgs e) + { + ((SplitContainer)sender).IsSplitterFixed = false; + } + + [SupportedOSPlatform("windows")] + private void OnFilterSplitContainerMouseMove (object sender, MouseEventArgs e) + { + var splitContainer = (SplitContainer)sender; + if (splitContainer.IsSplitterFixed) + { + if (e.Button.Equals(MouseButtons.Left)) + { + if (splitContainer.Orientation.Equals(Orientation.Vertical)) + { + if (e.X > 0 && e.X < splitContainer.Width) + { + splitContainer.SplitterDistance = e.X; + splitContainer.Refresh(); + } + } + else + { + if (e.Y > 0 && e.Y < splitContainer.Height) + { + splitContainer.SplitterDistance = e.Y; + splitContainer.Refresh(); + } + } + } + else + { + splitContainer.IsSplitterFixed = false; + } + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterSplitContainerMouseDoubleClick (object sender, MouseEventArgs e) + { + AutoResizeFilterBox(); + } + + #region Context Menu + + [SupportedOSPlatform("windows")] + private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e) + { + var lineNum = -1; + if (dataGridView.CurrentRow != null) + { + lineNum = dataGridView.CurrentRow.Index; + } + + if (lineNum == -1) + { + return; + } + + var refLineNum = lineNum; + + copyToTabToolStripMenuItem.Enabled = dataGridView.SelectedCells.Count > 0; + scrollAllTabsToTimestampToolStripMenuItem.Enabled = CurrentColumnizer.IsTimeshiftImplemented() + && + GetTimestampForLine(ref refLineNum, false) != + DateTime.MinValue; + + locateLineInOriginalFileToolStripMenuItem.Enabled = IsTempFile && + FilterPipe != null && + FilterPipe.GetOriginalLineNum(lineNum) != -1; + + markEditModeToolStripMenuItem.Enabled = !dataGridView.CurrentCell.ReadOnly; + + // Remove all "old" plugin entries + var index = dataGridContextMenuStrip.Items.IndexOf(pluginSeparator); + + if (index > 0) + { + for (var i = index + 1; i < dataGridContextMenuStrip.Items.Count;) + { + dataGridContextMenuStrip.Items.RemoveAt(i); + } + } + + // Add plugin entries + var isAdded = false; + if (PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins.Count > 0) + { + var lines = GetSelectedContent(); + foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) + { + LogExpertCallback callback = new(this); + var menuText = entry.GetMenuText(lines.Count, CurrentColumnizer, callback.GetLogLine(lines[0])); + + if (menuText != null) + { + var disabled = menuText.StartsWith('_'); + if (disabled) + { + menuText = menuText[1..]; + } + + var item = dataGridContextMenuStrip.Items.Add(menuText, null, OnHandlePluginContextMenu); + item.Tag = new ContextMenuPluginEventArgs(entry, lines, CurrentColumnizer, callback); + item.Enabled = !disabled; + isAdded = true; + } + } + } + + pluginSeparator.Visible = isAdded; + + // enable/disable Temp Highlight item + tempHighlightsToolStripMenuItem.Enabled = _tempHighlightEntryList.Count > 0; + + markCurrentFilterRangeToolStripMenuItem.Enabled = string.IsNullOrEmpty(filterRangeComboBox.Text) == false; + + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + var list = _parentLogTabWin.GetListOfOpenFiles(); + syncTimestampsToToolStripMenuItem.Enabled = true; + syncTimestampsToToolStripMenuItem.DropDownItems.Clear(); + EventHandler ev = OnHandleSyncContextMenu; + Font italicFont = new(syncTimestampsToToolStripMenuItem.Font.FontFamily, syncTimestampsToToolStripMenuItem.Font.Size, FontStyle.Italic); + + foreach (var fileEntry in list) + { + if (fileEntry.LogWindow != this) + { + var item = syncTimestampsToToolStripMenuItem.DropDownItems.Add(fileEntry.Title, null, ev) as ToolStripMenuItem; + item.Tag = fileEntry; + item.Checked = TimeSyncList != null && TimeSyncList.Contains(fileEntry.LogWindow); + if (fileEntry.LogWindow.TimeSyncList != null && !fileEntry.LogWindow.TimeSyncList.Contains(this)) + { + item.Font = italicFont; + item.ForeColor = Color.Blue; + } + + item.Enabled = fileEntry.LogWindow.CurrentColumnizer.IsTimeshiftImplemented(); + } + } + } + else + { + syncTimestampsToToolStripMenuItem.Enabled = false; + } + + freeThisWindowFromTimeSyncToolStripMenuItem.Enabled = TimeSyncList != null && + TimeSyncList.Count > 1; + } + + [SupportedOSPlatform("windows")] + private void OnHandlePluginContextMenu (object sender, EventArgs args) + { + if (sender is ToolStripItem item) + { + var menuArgs = item.Tag as ContextMenuPluginEventArgs; + var logLines = menuArgs.LogLines; + menuArgs.Entry.MenuSelected(logLines.Count, menuArgs.Columnizer, menuArgs.Callback.GetLogLine(logLines[0])); + } + } + + [SupportedOSPlatform("windows")] + private void OnHandleSyncContextMenu (object sender, EventArgs args) + { + if (sender is ToolStripItem item) + { + var entry = item.Tag as WindowFileEntry; + + if (TimeSyncList != null && TimeSyncList.Contains(entry.LogWindow)) + { + FreeSlaveFromTimesync(entry.LogWindow); + } + else + //AddSlaveToTimesync(entry.LogWindow); + { + AddOtherWindowToTimesync(entry.LogWindow); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnCopyToolStripMenuItemClick (object sender, EventArgs e) + { + CopyMarkedLinesToClipboard(); + } + + private void OnCopyToTabToolStripMenuItemClick (object sender, EventArgs e) + { + CopyMarkedLinesToTab(); + } + + [SupportedOSPlatform("windows")] + private void OnScrollAllTabsToTimestampToolStripMenuItemClick (object sender, EventArgs e) + { + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + var currentLine = dataGridView.CurrentCellAddress.Y; + if (currentLine > 0 && currentLine < dataGridView.RowCount) + { + var lineNum = currentLine; + var timeStamp = GetTimestampForLine(ref lineNum, false); + if (timeStamp.Equals(DateTime.MinValue)) // means: invalid + { + return; + } + + _parentLogTabWin.ScrollAllTabsToTimestamp(timeStamp, this); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnLocateLineInOriginalFileToolStripMenuItemClick (object sender, EventArgs e) + { + if (dataGridView.CurrentRow != null && FilterPipe != null) + { + var lineNum = FilterPipe.GetOriginalLineNum(dataGridView.CurrentRow.Index); + if (lineNum != -1) + { + FilterPipe.LogWindow.SelectLine(lineNum, false, true); + _parentLogTabWin.SelectTab(FilterPipe.LogWindow); + } + } + } + + private void OnToggleBoomarkToolStripMenuItemClick (object sender, EventArgs e) + { + ToggleBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnMarkEditModeToolStripMenuItemClick (object sender, EventArgs e) + { + StartEditMode(); + } + + private void OnLogWindowSizeChanged (object sender, EventArgs e) + { + //AdjustMinimumGridWith(); + AdjustHighlightSplitterWidth(); + } + + #region BookMarkList + + [SupportedOSPlatform("windows")] + private void OnColumnRestrictCheckBoxCheckedChanged (object sender, EventArgs e) + { + columnButton.Enabled = columnRestrictCheckBox.Checked; + if (columnRestrictCheckBox.Checked) // disable when nothing to filter + { + columnNamesLabel.Visible = true; + _filterParams.ColumnRestrict = true; + columnNamesLabel.Text = CalculateColumnNames(_filterParams); + } + else + { + columnNamesLabel.Visible = false; + } + + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnColumnButtonClick (object sender, EventArgs e) + { + _filterParams.CurrentColumnizer = _currentColumnizer; + FilterColumnChooser chooser = new(_filterParams); + if (chooser.ShowDialog() == DialogResult.OK) + { + columnNamesLabel.Text = CalculateColumnNames(_filterParams); + + //CheckForFilterDirty(); //!!!GBro: Indicate to redo the search if search columns were changed + filterSearchButton.Image = _searchButtonImage; + saveFilterButton.Enabled = false; + } + } + + #endregion + + #region Column Header Context Menu + + [SupportedOSPlatform("windows")] + private void OnDataGridViewCellContextMenuStripNeeded (object sender, DataGridViewCellContextMenuStripNeededEventArgs e) + { + if (e.RowIndex >= 0 && e.RowIndex < dataGridView.RowCount && !dataGridView.Rows[e.RowIndex].Selected) + { + SelectLine(e.RowIndex, false, true); + } + else if (e.RowIndex < 0) + { + e.ContextMenuStrip = columnContextMenuStrip; + } + + if (e.ContextMenuStrip == columnContextMenuStrip) + { + _selectedCol = e.ColumnIndex; + } + } + + //private void boomarkDataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) + //{ + // if (e.RowIndex > 0 && e.RowIndex < this.boomarkDataGridView.RowCount + // && !this.boomarkDataGridView.Rows[e.RowIndex].Selected) + // { + // this.boomarkDataGridView.Rows[e.RowIndex].Selected = true; + // this.boomarkDataGridView.CurrentCell = this.boomarkDataGridView.Rows[e.RowIndex].Cells[0]; + // } + // if (e.ContextMenuStrip == this.columnContextMenuStrip) + // { + // this.selectedCol = e.ColumnIndex; + // } + //} + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewCellContextMenuStripNeeded (object sender, DataGridViewCellContextMenuStripNeededEventArgs e) + { + if (e.ContextMenuStrip == columnContextMenuStrip) + { + _selectedCol = e.ColumnIndex; + } + } + + [SupportedOSPlatform("windows")] + private void OnColumnContextMenuStripOpening (object sender, CancelEventArgs e) + { + var ctl = columnContextMenuStrip.SourceControl; + var gridView = ctl as BufferedDataGridView; + var frozen = false; + if (_freezeStateMap.TryGetValue(ctl, out var value)) + { + frozen = value; + } + + freezeLeftColumnsUntilHereToolStripMenuItem.Checked = frozen; + + if (frozen) + { + freezeLeftColumnsUntilHereToolStripMenuItem.Text = "Frozen"; + } + else + { + if (ctl is BufferedDataGridView) + { + freezeLeftColumnsUntilHereToolStripMenuItem.Text = $"Freeze left columns until here ({gridView.Columns[_selectedCol].HeaderText})"; + } + } + + + var col = gridView.Columns[_selectedCol]; + moveLeftToolStripMenuItem.Enabled = col != null && col.DisplayIndex > 0; + moveRightToolStripMenuItem.Enabled = col != null && col.DisplayIndex < gridView.Columns.Count - 1; + + if (gridView.Columns.Count - 1 > _selectedCol) + { + // DataGridViewColumn colRight = gridView.Columns[this.selectedCol + 1]; + var colRight = gridView.Columns.GetNextColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); + moveRightToolStripMenuItem.Enabled = colRight != null && colRight.Frozen == col.Frozen; + } + + if (_selectedCol > 0) + { + //DataGridViewColumn colLeft = gridView.Columns[this.selectedCol - 1]; + var colLeft = gridView.Columns.GetPreviousColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); + + moveLeftToolStripMenuItem.Enabled = colLeft != null && colLeft.Frozen == col.Frozen; + } + + var colLast = gridView.Columns[gridView.Columns.Count - 1]; + moveToLastColumnToolStripMenuItem.Enabled = colLast != null && colLast.Frozen == col.Frozen; + + // Fill context menu with column names + // + EventHandler ev = OnHandleColumnItemContextMenu; + allColumnsToolStripMenuItem.DropDownItems.Clear(); + foreach (DataGridViewColumn column in gridView.Columns) + { + if (column.HeaderText.Length > 0) + { + var item = allColumnsToolStripMenuItem.DropDownItems.Add(column.HeaderText, null, ev) as ToolStripMenuItem; + item.Tag = column; + item.Enabled = !column.Frozen; + } + } + } + + [SupportedOSPlatform("windows")] + private void OnHandleColumnItemContextMenu (object sender, EventArgs args) + { + if (sender is ToolStripItem item) + { + var column = item.Tag as DataGridViewColumn; + column.Visible = true; + column.DataGridView.FirstDisplayedScrollingColumnIndex = column.Index; + } + } + + [SupportedOSPlatform("windows")] + private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick (object sender, EventArgs e) + { + var ctl = columnContextMenuStrip.SourceControl; + var frozen = false; + + if (_freezeStateMap.TryGetValue(ctl, out var value)) + { + frozen = value; + } + + frozen = !frozen; + _freezeStateMap[ctl] = frozen; + + if (ctl is BufferedDataGridView gridView) + { + ApplyFrozenState(gridView); + } + } + + [SupportedOSPlatform("windows")] + private void OnMoveToLastColumnToolStripMenuItemClick (object sender, EventArgs e) + { + var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; + var col = gridView.Columns[_selectedCol]; + if (col != null) + { + col.DisplayIndex = gridView.Columns.Count - 1; + } + } + + [SupportedOSPlatform("windows")] + private void OnMoveLeftToolStripMenuItemClick (object sender, EventArgs e) + { + var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; + var col = gridView.Columns[_selectedCol]; + if (col != null && col.DisplayIndex > 0) + { + col.DisplayIndex -= 1; + } + } + + [SupportedOSPlatform("windows")] + private void OnMoveRightToolStripMenuItemClick (object sender, EventArgs e) + { + var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; + var col = gridView.Columns[_selectedCol]; + if (col != null && col.DisplayIndex < gridView.Columns.Count - 1) + { + col.DisplayIndex = col.DisplayIndex + 1; + } + } + + [SupportedOSPlatform("windows")] + private void OnHideColumnToolStripMenuItemClick (object sender, EventArgs e) + { + var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; + var col = gridView.Columns[_selectedCol]; + col.Visible = false; + } + + [SupportedOSPlatform("windows")] + private void OnRestoreColumnsToolStripMenuItemClick (object sender, EventArgs e) + { + var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; + foreach (DataGridViewColumn col in gridView.Columns) + { + col.Visible = true; + } + } + + [SupportedOSPlatform("windows")] + private void OnTimeSpreadingControlLineSelected (object sender, SelectLineEventArgs e) + { + SelectLine(e.Line, false, true); + } + + [SupportedOSPlatform("windows")] + private void OnBookmarkCommentToolStripMenuItemClick (object sender, EventArgs e) + { + AddBookmarkAndEditComment(); + } + + [SupportedOSPlatform("windows")] + private void OnHighlightSelectionInLogFileToolStripMenuItemClick (object sender, EventArgs e) + { + if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) + { + var he = new HighlightEntry() + { + SearchText = ctl.SelectedText, + ForegroundColor = Color.Red, + BackgroundColor = Color.Yellow, + IsRegEx = false, + IsCaseSensitive = true, + IsLedSwitch = false, + IsSetBookmark = false, + IsActionEntry = false, + ActionEntry = null, + IsWordMatch = false + }; + + lock (_tempHighlightEntryListLock) + { + _tempHighlightEntryList.Add(he); + } + + dataGridView.CancelEdit(); + dataGridView.EndEdit(); + RefreshAllGrids(); + } + } + + [SupportedOSPlatform("windows")] + private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick (object sender, EventArgs e) + { + if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) + { + HighlightEntry he = new() + { + SearchText = ctl.SelectedText, + ForegroundColor = Color.Red, + BackgroundColor = Color.Yellow, + IsRegEx = false, + IsCaseSensitive = true, + IsLedSwitch = false, + IsStopTail = false, + IsSetBookmark = false, + IsActionEntry = false, + ActionEntry = null, + IsWordMatch = true + }; + + lock (_tempHighlightEntryListLock) + { + _tempHighlightEntryList.Add(he); + } + + dataGridView.CancelEdit(); + dataGridView.EndEdit(); + RefreshAllGrids(); + } + } + + [SupportedOSPlatform("windows")] + private void OnEditModeCopyToolStripMenuItemClick (object sender, EventArgs e) + { + if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) + { + if (Util.IsNull(ctl.SelectedText) == false) + { + Clipboard.SetText(ctl.SelectedText); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnRemoveAllToolStripMenuItemClick (object sender, EventArgs e) + { + RemoveTempHighlights(); + } + + [SupportedOSPlatform("windows")] + private void OnMakePermanentToolStripMenuItemClick (object sender, EventArgs e) + { + lock (_tempHighlightEntryListLock) + { + lock (_currentHighlightGroupLock) + { + _currentHighlightGroup.HighlightEntryList.AddRange(_tempHighlightEntryList); + RemoveTempHighlights(); + OnCurrentHighlightListChanged(); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnMarkCurrentFilterRangeToolStripMenuItemClick (object sender, EventArgs e) + { + MarkCurrentFilterRange(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterForSelectionToolStripMenuItemClick (object sender, EventArgs e) + { + if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) + { + splitContainerLogWindow.Panel2Collapsed = false; + ResetFilterControls(); + FilterSearch(ctl.SelectedText); + } + } + + [SupportedOSPlatform("windows")] + private void OnSetSelectedTextAsBookmarkCommentToolStripMenuItemClick (object sender, EventArgs e) + { + if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) + { + AddBookmarkComment(ctl.SelectedText); + } + } + + private void OnDataGridViewCellClick (object sender, DataGridViewCellEventArgs e) + { + _shouldCallTimeSync = true; + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) + { + if (e.ColumnIndex == 0) + { + ToggleBookmark(); + } + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewOverlayDoubleClicked (object sender, OverlayEventArgs e) + { + BookmarkComment(e.BookmarkOverlay.Bookmark); + } + + [SupportedOSPlatform("windows")] + private void OnFilterRegexCheckBoxMouseUp (object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Right) + { + RegexHelperDialog dlg = new() + { + ExpressionHistoryList = ConfigManager.Settings.RegexHistory.ExpressionHistoryList, + TesttextHistoryList = ConfigManager.Settings.RegexHistory.TesttextHistoryList, + Owner = this, + CaseSensitive = filterCaseSensitiveCheckBox.Checked, + Pattern = filterComboBox.Text + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + ConfigManager.Settings.RegexHistory.ExpressionHistoryList = dlg.ExpressionHistoryList; + ConfigManager.Settings.RegexHistory.TesttextHistoryList = dlg.TesttextHistoryList; + + filterCaseSensitiveCheckBox.Checked = dlg.CaseSensitive; + filterComboBox.Text = dlg.Pattern; + + ConfigManager.Save(SettingsFlags.RegexHistory); + } + } + } + + #endregion + + #region Filter-Highlight + + [SupportedOSPlatform("windows")] + private void OnToggleHighlightPanelButtonClick (object sender, EventArgs e) + { + ToggleHighlightPanel(highlightSplitContainer.Panel2Collapsed); + } + + private void OnSaveFilterButtonClick (object sender, EventArgs e) + { + var newParams = _filterParams.Clone(); + newParams.Color = Color.FromKnownColor(KnownColor.Black); + ConfigManager.Settings.FilterList.Add(newParams); + OnFilterListChanged(this); + } + + [SupportedOSPlatform("windows")] + private void OnDeleteFilterButtonClick (object sender, EventArgs e) + { + var index = filterListBox.SelectedIndex; + if (index >= 0) + { + var filterParams = (FilterParams)filterListBox.Items[index]; + ConfigManager.Settings.FilterList.Remove(filterParams); + OnFilterListChanged(this); + if (filterListBox.Items.Count > 0) + { + filterListBox.SelectedIndex = filterListBox.Items.Count - 1; + } + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterUpButtonClick (object sender, EventArgs e) + { + var i = filterListBox.SelectedIndex; + if (i > 0) + { + var filterParams = (FilterParams)filterListBox.Items[i]; + ConfigManager.Settings.FilterList.RemoveAt(i); + i--; + ConfigManager.Settings.FilterList.Insert(i, filterParams); + OnFilterListChanged(this); + filterListBox.SelectedIndex = i; + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterDownButtonClick (object sender, EventArgs e) + { + var i = filterListBox.SelectedIndex; + if (i < 0) + { + return; + } + + if (i < filterListBox.Items.Count - 1) + { + var filterParams = (FilterParams)filterListBox.Items[i]; + ConfigManager.Settings.FilterList.RemoveAt(i); + i++; + ConfigManager.Settings.FilterList.Insert(i, filterParams); + OnFilterListChanged(this); + filterListBox.SelectedIndex = i; + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterListBoxMouseDoubleClick (object sender, MouseEventArgs e) + { + if (filterListBox.SelectedIndex >= 0) + { + var filterParams = (FilterParams)filterListBox.Items[filterListBox.SelectedIndex]; + var newParams = filterParams.Clone(); + //newParams.historyList = ConfigManager.Settings.filterHistoryList; + _filterParams = newParams; + ReInitFilterParams(_filterParams); + ApplyFilterParams(); + CheckForAdvancedButtonDirty(); + CheckForFilterDirty(); + filterSearchButton.Image = _searchButtonImage; + saveFilterButton.Enabled = false; + if (hideFilterListOnLoadCheckBox.Checked) + { + ToggleHighlightPanel(false); + } + + if (filterOnLoadCheckBox.Checked) + { + FilterSearch(); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterListBoxDrawItem (object sender, DrawItemEventArgs e) + { + e.DrawBackground(); + if (e.Index >= 0) + { + var filterParams = (FilterParams)filterListBox.Items[e.Index]; + Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); + + Brush brush; + + if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) + { + brush = new SolidBrush(filterListBox.BackColor); + } + else + { + brush = new SolidBrush(filterParams.Color); + } + + e.Graphics.DrawString(filterParams.SearchText, e.Font, brush, + new PointF(rectangle.Left, rectangle.Top)); + e.DrawFocusRectangle(); + brush.Dispose(); + } + } + + [SupportedOSPlatform("windows")] + // Color for filter list entry + private void OnColorToolStripMenuItemClick (object sender, EventArgs e) + { + var i = filterListBox.SelectedIndex; + if (i < filterListBox.Items.Count && i >= 0) + { + var filterParams = (FilterParams)filterListBox.Items[i]; + ColorDialog dlg = new() + { + CustomColors = [filterParams.Color.ToArgb()], + Color = filterParams.Color + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + filterParams.Color = dlg.Color; + filterListBox.Refresh(); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnFilterCaseSensitiveCheckBoxCheckedChanged (object sender, EventArgs e) + { + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterRegexCheckBoxCheckedChanged (object sender, EventArgs e) + { + fuzzyKnobControl.Enabled = !filterRegexCheckBox.Checked; + fuzzyLabel.Enabled = !filterRegexCheckBox.Checked; + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnInvertFilterCheckBoxCheckedChanged (object sender, EventArgs e) + { + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterRangeComboBoxTextChanged (object sender, EventArgs e) + { + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnFuzzyKnobControlValueChanged (object sender, EventArgs e) + { + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterComboBoxTextChanged (object sender, EventArgs e) + { + CheckForFilterDirty(); + } + + [SupportedOSPlatform("windows")] + private void OnSetBookmarksOnSelectedLinesToolStripMenuItemClick (object sender, EventArgs e) + { + SetBookmarksForSelectedFilterLines(); + } + + private void OnParentHighlightSettingsChanged (object sender, EventArgs e) + { + var groupName = _guiStateArgs.HighlightGroupName; + SetCurrentHighlightGroup(groupName); + } + + [SupportedOSPlatform("windows")] + private void OnFilterOnLoadCheckBoxMouseClick (object sender, MouseEventArgs e) + { + HandleChangedFilterOnLoadSetting(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterOnLoadCheckBoxKeyPress (object sender, KeyPressEventArgs e) + { + HandleChangedFilterOnLoadSetting(); + } + + [SupportedOSPlatform("windows")] + private void OnHideFilterListOnLoadCheckBoxMouseClick (object sender, MouseEventArgs e) + { + HandleChangedFilterOnLoadSetting(); + } + + [SupportedOSPlatform("windows")] + private void OnFilterToTabToolStripMenuItemClick (object sender, EventArgs e) + { + FilterToTab(); + } + + private void OnTimeSyncListWindowRemoved (object sender, EventArgs e) + { + var syncList = sender as TimeSyncList; + lock (_timeSyncListLock) + { + if (syncList.Count == 0 || (syncList.Count == 1 && syncList.Contains(this))) + { + if (syncList == TimeSyncList) + { + TimeSyncList = null; + OnSyncModeChanged(); + } + } + } + } + + private void OnFreeThisWindowFromTimeSyncToolStripMenuItemClick (object sender, EventArgs e) + { + FreeFromTimeSync(); + } + + [SupportedOSPlatform("windows")] + private void OnSplitContainerSplitterMoved (object sender, SplitterEventArgs e) + { + advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; + } + + [SupportedOSPlatform("windows")] + private void OnMarkFilterHitsInLogViewToolStripMenuItemClick (object sender, EventArgs e) + { + SearchParams p = new() + { + SearchText = _filterParams.SearchText, + IsRegex = _filterParams.IsRegex, + IsCaseSensitive = _filterParams.IsCaseSensitive + }; + + AddSearchHitHighlightEntry(p); + } + + [SupportedOSPlatform("windows")] + private void OnColumnComboBoxSelectionChangeCommitted (object sender, EventArgs e) + { + SelectColumn(); + } + + [SupportedOSPlatform("windows")] + private void OnColumnComboBoxKeyDown (object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + SelectColumn(); + dataGridView.Focus(); + } + } + + [SupportedOSPlatform("windows")] + private void OnColumnComboBoxPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) + { + if (e.KeyCode == Keys.Down && e.Modifiers == Keys.Alt) + { + columnComboBox.DroppedDown = true; + } + + if (e.KeyCode == Keys.Enter) + { + e.IsInputKey = true; + } + } + + [SupportedOSPlatform("windows")] + private void OnBookmarkProviderBookmarkRemoved (object sender, EventArgs e) + { + if (!_isLoading) + { + dataGridView.Refresh(); + filterGridView.Refresh(); + } + } + + [SupportedOSPlatform("windows")] + private void OnBookmarkProviderBookmarkAdded (object sender, EventArgs e) + { + if (!_isLoading) + { + dataGridView.Refresh(); + filterGridView.Refresh(); + } + } + + private void OnBookmarkProviderAllBookmarksRemoved (object sender, EventArgs e) + { + // nothing + } + + private void OnLogWindowLeave (object sender, EventArgs e) + { + InvalidateCurrentRow(); + } + + private void OnLogWindowEnter (object sender, EventArgs e) + { + InvalidateCurrentRow(); + } + + [SupportedOSPlatform("windows")] + private void OnDataGridViewRowUnshared (object sender, DataGridViewRowEventArgs e) + { + if (_logger.IsTraceEnabled) + { + _logger.Trace($"Row unshared line {e.Row.Cells[1].Value}"); + } + } + + #endregion + + #endregion + + #endregion + + [SupportedOSPlatform("windows")] + private void MeasureItem (object sender, MeasureItemEventArgs e) + { + e.ItemHeight = filterListBox.Font.Height; + } + + #endregion + + #region Private Methods + + [SupportedOSPlatform("windows")] + private void RegisterLogFileReaderEvents () + { + _logFileReader.LoadFile += OnLogFileReaderLoadFile; + _logFileReader.LoadingFinished += OnLogFileReaderFinishedLoading; + _logFileReader.LoadingStarted += OnLogFileReaderLoadingStarted; + _logFileReader.FileNotFound += OnLogFileReaderFileNotFound; + _logFileReader.Respawned += OnLogFileReaderRespawned; + // FileSizeChanged is not registered here because it's registered after loading has finished + } + + [SupportedOSPlatform("windows")] + private void UnRegisterLogFileReaderEvents () + { + if (_logFileReader != null) + { + _logFileReader.LoadFile -= OnLogFileReaderLoadFile; + _logFileReader.LoadingFinished -= OnLogFileReaderFinishedLoading; + _logFileReader.LoadingStarted -= OnLogFileReaderLoadingStarted; + _logFileReader.FileNotFound -= OnLogFileReaderFileNotFound; + _logFileReader.Respawned -= OnLogFileReaderRespawned; + _logFileReader.FileSizeChanged -= OnFileSizeChanged; + } + } + + [SupportedOSPlatform("windows")] + private void CreateDefaultViewStyle () + { + DataGridViewCellStyle dataGridViewCellStyleMainGrid = new(); + DataGridViewCellStyle dataGridViewCellStyleFilterGrid = new(); + + dataGridViewCellStyleMainGrid.Alignment = DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyleMainGrid.BackColor = SystemColors.Window; + dataGridViewCellStyleMainGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + dataGridViewCellStyleMainGrid.ForeColor = SystemColors.ControlText; + dataGridViewCellStyleMainGrid.SelectionBackColor = SystemColors.Highlight; + //dataGridViewCellStyleMainGrid.SelectionForeColor = SystemColors.HighlightText; + + var highlightColor = SystemColors.Highlight; + //Color is smaller than 128, means its darker + var isSelectionBackColorDark = (highlightColor.R * 0.2126) + (highlightColor.G * 0.7152) + (highlightColor.B * 0.0722) < 255 / 2; + + if (isSelectionBackColorDark) + { + dataGridViewCellStyleMainGrid.SelectionForeColor = Color.White; + } + else + { + dataGridViewCellStyleMainGrid.SelectionForeColor = Color.Black; + + } + + dataGridViewCellStyleMainGrid.WrapMode = DataGridViewTriState.False; + dataGridView.DefaultCellStyle = dataGridViewCellStyleMainGrid; + + dataGridViewCellStyleFilterGrid.Alignment = DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyleFilterGrid.BackColor = SystemColors.Window; + dataGridViewCellStyleFilterGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + dataGridViewCellStyleFilterGrid.ForeColor = SystemColors.ControlText; + dataGridViewCellStyleFilterGrid.SelectionBackColor = SystemColors.Highlight; + //dataGridViewCellStyleFilterGrid.SelectionForeColor = SystemColors.HighlightText; + + if (isSelectionBackColorDark) + { + dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.White; + } + else + { + dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.Black; + } + + dataGridViewCellStyleFilterGrid.WrapMode = DataGridViewTriState.False; + filterGridView.DefaultCellStyle = dataGridViewCellStyleFilterGrid; + } + + [SupportedOSPlatform("windows")] + private bool LoadPersistenceOptions () + { + if (InvokeRequired) + { + return (bool)Invoke(new BoolReturnDelegate(LoadPersistenceOptions)); + } + + if (!Preferences.SaveSessions && ForcedPersistenceFileName == null) + { + return false; + } + + try + { + var persistenceData = ForcedPersistenceFileName == null + ? Persister.LoadPersistenceDataOptionsOnly(FileName, Preferences) + : Persister.LoadPersistenceDataOptionsOnlyFromFixedFile(ForcedPersistenceFileName); + + if (persistenceData == null) + { + _logger.Info($"No persistence data for {FileName} found."); + return false; + } + + IsMultiFile = persistenceData.MultiFile; + _multiFileOptions = new MultiFileOptions + { + FormatPattern = persistenceData.MultiFilePattern, + MaxDayTry = persistenceData.MultiFileMaxDays + }; + + if (string.IsNullOrEmpty(_multiFileOptions.FormatPattern)) + { + _multiFileOptions = ObjectClone.Clone(Preferences.MultiFileOptions); + } + + splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; + splitContainerLogWindow.Panel2Collapsed = !persistenceData.FilterVisible; + ToggleHighlightPanel(persistenceData.FilterSaveListVisible); + ShowAdvancedFilterPanel(persistenceData.FilterAdvanced); + + if (_reloadMemento == null) + { + PreselectColumnizer(persistenceData.ColumnizerName); + } + + FollowTailChanged(persistenceData.FollowTail, false); + if (persistenceData.TabName != null) + { + Text = persistenceData.TabName; + } + + AdjustHighlightSplitterWidth(); + SetCurrentHighlightGroup(persistenceData.HighlightGroupName); + + if (persistenceData.MultiFileNames.Count > 0) + { + _logger.Info(CultureInfo.InvariantCulture, "Detected MultiFile name list in persistence options"); + _fileNames = new string[persistenceData.MultiFileNames.Count]; + persistenceData.MultiFileNames.CopyTo(_fileNames); + } + else + { + _fileNames = null; + } + + //this.bookmarkWindow.ShowBookmarkCommentColumn = persistenceData.showBookmarkCommentColumn; + SetExplicitEncoding(persistenceData.Encoding); + return true; + } + catch (Exception ex) + { + _logger.Error(ex, "Error loading persistence data: "); + return false; + } + } + + [SupportedOSPlatform("windows")] + private void SetDefaultsFromPrefs () + { + filterTailCheckBox.Checked = Preferences.FilterTail; + syncFilterCheckBox.Checked = Preferences.FilterSync; + FollowTailChanged(Preferences.FollowTail, false); + _multiFileOptions = ObjectClone.Clone(Preferences.MultiFileOptions); + } + + [SupportedOSPlatform("windows")] + private void LoadPersistenceData () + { + if (InvokeRequired) + { + Invoke(new MethodInvoker(LoadPersistenceData)); + return; + } + + if (!Preferences.SaveSessions && !ForcePersistenceLoading && ForcedPersistenceFileName == null) + { + SetDefaultsFromPrefs(); + return; + } + + if (IsTempFile) + { + SetDefaultsFromPrefs(); + return; + } + + ForcePersistenceLoading = false; // force only 1 time (while session load) + + try + { + var persistenceData = ForcedPersistenceFileName == null + ? Persister.LoadPersistenceData(FileName, Preferences) + : Persister.LoadPersistenceDataFromFixedFile(ForcedPersistenceFileName); + + if (persistenceData.LineCount > _logFileReader.LineCount) + { + // outdated persistence data (logfile rollover) + // MessageBox.Show(this, "Persistence data for " + this.FileName + " is outdated. It was discarded.", "Log Expert"); + _logger.Info($"Persistence data for {FileName} is outdated. It was discarded."); + _ = LoadPersistenceOptions(); + return; + } + + _bookmarkProvider.SetBookmarks(persistenceData.BookmarkList); + _rowHeightList = persistenceData.RowHeightList; + try + { + if (persistenceData.CurrentLine >= 0 && persistenceData.CurrentLine < dataGridView.RowCount) + { + SelectLine(persistenceData.CurrentLine, false, true); + } + else + { + if (_logFileReader.LineCount > 0) + { + dataGridView.FirstDisplayedScrollingRowIndex = _logFileReader.LineCount - 1; + SelectLine(_logFileReader.LineCount - 1, false, true); + } + } + + if (persistenceData.FirstDisplayedLine >= 0 && + persistenceData.FirstDisplayedLine < dataGridView.RowCount) + { + dataGridView.FirstDisplayedScrollingRowIndex = persistenceData.FirstDisplayedLine; + } + + if (persistenceData.FollowTail) + { + FollowTailChanged(persistenceData.FollowTail, false); + } + } + catch (ArgumentOutOfRangeException) + { + // FirstDisplayedScrollingRowIndex calculates sometimes the wrong scrolling ranges??? + } + + if (Preferences.SaveFilters) + { + RestoreFilters(persistenceData); + } + } + catch (IOException ex) + { + SetDefaultsFromPrefs(); + _logger.Error(ex, "Error loading bookmarks: "); + } + } + + [SupportedOSPlatform("windows")] + private void RestoreFilters (PersistenceData persistenceData) + { + if (persistenceData.FilterParamsList.Count > 0) + { + _filterParams = persistenceData.FilterParamsList[0]; + ReInitFilterParams(_filterParams); + } + + ApplyFilterParams(); // re-loaded filter settingss + BeginInvoke(new MethodInvoker(FilterSearch)); + try + { + splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; + splitContainerLogWindow.Panel2Collapsed = !persistenceData.FilterVisible; + } + catch (InvalidOperationException e) + { + _logger.Error(e, "Error setting splitter distance: "); + } + + ShowAdvancedFilterPanel(persistenceData.FilterAdvanced); + if (_filterPipeList.Count == 0) // don't restore if it's only a reload + { + RestoreFilterTabs(persistenceData); + } + } + + private void RestoreFilterTabs (PersistenceData persistenceData) + { + foreach (var data in persistenceData.FilterTabDataList) + { + var persistFilterParams = data.FilterParams; + ReInitFilterParams(persistFilterParams); + List filterResultList = []; + //List lastFilterResultList = new List(); + List filterHitList = []; + Filter(persistFilterParams, filterResultList, _lastFilterLinesList, filterHitList); + FilterPipe pipe = new(persistFilterParams.Clone(), this); + WritePipeToTab(pipe, filterResultList, data.PersistenceData.TabName, data.PersistenceData); + } + } + + private void ReInitFilterParams (FilterParams filterParams) + { + filterParams.SearchText = filterParams.SearchText; // init "lowerSearchText" + filterParams.RangeSearchText = filterParams.RangeSearchText; // init "lowerRangesearchText" + filterParams.CurrentColumnizer = CurrentColumnizer; + if (filterParams.IsRegex) + { + try + { + filterParams.CreateRegex(); + } + catch (ArgumentException) + { + StatusLineError("Invalid regular expression"); + } + } + } + + private void EnterLoadFileStatus () + { + _logger.Debug(CultureInfo.InvariantCulture, "EnterLoadFileStatus begin"); + + if (InvokeRequired) + { + Invoke(new MethodInvoker(EnterLoadFileStatus)); + return; + } + + _statusEventArgs.StatusText = "Loading file..."; + _statusEventArgs.LineCount = 0; + _statusEventArgs.FileSize = 0; + SendStatusLineUpdate(); + + _progressEventArgs.MinValue = 0; + _progressEventArgs.MaxValue = 0; + _progressEventArgs.Value = 0; + _progressEventArgs.Visible = true; + SendProgressBarUpdate(); + + _isLoading = true; + _shouldCancel = true; + ClearFilterList(); + ClearBookmarkList(); + dataGridView.ClearSelection(); + dataGridView.RowCount = 0; + _logger.Debug(CultureInfo.InvariantCulture, "EnterLoadFileStatus end"); + } + + [SupportedOSPlatform("windows")] + private void PositionAfterReload (ReloadMemento reloadMemento) + { + if (_reloadMemento.CurrentLine < dataGridView.RowCount && _reloadMemento.CurrentLine >= 0) + { + dataGridView.CurrentCell = dataGridView.Rows[_reloadMemento.CurrentLine].Cells[0]; + } + + if (_reloadMemento.FirstDisplayedLine < dataGridView.RowCount && _reloadMemento.FirstDisplayedLine >= 0) + { + dataGridView.FirstDisplayedScrollingRowIndex = _reloadMemento.FirstDisplayedLine; + } + } + + [SupportedOSPlatform("windows")] + private void LogfileDead () + { + _logger.Info(CultureInfo.InvariantCulture, "File not found."); + _isDeadFile = true; + + //this.logFileReader.FileSizeChanged -= this.FileSizeChangedHandler; + //if (this.logFileReader != null) + // this.logFileReader.stopMonitoring(); + + dataGridView.Enabled = false; + dataGridView.RowCount = 0; + _progressEventArgs.Visible = false; + _progressEventArgs.Value = _progressEventArgs.MaxValue; + SendProgressBarUpdate(); + _statusEventArgs.FileSize = 0; + _statusEventArgs.LineCount = 0; + _statusEventArgs.CurrentLineNum = 0; + SendStatusLineUpdate(); + _shouldCancel = true; + ClearFilterList(); + ClearBookmarkList(); + + StatusLineText("File not found"); + OnFileNotFound(EventArgs.Empty); + } + + [SupportedOSPlatform("windows")] + private void LogfileRespawned () + { + _logger.Info(CultureInfo.InvariantCulture, "LogfileDead(): Reloading file because it has been respawned."); + _isDeadFile = false; + dataGridView.Enabled = true; + StatusLineText(""); + OnFileRespawned(EventArgs.Empty); + Reload(); + } + + [SupportedOSPlatform("windows")] + private void SetGuiAfterLoading () + { + if (Text.Length == 0) + { + Text = IsTempFile + ? TempTitleName + : Util.GetNameFromPath(FileName); + } + + ShowBookmarkBubbles = Preferences.ShowBubbles; + //if (this.forcedColumnizer == null) + { + ILogLineColumnizer columnizer; + if (_forcedColumnizerForLoading != null) + { + columnizer = _forcedColumnizerForLoading; + _forcedColumnizerForLoading = null; + } + else + { + columnizer = FindColumnizer(); + if (columnizer != null) + { + if (_reloadMemento == null) + { + //TODO this needs to be refactored + var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; + + columnizer = ColumnizerPicker.CloneColumnizer(columnizer, directory); + } + } + else + { + //TODO this needs to be refactored + var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; + + // Default Columnizers + columnizer = ColumnizerPicker.CloneColumnizer(ColumnizerPicker.FindColumnizer(FileName, _logFileReader, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers), directory); + } + } + + Invoke(new SetColumnizerFx(SetColumnizer), columnizer); + } + + dataGridView.Enabled = true; + DisplayCurrentFileOnStatusline(); + //this.guiStateArgs.FollowTail = this.Preferences.followTail; + _guiStateArgs.MultiFileEnabled = !IsTempFile; + _guiStateArgs.MenuEnabled = true; + _guiStateArgs.CurrentEncoding = _logFileReader.CurrentEncoding; + SendGuiStateUpdate(); + //if (this.dataGridView.RowCount > 0) + // SelectLine(this.dataGridView.RowCount - 1); + //if (this.dataGridView.Columns.Count > 1) + //{ + // this.dataGridView.Columns[this.dataGridView.Columns.Count-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; + // this.dataGridView.Columns[this.dataGridView.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; + // AdjustMinimumGridWith(); + //} + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + if (Preferences.TimestampControl) + { + SetTimestampLimits(); + SyncTimestampDisplay(); + } + + var settings = ConfigManager.Settings; + ShowLineColumn(!settings.HideLineColumn); + } + + ShowTimeSpread(Preferences.ShowTimeSpread && CurrentColumnizer.IsTimeshiftImplemented()); + locateLineInOriginalFileToolStripMenuItem.Enabled = FilterPipe != null; + } + + private ILogLineColumnizer FindColumnizer () + { + var columnizer = Preferences.MaskPrio + ? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)) ?? _parentLogTabWin.GetColumnizerHistoryEntry(FileName) + : _parentLogTabWin.GetColumnizerHistoryEntry(FileName) ?? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)); + + return columnizer; + } + + private void ReloadNewFile () + { + // prevent "overloads". May occur on very fast rollovers (next rollover before the file is reloaded) + lock (_reloadLock) + { + _reloadOverloadCounter++; + _logger.Info($"ReloadNewFile(): counter = {_reloadOverloadCounter}"); + if (_reloadOverloadCounter <= 1) + { + SavePersistenceData(false); + _loadingFinishedEvent.Reset(); + _externaLoadingFinishedEvent.Reset(); + Thread reloadFinishedThread = new(ReloadFinishedThreadFx) + { + IsBackground = true + }; + reloadFinishedThread.Start(); + LoadFile(FileName, EncodingOptions); + + ClearBookmarkList(); + SavePersistenceData(false); + + //if (this.filterTailCheckBox.Checked) + //{ + // _logger.logDebug("Waiting for loading to be complete."); + // loadingFinishedEvent.WaitOne(); + // _logger.logDebug("Refreshing filter view because of reload."); + // FilterSearch(); + //} + //LoadFilterPipes(); + } + else + { + _logger.Debug(CultureInfo.InvariantCulture, "Preventing reload because of recursive calls."); + } + + _reloadOverloadCounter--; + } + } + + [SupportedOSPlatform("windows")] + private void ReloadFinishedThreadFx () + { + _logger.Info(CultureInfo.InvariantCulture, "Waiting for loading to be complete."); + _loadingFinishedEvent.WaitOne(); + _logger.Info(CultureInfo.InvariantCulture, "Refreshing filter view because of reload."); + Invoke(new MethodInvoker(FilterSearch)); + LoadFilterPipes(); + } + + private void UpdateProgress (LoadFileEventArgs e) + { + try + { + if (e.ReadPos >= e.FileSize) + { + //_logger.Warn(CultureInfo.InvariantCulture, "UpdateProgress(): ReadPos (" + e.ReadPos + ") is greater than file size (" + e.FileSize + "). Aborting Update"); + return; + } + + _statusEventArgs.FileSize = e.ReadPos; + //this.progressEventArgs.Visible = true; + _progressEventArgs.MaxValue = (int)e.FileSize; + _progressEventArgs.Value = (int)e.ReadPos; + SendProgressBarUpdate(); + SendStatusLineUpdate(); + } + catch (Exception ex) + { + _logger.Error(ex, "UpdateProgress(): "); + } + } + + private void LoadingStarted (LoadFileEventArgs e) + { + try + { + _statusEventArgs.FileSize = e.ReadPos; + _statusEventArgs.StatusText = "Loading " + Util.GetNameFromPath(e.FileName); + _progressEventArgs.Visible = true; + _progressEventArgs.MaxValue = (int)e.FileSize; + _progressEventArgs.Value = (int)e.ReadPos; + SendProgressBarUpdate(); + SendStatusLineUpdate(); + } + catch (Exception ex) + { + _logger.Error(ex, "LoadingStarted(): "); + } + } + + private void LoadingFinished () + { + _logger.Info(CultureInfo.InvariantCulture, "File loading complete."); + + StatusLineText(""); + _logFileReader.FileSizeChanged += OnFileSizeChanged; + _isLoading = false; + _shouldCancel = false; + dataGridView.SuspendLayout(); + dataGridView.RowCount = _logFileReader.LineCount; + dataGridView.CurrentCellChanged += OnDataGridViewCurrentCellChanged; + dataGridView.Enabled = true; + dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + dataGridView.ResumeLayout(); + _progressEventArgs.Visible = false; + _progressEventArgs.Value = _progressEventArgs.MaxValue; + SendProgressBarUpdate(); + //if (this.logFileReader.LineCount > 0) + //{ + // this.dataGridView.FirstDisplayedScrollingRowIndex = this.logFileReader.LineCount - 1; + // SelectLine(this.logFileReader.LineCount - 1); + //} + _guiStateArgs.FollowTail = true; + SendGuiStateUpdate(); + _statusEventArgs.LineCount = _logFileReader.LineCount; + _statusEventArgs.FileSize = _logFileReader.FileSize; + SendStatusLineUpdate(); + + var setLastColumnWidth = _parentLogTabWin.Preferences.SetLastColumnWidth; + var lastColumnWidth = _parentLogTabWin.Preferences.LastColumnWidth; + var fontName = _parentLogTabWin.Preferences.FontName; + var fontSize = _parentLogTabWin.Preferences.FontSize; + + PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, true, SettingsFlags.All); + //LoadPersistenceData(); + } + + private void LogEventWorker () + { + Thread.CurrentThread.Name = "LogEventWorker"; + while (true) + { + _logger.Debug(CultureInfo.InvariantCulture, "Waiting for signal"); + _logEventArgsEvent.WaitOne(); + _logger.Debug(CultureInfo.InvariantCulture, "Wakeup signal received."); + while (true) + { + LogEventArgs e; + var lastLineCount = 0; + lock (_logEventArgsList) + { + _logger.Info(CultureInfo.InvariantCulture, "{0} events in queue", _logEventArgsList.Count); + if (_logEventArgsList.Count == 0) + { + _logEventArgsEvent.Reset(); + break; + } + + e = _logEventArgsList[0]; + _logEventArgsList.RemoveAt(0); + } + + if (e.IsRollover) + { + ShiftBookmarks(e.RolloverOffset); + ShiftRowHeightList(e.RolloverOffset); + ShiftFilterPipes(e.RolloverOffset); + lastLineCount = 0; + } + else + { + if (e.LineCount < lastLineCount) + { + _logger.Error("Line count of event is: {0}, should be greater than last line count: {1}", e.LineCount, lastLineCount); + } + } + + Invoke(UpdateGrid, [e]); + CheckFilterAndHighlight(e); + _timeSpreadCalc.SetLineCount(e.LineCount); + } + } + } + + private void StopLogEventWorkerThread () + { + _logEventArgsEvent.Set(); + cts.Cancel(); + //_logEventHandlerThread.Abort(); + //_logEventHandlerThread.Join(); + } + + private void OnFileSizeChanged (LogEventArgs e) + { + FileSizeChanged?.Invoke(this, e); + } + + private void UpdateGrid (LogEventArgs e) + { + var oldRowCount = dataGridView.RowCount; + var firstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex; + + if (dataGridView.CurrentCellAddress.Y >= e.LineCount) + { + //this.dataGridView.Rows[this.dataGridView.CurrentCellAddress.Y].Selected = false; + //this.dataGridView.CurrentCell = this.dataGridView.Rows[0].Cells[0]; + } + + try + { + if (dataGridView.RowCount > e.LineCount) + { + var currentLineNum = dataGridView.CurrentCellAddress.Y; + dataGridView.RowCount = 0; + dataGridView.RowCount = e.LineCount; + if (_guiStateArgs.FollowTail == false) + { + if (currentLineNum >= dataGridView.RowCount) + { + currentLineNum = dataGridView.RowCount - 1; + } + + dataGridView.CurrentCell = dataGridView.Rows[currentLineNum].Cells[0]; + } + } + else + { + dataGridView.RowCount = e.LineCount; + } + + _logger.Debug(CultureInfo.InvariantCulture, "UpdateGrid(): new RowCount={0}", dataGridView.RowCount); + + if (e.IsRollover) + { + // Multifile rollover + // keep selection and view range, if no follow tail mode + if (!_guiStateArgs.FollowTail) + { + var currentLineNum = dataGridView.CurrentCellAddress.Y; + currentLineNum -= e.RolloverOffset; + if (currentLineNum < 0) + { + currentLineNum = 0; + } + + _logger.Debug(CultureInfo.InvariantCulture, "UpdateGrid(): Rollover=true, Rollover offset={0}, currLineNum was {1}, new currLineNum={2}", e.RolloverOffset, dataGridView.CurrentCellAddress.Y, currentLineNum); + firstDisplayedLine -= e.RolloverOffset; + if (firstDisplayedLine < 0) + { + firstDisplayedLine = 0; + } + + dataGridView.FirstDisplayedScrollingRowIndex = firstDisplayedLine; + dataGridView.CurrentCell = dataGridView.Rows[currentLineNum].Cells[0]; + dataGridView.Rows[currentLineNum].Selected = true; + } + } + + _statusEventArgs.LineCount = e.LineCount; + StatusLineFileSize(e.FileSize); + + if (!_isLoading) + { + if (oldRowCount == 0) + { + AdjustMinimumGridWith(); + } + + //CheckFilterAndHighlight(e); + } + + if (_guiStateArgs.FollowTail && dataGridView.RowCount > 0) + { + dataGridView.FirstDisplayedScrollingRowIndex = dataGridView.RowCount - 1; + OnTailFollowed(EventArgs.Empty); + } + + if (Preferences.TimestampControl && !_isLoading) + { + SetTimestampLimits(); + } + } + catch (Exception ex) + { + _logger.Error(ex, "Fehler bei UpdateGrid(): "); + } + + //this.dataGridView.Refresh(); + //this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + } + + private void CheckFilterAndHighlight (LogEventArgs e) + { + var noLed = true; + bool suppressLed; + bool setBookmark; + bool stopTail; + string bookmarkComment; + + if (filterTailCheckBox.Checked || _filterPipeList.Count > 0) + { + var filterStart = e.PrevLineCount; + if (e.IsRollover) + { + ShiftFilterLines(e.RolloverOffset); + filterStart -= e.RolloverOffset; + } + + var firstStopTail = true; + ColumnizerCallback callback = new(this); + var filterLineAdded = false; + for (var i = filterStart; i < e.LineCount; ++i) + { + var line = _logFileReader.GetLogLine(i); + if (line == null) + { + return; + } + + if (filterTailCheckBox.Checked) + { + callback.SetLineNum(i); + if (Util.TestFilterCondition(_filterParams, line, callback)) + { + //AddFilterLineFx addFx = new AddFilterLineFx(AddFilterLine); + //this.Invoke(addFx, new object[] { i, true }); + filterLineAdded = true; + AddFilterLine(i, false, _filterParams, _filterResultList, _lastFilterLinesList, + _filterHitList); + } + } + + //ProcessFilterPipeFx pipeFx = new ProcessFilterPipeFx(ProcessFilterPipes); + //pipeFx.BeginInvoke(i, null, null); + ProcessFilterPipes(i); + + var matchingList = FindMatchingHilightEntries(line); + LaunchHighlightPlugins(matchingList, i); + GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); + if (setBookmark) + { + SetBookmarkFx fx = SetBookmarkFromTrigger; + fx.BeginInvoke(i, bookmarkComment, null, null); + } + + if (stopTail && _guiStateArgs.FollowTail) + { + var wasFollow = _guiStateArgs.FollowTail; + FollowTailChanged(false, true); + if (firstStopTail && wasFollow) + { + Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); + firstStopTail = false; + } + } + + if (!suppressLed) + { + noLed = false; + } + } + + if (filterLineAdded) + { + //AddFilterLineGuiUpdateFx addFx = new AddFilterLineGuiUpdateFx(AddFilterLineGuiUpdate); + //this.Invoke(addFx); + TriggerFilterLineGuiUpdate(); + } + } + else + { + var firstStopTail = true; + var startLine = e.PrevLineCount; + if (e.IsRollover) + { + ShiftFilterLines(e.RolloverOffset); + startLine -= e.RolloverOffset; + } + + for (var i = startLine; i < e.LineCount; ++i) + { + var line = _logFileReader.GetLogLine(i); + if (line != null) + { + var matchingList = FindMatchingHilightEntries(line); + LaunchHighlightPlugins(matchingList, i); + GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, + out bookmarkComment); + if (setBookmark) + { + SetBookmarkFx fx = SetBookmarkFromTrigger; + fx.BeginInvoke(i, bookmarkComment, null, null); + } + + if (stopTail && _guiStateArgs.FollowTail) + { + var wasFollow = _guiStateArgs.FollowTail; + FollowTailChanged(false, true); + if (firstStopTail && wasFollow) + { + Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); + firstStopTail = false; + } + } + + if (!suppressLed) + { + noLed = false; + } + } + } + } + + if (!noLed) + { + OnFileSizeChanged(e); + } + } + + private void LaunchHighlightPlugins (IList matchingList, int lineNum) + { + LogExpertCallback callback = new(this) + { + LineNum = lineNum + }; + + foreach (var entry in matchingList) + { + if (entry.IsActionEntry && entry.ActionEntry.PluginName != null) + { + var plugin = PluginRegistry.PluginRegistry.Instance.FindKeywordActionPluginByName(entry.ActionEntry.PluginName); + if (plugin != null) + { + ActionPluginExecuteFx fx = plugin.Execute; + fx.BeginInvoke(entry.SearchText, entry.ActionEntry.ActionParam, callback, CurrentColumnizer, null, null); + } + } + } + } + + private void PreSelectColumnizer (ILogLineColumnizer columnizer) + { + CurrentColumnizer = columnizer != null + ? (_forcedColumnizerForLoading = columnizer) + : (_forcedColumnizerForLoading = ColumnizerPicker.FindColumnizer(FileName, _logFileReader, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers)); + } + + private void SetColumnizer (ILogLineColumnizer columnizer) + { + columnizer = ColumnizerPicker.FindReplacementForAutoColumnizer(FileName, _logFileReader, columnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + + var timeDiff = 0; + if (CurrentColumnizer != null && CurrentColumnizer.IsTimeshiftImplemented()) + { + timeDiff = CurrentColumnizer.GetTimeOffset(); + } + + SetColumnizerInternal(columnizer); + + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + CurrentColumnizer.SetTimeOffset(timeDiff); + } + } + + private void SetColumnizerInternal (ILogLineColumnizer columnizer) + { + _logger.Info(CultureInfo.InvariantCulture, "SetColumnizerInternal(): {0}", columnizer.GetName()); + + var oldColumnizer = CurrentColumnizer; + var oldColumnizerIsXmlType = CurrentColumnizer is ILogLineXmlColumnizer; + var oldColumnizerIsPreProcess = CurrentColumnizer is IPreProcessColumnizer; + var mustReload = false; + + // Check if the filtered columns disappeared, if so must refresh the UI + if (_filterParams.ColumnRestrict) + { + var newColumns = columnizer != null ? columnizer.GetColumnNames() : Array.Empty(); + var colChanged = false; + + if (dataGridView.ColumnCount - 2 == newColumns.Length) // two first columns are 'marker' and 'line number' + { + for (var i = 0; i < newColumns.Length; i++) + { + if (dataGridView.Columns[i].HeaderText != newColumns[i]) + { + colChanged = true; + break; // one change is sufficient + } + } + } + else + { + colChanged = true; + } + + if (colChanged) + { + // Update UI + columnNamesLabel.Text = CalculateColumnNames(_filterParams); + } + } + + var oldColType = _filterParams.CurrentColumnizer?.GetType(); + var newColType = columnizer?.GetType(); + + if (oldColType != newColType && _filterParams.ColumnRestrict && _filterParams.IsFilterTail) + { + _filterParams.ColumnList.Clear(); + } + + if (CurrentColumnizer == null || CurrentColumnizer.GetType() != columnizer.GetType()) + { + CurrentColumnizer = columnizer; + _freezeStateMap.Clear(); + if (_logFileReader != null) + { + if (CurrentColumnizer is IPreProcessColumnizer) + { + _logFileReader.PreProcessColumnizer = (IPreProcessColumnizer)CurrentColumnizer; + } + else + { + _logFileReader.PreProcessColumnizer = null; + } + } + + // always reload when choosing XML columnizers + if (_logFileReader != null && CurrentColumnizer is ILogLineXmlColumnizer) + { + //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() + mustReload = true; + } + + // Reload when choosing no XML columnizer but previous columnizer was XML + if (_logFileReader != null && !(CurrentColumnizer is ILogLineXmlColumnizer) && oldColumnizerIsXmlType) + { + _logFileReader.IsXmlMode = false; + //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() + mustReload = true; + } + + // Reload when previous columnizer was PreProcess and current is not, and vice versa. + // When the current columnizer is a preProcess columnizer, reload in every case. + if (CurrentColumnizer is IPreProcessColumnizer != oldColumnizerIsPreProcess || + CurrentColumnizer is IPreProcessColumnizer) + { + //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() + mustReload = true; + } + } + else + { + CurrentColumnizer = columnizer; + } + + (oldColumnizer as IInitColumnizer)?.DeSelected(new ColumnizerCallback(this)); + + (columnizer as IInitColumnizer)?.Selected(new ColumnizerCallback(this)); + + SetColumnizer(columnizer, dataGridView); + SetColumnizer(columnizer, filterGridView); + _patternWindow?.SetColumnizer(columnizer); + + _guiStateArgs.TimeshiftPossible = columnizer.IsTimeshiftImplemented(); + SendGuiStateUpdate(); + + if (_logFileReader != null) + { + dataGridView.RowCount = _logFileReader.LineCount; + } + + if (_filterResultList != null) + { + filterGridView.RowCount = _filterResultList.Count; + } + + if (mustReload) + { + Reload(); + } + else + { + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + SetTimestampLimits(); + SyncTimestampDisplay(); + } + + var settings = ConfigManager.Settings; + ShowLineColumn(!settings.HideLineColumn); + ShowTimeSpread(Preferences.ShowTimeSpread && columnizer.IsTimeshiftImplemented()); + } + + if (!columnizer.IsTimeshiftImplemented() && IsTimeSynced) + { + FreeFromTimeSync(); + } + + columnComboBox.Items.Clear(); + + foreach (var columnName in columnizer.GetColumnNames()) + { + columnComboBox.Items.Add(columnName); + } + + columnComboBox.SelectedIndex = 0; + + OnColumnizerChanged(CurrentColumnizer); + } + + private void AutoResizeColumns (BufferedDataGridView gridView) + { + try + { + gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + if (gridView.Columns.Count > 1 && Preferences.SetLastColumnWidth && + gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.LastColumnWidth + ) + { + // It seems that using 'MinimumWidth' instead of 'Width' prevents the DataGridView's NullReferenceExceptions + //gridView.Columns[gridView.Columns.Count - 1].Width = this.Preferences.lastColumnWidth; + gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.LastColumnWidth; + } + } + catch (NullReferenceException e) + { + // See https://connect.microsoft.com/VisualStudio/feedback/details/366943/autoresizecolumns-in-datagridview-throws-nullreferenceexception + // possible solution => https://stackoverflow.com/questions/36287553/nullreferenceexception-when-trying-to-set-datagridview-column-width-brings-th + // There are some rare situations with null ref exceptions when resizing columns and on filter finished + // So catch them here. Better than crashing. + _logger.Error(e, "Error while resizing columns: "); + } + } + + private void PaintCell (DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) + { + PaintHighlightedCell(e, gridView, noBackgroundFill, groundEntry); + } + + private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) + { + var column = e.Value as IColumn; + + column ??= Column.EmptyColumn; + + var matchList = FindHighlightMatches(column); + // too many entries per line seem to cause problems with the GDI + while (matchList.Count > 50) + { + matchList.RemoveAt(50); + } + + var he = new HighlightEntry + { + SearchText = column.DisplayValue, + ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), + BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, + IsWordMatch = true + }; + + HighlightMatchEntry hme = new() + { + StartPos = 0, + Length = column.DisplayValue.Length, + HighlightEntry = he + }; + + if (groundEntry != null) + { + hme.HighlightEntry.IsBold = groundEntry.IsBold; + } + + matchList = MergeHighlightMatchEntries(matchList, hme); + + //var leftPad = e.CellStyle.Padding.Left; + //RectangleF rect = new(e.CellBounds.Left + leftPad, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height); + + var borderWidths = PaintHelper.BorderWidths(e.AdvancedBorderStyle); + var valBounds = e.CellBounds; + valBounds.Offset(borderWidths.X, borderWidths.Y); + valBounds.Width -= borderWidths.Right; + valBounds.Height -= borderWidths.Bottom; + if (e.CellStyle.Padding != Padding.Empty) + { + valBounds.Offset(e.CellStyle.Padding.Left, e.CellStyle.Padding.Top); + valBounds.Width -= e.CellStyle.Padding.Horizontal; + valBounds.Height -= e.CellStyle.Padding.Vertical; + } + + var flags = + TextFormatFlags.Left + | TextFormatFlags.SingleLine + | TextFormatFlags.NoPrefix + | TextFormatFlags.PreserveGraphicsClipping + | TextFormatFlags.NoPadding + | TextFormatFlags.VerticalCenter + | TextFormatFlags.TextBoxControl + ; + + // | TextFormatFlags.VerticalCenter + // | TextFormatFlags.TextBoxControl + // TextFormatFlags.SingleLine + + //TextRenderer.DrawText(e.Graphics, e.Value as String, e.CellStyle.Font, valBounds, Color.FromKnownColor(KnownColor.Black), flags); + + var wordPos = valBounds.Location; + Size proposedSize = new(valBounds.Width, valBounds.Height); + + var r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); + e.Graphics.SetClip(e.CellBounds); + + foreach (var matchEntry in matchList) + { + var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? BoldFont : NormalFont; + + Brush bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty + ? new SolidBrush(matchEntry.HighlightEntry.BackgroundColor) + : null; + + var matchWord = column.DisplayValue.Substring(matchEntry.StartPos, matchEntry.Length); + var wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); + wordSize.Height = e.CellBounds.Height; + Rectangle wordRect = new(wordPos, wordSize); + + var foreColor = matchEntry.HighlightEntry.ForegroundColor; + if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) + { + if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) + { + e.Graphics.FillRectangle(bgBrush, wordRect); + } + } + + TextRenderer.DrawText(e.Graphics, matchWord, font, wordRect, foreColor, flags); + + wordPos.Offset(wordSize.Width, 0); + bgBrush?.Dispose(); + } + } + + /// + /// Builds a list of HilightMatchEntry objects. A HilightMatchEntry spans over a region that is painted with the same foreground and + /// background colors. + /// All regions which don't match a word-mode entry will be painted with the colors of a default entry (groundEntry). This is either the + /// first matching non-word-mode highlight entry or a black-on-white default (if no matching entry was found). + /// + /// List of all highlight matches for the current cell + /// The entry that is used as the default. + /// List of HighlightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. + private IList MergeHighlightMatchEntries (IList matchList, HighlightMatchEntry groundEntry) + { + // Fill an area with lenth of whole text with a default hilight entry + var entryArray = new HighlightEntry[groundEntry.Length]; + for (var i = 0; i < entryArray.Length; ++i) + { + entryArray[i] = groundEntry.HighlightEntry; + } + + // "overpaint" with all matching word match enries + // Non-word-mode matches will not overpaint because they use the groundEntry + foreach (var me in matchList) + { + var endPos = me.StartPos + me.Length; + for (var i = me.StartPos; i < endPos; ++i) + { + if (me.HighlightEntry.IsWordMatch) + { + entryArray[i] = me.HighlightEntry; + } + else + { + //entryArray[i].ForegroundColor = me.HilightEntry.ForegroundColor; + } + } + } + + // collect areas with same hilight entry and build new highlight match entries for it + IList mergedList = []; + + if (entryArray.Length > 0) + { + var currentEntry = entryArray[0]; + var lastStartPos = 0; + var pos = 0; + + for (; pos < entryArray.Length; ++pos) + { + if (entryArray[pos] != currentEntry) + { + HighlightMatchEntry me = new() + { + StartPos = lastStartPos, + Length = pos - lastStartPos, + HighlightEntry = currentEntry + }; + + mergedList.Add(me); + currentEntry = entryArray[pos]; + lastStartPos = pos; + } + } + + HighlightMatchEntry me2 = new() + { + StartPos = lastStartPos, + Length = pos - lastStartPos, + HighlightEntry = currentEntry + }; + + mergedList.Add(me2); + } + + return mergedList; + } + + /// + /// Returns the first HilightEntry that matches the given line + /// + private HighlightEntry FindHilightEntry (ITextValue line) + { + return FindHighlightEntry(line, false); + } + + private HighlightEntry FindFirstNoWordMatchHilightEntry (ITextValue line) + { + return FindHighlightEntry(line, true); + } + + private bool CheckHighlightEntryMatch (HighlightEntry entry, ITextValue column) + { + if (entry.IsRegEx) + { + //Regex rex = new Regex(entry.SearchText, entry.IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + if (entry.Regex.IsMatch(column.Text)) + { + return true; + } + } + else + { + if (entry.IsCaseSensitive) + { + if (column.Text.Contains(entry.SearchText, StringComparison.Ordinal)) + { + return true; + } + } + else + { + if (column.Text.ToUpperInvariant().Contains(entry.SearchText.ToUpperInvariant(), StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + return false; + } + + /// + /// Returns all HilightEntry entries which matches the given line + /// + private IList FindMatchingHilightEntries (ITextValue line) + { + IList resultList = []; + if (line != null) + { + lock (_currentHighlightGroupLock) + { + foreach (var entry in _currentHighlightGroup.HighlightEntryList) + { + if (CheckHighlightEntryMatch(entry, line)) + { + resultList.Add(entry); + } + } + } + } + + return resultList; + } + + private void GetHighlightEntryMatches (ITextValue line, IList hilightEntryList, IList resultList) + { + foreach (var entry in hilightEntryList) + { + if (entry.IsWordMatch) + { + var matches = entry.Regex.Matches(line.Text); + foreach (Match match in matches) + { + HighlightMatchEntry me = new() + { + HighlightEntry = entry, + StartPos = match.Index, + Length = match.Length + }; + + resultList.Add(me); + } + } + else + { + if (CheckHighlightEntryMatch(entry, line)) + { + HighlightMatchEntry me = new() + { + HighlightEntry = entry, + StartPos = 0, + Length = line.Text.Length + }; + + resultList.Add(me); + } + } + } + } + + private void GetHilightActions (IList matchingList, out bool noLed, out bool stopTail, out bool setBookmark, out string bookmarkComment) + { + noLed = stopTail = setBookmark = false; + bookmarkComment = string.Empty; + + foreach (var entry in matchingList) + { + if (entry.IsLedSwitch) + { + noLed = true; + } + + if (entry.IsSetBookmark) + { + setBookmark = true; + if (!string.IsNullOrEmpty(entry.BookmarkComment)) + { + bookmarkComment += entry.BookmarkComment + "\r\n"; + } + } + + if (entry.IsStopTail) + { + stopTail = true; + } + } + + bookmarkComment = bookmarkComment.TrimEnd(['\r', '\n']); + } + + private void StopTimespreadThread () + { + _timeSpreadCalc.Stop(); + } + + private void StopTimestampSyncThread () + { + _shouldTimestampDisplaySyncingCancel = true; + //_timeShiftSyncWakeupEvent.Set(); + //_timeShiftSyncThread.Abort(); + //_timeShiftSyncThread.Join(); + cts.Cancel(); + } + + [SupportedOSPlatform("windows")] + private void SyncTimestampDisplay () + { + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + if (dataGridView.CurrentRow != null) + { + SyncTimestampDisplay(dataGridView.CurrentRow.Index); + } + } + } + + [SupportedOSPlatform("windows")] + private void SyncTimestampDisplay (int lineNum) + { + _timeShiftSyncLine = lineNum; + _timeShiftSyncTimerEvent.Set(); + _timeShiftSyncWakeupEvent.Set(); + } + + [SupportedOSPlatform("windows")] + private void SyncTimestampDisplayWorker () + { + const int WAIT_TIME = 500; + Thread.CurrentThread.Name = "SyncTimestampDisplayWorker"; + _shouldTimestampDisplaySyncingCancel = false; + _isTimestampDisplaySyncing = true; + + while (!_shouldTimestampDisplaySyncingCancel) + { + _timeShiftSyncWakeupEvent.WaitOne(); + if (_shouldTimestampDisplaySyncingCancel) + { + return; + } + + _timeShiftSyncWakeupEvent.Reset(); + + while (!_shouldTimestampDisplaySyncingCancel) + { + var signaled = _timeShiftSyncTimerEvent.WaitOne(WAIT_TIME, true); + _timeShiftSyncTimerEvent.Reset(); + if (!signaled) + { + break; + } + } + + // timeout with no new Trigger -> update display + var lineNum = _timeShiftSyncLine; + if (lineNum >= 0 && lineNum < dataGridView.RowCount) + { + var refLine = lineNum; + var timeStamp = GetTimestampForLine(ref refLine, true); + if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) + { + _guiStateArgs.Timestamp = timeStamp; + SendGuiStateUpdate(); + if (_shouldCallTimeSync) + { + refLine = lineNum; + var exactTimeStamp = GetTimestampForLine(ref refLine, false); + SyncOtherWindows(exactTimeStamp); + _shouldCallTimeSync = false; + } + } + } + + // show time difference between 2 selected lines + if (dataGridView.SelectedRows.Count == 2) + { + var row1 = dataGridView.SelectedRows[0].Index; + var row2 = dataGridView.SelectedRows[1].Index; + if (row1 > row2) + { + (row2, row1) = (row1, row2); + } + + var refLine = row1; + var timeStamp1 = GetTimestampForLine(ref refLine, false); + refLine = row2; + var timeStamp2 = GetTimestampForLine(ref refLine, false); + //TimeSpan span = TimeSpan.FromTicks(timeStamp2.Ticks - timeStamp1.Ticks); + DateTime diff; + if (timeStamp1.Ticks > timeStamp2.Ticks) + { + diff = new DateTime(timeStamp1.Ticks - timeStamp2.Ticks); + } + else + { + diff = new DateTime(timeStamp2.Ticks - timeStamp1.Ticks); + } + + StatusLineText("Time diff is " + diff.ToString("HH:mm:ss.fff")); + } + else + { + if (!IsMultiFile && dataGridView.SelectedRows.Count == 1) + { + StatusLineText(string.Empty); + } + } + } + } + + [SupportedOSPlatform("windows")] + private void SyncFilterGridPos () + { + try + { + if (_filterResultList.Count > 0) + { + var index = _filterResultList.BinarySearch(dataGridView.CurrentRow.Index); + if (index < 0) + { + index = ~index; + if (index > 0) + { + --index; + } + } + + if (filterGridView.Rows.GetRowCount(DataGridViewElementStates.None) > 0) // exception no rows + { + filterGridView.CurrentCell = filterGridView.Rows[index].Cells[0]; + } + else + { + filterGridView.CurrentCell = null; + } + } + } + catch (Exception e) + { + _logger.Error(e, "SyncFilterGridPos(): "); + } + } + + private void StatusLineFileSize (long size) + { + _statusEventArgs.FileSize = size; + SendStatusLineUpdate(); + } + + [SupportedOSPlatform("windows")] + private int Search (SearchParams searchParams) + { + if (searchParams.SearchText == null) + { + return -1; + } + + var lineNum = searchParams.IsFromTop && !searchParams.IsFindNext + ? 0 + : searchParams.CurrentLine; + + var lowerSearchText = searchParams.SearchText.ToLowerInvariant(); + var count = 0; + var hasWrapped = false; + + while (true) + { + if ((searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed) + { + if (lineNum >= _logFileReader.LineCount) + { + if (hasWrapped) + { + StatusLineError("Not found: " + searchParams.SearchText); + return -1; + } + + lineNum = 0; + count = 0; + hasWrapped = true; + StatusLineError("Started from beginning of file"); + } + } + else + { + if (lineNum < 0) + { + if (hasWrapped) + { + StatusLineError("Not found: " + searchParams.SearchText); + return -1; + } + + count = 0; + lineNum = _logFileReader.LineCount - 1; + hasWrapped = true; + StatusLineError("Started from end of file"); + } + } + + var line = _logFileReader.GetLogLine(lineNum); + if (line == null) + { + return -1; + } + + if (searchParams.IsRegex) + { + Regex rex = new(searchParams.SearchText, searchParams.IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + if (rex.IsMatch(line.FullLine)) + { + return lineNum; + } + } + else + { + if (searchParams.IsCaseSensitive) + { + if (line.FullLine.Contains(searchParams.SearchText, StringComparison.Ordinal)) + { + return lineNum; + } + } + else + { + if (line.FullLine.Contains(lowerSearchText, StringComparison.OrdinalIgnoreCase)) + { + return lineNum; + } + } + } + + if ((searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed) + { + lineNum++; + } + else + { + lineNum--; + } + + if (_shouldCancel) + { + return -1; + } + + if (++count % PROGRESS_BAR_MODULO == 0) + { + try + { + if (!Disposing) + { + Invoke(UpdateProgressBar, [count]); + } + } + catch (ObjectDisposedException ex) // can occur when closing the app while searching + { + _logger.Warn(ex); + } + } + } + } + + private void ResetProgressBar () + { + _progressEventArgs.Value = _progressEventArgs.MaxValue; + _progressEventArgs.Visible = false; + SendProgressBarUpdate(); + } + + [SupportedOSPlatform("windows")] + private void SelectLine (int line, bool triggerSyncCall, bool shouldScroll) + { + try + { + _shouldCallTimeSync = triggerSyncCall; + var wasCancelled = _shouldCancel; + _shouldCancel = false; + _isSearching = false; + StatusLineText(string.Empty); + _guiStateArgs.MenuEnabled = true; + + if (wasCancelled) + { + return; + } + + if (line == -1) + { + // Hmm... is that experimental code from early days? + MessageBox.Show(this, "Not found:", "Search result"); + return; + } + + // Prevent ArgumentOutOfRangeException + if (line >= dataGridView.Rows.GetRowCount(DataGridViewElementStates.None)) + { + line = dataGridView.Rows.GetRowCount(DataGridViewElementStates.None) - 1; + } + + dataGridView.Rows[line].Selected = true; + + if (shouldScroll) + { + dataGridView.CurrentCell = dataGridView.Rows[line].Cells[0]; + dataGridView.Focus(); + } + } + catch (ArgumentOutOfRangeException e) + { + _logger.Error(e, "Error while selecting line: "); + } + catch (IndexOutOfRangeException e) + { + // Occures sometimes (but cannot reproduce) + _logger.Error(e, "Error while selecting line: "); + } + } + + [SupportedOSPlatform("windows")] + private void StartEditMode () + { + if (!dataGridView.CurrentCell.ReadOnly) + { + dataGridView.BeginEdit(false); + if (dataGridView.EditingControl != null) + { + if (dataGridView.EditingControl is LogCellEditingControl editControl) + { + editControl.KeyDown += OnEditControlKeyDown; + editControl.KeyPress += OnEditControlKeyPress; + editControl.KeyUp += OnEditControlKeyUp; + editControl.Click += OnEditControlClick; + dataGridView.CellEndEdit += OnDataGridViewCellEndEdit; + editControl.SelectionStart = 0; + } + else + { + _logger.Warn(CultureInfo.InvariantCulture, "Edit control in logWindow was null"); + } + } + } + } + + [SupportedOSPlatform("windows")] + private void UpdateEditColumnDisplay (DataGridViewTextBoxEditingControl editControl) + { + // prevents key events after edit mode has ended + if (dataGridView.EditingControl != null) + { + var pos = editControl.SelectionStart + editControl.SelectionLength; + StatusLineText(" " + pos); + _logger.Debug(CultureInfo.InvariantCulture, "SelStart: {0}, SelLen: {1}", editControl.SelectionStart, editControl.SelectionLength); + } + } + + [SupportedOSPlatform("windows")] + private void SelectPrevHighlightLine () + { + var lineNum = dataGridView.CurrentCellAddress.Y; + while (lineNum > 0) + { + lineNum--; + var line = _logFileReader.GetLogLine(lineNum); + if (line != null) + { + var entry = FindHilightEntry(line); + if (entry != null) + { + SelectLine(lineNum, false, true); + break; + } + } + } + } + + [SupportedOSPlatform("windows")] + private void SelectNextHighlightLine () + { + var lineNum = dataGridView.CurrentCellAddress.Y; + while (lineNum < _logFileReader.LineCount) + { + lineNum++; + var line = _logFileReader.GetLogLine(lineNum); + if (line != null) + { + var entry = FindHilightEntry(line); + if (entry != null) + { + SelectLine(lineNum, false, true); + break; + } + } + } + } + + [SupportedOSPlatform("windows")] + private int FindNextBookmarkIndex (int lineNum) + { + if (lineNum >= dataGridView.RowCount) + { + lineNum = 0; + } + else + { + lineNum++; + } + + return _bookmarkProvider.FindNextBookmarkIndex(lineNum); + } + + [SupportedOSPlatform("windows")] + private int FindPrevBookmarkIndex (int lineNum) + { + if (lineNum <= 0) + { + lineNum = dataGridView.RowCount - 1; + } + else + { + lineNum--; + } + + return _bookmarkProvider.FindPrevBookmarkIndex(lineNum); + } + + /** + * Shift bookmarks after a logfile rollover + */ + + private void ShiftBookmarks (int offset) + { + _bookmarkProvider.ShiftBookmarks(offset); + OnBookmarkRemoved(); + } + + private void ShiftRowHeightList (int offset) + { + SortedList newList = []; + foreach (var entry in _rowHeightList.Values) + { + var line = entry.LineNum - offset; + if (line >= 0) + { + entry.LineNum = line; + newList.Add(line, entry); + } + } + + _rowHeightList = newList; + } + + private void ShiftFilterPipes (int offset) + { + lock (_filterPipeList) + { + foreach (var pipe in _filterPipeList) + { + pipe.ShiftLineNums(offset); + } + } + } + + [SupportedOSPlatform("windows")] + private void LoadFilterPipes () + { + lock (_filterPipeList) + { + foreach (var pipe in _filterPipeList) + { + pipe.RecreateTempFile(); + } + } + + if (_filterPipeList.Count > 0) + { + for (var i = 0; i < dataGridView.RowCount; ++i) + { + ProcessFilterPipes(i); + } + } + } + + private void DisconnectFilterPipes () + { + lock (_filterPipeList) + { + foreach (var pipe in _filterPipeList) + { + pipe.ClearLineList(); + } + } + } + + [SupportedOSPlatform("windows")] + private void ApplyFilterParams () + { + filterComboBox.Text = _filterParams.SearchText; + filterCaseSensitiveCheckBox.Checked = _filterParams.IsCaseSensitive; + filterRegexCheckBox.Checked = _filterParams.IsRegex; + filterTailCheckBox.Checked = _filterParams.IsFilterTail; + invertFilterCheckBox.Checked = _filterParams.IsInvert; + filterKnobBackSpread.Value = _filterParams.SpreadBefore; + filterKnobForeSpread.Value = _filterParams.SpreadBehind; + rangeCheckBox.Checked = _filterParams.IsRangeSearch; + columnRestrictCheckBox.Checked = _filterParams.ColumnRestrict; + fuzzyKnobControl.Value = _filterParams.FuzzyValue; + filterRangeComboBox.Text = _filterParams.RangeSearchText; + } + + [SupportedOSPlatform("windows")] + private void ResetFilterControls () + { + filterComboBox.Text = ""; + filterCaseSensitiveCheckBox.Checked = false; + filterRegexCheckBox.Checked = false; + //this.filterTailCheckBox.Checked = this.Preferences.filterTail; + invertFilterCheckBox.Checked = false; + filterKnobBackSpread.Value = 0; + filterKnobForeSpread.Value = 0; + rangeCheckBox.Checked = false; + columnRestrictCheckBox.Checked = false; + fuzzyKnobControl.Value = 0; + filterRangeComboBox.Text = ""; + } + + [SupportedOSPlatform("windows")] + private void FilterSearch () + { + if (filterComboBox.Text.Length == 0) + { + _filterParams.SearchText = string.Empty; + _filterParams.LowerSearchText = string.Empty; + _filterParams.IsRangeSearch = false; + ClearFilterList(); + filterSearchButton.Image = null; + ResetFilterControls(); + saveFilterButton.Enabled = false; + return; + } + + FilterSearch(filterComboBox.Text); + } + + [SupportedOSPlatform("windows")] + private async void FilterSearch (string text) + { + FireCancelHandlers(); // make sure that there's no other filter running (maybe from filter restore) + + _filterParams.SearchText = text; + _filterParams.LowerSearchText = text.ToLowerInvariant(); + ConfigManager.Settings.FilterHistoryList.Remove(text); + ConfigManager.Settings.FilterHistoryList.Insert(0, text); + var maxHistory = ConfigManager.Settings.Preferences.MaximumFilterEntries; + + if (ConfigManager.Settings.FilterHistoryList.Count > maxHistory) + { + ConfigManager.Settings.FilterHistoryList.RemoveAt(filterComboBox.Items.Count - 1); + } + + filterComboBox.Items.Clear(); + foreach (var item in ConfigManager.Settings.FilterHistoryList) + { + filterComboBox.Items.Add(item); + } + + filterComboBox.Text = text; + + _filterParams.IsRangeSearch = rangeCheckBox.Checked; + _filterParams.RangeSearchText = filterRangeComboBox.Text; + if (_filterParams.IsRangeSearch) + { + ConfigManager.Settings.FilterRangeHistoryList.Remove(filterRangeComboBox.Text); + ConfigManager.Settings.FilterRangeHistoryList.Insert(0, filterRangeComboBox.Text); + if (ConfigManager.Settings.FilterRangeHistoryList.Count > maxHistory) + { + ConfigManager.Settings.FilterRangeHistoryList.RemoveAt(filterRangeComboBox.Items.Count - 1); + } + + filterRangeComboBox.Items.Clear(); + foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) + { + filterRangeComboBox.Items.Add(item); + } + } + + ConfigManager.Save(SettingsFlags.FilterHistory); + + _filterParams.IsCaseSensitive = filterCaseSensitiveCheckBox.Checked; + _filterParams.IsRegex = filterRegexCheckBox.Checked; + _filterParams.IsFilterTail = filterTailCheckBox.Checked; + _filterParams.IsInvert = invertFilterCheckBox.Checked; + if (_filterParams.IsRegex) + { + try + { + _filterParams.CreateRegex(); + } + catch (ArgumentException) + { + StatusLineError("Invalid regular expression"); + return; + } + } + + _filterParams.FuzzyValue = fuzzyKnobControl.Value; + _filterParams.SpreadBefore = filterKnobBackSpread.Value; + _filterParams.SpreadBehind = filterKnobForeSpread.Value; + _filterParams.ColumnRestrict = columnRestrictCheckBox.Checked; + + //ConfigManager.SaveFilterParams(this.filterParams); + ConfigManager.Settings.FilterParams = _filterParams; // wozu eigentlich? sinnlos seit MDI? + + _shouldCancel = false; + _isSearching = true; + StatusLineText("Filtering... Press ESC to cancel"); + filterSearchButton.Enabled = false; + ClearFilterList(); + + _progressEventArgs.MinValue = 0; + _progressEventArgs.MaxValue = dataGridView.RowCount; + _progressEventArgs.Value = 0; + _progressEventArgs.Visible = true; + SendProgressBarUpdate(); + + var settings = ConfigManager.Settings; + + //FilterFx fx = settings.preferences.multiThreadFilter ? MultiThreadedFilter : new FilterFx(Filter); + FilterFxAction = settings.Preferences.MultiThreadFilter ? MultiThreadedFilter : Filter; + + //Task.Run(() => fx.Invoke(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList)); + var filterFxActionTask = Task.Run(() => Filter(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList)); + + await filterFxActionTask; + FilterComplete(); + + //fx.BeginInvoke(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList, FilterComplete, null); + CheckForFilterDirty(); + } + + private void MultiThreadedFilter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) + { + ColumnizerCallback callback = new(this); + + FilterStarter fs = new(callback, Environment.ProcessorCount + 2) + { + FilterHitList = _filterHitList, + FilterResultLines = _filterResultList, + LastFilterLinesList = _lastFilterLinesList + }; + + var cancelHandler = new FilterCancelHandler(fs); + OnRegisterCancelHandler(cancelHandler); + long startTime = Environment.TickCount; + + fs.DoFilter(filterParams, 0, _logFileReader.LineCount, FilterProgressCallback); + + long endTime = Environment.TickCount; + + _logger.Debug($"Multi threaded filter duration: {endTime - startTime} ms."); + + OnDeRegisterCancelHandler(cancelHandler); + StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); + } + + private void FilterProgressCallback (int lineCount) + { + UpdateProgressBar(lineCount); + } + + [SupportedOSPlatform("windows")] + private void Filter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) + { + long startTime = Environment.TickCount; + try + { + filterParams.Reset(); + var lineNum = 0; + //AddFilterLineFx addFx = new AddFilterLineFx(AddFilterLine); + ColumnizerCallback callback = new(this); + while (true) + { + var line = _logFileReader.GetLogLine(lineNum); + if (line == null) + { + break; + } + + callback.LineNum = lineNum; + if (Util.TestFilterCondition(filterParams, line, callback)) + { + AddFilterLine(lineNum, false, filterParams, filterResultLines, lastFilterLinesList, + filterHitList); + } + + lineNum++; + if (lineNum % PROGRESS_BAR_MODULO == 0) + { + UpdateProgressBar(lineNum); + } + + if (_shouldCancel) + { + break; + } + } + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while filtering. Please report to developer: "); + MessageBox.Show(null, $"Exception while filtering. Please report to developer: \n\n{ex}\n\n{ex.StackTrace}", "LogExpert"); + } + + long endTime = Environment.TickCount; + + _logger.Info($"Single threaded filter duration: {endTime - startTime} ms."); + + StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); + } + + /// + /// Returns a list with 'additional filter results'. This is the given line number + /// and (if back spread and/or fore spread is enabled) some additional lines. + /// This function doesn't check the filter condition! + /// + /// + /// + /// + /// + private IList GetAdditionalFilterResults (FilterParams filterParams, int lineNum, IList checkList) + { + IList resultList = []; + //string textLine = this.logFileReader.GetLogLine(lineNum); + //ColumnizerCallback callback = new ColumnizerCallback(this); + //callback.LineNum = lineNum; + + if (filterParams.SpreadBefore == 0 && filterParams.SpreadBehind == 0) + { + resultList.Add(lineNum); + return resultList; + } + + // back spread + for (var i = filterParams.SpreadBefore; i > 0; --i) + { + if (lineNum - i > 0) + { + if (!resultList.Contains(lineNum - i) && !checkList.Contains(lineNum - i)) + { + resultList.Add(lineNum - i); + } + } + } + + // direct filter hit + if (!resultList.Contains(lineNum) && !checkList.Contains(lineNum)) + { + resultList.Add(lineNum); + } + + // after spread + for (var i = 1; i <= filterParams.SpreadBehind; ++i) + { + if (lineNum + i < _logFileReader.LineCount) + { + if (!resultList.Contains(lineNum + i) && !checkList.Contains(lineNum + i)) + { + resultList.Add(lineNum + i); + } + } + } + + return resultList; + } + + [SupportedOSPlatform("windows")] + private void AddFilterLine (int lineNum, bool immediate, FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) + { + int count; + lock (_filterResultList) + { + filterHitList.Add(lineNum); + var filterResult = GetAdditionalFilterResults(filterParams, lineNum, lastFilterLinesList); + filterResultLines.AddRange(filterResult); + count = filterResultLines.Count; + lastFilterLinesList.AddRange(filterResult); + if (lastFilterLinesList.Count > SPREAD_MAX * 2) + { + lastFilterLinesList.RemoveRange(0, lastFilterLinesList.Count - SPREAD_MAX * 2); + } + } + + if (immediate) + { + TriggerFilterLineGuiUpdate(); + } + else if (lineNum % PROGRESS_BAR_MODULO == 0) + { + //FunctionWith1IntParam fx = new FunctionWith1IntParam(UpdateFilterCountLabel); + //this.Invoke(fx, new object[] { count}); + } + } + + [SupportedOSPlatform("windows")] + private void TriggerFilterLineGuiUpdate () + { + //lock (this.filterUpdateThread) + //{ + // this.filterEventCount++; + // this.filterUpdateEvent.Set(); + //} + Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); + } + + //private void FilterUpdateWorker() + //{ + // Thread.CurrentThread.Name = "FilterUpdateWorker"; + // while (true) + // { + // this.filterUpdateEvent.WaitOne(); + // lock (this.filterUpdateThread) + // { + // this.Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); + // this.filterUpdateEvent.Reset(); + // } + + // //_logger.logDebug("FilterUpdateWorker: Waiting for signal"); + // //bool signaled = this.filterUpdateEvent.WaitOne(1000, false); + + // //if (!signaled) + // //{ + // // lock (this.filterUpdateThread) + // // { + // // if (this.filterEventCount > 0) + // // { + // // this.filterEventCount = 0; + // // _logger.logDebug("FilterUpdateWorker: Invoking GUI update because of wait timeout"); + // // this.Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); + // // } + // // } + // //} + // //else + // //{ + // // _logger.logDebug("FilterUpdateWorker: Wakeup signal received."); + // // lock (this.filterUpdateThread) + // // { + // // _logger.logDebug("FilterUpdateWorker: event count: " + this.filterEventCount); + // // if (this.filterEventCount > 100) + // // { + // // this.filterEventCount = 0; + // // _logger.logDebug("FilterUpdateWorker: Invoking GUI update because of event count"); + // // this.Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); + // // } + // // this.filterUpdateEvent.Reset(); + // // } + // //} + // } + //} + + //private void StopFilterUpdateWorkerThread() + //{ + // this.filterUpdateEvent.Set(); + // this.filterUpdateThread.Abort(); + // this.filterUpdateThread.Join(); + //} + + [SupportedOSPlatform("windows")] + private void AddFilterLineGuiUpdate () + { + try + { + lock (_filterResultList) + { + lblFilterCount.Text = "" + _filterResultList.Count; + if (filterGridView.RowCount > _filterResultList.Count) + { + filterGridView.RowCount = 0; // helps to prevent hang ? + } + + filterGridView.RowCount = _filterResultList.Count; + if (filterGridView.RowCount > 0) + { + filterGridView.FirstDisplayedScrollingRowIndex = filterGridView.RowCount - 1; + } + + if (filterGridView.RowCount == 1) + { + // after a file reload adjusted column sizes anew when the first line arrives + //this.filterGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + AutoResizeColumns(filterGridView); + } + } + } + catch (Exception e) + { + _logger.Error(e, "AddFilterLineGuiUpdate(): "); + } + } + + private void UpdateProgressBar (int value) + { + _progressEventArgs.Value = value; + if (value > _progressEventArgs.MaxValue) + { + // can occur if new lines will be added while filtering + _progressEventArgs.MaxValue = value; + } + + SendProgressBarUpdate(); + } + + [SupportedOSPlatform("windows")] + private void FilterComplete () + { + if (!IsDisposed && !_waitingForClose && !Disposing) + { + Invoke(new MethodInvoker(ResetStatusAfterFilter)); + } + } + + [SupportedOSPlatform("windows")] + private void FilterComplete (IAsyncResult result) + { + if (!IsDisposed && !_waitingForClose && !Disposing) + { + Invoke(new MethodInvoker(ResetStatusAfterFilter)); + } + } + + [SupportedOSPlatform("windows")] + private void ResetStatusAfterFilter () + { + try + { + //StatusLineText(""); + _isSearching = false; + _progressEventArgs.Value = _progressEventArgs.MaxValue; + _progressEventArgs.Visible = false; + SendProgressBarUpdate(); + filterGridView.RowCount = _filterResultList.Count; + //this.filterGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + AutoResizeColumns(filterGridView); + lblFilterCount.Text = "" + _filterResultList.Count; + if (filterGridView.RowCount > 0) + { + filterGridView.Focus(); + } + + filterSearchButton.Enabled = true; + } + catch (NullReferenceException e) + { + // See https://connect.microsoft.com/VisualStudio/feedback/details/366943/autoresizecolumns-in-datagridview-throws-nullreferenceexception + // There are some rare situations with null ref exceptions when resizing columns and on filter finished + // So catch them here. Better than crashing. + _logger.Error(e, "Error: "); + } + } + + [SupportedOSPlatform("windows")] + private void ClearFilterList () + { + try + { + //this.shouldCancel = true; + lock (_filterResultList) + { + filterGridView.SuspendLayout(); + filterGridView.RowCount = 0; + lblFilterCount.Text = "0"; + _filterResultList = []; + _lastFilterLinesList = []; + _filterHitList = []; + //this.filterGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + filterGridView.ResumeLayout(); + } + } + catch (Exception ex) + { + _logger.Error(ex, "Wieder dieser sporadische Fehler: "); + + MessageBox.Show(null, ex.StackTrace, "Wieder dieser sporadische Fehler:"); + } + } + + private void ClearBookmarkList () + { + _bookmarkProvider.ClearAllBookmarks(); + } + + /** + * Shift filter list line entries after a logfile rollover + */ + [SupportedOSPlatform("windows")] + private void ShiftFilterLines (int offset) + { + List newFilterList = []; + lock (_filterResultList) + { + foreach (var lineNum in _filterResultList) + { + var line = lineNum - offset; + if (line >= 0) + { + newFilterList.Add(line); + } + } + + _filterResultList = newFilterList; + } + + newFilterList = []; + foreach (var lineNum in _filterHitList) + { + var line = lineNum - offset; + if (line >= 0) + { + newFilterList.Add(line); + } + } + + _filterHitList = newFilterList; + + var count = SPREAD_MAX; + if (_filterResultList.Count < SPREAD_MAX) + { + count = _filterResultList.Count; + } + + _lastFilterLinesList = _filterResultList.GetRange(_filterResultList.Count - count, count); + + //this.filterGridView.RowCount = this.filterResultList.Count; + //this.filterCountLabel.Text = "" + this.filterResultList.Count; + //this.BeginInvoke(new MethodInvoker(this.filterGridView.Refresh)); + //this.BeginInvoke(new MethodInvoker(AddFilterLineGuiUpdate)); + TriggerFilterLineGuiUpdate(); + } + + [SupportedOSPlatform("windows")] + private void CheckForFilterDirty () + { + if (IsFilterSearchDirty(_filterParams)) + { + filterSearchButton.Image = _searchButtonImage; + saveFilterButton.Enabled = false; + } + else + { + filterSearchButton.Image = null; + saveFilterButton.Enabled = true; + } + } + + [SupportedOSPlatform("windows")] + private bool IsFilterSearchDirty (FilterParams filterParams) + { + if (!filterParams.SearchText.Equals(filterComboBox.Text, StringComparison.Ordinal)) + { + return true; + } + + if (filterParams.IsRangeSearch != rangeCheckBox.Checked) + { + return true; + } + + if (filterParams.IsRangeSearch && !filterParams.RangeSearchText.Equals(filterRangeComboBox.Text, StringComparison.Ordinal)) + { + return true; + } + + if (filterParams.IsRegex != filterRegexCheckBox.Checked) + { + return true; + } + + if (filterParams.IsInvert != invertFilterCheckBox.Checked) + { + return true; + } + + if (filterParams.SpreadBefore != filterKnobBackSpread.Value) + { + return true; + } + + if (filterParams.SpreadBehind != filterKnobForeSpread.Value) + { + return true; + } + + if (filterParams.FuzzyValue != fuzzyKnobControl.Value) + { + return true; + } + + if (filterParams.ColumnRestrict != columnRestrictCheckBox.Checked) + { + return true; + } + + if (filterParams.IsCaseSensitive != filterCaseSensitiveCheckBox.Checked) + { + return true; + } + + return false; + } + + [SupportedOSPlatform("windows")] + private void AdjustMinimumGridWith () + { + if (dataGridView.Columns.Count > 1) + { + //this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + AutoResizeColumns(dataGridView); + + var width = dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible); + var diff = dataGridView.Width - width; + if (diff > 0) + { + diff -= dataGridView.RowHeadersWidth / 2; + dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].Width += diff; + filterGridView.Columns[filterGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].Width += diff; + } + } + } + + [SupportedOSPlatform("windows")] + private void InvalidateCurrentRow (BufferedDataGridView gridView) + { + if (gridView.CurrentCellAddress.Y > -1) + { + gridView.InvalidateRow(gridView.CurrentCellAddress.Y); + } + } + + private void InvalidateCurrentRow () + { + InvalidateCurrentRow(dataGridView); + InvalidateCurrentRow(filterGridView); + } + + [SupportedOSPlatform("windows")] + private void DisplayCurrentFileOnStatusline () + { + if (_logFileReader.IsMultiFile) + { + try + { + if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index > -1) + { + var fileName = _logFileReader.GetLogFileNameForLine(dataGridView.CurrentRow.Index); + if (fileName != null) + { + StatusLineText(Util.GetNameFromPath(fileName)); + } + } + } + catch (Exception) + { + // TODO: handle this concurrent situation better: + // this.dataGridView.CurrentRow may be null even if checked before. + // This can happen when MultiFile shift deselects the current row because there + // are less lines after rollover than before. + // access to dataGridView-Rows should be locked + } + } + } + + private void UpdateSelectionDisplay () + { + if (_noSelectionUpdates) + { + return; + } + } + + [SupportedOSPlatform("windows")] + private void UpdateFilterHistoryFromSettings () + { + ConfigManager.Settings.FilterHistoryList = ConfigManager.Settings.FilterHistoryList; + filterComboBox.Items.Clear(); + foreach (var item in ConfigManager.Settings.FilterHistoryList) + { + filterComboBox.Items.Add(item); + } + + filterRangeComboBox.Items.Clear(); + foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) + { + filterRangeComboBox.Items.Add(item); + } + } + + private void StatusLineText (string text) + { + _statusEventArgs.StatusText = text; + SendStatusLineUpdate(); + } + + private void StatusLineError (string text) + { + StatusLineText(text); + _isErrorShowing = true; + } + + private void RemoveStatusLineError () + { + StatusLineText(""); + _isErrorShowing = false; + } + + private void SendGuiStateUpdate () + { + OnGuiState(_guiStateArgs); + } + + private void SendProgressBarUpdate () + { + OnProgressBarUpdate(_progressEventArgs); + } + + private void SendStatusLineUpdate () + { + OnStatusLine(_statusEventArgs); + } + + [SupportedOSPlatform("windows")] + private void ShowAdvancedFilterPanel (bool show) + { + if (show) + { + advancedButton.Text = "Hide advanced..."; + advancedButton.Image = null; + } + else + { + advancedButton.Text = "Show advanced..."; + CheckForAdvancedButtonDirty(); + } + + advancedFilterSplitContainer.Panel1Collapsed = !show; + advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; + _showAdvanced = show; + } + + [SupportedOSPlatform("windows")] + private void CheckForAdvancedButtonDirty () + { + advancedButton.Image = IsAdvancedOptionActive() && !_showAdvanced + ? _advancedButtonImage + : null; + } + + [SupportedOSPlatform("windows")] + private void FilterToTab () + { + filterSearchButton.Enabled = false; + Task.Run(() => WriteFilterToTab()); + } + + [SupportedOSPlatform("windows")] + private void WriteFilterToTab () + { + FilterPipe pipe = new(_filterParams.Clone(), this); + lock (_filterResultList) + { + var namePrefix = "->F"; + var title = IsTempFile + ? TempTitleName + namePrefix + ++_filterPipeNameCounter + : Util.GetNameFromPath(FileName) + namePrefix + ++_filterPipeNameCounter; + + WritePipeToTab(pipe, _filterResultList, title, null); + } + } + + [SupportedOSPlatform("windows")] + private void WritePipeToTab (FilterPipe pipe, IList lineNumberList, string name, PersistenceData persistenceData) + { + _logger.Info(CultureInfo.InvariantCulture, "WritePipeToTab(): {0} lines.", lineNumberList.Count); + StatusLineText("Writing to temp file... Press ESC to cancel."); + _guiStateArgs.MenuEnabled = false; + SendGuiStateUpdate(); + _progressEventArgs.MinValue = 0; + _progressEventArgs.MaxValue = lineNumberList.Count; + _progressEventArgs.Value = 0; + _progressEventArgs.Visible = true; + Invoke(new MethodInvoker(SendProgressBarUpdate)); + _isSearching = true; + _shouldCancel = false; + + lock (_filterPipeList) + { + _filterPipeList.Add(pipe); + } + + pipe.Closed += OnPipeDisconnected; + var count = 0; + pipe.OpenFile(); + LogExpertCallback callback = new(this); + foreach (var i in lineNumberList) + { + if (_shouldCancel) + { + break; + } + + var line = _logFileReader.GetLogLine(i); + if (CurrentColumnizer is ILogLineXmlColumnizer) + { + callback.LineNum = i; + line = (CurrentColumnizer as ILogLineXmlColumnizer).GetLineTextForClipboard(line, callback); + } + + pipe.WriteToPipe(line, i); + if (++count % PROGRESS_BAR_MODULO == 0) + { + _progressEventArgs.Value = count; + Invoke(new MethodInvoker(SendProgressBarUpdate)); + } + } + + pipe.CloseFile(); + _logger.Info(CultureInfo.InvariantCulture, "WritePipeToTab(): finished"); + Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), pipe, name, persistenceData); + } + + [SupportedOSPlatform("windows")] + private void WriteFilterToTabFinished (FilterPipe pipe, string name, PersistenceData persistenceData) + { + _isSearching = false; + if (!_shouldCancel) + { + var title = name; + ILogLineColumnizer preProcessColumnizer = null; + if (CurrentColumnizer is not ILogLineXmlColumnizer) + { + preProcessColumnizer = CurrentColumnizer; + } + + var newWin = _parentLogTabWin.AddFilterTab(pipe, title, preProcessColumnizer); + newWin.FilterPipe = pipe; + pipe.OwnLogWindow = newWin; + if (persistenceData != null) + { + Task.Run(() => FilterRestore(newWin, persistenceData)); + } + } + + _progressEventArgs.Value = _progressEventArgs.MaxValue; + _progressEventArgs.Visible = false; + SendProgressBarUpdate(); + _guiStateArgs.MenuEnabled = true; + SendGuiStateUpdate(); + StatusLineText(""); + filterSearchButton.Enabled = true; + } + + /// + /// Used to create a new tab and pipe the given content into it. + /// + /// + /// + [SupportedOSPlatform("windows")] + internal void WritePipeTab (IList lineEntryList, string title) + { + FilterPipe pipe = new(new FilterParams(), this) + { + IsStopped = true + }; + pipe.Closed += OnPipeDisconnected; + pipe.OpenFile(); + foreach (var entry in lineEntryList) + { + pipe.WriteToPipe(entry.LogLine, entry.LineNum); + } + + pipe.CloseFile(); + Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), [pipe, title, null]); + } + + [SupportedOSPlatform("windows")] + private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) + { + newWin.WaitForLoadingFinished(); + var columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.ColumnizerName, + PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + if (columnizer != null) + { + SetColumnizerFx fx = newWin.ForceColumnizer; + newWin.Invoke(fx, [columnizer]); + } + else + { + _logger.Warn($"FilterRestore(): Columnizer {persistenceData.ColumnizerName} not found"); + } + + newWin.BeginInvoke(new RestoreFiltersFx(newWin.RestoreFilters), [persistenceData]); + } + + [SupportedOSPlatform("windows")] + private void ProcessFilterPipes (int lineNum) + { + var searchLine = _logFileReader.GetLogLine(lineNum); + if (searchLine == null) + { + return; + } + + ColumnizerCallback callback = new(this) + { + LineNum = lineNum + }; + IList deleteList = []; + lock (_filterPipeList) + { + foreach (var pipe in _filterPipeList) + { + if (pipe.IsStopped) + { + continue; + } + + //long startTime = Environment.TickCount; + if (Util.TestFilterCondition(pipe.FilterParams, searchLine, callback)) + { + var filterResult = + GetAdditionalFilterResults(pipe.FilterParams, lineNum, pipe.LastLinesHistoryList); + pipe.OpenFile(); + foreach (var line in filterResult) + { + pipe.LastLinesHistoryList.Add(line); + if (pipe.LastLinesHistoryList.Count > SPREAD_MAX * 2) + { + pipe.LastLinesHistoryList.RemoveAt(0); + } + + var textLine = _logFileReader.GetLogLine(line); + var fileOk = pipe.WriteToPipe(textLine, line); + if (!fileOk) + { + deleteList.Add(pipe); + } + } + + pipe.CloseFile(); + } + + //long endTime = Environment.TickCount; + //_logger.logDebug("ProcessFilterPipes(" + lineNum + ") duration: " + ((endTime - startTime))); + } + } + + foreach (var pipe in deleteList) + { + _filterPipeList.Remove(pipe); + } + } + + [SupportedOSPlatform("windows")] + private void CopyMarkedLinesToClipboard () + { + if (_guiStateArgs.CellSelectMode) + { + var data = dataGridView.GetClipboardContent(); + Clipboard.SetDataObject(data); + } + else + { + List lineNumList = []; + foreach (DataGridViewRow row in dataGridView.SelectedRows) + { + if (row.Index != -1) + { + lineNumList.Add(row.Index); + } + } + + lineNumList.Sort(); + StringBuilder clipText = new(); + LogExpertCallback callback = new(this); + + var xmlColumnizer = _currentColumnizer as ILogLineXmlColumnizer; + + foreach (var lineNum in lineNumList) + { + var line = _logFileReader.GetLogLine(lineNum); + if (xmlColumnizer != null) + { + callback.LineNum = lineNum; + line = xmlColumnizer.GetLineTextForClipboard(line, callback); + } + + clipText.AppendLine(line.ToClipBoardText()); + } + + Clipboard.SetText(clipText.ToString()); + } + } + + /// + /// Set an Encoding which shall be used when loading a file. Used before a file is loaded. + /// + /// + private void SetExplicitEncoding (Encoding encoding) + { + EncodingOptions.Encoding = encoding; + } + + [SupportedOSPlatform("windows")] + private void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, bool setLastColumnWidth, int lastColumnWidth) + { + if (dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) > 1) + { + if (setLastColumnWidth) + { + dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = lastColumnWidth; + } + else + { + // Workaround for a .NET bug which brings the DataGridView into an unstable state (causing lots of NullReferenceExceptions). + dataGridView.FirstDisplayedScrollingColumnIndex = 0; + + dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = 5; // default + } + } + + if (dataGridView.RowCount > 0) + { + dataGridView.UpdateRowHeightInfo(0, true); + } + + dataGridView.Invalidate(); + dataGridView.Refresh(); + AutoResizeColumns(dataGridView); + } + + [SupportedOSPlatform("windows")] + private IList GetSelectedContent () + { + if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + { + List lineNumList = []; + + foreach (DataGridViewRow row in dataGridView.SelectedRows) + { + if (row.Index != -1) + { + lineNumList.Add(row.Index); + } + } + + lineNumList.Sort(); + return lineNumList; + } + + return []; + } + + /* ======================================================================== + * Timestamp stuff + * =======================================================================*/ + + [SupportedOSPlatform("windows")] + private void SetTimestampLimits () + { + if (!CurrentColumnizer.IsTimeshiftImplemented()) + { + return; + } + + var line = 0; + _guiStateArgs.MinTimestamp = GetTimestampForLineForward(ref line, true); + line = dataGridView.RowCount - 1; + _guiStateArgs.MaxTimestamp = GetTimestampForLine(ref line, true); + SendGuiStateUpdate(); + } + + private void AdjustHighlightSplitterWidth () + { + //int size = this.editHighlightsSplitContainer.Panel2Collapsed ? 600 : 660; + //int distance = this.highlightSplitContainer.Width - size; + //if (distance < 10) + // distance = 10; + //this.highlightSplitContainer.SplitterDistance = distance; + } + + [SupportedOSPlatform("windows")] + private void BookmarkComment (Bookmark bookmark) + { + BookmarkCommentDlg dlg = new() + { + Comment = bookmark.Text + }; + if (dlg.ShowDialog() == DialogResult.OK) + { + bookmark.Text = dlg.Comment; + dataGridView.Refresh(); + OnBookmarkTextChanged(bookmark); + } + } + + /// + /// Indicates which columns we are filtering on + /// + /// + /// + [SupportedOSPlatform("windows")] + private string CalculateColumnNames (FilterParams filter) + { + var names = string.Empty; + + if (filter.ColumnRestrict) + { + foreach (var colIndex in filter.ColumnList) + { + if (colIndex < dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 2) + { + if (names.Length > 0) + { + names += ", "; + } + + names += dataGridView.Columns[2 + colIndex] + .HeaderText; // skip first two columns: marker + line number + } + } + } + + return names; + } + + [SupportedOSPlatform("windows")] + private void ApplyFrozenState (BufferedDataGridView gridView) + { + SortedDictionary dict = []; + foreach (DataGridViewColumn col in gridView.Columns) + { + dict.Add(col.DisplayIndex, col); + } + + foreach (var col in dict.Values) + { + col.Frozen = _freezeStateMap.ContainsKey(gridView) && _freezeStateMap[gridView]; + var sel = col.HeaderCell.Selected; + if (col.Index == _selectedCol) + { + break; + } + } + } + + [SupportedOSPlatform("windows")] + private void ShowTimeSpread (bool show) + { + if (show) + { + tableLayoutPanel1.ColumnStyles[1].Width = 16; + } + else + { + tableLayoutPanel1.ColumnStyles[1].Width = 0; + } + + _timeSpreadCalc.Enabled = show; + } + + [SupportedOSPlatform("windows")] + protected internal void AddTempFileTab (string fileName, string title) + { + _parentLogTabWin.AddTempFileTab(fileName, title); + } + + private void InitPatternWindow () + { + //PatternStatistic(this.patternArgs); + _patternWindow = new PatternWindow(this); + _patternWindow.SetColumnizer(CurrentColumnizer); + //this.patternWindow.SetBlockList(blockList); + _patternWindow.SetFont(Preferences.FontName, Preferences.FontSize); + _patternWindow.Fuzzy = _patternArgs.Fuzzy; + _patternWindow.MaxDiff = _patternArgs.MaxDiffInBlock; + _patternWindow.MaxMisses = _patternArgs.MaxMisses; + _patternWindow.Weight = _patternArgs.MinWeight; + //this.patternWindow.Show(); + } + + [SupportedOSPlatform("windows")] + private void TestStatistic (PatternArgs patternArgs) + { + var beginLine = patternArgs.StartLine; + _logger.Info($"TestStatistics() called with start line {beginLine}"); + + _patternArgs = patternArgs; + + var num = beginLine + 1; //this.dataGridView.RowCount; + + _progressEventArgs.MinValue = 0; + _progressEventArgs.MaxValue = dataGridView.RowCount; + _progressEventArgs.Value = beginLine; + _progressEventArgs.Visible = true; + SendProgressBarUpdate(); + + PrepareDict(); + ResetCache(num); + + Dictionary processedLinesDict = []; + List blockList = []; + var blockId = 0; + _isSearching = true; + _shouldCancel = false; + var searchLine = -1; + for (var i = beginLine; i < num && !_shouldCancel; ++i) + { + if (processedLinesDict.ContainsKey(i)) + { + continue; + } + + PatternBlock block; + var maxBlockLen = patternArgs.EndLine - patternArgs.StartLine; + //int searchLine = i + 1; + _logger.Debug(CultureInfo.InvariantCulture, "TestStatistic(): i={0} searchLine={1}", i, searchLine); + //bool firstBlock = true; + searchLine++; + UpdateProgressBar(searchLine); + while (!_shouldCancel && + (block = + DetectBlock(i, searchLine, maxBlockLen, _patternArgs.MaxDiffInBlock, + _patternArgs.MaxMisses, + processedLinesDict)) != null) + { + _logger.Debug(CultureInfo.InvariantCulture, "Found block: {0}", block); + if (block.Weigth >= _patternArgs.MinWeight) + { + //PatternBlock existingBlock = FindExistingBlock(block, blockList); + //if (existingBlock != null) + //{ + // if (block.weigth > existingBlock.weigth) + // { + // blockList.Remove(existingBlock); + // blockList.Add(block); + // } + //} + //else + { + blockList.Add(block); + AddBlockTargetLinesToDict(processedLinesDict, block); + } + block.BlockId = blockId; + //if (firstBlock) + //{ + // addBlockSrcLinesToDict(processedLinesDict, block); + //} + searchLine = block.TargetEnd + 1; + } + else + { + searchLine = block.TargetStart + 1; + } + + UpdateProgressBar(searchLine); + } + + blockId++; + } + + _isSearching = false; + _progressEventArgs.MinValue = 0; + _progressEventArgs.MaxValue = 0; + _progressEventArgs.Value = 0; + _progressEventArgs.Visible = false; + SendProgressBarUpdate(); + //if (this.patternWindow.IsDisposed) + //{ + // this.Invoke(new MethodInvoker(CreatePatternWindow)); + //} + _patternWindow.SetBlockList(blockList, _patternArgs); + _logger.Info(CultureInfo.InvariantCulture, "TestStatistics() ended"); + } + + private void AddBlockTargetLinesToDict (Dictionary dict, PatternBlock block) + { + foreach (var lineNum in block.TargetLines.Keys) + { + _ = dict.TryAdd(lineNum, lineNum); + } + } + + //Well keep this for the moment because there is some other commented code which calls this one + private PatternBlock FindExistingBlock (PatternBlock block, List blockList) + { + foreach (var searchBlock in blockList) + { + if (((block.StartLine > searchBlock.StartLine && block.StartLine < searchBlock.EndLine) || + (block.EndLine > searchBlock.StartLine && block.EndLine < searchBlock.EndLine)) && + block.StartLine != searchBlock.StartLine && + block.EndLine != searchBlock.EndLine + ) + { + return searchBlock; + } + } + + return null; + } + + private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBlockLen, int maxDiffInBlock, int maxMisses, Dictionary processedLinesDict) + { + var targetLine = FindSimilarLine(startNum, startLineToSearch, processedLinesDict); + if (targetLine == -1) + { + return null; + } + + PatternBlock block = new() + { + StartLine = startNum + }; + var srcLine = block.StartLine; + block.TargetStart = targetLine; + var srcMisses = 0; + block.SrcLines.Add(srcLine, srcLine); + //block.targetLines.Add(targetLine, targetLine); + var len = 0; + QualityInfo qi = new() + { + Quality = block.Weigth + }; + block.QualityInfoList[targetLine] = qi; + + while (!_shouldCancel) + { + srcLine++; + len++; + //if (srcLine >= block.targetStart) + // break; // prevent to search in the own block + if (maxBlockLen > 0 && len > maxBlockLen) + { + break; + } + + var nextTargetLine = FindSimilarLine(srcLine, targetLine + 1, processedLinesDict); + if (nextTargetLine > -1 && nextTargetLine - targetLine - 1 <= maxDiffInBlock) + { + block.Weigth += maxDiffInBlock - (nextTargetLine - targetLine - 1) + 1; + block.EndLine = srcLine; + //block.targetLines.Add(nextTargetLine, nextTargetLine); + block.SrcLines.Add(srcLine, srcLine); + if (nextTargetLine - targetLine > 1) + { + var tempWeight = block.Weigth; + for (var tl = targetLine + 1; tl < nextTargetLine; ++tl) + { + qi = new QualityInfo + { + Quality = --tempWeight + }; + block.QualityInfoList[tl] = qi; + } + } + + targetLine = nextTargetLine; + qi = new QualityInfo + { + Quality = block.Weigth + }; + block.QualityInfoList[targetLine] = qi; + } + else + { + srcMisses++; + block.Weigth--; + targetLine++; + qi = new QualityInfo + { + Quality = block.Weigth + }; + block.QualityInfoList[targetLine] = qi; + if (srcMisses > maxMisses) + { + break; + } + } + } + + block.TargetEnd = targetLine; + qi = new QualityInfo + { + Quality = block.Weigth + }; + + block.QualityInfoList[targetLine] = qi; + + for (var k = block.TargetStart; k <= block.TargetEnd; ++k) + { + block.TargetLines.Add(k, k); + } + + return block; + } + + private void PrepareDict () + { + _lineHashList.Clear(); + Regex regex = new("\\d"); + Regex regex2 = new("\\S"); + + var num = _logFileReader.LineCount; + for (var i = 0; i < num; ++i) + { + var msg = GetMsgForLine(i); + if (msg != null) + { + msg = msg.ToLowerInvariant(); + msg = regex.Replace(msg, "0"); + msg = regex2.Replace(msg, " "); + var chars = msg.ToCharArray(); + var value = 0; + var numOfE = 0; + var numOfA = 0; + var numOfI = 0; + foreach (var t in chars) + { + value += t; + switch (t) + { + case 'e': + numOfE++; + break; + case 'a': + numOfA++; + break; + case 'i': + numOfI++; + break; + } + } + + value += numOfE * 30; + value += numOfA * 20; + value += numOfI * 10; + _lineHashList.Add(value); + } + } + } + + private int FindSimilarLine (int srcLine, int startLine) + { + var value = _lineHashList[srcLine]; + + var num = _lineHashList.Count; + for (var i = startLine; i < num; ++i) + { + if (Math.Abs(_lineHashList[i] - value) < 3) + { + return i; + } + } + + return -1; + } + + // int[,] similarCache; + + private void ResetCache (int num) + { + //this.similarCache = new int[num, num]; + //for (int i = 0; i < num; ++i) + //{ + // for (int j = 0; j < num; j++) + // { + // this.similarCache[i, j] = -1; + // } + //} + } + + private int FindSimilarLine (int srcLine, int startLine, Dictionary processedLinesDict) + { + var threshold = _patternArgs.Fuzzy; + + var prepared = false; + Regex regex = null; + Regex regex2 = null; + string msgToFind = null; + var culture = CultureInfo.CurrentCulture; + + var num = _logFileReader.LineCount; + for (var i = startLine; i < num; ++i) + { + if (processedLinesDict.ContainsKey(i)) + { + continue; + } + + //if (this.similarCache[srcLine, i] != -1) + //{ + // if (this.similarCache[srcLine, i] < threshold) + // { + // return i; + // } + //} + //else + { + if (!prepared) + { + msgToFind = GetMsgForLine(srcLine); + regex = new Regex("\\d"); + regex2 = new Regex("\\W"); + msgToFind = msgToFind.ToLower(culture); + msgToFind = regex.Replace(msgToFind, "0"); + msgToFind = regex2.Replace(msgToFind, " "); + prepared = true; + } + + var msg = GetMsgForLine(i); + if (msg != null) + { + msg = regex.Replace(msg, "0"); + msg = regex2.Replace(msg, " "); + var lenDiff = Math.Abs(msg.Length - msgToFind.Length); + if (lenDiff > threshold) + { + //this.similarCache[srcLine, i] = lenDiff; + continue; + } + + msg = msg.ToLower(culture); + var distance = Util.YetiLevenshtein(msgToFind, msg); + //this.similarCache[srcLine, i] = distance; + if (distance < threshold) + { + return i; + } + } + } + } + + return -1; + } + + private string GetMsgForLine (int i) + { + var line = _logFileReader.GetLogLine(i); + var columnizer = CurrentColumnizer; + ColumnizerCallback callback = new(this); + var cols = columnizer.SplitLine(callback, line); + return cols.ColumnValues.Last().FullValue; + } + + [SupportedOSPlatform("windows")] + private void ChangeRowHeight (bool decrease) + { + var rowNum = dataGridView.CurrentCellAddress.Y; + if (rowNum < 0 || rowNum >= dataGridView.RowCount) + { + return; + } + + if (decrease) + { + if (!_rowHeightList.TryGetValue(rowNum, out var entry)) + { + return; + } + else + { + entry.Height -= _lineHeight; + if (entry.Height <= _lineHeight) + { + _rowHeightList.Remove(rowNum); + } + } + } + else + { + RowHeightEntry entry; + if (!_rowHeightList.TryGetValue(rowNum, out var value)) + { + entry = new RowHeightEntry + { + LineNum = rowNum, + Height = _lineHeight + }; + + _rowHeightList[rowNum] = entry; + } + else + { + entry = value; + } + + entry.Height += _lineHeight; + } + + dataGridView.UpdateRowHeightInfo(rowNum, false); + if (rowNum == dataGridView.RowCount - 1 && _guiStateArgs.FollowTail) + { + dataGridView.FirstDisplayedScrollingRowIndex = rowNum; + } + + dataGridView.Refresh(); + } + + private int GetRowHeight (int rowNum) + { + return _rowHeightList.TryGetValue(rowNum, out var value) + ? value.Height + : _lineHeight; + } + + private void AddBookmarkAtLineSilently (int lineNum) + { + if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) + { + _bookmarkProvider.AddBookmark(new Bookmark(lineNum)); + } + } + + [SupportedOSPlatform("windows")] + private void AddBookmarkAndEditComment () + { + var lineNum = dataGridView.CurrentCellAddress.Y; + if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) + { + ToggleBookmark(); + } + + BookmarkComment(_bookmarkProvider.GetBookmarkForLine(lineNum)); + } + + [SupportedOSPlatform("windows")] + private void AddBookmarkComment (string text) + { + var lineNum = dataGridView.CurrentCellAddress.Y; + Bookmark bookmark; + if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) + { + _bookmarkProvider.AddBookmark(bookmark = new Bookmark(lineNum)); + } + else + { + bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); + } + + bookmark.Text += text; + dataGridView.Refresh(); + filterGridView.Refresh(); + OnBookmarkTextChanged(bookmark); + } + + [SupportedOSPlatform("windows")] + private void MarkCurrentFilterRange () + { + _filterParams.RangeSearchText = filterRangeComboBox.Text; + ColumnizerCallback callback = new(this); + RangeFinder rangeFinder = new(_filterParams, callback); + var range = rangeFinder.FindRange(dataGridView.CurrentCellAddress.Y); + if (range != null) + { + SetCellSelectionMode(false); + _noSelectionUpdates = true; + for (var i = range.StartLine; i <= range.EndLine; ++i) + { + dataGridView.Rows[i].Selected = true; + } + + _noSelectionUpdates = false; + UpdateSelectionDisplay(); + } + } + + [SupportedOSPlatform("windows")] + private void RemoveTempHighlights () + { + lock (_tempHighlightEntryListLock) + { + _tempHighlightEntryList.Clear(); + } + + RefreshAllGrids(); + } + + [SupportedOSPlatform("windows")] + private void ToggleHighlightPanel (bool open) + { + highlightSplitContainer.Panel2Collapsed = !open; + btnToggleHighlightPanel.Image = open + ? new Bitmap(_panelCloseButtonImage, new Size(btnToggleHighlightPanel.Size.Height, btnToggleHighlightPanel.Size.Height)) + : new Bitmap(_panelOpenButtonImage, new Size(btnToggleHighlightPanel.Size.Height, btnToggleHighlightPanel.Size.Height)); + } + + [SupportedOSPlatform("windows")] + private void SetBookmarksForSelectedFilterLines () + { + lock (_filterResultList) + { + foreach (DataGridViewRow row in filterGridView.SelectedRows) + { + var lineNum = _filterResultList[row.Index]; + AddBookmarkAtLineSilently(lineNum); + } + } + + dataGridView.Refresh(); + filterGridView.Refresh(); + OnBookmarkAdded(); + } + + private void SetDefaultHighlightGroup () + { + var group = _parentLogTabWin.FindHighlightGroupByFileMask(FileName); + if (group != null) + { + SetCurrentHighlightGroup(group.GroupName); + } + else + { + SetCurrentHighlightGroup("[Default]"); + } + } + + [SupportedOSPlatform("windows")] + private void HandleChangedFilterOnLoadSetting () + { + _parentLogTabWin.Preferences.IsFilterOnLoad = filterOnLoadCheckBox.Checked; + _parentLogTabWin.Preferences.IsAutoHideFilterList = hideFilterListOnLoadCheckBox.Checked; + OnFilterListChanged(this); + } + + private void FireCancelHandlers () + { + lock (_cancelHandlerList) + { + foreach (var handler in _cancelHandlerList) + { + handler.EscapePressed(); + } + } + } + + private void SyncOtherWindows (DateTime timestamp) + { + lock (_timeSyncListLock) + { + TimeSyncList?.NavigateToTimestamp(timestamp, this); + } + } + + [SupportedOSPlatform("windows")] + private void AddSlaveToTimesync (LogWindow slave) + { + lock (_timeSyncListLock) + { + if (TimeSyncList == null) + { + if (slave.TimeSyncList == null) + { + TimeSyncList = new TimeSyncList(); + TimeSyncList.AddWindow(this); + } + else + { + TimeSyncList = slave.TimeSyncList; + } + + var currentLineNum = dataGridView.CurrentCellAddress.Y; + var refLine = currentLineNum; + var timeStamp = GetTimestampForLine(ref refLine, true); + if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) + { + TimeSyncList.CurrentTimestamp = timeStamp; + } + + TimeSyncList.WindowRemoved += OnTimeSyncListWindowRemoved; + } + } + + slave.AddToTimeSync(this); + OnSyncModeChanged(); + } + + private void FreeSlaveFromTimesync (LogWindow slave) + { + slave.FreeFromTimeSync(); + } + + private void OnSyncModeChanged () + { + SyncModeChanged?.Invoke(this, new SyncModeEventArgs(IsTimeSynced)); + } + + [SupportedOSPlatform("windows")] + private void AddSearchHitHighlightEntry (SearchParams para) + { + HighlightEntry he = new() + { + SearchText = para.SearchText, + ForegroundColor = Color.Red, + BackgroundColor = Color.Yellow, + IsRegEx = para.IsRegex, + IsCaseSensitive = para.IsCaseSensitive, + IsLedSwitch = false, + IsStopTail = false, + IsSetBookmark = false, + IsActionEntry = false, + ActionEntry = null, + IsWordMatch = true, + IsSearchHit = true + }; + + lock (_tempHighlightEntryListLock) + { + _tempHighlightEntryList.Add(he); + } + + RefreshAllGrids(); + } + + [SupportedOSPlatform("windows")] + private void RemoveAllSearchHighlightEntries () + { + lock (_tempHighlightEntryListLock) + { + List newList = []; + foreach (var he in _tempHighlightEntryList) + { + if (!he.IsSearchHit) + { + newList.Add(he); + } + } + + _tempHighlightEntryList = newList; + } + + RefreshAllGrids(); + } + + [SupportedOSPlatform("windows")] + private DataGridViewColumn GetColumnByName (BufferedDataGridView dataGridView, string name) + { + foreach (DataGridViewColumn col in dataGridView.Columns) + { + if (col.HeaderText.Equals(name, StringComparison.Ordinal)) + { + return col; + } + } + + return null; + } + + [SupportedOSPlatform("windows")] + private void SelectColumn () + { + var colName = columnComboBox.SelectedItem as string; + var col = GetColumnByName(dataGridView, colName); + if (col != null && !col.Frozen) + { + dataGridView.FirstDisplayedScrollingColumnIndex = col.Index; + var currentLine = dataGridView.CurrentCellAddress.Y; + if (currentLine >= 0) + { + dataGridView.CurrentCell = dataGridView.Rows[dataGridView.CurrentCellAddress.Y].Cells[col.Index]; + } + } + } + + #endregion + + #region Public methods + + public void LoadFile (string fileName, EncodingOptions encodingOptions) + { + EnterLoadFileStatus(); + + if (fileName != null) + { + FileName = fileName; + EncodingOptions = encodingOptions; + + if (_logFileReader != null) + { + _logFileReader.StopMonitoringAsync(); + UnRegisterLogFileReaderEvents(); + } + + // + // isUsingDefaultColumnizer is to enable automatically find the best columnizer. + // When a new log file is opened, and no Columnizer can be chose by file mask, + // this flag will enable find a columnizer automatically. + // Current solution is not elegant. + // Since the refactory will involving a lot of work, we can plan it in the future. + // One possible solution is, using raw file stream to read the sample lines to help + // the ColumnizerPicker to determine the priority. + // + var isUsingDefaultColumnizer = false; + if (!LoadPersistenceOptions()) + { + if (!IsTempFile) + { + var columnizer = FindColumnizer(); + if (columnizer != null) + { + if (_reloadMemento == null) + { + //TODO this needs to be refactored + var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; + + columnizer = ColumnizerPicker.CloneColumnizer(columnizer, directory); + } + } + else + { + isUsingDefaultColumnizer = true; + } + + PreSelectColumnizer(columnizer); + } + + SetDefaultHighlightGroup(); + } + + // this may be set after loading persistence data + if (_fileNames != null && IsMultiFile) + { + LoadFilesAsMulti(_fileNames, EncodingOptions); + return; + } + + _columnCache = new ColumnCache(); + + try + { + _logFileReader = new(fileName, EncodingOptions, IsMultiFile, Preferences.BufferCount, Preferences.LinesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) + { + UseNewReader = !Preferences.UseLegacyReader + }; + } + catch (LogFileException lfe) + { + _logger.Error(lfe); + MessageBox.Show($"Cannot load file\n{lfe.Message}", "LogExpert"); + _ = BeginInvoke(new FunctionWith1BoolParam(Close), true); + _isLoadError = true; + return; + } + + if (CurrentColumnizer is ILogLineXmlColumnizer xmlColumnizer) + { + _logFileReader.IsXmlMode = true; + _logFileReader.XmlLogConfig = xmlColumnizer.GetXmlLogConfiguration(); + } + + if (_forcedColumnizerForLoading != null) + { + CurrentColumnizer = _forcedColumnizerForLoading; + } + + _logFileReader.PreProcessColumnizer = CurrentColumnizer is IPreProcessColumnizer processColumnizer ? processColumnizer : null; + + RegisterLogFileReaderEvents(); + _logger.Info($"Loading logfile: {fileName}"); + _logFileReader.StartMonitoring(); + + if (isUsingDefaultColumnizer) + { + if (Preferences.AutoPick) + { + var newColumnizer = ColumnizerPicker.FindBetterColumnizer(FileName, _logFileReader, CurrentColumnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + + if (newColumnizer != null) + { + _logger.Debug($"Picked new columnizer '{newColumnizer}'"); + + PreSelectColumnizer(newColumnizer); + } + } + } + } + } + + public void LoadFilesAsMulti (string[] fileNames, EncodingOptions encodingOptions) + { + _logger.Info("Loading given files as MultiFile:"); + + EnterLoadFileStatus(); + + foreach (var name in fileNames) + { + _logger.Info($"File: {name}"); + } + + if (_logFileReader != null) + { + _logFileReader.StopMonitoring(); + UnRegisterLogFileReaderEvents(); + } + + EncodingOptions = encodingOptions; + _columnCache = new ColumnCache(); + + _logFileReader = new(fileNames, EncodingOptions, Preferences.BufferCount, Preferences.LinesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) + { + UseNewReader = !Preferences.UseLegacyReader + }; + + RegisterLogFileReaderEvents(); + _logFileReader.StartMonitoring(); + FileName = fileNames[^1]; + _fileNames = fileNames; + IsMultiFile = true; + //if (this.isTempFile) + // this.Text = this.tempTitleName; + //else + // this.Text = Util.GetNameFromPath(this.FileName); + } + + public string SavePersistenceData (bool force) + { + if (!force) + { + if (!Preferences.SaveSessions) + { + return null; + } + } + + if (IsTempFile || _isLoadError) + { + return null; + } + + try + { + var persistenceData = GetPersistenceData(); + + return ForcedPersistenceFileName == null + ? Persister.SavePersistenceData(FileName, persistenceData, Preferences) + : Persister.SavePersistenceDataWithFixedName(ForcedPersistenceFileName, persistenceData); + } + catch (IOException ex) + { + _logger.Error(ex, "Error saving persistence: "); + } + catch (Exception e) + { + MessageBox.Show($"Unexpected error while saving persistence: {e.Message}"); + } + + return null; + } + + public PersistenceData GetPersistenceData () + { + PersistenceData persistenceData = new() + { + BookmarkList = _bookmarkProvider.BookmarkList, + RowHeightList = _rowHeightList, + MultiFile = IsMultiFile, + MultiFilePattern = _multiFileOptions.FormatPattern, + MultiFileMaxDays = _multiFileOptions.MaxDayTry, + CurrentLine = dataGridView.CurrentCellAddress.Y, + FirstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex, + FilterVisible = !splitContainerLogWindow.Panel2Collapsed, + FilterAdvanced = !advancedFilterSplitContainer.Panel1Collapsed, + FilterPosition = splitContainerLogWindow.SplitterDistance, + FollowTail = _guiStateArgs.FollowTail, + FileName = FileName, + TabName = Text, + SessionFileName = SessionFileName, + ColumnizerName = CurrentColumnizer.GetName(), + LineCount = _logFileReader.LineCount + }; + + _filterParams.IsFilterTail = filterTailCheckBox.Checked; // this option doesnt need a press on 'search' + + if (Preferences.SaveFilters) + { + List filterList = [_filterParams]; + persistenceData.FilterParamsList = filterList; + + foreach (var filterPipe in _filterPipeList) + { + FilterTabData data = new() + { + PersistenceData = filterPipe.OwnLogWindow.GetPersistenceData(), + FilterParams = filterPipe.FilterParams + }; + persistenceData.FilterTabDataList.Add(data); + } + } + + if (_currentHighlightGroup != null) + { + persistenceData.HighlightGroupName = _currentHighlightGroup.GroupName; + } + + if (_fileNames != null && IsMultiFile) + { + persistenceData.MultiFileNames.AddRange(_fileNames); + } + + //persistenceData.showBookmarkCommentColumn = this.bookmarkWindow.ShowBookmarkCommentColumn; + persistenceData.FilterSaveListVisible = !highlightSplitContainer.Panel2Collapsed; + persistenceData.Encoding = _logFileReader.CurrentEncoding; + + return persistenceData; + } + + public void Close (bool dontAsk) + { + Preferences.AskForClose = !dontAsk; + Close(); + } + + public void CloseLogWindow () + { + StopTimespreadThread(); + StopTimestampSyncThread(); + StopLogEventWorkerThread(); + _shouldCancel = true; + + if (_logFileReader != null) + { + UnRegisterLogFileReaderEvents(); + _logFileReader.StopMonitoringAsync(); + //this.logFileReader.DeleteAllContent(); + } + + if (_isLoading) + { + _waitingForClose = true; + } + + if (IsTempFile) + { + _logger.Info($"Deleting temp file {FileName}"); + + try + { + File.Delete(FileName); + } + catch (IOException e) + { + _logger.Error(e, $"Error while deleting temp file {FileName}: {e}"); + } + } + + FilterPipe?.CloseAndDisconnect(); + DisconnectFilterPipes(); + } + + public void WaitForLoadingFinished () + { + _externaLoadingFinishedEvent.WaitOne(); + } + + public void ForceColumnizer (ILogLineColumnizer columnizer) + { + //TODO this needs to be refactored + var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; + + _forcedColumnizer = ColumnizerPicker.CloneColumnizer(columnizer, directory); + SetColumnizer(_forcedColumnizer); + } + + public void ForceColumnizerForLoading (ILogLineColumnizer columnizer) + { + //TODO this needs to be refactored + var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; + + _forcedColumnizerForLoading = ColumnizerPicker.CloneColumnizer(columnizer, directory); + } + + public void PreselectColumnizer (string columnizerName) + { + //TODO this needs to be refactored + var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; + + var columnizer = ColumnizerPicker.FindColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + PreSelectColumnizer(ColumnizerPicker.CloneColumnizer(columnizer, directory)); + } + + public void ColumnizerConfigChanged () + { + SetColumnizerInternal(CurrentColumnizer); + } + + public void SetColumnizer (ILogLineColumnizer columnizer, BufferedDataGridView gridView) + { + PaintHelper.SetColumnizer(columnizer, gridView); + + gridView.Refresh(); + AutoResizeColumns(gridView); + ApplyFrozenState(gridView); + } + + public IColumn GetCellValue (int rowIndex, int columnIndex) + { + if (columnIndex == 1) + { + return new Column + { + FullValue = $"{rowIndex + 1}" // line number + }; + } + + if (columnIndex == 0) // marker column + { + return Column.EmptyColumn; + } + + try + { + var cols = GetColumnsForLine(rowIndex); + if (cols != null && cols.ColumnValues != null) + { + if (columnIndex <= cols.ColumnValues.Length + 1) + { + var value = cols.ColumnValues[columnIndex - 2]; + + return value != null && value.DisplayValue != null + ? value + : value; + } + + return columnIndex == 2 + ? cols.ColumnValues[^1] + : Column.EmptyColumn; + } + } + catch + { + return Column.EmptyColumn; + } + + return Column.EmptyColumn; + } + + public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) + { + if (rowIndex < 0 || e.ColumnIndex < 0) + { + e.Handled = false; + return; + } + + var line = _logFileReader.GetLogLineWithWait(rowIndex).Result; + + if (line != null) + { + var entry = FindFirstNoWordMatchHilightEntry(line); + e.Graphics.SetClip(e.CellBounds); + + if (e.State.HasFlag(DataGridViewElementStates.Selected)) + { + using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); + e.Graphics.FillRectangle(brush, e.CellBounds); + } + else + { + e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); + e.PaintBackground(e.ClipBounds, false); + } + + if (DebugOptions.DisableWordHighlight) + { + e.PaintContent(e.CellBounds); + } + else + { + PaintCell(e, gridView, false, entry); + } + + if (e.ColumnIndex == 0) + { + if (_bookmarkProvider.IsBookmarkAtLine(rowIndex)) + { + Rectangle r; // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); + r = e.CellBounds; + r.Inflate(-2, -2); + using var brush = new SolidBrush(BookmarkColor); + e.Graphics.FillRectangle(brush, r); + + var bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); + + if (bookmark.Text.Length > 0) + { + StringFormat format = new() + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Center + }; + + using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); //dark orange + using var font = new Font("Courier New", Preferences.FontSize, FontStyle.Bold); + e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); + } + } + } + + e.Paint(e.CellBounds, DataGridViewPaintParts.Border); + e.Handled = true; + } + } + + public void OnDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) + { + var gridView = (BufferedDataGridView)sender; + CellPainting(gridView, e.RowIndex, e); + } + + /// + /// Returns the first HilightEntry that matches the given line + /// + /// + /// + /// + public HighlightEntry FindHighlightEntry (ITextValue line, bool noWordMatches) + { + // first check the temp entries + lock (_tempHighlightEntryListLock) + { + foreach (var entry in _tempHighlightEntryList) + { + if (noWordMatches && entry.IsWordMatch) + { + continue; + } + + if (CheckHighlightEntryMatch(entry, line)) + { + return entry; + } + } + } + + lock (_currentHighlightGroupLock) + { + foreach (var entry in _currentHighlightGroup.HighlightEntryList) + { + if (noWordMatches && entry.IsWordMatch) + { + continue; + } + if (CheckHighlightEntryMatch(entry, line)) + { + return entry; + } + } + return null; + } + } + + public IList FindHighlightMatches (ITextValue line) + { + IList resultList = []; + + if (line != null) + { + lock (_currentHighlightGroupLock) + { + GetHighlightEntryMatches(line, _currentHighlightGroup.HighlightEntryList, resultList); + } + + lock (_tempHighlightEntryList) + { + GetHighlightEntryMatches(line, _tempHighlightEntryList, resultList); + } + } + + return resultList; + } + + public void FollowTailChanged (bool isChecked, bool byTrigger) + { + _guiStateArgs.FollowTail = isChecked; + + if (_guiStateArgs.FollowTail && _logFileReader != null) + { + if (dataGridView.RowCount >= _logFileReader.LineCount && _logFileReader.LineCount > 0) + { + dataGridView.FirstDisplayedScrollingRowIndex = _logFileReader.LineCount - 1; + } + } + + BeginInvoke(new MethodInvoker(dataGridView.Refresh)); + //this.dataGridView.Refresh(); + _parentLogTabWin.FollowTailChanged(this, isChecked, byTrigger); + SendGuiStateUpdate(); + } + + public void TryToTruncate () + { + try + { + if (LockFinder.CheckIfFileIsLocked(Title)) + { + var name = LockFinder.FindLockedProcessName(Title); + StatusLineText($"Truncate failed: file is locked by {name}"); + } + else + { + File.WriteAllText(Title, ""); + } + } + catch (Exception ex) + { + _logger.Warn($"Unexpected issue truncating file: {ex.Message}"); + StatusLineText("Unexpected issue truncating file"); + throw; + } + } + + public void GotoLine (int line) + { + if (line >= 0) + { + if (line < dataGridView.RowCount) + { + SelectLine(line, false, true); + } + else + { + SelectLine(dataGridView.RowCount - 1, false, true); + } + dataGridView.Focus(); + } + } + + public void StartSearch () + { + _guiStateArgs.MenuEnabled = false; + GuiStateUpdate(this, _guiStateArgs); + var searchParams = _parentLogTabWin.SearchParams; + + searchParams.CurrentLine = (searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed + ? dataGridView.CurrentCellAddress.Y + 1 + : dataGridView.CurrentCellAddress.Y - 1; + + _currentSearchParams = searchParams; // remember for async "not found" messages + + _isSearching = true; + _shouldCancel = false; + StatusLineText("Searching... Press ESC to cancel."); + + _progressEventArgs.MinValue = 0; + _progressEventArgs.MaxValue = dataGridView.RowCount; + _progressEventArgs.Value = 0; + _progressEventArgs.Visible = true; + SendProgressBarUpdate(); + + Task.Run(() => Search(searchParams)).ContinueWith(SearchComplete); + + RemoveAllSearchHighlightEntries(); + AddSearchHitHighlightEntry(searchParams); + } + + private void SearchComplete (Task task) + { + if (Disposing) + { + return; + } + + try + { + Invoke(new MethodInvoker(ResetProgressBar)); + var line = task.Result; + _guiStateArgs.MenuEnabled = true; + GuiStateUpdate(this, _guiStateArgs); + if (line == -1) + { + return; + } + + dataGridView.Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); + } + catch (Exception ex) // in the case the windows is already destroyed + { + _logger.Warn(ex); + } + } + + public void SelectLogLine (int line) + { + Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); + } + + public void SelectAndEnsureVisible (int line, bool triggerSyncCall) + { + try + { + SelectLine(line, triggerSyncCall, false); + + //if (!this.dataGridView.CurrentRow.Displayed) + if (line < dataGridView.FirstDisplayedScrollingRowIndex || line > dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false)) + { + dataGridView.FirstDisplayedScrollingRowIndex = line; + for (var i = 0; i < 8 && dataGridView.FirstDisplayedScrollingRowIndex > 0 && line < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false); ++i) + { + dataGridView.FirstDisplayedScrollingRowIndex -= 1; + } + + if (line >= dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false)) + { + dataGridView.FirstDisplayedScrollingRowIndex += 1; + } + } + + dataGridView.CurrentCell = dataGridView.Rows[line].Cells[0]; + } + catch (Exception e) + { + // In rare situations there seems to be an invalid argument exceptions (or something like this). Concrete location isn't visible in stack + // trace because use of Invoke(). So catch it, and log (better than crashing the app). + _logger.Error(e); + } + } + + public void OnLogWindowKeyDown (object sender, KeyEventArgs e) + { + if (_isErrorShowing) + { + RemoveStatusLineError(); + } + + switch (e.KeyCode) + { + case Keys.F3 when _parentLogTabWin.SearchParams?.SearchText == null || _parentLogTabWin.SearchParams.SearchText.Length == 0: + { + return; + } + case Keys.F3: + { + _parentLogTabWin.SearchParams.IsFindNext = true; + _parentLogTabWin.SearchParams.IsShiftF3Pressed = (e.Modifiers & Keys.Shift) == Keys.Shift; + StartSearch(); + break; + } + case Keys.Escape: + { + if (_isSearching) + { + _shouldCancel = true; + } + + FireCancelHandlers(); + RemoveAllSearchHighlightEntries(); + break; + } + case Keys.E when (e.Modifiers & Keys.Control) == Keys.Control: + { + StartEditMode(); + + break; + } + case Keys.Down when e.Modifiers == Keys.Alt: + { + var newLine = _logFileReader.GetNextMultiFileLine(dataGridView.CurrentCellAddress.Y); + + if (newLine != -1) + { + SelectLine(newLine, false, true); + } + + e.Handled = true; + + break; + } + case Keys.Up when e.Modifiers == Keys.Alt: + { + var newLine = _logFileReader.GetPrevMultiFileLine(dataGridView.CurrentCellAddress.Y); + + if (newLine != -1) + { + SelectLine(newLine - 1, false, true); + } + + e.Handled = true; + + break; + } + case Keys.Enter when dataGridView.Focused: + { + ChangeRowHeight(e.Shift); + e.Handled = true; + + break; + } + case Keys.Back when dataGridView.Focused: + { + ChangeRowHeight(true); + e.Handled = true; + + break; + } + case Keys.PageUp when e.Modifiers == Keys.Alt: + { + SelectPrevHighlightLine(); + e.Handled = true; + + break; + } + case Keys.PageDown when e.Modifiers == Keys.Alt: + { + SelectNextHighlightLine(); + e.Handled = true; + + break; + } + case Keys.T when (e.Modifiers & Keys.Control) == Keys.Control && (e.Modifiers & Keys.Shift) == Keys.Shift: + { + FilterToTab(); + break; + } + } + } + + public void AddBookmarkOverlays () + { + const int OVERSCAN = 20; + + var firstLine = dataGridView.FirstDisplayedScrollingRowIndex; + if (firstLine < 0) + { + return; + } + + firstLine -= OVERSCAN; + if (firstLine < 0) + { + firstLine = 0; + } + + var oversizeCount = OVERSCAN; + + for (var i = firstLine; i < dataGridView.RowCount; ++i) + { + if (!dataGridView.Rows[i].Displayed && i > dataGridView.FirstDisplayedScrollingRowIndex) + { + if (oversizeCount-- < 0) + { + break; + } + } + + if (_bookmarkProvider.IsBookmarkAtLine(i)) + { + var bookmark = _bookmarkProvider.GetBookmarkForLine(i); + if (bookmark.Text.Length > 0) + { + //BookmarkOverlay overlay = new BookmarkOverlay(); + var overlay = bookmark.Overlay; + overlay.Bookmark = bookmark; + + Rectangle r; + if (dataGridView.Rows[i].Displayed) + { + r = dataGridView.GetCellDisplayRectangle(0, i, false); + } + else + { + r = dataGridView.GetCellDisplayRectangle(0, dataGridView.FirstDisplayedScrollingRowIndex, false); + //int count = i - this.dataGridView.FirstDisplayedScrollingRowIndex; + var heightSum = 0; + if (dataGridView.FirstDisplayedScrollingRowIndex < i) + { + for (var rn = dataGridView.FirstDisplayedScrollingRowIndex + 1; rn < i; ++rn) + { + //Rectangle rr = this.dataGridView.GetCellDisplayRectangle(0, rn, false); + //heightSum += rr.Height; + heightSum += GetRowHeight(rn); + } + + r.Offset(0, r.Height + heightSum); + } + else + { + for (var rn = dataGridView.FirstDisplayedScrollingRowIndex + 1; rn > i; --rn) + { + //Rectangle rr = this.dataGridView.GetCellDisplayRectangle(0, rn, false); + //heightSum += rr.Height; + heightSum += GetRowHeight(rn); + } + + r.Offset(0, -(r.Height + heightSum)); + } + //r.Offset(0, this.dataGridView.DisplayRectangle.Height); + } + + if (_logger.IsDebugEnabled) + { + _logger.Debug($"AddBookmarkOverlay() r.Location={r.Location.X}, width={r.Width}, scroll_offset={dataGridView.HorizontalScrollingOffset}"); + } + + overlay.Position = r.Location - new Size(dataGridView.HorizontalScrollingOffset, 0); + overlay.Position += new Size(10, r.Height / 2); + dataGridView.AddOverlay(overlay); + } + } + } + } + + public void ToggleBookmark () + { + BufferedDataGridView gridView; + int lineNum; + + if (filterGridView.Focused) + { + gridView = filterGridView; + if (gridView.CurrentCellAddress.Y == -1) + { + return; + } + + lineNum = _filterResultList[gridView.CurrentCellAddress.Y]; + } + else + { + gridView = dataGridView; + if (gridView.CurrentCellAddress.Y == -1) + { + return; + } + lineNum = dataGridView.CurrentCellAddress.Y; + } + + ToggleBookmark(lineNum); + } + + public void ToggleBookmark (int lineNum) + { + if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) + { + var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); + + if (string.IsNullOrEmpty(bookmark.Text) == false) + { + if (DialogResult.No == MessageBox.Show("There's a comment attached to the bookmark. Really remove the bookmark?", "LogExpert", MessageBoxButtons.YesNo)) + { + return; + } + } + _bookmarkProvider.RemoveBookmarkForLine(lineNum); + } + else + { + _bookmarkProvider.AddBookmark(new Bookmark(lineNum)); + } + dataGridView.Refresh(); + filterGridView.Refresh(); + OnBookmarkAdded(); + } + + public void SetBookmarkFromTrigger (int lineNum, string comment) + { + lock (_bookmarkLock) + { + var line = _logFileReader.GetLogLine(lineNum); + if (line == null) + { + return; + } + var paramParser = new ParamParser(comment); + try + { + comment = paramParser.ReplaceParams(line, lineNum, FileName); + } + catch (ArgumentException) + { + // occurs on invalid regex + } + if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) + { + _bookmarkProvider.RemoveBookmarkForLine(lineNum); + } + _bookmarkProvider.AddBookmark(new Bookmark(lineNum, comment)); + OnBookmarkAdded(); + } + } + + public void JumpNextBookmark () + { + if (_bookmarkProvider.Bookmarks.Count > 0) + { + if (filterGridView.Focused) + { + var index = FindNextBookmarkIndex(_filterResultList[filterGridView.CurrentCellAddress.Y]); + var startIndex = index; + var wrapped = false; + while (true) + { + var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; + if (_filterResultList.Contains(lineNum)) + { + var filterLine = _filterResultList.IndexOf(lineNum); + filterGridView.Rows[filterLine].Selected = true; + filterGridView.CurrentCell = filterGridView.Rows[filterLine].Cells[0]; + break; + } + index++; + if (index > _bookmarkProvider.Bookmarks.Count - 1) + { + index = 0; + wrapped = true; + } + if (index >= startIndex && wrapped) + { + break; + } + } + } + else + { + var index = FindNextBookmarkIndex(dataGridView.CurrentCellAddress.Y); + if (index > _bookmarkProvider.Bookmarks.Count - 1) + { + index = 0; + } + + var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; + SelectLine(lineNum, true, true); + } + } + } + + public void JumpPrevBookmark () + { + if (_bookmarkProvider.Bookmarks.Count > 0) + { + if (filterGridView.Focused) + { + //int index = this.bookmarkList.BinarySearch(this.filterResultList[this.filterGridView.CurrentCellAddress.Y]); + //if (index < 0) + // index = ~index; + //index--; + var index = FindPrevBookmarkIndex(_filterResultList[filterGridView.CurrentCellAddress.Y]); + if (index < 0) + { + index = _bookmarkProvider.Bookmarks.Count - 1; + } + var startIndex = index; + var wrapped = false; + while (true) + { + var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; + if (_filterResultList.Contains(lineNum)) + { + var filterLine = _filterResultList.IndexOf(lineNum); + filterGridView.Rows[filterLine].Selected = true; + filterGridView.CurrentCell = filterGridView.Rows[filterLine].Cells[0]; + break; + } + index--; + if (index < 0) + { + index = _bookmarkProvider.Bookmarks.Count - 1; + wrapped = true; + } + if (index <= startIndex && wrapped) + { + break; + } + } + } + else + { + var index = FindPrevBookmarkIndex(dataGridView.CurrentCellAddress.Y); + if (index < 0) + { + index = _bookmarkProvider.Bookmarks.Count - 1; + } + + var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; + SelectLine(lineNum, false, true); + } + } + } + + public void DeleteBookmarks (List lineNumList) + { + var bookmarksPresent = false; + foreach (var lineNum in lineNumList) + { + if (lineNum != -1) + { + if (_bookmarkProvider.IsBookmarkAtLine(lineNum) && + _bookmarkProvider.GetBookmarkForLine(lineNum).Text.Length > 0) + { + bookmarksPresent = true; + } + } + } + if (bookmarksPresent) + { + if ( + MessageBox.Show("There are some comments in the bookmarks. Really remove bookmarks?", "LogExpert", + MessageBoxButtons.YesNo) == DialogResult.No) + { + return; + } + } + _bookmarkProvider.RemoveBookmarksForLines(lineNumList); + OnBookmarkRemoved(); + } + + public void SetTimeshiftValue (string value) + { + _guiStateArgs.TimeshiftText = value; + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + try + { + if (_guiStateArgs.TimeshiftEnabled) + { + try + { + var text = _guiStateArgs.TimeshiftText; + if (text.StartsWith("+")) + { + text = text.Substring(1); + } + var timeSpan = TimeSpan.Parse(text); + var diff = (int)(timeSpan.Ticks / TimeSpan.TicksPerMillisecond); + CurrentColumnizer.SetTimeOffset(diff); + } + catch (Exception) + { + CurrentColumnizer.SetTimeOffset(0); + } + } + else + { + CurrentColumnizer.SetTimeOffset(0); + } + dataGridView.Refresh(); + filterGridView.Refresh(); + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + SetTimestampLimits(); + SyncTimestampDisplay(); + } + } + catch (FormatException ex) + { + _logger.Error(ex); + } + } + } + + public void ToggleFilterPanel () + { + splitContainerLogWindow.Panel2Collapsed = !splitContainerLogWindow.Panel2Collapsed; + if (!splitContainerLogWindow.Panel2Collapsed) + { + filterComboBox.Focus(); + } + else + { + dataGridView.Focus(); + } + } + + public void LogWindowActivated () + { + if (_guiStateArgs.FollowTail && !_isDeadFile) + { + OnTailFollowed(EventArgs.Empty); + } + + if (Preferences.TimestampControl) + { + SetTimestampLimits(); + SyncTimestampDisplay(); + } + + dataGridView.Focus(); + + SendGuiStateUpdate(); + SendStatusLineUpdate(); + SendProgressBarUpdate(); + } + + public void SetCellSelectionMode (bool isCellMode) + { + if (isCellMode) + { + //possible performance issue, see => https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/best-practices-for-scaling-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8#using-the-selected-cells-rows-and-columns-collections-efficiently + dataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect; + } + else + { + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + } + + _guiStateArgs.CellSelectMode = isCellMode; + } + + public void TimeshiftEnabled (bool isEnabled, string shiftValue) + { + _guiStateArgs.TimeshiftEnabled = isEnabled; + SetTimestampLimits(); + SetTimeshiftValue(shiftValue); + } + + public void CopyMarkedLinesToTab () + { + if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + { + var lineNumList = new List(); + foreach (DataGridViewRow row in dataGridView.SelectedRows) + { + if (row.Index != -1) + { + lineNumList.Add(row.Index); + } + } + + lineNumList.Sort(); + // create dummy FilterPipe for connecting line numbers to original window + // setting IsStopped to true prevents further filter processing + var pipe = new FilterPipe(new FilterParams(), this) + { + IsStopped = true + }; + WritePipeToTab(pipe, lineNumList, Text + "->C", null); + } + else + { + var fileName = Path.GetTempFileName(); + var fStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read); + var writer = new StreamWriter(fStream, Encoding.Unicode); + + var data = dataGridView.GetClipboardContent(); + var text = data.GetText(TextDataFormat.Text); + writer.Write(text); + + writer.Close(); + var title = Util.GetNameFromPath(FileName) + "->Clip"; + _parentLogTabWin.AddTempFileTab(fileName, title); + } + } + + /// + /// Change the file encoding. May force a reload if byte count ot preamble lenght differs from previous used encoding. + /// + /// + public void ChangeEncoding (Encoding encoding) + { + _logFileReader.ChangeEncoding(encoding); + EncodingOptions.Encoding = encoding; + if (_guiStateArgs.CurrentEncoding.IsSingleByte != encoding.IsSingleByte || + _guiStateArgs.CurrentEncoding.GetPreamble().Length != encoding.GetPreamble().Length) + { + Reload(); + } + else + { + dataGridView.Refresh(); + SendGuiStateUpdate(); + } + _guiStateArgs.CurrentEncoding = _logFileReader.CurrentEncoding; + } + + public void Reload () + { + SavePersistenceData(false); + + _reloadMemento = new ReloadMemento + { + CurrentLine = dataGridView.CurrentCellAddress.Y, + FirstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex + }; + _forcedColumnizerForLoading = CurrentColumnizer; + + if (_fileNames == null || !IsMultiFile) + { + LoadFile(FileName, EncodingOptions); + } + else + { + LoadFilesAsMulti(_fileNames, EncodingOptions); + } + //if (currentLine < this.dataGridView.RowCount && currentLine >= 0) + // this.dataGridView.CurrentCell = this.dataGridView.Rows[currentLine].Cells[0]; + //if (firstDisplayedLine < this.dataGridView.RowCount && firstDisplayedLine >= 0) + // this.dataGridView.FirstDisplayedScrollingRowIndex = firstDisplayedLine; + + //if (this.filterTailCheckBox.Checked) + //{ + // _logger.logInfo("Refreshing filter view because of reload."); + // FilterSearch(); + //} + } + + public void PreferencesChanged (string fontName, float fontSize, bool setLastColumnWidth, int lastColumnWidth, bool isLoadTime, SettingsFlags flags) + { + if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) + { + NormalFont = new Font(new FontFamily(fontName), fontSize); + BoldFont = new Font(NormalFont, FontStyle.Bold); + MonospacedFont = new Font("Courier New", Preferences.FontSize, FontStyle.Bold); + + var lineSpacing = NormalFont.FontFamily.GetLineSpacing(FontStyle.Regular); + var lineSpacingPixel = NormalFont.Size * lineSpacing / NormalFont.FontFamily.GetEmHeight(FontStyle.Regular); + + dataGridView.DefaultCellStyle.Font = NormalFont; + filterGridView.DefaultCellStyle.Font = NormalFont; + _lineHeight = NormalFont.Height + 4; + dataGridView.RowTemplate.Height = NormalFont.Height + 4; + + ShowBookmarkBubbles = Preferences.ShowBubbles; + + ApplyDataGridViewPrefs(dataGridView, setLastColumnWidth, lastColumnWidth); + ApplyDataGridViewPrefs(filterGridView, setLastColumnWidth, lastColumnWidth); + + if (Preferences.TimestampControl) + { + SetTimestampLimits(); + SyncTimestampDisplay(); + } + + if (isLoadTime) + { + filterTailCheckBox.Checked = Preferences.FilterTail; + syncFilterCheckBox.Checked = Preferences.FilterSync; + //this.FollowTailChanged(this.Preferences.followTail, false); + } + + _timeSpreadCalc.TimeMode = Preferences.TimeSpreadTimeMode; + timeSpreadingControl.ForeColor = Preferences.TimeSpreadColor; + timeSpreadingControl.ReverseAlpha = Preferences.ReverseAlpha; + + if (CurrentColumnizer.IsTimeshiftImplemented()) + { + timeSpreadingControl.Invoke(new MethodInvoker(timeSpreadingControl.Refresh)); + ShowTimeSpread(Preferences.ShowTimeSpread); + } + + ToggleColumnFinder(Preferences.ShowColumnFinder, false); + } + + if ((flags & SettingsFlags.FilterList) == SettingsFlags.FilterList) + { + HandleChangedFilterList(); + } + + if ((flags & SettingsFlags.FilterHistory) == SettingsFlags.FilterHistory) + { + UpdateFilterHistoryFromSettings(); + + if (isLoadTime) + { + AutoResizeFilterBox(); + } + } + } + + public bool ScrollToTimestamp (DateTime timestamp, bool roundToSeconds, bool triggerSyncCall) + { + if (InvokeRequired) + { + BeginInvoke(new ScrollToTimestampFx(ScrollToTimestampWorker), timestamp, roundToSeconds, triggerSyncCall); + return true; + } + + return ScrollToTimestampWorker(timestamp, roundToSeconds, triggerSyncCall); + } + + public bool ScrollToTimestampWorker (DateTime timestamp, bool roundToSeconds, bool triggerSyncCall) + { + var hasScrolled = false; + if (!CurrentColumnizer.IsTimeshiftImplemented() || dataGridView.RowCount == 0) + { + return false; + } + + //this.Cursor = Cursors.WaitCursor; + var currentLine = dataGridView.CurrentCellAddress.Y; + if (currentLine < 0 || currentLine >= dataGridView.RowCount) + { + currentLine = 0; + } + var foundLine = FindTimestampLine(currentLine, timestamp, roundToSeconds); + if (foundLine >= 0) + { + SelectAndEnsureVisible(foundLine, triggerSyncCall); + hasScrolled = true; + } + //this.Cursor = Cursors.Default; + return hasScrolled; + } + + public int FindTimestampLine (int lineNum, DateTime timestamp, bool roundToSeconds) + { + var foundLine = + FindTimestampLine_Internal(lineNum, 0, dataGridView.RowCount - 1, timestamp, roundToSeconds); + if (foundLine >= 0) + { + // go backwards to the first occurence of the hit + var foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); + while (foundTimestamp.CompareTo(timestamp) == 0 && foundLine >= 0) + { + foundLine--; + foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); + } + if (foundLine < 0) + { + return 0; + } + + foundLine++; + GetTimestampForLineForward(ref foundLine, roundToSeconds); // fwd to next valid timestamp + return foundLine; + } + + return -foundLine; + } + + public int FindTimestampLine_Internal (int lineNum, int rangeStart, int rangeEnd, DateTime timestamp, + bool roundToSeconds) + { + _logger.Debug("FindTimestampLine_Internal(): timestamp={0}, lineNum={1}, rangeStart={2}, rangeEnd={3}", timestamp, lineNum, rangeStart, rangeEnd); + var refLine = lineNum; + var currentTimestamp = GetTimestampForLine(ref refLine, roundToSeconds); + if (currentTimestamp.CompareTo(timestamp) == 0) + { + return lineNum; + } + + if (timestamp < currentTimestamp) + { + //rangeStart = rangeStart; + rangeEnd = lineNum; + } + else + { + rangeStart = lineNum; + //rangeEnd = rangeEnd; + } + + if (rangeEnd - rangeStart <= 0) + { + return -lineNum; + } + + lineNum = ((rangeEnd - rangeStart) / 2) + rangeStart; + // prevent endless loop + if (rangeEnd - rangeStart < 2) + { + currentTimestamp = GetTimestampForLine(ref rangeStart, roundToSeconds); + if (currentTimestamp.CompareTo(timestamp) == 0) + { + return rangeStart; + } + + currentTimestamp = GetTimestampForLine(ref rangeEnd, roundToSeconds); + + return currentTimestamp.CompareTo(timestamp) == 0 + ? rangeEnd + : -lineNum; + } + + return FindTimestampLine_Internal(lineNum, rangeStart, rangeEnd, timestamp, roundToSeconds); + } + + /** + * Get the timestamp for the given line number. If the line + * has no timestamp, the previous line will be checked until a + * timestamp is found. + */ + public DateTime GetTimestampForLine (ref int lineNum, bool roundToSeconds) + { + lock (_currentColumnizerLock) + { + if (!CurrentColumnizer.IsTimeshiftImplemented()) + { + return DateTime.MinValue; + } + + _logger.Debug($"GetTimestampForLine({lineNum}) enter"); + var timeStamp = DateTime.MinValue; + var lookBack = false; + if (lineNum >= 0 && lineNum < dataGridView.RowCount) + { + while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum >= 0) + { + if (_isTimestampDisplaySyncing && _shouldTimestampDisplaySyncingCancel) + { + return DateTime.MinValue; + } + + lookBack = true; + var logLine = _logFileReader.GetLogLine(lineNum); + if (logLine == null) + { + return DateTime.MinValue; + } + + ColumnizerCallbackObject.LineNum = lineNum; + timeStamp = CurrentColumnizer.GetTimestamp(ColumnizerCallbackObject, logLine); + if (roundToSeconds) + { + timeStamp = timeStamp.Subtract(TimeSpan.FromMilliseconds(timeStamp.Millisecond)); + } + + lineNum--; + } + } + + if (lookBack) + { + lineNum++; + } + + _logger.Debug("GetTimestampForLine() leave with lineNum={0}", lineNum); + return timeStamp; + } + } + + /** + * Get the timestamp for the given line number. If the line + * has no timestamp, the next line will be checked until a + * timestamp is found. + */ + public DateTime GetTimestampForLineForward (ref int lineNum, bool roundToSeconds) + { + lock (_currentColumnizerLock) + { + if (!CurrentColumnizer.IsTimeshiftImplemented()) + { + return DateTime.MinValue; + } + + var timeStamp = DateTime.MinValue; + var lookFwd = false; + if (lineNum >= 0 && lineNum < dataGridView.RowCount) + { + while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum < dataGridView.RowCount) + { + lookFwd = true; + var logLine = _logFileReader.GetLogLine(lineNum); + if (logLine == null) + { + timeStamp = DateTime.MinValue; + break; + } + timeStamp = CurrentColumnizer.GetTimestamp(ColumnizerCallbackObject, logLine); + if (roundToSeconds) + { + timeStamp = timeStamp.Subtract(TimeSpan.FromMilliseconds(timeStamp.Millisecond)); + } + lineNum++; + } + } + if (lookFwd) + { + lineNum--; + } + return timeStamp; + } + } + + public void AppFocusLost () + { + InvalidateCurrentRow(dataGridView); + } + + public void AppFocusGained () + { + InvalidateCurrentRow(dataGridView); + } + + public ILogLine GetCurrentLine () + { + if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index != -1) + { + return _logFileReader.GetLogLine(dataGridView.CurrentRow.Index); + } + return null; + } + + public ILogLine GetLine (int lineNum) + { + if (lineNum < 0 || _logFileReader == null || lineNum >= _logFileReader.LineCount) + { + return null; + } + return _logFileReader.GetLogLine(lineNum); + } + + public int GetCurrentLineNum () + { + if (dataGridView.CurrentRow == null) + { + return -1; + } + return dataGridView.CurrentRow.Index; + } + + public int GetRealLineNum () + { + var lineNum = GetCurrentLineNum(); + if (lineNum == -1) + { + return -1; + } + return _logFileReader.GetRealLineNumForVirtualLineNum(lineNum); + } + + public ILogFileInfo GetCurrentFileInfo () + { + if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index != -1) + { + return _logFileReader.GetLogFileInfoForLine(dataGridView.CurrentRow.Index); + } + return null; + } + + /// + /// zero-based + /// + /// + /// + public string GetCurrentFileName (int lineNum) + { + return _logFileReader.GetLogFileNameForLine(lineNum); + } + + // =============== end of bookmark stuff =================================== + + public void ShowLineColumn (bool show) + { + dataGridView.Columns[1].Visible = show; + filterGridView.Columns[1].Visible = show; + } + + // ================================================================= + // Pattern statistics + // ================================================================= + + public void PatternStatistic () + { + InitPatternWindow(); + } + + public void PatternStatisticSelectRange (PatternArgs patternArgs) + { + if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + { + List lineNumList = []; + foreach (DataGridViewRow row in dataGridView.SelectedRows) + { + if (row.Index != -1) + { + lineNumList.Add(row.Index); + } + } + lineNumList.Sort(); + patternArgs.StartLine = lineNumList[0]; + patternArgs.EndLine = lineNumList[^1]; + } + else + { + patternArgs.StartLine = dataGridView.CurrentCellAddress.Y != -1 + ? dataGridView.CurrentCellAddress.Y + : 0; + patternArgs.EndLine = dataGridView.RowCount - 1; + } + } + + public void PatternStatistic (PatternArgs patternArgs) + { + var fx = new PatternStatisticFx(TestStatistic); + fx.BeginInvoke(patternArgs, null, null); + } + + public void ExportBookmarkList () + { + SaveFileDialog dlg = new() + { + Title = "Choose a file to save bookmarks into", + AddExtension = true, + DefaultExt = "csv", + Filter = "CSV file (*.csv)|*.csv|Bookmark file (*.bmk)|*.bmk", + FilterIndex = 1, + FileName = Path.GetFileNameWithoutExtension(FileName) + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + try + { + BookmarkExporter.ExportBookmarkList(_bookmarkProvider.BookmarkList, FileName, + dlg.FileName); + } + catch (IOException e) + { + _logger.Error(e); + MessageBox.Show("Error while exporting bookmark list: " + e.Message, "LogExpert"); + } + } + } + + public void ImportBookmarkList () + { + OpenFileDialog dlg = new() + { + Title = "Choose a file to load bookmarks from", + AddExtension = true, + DefaultExt = "csv", + Filter = "CSV file (*.csv)|*.csv|Bookmark file (*.bmk)|*.bmk", + FilterIndex = 1, + FileName = Path.GetFileNameWithoutExtension(FileName) + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + try + { + // add to the existing bookmarks + SortedList newBookmarks = []; + BookmarkExporter.ImportBookmarkList(FileName, dlg.FileName, newBookmarks); + + // Add (or replace) to existing bookmark list + var bookmarkAdded = false; + foreach (var b in newBookmarks.Values) + { + if (!_bookmarkProvider.BookmarkList.ContainsKey(b.LineNum)) + { + _bookmarkProvider.BookmarkList.Add(b.LineNum, b); + bookmarkAdded = true; // refresh the list only once at the end + } + else + { + var existingBookmark = _bookmarkProvider.BookmarkList[b.LineNum]; + existingBookmark.Text = + b.Text; // replace existing bookmark for that line, preserving the overlay + OnBookmarkTextChanged(b); + } + } + + // Refresh the lists + if (bookmarkAdded) + { + OnBookmarkAdded(); + } + dataGridView.Refresh(); + filterGridView.Refresh(); + } + catch (IOException e) + { + _logger.Error(e); + MessageBox.Show($"Error while importing bookmark list: {e.Message}", "LogExpert"); + } + } + } + + public bool IsAdvancedOptionActive () + { + return rangeCheckBox.Checked || + fuzzyKnobControl.Value > 0 || + filterKnobBackSpread.Value > 0 || + filterKnobForeSpread.Value > 0 || + invertFilterCheckBox.Checked || + columnRestrictCheckBox.Checked; + } + + public void HandleChangedFilterList () + { + Invoke(new MethodInvoker(HandleChangedFilterListWorker)); + } + + public void HandleChangedFilterListWorker () + { + var index = filterListBox.SelectedIndex; + filterListBox.Items.Clear(); + foreach (var filterParam in ConfigManager.Settings.FilterList) + { + filterListBox.Items.Add(filterParam); + } + filterListBox.Refresh(); + if (index >= 0 && index < filterListBox.Items.Count) + { + filterListBox.SelectedIndex = index; + } + filterOnLoadCheckBox.Checked = Preferences.IsFilterOnLoad; + hideFilterListOnLoadCheckBox.Checked = Preferences.IsAutoHideFilterList; + } + + public void SetCurrentHighlightGroup (string groupName) + { + _guiStateArgs.HighlightGroupName = groupName; + lock (_currentHighlightGroupLock) + { + _currentHighlightGroup = _parentLogTabWin.FindHighlightGroup(groupName); + + _currentHighlightGroup ??= _parentLogTabWin.HighlightGroupList.Count > 0 + ? _parentLogTabWin.HighlightGroupList[0] + : new HighlightGroup(); + + _guiStateArgs.HighlightGroupName = _currentHighlightGroup.GroupName; + } + + SendGuiStateUpdate(); + BeginInvoke(new MethodInvoker(RefreshAllGrids)); + } + + public void SwitchMultiFile (bool enabled) + { + IsMultiFile = enabled; + Reload(); + } + + public void AddOtherWindowToTimesync (LogWindow other) + { + if (other.IsTimeSynced) + { + if (IsTimeSynced) + { + other.FreeFromTimeSync(); + AddSlaveToTimesync(other); + } + else + { + AddToTimeSync(other); + } + } + else + { + AddSlaveToTimesync(other); + } + } + + public void AddToTimeSync (LogWindow master) + { + _logger.Info($"Syncing window for {Util.GetNameFromPath(FileName)} to {Util.GetNameFromPath(master.FileName)}"); + lock (_timeSyncListLock) + { + if (IsTimeSynced && master.TimeSyncList != TimeSyncList) + // already synced but master has different sync list + { + FreeFromTimeSync(); + } + + TimeSyncList = master.TimeSyncList; + TimeSyncList.AddWindow(this); + ScrollToTimestamp(TimeSyncList.CurrentTimestamp, false, false); + } + + OnSyncModeChanged(); + } + + public void FreeFromTimeSync () + { + lock (_timeSyncListLock) + { + if (TimeSyncList != null) + { + _logger.Info($"De-Syncing window for {Util.GetNameFromPath(FileName)}"); + TimeSyncList.WindowRemoved -= OnTimeSyncListWindowRemoved; + TimeSyncList.RemoveWindow(this); + TimeSyncList = null; + } + } + + OnSyncModeChanged(); + } + + public void RefreshLogView () + { + RefreshAllGrids(); + } + + #endregion } \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.resx b/src/LogExpert.UI/Controls/LogWindow/LogWindow.resx index dd8f0ebb..1af7de15 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.resx +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.resx @@ -1,17 +1,17 @@ - + - @@ -117,57 +117,4 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 17, 27 - - - 11, 68 - - - 17, 27 - - - 862, 21 - - - - - iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vAAADrwBlbxySQAAAM1JREFUOE/dlDsKQkEMRYO1jZU7EAS3YG1h51ZsdSdWIoLrcBla2dhZ2PvhPiYQ - rplMsLDwwBS5n8C8gSfyT0xF5EVnwqEsF1q0FZE9aRsuRWgpopfMdaSDhWb+3ApUQGfBovLNQjCudfWV - syB7o/mD5rcxeFnMV9I6cceig7ewqkM40MwhT1NczxOt5vkWeEcWR5WSLvM8S9WH0WcxKhSWUWYdmQHo - DFi0ZK5qQfbBoocunrFhWJXMk42IOT2Sd4ZcyoJf3N0sOnHgJ7wBih1ZgqnoK8MAAAAASUVORK5CYII= - - - - - iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vAAADrwBlbxySQAAAM1JREFUOE/dlDsKQkEMRYO1jZU7EAS3YG1h51ZsdSdWIoLrcBla2dhZ2PvhPiYQ - rplMsLDwwBS5n8C8gSfyT0xF5EVnwqEsF1q0FZE9aRsuRWgpopfMdaSDhWb+3ApUQGfBovLNQjCudfWV - syB7o/mD5rcxeFnMV9I6cceig7ewqkM40MwhT1NczxOt5vkWeEcWR5WSLvM8S9WH0WcxKhSWUWYdmQHo - DFi0ZK5qQfbBoocunrFhWJXMk42IOT2Sd4ZcyoJf3N0sOnHgJ7wBih1ZgqnoK8MAAAAASUVORK5CYII= - - - - 261, 21 - - - 467, 21 - - - 658, 21 - - - 70 - - - - AAABAAEAEBAQAAAABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAABAA - AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// - AAD///8AAAAAAAAAAAAP////////8A/////////wD/AAAAAAD/AP////////8A/wAAAAAA/wD/////// - //AP8ADwAAAP8A////D////wD/AA8AAP//AP///w////8A//APAAAP/wD/////////AP////////8AAA - AAAAAAAAAAAAAAAAAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAIABAAD//wAA - - \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs deleted file mode 100644 index 9150a4a2..00000000 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.cs +++ /dev/null @@ -1,1723 +0,0 @@ -using System.ComponentModel; -using System.Globalization; -using System.Runtime.Versioning; - -using LogExpert.Core.Classes; -using LogExpert.Core.Classes.Filter; -using LogExpert.Core.Classes.Highlight; -using LogExpert.Core.Config; -using LogExpert.Core.Entities; -using LogExpert.Core.EventArguments; -using LogExpert.Core.Interface; -using LogExpert.Dialogs; -using LogExpert.UI.Dialogs; -using LogExpert.UI.Entities; -using LogExpert.UI.Extensions; - -namespace LogExpert.UI.Controls.LogWindow; - -partial class LogWindow -{ - [SupportedOSPlatform("windows")] - private void AutoResizeFilterBox () - { - filterSplitContainer.SplitterDistance = filterComboBox.Left + filterComboBox.GetMaxTextWidth(); - } - - #region Events handler - - protected void OnProgressBarUpdate (ProgressEventArgs e) - { - ProgressBarUpdate?.Invoke(this, e); - } - - protected void OnStatusLine (StatusLineEventArgs e) - { - StatusLineEvent?.Invoke(this, e); - } - - protected void OnGuiState (GuiStateArgs e) - { - GuiStateUpdate?.Invoke(this, e); - } - - protected void OnTailFollowed (EventArgs e) - { - TailFollowed?.Invoke(this, e); - } - - protected void OnFileNotFound (EventArgs e) - { - FileNotFound?.Invoke(this, e); - } - - protected void OnFileRespawned (EventArgs e) - { - FileRespawned?.Invoke(this, e); - } - - protected void OnFilterListChanged (LogWindow source) - { - FilterListChanged?.Invoke(this, new FilterListChangedEventArgs(source)); - } - - protected void OnCurrentHighlightListChanged () - { - CurrentHighlightGroupChanged?.Invoke(this, new CurrentHighlightGroupChangedEventArgs(this, _currentHighlightGroup)); - } - - protected void OnBookmarkAdded () - { - BookmarkAdded?.Invoke(this, EventArgs.Empty); - } - - protected void OnBookmarkRemoved () - { - BookmarkRemoved?.Invoke(this, EventArgs.Empty); - } - - protected void OnBookmarkTextChanged (Bookmark bookmark) - { - BookmarkTextChanged?.Invoke(this, new BookmarkEventArgs(bookmark)); - } - - protected void OnColumnizerChanged (ILogLineColumnizer columnizer) - { - ColumnizerChanged?.Invoke(this, new ColumnizerEventArgs(columnizer)); - } - - protected void OnRegisterCancelHandler (IBackgroundProcessCancelHandler handler) - { - lock (_cancelHandlerList) - { - _cancelHandlerList.Add(handler); - } - } - - protected void OnDeRegisterCancelHandler (IBackgroundProcessCancelHandler handler) - { - lock (_cancelHandlerList) - { - _cancelHandlerList.Remove(handler); - } - } - - [SupportedOSPlatform("windows")] - private void OnLogWindowLoad (object sender, EventArgs e) - { - var setLastColumnWidth = _parentLogTabWin.Preferences.SetLastColumnWidth; - var lastColumnWidth = _parentLogTabWin.Preferences.LastColumnWidth; - var fontName = _parentLogTabWin.Preferences.FontName; - var fontSize = _parentLogTabWin.Preferences.FontSize; - - PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, true, SettingsFlags.GuiOrColors); - } - - [SupportedOSPlatform("windows")] - private void OnLogWindowDisposed (object sender, EventArgs e) - { - _waitingForClose = true; - _parentLogTabWin.HighlightSettingsChanged -= OnParentHighlightSettingsChanged; - _logFileReader?.DeleteAllContent(); - - FreeFromTimeSync(); - } - - [SupportedOSPlatform("windows")] - private void OnLogFileReaderLoadingStarted (object sender, LoadFileEventArgs e) - { - Invoke(LoadingStarted, e); - } - - [SupportedOSPlatform("windows")] - private void OnLogFileReaderFinishedLoading (object sender, EventArgs e) - { - //Thread.CurrentThread.Name = "FinishedLoading event thread"; - _logger.Info(CultureInfo.InvariantCulture, "Finished loading."); - _isLoading = false; - _isDeadFile = false; - if (!_waitingForClose) - { - Invoke(new MethodInvoker(LoadingFinished)); - Invoke(new MethodInvoker(LoadPersistenceData)); - Invoke(new MethodInvoker(SetGuiAfterLoading)); - _loadingFinishedEvent.Set(); - _externaLoadingFinishedEvent.Set(); - _timeSpreadCalc.SetLineCount(_logFileReader.LineCount); - - if (_reloadMemento != null) - { - Invoke(new PositionAfterReloadFx(PositionAfterReload), _reloadMemento); - } - - if (filterTailCheckBox.Checked) - { - _logger.Info(CultureInfo.InvariantCulture, "Refreshing filter view because of reload."); - Invoke(new MethodInvoker(FilterSearch)); // call on proper thread - } - - HandleChangedFilterList(); - } - - _reloadMemento = null; - } - - [SupportedOSPlatform("windows")] - private void OnLogFileReaderFileNotFound (object sender, EventArgs e) - { - if (!IsDisposed && !Disposing) - { - _logger.Info(CultureInfo.InvariantCulture, "Handling file not found event."); - _isDeadFile = true; - BeginInvoke(new MethodInvoker(LogfileDead)); - } - } - - [SupportedOSPlatform("windows")] - private void OnLogFileReaderRespawned (object sender, EventArgs e) - { - BeginInvoke(new MethodInvoker(LogfileRespawned)); - } - - [SupportedOSPlatform("windows")] - private void OnLogWindowClosing (object sender, CancelEventArgs e) - { - if (Preferences.AskForClose) - { - if (MessageBox.Show("Sure to close?", "LogExpert", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - e.Cancel = true; - return; - } - } - - SavePersistenceData(false); - CloseLogWindow(); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - AutoResizeColumns(dataGridView); - } - - /** - * Event handler for the Load event from LogfileReader - */ - [SupportedOSPlatform("windows")] - private void OnLogFileReaderLoadFile (object sender, LoadFileEventArgs e) - { - if (e.NewFile) - { - _logger.Info(CultureInfo.InvariantCulture, "File created anew."); - - // File was new created (e.g. rollover) - _isDeadFile = false; - UnRegisterLogFileReaderEvents(); - dataGridView.CurrentCellChanged -= OnDataGridViewCurrentCellChanged; - MethodInvoker invoker = ReloadNewFile; - BeginInvoke(invoker); - //Thread loadThread = new Thread(new ThreadStart(ReloadNewFile)); - //loadThread.Start(); - _logger.Debug(CultureInfo.InvariantCulture, "Reloading invoked."); - } - else if (_isLoading) - { - BeginInvoke(UpdateProgress, e); - } - } - - private void OnFileSizeChanged (object sender, LogEventArgs e) - { - //OnFileSizeChanged(e); // now done in UpdateGrid() - _logger.Info(CultureInfo.InvariantCulture, "Got FileSizeChanged event. prevLines:{0}, curr lines: {1}", e.PrevLineCount, e.LineCount); - - // - now done in the thread that works on the event args list - //if (e.IsRollover) - //{ - // ShiftBookmarks(e.RolloverOffset); - // ShiftFilterPipes(e.RolloverOffset); - //} - - //UpdateGridCallback callback = new UpdateGridCallback(UpdateGrid); - //this.BeginInvoke(callback, new object[] { e }); - lock (_logEventArgsList) - { - _logEventArgsList.Add(e); - _logEventArgsEvent.Set(); - } - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) - { - var startCount = CurrentColumnizer?.GetColumnCount() ?? 0; - - e.Value = GetCellValue(e.RowIndex, e.ColumnIndex); - - // The new column could be find dynamically. - // Only support add new columns for now. - // TODO: Support reload all columns? - if (CurrentColumnizer != null && CurrentColumnizer.GetColumnCount() > startCount) - { - for (var i = startCount; i < CurrentColumnizer.GetColumnCount(); i++) - { - var colName = CurrentColumnizer.GetColumnNames()[i]; - dataGridView.Columns.Add(PaintHelper.CreateTitleColumn(colName)); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewCellValuePushed (object sender, DataGridViewCellValueEventArgs e) - { - if (!CurrentColumnizer.IsTimeshiftImplemented()) - { - return; - } - - var line = _logFileReader.GetLogLine(e.RowIndex); - var offset = CurrentColumnizer.GetTimeOffset(); - CurrentColumnizer.SetTimeOffset(0); - ColumnizerCallbackObject.SetLineNum(e.RowIndex); - var cols = CurrentColumnizer.SplitLine(ColumnizerCallbackObject, line); - CurrentColumnizer.SetTimeOffset(offset); - if (cols.ColumnValues.Length <= e.ColumnIndex - 2) - { - return; - } - - var oldValue = cols.ColumnValues[e.ColumnIndex - 2].FullValue; - var newValue = (string)e.Value; - //string oldValue = (string) this.dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; - CurrentColumnizer.PushValue(ColumnizerCallbackObject, e.ColumnIndex - 2, newValue, oldValue); - dataGridView.Refresh(); - TimeSpan timeSpan = new(CurrentColumnizer.GetTimeOffset() * TimeSpan.TicksPerMillisecond); - var span = timeSpan.ToString(); - var index = span.LastIndexOf('.'); - if (index > 0) - { - span = span.Substring(0, index + 4); - } - - SetTimeshiftValue(span); - SendGuiStateUpdate(); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewRowHeightInfoNeeded (object sender, DataGridViewRowHeightInfoNeededEventArgs e) - { - e.Height = GetRowHeight(e.RowIndex); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewCurrentCellChanged (object sender, EventArgs e) - { - if (dataGridView.CurrentRow != null) - { - _statusEventArgs.CurrentLineNum = dataGridView.CurrentRow.Index + 1; - SendStatusLineUpdate(); - if (syncFilterCheckBox.Checked) - { - SyncFilterGridPos(); - } - - if (CurrentColumnizer.IsTimeshiftImplemented() && Preferences.TimestampControl) - { - SyncTimestampDisplay(); - } - - //MethodInvoker invoker = new MethodInvoker(DisplayCurrentFileOnStatusline); - //invoker.BeginInvoke(null, null); - } - } - - private void OnDataGridViewCellEndEdit (object sender, DataGridViewCellEventArgs e) - { - StatusLineText(string.Empty); - } - - [SupportedOSPlatform("windows")] - private void OnEditControlKeyUp (object sender, KeyEventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - [SupportedOSPlatform("windows")] - private void OnEditControlKeyPress (object sender, KeyPressEventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - [SupportedOSPlatform("windows")] - private void OnEditControlClick (object sender, EventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - [SupportedOSPlatform("windows")] - private void OnEditControlKeyDown (object sender, KeyEventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewPaint (object sender, PaintEventArgs e) - { - if (ShowBookmarkBubbles) - { - AddBookmarkOverlays(); - } - } - - // ====================================================================================== - // Filter Grid stuff - // ====================================================================================== - - [SupportedOSPlatform("windows")] - private void OnFilterSearchButtonClick (object sender, EventArgs e) - { - FilterSearch(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) - { - var gridView = (BufferedDataGridView)sender; - - if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) - { - e.Handled = false; - return; - } - - - - var lineNum = _filterResultList[e.RowIndex]; - var line = _logFileReader.GetLogLineWithWait(lineNum).Result; - - if (line != null) - { - var entry = FindFirstNoWordMatchHilightEntry(line); - e.Graphics.SetClip(e.CellBounds); - if (e.State.HasFlag(DataGridViewElementStates.Selected)) - { - using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); - e.Graphics.FillRectangle(brush, e.CellBounds); - } - else - { - // paint direct filter hits with different bg color - //if (this.filterParams.SpreadEnabled && this.filterHitList.Contains(lineNum)) - //{ - // bgColor = Color.FromArgb(255, 220, 220, 220); - //} - e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); - e.PaintBackground(e.ClipBounds, false); - } - - if (DebugOptions.DisableWordHighlight) - { - e.PaintContent(e.CellBounds); - } - else - { - PaintCell(e, filterGridView, false, entry); - } - - if (e.ColumnIndex == 0) - { - if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - Rectangle r;// = new(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); - r = e.CellBounds; - r.Inflate(-2, -2); - using var brush = new SolidBrush(BookmarkColor); - e.Graphics.FillRectangle(brush, r); - - var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); - - if (bookmark.Text.Length > 0) - { - StringFormat format = new() - { - LineAlignment = StringAlignment.Center, - Alignment = StringAlignment.Center - }; - - using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - using var font = new Font("Verdana", Preferences.FontSize, FontStyle.Bold); - e.Graphics.DrawString("!", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); - } - } - } - - e.Paint(e.CellBounds, DataGridViewPaintParts.Border); - e.Handled = true; - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) - { - if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) - { - e.Value = ""; - return; - } - - var lineNum = _filterResultList[e.RowIndex]; - e.Value = GetCellValue(lineNum, e.ColumnIndex); - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewRowHeightInfoNeeded (object sender, DataGridViewRowHeightInfoNeededEventArgs e) - { - e.Height = _lineHeight; - } - - [SupportedOSPlatform("windows")] - private void OnFilterComboBoxKeyDown (object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) - { - FilterSearch(); - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewColumnDividerDoubleClick (object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - AutoResizeColumnsFx fx = AutoResizeColumns; - BeginInvoke(fx, filterGridView); - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) - { - if (e.ColumnIndex == 0) - { - ToggleBookmark(); - return; - } - - if (filterGridView.CurrentRow != null && e.RowIndex >= 0) - { - var lineNum = _filterResultList[filterGridView.CurrentRow.Index]; - SelectAndEnsureVisible(lineNum, true); - } - } - - [SupportedOSPlatform("windows")] - private void OnRangeCheckBoxCheckedChanged (object sender, EventArgs e) - { - filterRangeComboBox.Enabled = rangeCheckBox.Checked; - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewScroll (object sender, ScrollEventArgs e) - { - if (e.ScrollOrientation == ScrollOrientation.VerticalScroll) - { - if (dataGridView.DisplayedRowCount(false) + dataGridView.FirstDisplayedScrollingRowIndex >= dataGridView.RowCount) - { - //this.guiStateArgs.FollowTail = true; - if (!_guiStateArgs.FollowTail) - { - FollowTailChanged(true, false); - } - - OnTailFollowed(EventArgs.Empty); - } - else - { - //this.guiStateArgs.FollowTail = false; - if (_guiStateArgs.FollowTail) - { - FollowTailChanged(false, false); - } - } - - SendGuiStateUpdate(); - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewKeyDown (object sender, KeyEventArgs e) - { - switch (e.KeyCode) - { - case Keys.Enter: - { - if (filterGridView.CurrentCellAddress.Y >= 0 && filterGridView.CurrentCellAddress.Y < _filterResultList.Count) - { - var lineNum = _filterResultList[filterGridView.CurrentCellAddress.Y]; - SelectLine(lineNum, false, true); - e.Handled = true; - } - - break; - } - case Keys.Tab when e.Modifiers == Keys.None: - dataGridView.Focus(); - e.Handled = true; - break; - } - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewKeyDown (object sender, KeyEventArgs e) - { - switch (e.KeyCode) - { - case Keys.Tab when e.Modifiers == Keys.None: - { - filterGridView.Focus(); - e.Handled = true; - break; - } - } - - //switch (e.KeyCode) - //{ - // case Keys.Tab when e.Modifiers == Keys.Control: - // //this.parentLogTabWin.SwitchTab(e.Shift); - // break; - //} - - _shouldCallTimeSync = true; - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) - { - if (e.KeyCode == Keys.Tab && e.Control) - { - e.IsInputKey = true; - } - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewCellContentDoubleClick (object sender, DataGridViewCellEventArgs e) - { - if (dataGridView.CurrentCell != null) - { - dataGridView.BeginEdit(false); - } - } - - [SupportedOSPlatform("windows")] - private void OnSyncFilterCheckBoxCheckedChanged (object sender, EventArgs e) - { - if (syncFilterCheckBox.Checked) - { - SyncFilterGridPos(); - } - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewLeave (object sender, EventArgs e) - { - InvalidateCurrentRow(dataGridView); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewEnter (object sender, EventArgs e) - { - InvalidateCurrentRow(dataGridView); - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewEnter (object sender, EventArgs e) - { - InvalidateCurrentRow(filterGridView); - } - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewLeave (object sender, EventArgs e) - { - InvalidateCurrentRow(filterGridView); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewResize (object sender, EventArgs e) - { - if (_logFileReader != null && dataGridView.RowCount > 0 && _guiStateArgs.FollowTail) - { - dataGridView.FirstDisplayedScrollingRowIndex = dataGridView.RowCount - 1; - } - } - - private void OnDataGridViewSelectionChanged (object sender, EventArgs e) - { - UpdateSelectionDisplay(); - } - - [SupportedOSPlatform("windows")] - private void OnSelectionChangedTriggerSignal (object sender, EventArgs e) - { - var selCount = 0; - try - { - _logger.Debug(CultureInfo.InvariantCulture, "Selection changed trigger"); - selCount = dataGridView.SelectedRows.Count; - if (selCount > 1) - { - StatusLineText(selCount + " selected lines"); - } - else - { - if (IsMultiFile) - { - MethodInvoker invoker = DisplayCurrentFileOnStatusline; - invoker.BeginInvoke(null, null); - } - else - { - StatusLineText(""); - } - } - } - catch (Exception ex) - { - _logger.Error(ex, "Error in selectionChangedTrigger_Signal selcount {0}", selCount); - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterKnobControlValueChanged (object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterToTabButtonClick (object sender, EventArgs e) - { - FilterToTab(); - } - - private void OnPipeDisconnected (object sender, EventArgs e) - { - if (sender.GetType() == typeof(FilterPipe)) - { - lock (_filterPipeList) - { - _filterPipeList.Remove((FilterPipe)sender); - if (_filterPipeList.Count == 0) - // reset naming counter to 0 if no more open filter tabs for this source window - { - _filterPipeNameCounter = 0; - } - } - } - } - - [SupportedOSPlatform("windows")] - private void OnAdvancedButtonClick (object sender, EventArgs e) - { - _showAdvanced = !_showAdvanced; - ShowAdvancedFilterPanel(_showAdvanced); - } - - [SupportedOSPlatform("windows")] - private void OnFilterSplitContainerMouseDown (object sender, MouseEventArgs e) - { - ((SplitContainer)sender).IsSplitterFixed = true; - } - - [SupportedOSPlatform("windows")] - private void OnFilterSplitContainerMouseUp (object sender, MouseEventArgs e) - { - ((SplitContainer)sender).IsSplitterFixed = false; - } - - [SupportedOSPlatform("windows")] - private void OnFilterSplitContainerMouseMove (object sender, MouseEventArgs e) - { - var splitContainer = (SplitContainer)sender; - if (splitContainer.IsSplitterFixed) - { - if (e.Button.Equals(MouseButtons.Left)) - { - if (splitContainer.Orientation.Equals(Orientation.Vertical)) - { - if (e.X > 0 && e.X < splitContainer.Width) - { - splitContainer.SplitterDistance = e.X; - splitContainer.Refresh(); - } - } - else - { - if (e.Y > 0 && e.Y < splitContainer.Height) - { - splitContainer.SplitterDistance = e.Y; - splitContainer.Refresh(); - } - } - } - else - { - splitContainer.IsSplitterFixed = false; - } - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterSplitContainerMouseDoubleClick (object sender, MouseEventArgs e) - { - AutoResizeFilterBox(); - } - - #region Context Menu - - [SupportedOSPlatform("windows")] - private void OnDataGridContextMenuStripOpening (object sender, CancelEventArgs e) - { - var lineNum = -1; - if (dataGridView.CurrentRow != null) - { - lineNum = dataGridView.CurrentRow.Index; - } - - if (lineNum == -1) - { - return; - } - - var refLineNum = lineNum; - - copyToTabToolStripMenuItem.Enabled = dataGridView.SelectedCells.Count > 0; - scrollAllTabsToTimestampToolStripMenuItem.Enabled = CurrentColumnizer.IsTimeshiftImplemented() - && - GetTimestampForLine(ref refLineNum, false) != - DateTime.MinValue; - - locateLineInOriginalFileToolStripMenuItem.Enabled = IsTempFile && - FilterPipe != null && - FilterPipe.GetOriginalLineNum(lineNum) != -1; - - markEditModeToolStripMenuItem.Enabled = !dataGridView.CurrentCell.ReadOnly; - - // Remove all "old" plugin entries - var index = dataGridContextMenuStrip.Items.IndexOf(pluginSeparator); - - if (index > 0) - { - for (var i = index + 1; i < dataGridContextMenuStrip.Items.Count;) - { - dataGridContextMenuStrip.Items.RemoveAt(i); - } - } - - // Add plugin entries - var isAdded = false; - if (PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins.Count > 0) - { - var lines = GetSelectedContent(); - foreach (var entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) - { - LogExpertCallback callback = new(this); - var menuText = entry.GetMenuText(lines.Count, CurrentColumnizer, callback.GetLogLine(lines[0])); - - if (menuText != null) - { - var disabled = menuText.StartsWith('_'); - if (disabled) - { - menuText = menuText[1..]; - } - - var item = dataGridContextMenuStrip.Items.Add(menuText, null, OnHandlePluginContextMenu); - item.Tag = new ContextMenuPluginEventArgs(entry, lines, CurrentColumnizer, callback); - item.Enabled = !disabled; - isAdded = true; - } - } - } - - pluginSeparator.Visible = isAdded; - - // enable/disable Temp Highlight item - tempHighlightsToolStripMenuItem.Enabled = _tempHighlightEntryList.Count > 0; - - markCurrentFilterRangeToolStripMenuItem.Enabled = string.IsNullOrEmpty(filterRangeComboBox.Text) == false; - - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - var list = _parentLogTabWin.GetListOfOpenFiles(); - syncTimestampsToToolStripMenuItem.Enabled = true; - syncTimestampsToToolStripMenuItem.DropDownItems.Clear(); - EventHandler ev = OnHandleSyncContextMenu; - Font italicFont = new(syncTimestampsToToolStripMenuItem.Font.FontFamily, syncTimestampsToToolStripMenuItem.Font.Size, FontStyle.Italic); - - foreach (var fileEntry in list) - { - if (fileEntry.LogWindow != this) - { - var item = syncTimestampsToToolStripMenuItem.DropDownItems.Add(fileEntry.Title, null, ev) as ToolStripMenuItem; - item.Tag = fileEntry; - item.Checked = TimeSyncList != null && TimeSyncList.Contains(fileEntry.LogWindow); - if (fileEntry.LogWindow.TimeSyncList != null && !fileEntry.LogWindow.TimeSyncList.Contains(this)) - { - item.Font = italicFont; - item.ForeColor = Color.Blue; - } - - item.Enabled = fileEntry.LogWindow.CurrentColumnizer.IsTimeshiftImplemented(); - } - } - } - else - { - syncTimestampsToToolStripMenuItem.Enabled = false; - } - - freeThisWindowFromTimeSyncToolStripMenuItem.Enabled = TimeSyncList != null && - TimeSyncList.Count > 1; - } - - [SupportedOSPlatform("windows")] - private void OnHandlePluginContextMenu (object sender, EventArgs args) - { - if (sender is ToolStripItem item) - { - var menuArgs = item.Tag as ContextMenuPluginEventArgs; - var logLines = menuArgs.LogLines; - menuArgs.Entry.MenuSelected(logLines.Count, menuArgs.Columnizer, menuArgs.Callback.GetLogLine(logLines[0])); - } - } - - [SupportedOSPlatform("windows")] - private void OnHandleSyncContextMenu (object sender, EventArgs args) - { - if (sender is ToolStripItem item) - { - var entry = item.Tag as WindowFileEntry; - - if (TimeSyncList != null && TimeSyncList.Contains(entry.LogWindow)) - { - FreeSlaveFromTimesync(entry.LogWindow); - } - else - //AddSlaveToTimesync(entry.LogWindow); - { - AddOtherWindowToTimesync(entry.LogWindow); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnCopyToolStripMenuItemClick (object sender, EventArgs e) - { - CopyMarkedLinesToClipboard(); - } - - private void OnCopyToTabToolStripMenuItemClick (object sender, EventArgs e) - { - CopyMarkedLinesToTab(); - } - - [SupportedOSPlatform("windows")] - private void OnScrollAllTabsToTimestampToolStripMenuItemClick (object sender, EventArgs e) - { - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - var currentLine = dataGridView.CurrentCellAddress.Y; - if (currentLine > 0 && currentLine < dataGridView.RowCount) - { - var lineNum = currentLine; - var timeStamp = GetTimestampForLine(ref lineNum, false); - if (timeStamp.Equals(DateTime.MinValue)) // means: invalid - { - return; - } - - _parentLogTabWin.ScrollAllTabsToTimestamp(timeStamp, this); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnLocateLineInOriginalFileToolStripMenuItemClick (object sender, EventArgs e) - { - if (dataGridView.CurrentRow != null && FilterPipe != null) - { - var lineNum = FilterPipe.GetOriginalLineNum(dataGridView.CurrentRow.Index); - if (lineNum != -1) - { - FilterPipe.LogWindow.SelectLine(lineNum, false, true); - _parentLogTabWin.SelectTab(FilterPipe.LogWindow); - } - } - } - - private void OnToggleBoomarkToolStripMenuItemClick (object sender, EventArgs e) - { - ToggleBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnMarkEditModeToolStripMenuItemClick (object sender, EventArgs e) - { - StartEditMode(); - } - - private void OnLogWindowSizeChanged (object sender, EventArgs e) - { - //AdjustMinimumGridWith(); - AdjustHighlightSplitterWidth(); - } - - #region BookMarkList - - [SupportedOSPlatform("windows")] - private void OnColumnRestrictCheckBoxCheckedChanged (object sender, EventArgs e) - { - columnButton.Enabled = columnRestrictCheckBox.Checked; - if (columnRestrictCheckBox.Checked) // disable when nothing to filter - { - columnNamesLabel.Visible = true; - _filterParams.ColumnRestrict = true; - columnNamesLabel.Text = CalculateColumnNames(_filterParams); - } - else - { - columnNamesLabel.Visible = false; - } - - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnColumnButtonClick (object sender, EventArgs e) - { - _filterParams.CurrentColumnizer = _currentColumnizer; - FilterColumnChooser chooser = new(_filterParams); - if (chooser.ShowDialog() == DialogResult.OK) - { - columnNamesLabel.Text = CalculateColumnNames(_filterParams); - - //CheckForFilterDirty(); //!!!GBro: Indicate to redo the search if search columns were changed - filterSearchButton.Image = _searchButtonImage; - saveFilterButton.Enabled = false; - } - } - - #endregion - - #region Column Header Context Menu - - [SupportedOSPlatform("windows")] - private void OnDataGridViewCellContextMenuStripNeeded (object sender, DataGridViewCellContextMenuStripNeededEventArgs e) - { - if (e.RowIndex >= 0 && e.RowIndex < dataGridView.RowCount && !dataGridView.Rows[e.RowIndex].Selected) - { - SelectLine(e.RowIndex, false, true); - } - else if (e.RowIndex < 0) - { - e.ContextMenuStrip = columnContextMenuStrip; - } - - if (e.ContextMenuStrip == columnContextMenuStrip) - { - _selectedCol = e.ColumnIndex; - } - } - - //private void boomarkDataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) - //{ - // if (e.RowIndex > 0 && e.RowIndex < this.boomarkDataGridView.RowCount - // && !this.boomarkDataGridView.Rows[e.RowIndex].Selected) - // { - // this.boomarkDataGridView.Rows[e.RowIndex].Selected = true; - // this.boomarkDataGridView.CurrentCell = this.boomarkDataGridView.Rows[e.RowIndex].Cells[0]; - // } - // if (e.ContextMenuStrip == this.columnContextMenuStrip) - // { - // this.selectedCol = e.ColumnIndex; - // } - //} - - [SupportedOSPlatform("windows")] - private void OnFilterGridViewCellContextMenuStripNeeded (object sender, DataGridViewCellContextMenuStripNeededEventArgs e) - { - if (e.ContextMenuStrip == columnContextMenuStrip) - { - _selectedCol = e.ColumnIndex; - } - } - - [SupportedOSPlatform("windows")] - private void OnColumnContextMenuStripOpening (object sender, CancelEventArgs e) - { - var ctl = columnContextMenuStrip.SourceControl; - var gridView = ctl as BufferedDataGridView; - var frozen = false; - if (_freezeStateMap.TryGetValue(ctl, out var value)) - { - frozen = value; - } - - freezeLeftColumnsUntilHereToolStripMenuItem.Checked = frozen; - - if (frozen) - { - freezeLeftColumnsUntilHereToolStripMenuItem.Text = "Frozen"; - } - else - { - if (ctl is BufferedDataGridView) - { - freezeLeftColumnsUntilHereToolStripMenuItem.Text = $"Freeze left columns until here ({gridView.Columns[_selectedCol].HeaderText})"; - } - } - - - var col = gridView.Columns[_selectedCol]; - moveLeftToolStripMenuItem.Enabled = col != null && col.DisplayIndex > 0; - moveRightToolStripMenuItem.Enabled = col != null && col.DisplayIndex < gridView.Columns.Count - 1; - - if (gridView.Columns.Count - 1 > _selectedCol) - { - // DataGridViewColumn colRight = gridView.Columns[this.selectedCol + 1]; - var colRight = gridView.Columns.GetNextColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); - moveRightToolStripMenuItem.Enabled = colRight != null && colRight.Frozen == col.Frozen; - } - - if (_selectedCol > 0) - { - //DataGridViewColumn colLeft = gridView.Columns[this.selectedCol - 1]; - var colLeft = gridView.Columns.GetPreviousColumn(col, DataGridViewElementStates.None, DataGridViewElementStates.None); - - moveLeftToolStripMenuItem.Enabled = colLeft != null && colLeft.Frozen == col.Frozen; - } - - var colLast = gridView.Columns[gridView.Columns.Count - 1]; - moveToLastColumnToolStripMenuItem.Enabled = colLast != null && colLast.Frozen == col.Frozen; - - // Fill context menu with column names - // - EventHandler ev = OnHandleColumnItemContextMenu; - allColumnsToolStripMenuItem.DropDownItems.Clear(); - foreach (DataGridViewColumn column in gridView.Columns) - { - if (column.HeaderText.Length > 0) - { - var item = allColumnsToolStripMenuItem.DropDownItems.Add(column.HeaderText, null, ev) as ToolStripMenuItem; - item.Tag = column; - item.Enabled = !column.Frozen; - } - } - } - - [SupportedOSPlatform("windows")] - private void OnHandleColumnItemContextMenu (object sender, EventArgs args) - { - if (sender is ToolStripItem item) - { - var column = item.Tag as DataGridViewColumn; - column.Visible = true; - column.DataGridView.FirstDisplayedScrollingColumnIndex = column.Index; - } - } - - [SupportedOSPlatform("windows")] - private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick (object sender, EventArgs e) - { - var ctl = columnContextMenuStrip.SourceControl; - var frozen = false; - - if (_freezeStateMap.TryGetValue(ctl, out var value)) - { - frozen = value; - } - - frozen = !frozen; - _freezeStateMap[ctl] = frozen; - - if (ctl is BufferedDataGridView gridView) - { - ApplyFrozenState(gridView); - } - } - - [SupportedOSPlatform("windows")] - private void OnMoveToLastColumnToolStripMenuItemClick (object sender, EventArgs e) - { - var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - var col = gridView.Columns[_selectedCol]; - if (col != null) - { - col.DisplayIndex = gridView.Columns.Count - 1; - } - } - - [SupportedOSPlatform("windows")] - private void OnMoveLeftToolStripMenuItemClick (object sender, EventArgs e) - { - var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - var col = gridView.Columns[_selectedCol]; - if (col != null && col.DisplayIndex > 0) - { - col.DisplayIndex -= 1; - } - } - - [SupportedOSPlatform("windows")] - private void OnMoveRightToolStripMenuItemClick (object sender, EventArgs e) - { - var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - var col = gridView.Columns[_selectedCol]; - if (col != null && col.DisplayIndex < gridView.Columns.Count - 1) - { - col.DisplayIndex = col.DisplayIndex + 1; - } - } - - [SupportedOSPlatform("windows")] - private void OnHideColumnToolStripMenuItemClick (object sender, EventArgs e) - { - var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - var col = gridView.Columns[_selectedCol]; - col.Visible = false; - } - - [SupportedOSPlatform("windows")] - private void OnRestoreColumnsToolStripMenuItemClick (object sender, EventArgs e) - { - var gridView = columnContextMenuStrip.SourceControl as BufferedDataGridView; - foreach (DataGridViewColumn col in gridView.Columns) - { - col.Visible = true; - } - } - - [SupportedOSPlatform("windows")] - private void OnTimeSpreadingControlLineSelected (object sender, SelectLineEventArgs e) - { - SelectLine(e.Line, false, true); - } - - [SupportedOSPlatform("windows")] - private void OnBookmarkCommentToolStripMenuItemClick (object sender, EventArgs e) - { - AddBookmarkAndEditComment(); - } - - [SupportedOSPlatform("windows")] - private void OnHighlightSelectionInLogFileToolStripMenuItemClick (object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - var he = new HighlightEntry() - { - SearchText = ctl.SelectedText, - ForegroundColor = Color.Red, - BackgroundColor = Color.Yellow, - IsRegEx = false, - IsCaseSensitive = true, - IsLedSwitch = false, - IsSetBookmark = false, - IsActionEntry = false, - ActionEntry = null, - IsWordMatch = false - }; - - lock (_tempHighlightEntryListLock) - { - _tempHighlightEntryList.Add(he); - } - - dataGridView.CancelEdit(); - dataGridView.EndEdit(); - RefreshAllGrids(); - } - } - - [SupportedOSPlatform("windows")] - private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick (object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - HighlightEntry he = new() - { - SearchText = ctl.SelectedText, - ForegroundColor = Color.Red, - BackgroundColor = Color.Yellow, - IsRegEx = false, - IsCaseSensitive = true, - IsLedSwitch = false, - IsStopTail = false, - IsSetBookmark = false, - IsActionEntry = false, - ActionEntry = null, - IsWordMatch = true - }; - - lock (_tempHighlightEntryListLock) - { - _tempHighlightEntryList.Add(he); - } - - dataGridView.CancelEdit(); - dataGridView.EndEdit(); - RefreshAllGrids(); - } - } - - [SupportedOSPlatform("windows")] - private void OnEditModeCopyToolStripMenuItemClick (object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - if (Util.IsNull(ctl.SelectedText) == false) - { - Clipboard.SetText(ctl.SelectedText); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnRemoveAllToolStripMenuItemClick (object sender, EventArgs e) - { - RemoveTempHighlights(); - } - - [SupportedOSPlatform("windows")] - private void OnMakePermanentToolStripMenuItemClick (object sender, EventArgs e) - { - lock (_tempHighlightEntryListLock) - { - lock (_currentHighlightGroupLock) - { - _currentHighlightGroup.HighlightEntryList.AddRange(_tempHighlightEntryList); - RemoveTempHighlights(); - OnCurrentHighlightListChanged(); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnMarkCurrentFilterRangeToolStripMenuItemClick (object sender, EventArgs e) - { - MarkCurrentFilterRange(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterForSelectionToolStripMenuItemClick (object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - splitContainerLogWindow.Panel2Collapsed = false; - ResetFilterControls(); - FilterSearch(ctl.SelectedText); - } - } - - [SupportedOSPlatform("windows")] - private void OnSetSelectedTextAsBookmarkCommentToolStripMenuItemClick (object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - AddBookmarkComment(ctl.SelectedText); - } - } - - private void OnDataGridViewCellClick (object sender, DataGridViewCellEventArgs e) - { - _shouldCallTimeSync = true; - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewCellDoubleClick (object sender, DataGridViewCellEventArgs e) - { - if (e.ColumnIndex == 0) - { - ToggleBookmark(); - } - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewOverlayDoubleClicked (object sender, OverlayEventArgs e) - { - BookmarkComment(e.BookmarkOverlay.Bookmark); - } - - [SupportedOSPlatform("windows")] - private void OnFilterRegexCheckBoxMouseUp (object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - RegexHelperDialog dlg = new() - { - ExpressionHistoryList = ConfigManager.Settings.RegexHistory.ExpressionHistoryList, - TesttextHistoryList = ConfigManager.Settings.RegexHistory.TesttextHistoryList, - Owner = this, - CaseSensitive = filterCaseSensitiveCheckBox.Checked, - Pattern = filterComboBox.Text - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - ConfigManager.Settings.RegexHistory.ExpressionHistoryList = dlg.ExpressionHistoryList; - ConfigManager.Settings.RegexHistory.TesttextHistoryList = dlg.TesttextHistoryList; - - filterCaseSensitiveCheckBox.Checked = dlg.CaseSensitive; - filterComboBox.Text = dlg.Pattern; - - ConfigManager.Save(SettingsFlags.RegexHistory); - } - } - } - - #endregion - - #region Filter-Highlight - - [SupportedOSPlatform("windows")] - private void OnToggleHighlightPanelButtonClick (object sender, EventArgs e) - { - ToggleHighlightPanel(highlightSplitContainer.Panel2Collapsed); - } - - private void OnSaveFilterButtonClick (object sender, EventArgs e) - { - var newParams = _filterParams.Clone(); - newParams.Color = Color.FromKnownColor(KnownColor.Black); - ConfigManager.Settings.FilterList.Add(newParams); - OnFilterListChanged(this); - } - - [SupportedOSPlatform("windows")] - private void OnDeleteFilterButtonClick (object sender, EventArgs e) - { - var index = filterListBox.SelectedIndex; - if (index >= 0) - { - var filterParams = (FilterParams)filterListBox.Items[index]; - ConfigManager.Settings.FilterList.Remove(filterParams); - OnFilterListChanged(this); - if (filterListBox.Items.Count > 0) - { - filterListBox.SelectedIndex = filterListBox.Items.Count - 1; - } - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterUpButtonClick (object sender, EventArgs e) - { - var i = filterListBox.SelectedIndex; - if (i > 0) - { - var filterParams = (FilterParams)filterListBox.Items[i]; - ConfigManager.Settings.FilterList.RemoveAt(i); - i--; - ConfigManager.Settings.FilterList.Insert(i, filterParams); - OnFilterListChanged(this); - filterListBox.SelectedIndex = i; - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterDownButtonClick (object sender, EventArgs e) - { - var i = filterListBox.SelectedIndex; - if (i < 0) - { - return; - } - - if (i < filterListBox.Items.Count - 1) - { - var filterParams = (FilterParams)filterListBox.Items[i]; - ConfigManager.Settings.FilterList.RemoveAt(i); - i++; - ConfigManager.Settings.FilterList.Insert(i, filterParams); - OnFilterListChanged(this); - filterListBox.SelectedIndex = i; - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterListBoxMouseDoubleClick (object sender, MouseEventArgs e) - { - if (filterListBox.SelectedIndex >= 0) - { - var filterParams = (FilterParams)filterListBox.Items[filterListBox.SelectedIndex]; - var newParams = filterParams.Clone(); - //newParams.historyList = ConfigManager.Settings.filterHistoryList; - _filterParams = newParams; - ReInitFilterParams(_filterParams); - ApplyFilterParams(); - CheckForAdvancedButtonDirty(); - CheckForFilterDirty(); - filterSearchButton.Image = _searchButtonImage; - saveFilterButton.Enabled = false; - if (hideFilterListOnLoadCheckBox.Checked) - { - ToggleHighlightPanel(false); - } - - if (filterOnLoadCheckBox.Checked) - { - FilterSearch(); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterListBoxDrawItem (object sender, DrawItemEventArgs e) - { - e.DrawBackground(); - if (e.Index >= 0) - { - var filterParams = (FilterParams)filterListBox.Items[e.Index]; - Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - - Brush brush; - - if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) - { - brush = new SolidBrush(filterListBox.BackColor); - } - else - { - brush = new SolidBrush(filterParams.Color); - } - - e.Graphics.DrawString(filterParams.SearchText, e.Font, brush, - new PointF(rectangle.Left, rectangle.Top)); - e.DrawFocusRectangle(); - brush.Dispose(); - } - } - - [SupportedOSPlatform("windows")] - // Color for filter list entry - private void OnColorToolStripMenuItemClick (object sender, EventArgs e) - { - var i = filterListBox.SelectedIndex; - if (i < filterListBox.Items.Count && i >= 0) - { - var filterParams = (FilterParams)filterListBox.Items[i]; - ColorDialog dlg = new() - { - CustomColors = [filterParams.Color.ToArgb()], - Color = filterParams.Color - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - filterParams.Color = dlg.Color; - filterListBox.Refresh(); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnFilterCaseSensitiveCheckBoxCheckedChanged (object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterRegexCheckBoxCheckedChanged (object sender, EventArgs e) - { - fuzzyKnobControl.Enabled = !filterRegexCheckBox.Checked; - fuzzyLabel.Enabled = !filterRegexCheckBox.Checked; - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnInvertFilterCheckBoxCheckedChanged (object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterRangeComboBoxTextChanged (object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnFuzzyKnobControlValueChanged (object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterComboBoxTextChanged (object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - [SupportedOSPlatform("windows")] - private void OnSetBookmarksOnSelectedLinesToolStripMenuItemClick (object sender, EventArgs e) - { - SetBookmarksForSelectedFilterLines(); - } - - private void OnParentHighlightSettingsChanged (object sender, EventArgs e) - { - var groupName = _guiStateArgs.HighlightGroupName; - SetCurrentHighlightGroup(groupName); - } - - [SupportedOSPlatform("windows")] - private void OnFilterOnLoadCheckBoxMouseClick (object sender, MouseEventArgs e) - { - HandleChangedFilterOnLoadSetting(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterOnLoadCheckBoxKeyPress (object sender, KeyPressEventArgs e) - { - HandleChangedFilterOnLoadSetting(); - } - - [SupportedOSPlatform("windows")] - private void OnHideFilterListOnLoadCheckBoxMouseClick (object sender, MouseEventArgs e) - { - HandleChangedFilterOnLoadSetting(); - } - - [SupportedOSPlatform("windows")] - private void OnFilterToTabToolStripMenuItemClick (object sender, EventArgs e) - { - FilterToTab(); - } - - private void OnTimeSyncListWindowRemoved (object sender, EventArgs e) - { - var syncList = sender as TimeSyncList; - lock (_timeSyncListLock) - { - if (syncList.Count == 0 || (syncList.Count == 1 && syncList.Contains(this))) - { - if (syncList == TimeSyncList) - { - TimeSyncList = null; - OnSyncModeChanged(); - } - } - } - } - - private void OnFreeThisWindowFromTimeSyncToolStripMenuItemClick (object sender, EventArgs e) - { - FreeFromTimeSync(); - } - - [SupportedOSPlatform("windows")] - private void OnSplitContainerSplitterMoved (object sender, SplitterEventArgs e) - { - advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; - } - - [SupportedOSPlatform("windows")] - private void OnMarkFilterHitsInLogViewToolStripMenuItemClick (object sender, EventArgs e) - { - SearchParams p = new() - { - SearchText = _filterParams.SearchText, - IsRegex = _filterParams.IsRegex, - IsCaseSensitive = _filterParams.IsCaseSensitive - }; - - AddSearchHitHighlightEntry(p); - } - - [SupportedOSPlatform("windows")] - private void OnColumnComboBoxSelectionChangeCommitted (object sender, EventArgs e) - { - SelectColumn(); - } - - [SupportedOSPlatform("windows")] - private void OnColumnComboBoxKeyDown (object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) - { - SelectColumn(); - dataGridView.Focus(); - } - } - - [SupportedOSPlatform("windows")] - private void OnColumnComboBoxPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) - { - if (e.KeyCode == Keys.Down && e.Modifiers == Keys.Alt) - { - columnComboBox.DroppedDown = true; - } - - if (e.KeyCode == Keys.Enter) - { - e.IsInputKey = true; - } - } - - [SupportedOSPlatform("windows")] - private void OnBookmarkProviderBookmarkRemoved (object sender, EventArgs e) - { - if (!_isLoading) - { - dataGridView.Refresh(); - filterGridView.Refresh(); - } - } - - [SupportedOSPlatform("windows")] - private void OnBookmarkProviderBookmarkAdded (object sender, EventArgs e) - { - if (!_isLoading) - { - dataGridView.Refresh(); - filterGridView.Refresh(); - } - } - - private void OnBookmarkProviderAllBookmarksRemoved (object sender, EventArgs e) - { - // nothing - } - - private void OnLogWindowLeave (object sender, EventArgs e) - { - InvalidateCurrentRow(); - } - - private void OnLogWindowEnter (object sender, EventArgs e) - { - InvalidateCurrentRow(); - } - - [SupportedOSPlatform("windows")] - private void OnDataGridViewRowUnshared (object sender, DataGridViewRowEventArgs e) - { - if (_logger.IsTraceEnabled) - { - _logger.Trace($"Row unshared line {e.Row.Cells[1].Value}"); - } - } - - #endregion - - #endregion - - #endregion - - [SupportedOSPlatform("windows")] - private void MeasureItem (object sender, MeasureItemEventArgs e) - { - e.ItemHeight = filterListBox.Font.Height; - } -} diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.resx b/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.resx deleted file mode 100644 index 1af7de15..00000000 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowEventHandlers.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs deleted file mode 100644 index cbfd9828..00000000 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPrivate.cs +++ /dev/null @@ -1,3820 +0,0 @@ -using System.Globalization; -using System.Runtime.Versioning; -using System.Text; -using System.Text.RegularExpressions; - -using LogExpert.Classes.Filter; -using LogExpert.Core.Callback; -using LogExpert.Core.Classes; -using LogExpert.Core.Classes.Columnizer; -using LogExpert.Core.Classes.Filter; -using LogExpert.Core.Classes.Highlight; -using LogExpert.Core.Classes.Persister; -using LogExpert.Core.Config; -using LogExpert.Core.Entities; -using LogExpert.Core.EventArguments; -using LogExpert.Dialogs; -using LogExpert.Extensions; -using LogExpert.UI.Entities; - -namespace LogExpert.UI.Controls.LogWindow; - -partial class LogWindow -{ - #region Private Methods - - [SupportedOSPlatform("windows")] - private void RegisterLogFileReaderEvents () - { - _logFileReader.LoadFile += OnLogFileReaderLoadFile; - _logFileReader.LoadingFinished += OnLogFileReaderFinishedLoading; - _logFileReader.LoadingStarted += OnLogFileReaderLoadingStarted; - _logFileReader.FileNotFound += OnLogFileReaderFileNotFound; - _logFileReader.Respawned += OnLogFileReaderRespawned; - // FileSizeChanged is not registered here because it's registered after loading has finished - } - - [SupportedOSPlatform("windows")] - private void UnRegisterLogFileReaderEvents () - { - if (_logFileReader != null) - { - _logFileReader.LoadFile -= OnLogFileReaderLoadFile; - _logFileReader.LoadingFinished -= OnLogFileReaderFinishedLoading; - _logFileReader.LoadingStarted -= OnLogFileReaderLoadingStarted; - _logFileReader.FileNotFound -= OnLogFileReaderFileNotFound; - _logFileReader.Respawned -= OnLogFileReaderRespawned; - _logFileReader.FileSizeChanged -= OnFileSizeChanged; - } - } - - [SupportedOSPlatform("windows")] - private void CreateDefaultViewStyle () - { - DataGridViewCellStyle dataGridViewCellStyleMainGrid = new(); - DataGridViewCellStyle dataGridViewCellStyleFilterGrid = new(); - - dataGridViewCellStyleMainGrid.Alignment = DataGridViewContentAlignment.MiddleLeft; - dataGridViewCellStyleMainGrid.BackColor = SystemColors.Window; - dataGridViewCellStyleMainGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - dataGridViewCellStyleMainGrid.ForeColor = SystemColors.ControlText; - dataGridViewCellStyleMainGrid.SelectionBackColor = SystemColors.Highlight; - //dataGridViewCellStyleMainGrid.SelectionForeColor = SystemColors.HighlightText; - - var highlightColor = SystemColors.Highlight; - //Color is smaller than 128, means its darker - var isSelectionBackColorDark = (highlightColor.R * 0.2126) + (highlightColor.G * 0.7152) + (highlightColor.B * 0.0722) < 255 / 2; - - if (isSelectionBackColorDark) - { - dataGridViewCellStyleMainGrid.SelectionForeColor = Color.White; - } - else - { - dataGridViewCellStyleMainGrid.SelectionForeColor = Color.Black; - - } - - dataGridViewCellStyleMainGrid.WrapMode = DataGridViewTriState.False; - dataGridView.DefaultCellStyle = dataGridViewCellStyleMainGrid; - - dataGridViewCellStyleFilterGrid.Alignment = DataGridViewContentAlignment.MiddleLeft; - dataGridViewCellStyleFilterGrid.BackColor = SystemColors.Window; - dataGridViewCellStyleFilterGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - dataGridViewCellStyleFilterGrid.ForeColor = SystemColors.ControlText; - dataGridViewCellStyleFilterGrid.SelectionBackColor = SystemColors.Highlight; - //dataGridViewCellStyleFilterGrid.SelectionForeColor = SystemColors.HighlightText; - - if (isSelectionBackColorDark) - { - dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.White; - } - else - { - dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.Black; - } - - dataGridViewCellStyleFilterGrid.WrapMode = DataGridViewTriState.False; - filterGridView.DefaultCellStyle = dataGridViewCellStyleFilterGrid; - } - - [SupportedOSPlatform("windows")] - private bool LoadPersistenceOptions () - { - if (InvokeRequired) - { - return (bool)Invoke(new BoolReturnDelegate(LoadPersistenceOptions)); - } - - if (!Preferences.SaveSessions && ForcedPersistenceFileName == null) - { - return false; - } - - try - { - var persistenceData = ForcedPersistenceFileName == null - ? Persister.LoadPersistenceDataOptionsOnly(FileName, Preferences) - : Persister.LoadPersistenceDataOptionsOnlyFromFixedFile(ForcedPersistenceFileName); - - if (persistenceData == null) - { - _logger.Info($"No persistence data for {FileName} found."); - return false; - } - - IsMultiFile = persistenceData.MultiFile; - _multiFileOptions = new MultiFileOptions - { - FormatPattern = persistenceData.MultiFilePattern, - MaxDayTry = persistenceData.MultiFileMaxDays - }; - - if (string.IsNullOrEmpty(_multiFileOptions.FormatPattern)) - { - _multiFileOptions = ObjectClone.Clone(Preferences.MultiFileOptions); - } - - splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; - splitContainerLogWindow.Panel2Collapsed = !persistenceData.FilterVisible; - ToggleHighlightPanel(persistenceData.FilterSaveListVisible); - ShowAdvancedFilterPanel(persistenceData.FilterAdvanced); - - if (_reloadMemento == null) - { - PreselectColumnizer(persistenceData.ColumnizerName); - } - - FollowTailChanged(persistenceData.FollowTail, false); - if (persistenceData.TabName != null) - { - Text = persistenceData.TabName; - } - - AdjustHighlightSplitterWidth(); - SetCurrentHighlightGroup(persistenceData.HighlightGroupName); - - if (persistenceData.MultiFileNames.Count > 0) - { - _logger.Info(CultureInfo.InvariantCulture, "Detected MultiFile name list in persistence options"); - _fileNames = new string[persistenceData.MultiFileNames.Count]; - persistenceData.MultiFileNames.CopyTo(_fileNames); - } - else - { - _fileNames = null; - } - - //this.bookmarkWindow.ShowBookmarkCommentColumn = persistenceData.showBookmarkCommentColumn; - SetExplicitEncoding(persistenceData.Encoding); - return true; - } - catch (Exception ex) - { - _logger.Error(ex, "Error loading persistence data: "); - return false; - } - } - - [SupportedOSPlatform("windows")] - private void SetDefaultsFromPrefs () - { - filterTailCheckBox.Checked = Preferences.FilterTail; - syncFilterCheckBox.Checked = Preferences.FilterSync; - FollowTailChanged(Preferences.FollowTail, false); - _multiFileOptions = ObjectClone.Clone(Preferences.MultiFileOptions); - } - - [SupportedOSPlatform("windows")] - private void LoadPersistenceData () - { - if (InvokeRequired) - { - Invoke(new MethodInvoker(LoadPersistenceData)); - return; - } - - if (!Preferences.SaveSessions && !ForcePersistenceLoading && ForcedPersistenceFileName == null) - { - SetDefaultsFromPrefs(); - return; - } - - if (IsTempFile) - { - SetDefaultsFromPrefs(); - return; - } - - ForcePersistenceLoading = false; // force only 1 time (while session load) - - try - { - var persistenceData = ForcedPersistenceFileName == null - ? Persister.LoadPersistenceData(FileName, Preferences) - : Persister.LoadPersistenceDataFromFixedFile(ForcedPersistenceFileName); - - if (persistenceData.LineCount > _logFileReader.LineCount) - { - // outdated persistence data (logfile rollover) - // MessageBox.Show(this, "Persistence data for " + this.FileName + " is outdated. It was discarded.", "Log Expert"); - _logger.Info($"Persistence data for {FileName} is outdated. It was discarded."); - _ = LoadPersistenceOptions(); - return; - } - - _bookmarkProvider.SetBookmarks(persistenceData.BookmarkList); - _rowHeightList = persistenceData.RowHeightList; - try - { - if (persistenceData.CurrentLine >= 0 && persistenceData.CurrentLine < dataGridView.RowCount) - { - SelectLine(persistenceData.CurrentLine, false, true); - } - else - { - if (_logFileReader.LineCount > 0) - { - dataGridView.FirstDisplayedScrollingRowIndex = _logFileReader.LineCount - 1; - SelectLine(_logFileReader.LineCount - 1, false, true); - } - } - - if (persistenceData.FirstDisplayedLine >= 0 && - persistenceData.FirstDisplayedLine < dataGridView.RowCount) - { - dataGridView.FirstDisplayedScrollingRowIndex = persistenceData.FirstDisplayedLine; - } - - if (persistenceData.FollowTail) - { - FollowTailChanged(persistenceData.FollowTail, false); - } - } - catch (ArgumentOutOfRangeException) - { - // FirstDisplayedScrollingRowIndex calculates sometimes the wrong scrolling ranges??? - } - - if (Preferences.SaveFilters) - { - RestoreFilters(persistenceData); - } - } - catch (IOException ex) - { - SetDefaultsFromPrefs(); - _logger.Error(ex, "Error loading bookmarks: "); - } - } - - [SupportedOSPlatform("windows")] - private void RestoreFilters (PersistenceData persistenceData) - { - if (persistenceData.FilterParamsList.Count > 0) - { - _filterParams = persistenceData.FilterParamsList[0]; - ReInitFilterParams(_filterParams); - } - - ApplyFilterParams(); // re-loaded filter settingss - BeginInvoke(new MethodInvoker(FilterSearch)); - try - { - splitContainerLogWindow.SplitterDistance = persistenceData.FilterPosition; - splitContainerLogWindow.Panel2Collapsed = !persistenceData.FilterVisible; - } - catch (InvalidOperationException e) - { - _logger.Error(e, "Error setting splitter distance: "); - } - - ShowAdvancedFilterPanel(persistenceData.FilterAdvanced); - if (_filterPipeList.Count == 0) // don't restore if it's only a reload - { - RestoreFilterTabs(persistenceData); - } - } - - private void RestoreFilterTabs (PersistenceData persistenceData) - { - foreach (var data in persistenceData.FilterTabDataList) - { - var persistFilterParams = data.FilterParams; - ReInitFilterParams(persistFilterParams); - List filterResultList = []; - //List lastFilterResultList = new List(); - List filterHitList = []; - Filter(persistFilterParams, filterResultList, _lastFilterLinesList, filterHitList); - FilterPipe pipe = new(persistFilterParams.Clone(), this); - WritePipeToTab(pipe, filterResultList, data.PersistenceData.TabName, data.PersistenceData); - } - } - - private void ReInitFilterParams (FilterParams filterParams) - { - filterParams.SearchText = filterParams.SearchText; // init "lowerSearchText" - filterParams.RangeSearchText = filterParams.RangeSearchText; // init "lowerRangesearchText" - filterParams.CurrentColumnizer = CurrentColumnizer; - if (filterParams.IsRegex) - { - try - { - filterParams.CreateRegex(); - } - catch (ArgumentException) - { - StatusLineError("Invalid regular expression"); - } - } - } - - private void EnterLoadFileStatus () - { - _logger.Debug(CultureInfo.InvariantCulture, "EnterLoadFileStatus begin"); - - if (InvokeRequired) - { - Invoke(new MethodInvoker(EnterLoadFileStatus)); - return; - } - - _statusEventArgs.StatusText = "Loading file..."; - _statusEventArgs.LineCount = 0; - _statusEventArgs.FileSize = 0; - SendStatusLineUpdate(); - - _progressEventArgs.MinValue = 0; - _progressEventArgs.MaxValue = 0; - _progressEventArgs.Value = 0; - _progressEventArgs.Visible = true; - SendProgressBarUpdate(); - - _isLoading = true; - _shouldCancel = true; - ClearFilterList(); - ClearBookmarkList(); - dataGridView.ClearSelection(); - dataGridView.RowCount = 0; - _logger.Debug(CultureInfo.InvariantCulture, "EnterLoadFileStatus end"); - } - - [SupportedOSPlatform("windows")] - private void PositionAfterReload (ReloadMemento reloadMemento) - { - if (_reloadMemento.CurrentLine < dataGridView.RowCount && _reloadMemento.CurrentLine >= 0) - { - dataGridView.CurrentCell = dataGridView.Rows[_reloadMemento.CurrentLine].Cells[0]; - } - - if (_reloadMemento.FirstDisplayedLine < dataGridView.RowCount && _reloadMemento.FirstDisplayedLine >= 0) - { - dataGridView.FirstDisplayedScrollingRowIndex = _reloadMemento.FirstDisplayedLine; - } - } - - [SupportedOSPlatform("windows")] - private void LogfileDead () - { - _logger.Info(CultureInfo.InvariantCulture, "File not found."); - _isDeadFile = true; - - //this.logFileReader.FileSizeChanged -= this.FileSizeChangedHandler; - //if (this.logFileReader != null) - // this.logFileReader.stopMonitoring(); - - dataGridView.Enabled = false; - dataGridView.RowCount = 0; - _progressEventArgs.Visible = false; - _progressEventArgs.Value = _progressEventArgs.MaxValue; - SendProgressBarUpdate(); - _statusEventArgs.FileSize = 0; - _statusEventArgs.LineCount = 0; - _statusEventArgs.CurrentLineNum = 0; - SendStatusLineUpdate(); - _shouldCancel = true; - ClearFilterList(); - ClearBookmarkList(); - - StatusLineText("File not found"); - OnFileNotFound(EventArgs.Empty); - } - - [SupportedOSPlatform("windows")] - private void LogfileRespawned () - { - _logger.Info(CultureInfo.InvariantCulture, "LogfileDead(): Reloading file because it has been respawned."); - _isDeadFile = false; - dataGridView.Enabled = true; - StatusLineText(""); - OnFileRespawned(EventArgs.Empty); - Reload(); - } - - [SupportedOSPlatform("windows")] - private void SetGuiAfterLoading () - { - if (Text.Length == 0) - { - Text = IsTempFile - ? TempTitleName - : Util.GetNameFromPath(FileName); - } - - ShowBookmarkBubbles = Preferences.ShowBubbles; - //if (this.forcedColumnizer == null) - { - ILogLineColumnizer columnizer; - if (_forcedColumnizerForLoading != null) - { - columnizer = _forcedColumnizerForLoading; - _forcedColumnizerForLoading = null; - } - else - { - columnizer = FindColumnizer(); - if (columnizer != null) - { - if (_reloadMemento == null) - { - //TODO this needs to be refactored - var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - - columnizer = ColumnizerPicker.CloneColumnizer(columnizer, directory); - } - } - else - { - //TODO this needs to be refactored - var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - - // Default Columnizers - columnizer = ColumnizerPicker.CloneColumnizer(ColumnizerPicker.FindColumnizer(FileName, _logFileReader, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers), directory); - } - } - - Invoke(new SetColumnizerFx(SetColumnizer), columnizer); - } - - dataGridView.Enabled = true; - DisplayCurrentFileOnStatusline(); - //this.guiStateArgs.FollowTail = this.Preferences.followTail; - _guiStateArgs.MultiFileEnabled = !IsTempFile; - _guiStateArgs.MenuEnabled = true; - _guiStateArgs.CurrentEncoding = _logFileReader.CurrentEncoding; - SendGuiStateUpdate(); - //if (this.dataGridView.RowCount > 0) - // SelectLine(this.dataGridView.RowCount - 1); - //if (this.dataGridView.Columns.Count > 1) - //{ - // this.dataGridView.Columns[this.dataGridView.Columns.Count-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; - // this.dataGridView.Columns[this.dataGridView.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - // AdjustMinimumGridWith(); - //} - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - if (Preferences.TimestampControl) - { - SetTimestampLimits(); - SyncTimestampDisplay(); - } - - var settings = ConfigManager.Settings; - ShowLineColumn(!settings.HideLineColumn); - } - - ShowTimeSpread(Preferences.ShowTimeSpread && CurrentColumnizer.IsTimeshiftImplemented()); - locateLineInOriginalFileToolStripMenuItem.Enabled = FilterPipe != null; - } - - private ILogLineColumnizer FindColumnizer () - { - var columnizer = Preferences.MaskPrio - ? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)) ?? _parentLogTabWin.GetColumnizerHistoryEntry(FileName) - : _parentLogTabWin.GetColumnizerHistoryEntry(FileName) ?? _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)); - - return columnizer; - } - - private void ReloadNewFile () - { - // prevent "overloads". May occur on very fast rollovers (next rollover before the file is reloaded) - lock (_reloadLock) - { - _reloadOverloadCounter++; - _logger.Info($"ReloadNewFile(): counter = {_reloadOverloadCounter}"); - if (_reloadOverloadCounter <= 1) - { - SavePersistenceData(false); - _loadingFinishedEvent.Reset(); - _externaLoadingFinishedEvent.Reset(); - Thread reloadFinishedThread = new(ReloadFinishedThreadFx) - { - IsBackground = true - }; - reloadFinishedThread.Start(); - LoadFile(FileName, EncodingOptions); - - ClearBookmarkList(); - SavePersistenceData(false); - - //if (this.filterTailCheckBox.Checked) - //{ - // _logger.logDebug("Waiting for loading to be complete."); - // loadingFinishedEvent.WaitOne(); - // _logger.logDebug("Refreshing filter view because of reload."); - // FilterSearch(); - //} - //LoadFilterPipes(); - } - else - { - _logger.Debug(CultureInfo.InvariantCulture, "Preventing reload because of recursive calls."); - } - - _reloadOverloadCounter--; - } - } - - [SupportedOSPlatform("windows")] - private void ReloadFinishedThreadFx () - { - _logger.Info(CultureInfo.InvariantCulture, "Waiting for loading to be complete."); - _loadingFinishedEvent.WaitOne(); - _logger.Info(CultureInfo.InvariantCulture, "Refreshing filter view because of reload."); - Invoke(new MethodInvoker(FilterSearch)); - LoadFilterPipes(); - } - - private void UpdateProgress (LoadFileEventArgs e) - { - try - { - if (e.ReadPos >= e.FileSize) - { - //_logger.Warn(CultureInfo.InvariantCulture, "UpdateProgress(): ReadPos (" + e.ReadPos + ") is greater than file size (" + e.FileSize + "). Aborting Update"); - return; - } - - _statusEventArgs.FileSize = e.ReadPos; - //this.progressEventArgs.Visible = true; - _progressEventArgs.MaxValue = (int)e.FileSize; - _progressEventArgs.Value = (int)e.ReadPos; - SendProgressBarUpdate(); - SendStatusLineUpdate(); - } - catch (Exception ex) - { - _logger.Error(ex, "UpdateProgress(): "); - } - } - - private void LoadingStarted (LoadFileEventArgs e) - { - try - { - _statusEventArgs.FileSize = e.ReadPos; - _statusEventArgs.StatusText = "Loading " + Util.GetNameFromPath(e.FileName); - _progressEventArgs.Visible = true; - _progressEventArgs.MaxValue = (int)e.FileSize; - _progressEventArgs.Value = (int)e.ReadPos; - SendProgressBarUpdate(); - SendStatusLineUpdate(); - } - catch (Exception ex) - { - _logger.Error(ex, "LoadingStarted(): "); - } - } - - private void LoadingFinished () - { - _logger.Info(CultureInfo.InvariantCulture, "File loading complete."); - - StatusLineText(""); - _logFileReader.FileSizeChanged += OnFileSizeChanged; - _isLoading = false; - _shouldCancel = false; - dataGridView.SuspendLayout(); - dataGridView.RowCount = _logFileReader.LineCount; - dataGridView.CurrentCellChanged += OnDataGridViewCurrentCellChanged; - dataGridView.Enabled = true; - dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - dataGridView.ResumeLayout(); - _progressEventArgs.Visible = false; - _progressEventArgs.Value = _progressEventArgs.MaxValue; - SendProgressBarUpdate(); - //if (this.logFileReader.LineCount > 0) - //{ - // this.dataGridView.FirstDisplayedScrollingRowIndex = this.logFileReader.LineCount - 1; - // SelectLine(this.logFileReader.LineCount - 1); - //} - _guiStateArgs.FollowTail = true; - SendGuiStateUpdate(); - _statusEventArgs.LineCount = _logFileReader.LineCount; - _statusEventArgs.FileSize = _logFileReader.FileSize; - SendStatusLineUpdate(); - - var setLastColumnWidth = _parentLogTabWin.Preferences.SetLastColumnWidth; - var lastColumnWidth = _parentLogTabWin.Preferences.LastColumnWidth; - var fontName = _parentLogTabWin.Preferences.FontName; - var fontSize = _parentLogTabWin.Preferences.FontSize; - - PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, true, SettingsFlags.All); - //LoadPersistenceData(); - } - - private void LogEventWorker () - { - Thread.CurrentThread.Name = "LogEventWorker"; - while (true) - { - _logger.Debug(CultureInfo.InvariantCulture, "Waiting for signal"); - _logEventArgsEvent.WaitOne(); - _logger.Debug(CultureInfo.InvariantCulture, "Wakeup signal received."); - while (true) - { - LogEventArgs e; - var lastLineCount = 0; - lock (_logEventArgsList) - { - _logger.Info(CultureInfo.InvariantCulture, "{0} events in queue", _logEventArgsList.Count); - if (_logEventArgsList.Count == 0) - { - _logEventArgsEvent.Reset(); - break; - } - - e = _logEventArgsList[0]; - _logEventArgsList.RemoveAt(0); - } - - if (e.IsRollover) - { - ShiftBookmarks(e.RolloverOffset); - ShiftRowHeightList(e.RolloverOffset); - ShiftFilterPipes(e.RolloverOffset); - lastLineCount = 0; - } - else - { - if (e.LineCount < lastLineCount) - { - _logger.Error("Line count of event is: {0}, should be greater than last line count: {1}", e.LineCount, lastLineCount); - } - } - - Invoke(UpdateGrid, [e]); - CheckFilterAndHighlight(e); - _timeSpreadCalc.SetLineCount(e.LineCount); - } - } - } - - private void StopLogEventWorkerThread () - { - _logEventArgsEvent.Set(); - cts.Cancel(); - //_logEventHandlerThread.Abort(); - //_logEventHandlerThread.Join(); - } - - private void OnFileSizeChanged (LogEventArgs e) - { - FileSizeChanged?.Invoke(this, e); - } - - private void UpdateGrid (LogEventArgs e) - { - var oldRowCount = dataGridView.RowCount; - var firstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex; - - if (dataGridView.CurrentCellAddress.Y >= e.LineCount) - { - //this.dataGridView.Rows[this.dataGridView.CurrentCellAddress.Y].Selected = false; - //this.dataGridView.CurrentCell = this.dataGridView.Rows[0].Cells[0]; - } - - try - { - if (dataGridView.RowCount > e.LineCount) - { - var currentLineNum = dataGridView.CurrentCellAddress.Y; - dataGridView.RowCount = 0; - dataGridView.RowCount = e.LineCount; - if (_guiStateArgs.FollowTail == false) - { - if (currentLineNum >= dataGridView.RowCount) - { - currentLineNum = dataGridView.RowCount - 1; - } - - dataGridView.CurrentCell = dataGridView.Rows[currentLineNum].Cells[0]; - } - } - else - { - dataGridView.RowCount = e.LineCount; - } - - _logger.Debug(CultureInfo.InvariantCulture, "UpdateGrid(): new RowCount={0}", dataGridView.RowCount); - - if (e.IsRollover) - { - // Multifile rollover - // keep selection and view range, if no follow tail mode - if (!_guiStateArgs.FollowTail) - { - var currentLineNum = dataGridView.CurrentCellAddress.Y; - currentLineNum -= e.RolloverOffset; - if (currentLineNum < 0) - { - currentLineNum = 0; - } - - _logger.Debug(CultureInfo.InvariantCulture, "UpdateGrid(): Rollover=true, Rollover offset={0}, currLineNum was {1}, new currLineNum={2}", e.RolloverOffset, dataGridView.CurrentCellAddress.Y, currentLineNum); - firstDisplayedLine -= e.RolloverOffset; - if (firstDisplayedLine < 0) - { - firstDisplayedLine = 0; - } - - dataGridView.FirstDisplayedScrollingRowIndex = firstDisplayedLine; - dataGridView.CurrentCell = dataGridView.Rows[currentLineNum].Cells[0]; - dataGridView.Rows[currentLineNum].Selected = true; - } - } - - _statusEventArgs.LineCount = e.LineCount; - StatusLineFileSize(e.FileSize); - - if (!_isLoading) - { - if (oldRowCount == 0) - { - AdjustMinimumGridWith(); - } - - //CheckFilterAndHighlight(e); - } - - if (_guiStateArgs.FollowTail && dataGridView.RowCount > 0) - { - dataGridView.FirstDisplayedScrollingRowIndex = dataGridView.RowCount - 1; - OnTailFollowed(EventArgs.Empty); - } - - if (Preferences.TimestampControl && !_isLoading) - { - SetTimestampLimits(); - } - } - catch (Exception ex) - { - _logger.Error(ex, "Fehler bei UpdateGrid(): "); - } - - //this.dataGridView.Refresh(); - //this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - } - - private void CheckFilterAndHighlight (LogEventArgs e) - { - var noLed = true; - bool suppressLed; - bool setBookmark; - bool stopTail; - string bookmarkComment; - - if (filterTailCheckBox.Checked || _filterPipeList.Count > 0) - { - var filterStart = e.PrevLineCount; - if (e.IsRollover) - { - ShiftFilterLines(e.RolloverOffset); - filterStart -= e.RolloverOffset; - } - - var firstStopTail = true; - ColumnizerCallback callback = new(this); - var filterLineAdded = false; - for (var i = filterStart; i < e.LineCount; ++i) - { - var line = _logFileReader.GetLogLine(i); - if (line == null) - { - return; - } - - if (filterTailCheckBox.Checked) - { - callback.SetLineNum(i); - if (Util.TestFilterCondition(_filterParams, line, callback)) - { - //AddFilterLineFx addFx = new AddFilterLineFx(AddFilterLine); - //this.Invoke(addFx, new object[] { i, true }); - filterLineAdded = true; - AddFilterLine(i, false, _filterParams, _filterResultList, _lastFilterLinesList, - _filterHitList); - } - } - - //ProcessFilterPipeFx pipeFx = new ProcessFilterPipeFx(ProcessFilterPipes); - //pipeFx.BeginInvoke(i, null, null); - ProcessFilterPipes(i); - - var matchingList = FindMatchingHilightEntries(line); - LaunchHighlightPlugins(matchingList, i); - GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); - if (setBookmark) - { - SetBookmarkFx fx = SetBookmarkFromTrigger; - fx.BeginInvoke(i, bookmarkComment, null, null); - } - - if (stopTail && _guiStateArgs.FollowTail) - { - var wasFollow = _guiStateArgs.FollowTail; - FollowTailChanged(false, true); - if (firstStopTail && wasFollow) - { - Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); - firstStopTail = false; - } - } - - if (!suppressLed) - { - noLed = false; - } - } - - if (filterLineAdded) - { - //AddFilterLineGuiUpdateFx addFx = new AddFilterLineGuiUpdateFx(AddFilterLineGuiUpdate); - //this.Invoke(addFx); - TriggerFilterLineGuiUpdate(); - } - } - else - { - var firstStopTail = true; - var startLine = e.PrevLineCount; - if (e.IsRollover) - { - ShiftFilterLines(e.RolloverOffset); - startLine -= e.RolloverOffset; - } - - for (var i = startLine; i < e.LineCount; ++i) - { - var line = _logFileReader.GetLogLine(i); - if (line != null) - { - var matchingList = FindMatchingHilightEntries(line); - LaunchHighlightPlugins(matchingList, i); - GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, - out bookmarkComment); - if (setBookmark) - { - SetBookmarkFx fx = SetBookmarkFromTrigger; - fx.BeginInvoke(i, bookmarkComment, null, null); - } - - if (stopTail && _guiStateArgs.FollowTail) - { - var wasFollow = _guiStateArgs.FollowTail; - FollowTailChanged(false, true); - if (firstStopTail && wasFollow) - { - Invoke(new SelectLineFx(SelectAndEnsureVisible), [i, false]); - firstStopTail = false; - } - } - - if (!suppressLed) - { - noLed = false; - } - } - } - } - - if (!noLed) - { - OnFileSizeChanged(e); - } - } - - private void LaunchHighlightPlugins (IList matchingList, int lineNum) - { - LogExpertCallback callback = new(this) - { - LineNum = lineNum - }; - - foreach (var entry in matchingList) - { - if (entry.IsActionEntry && entry.ActionEntry.PluginName != null) - { - var plugin = PluginRegistry.PluginRegistry.Instance.FindKeywordActionPluginByName(entry.ActionEntry.PluginName); - if (plugin != null) - { - ActionPluginExecuteFx fx = plugin.Execute; - fx.BeginInvoke(entry.SearchText, entry.ActionEntry.ActionParam, callback, CurrentColumnizer, null, null); - } - } - } - } - - private void PreSelectColumnizer (ILogLineColumnizer columnizer) - { - CurrentColumnizer = columnizer != null - ? (_forcedColumnizerForLoading = columnizer) - : (_forcedColumnizerForLoading = ColumnizerPicker.FindColumnizer(FileName, _logFileReader, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers)); - } - - private void SetColumnizer (ILogLineColumnizer columnizer) - { - columnizer = ColumnizerPicker.FindReplacementForAutoColumnizer(FileName, _logFileReader, columnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - - var timeDiff = 0; - if (CurrentColumnizer != null && CurrentColumnizer.IsTimeshiftImplemented()) - { - timeDiff = CurrentColumnizer.GetTimeOffset(); - } - - SetColumnizerInternal(columnizer); - - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - CurrentColumnizer.SetTimeOffset(timeDiff); - } - } - - private void SetColumnizerInternal (ILogLineColumnizer columnizer) - { - _logger.Info(CultureInfo.InvariantCulture, "SetColumnizerInternal(): {0}", columnizer.GetName()); - - var oldColumnizer = CurrentColumnizer; - var oldColumnizerIsXmlType = CurrentColumnizer is ILogLineXmlColumnizer; - var oldColumnizerIsPreProcess = CurrentColumnizer is IPreProcessColumnizer; - var mustReload = false; - - // Check if the filtered columns disappeared, if so must refresh the UI - if (_filterParams.ColumnRestrict) - { - var newColumns = columnizer != null ? columnizer.GetColumnNames() : Array.Empty(); - var colChanged = false; - - if (dataGridView.ColumnCount - 2 == newColumns.Length) // two first columns are 'marker' and 'line number' - { - for (var i = 0; i < newColumns.Length; i++) - { - if (dataGridView.Columns[i].HeaderText != newColumns[i]) - { - colChanged = true; - break; // one change is sufficient - } - } - } - else - { - colChanged = true; - } - - if (colChanged) - { - // Update UI - columnNamesLabel.Text = CalculateColumnNames(_filterParams); - } - } - - var oldColType = _filterParams.CurrentColumnizer?.GetType(); - var newColType = columnizer?.GetType(); - - if (oldColType != newColType && _filterParams.ColumnRestrict && _filterParams.IsFilterTail) - { - _filterParams.ColumnList.Clear(); - } - - if (CurrentColumnizer == null || CurrentColumnizer.GetType() != columnizer.GetType()) - { - CurrentColumnizer = columnizer; - _freezeStateMap.Clear(); - if (_logFileReader != null) - { - if (CurrentColumnizer is IPreProcessColumnizer) - { - _logFileReader.PreProcessColumnizer = (IPreProcessColumnizer)CurrentColumnizer; - } - else - { - _logFileReader.PreProcessColumnizer = null; - } - } - - // always reload when choosing XML columnizers - if (_logFileReader != null && CurrentColumnizer is ILogLineXmlColumnizer) - { - //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() - mustReload = true; - } - - // Reload when choosing no XML columnizer but previous columnizer was XML - if (_logFileReader != null && !(CurrentColumnizer is ILogLineXmlColumnizer) && oldColumnizerIsXmlType) - { - _logFileReader.IsXmlMode = false; - //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() - mustReload = true; - } - - // Reload when previous columnizer was PreProcess and current is not, and vice versa. - // When the current columnizer is a preProcess columnizer, reload in every case. - if (CurrentColumnizer is IPreProcessColumnizer != oldColumnizerIsPreProcess || - CurrentColumnizer is IPreProcessColumnizer) - { - //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() - mustReload = true; - } - } - else - { - CurrentColumnizer = columnizer; - } - - (oldColumnizer as IInitColumnizer)?.DeSelected(new ColumnizerCallback(this)); - - (columnizer as IInitColumnizer)?.Selected(new ColumnizerCallback(this)); - - SetColumnizer(columnizer, dataGridView); - SetColumnizer(columnizer, filterGridView); - _patternWindow?.SetColumnizer(columnizer); - - _guiStateArgs.TimeshiftPossible = columnizer.IsTimeshiftImplemented(); - SendGuiStateUpdate(); - - if (_logFileReader != null) - { - dataGridView.RowCount = _logFileReader.LineCount; - } - - if (_filterResultList != null) - { - filterGridView.RowCount = _filterResultList.Count; - } - - if (mustReload) - { - Reload(); - } - else - { - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - SetTimestampLimits(); - SyncTimestampDisplay(); - } - - var settings = ConfigManager.Settings; - ShowLineColumn(!settings.HideLineColumn); - ShowTimeSpread(Preferences.ShowTimeSpread && columnizer.IsTimeshiftImplemented()); - } - - if (!columnizer.IsTimeshiftImplemented() && IsTimeSynced) - { - FreeFromTimeSync(); - } - - columnComboBox.Items.Clear(); - - foreach (var columnName in columnizer.GetColumnNames()) - { - columnComboBox.Items.Add(columnName); - } - - columnComboBox.SelectedIndex = 0; - - OnColumnizerChanged(CurrentColumnizer); - } - - private void AutoResizeColumns (BufferedDataGridView gridView) - { - try - { - gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - if (gridView.Columns.Count > 1 && Preferences.SetLastColumnWidth && - gridView.Columns[gridView.Columns.Count - 1].Width < Preferences.LastColumnWidth - ) - { - // It seems that using 'MinimumWidth' instead of 'Width' prevents the DataGridView's NullReferenceExceptions - //gridView.Columns[gridView.Columns.Count - 1].Width = this.Preferences.lastColumnWidth; - gridView.Columns[gridView.Columns.Count - 1].MinimumWidth = Preferences.LastColumnWidth; - } - } - catch (NullReferenceException e) - { - // See https://connect.microsoft.com/VisualStudio/feedback/details/366943/autoresizecolumns-in-datagridview-throws-nullreferenceexception - // possible solution => https://stackoverflow.com/questions/36287553/nullreferenceexception-when-trying-to-set-datagridview-column-width-brings-th - // There are some rare situations with null ref exceptions when resizing columns and on filter finished - // So catch them here. Better than crashing. - _logger.Error(e, "Error while resizing columns: "); - } - } - - private void PaintCell (DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) - { - PaintHighlightedCell(e, gridView, noBackgroundFill, groundEntry); - } - - private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) - { - var column = e.Value as IColumn; - - column ??= Column.EmptyColumn; - - var matchList = FindHighlightMatches(column); - // too many entries per line seem to cause problems with the GDI - while (matchList.Count > 50) - { - matchList.RemoveAt(50); - } - - var he = new HighlightEntry - { - SearchText = column.DisplayValue, - ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), - BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, - IsWordMatch = true - }; - - HighlightMatchEntry hme = new() - { - StartPos = 0, - Length = column.DisplayValue.Length, - HighlightEntry = he - }; - - if (groundEntry != null) - { - hme.HighlightEntry.IsBold = groundEntry.IsBold; - } - - matchList = MergeHighlightMatchEntries(matchList, hme); - - //var leftPad = e.CellStyle.Padding.Left; - //RectangleF rect = new(e.CellBounds.Left + leftPad, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height); - - var borderWidths = PaintHelper.BorderWidths(e.AdvancedBorderStyle); - var valBounds = e.CellBounds; - valBounds.Offset(borderWidths.X, borderWidths.Y); - valBounds.Width -= borderWidths.Right; - valBounds.Height -= borderWidths.Bottom; - if (e.CellStyle.Padding != Padding.Empty) - { - valBounds.Offset(e.CellStyle.Padding.Left, e.CellStyle.Padding.Top); - valBounds.Width -= e.CellStyle.Padding.Horizontal; - valBounds.Height -= e.CellStyle.Padding.Vertical; - } - - var flags = - TextFormatFlags.Left - | TextFormatFlags.SingleLine - | TextFormatFlags.NoPrefix - | TextFormatFlags.PreserveGraphicsClipping - | TextFormatFlags.NoPadding - | TextFormatFlags.VerticalCenter - | TextFormatFlags.TextBoxControl - ; - - // | TextFormatFlags.VerticalCenter - // | TextFormatFlags.TextBoxControl - // TextFormatFlags.SingleLine - - //TextRenderer.DrawText(e.Graphics, e.Value as String, e.CellStyle.Font, valBounds, Color.FromKnownColor(KnownColor.Black), flags); - - var wordPos = valBounds.Location; - Size proposedSize = new(valBounds.Width, valBounds.Height); - - var r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); - e.Graphics.SetClip(e.CellBounds); - - foreach (var matchEntry in matchList) - { - var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? BoldFont : NormalFont; - - Brush bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty - ? new SolidBrush(matchEntry.HighlightEntry.BackgroundColor) - : null; - - var matchWord = column.DisplayValue.Substring(matchEntry.StartPos, matchEntry.Length); - var wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); - wordSize.Height = e.CellBounds.Height; - Rectangle wordRect = new(wordPos, wordSize); - - var foreColor = matchEntry.HighlightEntry.ForegroundColor; - if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) - { - if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) - { - e.Graphics.FillRectangle(bgBrush, wordRect); - } - } - - TextRenderer.DrawText(e.Graphics, matchWord, font, wordRect, foreColor, flags); - - wordPos.Offset(wordSize.Width, 0); - bgBrush?.Dispose(); - } - } - - /// - /// Builds a list of HilightMatchEntry objects. A HilightMatchEntry spans over a region that is painted with the same foreground and - /// background colors. - /// All regions which don't match a word-mode entry will be painted with the colors of a default entry (groundEntry). This is either the - /// first matching non-word-mode highlight entry or a black-on-white default (if no matching entry was found). - /// - /// List of all highlight matches for the current cell - /// The entry that is used as the default. - /// List of HighlightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. - private IList MergeHighlightMatchEntries (IList matchList, HighlightMatchEntry groundEntry) - { - // Fill an area with lenth of whole text with a default hilight entry - var entryArray = new HighlightEntry[groundEntry.Length]; - for (var i = 0; i < entryArray.Length; ++i) - { - entryArray[i] = groundEntry.HighlightEntry; - } - - // "overpaint" with all matching word match enries - // Non-word-mode matches will not overpaint because they use the groundEntry - foreach (var me in matchList) - { - var endPos = me.StartPos + me.Length; - for (var i = me.StartPos; i < endPos; ++i) - { - if (me.HighlightEntry.IsWordMatch) - { - entryArray[i] = me.HighlightEntry; - } - else - { - //entryArray[i].ForegroundColor = me.HilightEntry.ForegroundColor; - } - } - } - - // collect areas with same hilight entry and build new highlight match entries for it - IList mergedList = []; - - if (entryArray.Length > 0) - { - var currentEntry = entryArray[0]; - var lastStartPos = 0; - var pos = 0; - - for (; pos < entryArray.Length; ++pos) - { - if (entryArray[pos] != currentEntry) - { - HighlightMatchEntry me = new() - { - StartPos = lastStartPos, - Length = pos - lastStartPos, - HighlightEntry = currentEntry - }; - - mergedList.Add(me); - currentEntry = entryArray[pos]; - lastStartPos = pos; - } - } - - HighlightMatchEntry me2 = new() - { - StartPos = lastStartPos, - Length = pos - lastStartPos, - HighlightEntry = currentEntry - }; - - mergedList.Add(me2); - } - - return mergedList; - } - - /// - /// Returns the first HilightEntry that matches the given line - /// - private HighlightEntry FindHilightEntry (ITextValue line) - { - return FindHighlightEntry(line, false); - } - - private HighlightEntry FindFirstNoWordMatchHilightEntry (ITextValue line) - { - return FindHighlightEntry(line, true); - } - - private bool CheckHighlightEntryMatch (HighlightEntry entry, ITextValue column) - { - if (entry.IsRegEx) - { - //Regex rex = new Regex(entry.SearchText, entry.IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - if (entry.Regex.IsMatch(column.Text)) - { - return true; - } - } - else - { - if (entry.IsCaseSensitive) - { - if (column.Text.Contains(entry.SearchText, StringComparison.Ordinal)) - { - return true; - } - } - else - { - if (column.Text.ToUpperInvariant().Contains(entry.SearchText.ToUpperInvariant(), StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - } - - return false; - } - - /// - /// Returns all HilightEntry entries which matches the given line - /// - private IList FindMatchingHilightEntries (ITextValue line) - { - IList resultList = []; - if (line != null) - { - lock (_currentHighlightGroupLock) - { - foreach (var entry in _currentHighlightGroup.HighlightEntryList) - { - if (CheckHighlightEntryMatch(entry, line)) - { - resultList.Add(entry); - } - } - } - } - - return resultList; - } - - private void GetHighlightEntryMatches (ITextValue line, IList hilightEntryList, IList resultList) - { - foreach (var entry in hilightEntryList) - { - if (entry.IsWordMatch) - { - var matches = entry.Regex.Matches(line.Text); - foreach (Match match in matches) - { - HighlightMatchEntry me = new() - { - HighlightEntry = entry, - StartPos = match.Index, - Length = match.Length - }; - - resultList.Add(me); - } - } - else - { - if (CheckHighlightEntryMatch(entry, line)) - { - HighlightMatchEntry me = new() - { - HighlightEntry = entry, - StartPos = 0, - Length = line.Text.Length - }; - - resultList.Add(me); - } - } - } - } - - private void GetHilightActions (IList matchingList, out bool noLed, out bool stopTail, out bool setBookmark, out string bookmarkComment) - { - noLed = stopTail = setBookmark = false; - bookmarkComment = string.Empty; - - foreach (var entry in matchingList) - { - if (entry.IsLedSwitch) - { - noLed = true; - } - - if (entry.IsSetBookmark) - { - setBookmark = true; - if (!string.IsNullOrEmpty(entry.BookmarkComment)) - { - bookmarkComment += entry.BookmarkComment + "\r\n"; - } - } - - if (entry.IsStopTail) - { - stopTail = true; - } - } - - bookmarkComment = bookmarkComment.TrimEnd(['\r', '\n']); - } - - private void StopTimespreadThread () - { - _timeSpreadCalc.Stop(); - } - - private void StopTimestampSyncThread () - { - _shouldTimestampDisplaySyncingCancel = true; - //_timeShiftSyncWakeupEvent.Set(); - //_timeShiftSyncThread.Abort(); - //_timeShiftSyncThread.Join(); - cts.Cancel(); - } - - [SupportedOSPlatform("windows")] - private void SyncTimestampDisplay () - { - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - if (dataGridView.CurrentRow != null) - { - SyncTimestampDisplay(dataGridView.CurrentRow.Index); - } - } - } - - [SupportedOSPlatform("windows")] - private void SyncTimestampDisplay (int lineNum) - { - _timeShiftSyncLine = lineNum; - _timeShiftSyncTimerEvent.Set(); - _timeShiftSyncWakeupEvent.Set(); - } - - [SupportedOSPlatform("windows")] - private void SyncTimestampDisplayWorker () - { - const int WAIT_TIME = 500; - Thread.CurrentThread.Name = "SyncTimestampDisplayWorker"; - _shouldTimestampDisplaySyncingCancel = false; - _isTimestampDisplaySyncing = true; - - while (!_shouldTimestampDisplaySyncingCancel) - { - _timeShiftSyncWakeupEvent.WaitOne(); - if (_shouldTimestampDisplaySyncingCancel) - { - return; - } - - _timeShiftSyncWakeupEvent.Reset(); - - while (!_shouldTimestampDisplaySyncingCancel) - { - var signaled = _timeShiftSyncTimerEvent.WaitOne(WAIT_TIME, true); - _timeShiftSyncTimerEvent.Reset(); - if (!signaled) - { - break; - } - } - - // timeout with no new Trigger -> update display - var lineNum = _timeShiftSyncLine; - if (lineNum >= 0 && lineNum < dataGridView.RowCount) - { - var refLine = lineNum; - var timeStamp = GetTimestampForLine(ref refLine, true); - if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) - { - _guiStateArgs.Timestamp = timeStamp; - SendGuiStateUpdate(); - if (_shouldCallTimeSync) - { - refLine = lineNum; - var exactTimeStamp = GetTimestampForLine(ref refLine, false); - SyncOtherWindows(exactTimeStamp); - _shouldCallTimeSync = false; - } - } - } - - // show time difference between 2 selected lines - if (dataGridView.SelectedRows.Count == 2) - { - var row1 = dataGridView.SelectedRows[0].Index; - var row2 = dataGridView.SelectedRows[1].Index; - if (row1 > row2) - { - (row2, row1) = (row1, row2); - } - - var refLine = row1; - var timeStamp1 = GetTimestampForLine(ref refLine, false); - refLine = row2; - var timeStamp2 = GetTimestampForLine(ref refLine, false); - //TimeSpan span = TimeSpan.FromTicks(timeStamp2.Ticks - timeStamp1.Ticks); - DateTime diff; - if (timeStamp1.Ticks > timeStamp2.Ticks) - { - diff = new DateTime(timeStamp1.Ticks - timeStamp2.Ticks); - } - else - { - diff = new DateTime(timeStamp2.Ticks - timeStamp1.Ticks); - } - - StatusLineText("Time diff is " + diff.ToString("HH:mm:ss.fff")); - } - else - { - if (!IsMultiFile && dataGridView.SelectedRows.Count == 1) - { - StatusLineText(string.Empty); - } - } - } - } - - [SupportedOSPlatform("windows")] - private void SyncFilterGridPos () - { - try - { - if (_filterResultList.Count > 0) - { - var index = _filterResultList.BinarySearch(dataGridView.CurrentRow.Index); - if (index < 0) - { - index = ~index; - if (index > 0) - { - --index; - } - } - - if (filterGridView.Rows.GetRowCount(DataGridViewElementStates.None) > 0) // exception no rows - { - filterGridView.CurrentCell = filterGridView.Rows[index].Cells[0]; - } - else - { - filterGridView.CurrentCell = null; - } - } - } - catch (Exception e) - { - _logger.Error(e, "SyncFilterGridPos(): "); - } - } - - private void StatusLineFileSize (long size) - { - _statusEventArgs.FileSize = size; - SendStatusLineUpdate(); - } - - [SupportedOSPlatform("windows")] - private int Search (SearchParams searchParams) - { - if (searchParams.SearchText == null) - { - return -1; - } - - var lineNum = searchParams.IsFromTop && !searchParams.IsFindNext - ? 0 - : searchParams.CurrentLine; - - var lowerSearchText = searchParams.SearchText.ToLowerInvariant(); - var count = 0; - var hasWrapped = false; - - while (true) - { - if ((searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed) - { - if (lineNum >= _logFileReader.LineCount) - { - if (hasWrapped) - { - StatusLineError("Not found: " + searchParams.SearchText); - return -1; - } - - lineNum = 0; - count = 0; - hasWrapped = true; - StatusLineError("Started from beginning of file"); - } - } - else - { - if (lineNum < 0) - { - if (hasWrapped) - { - StatusLineError("Not found: " + searchParams.SearchText); - return -1; - } - - count = 0; - lineNum = _logFileReader.LineCount - 1; - hasWrapped = true; - StatusLineError("Started from end of file"); - } - } - - var line = _logFileReader.GetLogLine(lineNum); - if (line == null) - { - return -1; - } - - if (searchParams.IsRegex) - { - Regex rex = new(searchParams.SearchText, searchParams.IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - if (rex.IsMatch(line.FullLine)) - { - return lineNum; - } - } - else - { - if (searchParams.IsCaseSensitive) - { - if (line.FullLine.Contains(searchParams.SearchText, StringComparison.Ordinal)) - { - return lineNum; - } - } - else - { - if (line.FullLine.Contains(lowerSearchText, StringComparison.OrdinalIgnoreCase)) - { - return lineNum; - } - } - } - - if ((searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed) - { - lineNum++; - } - else - { - lineNum--; - } - - if (_shouldCancel) - { - return -1; - } - - if (++count % PROGRESS_BAR_MODULO == 0) - { - try - { - if (!Disposing) - { - Invoke(UpdateProgressBar, [count]); - } - } - catch (ObjectDisposedException ex) // can occur when closing the app while searching - { - _logger.Warn(ex); - } - } - } - } - - private void ResetProgressBar () - { - _progressEventArgs.Value = _progressEventArgs.MaxValue; - _progressEventArgs.Visible = false; - SendProgressBarUpdate(); - } - - [SupportedOSPlatform("windows")] - private void SelectLine (int line, bool triggerSyncCall, bool shouldScroll) - { - try - { - _shouldCallTimeSync = triggerSyncCall; - var wasCancelled = _shouldCancel; - _shouldCancel = false; - _isSearching = false; - StatusLineText(string.Empty); - _guiStateArgs.MenuEnabled = true; - - if (wasCancelled) - { - return; - } - - if (line == -1) - { - // Hmm... is that experimental code from early days? - MessageBox.Show(this, "Not found:", "Search result"); - return; - } - - // Prevent ArgumentOutOfRangeException - if (line >= dataGridView.Rows.GetRowCount(DataGridViewElementStates.None)) - { - line = dataGridView.Rows.GetRowCount(DataGridViewElementStates.None) - 1; - } - - dataGridView.Rows[line].Selected = true; - - if (shouldScroll) - { - dataGridView.CurrentCell = dataGridView.Rows[line].Cells[0]; - dataGridView.Focus(); - } - } - catch (ArgumentOutOfRangeException e) - { - _logger.Error(e, "Error while selecting line: "); - } - catch (IndexOutOfRangeException e) - { - // Occures sometimes (but cannot reproduce) - _logger.Error(e, "Error while selecting line: "); - } - } - - [SupportedOSPlatform("windows")] - private void StartEditMode () - { - if (!dataGridView.CurrentCell.ReadOnly) - { - dataGridView.BeginEdit(false); - if (dataGridView.EditingControl != null) - { - if (dataGridView.EditingControl is LogCellEditingControl editControl) - { - editControl.KeyDown += OnEditControlKeyDown; - editControl.KeyPress += OnEditControlKeyPress; - editControl.KeyUp += OnEditControlKeyUp; - editControl.Click += OnEditControlClick; - dataGridView.CellEndEdit += OnDataGridViewCellEndEdit; - editControl.SelectionStart = 0; - } - else - { - _logger.Warn(CultureInfo.InvariantCulture, "Edit control in logWindow was null"); - } - } - } - } - - [SupportedOSPlatform("windows")] - private void UpdateEditColumnDisplay (DataGridViewTextBoxEditingControl editControl) - { - // prevents key events after edit mode has ended - if (dataGridView.EditingControl != null) - { - var pos = editControl.SelectionStart + editControl.SelectionLength; - StatusLineText(" " + pos); - _logger.Debug(CultureInfo.InvariantCulture, "SelStart: {0}, SelLen: {1}", editControl.SelectionStart, editControl.SelectionLength); - } - } - - [SupportedOSPlatform("windows")] - private void SelectPrevHighlightLine () - { - var lineNum = dataGridView.CurrentCellAddress.Y; - while (lineNum > 0) - { - lineNum--; - var line = _logFileReader.GetLogLine(lineNum); - if (line != null) - { - var entry = FindHilightEntry(line); - if (entry != null) - { - SelectLine(lineNum, false, true); - break; - } - } - } - } - - [SupportedOSPlatform("windows")] - private void SelectNextHighlightLine () - { - var lineNum = dataGridView.CurrentCellAddress.Y; - while (lineNum < _logFileReader.LineCount) - { - lineNum++; - var line = _logFileReader.GetLogLine(lineNum); - if (line != null) - { - var entry = FindHilightEntry(line); - if (entry != null) - { - SelectLine(lineNum, false, true); - break; - } - } - } - } - - [SupportedOSPlatform("windows")] - private int FindNextBookmarkIndex (int lineNum) - { - if (lineNum >= dataGridView.RowCount) - { - lineNum = 0; - } - else - { - lineNum++; - } - - return _bookmarkProvider.FindNextBookmarkIndex(lineNum); - } - - [SupportedOSPlatform("windows")] - private int FindPrevBookmarkIndex (int lineNum) - { - if (lineNum <= 0) - { - lineNum = dataGridView.RowCount - 1; - } - else - { - lineNum--; - } - - return _bookmarkProvider.FindPrevBookmarkIndex(lineNum); - } - - /** - * Shift bookmarks after a logfile rollover - */ - - private void ShiftBookmarks (int offset) - { - _bookmarkProvider.ShiftBookmarks(offset); - OnBookmarkRemoved(); - } - - private void ShiftRowHeightList (int offset) - { - SortedList newList = []; - foreach (var entry in _rowHeightList.Values) - { - var line = entry.LineNum - offset; - if (line >= 0) - { - entry.LineNum = line; - newList.Add(line, entry); - } - } - - _rowHeightList = newList; - } - - private void ShiftFilterPipes (int offset) - { - lock (_filterPipeList) - { - foreach (var pipe in _filterPipeList) - { - pipe.ShiftLineNums(offset); - } - } - } - - [SupportedOSPlatform("windows")] - private void LoadFilterPipes () - { - lock (_filterPipeList) - { - foreach (var pipe in _filterPipeList) - { - pipe.RecreateTempFile(); - } - } - - if (_filterPipeList.Count > 0) - { - for (var i = 0; i < dataGridView.RowCount; ++i) - { - ProcessFilterPipes(i); - } - } - } - - private void DisconnectFilterPipes () - { - lock (_filterPipeList) - { - foreach (var pipe in _filterPipeList) - { - pipe.ClearLineList(); - } - } - } - - [SupportedOSPlatform("windows")] - private void ApplyFilterParams () - { - filterComboBox.Text = _filterParams.SearchText; - filterCaseSensitiveCheckBox.Checked = _filterParams.IsCaseSensitive; - filterRegexCheckBox.Checked = _filterParams.IsRegex; - filterTailCheckBox.Checked = _filterParams.IsFilterTail; - invertFilterCheckBox.Checked = _filterParams.IsInvert; - filterKnobBackSpread.Value = _filterParams.SpreadBefore; - filterKnobForeSpread.Value = _filterParams.SpreadBehind; - rangeCheckBox.Checked = _filterParams.IsRangeSearch; - columnRestrictCheckBox.Checked = _filterParams.ColumnRestrict; - fuzzyKnobControl.Value = _filterParams.FuzzyValue; - filterRangeComboBox.Text = _filterParams.RangeSearchText; - } - - [SupportedOSPlatform("windows")] - private void ResetFilterControls () - { - filterComboBox.Text = ""; - filterCaseSensitiveCheckBox.Checked = false; - filterRegexCheckBox.Checked = false; - //this.filterTailCheckBox.Checked = this.Preferences.filterTail; - invertFilterCheckBox.Checked = false; - filterKnobBackSpread.Value = 0; - filterKnobForeSpread.Value = 0; - rangeCheckBox.Checked = false; - columnRestrictCheckBox.Checked = false; - fuzzyKnobControl.Value = 0; - filterRangeComboBox.Text = ""; - } - - [SupportedOSPlatform("windows")] - private void FilterSearch () - { - if (filterComboBox.Text.Length == 0) - { - _filterParams.SearchText = string.Empty; - _filterParams.LowerSearchText = string.Empty; - _filterParams.IsRangeSearch = false; - ClearFilterList(); - filterSearchButton.Image = null; - ResetFilterControls(); - saveFilterButton.Enabled = false; - return; - } - - FilterSearch(filterComboBox.Text); - } - - [SupportedOSPlatform("windows")] - private async void FilterSearch (string text) - { - FireCancelHandlers(); // make sure that there's no other filter running (maybe from filter restore) - - _filterParams.SearchText = text; - _filterParams.LowerSearchText = text.ToLowerInvariant(); - ConfigManager.Settings.FilterHistoryList.Remove(text); - ConfigManager.Settings.FilterHistoryList.Insert(0, text); - var maxHistory = ConfigManager.Settings.Preferences.MaximumFilterEntries; - - if (ConfigManager.Settings.FilterHistoryList.Count > maxHistory) - { - ConfigManager.Settings.FilterHistoryList.RemoveAt(filterComboBox.Items.Count - 1); - } - - filterComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.FilterHistoryList) - { - filterComboBox.Items.Add(item); - } - - filterComboBox.Text = text; - - _filterParams.IsRangeSearch = rangeCheckBox.Checked; - _filterParams.RangeSearchText = filterRangeComboBox.Text; - if (_filterParams.IsRangeSearch) - { - ConfigManager.Settings.FilterRangeHistoryList.Remove(filterRangeComboBox.Text); - ConfigManager.Settings.FilterRangeHistoryList.Insert(0, filterRangeComboBox.Text); - if (ConfigManager.Settings.FilterRangeHistoryList.Count > maxHistory) - { - ConfigManager.Settings.FilterRangeHistoryList.RemoveAt(filterRangeComboBox.Items.Count - 1); - } - - filterRangeComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) - { - filterRangeComboBox.Items.Add(item); - } - } - - ConfigManager.Save(SettingsFlags.FilterHistory); - - _filterParams.IsCaseSensitive = filterCaseSensitiveCheckBox.Checked; - _filterParams.IsRegex = filterRegexCheckBox.Checked; - _filterParams.IsFilterTail = filterTailCheckBox.Checked; - _filterParams.IsInvert = invertFilterCheckBox.Checked; - if (_filterParams.IsRegex) - { - try - { - _filterParams.CreateRegex(); - } - catch (ArgumentException) - { - StatusLineError("Invalid regular expression"); - return; - } - } - - _filterParams.FuzzyValue = fuzzyKnobControl.Value; - _filterParams.SpreadBefore = filterKnobBackSpread.Value; - _filterParams.SpreadBehind = filterKnobForeSpread.Value; - _filterParams.ColumnRestrict = columnRestrictCheckBox.Checked; - - //ConfigManager.SaveFilterParams(this.filterParams); - ConfigManager.Settings.FilterParams = _filterParams; // wozu eigentlich? sinnlos seit MDI? - - _shouldCancel = false; - _isSearching = true; - StatusLineText("Filtering... Press ESC to cancel"); - filterSearchButton.Enabled = false; - ClearFilterList(); - - _progressEventArgs.MinValue = 0; - _progressEventArgs.MaxValue = dataGridView.RowCount; - _progressEventArgs.Value = 0; - _progressEventArgs.Visible = true; - SendProgressBarUpdate(); - - var settings = ConfigManager.Settings; - - //FilterFx fx = settings.preferences.multiThreadFilter ? MultiThreadedFilter : new FilterFx(Filter); - FilterFxAction = settings.Preferences.MultiThreadFilter ? MultiThreadedFilter : Filter; - - //Task.Run(() => fx.Invoke(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList)); - var filterFxActionTask = Task.Run(() => Filter(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList)); - - await filterFxActionTask; - FilterComplete(); - - //fx.BeginInvoke(_filterParams, _filterResultList, _lastFilterLinesList, _filterHitList, FilterComplete, null); - CheckForFilterDirty(); - } - - private void MultiThreadedFilter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) - { - ColumnizerCallback callback = new(this); - - FilterStarter fs = new(callback, Environment.ProcessorCount + 2) - { - FilterHitList = _filterHitList, - FilterResultLines = _filterResultList, - LastFilterLinesList = _lastFilterLinesList - }; - - var cancelHandler = new FilterCancelHandler(fs); - OnRegisterCancelHandler(cancelHandler); - long startTime = Environment.TickCount; - - fs.DoFilter(filterParams, 0, _logFileReader.LineCount, FilterProgressCallback); - - long endTime = Environment.TickCount; - - _logger.Debug($"Multi threaded filter duration: {endTime - startTime} ms."); - - OnDeRegisterCancelHandler(cancelHandler); - StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); - } - - private void FilterProgressCallback (int lineCount) - { - UpdateProgressBar(lineCount); - } - - [SupportedOSPlatform("windows")] - private void Filter (FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) - { - long startTime = Environment.TickCount; - try - { - filterParams.Reset(); - var lineNum = 0; - //AddFilterLineFx addFx = new AddFilterLineFx(AddFilterLine); - ColumnizerCallback callback = new(this); - while (true) - { - var line = _logFileReader.GetLogLine(lineNum); - if (line == null) - { - break; - } - - callback.LineNum = lineNum; - if (Util.TestFilterCondition(filterParams, line, callback)) - { - AddFilterLine(lineNum, false, filterParams, filterResultLines, lastFilterLinesList, - filterHitList); - } - - lineNum++; - if (lineNum % PROGRESS_BAR_MODULO == 0) - { - UpdateProgressBar(lineNum); - } - - if (_shouldCancel) - { - break; - } - } - } - catch (Exception ex) - { - _logger.Error(ex, "Exception while filtering. Please report to developer: "); - MessageBox.Show(null, $"Exception while filtering. Please report to developer: \n\n{ex}\n\n{ex.StackTrace}", "LogExpert"); - } - - long endTime = Environment.TickCount; - - _logger.Info($"Single threaded filter duration: {endTime - startTime} ms."); - - StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); - } - - /// - /// Returns a list with 'additional filter results'. This is the given line number - /// and (if back spread and/or fore spread is enabled) some additional lines. - /// This function doesn't check the filter condition! - /// - /// - /// - /// - /// - private IList GetAdditionalFilterResults (FilterParams filterParams, int lineNum, IList checkList) - { - IList resultList = []; - //string textLine = this.logFileReader.GetLogLine(lineNum); - //ColumnizerCallback callback = new ColumnizerCallback(this); - //callback.LineNum = lineNum; - - if (filterParams.SpreadBefore == 0 && filterParams.SpreadBehind == 0) - { - resultList.Add(lineNum); - return resultList; - } - - // back spread - for (var i = filterParams.SpreadBefore; i > 0; --i) - { - if (lineNum - i > 0) - { - if (!resultList.Contains(lineNum - i) && !checkList.Contains(lineNum - i)) - { - resultList.Add(lineNum - i); - } - } - } - - // direct filter hit - if (!resultList.Contains(lineNum) && !checkList.Contains(lineNum)) - { - resultList.Add(lineNum); - } - - // after spread - for (var i = 1; i <= filterParams.SpreadBehind; ++i) - { - if (lineNum + i < _logFileReader.LineCount) - { - if (!resultList.Contains(lineNum + i) && !checkList.Contains(lineNum + i)) - { - resultList.Add(lineNum + i); - } - } - } - - return resultList; - } - - [SupportedOSPlatform("windows")] - private void AddFilterLine (int lineNum, bool immediate, FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) - { - int count; - lock (_filterResultList) - { - filterHitList.Add(lineNum); - var filterResult = GetAdditionalFilterResults(filterParams, lineNum, lastFilterLinesList); - filterResultLines.AddRange(filterResult); - count = filterResultLines.Count; - lastFilterLinesList.AddRange(filterResult); - if (lastFilterLinesList.Count > SPREAD_MAX * 2) - { - lastFilterLinesList.RemoveRange(0, lastFilterLinesList.Count - SPREAD_MAX * 2); - } - } - - if (immediate) - { - TriggerFilterLineGuiUpdate(); - } - else if (lineNum % PROGRESS_BAR_MODULO == 0) - { - //FunctionWith1IntParam fx = new FunctionWith1IntParam(UpdateFilterCountLabel); - //this.Invoke(fx, new object[] { count}); - } - } - - [SupportedOSPlatform("windows")] - private void TriggerFilterLineGuiUpdate () - { - //lock (this.filterUpdateThread) - //{ - // this.filterEventCount++; - // this.filterUpdateEvent.Set(); - //} - Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); - } - - //private void FilterUpdateWorker() - //{ - // Thread.CurrentThread.Name = "FilterUpdateWorker"; - // while (true) - // { - // this.filterUpdateEvent.WaitOne(); - // lock (this.filterUpdateThread) - // { - // this.Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); - // this.filterUpdateEvent.Reset(); - // } - - // //_logger.logDebug("FilterUpdateWorker: Waiting for signal"); - // //bool signaled = this.filterUpdateEvent.WaitOne(1000, false); - - // //if (!signaled) - // //{ - // // lock (this.filterUpdateThread) - // // { - // // if (this.filterEventCount > 0) - // // { - // // this.filterEventCount = 0; - // // _logger.logDebug("FilterUpdateWorker: Invoking GUI update because of wait timeout"); - // // this.Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); - // // } - // // } - // //} - // //else - // //{ - // // _logger.logDebug("FilterUpdateWorker: Wakeup signal received."); - // // lock (this.filterUpdateThread) - // // { - // // _logger.logDebug("FilterUpdateWorker: event count: " + this.filterEventCount); - // // if (this.filterEventCount > 100) - // // { - // // this.filterEventCount = 0; - // // _logger.logDebug("FilterUpdateWorker: Invoking GUI update because of event count"); - // // this.Invoke(new MethodInvoker(AddFilterLineGuiUpdate)); - // // } - // // this.filterUpdateEvent.Reset(); - // // } - // //} - // } - //} - - //private void StopFilterUpdateWorkerThread() - //{ - // this.filterUpdateEvent.Set(); - // this.filterUpdateThread.Abort(); - // this.filterUpdateThread.Join(); - //} - - [SupportedOSPlatform("windows")] - private void AddFilterLineGuiUpdate () - { - try - { - lock (_filterResultList) - { - lblFilterCount.Text = "" + _filterResultList.Count; - if (filterGridView.RowCount > _filterResultList.Count) - { - filterGridView.RowCount = 0; // helps to prevent hang ? - } - - filterGridView.RowCount = _filterResultList.Count; - if (filterGridView.RowCount > 0) - { - filterGridView.FirstDisplayedScrollingRowIndex = filterGridView.RowCount - 1; - } - - if (filterGridView.RowCount == 1) - { - // after a file reload adjusted column sizes anew when the first line arrives - //this.filterGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - AutoResizeColumns(filterGridView); - } - } - } - catch (Exception e) - { - _logger.Error(e, "AddFilterLineGuiUpdate(): "); - } - } - - private void UpdateProgressBar (int value) - { - _progressEventArgs.Value = value; - if (value > _progressEventArgs.MaxValue) - { - // can occur if new lines will be added while filtering - _progressEventArgs.MaxValue = value; - } - - SendProgressBarUpdate(); - } - - [SupportedOSPlatform("windows")] - private void FilterComplete () - { - if (!IsDisposed && !_waitingForClose && !Disposing) - { - Invoke(new MethodInvoker(ResetStatusAfterFilter)); - } - } - - [SupportedOSPlatform("windows")] - private void FilterComplete (IAsyncResult result) - { - if (!IsDisposed && !_waitingForClose && !Disposing) - { - Invoke(new MethodInvoker(ResetStatusAfterFilter)); - } - } - - [SupportedOSPlatform("windows")] - private void ResetStatusAfterFilter () - { - try - { - //StatusLineText(""); - _isSearching = false; - _progressEventArgs.Value = _progressEventArgs.MaxValue; - _progressEventArgs.Visible = false; - SendProgressBarUpdate(); - filterGridView.RowCount = _filterResultList.Count; - //this.filterGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - AutoResizeColumns(filterGridView); - lblFilterCount.Text = "" + _filterResultList.Count; - if (filterGridView.RowCount > 0) - { - filterGridView.Focus(); - } - - filterSearchButton.Enabled = true; - } - catch (NullReferenceException e) - { - // See https://connect.microsoft.com/VisualStudio/feedback/details/366943/autoresizecolumns-in-datagridview-throws-nullreferenceexception - // There are some rare situations with null ref exceptions when resizing columns and on filter finished - // So catch them here. Better than crashing. - _logger.Error(e, "Error: "); - } - } - - [SupportedOSPlatform("windows")] - private void ClearFilterList () - { - try - { - //this.shouldCancel = true; - lock (_filterResultList) - { - filterGridView.SuspendLayout(); - filterGridView.RowCount = 0; - lblFilterCount.Text = "0"; - _filterResultList = []; - _lastFilterLinesList = []; - _filterHitList = []; - //this.filterGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - filterGridView.ResumeLayout(); - } - } - catch (Exception ex) - { - _logger.Error(ex, "Wieder dieser sporadische Fehler: "); - - MessageBox.Show(null, ex.StackTrace, "Wieder dieser sporadische Fehler:"); - } - } - - private void ClearBookmarkList () - { - _bookmarkProvider.ClearAllBookmarks(); - } - - /** - * Shift filter list line entries after a logfile rollover - */ - [SupportedOSPlatform("windows")] - private void ShiftFilterLines (int offset) - { - List newFilterList = []; - lock (_filterResultList) - { - foreach (var lineNum in _filterResultList) - { - var line = lineNum - offset; - if (line >= 0) - { - newFilterList.Add(line); - } - } - - _filterResultList = newFilterList; - } - - newFilterList = []; - foreach (var lineNum in _filterHitList) - { - var line = lineNum - offset; - if (line >= 0) - { - newFilterList.Add(line); - } - } - - _filterHitList = newFilterList; - - var count = SPREAD_MAX; - if (_filterResultList.Count < SPREAD_MAX) - { - count = _filterResultList.Count; - } - - _lastFilterLinesList = _filterResultList.GetRange(_filterResultList.Count - count, count); - - //this.filterGridView.RowCount = this.filterResultList.Count; - //this.filterCountLabel.Text = "" + this.filterResultList.Count; - //this.BeginInvoke(new MethodInvoker(this.filterGridView.Refresh)); - //this.BeginInvoke(new MethodInvoker(AddFilterLineGuiUpdate)); - TriggerFilterLineGuiUpdate(); - } - - [SupportedOSPlatform("windows")] - private void CheckForFilterDirty () - { - if (IsFilterSearchDirty(_filterParams)) - { - filterSearchButton.Image = _searchButtonImage; - saveFilterButton.Enabled = false; - } - else - { - filterSearchButton.Image = null; - saveFilterButton.Enabled = true; - } - } - - [SupportedOSPlatform("windows")] - private bool IsFilterSearchDirty (FilterParams filterParams) - { - if (!filterParams.SearchText.Equals(filterComboBox.Text, StringComparison.Ordinal)) - { - return true; - } - - if (filterParams.IsRangeSearch != rangeCheckBox.Checked) - { - return true; - } - - if (filterParams.IsRangeSearch && !filterParams.RangeSearchText.Equals(filterRangeComboBox.Text, StringComparison.Ordinal)) - { - return true; - } - - if (filterParams.IsRegex != filterRegexCheckBox.Checked) - { - return true; - } - - if (filterParams.IsInvert != invertFilterCheckBox.Checked) - { - return true; - } - - if (filterParams.SpreadBefore != filterKnobBackSpread.Value) - { - return true; - } - - if (filterParams.SpreadBehind != filterKnobForeSpread.Value) - { - return true; - } - - if (filterParams.FuzzyValue != fuzzyKnobControl.Value) - { - return true; - } - - if (filterParams.ColumnRestrict != columnRestrictCheckBox.Checked) - { - return true; - } - - if (filterParams.IsCaseSensitive != filterCaseSensitiveCheckBox.Checked) - { - return true; - } - - return false; - } - - [SupportedOSPlatform("windows")] - private void AdjustMinimumGridWith () - { - if (dataGridView.Columns.Count > 1) - { - //this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - AutoResizeColumns(dataGridView); - - var width = dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible); - var diff = dataGridView.Width - width; - if (diff > 0) - { - diff -= dataGridView.RowHeadersWidth / 2; - dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].Width += diff; - filterGridView.Columns[filterGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].Width += diff; - } - } - } - - [SupportedOSPlatform("windows")] - private void InvalidateCurrentRow (BufferedDataGridView gridView) - { - if (gridView.CurrentCellAddress.Y > -1) - { - gridView.InvalidateRow(gridView.CurrentCellAddress.Y); - } - } - - private void InvalidateCurrentRow () - { - InvalidateCurrentRow(dataGridView); - InvalidateCurrentRow(filterGridView); - } - - [SupportedOSPlatform("windows")] - private void DisplayCurrentFileOnStatusline () - { - if (_logFileReader.IsMultiFile) - { - try - { - if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index > -1) - { - var fileName = _logFileReader.GetLogFileNameForLine(dataGridView.CurrentRow.Index); - if (fileName != null) - { - StatusLineText(Util.GetNameFromPath(fileName)); - } - } - } - catch (Exception) - { - // TODO: handle this concurrent situation better: - // this.dataGridView.CurrentRow may be null even if checked before. - // This can happen when MultiFile shift deselects the current row because there - // are less lines after rollover than before. - // access to dataGridView-Rows should be locked - } - } - } - - private void UpdateSelectionDisplay () - { - if (_noSelectionUpdates) - { - return; - } - } - - [SupportedOSPlatform("windows")] - private void UpdateFilterHistoryFromSettings () - { - ConfigManager.Settings.FilterHistoryList = ConfigManager.Settings.FilterHistoryList; - filterComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.FilterHistoryList) - { - filterComboBox.Items.Add(item); - } - - filterRangeComboBox.Items.Clear(); - foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) - { - filterRangeComboBox.Items.Add(item); - } - } - - private void StatusLineText (string text) - { - _statusEventArgs.StatusText = text; - SendStatusLineUpdate(); - } - - private void StatusLineError (string text) - { - StatusLineText(text); - _isErrorShowing = true; - } - - private void RemoveStatusLineError () - { - StatusLineText(""); - _isErrorShowing = false; - } - - private void SendGuiStateUpdate () - { - OnGuiState(_guiStateArgs); - } - - private void SendProgressBarUpdate () - { - OnProgressBarUpdate(_progressEventArgs); - } - - private void SendStatusLineUpdate () - { - OnStatusLine(_statusEventArgs); - } - - [SupportedOSPlatform("windows")] - private void ShowAdvancedFilterPanel (bool show) - { - if (show) - { - advancedButton.Text = "Hide advanced..."; - advancedButton.Image = null; - } - else - { - advancedButton.Text = "Show advanced..."; - CheckForAdvancedButtonDirty(); - } - - advancedFilterSplitContainer.Panel1Collapsed = !show; - advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; - _showAdvanced = show; - } - - [SupportedOSPlatform("windows")] - private void CheckForAdvancedButtonDirty () - { - advancedButton.Image = IsAdvancedOptionActive() && !_showAdvanced - ? _advancedButtonImage - : null; - } - - [SupportedOSPlatform("windows")] - private void FilterToTab () - { - filterSearchButton.Enabled = false; - Task.Run(() => WriteFilterToTab()); - } - - [SupportedOSPlatform("windows")] - private void WriteFilterToTab () - { - FilterPipe pipe = new(_filterParams.Clone(), this); - lock (_filterResultList) - { - var namePrefix = "->F"; - var title = IsTempFile - ? TempTitleName + namePrefix + ++_filterPipeNameCounter - : Util.GetNameFromPath(FileName) + namePrefix + ++_filterPipeNameCounter; - - WritePipeToTab(pipe, _filterResultList, title, null); - } - } - - [SupportedOSPlatform("windows")] - private void WritePipeToTab (FilterPipe pipe, IList lineNumberList, string name, PersistenceData persistenceData) - { - _logger.Info(CultureInfo.InvariantCulture, "WritePipeToTab(): {0} lines.", lineNumberList.Count); - StatusLineText("Writing to temp file... Press ESC to cancel."); - _guiStateArgs.MenuEnabled = false; - SendGuiStateUpdate(); - _progressEventArgs.MinValue = 0; - _progressEventArgs.MaxValue = lineNumberList.Count; - _progressEventArgs.Value = 0; - _progressEventArgs.Visible = true; - Invoke(new MethodInvoker(SendProgressBarUpdate)); - _isSearching = true; - _shouldCancel = false; - - lock (_filterPipeList) - { - _filterPipeList.Add(pipe); - } - - pipe.Closed += OnPipeDisconnected; - var count = 0; - pipe.OpenFile(); - LogExpertCallback callback = new(this); - foreach (var i in lineNumberList) - { - if (_shouldCancel) - { - break; - } - - var line = _logFileReader.GetLogLine(i); - if (CurrentColumnizer is ILogLineXmlColumnizer) - { - callback.LineNum = i; - line = (CurrentColumnizer as ILogLineXmlColumnizer).GetLineTextForClipboard(line, callback); - } - - pipe.WriteToPipe(line, i); - if (++count % PROGRESS_BAR_MODULO == 0) - { - _progressEventArgs.Value = count; - Invoke(new MethodInvoker(SendProgressBarUpdate)); - } - } - - pipe.CloseFile(); - _logger.Info(CultureInfo.InvariantCulture, "WritePipeToTab(): finished"); - Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), pipe, name, persistenceData); - } - - [SupportedOSPlatform("windows")] - private void WriteFilterToTabFinished (FilterPipe pipe, string name, PersistenceData persistenceData) - { - _isSearching = false; - if (!_shouldCancel) - { - var title = name; - ILogLineColumnizer preProcessColumnizer = null; - if (CurrentColumnizer is not ILogLineXmlColumnizer) - { - preProcessColumnizer = CurrentColumnizer; - } - - var newWin = _parentLogTabWin.AddFilterTab(pipe, title, preProcessColumnizer); - newWin.FilterPipe = pipe; - pipe.OwnLogWindow = newWin; - if (persistenceData != null) - { - Task.Run(() => FilterRestore(newWin, persistenceData)); - } - } - - _progressEventArgs.Value = _progressEventArgs.MaxValue; - _progressEventArgs.Visible = false; - SendProgressBarUpdate(); - _guiStateArgs.MenuEnabled = true; - SendGuiStateUpdate(); - StatusLineText(""); - filterSearchButton.Enabled = true; - } - - /// - /// Used to create a new tab and pipe the given content into it. - /// - /// - /// - [SupportedOSPlatform("windows")] - internal void WritePipeTab (IList lineEntryList, string title) - { - FilterPipe pipe = new(new FilterParams(), this) - { - IsStopped = true - }; - pipe.Closed += OnPipeDisconnected; - pipe.OpenFile(); - foreach (var entry in lineEntryList) - { - pipe.WriteToPipe(entry.LogLine, entry.LineNum); - } - - pipe.CloseFile(); - Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), [pipe, title, null]); - } - - [SupportedOSPlatform("windows")] - private void FilterRestore (LogWindow newWin, PersistenceData persistenceData) - { - newWin.WaitForLoadingFinished(); - var columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.ColumnizerName, - PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - if (columnizer != null) - { - SetColumnizerFx fx = newWin.ForceColumnizer; - newWin.Invoke(fx, [columnizer]); - } - else - { - _logger.Warn($"FilterRestore(): Columnizer {persistenceData.ColumnizerName} not found"); - } - - newWin.BeginInvoke(new RestoreFiltersFx(newWin.RestoreFilters), [persistenceData]); - } - - [SupportedOSPlatform("windows")] - private void ProcessFilterPipes (int lineNum) - { - var searchLine = _logFileReader.GetLogLine(lineNum); - if (searchLine == null) - { - return; - } - - ColumnizerCallback callback = new(this) - { - LineNum = lineNum - }; - IList deleteList = []; - lock (_filterPipeList) - { - foreach (var pipe in _filterPipeList) - { - if (pipe.IsStopped) - { - continue; - } - - //long startTime = Environment.TickCount; - if (Util.TestFilterCondition(pipe.FilterParams, searchLine, callback)) - { - var filterResult = - GetAdditionalFilterResults(pipe.FilterParams, lineNum, pipe.LastLinesHistoryList); - pipe.OpenFile(); - foreach (var line in filterResult) - { - pipe.LastLinesHistoryList.Add(line); - if (pipe.LastLinesHistoryList.Count > SPREAD_MAX * 2) - { - pipe.LastLinesHistoryList.RemoveAt(0); - } - - var textLine = _logFileReader.GetLogLine(line); - var fileOk = pipe.WriteToPipe(textLine, line); - if (!fileOk) - { - deleteList.Add(pipe); - } - } - - pipe.CloseFile(); - } - - //long endTime = Environment.TickCount; - //_logger.logDebug("ProcessFilterPipes(" + lineNum + ") duration: " + ((endTime - startTime))); - } - } - - foreach (var pipe in deleteList) - { - _filterPipeList.Remove(pipe); - } - } - - [SupportedOSPlatform("windows")] - private void CopyMarkedLinesToClipboard () - { - if (_guiStateArgs.CellSelectMode) - { - var data = dataGridView.GetClipboardContent(); - Clipboard.SetDataObject(data); - } - else - { - List lineNumList = []; - foreach (DataGridViewRow row in dataGridView.SelectedRows) - { - if (row.Index != -1) - { - lineNumList.Add(row.Index); - } - } - - lineNumList.Sort(); - StringBuilder clipText = new(); - LogExpertCallback callback = new(this); - - var xmlColumnizer = _currentColumnizer as ILogLineXmlColumnizer; - - foreach (var lineNum in lineNumList) - { - var line = _logFileReader.GetLogLine(lineNum); - if (xmlColumnizer != null) - { - callback.LineNum = lineNum; - line = xmlColumnizer.GetLineTextForClipboard(line, callback); - } - - clipText.AppendLine(line.ToClipBoardText()); - } - - Clipboard.SetText(clipText.ToString()); - } - } - - /// - /// Set an Encoding which shall be used when loading a file. Used before a file is loaded. - /// - /// - private void SetExplicitEncoding (Encoding encoding) - { - EncodingOptions.Encoding = encoding; - } - - [SupportedOSPlatform("windows")] - private void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, bool setLastColumnWidth, int lastColumnWidth) - { - if (dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) > 1) - { - if (setLastColumnWidth) - { - dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = lastColumnWidth; - } - else - { - // Workaround for a .NET bug which brings the DataGridView into an unstable state (causing lots of NullReferenceExceptions). - dataGridView.FirstDisplayedScrollingColumnIndex = 0; - - dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = 5; // default - } - } - - if (dataGridView.RowCount > 0) - { - dataGridView.UpdateRowHeightInfo(0, true); - } - - dataGridView.Invalidate(); - dataGridView.Refresh(); - AutoResizeColumns(dataGridView); - } - - [SupportedOSPlatform("windows")] - private IList GetSelectedContent () - { - if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) - { - List lineNumList = []; - - foreach (DataGridViewRow row in dataGridView.SelectedRows) - { - if (row.Index != -1) - { - lineNumList.Add(row.Index); - } - } - - lineNumList.Sort(); - return lineNumList; - } - - return []; - } - - /* ======================================================================== - * Timestamp stuff - * =======================================================================*/ - - [SupportedOSPlatform("windows")] - private void SetTimestampLimits () - { - if (!CurrentColumnizer.IsTimeshiftImplemented()) - { - return; - } - - var line = 0; - _guiStateArgs.MinTimestamp = GetTimestampForLineForward(ref line, true); - line = dataGridView.RowCount - 1; - _guiStateArgs.MaxTimestamp = GetTimestampForLine(ref line, true); - SendGuiStateUpdate(); - } - - private void AdjustHighlightSplitterWidth () - { - //int size = this.editHighlightsSplitContainer.Panel2Collapsed ? 600 : 660; - //int distance = this.highlightSplitContainer.Width - size; - //if (distance < 10) - // distance = 10; - //this.highlightSplitContainer.SplitterDistance = distance; - } - - [SupportedOSPlatform("windows")] - private void BookmarkComment (Bookmark bookmark) - { - BookmarkCommentDlg dlg = new() - { - Comment = bookmark.Text - }; - if (dlg.ShowDialog() == DialogResult.OK) - { - bookmark.Text = dlg.Comment; - dataGridView.Refresh(); - OnBookmarkTextChanged(bookmark); - } - } - - /// - /// Indicates which columns we are filtering on - /// - /// - /// - [SupportedOSPlatform("windows")] - private string CalculateColumnNames (FilterParams filter) - { - var names = string.Empty; - - if (filter.ColumnRestrict) - { - foreach (var colIndex in filter.ColumnList) - { - if (colIndex < dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 2) - { - if (names.Length > 0) - { - names += ", "; - } - - names += dataGridView.Columns[2 + colIndex] - .HeaderText; // skip first two columns: marker + line number - } - } - } - - return names; - } - - [SupportedOSPlatform("windows")] - private void ApplyFrozenState (BufferedDataGridView gridView) - { - SortedDictionary dict = []; - foreach (DataGridViewColumn col in gridView.Columns) - { - dict.Add(col.DisplayIndex, col); - } - - foreach (var col in dict.Values) - { - col.Frozen = _freezeStateMap.ContainsKey(gridView) && _freezeStateMap[gridView]; - var sel = col.HeaderCell.Selected; - if (col.Index == _selectedCol) - { - break; - } - } - } - - [SupportedOSPlatform("windows")] - private void ShowTimeSpread (bool show) - { - if (show) - { - tableLayoutPanel1.ColumnStyles[1].Width = 16; - } - else - { - tableLayoutPanel1.ColumnStyles[1].Width = 0; - } - - _timeSpreadCalc.Enabled = show; - } - - [SupportedOSPlatform("windows")] - protected internal void AddTempFileTab (string fileName, string title) - { - _parentLogTabWin.AddTempFileTab(fileName, title); - } - - private void InitPatternWindow () - { - //PatternStatistic(this.patternArgs); - _patternWindow = new PatternWindow(this); - _patternWindow.SetColumnizer(CurrentColumnizer); - //this.patternWindow.SetBlockList(blockList); - _patternWindow.SetFont(Preferences.FontName, Preferences.FontSize); - _patternWindow.Fuzzy = _patternArgs.Fuzzy; - _patternWindow.MaxDiff = _patternArgs.MaxDiffInBlock; - _patternWindow.MaxMisses = _patternArgs.MaxMisses; - _patternWindow.Weight = _patternArgs.MinWeight; - //this.patternWindow.Show(); - } - - [SupportedOSPlatform("windows")] - private void TestStatistic (PatternArgs patternArgs) - { - var beginLine = patternArgs.StartLine; - _logger.Info($"TestStatistics() called with start line {beginLine}"); - - _patternArgs = patternArgs; - - var num = beginLine + 1; //this.dataGridView.RowCount; - - _progressEventArgs.MinValue = 0; - _progressEventArgs.MaxValue = dataGridView.RowCount; - _progressEventArgs.Value = beginLine; - _progressEventArgs.Visible = true; - SendProgressBarUpdate(); - - PrepareDict(); - ResetCache(num); - - Dictionary processedLinesDict = []; - List blockList = []; - var blockId = 0; - _isSearching = true; - _shouldCancel = false; - var searchLine = -1; - for (var i = beginLine; i < num && !_shouldCancel; ++i) - { - if (processedLinesDict.ContainsKey(i)) - { - continue; - } - - PatternBlock block; - var maxBlockLen = patternArgs.EndLine - patternArgs.StartLine; - //int searchLine = i + 1; - _logger.Debug(CultureInfo.InvariantCulture, "TestStatistic(): i={0} searchLine={1}", i, searchLine); - //bool firstBlock = true; - searchLine++; - UpdateProgressBar(searchLine); - while (!_shouldCancel && - (block = - DetectBlock(i, searchLine, maxBlockLen, _patternArgs.MaxDiffInBlock, - _patternArgs.MaxMisses, - processedLinesDict)) != null) - { - _logger.Debug(CultureInfo.InvariantCulture, "Found block: {0}", block); - if (block.Weigth >= _patternArgs.MinWeight) - { - //PatternBlock existingBlock = FindExistingBlock(block, blockList); - //if (existingBlock != null) - //{ - // if (block.weigth > existingBlock.weigth) - // { - // blockList.Remove(existingBlock); - // blockList.Add(block); - // } - //} - //else - { - blockList.Add(block); - AddBlockTargetLinesToDict(processedLinesDict, block); - } - block.BlockId = blockId; - //if (firstBlock) - //{ - // addBlockSrcLinesToDict(processedLinesDict, block); - //} - searchLine = block.TargetEnd + 1; - } - else - { - searchLine = block.TargetStart + 1; - } - - UpdateProgressBar(searchLine); - } - - blockId++; - } - - _isSearching = false; - _progressEventArgs.MinValue = 0; - _progressEventArgs.MaxValue = 0; - _progressEventArgs.Value = 0; - _progressEventArgs.Visible = false; - SendProgressBarUpdate(); - //if (this.patternWindow.IsDisposed) - //{ - // this.Invoke(new MethodInvoker(CreatePatternWindow)); - //} - _patternWindow.SetBlockList(blockList, _patternArgs); - _logger.Info(CultureInfo.InvariantCulture, "TestStatistics() ended"); - } - - private void AddBlockTargetLinesToDict (Dictionary dict, PatternBlock block) - { - foreach (var lineNum in block.TargetLines.Keys) - { - _ = dict.TryAdd(lineNum, lineNum); - } - } - - //Well keep this for the moment because there is some other commented code which calls this one - private PatternBlock FindExistingBlock (PatternBlock block, List blockList) - { - foreach (var searchBlock in blockList) - { - if (((block.StartLine > searchBlock.StartLine && block.StartLine < searchBlock.EndLine) || - (block.EndLine > searchBlock.StartLine && block.EndLine < searchBlock.EndLine)) && - block.StartLine != searchBlock.StartLine && - block.EndLine != searchBlock.EndLine - ) - { - return searchBlock; - } - } - - return null; - } - - private PatternBlock DetectBlock (int startNum, int startLineToSearch, int maxBlockLen, int maxDiffInBlock, int maxMisses, Dictionary processedLinesDict) - { - var targetLine = FindSimilarLine(startNum, startLineToSearch, processedLinesDict); - if (targetLine == -1) - { - return null; - } - - PatternBlock block = new() - { - StartLine = startNum - }; - var srcLine = block.StartLine; - block.TargetStart = targetLine; - var srcMisses = 0; - block.SrcLines.Add(srcLine, srcLine); - //block.targetLines.Add(targetLine, targetLine); - var len = 0; - QualityInfo qi = new() - { - Quality = block.Weigth - }; - block.QualityInfoList[targetLine] = qi; - - while (!_shouldCancel) - { - srcLine++; - len++; - //if (srcLine >= block.targetStart) - // break; // prevent to search in the own block - if (maxBlockLen > 0 && len > maxBlockLen) - { - break; - } - - var nextTargetLine = FindSimilarLine(srcLine, targetLine + 1, processedLinesDict); - if (nextTargetLine > -1 && nextTargetLine - targetLine - 1 <= maxDiffInBlock) - { - block.Weigth += maxDiffInBlock - (nextTargetLine - targetLine - 1) + 1; - block.EndLine = srcLine; - //block.targetLines.Add(nextTargetLine, nextTargetLine); - block.SrcLines.Add(srcLine, srcLine); - if (nextTargetLine - targetLine > 1) - { - var tempWeight = block.Weigth; - for (var tl = targetLine + 1; tl < nextTargetLine; ++tl) - { - qi = new QualityInfo - { - Quality = --tempWeight - }; - block.QualityInfoList[tl] = qi; - } - } - - targetLine = nextTargetLine; - qi = new QualityInfo - { - Quality = block.Weigth - }; - block.QualityInfoList[targetLine] = qi; - } - else - { - srcMisses++; - block.Weigth--; - targetLine++; - qi = new QualityInfo - { - Quality = block.Weigth - }; - block.QualityInfoList[targetLine] = qi; - if (srcMisses > maxMisses) - { - break; - } - } - } - - block.TargetEnd = targetLine; - qi = new QualityInfo - { - Quality = block.Weigth - }; - - block.QualityInfoList[targetLine] = qi; - - for (var k = block.TargetStart; k <= block.TargetEnd; ++k) - { - block.TargetLines.Add(k, k); - } - - return block; - } - - private void PrepareDict () - { - _lineHashList.Clear(); - Regex regex = new("\\d"); - Regex regex2 = new("\\S"); - - var num = _logFileReader.LineCount; - for (var i = 0; i < num; ++i) - { - var msg = GetMsgForLine(i); - if (msg != null) - { - msg = msg.ToLowerInvariant(); - msg = regex.Replace(msg, "0"); - msg = regex2.Replace(msg, " "); - var chars = msg.ToCharArray(); - var value = 0; - var numOfE = 0; - var numOfA = 0; - var numOfI = 0; - foreach (var t in chars) - { - value += t; - switch (t) - { - case 'e': - numOfE++; - break; - case 'a': - numOfA++; - break; - case 'i': - numOfI++; - break; - } - } - - value += numOfE * 30; - value += numOfA * 20; - value += numOfI * 10; - _lineHashList.Add(value); - } - } - } - - private int FindSimilarLine (int srcLine, int startLine) - { - var value = _lineHashList[srcLine]; - - var num = _lineHashList.Count; - for (var i = startLine; i < num; ++i) - { - if (Math.Abs(_lineHashList[i] - value) < 3) - { - return i; - } - } - - return -1; - } - - // int[,] similarCache; - - private void ResetCache (int num) - { - //this.similarCache = new int[num, num]; - //for (int i = 0; i < num; ++i) - //{ - // for (int j = 0; j < num; j++) - // { - // this.similarCache[i, j] = -1; - // } - //} - } - - private int FindSimilarLine (int srcLine, int startLine, Dictionary processedLinesDict) - { - var threshold = _patternArgs.Fuzzy; - - var prepared = false; - Regex regex = null; - Regex regex2 = null; - string msgToFind = null; - var culture = CultureInfo.CurrentCulture; - - var num = _logFileReader.LineCount; - for (var i = startLine; i < num; ++i) - { - if (processedLinesDict.ContainsKey(i)) - { - continue; - } - - //if (this.similarCache[srcLine, i] != -1) - //{ - // if (this.similarCache[srcLine, i] < threshold) - // { - // return i; - // } - //} - //else - { - if (!prepared) - { - msgToFind = GetMsgForLine(srcLine); - regex = new Regex("\\d"); - regex2 = new Regex("\\W"); - msgToFind = msgToFind.ToLower(culture); - msgToFind = regex.Replace(msgToFind, "0"); - msgToFind = regex2.Replace(msgToFind, " "); - prepared = true; - } - - var msg = GetMsgForLine(i); - if (msg != null) - { - msg = regex.Replace(msg, "0"); - msg = regex2.Replace(msg, " "); - var lenDiff = Math.Abs(msg.Length - msgToFind.Length); - if (lenDiff > threshold) - { - //this.similarCache[srcLine, i] = lenDiff; - continue; - } - - msg = msg.ToLower(culture); - var distance = Util.YetiLevenshtein(msgToFind, msg); - //this.similarCache[srcLine, i] = distance; - if (distance < threshold) - { - return i; - } - } - } - } - - return -1; - } - - private string GetMsgForLine (int i) - { - var line = _logFileReader.GetLogLine(i); - var columnizer = CurrentColumnizer; - ColumnizerCallback callback = new(this); - var cols = columnizer.SplitLine(callback, line); - return cols.ColumnValues.Last().FullValue; - } - - [SupportedOSPlatform("windows")] - private void ChangeRowHeight (bool decrease) - { - var rowNum = dataGridView.CurrentCellAddress.Y; - if (rowNum < 0 || rowNum >= dataGridView.RowCount) - { - return; - } - - if (decrease) - { - if (!_rowHeightList.TryGetValue(rowNum, out var entry)) - { - return; - } - else - { - entry.Height -= _lineHeight; - if (entry.Height <= _lineHeight) - { - _rowHeightList.Remove(rowNum); - } - } - } - else - { - RowHeightEntry entry; - if (!_rowHeightList.TryGetValue(rowNum, out var value)) - { - entry = new RowHeightEntry - { - LineNum = rowNum, - Height = _lineHeight - }; - - _rowHeightList[rowNum] = entry; - } - else - { - entry = value; - } - - entry.Height += _lineHeight; - } - - dataGridView.UpdateRowHeightInfo(rowNum, false); - if (rowNum == dataGridView.RowCount - 1 && _guiStateArgs.FollowTail) - { - dataGridView.FirstDisplayedScrollingRowIndex = rowNum; - } - - dataGridView.Refresh(); - } - - private int GetRowHeight (int rowNum) - { - return _rowHeightList.TryGetValue(rowNum, out var value) - ? value.Height - : _lineHeight; - } - - private void AddBookmarkAtLineSilently (int lineNum) - { - if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - _bookmarkProvider.AddBookmark(new Bookmark(lineNum)); - } - } - - [SupportedOSPlatform("windows")] - private void AddBookmarkAndEditComment () - { - var lineNum = dataGridView.CurrentCellAddress.Y; - if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - ToggleBookmark(); - } - - BookmarkComment(_bookmarkProvider.GetBookmarkForLine(lineNum)); - } - - [SupportedOSPlatform("windows")] - private void AddBookmarkComment (string text) - { - var lineNum = dataGridView.CurrentCellAddress.Y; - Bookmark bookmark; - if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - _bookmarkProvider.AddBookmark(bookmark = new Bookmark(lineNum)); - } - else - { - bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); - } - - bookmark.Text += text; - dataGridView.Refresh(); - filterGridView.Refresh(); - OnBookmarkTextChanged(bookmark); - } - - [SupportedOSPlatform("windows")] - private void MarkCurrentFilterRange () - { - _filterParams.RangeSearchText = filterRangeComboBox.Text; - ColumnizerCallback callback = new(this); - RangeFinder rangeFinder = new(_filterParams, callback); - var range = rangeFinder.FindRange(dataGridView.CurrentCellAddress.Y); - if (range != null) - { - SetCellSelectionMode(false); - _noSelectionUpdates = true; - for (var i = range.StartLine; i <= range.EndLine; ++i) - { - dataGridView.Rows[i].Selected = true; - } - - _noSelectionUpdates = false; - UpdateSelectionDisplay(); - } - } - - [SupportedOSPlatform("windows")] - private void RemoveTempHighlights () - { - lock (_tempHighlightEntryListLock) - { - _tempHighlightEntryList.Clear(); - } - - RefreshAllGrids(); - } - - [SupportedOSPlatform("windows")] - private void ToggleHighlightPanel (bool open) - { - highlightSplitContainer.Panel2Collapsed = !open; - btnToggleHighlightPanel.Image = open - ? new Bitmap(_panelCloseButtonImage, new Size(btnToggleHighlightPanel.Size.Height, btnToggleHighlightPanel.Size.Height)) - : new Bitmap(_panelOpenButtonImage, new Size(btnToggleHighlightPanel.Size.Height, btnToggleHighlightPanel.Size.Height)); - } - - [SupportedOSPlatform("windows")] - private void SetBookmarksForSelectedFilterLines () - { - lock (_filterResultList) - { - foreach (DataGridViewRow row in filterGridView.SelectedRows) - { - var lineNum = _filterResultList[row.Index]; - AddBookmarkAtLineSilently(lineNum); - } - } - - dataGridView.Refresh(); - filterGridView.Refresh(); - OnBookmarkAdded(); - } - - private void SetDefaultHighlightGroup () - { - var group = _parentLogTabWin.FindHighlightGroupByFileMask(FileName); - if (group != null) - { - SetCurrentHighlightGroup(group.GroupName); - } - else - { - SetCurrentHighlightGroup("[Default]"); - } - } - - [SupportedOSPlatform("windows")] - private void HandleChangedFilterOnLoadSetting () - { - _parentLogTabWin.Preferences.IsFilterOnLoad = filterOnLoadCheckBox.Checked; - _parentLogTabWin.Preferences.IsAutoHideFilterList = hideFilterListOnLoadCheckBox.Checked; - OnFilterListChanged(this); - } - - private void FireCancelHandlers () - { - lock (_cancelHandlerList) - { - foreach (var handler in _cancelHandlerList) - { - handler.EscapePressed(); - } - } - } - - private void SyncOtherWindows (DateTime timestamp) - { - lock (_timeSyncListLock) - { - TimeSyncList?.NavigateToTimestamp(timestamp, this); - } - } - - [SupportedOSPlatform("windows")] - private void AddSlaveToTimesync (LogWindow slave) - { - lock (_timeSyncListLock) - { - if (TimeSyncList == null) - { - if (slave.TimeSyncList == null) - { - TimeSyncList = new TimeSyncList(); - TimeSyncList.AddWindow(this); - } - else - { - TimeSyncList = slave.TimeSyncList; - } - - var currentLineNum = dataGridView.CurrentCellAddress.Y; - var refLine = currentLineNum; - var timeStamp = GetTimestampForLine(ref refLine, true); - if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) - { - TimeSyncList.CurrentTimestamp = timeStamp; - } - - TimeSyncList.WindowRemoved += OnTimeSyncListWindowRemoved; - } - } - - slave.AddToTimeSync(this); - OnSyncModeChanged(); - } - - private void FreeSlaveFromTimesync (LogWindow slave) - { - slave.FreeFromTimeSync(); - } - - private void OnSyncModeChanged () - { - SyncModeChanged?.Invoke(this, new SyncModeEventArgs(IsTimeSynced)); - } - - [SupportedOSPlatform("windows")] - private void AddSearchHitHighlightEntry (SearchParams para) - { - HighlightEntry he = new() - { - SearchText = para.SearchText, - ForegroundColor = Color.Red, - BackgroundColor = Color.Yellow, - IsRegEx = para.IsRegex, - IsCaseSensitive = para.IsCaseSensitive, - IsLedSwitch = false, - IsStopTail = false, - IsSetBookmark = false, - IsActionEntry = false, - ActionEntry = null, - IsWordMatch = true, - IsSearchHit = true - }; - - lock (_tempHighlightEntryListLock) - { - _tempHighlightEntryList.Add(he); - } - - RefreshAllGrids(); - } - - [SupportedOSPlatform("windows")] - private void RemoveAllSearchHighlightEntries () - { - lock (_tempHighlightEntryListLock) - { - List newList = []; - foreach (var he in _tempHighlightEntryList) - { - if (!he.IsSearchHit) - { - newList.Add(he); - } - } - - _tempHighlightEntryList = newList; - } - - RefreshAllGrids(); - } - - [SupportedOSPlatform("windows")] - private DataGridViewColumn GetColumnByName (BufferedDataGridView dataGridView, string name) - { - foreach (DataGridViewColumn col in dataGridView.Columns) - { - if (col.HeaderText.Equals(name, StringComparison.Ordinal)) - { - return col; - } - } - - return null; - } - - [SupportedOSPlatform("windows")] - private void SelectColumn () - { - var colName = columnComboBox.SelectedItem as string; - var col = GetColumnByName(dataGridView, colName); - if (col != null && !col.Frozen) - { - dataGridView.FirstDisplayedScrollingColumnIndex = col.Index; - var currentLine = dataGridView.CurrentCellAddress.Y; - if (currentLine >= 0) - { - dataGridView.CurrentCell = dataGridView.Rows[dataGridView.CurrentCellAddress.Y].Cells[col.Index]; - } - } - } - - #endregion - -} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs deleted file mode 100644 index 5f1a9832..00000000 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindowPublic.cs +++ /dev/null @@ -1,1827 +0,0 @@ -using System.Text; - -using LogExpert.Core.Classes; -using LogExpert.Core.Classes.Columnizer; -using LogExpert.Core.Classes.Filter; -using LogExpert.Core.Classes.Highlight; -using LogExpert.Core.Classes.Persister; -using LogExpert.Core.Config; -using LogExpert.Core.Entities; -using LogExpert.Core.EventArguments; -using LogExpert.Dialogs; -using LogExpert.UI.Entities; -using LogExpert.UI.Extensions; - -namespace LogExpert.UI.Controls.LogWindow; - -partial class LogWindow -{ - #region Public methods - - public void LoadFile (string fileName, EncodingOptions encodingOptions) - { - EnterLoadFileStatus(); - - if (fileName != null) - { - FileName = fileName; - EncodingOptions = encodingOptions; - - if (_logFileReader != null) - { - _logFileReader.StopMonitoringAsync(); - UnRegisterLogFileReaderEvents(); - } - - // - // isUsingDefaultColumnizer is to enable automatically find the best columnizer. - // When a new log file is opened, and no Columnizer can be chose by file mask, - // this flag will enable find a columnizer automatically. - // Current solution is not elegant. - // Since the refactory will involving a lot of work, we can plan it in the future. - // One possible solution is, using raw file stream to read the sample lines to help - // the ColumnizerPicker to determine the priority. - // - var isUsingDefaultColumnizer = false; - if (!LoadPersistenceOptions()) - { - if (!IsTempFile) - { - var columnizer = FindColumnizer(); - if (columnizer != null) - { - if (_reloadMemento == null) - { - //TODO this needs to be refactored - var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - - columnizer = ColumnizerPicker.CloneColumnizer(columnizer, directory); - } - } - else - { - isUsingDefaultColumnizer = true; - } - - PreSelectColumnizer(columnizer); - } - - SetDefaultHighlightGroup(); - } - - // this may be set after loading persistence data - if (_fileNames != null && IsMultiFile) - { - LoadFilesAsMulti(_fileNames, EncodingOptions); - return; - } - - _columnCache = new ColumnCache(); - - try - { - _logFileReader = new(fileName, EncodingOptions, IsMultiFile, Preferences.BufferCount, Preferences.LinesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) - { - UseNewReader = !Preferences.UseLegacyReader - }; - } - catch (LogFileException lfe) - { - _logger.Error(lfe); - MessageBox.Show($"Cannot load file\n{lfe.Message}", "LogExpert"); - _ = BeginInvoke(new FunctionWith1BoolParam(Close), true); - _isLoadError = true; - return; - } - - if (CurrentColumnizer is ILogLineXmlColumnizer xmlColumnizer) - { - _logFileReader.IsXmlMode = true; - _logFileReader.XmlLogConfig = xmlColumnizer.GetXmlLogConfiguration(); - } - - if (_forcedColumnizerForLoading != null) - { - CurrentColumnizer = _forcedColumnizerForLoading; - } - - _logFileReader.PreProcessColumnizer = CurrentColumnizer is IPreProcessColumnizer processColumnizer ? processColumnizer : null; - - RegisterLogFileReaderEvents(); - _logger.Info($"Loading logfile: {fileName}"); - _logFileReader.StartMonitoring(); - - if (isUsingDefaultColumnizer) - { - if (Preferences.AutoPick) - { - var newColumnizer = ColumnizerPicker.FindBetterColumnizer(FileName, _logFileReader, CurrentColumnizer, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - - if (newColumnizer != null) - { - _logger.Debug($"Picked new columnizer '{newColumnizer}'"); - - PreSelectColumnizer(newColumnizer); - } - } - } - } - } - - public void LoadFilesAsMulti (string[] fileNames, EncodingOptions encodingOptions) - { - _logger.Info("Loading given files as MultiFile:"); - - EnterLoadFileStatus(); - - foreach (var name in fileNames) - { - _logger.Info($"File: {name}"); - } - - if (_logFileReader != null) - { - _logFileReader.StopMonitoring(); - UnRegisterLogFileReaderEvents(); - } - - EncodingOptions = encodingOptions; - _columnCache = new ColumnCache(); - - _logFileReader = new(fileNames, EncodingOptions, Preferences.BufferCount, Preferences.LinesPerBuffer, _multiFileOptions, PluginRegistry.PluginRegistry.Instance) - { - UseNewReader = !Preferences.UseLegacyReader - }; - - RegisterLogFileReaderEvents(); - _logFileReader.StartMonitoring(); - FileName = fileNames[^1]; - _fileNames = fileNames; - IsMultiFile = true; - //if (this.isTempFile) - // this.Text = this.tempTitleName; - //else - // this.Text = Util.GetNameFromPath(this.FileName); - } - - public string SavePersistenceData (bool force) - { - if (!force) - { - if (!Preferences.SaveSessions) - { - return null; - } - } - - if (IsTempFile || _isLoadError) - { - return null; - } - - try - { - var persistenceData = GetPersistenceData(); - - return ForcedPersistenceFileName == null - ? Persister.SavePersistenceData(FileName, persistenceData, Preferences) - : Persister.SavePersistenceDataWithFixedName(ForcedPersistenceFileName, persistenceData); - } - catch (IOException ex) - { - _logger.Error(ex, "Error saving persistence: "); - } - catch (Exception e) - { - MessageBox.Show($"Unexpected error while saving persistence: {e.Message}"); - } - - return null; - } - - public PersistenceData GetPersistenceData () - { - PersistenceData persistenceData = new() - { - BookmarkList = _bookmarkProvider.BookmarkList, - RowHeightList = _rowHeightList, - MultiFile = IsMultiFile, - MultiFilePattern = _multiFileOptions.FormatPattern, - MultiFileMaxDays = _multiFileOptions.MaxDayTry, - CurrentLine = dataGridView.CurrentCellAddress.Y, - FirstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex, - FilterVisible = !splitContainerLogWindow.Panel2Collapsed, - FilterAdvanced = !advancedFilterSplitContainer.Panel1Collapsed, - FilterPosition = splitContainerLogWindow.SplitterDistance, - FollowTail = _guiStateArgs.FollowTail, - FileName = FileName, - TabName = Text, - SessionFileName = SessionFileName, - ColumnizerName = CurrentColumnizer.GetName(), - LineCount = _logFileReader.LineCount - }; - - _filterParams.IsFilterTail = filterTailCheckBox.Checked; // this option doesnt need a press on 'search' - - if (Preferences.SaveFilters) - { - List filterList = [_filterParams]; - persistenceData.FilterParamsList = filterList; - - foreach (var filterPipe in _filterPipeList) - { - FilterTabData data = new() - { - PersistenceData = filterPipe.OwnLogWindow.GetPersistenceData(), - FilterParams = filterPipe.FilterParams - }; - persistenceData.FilterTabDataList.Add(data); - } - } - - if (_currentHighlightGroup != null) - { - persistenceData.HighlightGroupName = _currentHighlightGroup.GroupName; - } - - if (_fileNames != null && IsMultiFile) - { - persistenceData.MultiFileNames.AddRange(_fileNames); - } - - //persistenceData.showBookmarkCommentColumn = this.bookmarkWindow.ShowBookmarkCommentColumn; - persistenceData.FilterSaveListVisible = !highlightSplitContainer.Panel2Collapsed; - persistenceData.Encoding = _logFileReader.CurrentEncoding; - - return persistenceData; - } - - public void Close (bool dontAsk) - { - Preferences.AskForClose = !dontAsk; - Close(); - } - - public void CloseLogWindow () - { - StopTimespreadThread(); - StopTimestampSyncThread(); - StopLogEventWorkerThread(); - _shouldCancel = true; - - if (_logFileReader != null) - { - UnRegisterLogFileReaderEvents(); - _logFileReader.StopMonitoringAsync(); - //this.logFileReader.DeleteAllContent(); - } - - if (_isLoading) - { - _waitingForClose = true; - } - - if (IsTempFile) - { - _logger.Info($"Deleting temp file {FileName}"); - - try - { - File.Delete(FileName); - } - catch (IOException e) - { - _logger.Error(e, $"Error while deleting temp file {FileName}: {e}"); - } - } - - FilterPipe?.CloseAndDisconnect(); - DisconnectFilterPipes(); - } - - public void WaitForLoadingFinished () - { - _externaLoadingFinishedEvent.WaitOne(); - } - - public void ForceColumnizer (ILogLineColumnizer columnizer) - { - //TODO this needs to be refactored - var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - - _forcedColumnizer = ColumnizerPicker.CloneColumnizer(columnizer, directory); - SetColumnizer(_forcedColumnizer); - } - - public void ForceColumnizerForLoading (ILogLineColumnizer columnizer) - { - //TODO this needs to be refactored - var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - - _forcedColumnizerForLoading = ColumnizerPicker.CloneColumnizer(columnizer, directory); - } - - public void PreselectColumnizer (string columnizerName) - { - //TODO this needs to be refactored - var directory = ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir; - - var columnizer = ColumnizerPicker.FindColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - PreSelectColumnizer(ColumnizerPicker.CloneColumnizer(columnizer, directory)); - } - - public void ColumnizerConfigChanged () - { - SetColumnizerInternal(CurrentColumnizer); - } - - public void SetColumnizer (ILogLineColumnizer columnizer, BufferedDataGridView gridView) - { - PaintHelper.SetColumnizer(columnizer, gridView); - - gridView.Refresh(); - AutoResizeColumns(gridView); - ApplyFrozenState(gridView); - } - - public IColumn GetCellValue (int rowIndex, int columnIndex) - { - if (columnIndex == 1) - { - return new Column - { - FullValue = $"{rowIndex + 1}" // line number - }; - } - - if (columnIndex == 0) // marker column - { - return Column.EmptyColumn; - } - - try - { - var cols = GetColumnsForLine(rowIndex); - if (cols != null && cols.ColumnValues != null) - { - if (columnIndex <= cols.ColumnValues.Length + 1) - { - var value = cols.ColumnValues[columnIndex - 2]; - - return value != null && value.DisplayValue != null - ? value - : value; - } - - return columnIndex == 2 - ? cols.ColumnValues[^1] - : Column.EmptyColumn; - } - } - catch - { - return Column.EmptyColumn; - } - - return Column.EmptyColumn; - } - - public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) - { - if (rowIndex < 0 || e.ColumnIndex < 0) - { - e.Handled = false; - return; - } - - var line = _logFileReader.GetLogLineWithWait(rowIndex).Result; - - if (line != null) - { - var entry = FindFirstNoWordMatchHilightEntry(line); - e.Graphics.SetClip(e.CellBounds); - - if (e.State.HasFlag(DataGridViewElementStates.Selected)) - { - using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); - e.Graphics.FillRectangle(brush, e.CellBounds); - } - else - { - e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); - e.PaintBackground(e.ClipBounds, false); - } - - if (DebugOptions.DisableWordHighlight) - { - e.PaintContent(e.CellBounds); - } - else - { - PaintCell(e, gridView, false, entry); - } - - if (e.ColumnIndex == 0) - { - if (_bookmarkProvider.IsBookmarkAtLine(rowIndex)) - { - Rectangle r; // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); - r = e.CellBounds; - r.Inflate(-2, -2); - using var brush = new SolidBrush(BookmarkColor); - e.Graphics.FillRectangle(brush, r); - - var bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); - - if (bookmark.Text.Length > 0) - { - StringFormat format = new() - { - LineAlignment = StringAlignment.Center, - Alignment = StringAlignment.Center - }; - - using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); //dark orange - using var font = new Font("Courier New", Preferences.FontSize, FontStyle.Bold); - e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); - } - } - } - - e.Paint(e.CellBounds, DataGridViewPaintParts.Border); - e.Handled = true; - } - } - - public void OnDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) - { - var gridView = (BufferedDataGridView)sender; - CellPainting(gridView, e.RowIndex, e); - } - - /// - /// Returns the first HilightEntry that matches the given line - /// - /// - /// - /// - public HighlightEntry FindHighlightEntry (ITextValue line, bool noWordMatches) - { - // first check the temp entries - lock (_tempHighlightEntryListLock) - { - foreach (var entry in _tempHighlightEntryList) - { - if (noWordMatches && entry.IsWordMatch) - { - continue; - } - - if (CheckHighlightEntryMatch(entry, line)) - { - return entry; - } - } - } - - lock (_currentHighlightGroupLock) - { - foreach (var entry in _currentHighlightGroup.HighlightEntryList) - { - if (noWordMatches && entry.IsWordMatch) - { - continue; - } - if (CheckHighlightEntryMatch(entry, line)) - { - return entry; - } - } - return null; - } - } - - public IList FindHighlightMatches (ITextValue line) - { - IList resultList = []; - - if (line != null) - { - lock (_currentHighlightGroupLock) - { - GetHighlightEntryMatches(line, _currentHighlightGroup.HighlightEntryList, resultList); - } - - lock (_tempHighlightEntryList) - { - GetHighlightEntryMatches(line, _tempHighlightEntryList, resultList); - } - } - - return resultList; - } - - public void FollowTailChanged (bool isChecked, bool byTrigger) - { - _guiStateArgs.FollowTail = isChecked; - - if (_guiStateArgs.FollowTail && _logFileReader != null) - { - if (dataGridView.RowCount >= _logFileReader.LineCount && _logFileReader.LineCount > 0) - { - dataGridView.FirstDisplayedScrollingRowIndex = _logFileReader.LineCount - 1; - } - } - - BeginInvoke(new MethodInvoker(dataGridView.Refresh)); - //this.dataGridView.Refresh(); - _parentLogTabWin.FollowTailChanged(this, isChecked, byTrigger); - SendGuiStateUpdate(); - } - - public void TryToTruncate () - { - try - { - if (LockFinder.CheckIfFileIsLocked(Title)) - { - var name = LockFinder.FindLockedProcessName(Title); - StatusLineText($"Truncate failed: file is locked by {name}"); - } - else - { - File.WriteAllText(Title, ""); - } - } - catch (Exception ex) - { - _logger.Warn($"Unexpected issue truncating file: {ex.Message}"); - StatusLineText("Unexpected issue truncating file"); - throw; - } - } - - public void GotoLine (int line) - { - if (line >= 0) - { - if (line < dataGridView.RowCount) - { - SelectLine(line, false, true); - } - else - { - SelectLine(dataGridView.RowCount - 1, false, true); - } - dataGridView.Focus(); - } - } - - public void StartSearch () - { - _guiStateArgs.MenuEnabled = false; - GuiStateUpdate(this, _guiStateArgs); - var searchParams = _parentLogTabWin.SearchParams; - - searchParams.CurrentLine = (searchParams.IsForward || searchParams.IsFindNext) && !searchParams.IsShiftF3Pressed - ? dataGridView.CurrentCellAddress.Y + 1 - : dataGridView.CurrentCellAddress.Y - 1; - - _currentSearchParams = searchParams; // remember for async "not found" messages - - _isSearching = true; - _shouldCancel = false; - StatusLineText("Searching... Press ESC to cancel."); - - _progressEventArgs.MinValue = 0; - _progressEventArgs.MaxValue = dataGridView.RowCount; - _progressEventArgs.Value = 0; - _progressEventArgs.Visible = true; - SendProgressBarUpdate(); - - Task.Run(() => Search(searchParams)).ContinueWith(SearchComplete); - - RemoveAllSearchHighlightEntries(); - AddSearchHitHighlightEntry(searchParams); - } - - private void SearchComplete (Task task) - { - if (Disposing) - { - return; - } - - try - { - Invoke(new MethodInvoker(ResetProgressBar)); - var line = task.Result; - _guiStateArgs.MenuEnabled = true; - GuiStateUpdate(this, _guiStateArgs); - if (line == -1) - { - return; - } - - dataGridView.Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); - } - catch (Exception ex) // in the case the windows is already destroyed - { - _logger.Warn(ex); - } - } - - public void SelectLogLine (int line) - { - Invoke(new SelectLineFx((line1, triggerSyncCall) => SelectLine(line1, triggerSyncCall, true)), line, true); - } - - public void SelectAndEnsureVisible (int line, bool triggerSyncCall) - { - try - { - SelectLine(line, triggerSyncCall, false); - - //if (!this.dataGridView.CurrentRow.Displayed) - if (line < dataGridView.FirstDisplayedScrollingRowIndex || line > dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false)) - { - dataGridView.FirstDisplayedScrollingRowIndex = line; - for (var i = 0; i < 8 && dataGridView.FirstDisplayedScrollingRowIndex > 0 && line < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false); ++i) - { - dataGridView.FirstDisplayedScrollingRowIndex -= 1; - } - - if (line >= dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false)) - { - dataGridView.FirstDisplayedScrollingRowIndex += 1; - } - } - - dataGridView.CurrentCell = dataGridView.Rows[line].Cells[0]; - } - catch (Exception e) - { - // In rare situations there seems to be an invalid argument exceptions (or something like this). Concrete location isn't visible in stack - // trace because use of Invoke(). So catch it, and log (better than crashing the app). - _logger.Error(e); - } - } - - public void OnLogWindowKeyDown (object sender, KeyEventArgs e) - { - if (_isErrorShowing) - { - RemoveStatusLineError(); - } - - switch (e.KeyCode) - { - case Keys.F3 when _parentLogTabWin.SearchParams?.SearchText == null || _parentLogTabWin.SearchParams.SearchText.Length == 0: - { - return; - } - case Keys.F3: - { - _parentLogTabWin.SearchParams.IsFindNext = true; - _parentLogTabWin.SearchParams.IsShiftF3Pressed = (e.Modifiers & Keys.Shift) == Keys.Shift; - StartSearch(); - break; - } - case Keys.Escape: - { - if (_isSearching) - { - _shouldCancel = true; - } - - FireCancelHandlers(); - RemoveAllSearchHighlightEntries(); - break; - } - case Keys.E when (e.Modifiers & Keys.Control) == Keys.Control: - { - StartEditMode(); - - break; - } - case Keys.Down when e.Modifiers == Keys.Alt: - { - var newLine = _logFileReader.GetNextMultiFileLine(dataGridView.CurrentCellAddress.Y); - - if (newLine != -1) - { - SelectLine(newLine, false, true); - } - - e.Handled = true; - - break; - } - case Keys.Up when e.Modifiers == Keys.Alt: - { - var newLine = _logFileReader.GetPrevMultiFileLine(dataGridView.CurrentCellAddress.Y); - - if (newLine != -1) - { - SelectLine(newLine - 1, false, true); - } - - e.Handled = true; - - break; - } - case Keys.Enter when dataGridView.Focused: - { - ChangeRowHeight(e.Shift); - e.Handled = true; - - break; - } - case Keys.Back when dataGridView.Focused: - { - ChangeRowHeight(true); - e.Handled = true; - - break; - } - case Keys.PageUp when e.Modifiers == Keys.Alt: - { - SelectPrevHighlightLine(); - e.Handled = true; - - break; - } - case Keys.PageDown when e.Modifiers == Keys.Alt: - { - SelectNextHighlightLine(); - e.Handled = true; - - break; - } - case Keys.T when (e.Modifiers & Keys.Control) == Keys.Control && (e.Modifiers & Keys.Shift) == Keys.Shift: - { - FilterToTab(); - break; - } - } - } - - public void AddBookmarkOverlays () - { - const int OVERSCAN = 20; - - var firstLine = dataGridView.FirstDisplayedScrollingRowIndex; - if (firstLine < 0) - { - return; - } - - firstLine -= OVERSCAN; - if (firstLine < 0) - { - firstLine = 0; - } - - var oversizeCount = OVERSCAN; - - for (var i = firstLine; i < dataGridView.RowCount; ++i) - { - if (!dataGridView.Rows[i].Displayed && i > dataGridView.FirstDisplayedScrollingRowIndex) - { - if (oversizeCount-- < 0) - { - break; - } - } - - if (_bookmarkProvider.IsBookmarkAtLine(i)) - { - var bookmark = _bookmarkProvider.GetBookmarkForLine(i); - if (bookmark.Text.Length > 0) - { - //BookmarkOverlay overlay = new BookmarkOverlay(); - var overlay = bookmark.Overlay; - overlay.Bookmark = bookmark; - - Rectangle r; - if (dataGridView.Rows[i].Displayed) - { - r = dataGridView.GetCellDisplayRectangle(0, i, false); - } - else - { - r = dataGridView.GetCellDisplayRectangle(0, dataGridView.FirstDisplayedScrollingRowIndex, false); - //int count = i - this.dataGridView.FirstDisplayedScrollingRowIndex; - var heightSum = 0; - if (dataGridView.FirstDisplayedScrollingRowIndex < i) - { - for (var rn = dataGridView.FirstDisplayedScrollingRowIndex + 1; rn < i; ++rn) - { - //Rectangle rr = this.dataGridView.GetCellDisplayRectangle(0, rn, false); - //heightSum += rr.Height; - heightSum += GetRowHeight(rn); - } - - r.Offset(0, r.Height + heightSum); - } - else - { - for (var rn = dataGridView.FirstDisplayedScrollingRowIndex + 1; rn > i; --rn) - { - //Rectangle rr = this.dataGridView.GetCellDisplayRectangle(0, rn, false); - //heightSum += rr.Height; - heightSum += GetRowHeight(rn); - } - - r.Offset(0, -(r.Height + heightSum)); - } - //r.Offset(0, this.dataGridView.DisplayRectangle.Height); - } - - if (_logger.IsDebugEnabled) - { - _logger.Debug($"AddBookmarkOverlay() r.Location={r.Location.X}, width={r.Width}, scroll_offset={dataGridView.HorizontalScrollingOffset}"); - } - - overlay.Position = r.Location - new Size(dataGridView.HorizontalScrollingOffset, 0); - overlay.Position += new Size(10, r.Height / 2); - dataGridView.AddOverlay(overlay); - } - } - } - } - - public void ToggleBookmark () - { - BufferedDataGridView gridView; - int lineNum; - - if (filterGridView.Focused) - { - gridView = filterGridView; - if (gridView.CurrentCellAddress.Y == -1) - { - return; - } - - lineNum = _filterResultList[gridView.CurrentCellAddress.Y]; - } - else - { - gridView = dataGridView; - if (gridView.CurrentCellAddress.Y == -1) - { - return; - } - lineNum = dataGridView.CurrentCellAddress.Y; - } - - ToggleBookmark(lineNum); - } - - public void ToggleBookmark (int lineNum) - { - if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); - - if (string.IsNullOrEmpty(bookmark.Text) == false) - { - if (DialogResult.No == MessageBox.Show("There's a comment attached to the bookmark. Really remove the bookmark?", "LogExpert", MessageBoxButtons.YesNo)) - { - return; - } - } - _bookmarkProvider.RemoveBookmarkForLine(lineNum); - } - else - { - _bookmarkProvider.AddBookmark(new Bookmark(lineNum)); - } - dataGridView.Refresh(); - filterGridView.Refresh(); - OnBookmarkAdded(); - } - - public void SetBookmarkFromTrigger (int lineNum, string comment) - { - lock (_bookmarkLock) - { - var line = _logFileReader.GetLogLine(lineNum); - if (line == null) - { - return; - } - var paramParser = new ParamParser(comment); - try - { - comment = paramParser.ReplaceParams(line, lineNum, FileName); - } - catch (ArgumentException) - { - // occurs on invalid regex - } - if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - _bookmarkProvider.RemoveBookmarkForLine(lineNum); - } - _bookmarkProvider.AddBookmark(new Bookmark(lineNum, comment)); - OnBookmarkAdded(); - } - } - - public void JumpNextBookmark () - { - if (_bookmarkProvider.Bookmarks.Count > 0) - { - if (filterGridView.Focused) - { - var index = FindNextBookmarkIndex(_filterResultList[filterGridView.CurrentCellAddress.Y]); - var startIndex = index; - var wrapped = false; - while (true) - { - var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - if (_filterResultList.Contains(lineNum)) - { - var filterLine = _filterResultList.IndexOf(lineNum); - filterGridView.Rows[filterLine].Selected = true; - filterGridView.CurrentCell = filterGridView.Rows[filterLine].Cells[0]; - break; - } - index++; - if (index > _bookmarkProvider.Bookmarks.Count - 1) - { - index = 0; - wrapped = true; - } - if (index >= startIndex && wrapped) - { - break; - } - } - } - else - { - var index = FindNextBookmarkIndex(dataGridView.CurrentCellAddress.Y); - if (index > _bookmarkProvider.Bookmarks.Count - 1) - { - index = 0; - } - - var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - SelectLine(lineNum, true, true); - } - } - } - - public void JumpPrevBookmark () - { - if (_bookmarkProvider.Bookmarks.Count > 0) - { - if (filterGridView.Focused) - { - //int index = this.bookmarkList.BinarySearch(this.filterResultList[this.filterGridView.CurrentCellAddress.Y]); - //if (index < 0) - // index = ~index; - //index--; - var index = FindPrevBookmarkIndex(_filterResultList[filterGridView.CurrentCellAddress.Y]); - if (index < 0) - { - index = _bookmarkProvider.Bookmarks.Count - 1; - } - var startIndex = index; - var wrapped = false; - while (true) - { - var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - if (_filterResultList.Contains(lineNum)) - { - var filterLine = _filterResultList.IndexOf(lineNum); - filterGridView.Rows[filterLine].Selected = true; - filterGridView.CurrentCell = filterGridView.Rows[filterLine].Cells[0]; - break; - } - index--; - if (index < 0) - { - index = _bookmarkProvider.Bookmarks.Count - 1; - wrapped = true; - } - if (index <= startIndex && wrapped) - { - break; - } - } - } - else - { - var index = FindPrevBookmarkIndex(dataGridView.CurrentCellAddress.Y); - if (index < 0) - { - index = _bookmarkProvider.Bookmarks.Count - 1; - } - - var lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - SelectLine(lineNum, false, true); - } - } - } - - public void DeleteBookmarks (List lineNumList) - { - var bookmarksPresent = false; - foreach (var lineNum in lineNumList) - { - if (lineNum != -1) - { - if (_bookmarkProvider.IsBookmarkAtLine(lineNum) && - _bookmarkProvider.GetBookmarkForLine(lineNum).Text.Length > 0) - { - bookmarksPresent = true; - } - } - } - if (bookmarksPresent) - { - if ( - MessageBox.Show("There are some comments in the bookmarks. Really remove bookmarks?", "LogExpert", - MessageBoxButtons.YesNo) == DialogResult.No) - { - return; - } - } - _bookmarkProvider.RemoveBookmarksForLines(lineNumList); - OnBookmarkRemoved(); - } - - public void SetTimeshiftValue (string value) - { - _guiStateArgs.TimeshiftText = value; - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - try - { - if (_guiStateArgs.TimeshiftEnabled) - { - try - { - var text = _guiStateArgs.TimeshiftText; - if (text.StartsWith("+")) - { - text = text.Substring(1); - } - var timeSpan = TimeSpan.Parse(text); - var diff = (int)(timeSpan.Ticks / TimeSpan.TicksPerMillisecond); - CurrentColumnizer.SetTimeOffset(diff); - } - catch (Exception) - { - CurrentColumnizer.SetTimeOffset(0); - } - } - else - { - CurrentColumnizer.SetTimeOffset(0); - } - dataGridView.Refresh(); - filterGridView.Refresh(); - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - SetTimestampLimits(); - SyncTimestampDisplay(); - } - } - catch (FormatException ex) - { - _logger.Error(ex); - } - } - } - - public void ToggleFilterPanel () - { - splitContainerLogWindow.Panel2Collapsed = !splitContainerLogWindow.Panel2Collapsed; - if (!splitContainerLogWindow.Panel2Collapsed) - { - filterComboBox.Focus(); - } - else - { - dataGridView.Focus(); - } - } - - public void LogWindowActivated () - { - if (_guiStateArgs.FollowTail && !_isDeadFile) - { - OnTailFollowed(EventArgs.Empty); - } - - if (Preferences.TimestampControl) - { - SetTimestampLimits(); - SyncTimestampDisplay(); - } - - dataGridView.Focus(); - - SendGuiStateUpdate(); - SendStatusLineUpdate(); - SendProgressBarUpdate(); - } - - public void SetCellSelectionMode (bool isCellMode) - { - if (isCellMode) - { - //possible performance issue, see => https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/best-practices-for-scaling-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8#using-the-selected-cells-rows-and-columns-collections-efficiently - dataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect; - } - else - { - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - } - - _guiStateArgs.CellSelectMode = isCellMode; - } - - public void TimeshiftEnabled (bool isEnabled, string shiftValue) - { - _guiStateArgs.TimeshiftEnabled = isEnabled; - SetTimestampLimits(); - SetTimeshiftValue(shiftValue); - } - - public void CopyMarkedLinesToTab () - { - if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) - { - var lineNumList = new List(); - foreach (DataGridViewRow row in dataGridView.SelectedRows) - { - if (row.Index != -1) - { - lineNumList.Add(row.Index); - } - } - - lineNumList.Sort(); - // create dummy FilterPipe for connecting line numbers to original window - // setting IsStopped to true prevents further filter processing - var pipe = new FilterPipe(new FilterParams(), this) - { - IsStopped = true - }; - WritePipeToTab(pipe, lineNumList, Text + "->C", null); - } - else - { - var fileName = Path.GetTempFileName(); - var fStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read); - var writer = new StreamWriter(fStream, Encoding.Unicode); - - var data = dataGridView.GetClipboardContent(); - var text = data.GetText(TextDataFormat.Text); - writer.Write(text); - - writer.Close(); - var title = Util.GetNameFromPath(FileName) + "->Clip"; - _parentLogTabWin.AddTempFileTab(fileName, title); - } - } - - /// - /// Change the file encoding. May force a reload if byte count ot preamble lenght differs from previous used encoding. - /// - /// - public void ChangeEncoding (Encoding encoding) - { - _logFileReader.ChangeEncoding(encoding); - EncodingOptions.Encoding = encoding; - if (_guiStateArgs.CurrentEncoding.IsSingleByte != encoding.IsSingleByte || - _guiStateArgs.CurrentEncoding.GetPreamble().Length != encoding.GetPreamble().Length) - { - Reload(); - } - else - { - dataGridView.Refresh(); - SendGuiStateUpdate(); - } - _guiStateArgs.CurrentEncoding = _logFileReader.CurrentEncoding; - } - - public void Reload () - { - SavePersistenceData(false); - - _reloadMemento = new ReloadMemento - { - CurrentLine = dataGridView.CurrentCellAddress.Y, - FirstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex - }; - _forcedColumnizerForLoading = CurrentColumnizer; - - if (_fileNames == null || !IsMultiFile) - { - LoadFile(FileName, EncodingOptions); - } - else - { - LoadFilesAsMulti(_fileNames, EncodingOptions); - } - //if (currentLine < this.dataGridView.RowCount && currentLine >= 0) - // this.dataGridView.CurrentCell = this.dataGridView.Rows[currentLine].Cells[0]; - //if (firstDisplayedLine < this.dataGridView.RowCount && firstDisplayedLine >= 0) - // this.dataGridView.FirstDisplayedScrollingRowIndex = firstDisplayedLine; - - //if (this.filterTailCheckBox.Checked) - //{ - // _logger.logInfo("Refreshing filter view because of reload."); - // FilterSearch(); - //} - } - - public void PreferencesChanged (string fontName, float fontSize, bool setLastColumnWidth, int lastColumnWidth, bool isLoadTime, SettingsFlags flags) - { - if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) - { - NormalFont = new Font(new FontFamily(fontName), fontSize); - BoldFont = new Font(NormalFont, FontStyle.Bold); - MonospacedFont = new Font("Courier New", Preferences.FontSize, FontStyle.Bold); - - var lineSpacing = NormalFont.FontFamily.GetLineSpacing(FontStyle.Regular); - var lineSpacingPixel = NormalFont.Size * lineSpacing / NormalFont.FontFamily.GetEmHeight(FontStyle.Regular); - - dataGridView.DefaultCellStyle.Font = NormalFont; - filterGridView.DefaultCellStyle.Font = NormalFont; - _lineHeight = NormalFont.Height + 4; - dataGridView.RowTemplate.Height = NormalFont.Height + 4; - - ShowBookmarkBubbles = Preferences.ShowBubbles; - - ApplyDataGridViewPrefs(dataGridView, setLastColumnWidth, lastColumnWidth); - ApplyDataGridViewPrefs(filterGridView, setLastColumnWidth, lastColumnWidth); - - if (Preferences.TimestampControl) - { - SetTimestampLimits(); - SyncTimestampDisplay(); - } - - if (isLoadTime) - { - filterTailCheckBox.Checked = Preferences.FilterTail; - syncFilterCheckBox.Checked = Preferences.FilterSync; - //this.FollowTailChanged(this.Preferences.followTail, false); - } - - _timeSpreadCalc.TimeMode = Preferences.TimeSpreadTimeMode; - timeSpreadingControl.ForeColor = Preferences.TimeSpreadColor; - timeSpreadingControl.ReverseAlpha = Preferences.ReverseAlpha; - - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - timeSpreadingControl.Invoke(new MethodInvoker(timeSpreadingControl.Refresh)); - ShowTimeSpread(Preferences.ShowTimeSpread); - } - - ToggleColumnFinder(Preferences.ShowColumnFinder, false); - } - - if ((flags & SettingsFlags.FilterList) == SettingsFlags.FilterList) - { - HandleChangedFilterList(); - } - - if ((flags & SettingsFlags.FilterHistory) == SettingsFlags.FilterHistory) - { - UpdateFilterHistoryFromSettings(); - - if (isLoadTime) - { - AutoResizeFilterBox(); - } - } - } - - public bool ScrollToTimestamp (DateTime timestamp, bool roundToSeconds, bool triggerSyncCall) - { - if (InvokeRequired) - { - BeginInvoke(new ScrollToTimestampFx(ScrollToTimestampWorker), timestamp, roundToSeconds, triggerSyncCall); - return true; - } - - return ScrollToTimestampWorker(timestamp, roundToSeconds, triggerSyncCall); - } - - public bool ScrollToTimestampWorker (DateTime timestamp, bool roundToSeconds, bool triggerSyncCall) - { - var hasScrolled = false; - if (!CurrentColumnizer.IsTimeshiftImplemented() || dataGridView.RowCount == 0) - { - return false; - } - - //this.Cursor = Cursors.WaitCursor; - var currentLine = dataGridView.CurrentCellAddress.Y; - if (currentLine < 0 || currentLine >= dataGridView.RowCount) - { - currentLine = 0; - } - var foundLine = FindTimestampLine(currentLine, timestamp, roundToSeconds); - if (foundLine >= 0) - { - SelectAndEnsureVisible(foundLine, triggerSyncCall); - hasScrolled = true; - } - //this.Cursor = Cursors.Default; - return hasScrolled; - } - - public int FindTimestampLine (int lineNum, DateTime timestamp, bool roundToSeconds) - { - var foundLine = - FindTimestampLine_Internal(lineNum, 0, dataGridView.RowCount - 1, timestamp, roundToSeconds); - if (foundLine >= 0) - { - // go backwards to the first occurence of the hit - var foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); - while (foundTimestamp.CompareTo(timestamp) == 0 && foundLine >= 0) - { - foundLine--; - foundTimestamp = GetTimestampForLine(ref foundLine, roundToSeconds); - } - if (foundLine < 0) - { - return 0; - } - - foundLine++; - GetTimestampForLineForward(ref foundLine, roundToSeconds); // fwd to next valid timestamp - return foundLine; - } - - return -foundLine; - } - - public int FindTimestampLine_Internal (int lineNum, int rangeStart, int rangeEnd, DateTime timestamp, - bool roundToSeconds) - { - _logger.Debug("FindTimestampLine_Internal(): timestamp={0}, lineNum={1}, rangeStart={2}, rangeEnd={3}", timestamp, lineNum, rangeStart, rangeEnd); - var refLine = lineNum; - var currentTimestamp = GetTimestampForLine(ref refLine, roundToSeconds); - if (currentTimestamp.CompareTo(timestamp) == 0) - { - return lineNum; - } - - if (timestamp < currentTimestamp) - { - //rangeStart = rangeStart; - rangeEnd = lineNum; - } - else - { - rangeStart = lineNum; - //rangeEnd = rangeEnd; - } - - if (rangeEnd - rangeStart <= 0) - { - return -lineNum; - } - - lineNum = ((rangeEnd - rangeStart) / 2) + rangeStart; - // prevent endless loop - if (rangeEnd - rangeStart < 2) - { - currentTimestamp = GetTimestampForLine(ref rangeStart, roundToSeconds); - if (currentTimestamp.CompareTo(timestamp) == 0) - { - return rangeStart; - } - - currentTimestamp = GetTimestampForLine(ref rangeEnd, roundToSeconds); - - return currentTimestamp.CompareTo(timestamp) == 0 - ? rangeEnd - : -lineNum; - } - - return FindTimestampLine_Internal(lineNum, rangeStart, rangeEnd, timestamp, roundToSeconds); - } - - /** - * Get the timestamp for the given line number. If the line - * has no timestamp, the previous line will be checked until a - * timestamp is found. - */ - public DateTime GetTimestampForLine (ref int lineNum, bool roundToSeconds) - { - lock (_currentColumnizerLock) - { - if (!CurrentColumnizer.IsTimeshiftImplemented()) - { - return DateTime.MinValue; - } - - _logger.Debug($"GetTimestampForLine({lineNum}) enter"); - var timeStamp = DateTime.MinValue; - var lookBack = false; - if (lineNum >= 0 && lineNum < dataGridView.RowCount) - { - while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum >= 0) - { - if (_isTimestampDisplaySyncing && _shouldTimestampDisplaySyncingCancel) - { - return DateTime.MinValue; - } - - lookBack = true; - var logLine = _logFileReader.GetLogLine(lineNum); - if (logLine == null) - { - return DateTime.MinValue; - } - - ColumnizerCallbackObject.LineNum = lineNum; - timeStamp = CurrentColumnizer.GetTimestamp(ColumnizerCallbackObject, logLine); - if (roundToSeconds) - { - timeStamp = timeStamp.Subtract(TimeSpan.FromMilliseconds(timeStamp.Millisecond)); - } - - lineNum--; - } - } - - if (lookBack) - { - lineNum++; - } - - _logger.Debug("GetTimestampForLine() leave with lineNum={0}", lineNum); - return timeStamp; - } - } - - /** - * Get the timestamp for the given line number. If the line - * has no timestamp, the next line will be checked until a - * timestamp is found. - */ - public DateTime GetTimestampForLineForward (ref int lineNum, bool roundToSeconds) - { - lock (_currentColumnizerLock) - { - if (!CurrentColumnizer.IsTimeshiftImplemented()) - { - return DateTime.MinValue; - } - - var timeStamp = DateTime.MinValue; - var lookFwd = false; - if (lineNum >= 0 && lineNum < dataGridView.RowCount) - { - while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum < dataGridView.RowCount) - { - lookFwd = true; - var logLine = _logFileReader.GetLogLine(lineNum); - if (logLine == null) - { - timeStamp = DateTime.MinValue; - break; - } - timeStamp = CurrentColumnizer.GetTimestamp(ColumnizerCallbackObject, logLine); - if (roundToSeconds) - { - timeStamp = timeStamp.Subtract(TimeSpan.FromMilliseconds(timeStamp.Millisecond)); - } - lineNum++; - } - } - if (lookFwd) - { - lineNum--; - } - return timeStamp; - } - } - - public void AppFocusLost () - { - InvalidateCurrentRow(dataGridView); - } - - public void AppFocusGained () - { - InvalidateCurrentRow(dataGridView); - } - - public ILogLine GetCurrentLine () - { - if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index != -1) - { - return _logFileReader.GetLogLine(dataGridView.CurrentRow.Index); - } - return null; - } - - public ILogLine GetLine (int lineNum) - { - if (lineNum < 0 || _logFileReader == null || lineNum >= _logFileReader.LineCount) - { - return null; - } - return _logFileReader.GetLogLine(lineNum); - } - - public int GetCurrentLineNum () - { - if (dataGridView.CurrentRow == null) - { - return -1; - } - return dataGridView.CurrentRow.Index; - } - - public int GetRealLineNum () - { - var lineNum = GetCurrentLineNum(); - if (lineNum == -1) - { - return -1; - } - return _logFileReader.GetRealLineNumForVirtualLineNum(lineNum); - } - - public ILogFileInfo GetCurrentFileInfo () - { - if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index != -1) - { - return _logFileReader.GetLogFileInfoForLine(dataGridView.CurrentRow.Index); - } - return null; - } - - /// - /// zero-based - /// - /// - /// - public string GetCurrentFileName (int lineNum) - { - return _logFileReader.GetLogFileNameForLine(lineNum); - } - - // =============== end of bookmark stuff =================================== - - public void ShowLineColumn (bool show) - { - dataGridView.Columns[1].Visible = show; - filterGridView.Columns[1].Visible = show; - } - - // ================================================================= - // Pattern statistics - // ================================================================= - - public void PatternStatistic () - { - InitPatternWindow(); - } - - public void PatternStatisticSelectRange (PatternArgs patternArgs) - { - if (dataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect) - { - List lineNumList = []; - foreach (DataGridViewRow row in dataGridView.SelectedRows) - { - if (row.Index != -1) - { - lineNumList.Add(row.Index); - } - } - lineNumList.Sort(); - patternArgs.StartLine = lineNumList[0]; - patternArgs.EndLine = lineNumList[^1]; - } - else - { - patternArgs.StartLine = dataGridView.CurrentCellAddress.Y != -1 - ? dataGridView.CurrentCellAddress.Y - : 0; - patternArgs.EndLine = dataGridView.RowCount - 1; - } - } - - public void PatternStatistic (PatternArgs patternArgs) - { - var fx = new PatternStatisticFx(TestStatistic); - fx.BeginInvoke(patternArgs, null, null); - } - - public void ExportBookmarkList () - { - SaveFileDialog dlg = new() - { - Title = "Choose a file to save bookmarks into", - AddExtension = true, - DefaultExt = "csv", - Filter = "CSV file (*.csv)|*.csv|Bookmark file (*.bmk)|*.bmk", - FilterIndex = 1, - FileName = Path.GetFileNameWithoutExtension(FileName) - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - try - { - BookmarkExporter.ExportBookmarkList(_bookmarkProvider.BookmarkList, FileName, - dlg.FileName); - } - catch (IOException e) - { - _logger.Error(e); - MessageBox.Show("Error while exporting bookmark list: " + e.Message, "LogExpert"); - } - } - } - - public void ImportBookmarkList () - { - OpenFileDialog dlg = new() - { - Title = "Choose a file to load bookmarks from", - AddExtension = true, - DefaultExt = "csv", - Filter = "CSV file (*.csv)|*.csv|Bookmark file (*.bmk)|*.bmk", - FilterIndex = 1, - FileName = Path.GetFileNameWithoutExtension(FileName) - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - try - { - // add to the existing bookmarks - SortedList newBookmarks = []; - BookmarkExporter.ImportBookmarkList(FileName, dlg.FileName, newBookmarks); - - // Add (or replace) to existing bookmark list - var bookmarkAdded = false; - foreach (var b in newBookmarks.Values) - { - if (!_bookmarkProvider.BookmarkList.ContainsKey(b.LineNum)) - { - _bookmarkProvider.BookmarkList.Add(b.LineNum, b); - bookmarkAdded = true; // refresh the list only once at the end - } - else - { - var existingBookmark = _bookmarkProvider.BookmarkList[b.LineNum]; - existingBookmark.Text = - b.Text; // replace existing bookmark for that line, preserving the overlay - OnBookmarkTextChanged(b); - } - } - - // Refresh the lists - if (bookmarkAdded) - { - OnBookmarkAdded(); - } - dataGridView.Refresh(); - filterGridView.Refresh(); - } - catch (IOException e) - { - _logger.Error(e); - MessageBox.Show($"Error while importing bookmark list: {e.Message}", "LogExpert"); - } - } - } - - public bool IsAdvancedOptionActive () - { - return rangeCheckBox.Checked || - fuzzyKnobControl.Value > 0 || - filterKnobBackSpread.Value > 0 || - filterKnobForeSpread.Value > 0 || - invertFilterCheckBox.Checked || - columnRestrictCheckBox.Checked; - } - - public void HandleChangedFilterList () - { - Invoke(new MethodInvoker(HandleChangedFilterListWorker)); - } - - public void HandleChangedFilterListWorker () - { - var index = filterListBox.SelectedIndex; - filterListBox.Items.Clear(); - foreach (var filterParam in ConfigManager.Settings.FilterList) - { - filterListBox.Items.Add(filterParam); - } - filterListBox.Refresh(); - if (index >= 0 && index < filterListBox.Items.Count) - { - filterListBox.SelectedIndex = index; - } - filterOnLoadCheckBox.Checked = Preferences.IsFilterOnLoad; - hideFilterListOnLoadCheckBox.Checked = Preferences.IsAutoHideFilterList; - } - - public void SetCurrentHighlightGroup (string groupName) - { - _guiStateArgs.HighlightGroupName = groupName; - lock (_currentHighlightGroupLock) - { - _currentHighlightGroup = _parentLogTabWin.FindHighlightGroup(groupName); - - _currentHighlightGroup ??= _parentLogTabWin.HighlightGroupList.Count > 0 - ? _parentLogTabWin.HighlightGroupList[0] - : new HighlightGroup(); - - _guiStateArgs.HighlightGroupName = _currentHighlightGroup.GroupName; - } - - SendGuiStateUpdate(); - BeginInvoke(new MethodInvoker(RefreshAllGrids)); - } - - public void SwitchMultiFile (bool enabled) - { - IsMultiFile = enabled; - Reload(); - } - - public void AddOtherWindowToTimesync (LogWindow other) - { - if (other.IsTimeSynced) - { - if (IsTimeSynced) - { - other.FreeFromTimeSync(); - AddSlaveToTimesync(other); - } - else - { - AddToTimeSync(other); - } - } - else - { - AddSlaveToTimesync(other); - } - } - - public void AddToTimeSync (LogWindow master) - { - _logger.Info($"Syncing window for {Util.GetNameFromPath(FileName)} to {Util.GetNameFromPath(master.FileName)}"); - lock (_timeSyncListLock) - { - if (IsTimeSynced && master.TimeSyncList != TimeSyncList) - // already synced but master has different sync list - { - FreeFromTimeSync(); - } - - TimeSyncList = master.TimeSyncList; - TimeSyncList.AddWindow(this); - ScrollToTimestamp(TimeSyncList.CurrentTimestamp, false, false); - } - - OnSyncModeChanged(); - } - - public void FreeFromTimeSync () - { - lock (_timeSyncListLock) - { - if (TimeSyncList != null) - { - _logger.Info($"De-Syncing window for {Util.GetNameFromPath(FileName)}"); - TimeSyncList.WindowRemoved -= OnTimeSyncListWindowRemoved; - TimeSyncList.RemoveWindow(this); - TimeSyncList = null; - } - } - - OnSyncModeChanged(); - } - - public void RefreshLogView () - { - RefreshAllGrids(); - } - - #endregion -} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index 88889378..2eb2d0f7 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -1,14 +1,32 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; using System.Reflection; using System.Runtime.Versioning; +using System.Security; using System.Text; +using System.Text.RegularExpressions; +using LogExpert.Core.Classes; +using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Classes.Filter; +using LogExpert.Core.Classes.Persister; using LogExpert.Core.Config; using LogExpert.Core.Entities; +using LogExpert.Core.Enums; +using LogExpert.Core.EventArguments; using LogExpert.Core.Interface; using LogExpert.Dialogs; +using LogExpert.PluginRegistry.FileSystem; +using LogExpert.UI.Dialogs; +using LogExpert.UI.Entities; +using LogExpert.UI.Extensions; +using LogExpert.UI.Extensions.LogWindow; using NLog; +using WeifenLuo.WinFormsUI.Docking; + namespace LogExpert.UI.Controls.LogTabWindow; // Data shared over all LogTabWindow instances @@ -261,4 +279,2773 @@ private class LogWindowData #endregion } + + #region Public methods + + [SupportedOSPlatform("windows")] + public LogWindow.LogWindow AddTempFileTab (string fileName, string title) + { + return AddFileTab(fileName, true, title, false, null); + } + + [SupportedOSPlatform("windows")] + public LogWindow.LogWindow AddFilterTab (FilterPipe pipe, string title, ILogLineColumnizer preProcessColumnizer) + { + var logWin = AddFileTab(pipe.FileName, true, title, false, preProcessColumnizer); + if (pipe.FilterParams.SearchText.Length > 0) + { + ToolTip tip = new(components); + + tip.SetToolTip(logWin, + "Filter: \"" + pipe.FilterParams.SearchText + "\"" + + (pipe.FilterParams.IsInvert ? " (Invert match)" : "") + + (pipe.FilterParams.ColumnRestrict ? "\nColumn restrict" : "") + ); + + tip.AutomaticDelay = 10; + tip.AutoPopDelay = 5000; + var data = logWin.Tag as LogWindowData; + data.ToolTip = tip; + } + + return logWin; + } + + [SupportedOSPlatform("windows")] + public LogWindow.LogWindow AddFileTabDeferred (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer) + { + return AddFileTab(givenFileName, isTempFile, title, forcePersistenceLoading, preProcessColumnizer, true); + } + + [SupportedOSPlatform("windows")] + public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer, bool doNotAddToDockPanel = false) + { + var logFileName = FindFilenameForSettings(givenFileName); + var win = FindWindowForFile(logFileName); + if (win != null) + { + if (!isTempFile) + { + AddToFileHistory(givenFileName); + } + + SelectTab(win); + return win; + } + + EncodingOptions encodingOptions = new(); + FillDefaultEncodingFromSettings(encodingOptions); + LogWindow.LogWindow logWindow = new(this, logFileName, isTempFile, forcePersistenceLoading, ConfigManager) + { + GivenFileName = givenFileName + }; + + if (preProcessColumnizer != null) + { + logWindow.ForceColumnizerForLoading(preProcessColumnizer); + } + + if (isTempFile) + { + logWindow.TempTitleName = title; + encodingOptions.Encoding = new UnicodeEncoding(false, false); + } + + AddLogWindow(logWindow, title, doNotAddToDockPanel); + if (!isTempFile) + { + AddToFileHistory(givenFileName); + } + + var data = logWindow.Tag as LogWindowData; + data.Color = _defaultTabColor; + SetTabColor(logWindow, _defaultTabColor); + //data.tabPage.BorderColor = this.defaultTabBorderColor; + if (!isTempFile) + { + foreach (var colorEntry in ConfigManager.Settings.FileColors) + { + if (colorEntry.FileName.ToUpperInvariant().Equals(logFileName.ToUpperInvariant(), StringComparison.Ordinal)) + { + data.Color = colorEntry.Color; + SetTabColor(logWindow, colorEntry.Color); + break; + } + } + } + + if (!isTempFile) + { + SetTooltipText(logWindow, logFileName); + } + + if (givenFileName.EndsWith(".lxp", StringComparison.Ordinal)) + { + logWindow.ForcedPersistenceFileName = givenFileName; + } + + // this.BeginInvoke(new LoadFileDelegate(logWindow.LoadFile), new object[] { logFileName, encoding }); + Task.Run(() => logWindow.LoadFile(logFileName, encodingOptions)); + return logWindow; + } + + [SupportedOSPlatform("windows")] + public LogWindow.LogWindow AddMultiFileTab (string[] fileNames) + { + if (fileNames.Length < 1) + { + return null; + } + + LogWindow.LogWindow logWindow = new(this, fileNames[^1], false, false, ConfigManager); + AddLogWindow(logWindow, fileNames[^1], false); + multiFileToolStripMenuItem.Checked = true; + multiFileEnabledStripMenuItem.Checked = true; + EncodingOptions encodingOptions = new(); + FillDefaultEncodingFromSettings(encodingOptions); + BeginInvoke(new LoadMultiFilesDelegate(logWindow.LoadFilesAsMulti), fileNames, encodingOptions); + AddToFileHistory(fileNames[0]); + return logWindow; + } + + [SupportedOSPlatform("windows")] + public void LoadFiles (string[] fileNames) + { + Invoke(new AddFileTabsDelegate(AddFileTabs), [fileNames]); + } + + [SupportedOSPlatform("windows")] + public void OpenSearchDialog () + { + if (CurrentLogWindow == null) + { + return; + } + + SearchDialog dlg = new(); + AddOwnedForm(dlg); + dlg.TopMost = TopMost; + SearchParams.HistoryList = ConfigManager.Settings.SearchHistoryList; + dlg.SearchParams = SearchParams; + var res = dlg.ShowDialog(); + if (res == DialogResult.OK && dlg.SearchParams != null && !string.IsNullOrWhiteSpace(dlg.SearchParams.SearchText)) + { + SearchParams = dlg.SearchParams; + SearchParams.IsFindNext = false; + CurrentLogWindow.StartSearch(); + } + } + + public ILogLineColumnizer GetColumnizerHistoryEntry (string fileName) + { + var entry = FindColumnizerHistoryEntry(fileName); + if (entry != null) + { + foreach (var columnizer in PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers) + { + if (columnizer.GetName().Equals(entry.ColumnizerName, StringComparison.Ordinal)) + { + return columnizer; + } + } + + ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); // no valid name -> remove entry + } + + return null; + } + + public void SwitchTab (bool shiftPressed) + { + var index = dockPanel.Contents.IndexOf(dockPanel.ActiveContent); + if (shiftPressed) + { + index--; + if (index < 0) + { + index = dockPanel.Contents.Count - 1; + } + + if (index < 0) + { + return; + } + } + else + { + index++; + if (index >= dockPanel.Contents.Count) + { + index = 0; + } + } + + if (index < dockPanel.Contents.Count) + { + (dockPanel.Contents[index] as DockContent).Activate(); + } + } + + public void ScrollAllTabsToTimestamp (DateTime timestamp, LogWindow.LogWindow senderWindow) + { + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + if (logWindow != senderWindow) + { + if (logWindow.ScrollToTimestamp(timestamp, false, false)) + { + ShowLedPeak(logWindow); + } + } + } + } + } + + public ILogLineColumnizer FindColumnizerByFileMask (string fileName) + { + foreach (var entry in ConfigManager.Settings.Preferences.ColumnizerMaskList) + { + if (entry.Mask != null) + { + try + { + if (Regex.IsMatch(fileName, entry.Mask)) + { + var columnizer = ColumnizerPicker.FindColumnizerByName(entry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + return columnizer; + } + } + catch (ArgumentException e) + { + _logger.Error(e, "RegEx-error while finding columnizer: "); + // occurs on invalid regex patterns + } + } + } + + return null; + } + + public HighlightGroup FindHighlightGroupByFileMask (string fileName) + { + foreach (var entry in ConfigManager.Settings.Preferences.HighlightMaskList) + { + if (entry.Mask != null) + { + try + { + if (Regex.IsMatch(fileName, entry.Mask)) + { + var group = FindHighlightGroup(entry.HighlightGroupName); + return group; + } + } + catch (ArgumentException e) + { + _logger.Error(e, "RegEx-error while finding columnizer: "); + // occurs on invalid regex patterns + } + } + } + + return null; + } + + public void SelectTab (ILogWindow logWindow) + { + logWindow.Activate(); + } + + [SupportedOSPlatform("windows")] + public void SetForeground () + { + NativeMethods.SetForegroundWindow(Handle); + if (WindowState == FormWindowState.Minimized) + { + if (_wasMaximized) + { + WindowState = FormWindowState.Maximized; + } + else + { + WindowState = FormWindowState.Normal; + } + } + } + + // called from LogWindow when follow tail was changed + [SupportedOSPlatform("windows")] + public void FollowTailChanged (LogWindow.LogWindow logWindow, bool isEnabled, bool offByTrigger) + { + if (logWindow.Tag is not LogWindowData data) + { + return; + } + + if (isEnabled) + { + data.TailState = 0; + } + else + { + data.TailState = offByTrigger ? 2 : 1; + } + + if (Preferences.ShowTailState) + { + var icon = GetIcon(data.DiffSum, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); + } + } + + [SupportedOSPlatform("windows")] + public void NotifySettingsChanged (object sender, SettingsFlags flags) + { + if (sender != this) + { + NotifyWindowsForChangedPrefs(flags); + } + } + + public IList GetListOfOpenFiles () + { + IList list = []; + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + list.Add(new WindowFileEntry(logWindow)); + } + } + + return list; + } + + #endregion + + #region Private Methods + + /// + /// Creates a temp file with the text content of the clipboard and opens the temp file in a new tab. + /// + [SupportedOSPlatform("windows")] + private void PasteFromClipboard () + { + if (Clipboard.ContainsText()) + { + var text = Clipboard.GetText(); + var fileName = Path.GetTempFileName(); + + using (FileStream fStream = new(fileName, FileMode.Append, FileAccess.Write, FileShare.Read)) + using (StreamWriter writer = new(fStream, Encoding.Unicode)) + { + writer.Write(text); + writer.Close(); + } + + var title = "Clipboard"; + var logWindow = AddTempFileTab(fileName, title); + if (logWindow.Tag is LogWindowData data) + { + SetTooltipText(logWindow, "Pasted on " + DateTime.Now); + } + } + } + + [SupportedOSPlatform("windows")] + private void InitToolWindows () + { + InitBookmarkWindow(); + } + + [SupportedOSPlatform("windows")] + private void DestroyToolWindows () + { + DestroyBookmarkWindow(); + } + + [SupportedOSPlatform("windows")] + private void InitBookmarkWindow () + { + _bookmarkWindow = new BookmarkWindow + { + HideOnClose = true, + ShowHint = DockState.DockBottom + }; + + var setLastColumnWidth = ConfigManager.Settings.Preferences.SetLastColumnWidth; + var lastColumnWidth = ConfigManager.Settings.Preferences.LastColumnWidth; + var fontName = ConfigManager.Settings.Preferences.FontName; + var fontSize = ConfigManager.Settings.Preferences.FontSize; + + _bookmarkWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, SettingsFlags.All); + _bookmarkWindow.VisibleChanged += OnBookmarkWindowVisibleChanged; + _firstBookmarkWindowShow = true; + } + + [SupportedOSPlatform("windows")] + private void DestroyBookmarkWindow () + { + _bookmarkWindow.HideOnClose = false; + _bookmarkWindow.Close(); + } + + private void SaveLastOpenFilesList () + { + ConfigManager.Settings.LastOpenFilesList.Clear(); + foreach (DockContent content in dockPanel.Contents) + { + if (content is LogWindow.LogWindow logWin) + { + if (!logWin.IsTempFile) + { + ConfigManager.Settings.LastOpenFilesList.Add(logWin.GivenFileName); + } + } + } + } + + [SupportedOSPlatform("windows")] + private void SaveWindowPosition () + { + SuspendLayout(); + if (WindowState == FormWindowState.Normal) + { + ConfigManager.Settings.AppBounds = Bounds; + ConfigManager.Settings.IsMaximized = false; + } + else + { + ConfigManager.Settings.AppBoundsFullscreen = Bounds; + ConfigManager.Settings.IsMaximized = true; + WindowState = FormWindowState.Normal; + ConfigManager.Settings.AppBounds = Bounds; + } + + ResumeLayout(); + } + + private void SetTooltipText (LogWindow.LogWindow logWindow, string logFileName) + { + logWindow.ToolTipText = logFileName; + } + + private void FillDefaultEncodingFromSettings (EncodingOptions encodingOptions) + { + if (ConfigManager.Settings.Preferences.DefaultEncoding != null) + { + try + { + encodingOptions.DefaultEncoding = Encoding.GetEncoding(ConfigManager.Settings.Preferences.DefaultEncoding); + } + catch (ArgumentException) + { + _logger.Warn(CultureInfo.InvariantCulture, "Encoding " + ConfigManager.Settings.Preferences.DefaultEncoding + " is not a valid encoding"); + encodingOptions.DefaultEncoding = null; + } + } + } + + [SupportedOSPlatform("windows")] + private void AddFileTabs (string[] fileNames) + { + foreach (var fileName in fileNames) + { + if (!string.IsNullOrEmpty(fileName)) + { + if (fileName.EndsWith(".lxj")) + { + LoadProject(fileName, false); + } + else + { + AddFileTab(fileName, false, null, false, null); + } + } + } + + Activate(); + } + + [SupportedOSPlatform("windows")] + private void AddLogWindow (LogWindow.LogWindow logWindow, string title, bool doNotAddToPanel) + { + logWindow.CloseButton = true; + logWindow.TabPageContextMenuStrip = tabContextMenuStrip; + SetTooltipText(logWindow, title); + logWindow.DockAreas = DockAreas.Document | DockAreas.Float; + + if (!doNotAddToPanel) + { + logWindow.Show(dockPanel); + } + + LogWindowData data = new() + { + DiffSum = 0 + }; + + logWindow.Tag = data; + + lock (_logWindowList) + { + _logWindowList.Add(logWindow); + } + + logWindow.FileSizeChanged += OnFileSizeChanged; + logWindow.TailFollowed += OnTailFollowed; + logWindow.Disposed += OnLogWindowDisposed; + logWindow.FileNotFound += OnLogWindowFileNotFound; + logWindow.FileRespawned += OnLogWindowFileRespawned; + logWindow.FilterListChanged += OnLogWindowFilterListChanged; + logWindow.CurrentHighlightGroupChanged += OnLogWindowCurrentHighlightGroupChanged; + logWindow.SyncModeChanged += OnLogWindowSyncModeChanged; + + logWindow.Visible = true; + } + + [SupportedOSPlatform("windows")] + private void DisconnectEventHandlers (LogWindow.LogWindow logWindow) + { + logWindow.FileSizeChanged -= OnFileSizeChanged; + logWindow.TailFollowed -= OnTailFollowed; + logWindow.Disposed -= OnLogWindowDisposed; + logWindow.FileNotFound -= OnLogWindowFileNotFound; + logWindow.FileRespawned -= OnLogWindowFileRespawned; + logWindow.FilterListChanged -= OnLogWindowFilterListChanged; + logWindow.CurrentHighlightGroupChanged -= OnLogWindowCurrentHighlightGroupChanged; + logWindow.SyncModeChanged -= OnLogWindowSyncModeChanged; + + var data = logWindow.Tag as LogWindowData; + //data.tabPage.MouseClick -= tabPage_MouseClick; + //data.tabPage.TabDoubleClick -= tabPage_TabDoubleClick; + //data.tabPage.ContextMenuStrip = null; + //data.tabPage = null; + } + + [SupportedOSPlatform("windows")] + private void AddToFileHistory (string fileName) + { + bool FindName (string s) => s.ToUpperInvariant().Equals(fileName.ToUpperInvariant(), StringComparison.Ordinal); + + var index = ConfigManager.Settings.FileHistoryList.FindIndex(FindName); + + if (index != -1) + { + ConfigManager.Settings.FileHistoryList.RemoveAt(index); + } + + ConfigManager.Settings.FileHistoryList.Insert(0, fileName); + + while (ConfigManager.Settings.FileHistoryList.Count > MAX_FILE_HISTORY) + { + ConfigManager.Settings.FileHistoryList.RemoveAt(ConfigManager.Settings.FileHistoryList.Count - 1); + } + + ConfigManager.Save(SettingsFlags.FileHistory); + + FillHistoryMenu(); + } + + [SupportedOSPlatform("windows")] + private LogWindow.LogWindow FindWindowForFile (string fileName) + { + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + if (logWindow.FileName.ToUpperInvariant().Equals(fileName.ToUpperInvariant(), StringComparison.Ordinal)) + { + return logWindow; + } + } + } + + return null; + } + + /// + /// Checks if the file name is a settings file. If so, the contained logfile name + /// is returned. If not, the given file name is returned unchanged. + /// + /// + /// + private string FindFilenameForSettings (string fileName) + { + if (fileName.EndsWith(".lxp")) + { + var persistenceData = Persister.LoadOptionsOnly(fileName); + if (persistenceData == null) + { + return fileName; + } + + if (!string.IsNullOrEmpty(persistenceData.FileName)) + { + var fs = PluginRegistry.PluginRegistry.Instance.FindFileSystemForUri(persistenceData.FileName); + if (fs != null && !fs.GetType().Equals(typeof(LocalFileSystem))) + { + return persistenceData.FileName; + } + + // On relative paths the URI check (and therefore the file system plugin check) will fail. + // So fs == null and fs == LocalFileSystem are handled here like normal files. + if (Path.IsPathRooted(persistenceData.FileName)) + { + return persistenceData.FileName; + } + + // handle relative paths in .lxp files + var dir = Path.GetDirectoryName(fileName); + return Path.Combine(dir, persistenceData.FileName); + } + } + + return fileName; + } + + [SupportedOSPlatform("windows")] + private void FillHistoryMenu () + { + ToolStripDropDown strip = new ToolStripDropDownMenu(); + + foreach (var file in ConfigManager.Settings.FileHistoryList) + { + ToolStripItem item = new ToolStripMenuItem(file); + strip.Items.Add(item); + } + + strip.ItemClicked += OnHistoryItemClicked; + strip.MouseUp += OnStripMouseUp; + lastUsedToolStripMenuItem.DropDown = strip; + } + + [SupportedOSPlatform("windows")] + private void RemoveLogWindow (LogWindow.LogWindow logWindow) + { + lock (_logWindowList) + { + _logWindowList.Remove(logWindow); + } + + DisconnectEventHandlers(logWindow); + } + + [SupportedOSPlatform("windows")] + private void RemoveAndDisposeLogWindow (LogWindow.LogWindow logWindow, bool dontAsk) + { + if (CurrentLogWindow == logWindow) + { + ChangeCurrentLogWindow(null); + } + + lock (_logWindowList) + { + _logWindowList.Remove(logWindow); + } + + logWindow.Close(dontAsk); + } + + [SupportedOSPlatform("windows")] + private void ShowHighlightSettingsDialog () + { + HighlightDialog dlg = new(ConfigManager) + { + KeywordActionList = PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions, + Owner = this, + TopMost = TopMost, + HighlightGroupList = HighlightGroupList, + PreSelectedGroupName = groupsComboBoxHighlightGroups.Text + }; + + var res = dlg.ShowDialog(); + + if (res == DialogResult.OK) + { + HighlightGroupList = dlg.HighlightGroupList; + FillHighlightComboBox(); + ConfigManager.Settings.Preferences.HighlightGroupList = HighlightGroupList; + ConfigManager.Save(SettingsFlags.HighlightSettings); + OnHighlightSettingsChanged(); + } + } + + [SupportedOSPlatform("windows")] + private void FillHighlightComboBox () + { + var currentGroupName = groupsComboBoxHighlightGroups.Text; + groupsComboBoxHighlightGroups.Items.Clear(); + foreach (var group in HighlightGroupList) + { + groupsComboBoxHighlightGroups.Items.Add(group.GroupName); + if (group.GroupName.Equals(currentGroupName, StringComparison.Ordinal)) + { + groupsComboBoxHighlightGroups.Text = group.GroupName; + } + } + } + + [SupportedOSPlatform("windows")] + private void OpenFileDialog () + { + OpenFileDialog openFileDialog = new(); + + if (CurrentLogWindow != null) + { + FileInfo info = new(CurrentLogWindow.FileName); + openFileDialog.InitialDirectory = info.DirectoryName; + } + else + { + if (!string.IsNullOrEmpty(ConfigManager.Settings.LastDirectory)) + { + openFileDialog.InitialDirectory = ConfigManager.Settings.LastDirectory; + } + else + { + try + { + openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + } + catch (SecurityException e) + { + _logger.Warn(e, "Insufficient rights for GetFolderPath(): "); + // no initial directory if insufficient rights + } + } + } + + openFileDialog.Multiselect = true; + + if (DialogResult.OK == openFileDialog.ShowDialog(this)) + { + FileInfo info = new(openFileDialog.FileName); + if (info.Directory.Exists) + { + ConfigManager.Settings.LastDirectory = info.DirectoryName; + ConfigManager.Save(SettingsFlags.FileHistory); + } + + if (info.Exists) + { + LoadFiles(openFileDialog.FileNames, false); + } + } + } + + [SupportedOSPlatform("windows")] + private void LoadFiles (string[] names, bool invertLogic) + { + Array.Sort(names); + + if (names.Length == 1) + { + if (names[0].EndsWith(".lxj")) + { + LoadProject(names[0], true); + return; + } + + AddFileTab(names[0], false, null, false, null); + return; + } + + var option = ConfigManager.Settings.Preferences.MultiFileOption; + if (option == MultiFileOption.Ask) + { + MultiLoadRequestDialog dlg = new(); + var res = dlg.ShowDialog(); + + if (res == DialogResult.Yes) + { + option = MultiFileOption.SingleFiles; + } + else if (res == DialogResult.No) + { + option = MultiFileOption.MultiFile; + } + else + { + return; + } + } + else + { + if (invertLogic) + { + option = option == MultiFileOption.SingleFiles + ? MultiFileOption.MultiFile + : MultiFileOption.SingleFiles; + } + } + + if (option == MultiFileOption.SingleFiles) + { + AddFileTabs(names); + } + else + { + AddMultiFileTab(names); + } + } + + private void SetColumnizerHistoryEntry (string fileName, ILogLineColumnizer columnizer) + { + var entry = FindColumnizerHistoryEntry(fileName); + if (entry != null) + { + _ = ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); + + } + + ConfigManager.Settings.ColumnizerHistoryList.Add(new ColumnizerHistoryEntry(fileName, columnizer.GetName())); + + if (ConfigManager.Settings.ColumnizerHistoryList.Count > MAX_COLUMNIZER_HISTORY) + { + ConfigManager.Settings.ColumnizerHistoryList.RemoveAt(0); + } + } + + private ColumnizerHistoryEntry FindColumnizerHistoryEntry (string fileName) + { + foreach (var entry in ConfigManager.Settings.ColumnizerHistoryList) + { + if (entry.FileName.Equals(fileName, StringComparison.Ordinal)) + { + return entry; + } + } + + return null; + } + + [SupportedOSPlatform("windows")] + private void ToggleMultiFile () + { + if (CurrentLogWindow != null) + { + CurrentLogWindow.SwitchMultiFile(!CurrentLogWindow.IsMultiFile); + multiFileToolStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; + multiFileEnabledStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; + } + } + + [SupportedOSPlatform("windows")] + private void ChangeCurrentLogWindow (LogWindow.LogWindow newLogWindow) + { + if (newLogWindow == _currentLogWindow) + { + return; // do nothing if wishing to set the same window + } + + var oldLogWindow = _currentLogWindow; + _currentLogWindow = newLogWindow; + var titleName = _showInstanceNumbers ? "LogExpert #" + _instanceNumber : "LogExpert"; + + if (oldLogWindow != null) + { + oldLogWindow.StatusLineEvent -= OnStatusLineEvent; + oldLogWindow.ProgressBarUpdate -= OnProgressBarUpdate; + oldLogWindow.GuiStateUpdate -= OnGuiStateUpdate; + oldLogWindow.ColumnizerChanged -= OnColumnizerChanged; + oldLogWindow.BookmarkAdded -= OnBookmarkAdded; + oldLogWindow.BookmarkRemoved -= OnBookmarkRemoved; + oldLogWindow.BookmarkTextChanged -= OnBookmarkTextChanged; + DisconnectToolWindows(oldLogWindow); + } + + if (newLogWindow != null) + { + newLogWindow.StatusLineEvent += OnStatusLineEvent; + newLogWindow.ProgressBarUpdate += OnProgressBarUpdate; + newLogWindow.GuiStateUpdate += OnGuiStateUpdate; + newLogWindow.ColumnizerChanged += OnColumnizerChanged; + newLogWindow.BookmarkAdded += OnBookmarkAdded; + newLogWindow.BookmarkRemoved += OnBookmarkRemoved; + newLogWindow.BookmarkTextChanged += OnBookmarkTextChanged; + + Text = newLogWindow.IsTempFile + ? titleName + @" - " + newLogWindow.TempTitleName + : titleName + @" - " + newLogWindow.FileName; + + multiFileToolStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; + multiFileToolStripMenuItem.Enabled = true; + multiFileEnabledStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; + cellSelectModeToolStripMenuItem.Checked = true; + cellSelectModeToolStripMenuItem.Enabled = true; + closeFileToolStripMenuItem.Enabled = true; + searchToolStripMenuItem.Enabled = true; + filterToolStripMenuItem.Enabled = true; + goToLineToolStripMenuItem.Enabled = true; + //ConnectToolWindows(newLogWindow); + } + else + { + Text = titleName; + multiFileToolStripMenuItem.Checked = false; + multiFileEnabledStripMenuItem.Checked = false; + checkBoxFollowTail.Checked = false; + mainMenuStrip.Enabled = true; + timeshiftToolStripMenuItem.Enabled = false; + timeshiftToolStripMenuItem.Checked = false; + timeshiftMenuTextBox.Text = ""; + timeshiftMenuTextBox.Enabled = false; + multiFileToolStripMenuItem.Enabled = false; + cellSelectModeToolStripMenuItem.Checked = false; + cellSelectModeToolStripMenuItem.Enabled = false; + closeFileToolStripMenuItem.Enabled = false; + searchToolStripMenuItem.Enabled = false; + filterToolStripMenuItem.Enabled = false; + goToLineToolStripMenuItem.Enabled = false; + dragControlDateTime.Visible = false; + } + } + + private void ConnectToolWindows (LogWindow.LogWindow logWindow) + { + ConnectBookmarkWindow(logWindow); + } + + private void ConnectBookmarkWindow (LogWindow.LogWindow logWindow) + { + FileViewContext ctx = new(logWindow, logWindow); + _bookmarkWindow.SetBookmarkData(logWindow.BookmarkData); + _bookmarkWindow.SetCurrentFile(ctx); + } + + private void DisconnectToolWindows (LogWindow.LogWindow logWindow) + { + DisconnectBookmarkWindow(logWindow); + } + + private void DisconnectBookmarkWindow (LogWindow.LogWindow logWindow) + { + _bookmarkWindow.SetBookmarkData(null); + _bookmarkWindow.SetCurrentFile(null); + } + + [SupportedOSPlatform("windows")] + private void GuiStateUpdateWorker (GuiStateArgs e) + { + _skipEvents = true; + checkBoxFollowTail.Checked = e.FollowTail; + mainMenuStrip.Enabled = e.MenuEnabled; + timeshiftToolStripMenuItem.Enabled = e.TimeshiftPossible; + timeshiftToolStripMenuItem.Checked = e.TimeshiftEnabled; + timeshiftMenuTextBox.Text = e.TimeshiftText; + timeshiftMenuTextBox.Enabled = e.TimeshiftEnabled; + multiFileToolStripMenuItem.Enabled = e.MultiFileEnabled; // disabled for temp files + multiFileToolStripMenuItem.Checked = e.IsMultiFileActive; + multiFileEnabledStripMenuItem.Checked = e.IsMultiFileActive; + cellSelectModeToolStripMenuItem.Checked = e.CellSelectMode; + RefreshEncodingMenuBar(e.CurrentEncoding); + + if (e.TimeshiftPossible && ConfigManager.Settings.Preferences.TimestampControl) + { + dragControlDateTime.MinDateTime = e.MinTimestamp; + dragControlDateTime.MaxDateTime = e.MaxTimestamp; + dragControlDateTime.DateTime = e.Timestamp; + dragControlDateTime.Visible = true; + dragControlDateTime.Enabled = true; + dragControlDateTime.Refresh(); + } + else + { + dragControlDateTime.Visible = false; + dragControlDateTime.Enabled = false; + } + + toolStripButtonBubbles.Checked = e.ShowBookmarkBubbles; + groupsComboBoxHighlightGroups.Text = e.HighlightGroupName; + columnFinderToolStripMenuItem.Checked = e.ColumnFinderVisible; + + _skipEvents = false; + } + + [SupportedOSPlatform("windows")] + private void ProgressBarUpdateWorker (ProgressEventArgs e) + { + if (e.Value <= e.MaxValue && e.Value >= e.MinValue) + { + try + { + loadProgessBar.Minimum = e.MinValue; + loadProgessBar.Maximum = e.MaxValue; + loadProgessBar.Value = e.Value; + loadProgessBar.Visible = e.Visible; + } + catch (Exception ex) + { + _logger.Error(ex, "Error during ProgressBarUpdateWorker value {0}, min {1}, max {2}, visible {3}", e.Value, e.MinValue, e.MaxValue, e.Visible); + } + + Invoke(new System.Windows.Forms.MethodInvoker(statusStrip.Refresh)); + } + } + + [SupportedOSPlatform("windows")] + //TODO Crossthread Exception when a log file has been filtered to a new tab! + private void StatusLineEventWorker (StatusLineEventArgs e) + { + if (e != null) + { + //_logger.logDebug("StatusLineEvent: text = " + e.StatusText); + labelStatus.Text = e.StatusText; + labelStatus.Size = TextRenderer.MeasureText(labelStatus.Text, labelStatus.Font); + labelLines.Text = $" {e.LineCount} lines"; + labelLines.Size = TextRenderer.MeasureText(labelLines.Text, labelLines.Font); + labelSize.Text = Util.GetFileSizeAsText(e.FileSize); + labelSize.Size = TextRenderer.MeasureText(labelSize.Text, labelSize.Font); + labelCurrentLine.Text = $"Line: {e.CurrentLineNum}"; + labelCurrentLine.Size = TextRenderer.MeasureText(labelCurrentLine.Text, labelCurrentLine.Font); + if (statusStrip.InvokeRequired) + { + statusStrip.BeginInvoke(new System.Windows.Forms.MethodInvoker(statusStrip.Refresh)); + } + else + { + statusStrip.Refresh(); + } + } + } + + // tailState: 0,1,2 = on/off/off by Trigger + // syncMode: 0 = normal (no), 1 = time synced + [SupportedOSPlatform("windows")] + private Icon CreateLedIcon (int level, bool dirty, int tailState, int syncMode) + { + var iconRect = _leds[0]; + iconRect.Height = 16; // (DockPanel's damn hardcoded height) // this.leds[this.leds.Length - 1].Bottom; + iconRect.Width = iconRect.Right + 6; + Bitmap bmp = new(iconRect.Width, iconRect.Height); + var gfx = Graphics.FromImage(bmp); + + var offsetFromTop = 4; + + for (var i = 0; i < _leds.Length; ++i) + { + var ledRect = _leds[i]; + ledRect.Offset(0, offsetFromTop); + + if (level >= _leds.Length - i) + { + gfx.FillRectangle(_ledBrushes[i], ledRect); + } + else + { + gfx.FillRectangle(_offLedBrush, ledRect); + } + } + + var ledSize = 3; + var ledGap = 1; + var lastLed = _leds[^1]; + Rectangle dirtyLed = new(lastLed.Right + 2, lastLed.Bottom - ledSize, ledSize, ledSize); + Rectangle tailLed = new(dirtyLed.Location, dirtyLed.Size); + tailLed.Offset(0, -(ledSize + ledGap)); + Rectangle syncLed = new(tailLed.Location, dirtyLed.Size); + syncLed.Offset(0, -(ledSize + ledGap)); + + syncLed.Offset(0, offsetFromTop); + tailLed.Offset(0, offsetFromTop); + dirtyLed.Offset(0, offsetFromTop); + + if (dirty) + { + gfx.FillRectangle(_dirtyLedBrush, dirtyLed); + } + else + { + gfx.FillRectangle(_offLedBrush, dirtyLed); + } + + // tailMode 4 means: don't show + if (tailState < 3) + { + gfx.FillRectangle(_tailLedBrush[tailState], tailLed); + } + + if (syncMode == 1) + { + gfx.FillRectangle(_syncLedBrush, syncLed); + } + //else + //{ + // gfx.FillRectangle(this.offLedBrush, syncLed); + //} + + // see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=345656 + // GetHicon() creates an unmanaged handle which must be destroyed. The Clone() workaround creates + // a managed copy of icon. then the unmanaged win32 handle is destroyed + var iconHandle = bmp.GetHicon(); + var icon = Icon.FromHandle(iconHandle).Clone() as Icon; + NativeMethods.DestroyIcon(iconHandle); + + gfx.Dispose(); + bmp.Dispose(); + return icon; + } + + [SupportedOSPlatform("windows")] + private void CreateIcons () + { + for (var syncMode = 0; syncMode <= 1; syncMode++) // LED indicating time synced tabs + { + for (var tailMode = 0; tailMode < 4; tailMode++) + { + for (var i = 0; i < 6; ++i) + { + _ledIcons[i, 0, tailMode, syncMode] = CreateLedIcon(i, false, tailMode, syncMode); + } + + for (var i = 0; i < 6; ++i) + { + _ledIcons[i, 1, tailMode, syncMode] = CreateLedIcon(i, true, tailMode, syncMode); + } + } + } + } + + [SupportedOSPlatform("windows")] + private void FileNotFound (LogWindow.LogWindow logWin) + { + var data = logWin.Tag as LogWindowData; + BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, _deadIcon); + dragControlDateTime.Visible = false; + } + + [SupportedOSPlatform("windows")] + private void FileRespawned (LogWindow.LogWindow logWin) + { + var data = logWin.Tag as LogWindowData; + var icon = GetIcon(0, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); + } + + [SupportedOSPlatform("windows")] + private void ShowLedPeak (LogWindow.LogWindow logWin) + { + var data = logWin.Tag as LogWindowData; + lock (data) + { + data.DiffSum = DIFF_MAX; + } + + var icon = GetIcon(data.DiffSum, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); + } + + private int GetLevelFromDiff (int diff) + { + if (diff > 60) + { + diff = 60; + } + + var level = diff / 10; + if (diff > 0 && level == 0) + { + level = 2; + } + else if (level == 0) + { + level = 1; + } + + return level - 1; + } + + [SupportedOSPlatform("windows")] + private void LedThreadProc () + { + Thread.CurrentThread.Name = "LED Thread"; + while (!_shouldStop) + { + try + { + Thread.Sleep(200); + } + catch + { + return; + } + + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + var data = logWindow.Tag as LogWindowData; + if (data.DiffSum > 0) + { + data.DiffSum -= 10; + if (data.DiffSum < 0) + { + data.DiffSum = 0; + } + + var icon = GetIcon(data.DiffSum, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); + } + } + } + } + } + + [SupportedOSPlatform("windows")] + private void SetTabIcon (LogWindow.LogWindow logWindow, Icon icon) + { + if (logWindow != null) + { + logWindow.Icon = icon; + logWindow.DockHandler.Pane?.TabStripControl.Invalidate(false); + } + } + + private Icon GetIcon (int diff, LogWindowData data) + { + var icon = + _ledIcons[ + GetLevelFromDiff(diff), data.Dirty ? 1 : 0, Preferences.ShowTailState ? data.TailState : 3, + data.SyncMode + ]; + return icon; + } + + [SupportedOSPlatform("windows")] + private void RefreshEncodingMenuBar (Encoding encoding) + { + toolStripEncodingASCIIItem.Checked = false; + toolStripEncodingANSIItem.Checked = false; + toolStripEncodingUTF8Item.Checked = false; + toolStripEncodingUTF16Item.Checked = false; + toolStripEncodingISO88591Item.Checked = false; + + if (encoding == null) + { + return; + } + + if (encoding is ASCIIEncoding) + { + toolStripEncodingASCIIItem.Checked = true; + } + else if (encoding.Equals(Encoding.Default)) + { + toolStripEncodingANSIItem.Checked = true; + } + else if (encoding is UTF8Encoding) + { + toolStripEncodingUTF8Item.Checked = true; + } + else if (encoding is UnicodeEncoding) + { + toolStripEncodingUTF16Item.Checked = true; + } + else if (encoding.Equals(Encoding.GetEncoding("iso-8859-1"))) + { + toolStripEncodingISO88591Item.Checked = true; + } + + toolStripEncodingANSIItem.Text = Encoding.Default.HeaderName; + } + + [SupportedOSPlatform("windows")] + private void OpenSettings (int tabToOpen) + { + SettingsDialog dlg = new(ConfigManager.Settings.Preferences, this, tabToOpen, ConfigManager) + { + TopMost = TopMost + }; + + if (DialogResult.OK == dlg.ShowDialog()) + { + ConfigManager.Settings.Preferences = dlg.Preferences; + ConfigManager.Save(SettingsFlags.Settings); + NotifyWindowsForChangedPrefs(SettingsFlags.Settings); + } + } + + [SupportedOSPlatform("windows")] + private void NotifyWindowsForChangedPrefs (SettingsFlags flags) + { + _logger.Info(CultureInfo.InvariantCulture, "The preferences have changed"); + ApplySettings(ConfigManager.Settings, flags); + + var setLastColumnWidth = ConfigManager.Settings.Preferences.SetLastColumnWidth; + var lastColumnWidth = ConfigManager.Settings.Preferences.LastColumnWidth; + var fontName = ConfigManager.Settings.Preferences.FontName; + var fontSize = ConfigManager.Settings.Preferences.FontSize; + + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + logWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, false, flags); + } + } + + _bookmarkWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, flags); + + HighlightGroupList = ConfigManager.Settings.Preferences.HighlightGroupList; + if ((flags & SettingsFlags.HighlightSettings) == SettingsFlags.HighlightSettings) + { + OnHighlightSettingsChanged(); + } + } + + [SupportedOSPlatform("windows")] + private void ApplySettings (Settings settings, SettingsFlags flags) + { + if ((flags & SettingsFlags.WindowPosition) == SettingsFlags.WindowPosition) + { + TopMost = alwaysOnTopToolStripMenuItem.Checked = settings.AlwaysOnTop; + dragControlDateTime.DragOrientation = settings.Preferences.TimestampControlDragOrientation; + hideLineColumnToolStripMenuItem.Checked = settings.HideLineColumn; + } + + if ((flags & SettingsFlags.FileHistory) == SettingsFlags.FileHistory) + { + FillHistoryMenu(); + } + + if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) + { + SetTabIcons(settings.Preferences); + } + + if ((flags & SettingsFlags.ToolSettings) == SettingsFlags.ToolSettings) + { + FillToolLauncherBar(); + } + + if ((flags & SettingsFlags.HighlightSettings) == SettingsFlags.HighlightSettings) + { + FillHighlightComboBox(); + } + } + + [SupportedOSPlatform("windows")] + private void SetTabIcons (Preferences preferences) + { + _tailLedBrush[0] = new SolidBrush(preferences.ShowTailColor); + CreateIcons(); + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + var data = logWindow.Tag as LogWindowData; + var icon = GetIcon(data.DiffSum, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); + } + } + } + + [SupportedOSPlatform("windows")] + private void SetToolIcon (ToolEntry entry, ToolStripItem item) + { + var icon = NativeMethods.LoadIconFromExe(entry.IconFile, entry.IconIndex); + + if (icon != null) + { + item.Image = icon.ToBitmap(); + + item.DisplayStyle = item is ToolStripMenuItem + ? ToolStripItemDisplayStyle.ImageAndText + : ToolStripItemDisplayStyle.Image; + + NativeMethods.DestroyIcon(icon.Handle); + icon.Dispose(); + } + + if (!string.IsNullOrEmpty(entry.Cmd)) + { + item.ToolTipText = entry.Name; + } + } + + [SupportedOSPlatform("windows")] + private void ToolButtonClick (ToolEntry toolEntry) + { + if (string.IsNullOrEmpty(toolEntry.Cmd)) + { + //TODO TabIndex => To Enum + OpenSettings(2); + return; + } + + if (CurrentLogWindow != null) + { + var line = CurrentLogWindow.GetCurrentLine(); + var info = CurrentLogWindow.GetCurrentFileInfo(); + if (line != null && info != null) + { + ArgParser parser = new(toolEntry.Args); + var argLine = parser.BuildArgs(line, CurrentLogWindow.GetRealLineNum() + 1, info, this); + if (argLine != null) + { + StartTool(toolEntry.Cmd, argLine, toolEntry.Sysout, toolEntry.ColumnizerName, toolEntry.WorkingDir); + } + } + } + } + + [SupportedOSPlatform("windows")] + private void StartTool (string cmd, string args, bool sysoutPipe, string columnizerName, string workingDir) + { + if (string.IsNullOrEmpty(cmd)) + { + return; + } + + Process process = new(); + ProcessStartInfo startInfo = new(cmd, args); + if (!Util.IsNull(workingDir)) + { + startInfo.WorkingDirectory = workingDir; + } + + process.StartInfo = startInfo; + process.EnableRaisingEvents = true; + + if (sysoutPipe) + { + var columnizer = ColumnizerPicker.DecideColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + + _logger.Info(CultureInfo.InvariantCulture, "Starting external tool with sysout redirection: {0} {1}", cmd, args); + startInfo.UseShellExecute = false; + startInfo.RedirectStandardOutput = true; + //process.OutputDataReceived += pipe.DataReceivedEventHandler; + try + { + _ = process.Start(); + } + catch (Win32Exception e) + { + _logger.Error(e); + MessageBox.Show(e.Message); + return; + } + + SysoutPipe pipe = new(process.StandardOutput); + + var logWin = AddTempFileTab(pipe.FileName, + CurrentLogWindow.IsTempFile + ? CurrentLogWindow.TempTitleName + : Util.GetNameFromPath(CurrentLogWindow.FileName) + "->E"); + logWin.ForceColumnizer(columnizer); + + process.Exited += pipe.ProcessExitedEventHandler; + //process.BeginOutputReadLine(); + } + else + { + _logger.Info(CultureInfo.InvariantCulture, "Starting external tool: {0} {1}", cmd, args); + + try + { + startInfo.UseShellExecute = false; + _ = process.Start(); + } + catch (Exception e) + { + _logger.Error(e); + MessageBox.Show(e.Message); + } + } + } + + [SupportedOSPlatform("windows")] + private void CloseAllTabs () + { + IList closeList = []; + lock (_logWindowList) + { + foreach (DockContent content in dockPanel.Contents) + { + if (content is LogWindow.LogWindow window) + { + closeList.Add(window); + } + } + } + + foreach (var form in closeList) + { + form.Close(); + } + } + + //TODO Reimplement + private void SetTabColor (LogWindow.LogWindow logWindow, Color color) + { + //tabPage.BackLowColor = color; + //tabPage.BackLowColorDisabled = Color.FromArgb(255, + // Math.Max(0, color.R - 50), + // Math.Max(0, color.G - 50), + // Math.Max(0, color.B - 50) + // ); + } + + [SupportedOSPlatform("windows")] + private void LoadProject (string projectFileName, bool restoreLayout) + { + var projectData = ProjectPersister.LoadProjectData(projectFileName); + var hasLayoutData = projectData.TabLayoutXml != null; + + if (hasLayoutData && restoreLayout && _logWindowList.Count > 0) + { + ProjectLoadDlg dlg = new(); + if (DialogResult.Cancel != dlg.ShowDialog()) + { + switch (dlg.ProjectLoadResult) + { + case ProjectLoadDlgResult.IgnoreLayout: + hasLayoutData = false; + break; + case ProjectLoadDlgResult.CloseTabs: + CloseAllTabs(); + break; + case ProjectLoadDlgResult.NewWindow: + LogExpertProxy.NewWindow([projectFileName]); + return; + } + } + } + + if (projectData != null) + { + foreach (var fileName in projectData.MemberList) + { + if (hasLayoutData) + { + AddFileTabDeferred(fileName, false, null, true, null); + } + else + { + AddFileTab(fileName, false, null, true, null); + } + } + + if (hasLayoutData && restoreLayout) + { + // Re-creating tool (non-document) windows is needed because the DockPanel control would throw strange errors + DestroyToolWindows(); + InitToolWindows(); + RestoreLayout(projectData.TabLayoutXml); + } + } + } + + [SupportedOSPlatform("windows")] + private void ApplySelectedHighlightGroup () + { + var groupName = groupsComboBoxHighlightGroups.Text; + CurrentLogWindow?.SetCurrentHighlightGroup(groupName); + } + + [SupportedOSPlatform("windows")] + private void FillToolLauncherBar () + { + char[] labels = + [ + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z' + ]; + toolsToolStripMenuItem.DropDownItems.Clear(); + toolsToolStripMenuItem.DropDownItems.Add(configureToolStripMenuItem); + toolsToolStripMenuItem.DropDownItems.Add(configureToolStripSeparator); + externalToolsToolStrip.Items.Clear(); + var num = 0; + externalToolsToolStrip.SuspendLayout(); + foreach (var tool in Preferences.ToolEntries) + { + if (tool.IsFavourite) + { + ToolStripButton button = new("" + labels[num % 26]) + { + Alignment = ToolStripItemAlignment.Left, + Tag = tool + }; + + SetToolIcon(tool, button); + externalToolsToolStrip.Items.Add(button); + } + + num++; + ToolStripMenuItem menuItem = new(tool.Name) + { + Tag = tool + }; + + SetToolIcon(tool, menuItem); + toolsToolStripMenuItem.DropDownItems.Add(menuItem); + } + + externalToolsToolStrip.ResumeLayout(); + + externalToolsToolStrip.Visible = num > 0; // do not show bar if no tool uses it + } + + private void RunGC () + { + _logger.Info($"Running GC. Used mem before: {GC.GetTotalMemory(false):N0}"); + GC.Collect(); + _logger.Info($"GC done. Used mem after: {GC.GetTotalMemory(true):N0}"); + } + + private void DumpGCInfo () + { + _logger.Info($"-------- GC info -----------\r\nUsed mem: {GC.GetTotalMemory(false):N0}"); + for (var i = 0; i < GC.MaxGeneration; ++i) + { + _logger.Info($"Generation {i} collect count: {GC.CollectionCount(i)}"); + } + + _logger.Info(CultureInfo.InvariantCulture, "----------------------------"); + } + + private void ThrowExceptionFx () + { + throw new Exception("This is a test exception thrown by an async delegate"); + } + + private void ThrowExceptionThreadFx () + { + throw new Exception("This is a test exception thrown by a background thread"); + } + + private string SaveLayout () + { + using MemoryStream memStream = new(2000); + using StreamReader r = new(memStream); + dockPanel.SaveAsXml(memStream, Encoding.UTF8, true); + + memStream.Seek(0, SeekOrigin.Begin); + var resultXml = r.ReadToEnd(); + + r.Close(); + + return resultXml; + } + + [SupportedOSPlatform("windows")] + private void RestoreLayout (string layoutXml) + { + using MemoryStream memStream = new(2000); + using StreamWriter w = new(memStream); + w.Write(layoutXml); + w.Flush(); + + memStream.Seek(0, SeekOrigin.Begin); + + dockPanel.LoadFromXml(memStream, DeserializeDockContent, true); + } + + [SupportedOSPlatform("windows")] + private IDockContent DeserializeDockContent (string persistString) + { + if (persistString.Equals(WindowTypes.BookmarkWindow.ToString(), StringComparison.Ordinal)) + { + return _bookmarkWindow; + } + + if (persistString.StartsWith(WindowTypes.LogWindow.ToString())) + { + var fileName = persistString[(WindowTypes.LogWindow.ToString().Length + 1)..]; + var win = FindWindowForFile(fileName); + if (win != null) + { + return win; + } + + _logger.Warn($"Layout data contains non-existing LogWindow for {fileName}"); + } + + return null; + } + + private void OnHighlightSettingsChanged () + { + HighlightSettingsChanged?.Invoke(this, EventArgs.Empty); + } + + #endregion + + #region Events handler + + private void OnBookmarkWindowVisibleChanged (object sender, EventArgs e) + { + _firstBookmarkWindowShow = false; + } + + private void OnLogTabWindowLoad (object sender, EventArgs e) + { + ApplySettings(ConfigManager.Settings, SettingsFlags.All); + if (ConfigManager.Settings.IsMaximized) + { + Bounds = ConfigManager.Settings.AppBoundsFullscreen; + WindowState = FormWindowState.Maximized; + Bounds = ConfigManager.Settings.AppBounds; + } + else + { + if (ConfigManager.Settings.AppBounds.Right > 0) + { + Bounds = ConfigManager.Settings.AppBounds; + } + } + + if (ConfigManager.Settings.Preferences.OpenLastFiles && _startupFileNames == null) + { + var tmpList = ObjectClone.Clone(ConfigManager.Settings.LastOpenFilesList); + + foreach (var name in tmpList) + { + if (string.IsNullOrEmpty(name) == false) + { + AddFileTab(name, false, null, false, null); + } + } + } + + if (_startupFileNames != null) + { + LoadFiles(_startupFileNames, false); + } + + _ledThread = new Thread(LedThreadProc) + { + IsBackground = true + }; + _ledThread.Start(); + + FillHighlightComboBox(); + FillToolLauncherBar(); +#if !DEBUG + debugToolStripMenuItem.Visible = false; +#endif + } + + private void OnLogTabWindowClosing (object sender, CancelEventArgs e) + { + try + { + _shouldStop = true; + _ = _statusLineEventHandle.Set(); + _ = _statusLineEventWakeupHandle.Set(); + _ledThread.Join(); + + IList deleteLogWindowList = []; + ConfigManager.Settings.AlwaysOnTop = TopMost && ConfigManager.Settings.Preferences.AllowOnlyOneInstance; + SaveLastOpenFilesList(); + + foreach (var logWindow in _logWindowList.ToArray()) + { + RemoveAndDisposeLogWindow(logWindow, true); + } + + DestroyBookmarkWindow(); + + ConfigManager.Instance.ConfigChanged -= OnConfigChanged; + + SaveWindowPosition(); + ConfigManager.Save(SettingsFlags.WindowPosition | SettingsFlags.FileHistory); + } + catch (Exception) + { + // ignore error (can occur then multipe instances are closed simultaneously or if the + // window was not constructed completely because of errors) + } + finally + { + LogExpertProxy?.WindowClosed(this); + } + } + + private void OnStripMouseUp (object sender, MouseEventArgs e) + { + if (sender is ToolStripDropDown dropDown) + { + AddFileTab(dropDown.Text, false, null, false, null); + } + } + + private void OnHistoryItemClicked (object sender, ToolStripItemClickedEventArgs e) + { + if (string.IsNullOrEmpty(e.ClickedItem.Text) == false) + { + AddFileTab(e.ClickedItem.Text, false, null, false, null); + } + } + + private void OnLogWindowDisposed (object sender, EventArgs e) + { + var logWindow = sender as LogWindow.LogWindow; + + if (sender == CurrentLogWindow) + { + ChangeCurrentLogWindow(null); + } + + RemoveLogWindow(logWindow); + + logWindow.Tag = null; + } + + private void OnExitToolStripMenuItemClick (object sender, EventArgs e) + { + Close(); + } + + private void OnSelectFilterToolStripMenuItemClick (object sender, EventArgs e) + { + if (CurrentLogWindow == null) + { + return; + } + + CurrentLogWindow.ColumnizerCallbackObject.LineNum = CurrentLogWindow.GetCurrentLineNum(); + FilterSelectorForm form = new(PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers, CurrentLogWindow.CurrentColumnizer, CurrentLogWindow.ColumnizerCallbackObject, ConfigManager) + { + Owner = this, + TopMost = TopMost + }; + var res = form.ShowDialog(); + + if (res == DialogResult.OK) + { + if (form.ApplyToAll) + { + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + if (logWindow.CurrentColumnizer.GetType() != form.SelectedColumnizer.GetType()) + { + //logWindow.SetColumnizer(form.SelectedColumnizer); + SetColumnizerFx fx = logWindow.ForceColumnizer; + logWindow.Invoke(fx, form.SelectedColumnizer); + SetColumnizerHistoryEntry(logWindow.FileName, form.SelectedColumnizer); + } + else + { + if (form.IsConfigPressed) + { + logWindow.ColumnizerConfigChanged(); + } + } + } + } + } + else + { + if (CurrentLogWindow.CurrentColumnizer.GetType() != form.SelectedColumnizer.GetType()) + { + SetColumnizerFx fx = CurrentLogWindow.ForceColumnizer; + CurrentLogWindow.Invoke(fx, form.SelectedColumnizer); + SetColumnizerHistoryEntry(CurrentLogWindow.FileName, form.SelectedColumnizer); + } + + if (form.IsConfigPressed) + { + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + if (logWindow.CurrentColumnizer.GetType() == form.SelectedColumnizer.GetType()) + { + logWindow.ColumnizerConfigChanged(); + } + } + } + } + } + } + } + + private void OnGoToLineToolStripMenuItemClick (object sender, EventArgs e) + { + if (CurrentLogWindow == null) + { + return; + } + + GotoLineDialog dlg = new(this); + var res = dlg.ShowDialog(); + if (res == DialogResult.OK) + { + var line = dlg.Line - 1; + if (line >= 0) + { + CurrentLogWindow.GotoLine(line); + } + } + } + + private void OnHighlightingToolStripMenuItemClick (object sender, EventArgs e) + { + ShowHighlightSettingsDialog(); + } + + private void OnSearchToolStripMenuItemClick (object sender, EventArgs e) + { + OpenSearchDialog(); + } + + private void OnOpenToolStripMenuItemClick (object sender, EventArgs e) + { + OpenFileDialog(); + } + + private void OnLogTabWindowDragEnter (object sender, DragEventArgs e) + { +#if DEBUG + var formats = e.Data.GetFormats(); + var s = "Dragging something over LogExpert. Formats: "; + foreach (var format in formats) + { + s += format; + s += " , "; + } + + s = s[..^3]; + _logger.Info(s); +#endif + } + + private void OnLogWindowDragOver (object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + { + e.Effect = DragDropEffects.None; + } + else + { + e.Effect = DragDropEffects.Copy; + } + } + + private void OnLogWindowDragDrop (object sender, DragEventArgs e) + { +#if DEBUG + var formats = e.Data.GetFormats(); + var s = "Dropped formats: "; + foreach (var format in formats) + { + s += format; + s += " , "; + } + + s = s[..^3]; + _logger.Debug(s); +#endif + + if (e.Data.GetDataPresent(DataFormats.FileDrop)) + { + var o = e.Data.GetData(DataFormats.FileDrop); + if (o is string[] names) + { + LoadFiles(names, (e.KeyState & 4) == 4); // (shift pressed?) + e.Effect = DragDropEffects.Copy; + } + } + } + + [SupportedOSPlatform("windows")] + private void OnTimeShiftToolStripMenuItemCheckStateChanged (object sender, EventArgs e) + { + if (!_skipEvents && CurrentLogWindow != null) + { + CurrentLogWindow.SetTimeshiftValue(timeshiftMenuTextBox.Text); + timeshiftMenuTextBox.Enabled = timeshiftToolStripMenuItem.Checked; + CurrentLogWindow.TimeshiftEnabled(timeshiftToolStripMenuItem.Checked, + timeshiftMenuTextBox.Text); + } + } + + [SupportedOSPlatform("windows")] + private void OnAboutToolStripMenuItemClick (object sender, EventArgs e) + { + AboutBox aboutBox = new() + { + TopMost = TopMost + }; + + aboutBox.ShowDialog(); + } + + private void OnFilterToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ToggleFilterPanel(); + } + + [SupportedOSPlatform("windows")] + private void OnMultiFileToolStripMenuItemClick (object sender, EventArgs e) + { + ToggleMultiFile(); + fileToolStripMenuItem.HideDropDown(); + } + + [SupportedOSPlatform("windows")] + private void OnGuiStateUpdate (object sender, GuiStateArgs e) + { + BeginInvoke(GuiStateUpdateWorker, e); + } + + private void OnColumnizerChanged (object sender, ColumnizerEventArgs e) + { + _bookmarkWindow?.SetColumnizer(e.Columnizer); + } + + private void OnBookmarkAdded (object sender, EventArgs e) + { + _bookmarkWindow.UpdateView(); + } + + private void OnBookmarkTextChanged (object sender, BookmarkEventArgs e) + { + _bookmarkWindow.BookmarkTextChanged(e.Bookmark); + } + + private void OnBookmarkRemoved (object sender, EventArgs e) + { + _bookmarkWindow.UpdateView(); + } + + private void OnProgressBarUpdate (object sender, ProgressEventArgs e) + { + Invoke(ProgressBarUpdateWorker, e); + } + + private void OnStatusLineEvent (object sender, StatusLineEventArgs e) + { + StatusLineEventWorker(e); + } + + private void OnFollowTailCheckBoxClick (object sender, EventArgs e) + { + CurrentLogWindow?.FollowTailChanged(checkBoxFollowTail.Checked, false); + } + + private void OnLogTabWindowKeyDown (object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.W && e.Control) + { + CurrentLogWindow?.Close(); + } + else if (e.KeyCode == Keys.Tab && e.Control) + { + SwitchTab(e.Shift); + } + else + { + CurrentLogWindow?.OnLogWindowKeyDown(sender, e); + } + } + + private void OnCloseFileToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.Close(); + } + + [SupportedOSPlatform("windows")] + private void OnCellSelectModeToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.SetCellSelectionMode(cellSelectModeToolStripMenuItem.Checked); + } + + private void OnCopyMarkedLinesIntoNewTabToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.CopyMarkedLinesToTab(); + } + + private void OnTimeShiftMenuTextBoxKeyDown (object sender, KeyEventArgs e) + { + if (CurrentLogWindow == null) + { + return; + } + + if (e.KeyCode == Keys.Enter) + { + e.Handled = true; + CurrentLogWindow.SetTimeshiftValue(timeshiftMenuTextBox.Text); + } + } + + [SupportedOSPlatform("windows")] + private void OnAlwaysOnTopToolStripMenuItemClick (object sender, EventArgs e) + { + TopMost = alwaysOnTopToolStripMenuItem.Checked; + } + + private void OnFileSizeChanged (object sender, LogEventArgs e) + { + if (sender.GetType().IsAssignableFrom(typeof(LogWindow.LogWindow))) + { + var diff = e.LineCount - e.PrevLineCount; + if (diff < 0) + { + return; + } + + if (((LogWindow.LogWindow)sender).Tag is LogWindowData data) + { + lock (data) + { + data.DiffSum += diff; + if (data.DiffSum > DIFF_MAX) + { + data.DiffSum = DIFF_MAX; + } + } + + //if (this.dockPanel.ActiveContent != null && + // this.dockPanel.ActiveContent != sender || data.tailState != 0) + if (CurrentLogWindow != null && + CurrentLogWindow != sender || data.TailState != 0) + { + data.Dirty = true; + } + var icon = GetIcon(diff, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); + } + } + } + + private void OnLogWindowFileNotFound (object sender, EventArgs e) + { + Invoke(new FileNotFoundDelegate(FileNotFound), sender); + } + + private void OnLogWindowFileRespawned (object sender, EventArgs e) + { + Invoke(new FileRespawnedDelegate(FileRespawned), sender); + } + + private void OnLogWindowFilterListChanged (object sender, FilterListChangedEventArgs e) + { + lock (_logWindowList) + { + foreach (var logWindow in _logWindowList) + { + if (logWindow != e.LogWindow) + { + logWindow.HandleChangedFilterList(); + } + } + } + ConfigManager.Save(SettingsFlags.FilterList); + } + + private void OnLogWindowCurrentHighlightGroupChanged (object sender, CurrentHighlightGroupChangedEventArgs e) + { + OnHighlightSettingsChanged(); + ConfigManager.Settings.Preferences.HighlightGroupList = HighlightGroupList; + ConfigManager.Save(SettingsFlags.HighlightSettings); + } + + private void OnTailFollowed (object sender, EventArgs e) + { + if (dockPanel.ActiveContent == null) + { + return; + } + if (sender.GetType().IsAssignableFrom(typeof(LogWindow.LogWindow))) + { + if (dockPanel.ActiveContent == sender) + { + var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; + data.Dirty = false; + var icon = GetIcon(data.DiffSum, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnLogWindowSyncModeChanged (object sender, SyncModeEventArgs e) + { + if (!Disposing) + { + var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; + data.SyncMode = e.IsTimeSynced ? 1 : 0; + var icon = GetIcon(data.DiffSum, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); + } + else + { + _logger.Warn(CultureInfo.InvariantCulture, "Received SyncModeChanged event while disposing. Event ignored."); + } + } + + [SupportedOSPlatform("windows")] + private void OnToggleBookmarkToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ToggleBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnJumpToNextToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.JumpNextBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnJumpToPrevToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.JumpPrevBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnASCIIToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ChangeEncoding(Encoding.ASCII); + } + + [SupportedOSPlatform("windows")] + private void OnANSIToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ChangeEncoding(Encoding.Default); + } + + [SupportedOSPlatform("windows")] + private void OnUTF8ToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ChangeEncoding(new UTF8Encoding(false)); + } + + [SupportedOSPlatform("windows")] + private void OnUTF16ToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ChangeEncoding(Encoding.Unicode); + } + + [SupportedOSPlatform("windows")] + private void OnISO88591ToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ChangeEncoding(Encoding.GetEncoding("iso-8859-1")); + } + + [SupportedOSPlatform("windows")] + private void OnReloadToolStripMenuItemClick (object sender, EventArgs e) + { + if (CurrentLogWindow != null) + { + var data = CurrentLogWindow.Tag as LogWindowData; + var icon = GetIcon(0, data); + BeginInvoke(new SetTabIconDelegate(SetTabIcon), CurrentLogWindow, icon); + CurrentLogWindow.Reload(); + } + } + + [SupportedOSPlatform("windows")] + private void OnSettingsToolStripMenuItemClick (object sender, EventArgs e) + { + OpenSettings(0); + } + + [SupportedOSPlatform("windows")] + private void OnDateTimeDragControlValueDragged (object sender, EventArgs e) + { + if (CurrentLogWindow != null) + { + //this.CurrentLogWindow.ScrollToTimestamp(this.dateTimeDragControl.DateTime); + } + } + + [SupportedOSPlatform("windows")] + private void OnDateTimeDragControlValueChanged (object sender, EventArgs e) + { + CurrentLogWindow?.ScrollToTimestamp(dragControlDateTime.DateTime, true, true); + } + + [SupportedOSPlatform("windows")] + private void OnLogTabWindowDeactivate (object sender, EventArgs e) + { + CurrentLogWindow?.AppFocusLost(); + } + + [SupportedOSPlatform("windows")] + private void OnLogTabWindowActivated (object sender, EventArgs e) + { + CurrentLogWindow?.AppFocusGained(); + } + + [SupportedOSPlatform("windows")] + private void OnShowBookmarkListToolStripMenuItemClick (object sender, EventArgs e) + { + if (_bookmarkWindow.Visible) + { + _bookmarkWindow.Hide(); + } + else + { + // strange: on very first Show() now bookmarks are displayed. after a hide it will work. + if (_firstBookmarkWindowShow) + { + _bookmarkWindow.Show(dockPanel); + _bookmarkWindow.Hide(); + } + + _bookmarkWindow.Show(dockPanel); + } + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonOpenClick (object sender, EventArgs e) + { + OpenFileDialog(); + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonSearchClick (object sender, EventArgs e) + { + OpenSearchDialog(); + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonFilterClick (object sender, EventArgs e) + { + CurrentLogWindow?.ToggleFilterPanel(); + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonBookmarkClick (object sender, EventArgs e) + { + CurrentLogWindow?.ToggleBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonUpClick (object sender, EventArgs e) + { + CurrentLogWindow?.JumpPrevBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonDownClick (object sender, EventArgs e) + { + CurrentLogWindow?.JumpNextBookmark(); + } + + [SupportedOSPlatform("windows")] + private void OnShowHelpToolStripMenuItemClick (object sender, EventArgs e) + { + Help.ShowHelp(this, "LogExpert.chm"); + } + + private void OnHideLineColumnToolStripMenuItemClick (object sender, EventArgs e) + { + ConfigManager.Settings.HideLineColumn = hideLineColumnToolStripMenuItem.Checked; + lock (_logWindowList) + { + foreach (var logWin in _logWindowList) + { + logWin.ShowLineColumn(!ConfigManager.Settings.HideLineColumn); + } + } + _bookmarkWindow.LineColumnVisible = ConfigManager.Settings.HideLineColumn; + } + + // ================================================================== + // Tab context menu stuff + // ================================================================== + + [SupportedOSPlatform("windows")] + private void OnCloseThisTabToolStripMenuItemClick (object sender, EventArgs e) + { + (dockPanel.ActiveContent as LogWindow.LogWindow).Close(); + } + + [SupportedOSPlatform("windows")] + private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) + { + var closeList = dockPanel.Contents + .OfType() + .Where(content => content != dockPanel.ActiveContent) + .ToList(); + + foreach (var logWindow in closeList) + { + logWindow.Close(); + } + } + + [SupportedOSPlatform("windows")] + private void OnCloseAllTabsToolStripMenuItemClick (object sender, EventArgs e) + { + CloseAllTabs(); + } + + [SupportedOSPlatform("windows")] + private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) + { + var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; + + if (logWindow.Tag is not LogWindowData data) + { + return; + } + + ColorDialog dlg = new() + { + Color = data.Color + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + data.Color = dlg.Color; + SetTabColor(logWindow, data.Color); + } + + List delList = []; + + foreach (var entry in ConfigManager.Settings.FileColors) + { + if (entry.FileName.Equals(logWindow.FileName, StringComparison.Ordinal)) + { + delList.Add(entry); + } + } + + foreach (var entry in delList) + { + _ = ConfigManager.Settings.FileColors.Remove(entry); + } + + ConfigManager.Settings.FileColors.Add(new ColorEntry(logWindow.FileName, dlg.Color)); + + while (ConfigManager.Settings.FileColors.Count > MAX_COLOR_HISTORY) + { + ConfigManager.Settings.FileColors.RemoveAt(0); + } + } + + [SupportedOSPlatform("windows")] + private void OnLogTabWindowSizeChanged (object sender, EventArgs e) + { + if (WindowState != FormWindowState.Minimized) + { + _wasMaximized = WindowState == FormWindowState.Maximized; + } + } + + [SupportedOSPlatform("windows")] + private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) + { + SaveFileDialog dlg = new() + { + DefaultExt = "lxj", + Filter = @"LogExpert session (*.lxj)|*.lxj" + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + var fileName = dlg.FileName; + List fileNames = []; + + lock (_logWindowList) + { + foreach (var logWindow in dockPanel.Contents.OfType()) + { + var persistenceFileName = logWindow?.SavePersistenceData(true); + if (persistenceFileName != null) + { + fileNames.Add(persistenceFileName); + } + } + } + + ProjectData projectData = new() + { + MemberList = fileNames, + TabLayoutXml = SaveLayout() + }; + ProjectPersister.SaveProjectData(fileName, projectData); + } + } + + [SupportedOSPlatform("windows")] + private void OnLoadProjectToolStripMenuItemClick (object sender, EventArgs e) + { + OpenFileDialog dlg = new() + { + DefaultExt = "lxj", + Filter = @"LogExpert sessions (*.lxj)|*.lxj" + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + var projectFileName = dlg.FileName; + LoadProject(projectFileName, true); + } + } + + [SupportedOSPlatform("windows")] + private void OnToolStripButtonBubblesClick (object sender, EventArgs e) + { + if (CurrentLogWindow != null) + { + CurrentLogWindow.ShowBookmarkBubbles = toolStripButtonBubbles.Checked; + } + } + + [SupportedOSPlatform("windows")] + private void OnCopyPathToClipboardToolStripMenuItemClick (object sender, EventArgs e) + { + var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; + Clipboard.SetText(logWindow.Title); + } + + private void OnFindInExplorerToolStripMenuItemClick (object sender, EventArgs e) + { + var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; + + Process explorer = new(); + explorer.StartInfo.FileName = "explorer.exe"; + explorer.StartInfo.Arguments = "/e,/select," + logWindow.Title; + explorer.StartInfo.UseShellExecute = false; + explorer.Start(); + } + + private void TruncateFileToolStripMenuItem_Click (object sender, EventArgs e) + { + CurrentLogWindow?.TryToTruncate(); + } + + private void OnExportBookmarksToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ExportBookmarkList(); + } + + [SupportedOSPlatform("windows")] + private void OnHighlightGroupsComboBoxDropDownClosed (object sender, EventArgs e) + { + ApplySelectedHighlightGroup(); + } + + [SupportedOSPlatform("windows")] + private void OnHighlightGroupsComboBoxSelectedIndexChanged (object sender, EventArgs e) + { + ApplySelectedHighlightGroup(); + } + + [SupportedOSPlatform("windows")] + private void OnHighlightGroupsComboBoxMouseUp (object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Right) + { + ShowHighlightSettingsDialog(); + } + } + + + private void OnConfigChanged (object sender, ConfigChangedEventArgs e) + { + if (LogExpertProxy != null) + { + NotifySettingsChanged(null, e.Flags); + } + } + + [SupportedOSPlatform("windows")] + private void OnDumpLogBufferInfoToolStripMenuItemClick (object sender, EventArgs e) + { +#if DEBUG + CurrentLogWindow?.DumpBufferInfo(); +#endif + } + + [SupportedOSPlatform("windows")] + private void OnDumpBufferDiagnosticToolStripMenuItemClick (object sender, EventArgs e) + { +#if DEBUG + CurrentLogWindow?.DumpBufferDiagnostic(); +#endif + } + + private void OnRunGCToolStripMenuItemClick (object sender, EventArgs e) + { + RunGC(); + } + + private void OnGCInfoToolStripMenuItemClick (object sender, EventArgs e) + { + DumpGCInfo(); + } + + [SupportedOSPlatform("windows")] + private void OnToolsToolStripMenuItemDropDownItemClicked (object sender, ToolStripItemClickedEventArgs e) + { + if (e.ClickedItem.Tag is ToolEntry tag) + { + ToolButtonClick(tag); + } + } + + [SupportedOSPlatform("windows")] + private void OnExternalToolsToolStripItemClicked (object sender, ToolStripItemClickedEventArgs e) + { + ToolButtonClick(e.ClickedItem.Tag as ToolEntry); + } + + [SupportedOSPlatform("windows")] + private void OnConfigureToolStripMenuItemClick (object sender, EventArgs e) + { + OpenSettings(2); + } + + private void OnThrowExceptionGUIThreadToolStripMenuItemClick (object sender, EventArgs e) + { + throw new Exception("This is a test exception thrown by the GUI thread"); + } + + private void OnThrowExceptionBackgroundThToolStripMenuItemClick (object sender, EventArgs e) + { + ExceptionFx fx = ThrowExceptionFx; + fx.BeginInvoke(null, null); + } + + private void OnThrowExceptionBackgroundThreadToolStripMenuItemClick (object sender, EventArgs e) + { + Thread thread = new(ThrowExceptionThreadFx) + { + IsBackground = true + }; + + thread.Start(); + } + + private void OnWarnToolStripMenuItemClick (object sender, EventArgs e) + { + //_logger.GetLogger().LogLevel = _logger.Level.WARN; + } + + private void OnInfoToolStripMenuItemClick (object sender, EventArgs e) + { + //_logger.Get_logger().LogLevel = _logger.Level.INFO; + } + + private void OnDebugToolStripMenuItemClick (object sender, EventArgs e) + { + //_logger.Get_logger().LogLevel = _logger.Level.DEBUG; + } + + private void OnLogLevelToolStripMenuItemClick (object sender, EventArgs e) + { + } + + private void OnLogLevelToolStripMenuItemDropDownOpening (object sender, EventArgs e) + { + //warnToolStripMenuItem.Checked = _logger.Get_logger().LogLevel == _logger.Level.WARN; + //infoToolStripMenuItem.Checked = _logger.Get_logger().LogLevel == _logger.Level.INFO; + //debugToolStripMenuItem1.Checked = _logger.Get_logger().LogLevel == _logger.Level.DEBUG; + } + + [SupportedOSPlatform("windows")] + private void OnDisableWordHighlightModeToolStripMenuItemClick (object sender, EventArgs e) + { + DebugOptions.DisableWordHighlight = disableWordHighlightModeToolStripMenuItem.Checked; + CurrentLogWindow?.RefreshAllGrids(); + } + + [SupportedOSPlatform("windows")] + private void OnMultiFileMaskToolStripMenuItemClick (object sender, EventArgs e) + { + CurrentLogWindow?.ChangeMultifileMask(); + } + + [SupportedOSPlatform("windows")] + private void OnMultiFileEnabledStripMenuItemClick (object sender, EventArgs e) + { + ToggleMultiFile(); + } + + [SupportedOSPlatform("windows")] + private void OnLockInstanceToolStripMenuItemClick (object sender, EventArgs e) + { + AbstractLogTabWindow.StaticData.CurrentLockedMainWindow = lockInstanceToolStripMenuItem.Checked ? null : this; + } + + [SupportedOSPlatform("windows")] + private void OnOptionToolStripMenuItemDropDownOpening (object sender, EventArgs e) + { + lockInstanceToolStripMenuItem.Enabled = !ConfigManager.Settings.Preferences.AllowOnlyOneInstance; + lockInstanceToolStripMenuItem.Checked = AbstractLogTabWindow.StaticData.CurrentLockedMainWindow == this; + } + + [SupportedOSPlatform("windows")] + private void OnFileToolStripMenuItemDropDownOpening (object sender, EventArgs e) + { + newFromClipboardToolStripMenuItem.Enabled = Clipboard.ContainsText(); + } + + [SupportedOSPlatform("windows")] + private void OnNewFromClipboardToolStripMenuItemClick (object sender, EventArgs e) + { + PasteFromClipboard(); + } + + [SupportedOSPlatform("windows")] + private void OnOpenURIToolStripMenuItemClick (object sender, EventArgs e) + { + OpenUriDialog dlg = new() + { + UriHistory = ConfigManager.Settings.UriHistoryList + }; + + if (DialogResult.OK == dlg.ShowDialog()) + { + if (dlg.Uri.Trim().Length > 0) + { + ConfigManager.Settings.UriHistoryList = dlg.UriHistory; + ConfigManager.Save(SettingsFlags.FileHistory); + LoadFiles([dlg.Uri], false); + } + } + } + + [SupportedOSPlatform("windows")] + private void OnColumnFinderToolStripMenuItemClick (object sender, EventArgs e) + { + if (CurrentLogWindow != null && !_skipEvents) + { + CurrentLogWindow.ToggleColumnFinder(columnFinderToolStripMenuItem.Checked, true); + } + } + + [SupportedOSPlatform("windows")] + private void OnDockPanelActiveContentChanged (object sender, EventArgs e) + { + if (dockPanel.ActiveContent is LogWindow.LogWindow window) + { + CurrentLogWindow = window; + CurrentLogWindow.LogWindowActivated(); + ConnectToolWindows(CurrentLogWindow); + } + } + + [SupportedOSPlatform("windows")] + private void OnTabRenameToolStripMenuItemClick (object sender, EventArgs e) + { + if (CurrentLogWindow != null) + { + TabRenameDialog dlg = new() + { + TabName = CurrentLogWindow.Text + }; + + if (DialogResult.OK == dlg.ShowDialog()) + { + CurrentLogWindow.Text = dlg.TabName; + } + + dlg.Dispose(); + } + } + + #endregion } \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs deleted file mode 100644 index 587414f2..00000000 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowEventHandlers.cs +++ /dev/null @@ -1,1094 +0,0 @@ -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.Versioning; -using System.Text; - -using LogExpert.Core.Classes; -using LogExpert.Core.Classes.Persister; -using LogExpert.Core.Config; -using LogExpert.Core.Entities; -using LogExpert.Core.EventArguments; -using LogExpert.Dialogs; -using LogExpert.UI.Dialogs; -using LogExpert.UI.Extensions.LogWindow; - -namespace LogExpert.UI.Controls.LogTabWindow; - -internal partial class LogTabWindow -{ - #region Events handler - - private void OnBookmarkWindowVisibleChanged (object sender, EventArgs e) - { - _firstBookmarkWindowShow = false; - } - - private void OnLogTabWindowLoad (object sender, EventArgs e) - { - ApplySettings(ConfigManager.Settings, SettingsFlags.All); - if (ConfigManager.Settings.IsMaximized) - { - Bounds = ConfigManager.Settings.AppBoundsFullscreen; - WindowState = FormWindowState.Maximized; - Bounds = ConfigManager.Settings.AppBounds; - } - else - { - if (ConfigManager.Settings.AppBounds.Right > 0) - { - Bounds = ConfigManager.Settings.AppBounds; - } - } - - if (ConfigManager.Settings.Preferences.OpenLastFiles && _startupFileNames == null) - { - var tmpList = ObjectClone.Clone(ConfigManager.Settings.LastOpenFilesList); - - foreach (var name in tmpList) - { - if (string.IsNullOrEmpty(name) == false) - { - AddFileTab(name, false, null, false, null); - } - } - } - - if (_startupFileNames != null) - { - LoadFiles(_startupFileNames, false); - } - - _ledThread = new Thread(LedThreadProc) - { - IsBackground = true - }; - _ledThread.Start(); - - FillHighlightComboBox(); - FillToolLauncherBar(); -#if !DEBUG - debugToolStripMenuItem.Visible = false; -#endif - } - - private void OnLogTabWindowClosing (object sender, CancelEventArgs e) - { - try - { - _shouldStop = true; - _ = _statusLineEventHandle.Set(); - _ = _statusLineEventWakeupHandle.Set(); - _ledThread.Join(); - - IList deleteLogWindowList = []; - ConfigManager.Settings.AlwaysOnTop = TopMost && ConfigManager.Settings.Preferences.AllowOnlyOneInstance; - SaveLastOpenFilesList(); - - foreach (var logWindow in _logWindowList.ToArray()) - { - RemoveAndDisposeLogWindow(logWindow, true); - } - - DestroyBookmarkWindow(); - - ConfigManager.Instance.ConfigChanged -= OnConfigChanged; - - SaveWindowPosition(); - ConfigManager.Save(SettingsFlags.WindowPosition | SettingsFlags.FileHistory); - } - catch (Exception) - { - // ignore error (can occur then multipe instances are closed simultaneously or if the - // window was not constructed completely because of errors) - } - finally - { - LogExpertProxy?.WindowClosed(this); - } - } - - private void OnStripMouseUp (object sender, MouseEventArgs e) - { - if (sender is ToolStripDropDown dropDown) - { - AddFileTab(dropDown.Text, false, null, false, null); - } - } - - private void OnHistoryItemClicked (object sender, ToolStripItemClickedEventArgs e) - { - if (string.IsNullOrEmpty(e.ClickedItem.Text) == false) - { - AddFileTab(e.ClickedItem.Text, false, null, false, null); - } - } - - private void OnLogWindowDisposed (object sender, EventArgs e) - { - var logWindow = sender as LogWindow.LogWindow; - - if (sender == CurrentLogWindow) - { - ChangeCurrentLogWindow(null); - } - - RemoveLogWindow(logWindow); - - logWindow.Tag = null; - } - - private void OnExitToolStripMenuItemClick (object sender, EventArgs e) - { - Close(); - } - - private void OnSelectFilterToolStripMenuItemClick (object sender, EventArgs e) - { - if (CurrentLogWindow == null) - { - return; - } - - CurrentLogWindow.ColumnizerCallbackObject.LineNum = CurrentLogWindow.GetCurrentLineNum(); - FilterSelectorForm form = new(PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers, CurrentLogWindow.CurrentColumnizer, CurrentLogWindow.ColumnizerCallbackObject, ConfigManager) - { - Owner = this, - TopMost = TopMost - }; - var res = form.ShowDialog(); - - if (res == DialogResult.OK) - { - if (form.ApplyToAll) - { - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - if (logWindow.CurrentColumnizer.GetType() != form.SelectedColumnizer.GetType()) - { - //logWindow.SetColumnizer(form.SelectedColumnizer); - SetColumnizerFx fx = logWindow.ForceColumnizer; - logWindow.Invoke(fx, form.SelectedColumnizer); - SetColumnizerHistoryEntry(logWindow.FileName, form.SelectedColumnizer); - } - else - { - if (form.IsConfigPressed) - { - logWindow.ColumnizerConfigChanged(); - } - } - } - } - } - else - { - if (CurrentLogWindow.CurrentColumnizer.GetType() != form.SelectedColumnizer.GetType()) - { - SetColumnizerFx fx = CurrentLogWindow.ForceColumnizer; - CurrentLogWindow.Invoke(fx, form.SelectedColumnizer); - SetColumnizerHistoryEntry(CurrentLogWindow.FileName, form.SelectedColumnizer); - } - - if (form.IsConfigPressed) - { - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - if (logWindow.CurrentColumnizer.GetType() == form.SelectedColumnizer.GetType()) - { - logWindow.ColumnizerConfigChanged(); - } - } - } - } - } - } - } - - private void OnGoToLineToolStripMenuItemClick (object sender, EventArgs e) - { - if (CurrentLogWindow == null) - { - return; - } - - GotoLineDialog dlg = new(this); - var res = dlg.ShowDialog(); - if (res == DialogResult.OK) - { - var line = dlg.Line - 1; - if (line >= 0) - { - CurrentLogWindow.GotoLine(line); - } - } - } - - private void OnHighlightingToolStripMenuItemClick (object sender, EventArgs e) - { - ShowHighlightSettingsDialog(); - } - - private void OnSearchToolStripMenuItemClick (object sender, EventArgs e) - { - OpenSearchDialog(); - } - - private void OnOpenToolStripMenuItemClick (object sender, EventArgs e) - { - OpenFileDialog(); - } - - private void OnLogTabWindowDragEnter (object sender, DragEventArgs e) - { -#if DEBUG - var formats = e.Data.GetFormats(); - var s = "Dragging something over LogExpert. Formats: "; - foreach (var format in formats) - { - s += format; - s += " , "; - } - - s = s[..^3]; - _logger.Info(s); -#endif - } - - private void OnLogWindowDragOver (object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - { - e.Effect = DragDropEffects.None; - } - else - { - e.Effect = DragDropEffects.Copy; - } - } - - private void OnLogWindowDragDrop (object sender, DragEventArgs e) - { -#if DEBUG - var formats = e.Data.GetFormats(); - var s = "Dropped formats: "; - foreach (var format in formats) - { - s += format; - s += " , "; - } - - s = s[..^3]; - _logger.Debug(s); -#endif - - if (e.Data.GetDataPresent(DataFormats.FileDrop)) - { - var o = e.Data.GetData(DataFormats.FileDrop); - if (o is string[] names) - { - LoadFiles(names, (e.KeyState & 4) == 4); // (shift pressed?) - e.Effect = DragDropEffects.Copy; - } - } - } - - [SupportedOSPlatform("windows")] - private void OnTimeShiftToolStripMenuItemCheckStateChanged (object sender, EventArgs e) - { - if (!_skipEvents && CurrentLogWindow != null) - { - CurrentLogWindow.SetTimeshiftValue(timeshiftMenuTextBox.Text); - timeshiftMenuTextBox.Enabled = timeshiftToolStripMenuItem.Checked; - CurrentLogWindow.TimeshiftEnabled(timeshiftToolStripMenuItem.Checked, - timeshiftMenuTextBox.Text); - } - } - - [SupportedOSPlatform("windows")] - private void OnAboutToolStripMenuItemClick (object sender, EventArgs e) - { - AboutBox aboutBox = new() - { - TopMost = TopMost - }; - - aboutBox.ShowDialog(); - } - - private void OnFilterToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ToggleFilterPanel(); - } - - [SupportedOSPlatform("windows")] - private void OnMultiFileToolStripMenuItemClick (object sender, EventArgs e) - { - ToggleMultiFile(); - fileToolStripMenuItem.HideDropDown(); - } - - [SupportedOSPlatform("windows")] - private void OnGuiStateUpdate (object sender, GuiStateArgs e) - { - BeginInvoke(GuiStateUpdateWorker, e); - } - - private void OnColumnizerChanged (object sender, ColumnizerEventArgs e) - { - _bookmarkWindow?.SetColumnizer(e.Columnizer); - } - - private void OnBookmarkAdded (object sender, EventArgs e) - { - _bookmarkWindow.UpdateView(); - } - - private void OnBookmarkTextChanged (object sender, BookmarkEventArgs e) - { - _bookmarkWindow.BookmarkTextChanged(e.Bookmark); - } - - private void OnBookmarkRemoved (object sender, EventArgs e) - { - _bookmarkWindow.UpdateView(); - } - - private void OnProgressBarUpdate (object sender, ProgressEventArgs e) - { - Invoke(ProgressBarUpdateWorker, e); - } - - private void OnStatusLineEvent (object sender, StatusLineEventArgs e) - { - StatusLineEventWorker(e); - } - - private void OnFollowTailCheckBoxClick (object sender, EventArgs e) - { - CurrentLogWindow?.FollowTailChanged(checkBoxFollowTail.Checked, false); - } - - private void OnLogTabWindowKeyDown (object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.W && e.Control) - { - CurrentLogWindow?.Close(); - } - else if (e.KeyCode == Keys.Tab && e.Control) - { - SwitchTab(e.Shift); - } - else - { - CurrentLogWindow?.OnLogWindowKeyDown(sender, e); - } - } - - private void OnCloseFileToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.Close(); - } - - [SupportedOSPlatform("windows")] - private void OnCellSelectModeToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.SetCellSelectionMode(cellSelectModeToolStripMenuItem.Checked); - } - - private void OnCopyMarkedLinesIntoNewTabToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.CopyMarkedLinesToTab(); - } - - private void OnTimeShiftMenuTextBoxKeyDown (object sender, KeyEventArgs e) - { - if (CurrentLogWindow == null) - { - return; - } - - if (e.KeyCode == Keys.Enter) - { - e.Handled = true; - CurrentLogWindow.SetTimeshiftValue(timeshiftMenuTextBox.Text); - } - } - - [SupportedOSPlatform("windows")] - private void OnAlwaysOnTopToolStripMenuItemClick (object sender, EventArgs e) - { - TopMost = alwaysOnTopToolStripMenuItem.Checked; - } - - private void OnFileSizeChanged (object sender, LogEventArgs e) - { - if (sender.GetType().IsAssignableFrom(typeof(LogWindow.LogWindow))) - { - var diff = e.LineCount - e.PrevLineCount; - if (diff < 0) - { - return; - } - - if (((LogWindow.LogWindow)sender).Tag is LogWindowData data) - { - lock (data) - { - data.DiffSum += diff; - if (data.DiffSum > DIFF_MAX) - { - data.DiffSum = DIFF_MAX; - } - } - - //if (this.dockPanel.ActiveContent != null && - // this.dockPanel.ActiveContent != sender || data.tailState != 0) - if (CurrentLogWindow != null && - CurrentLogWindow != sender || data.TailState != 0) - { - data.Dirty = true; - } - var icon = GetIcon(diff, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); - } - } - } - - private void OnLogWindowFileNotFound (object sender, EventArgs e) - { - Invoke(new FileNotFoundDelegate(FileNotFound), sender); - } - - private void OnLogWindowFileRespawned (object sender, EventArgs e) - { - Invoke(new FileRespawnedDelegate(FileRespawned), sender); - } - - private void OnLogWindowFilterListChanged (object sender, FilterListChangedEventArgs e) - { - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - if (logWindow != e.LogWindow) - { - logWindow.HandleChangedFilterList(); - } - } - } - ConfigManager.Save(SettingsFlags.FilterList); - } - - private void OnLogWindowCurrentHighlightGroupChanged (object sender, CurrentHighlightGroupChangedEventArgs e) - { - OnHighlightSettingsChanged(); - ConfigManager.Settings.Preferences.HighlightGroupList = HighlightGroupList; - ConfigManager.Save(SettingsFlags.HighlightSettings); - } - - private void OnTailFollowed (object sender, EventArgs e) - { - if (dockPanel.ActiveContent == null) - { - return; - } - if (sender.GetType().IsAssignableFrom(typeof(LogWindow.LogWindow))) - { - if (dockPanel.ActiveContent == sender) - { - var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; - data.Dirty = false; - var icon = GetIcon(data.DiffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnLogWindowSyncModeChanged (object sender, SyncModeEventArgs e) - { - if (!Disposing) - { - var data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; - data.SyncMode = e.IsTimeSynced ? 1 : 0; - var icon = GetIcon(data.DiffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); - } - else - { - _logger.Warn(CultureInfo.InvariantCulture, "Received SyncModeChanged event while disposing. Event ignored."); - } - } - - [SupportedOSPlatform("windows")] - private void OnToggleBookmarkToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ToggleBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnJumpToNextToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.JumpNextBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnJumpToPrevToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.JumpPrevBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnASCIIToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.ASCII); - } - - [SupportedOSPlatform("windows")] - private void OnANSIToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.Default); - } - - [SupportedOSPlatform("windows")] - private void OnUTF8ToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(new UTF8Encoding(false)); - } - - [SupportedOSPlatform("windows")] - private void OnUTF16ToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.Unicode); - } - - [SupportedOSPlatform("windows")] - private void OnISO88591ToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.GetEncoding("iso-8859-1")); - } - - [SupportedOSPlatform("windows")] - private void OnReloadToolStripMenuItemClick (object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - var data = CurrentLogWindow.Tag as LogWindowData; - var icon = GetIcon(0, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), CurrentLogWindow, icon); - CurrentLogWindow.Reload(); - } - } - - [SupportedOSPlatform("windows")] - private void OnSettingsToolStripMenuItemClick (object sender, EventArgs e) - { - OpenSettings(0); - } - - [SupportedOSPlatform("windows")] - private void OnDateTimeDragControlValueDragged (object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - //this.CurrentLogWindow.ScrollToTimestamp(this.dateTimeDragControl.DateTime); - } - } - - [SupportedOSPlatform("windows")] - private void OnDateTimeDragControlValueChanged (object sender, EventArgs e) - { - CurrentLogWindow?.ScrollToTimestamp(dragControlDateTime.DateTime, true, true); - } - - [SupportedOSPlatform("windows")] - private void OnLogTabWindowDeactivate (object sender, EventArgs e) - { - CurrentLogWindow?.AppFocusLost(); - } - - [SupportedOSPlatform("windows")] - private void OnLogTabWindowActivated (object sender, EventArgs e) - { - CurrentLogWindow?.AppFocusGained(); - } - - [SupportedOSPlatform("windows")] - private void OnShowBookmarkListToolStripMenuItemClick (object sender, EventArgs e) - { - if (_bookmarkWindow.Visible) - { - _bookmarkWindow.Hide(); - } - else - { - // strange: on very first Show() now bookmarks are displayed. after a hide it will work. - if (_firstBookmarkWindowShow) - { - _bookmarkWindow.Show(dockPanel); - _bookmarkWindow.Hide(); - } - - _bookmarkWindow.Show(dockPanel); - } - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonOpenClick (object sender, EventArgs e) - { - OpenFileDialog(); - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonSearchClick (object sender, EventArgs e) - { - OpenSearchDialog(); - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonFilterClick (object sender, EventArgs e) - { - CurrentLogWindow?.ToggleFilterPanel(); - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonBookmarkClick (object sender, EventArgs e) - { - CurrentLogWindow?.ToggleBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonUpClick (object sender, EventArgs e) - { - CurrentLogWindow?.JumpPrevBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonDownClick (object sender, EventArgs e) - { - CurrentLogWindow?.JumpNextBookmark(); - } - - [SupportedOSPlatform("windows")] - private void OnShowHelpToolStripMenuItemClick (object sender, EventArgs e) - { - Help.ShowHelp(this, "LogExpert.chm"); - } - - private void OnHideLineColumnToolStripMenuItemClick (object sender, EventArgs e) - { - ConfigManager.Settings.HideLineColumn = hideLineColumnToolStripMenuItem.Checked; - lock (_logWindowList) - { - foreach (var logWin in _logWindowList) - { - logWin.ShowLineColumn(!ConfigManager.Settings.HideLineColumn); - } - } - _bookmarkWindow.LineColumnVisible = ConfigManager.Settings.HideLineColumn; - } - - // ================================================================== - // Tab context menu stuff - // ================================================================== - - [SupportedOSPlatform("windows")] - private void OnCloseThisTabToolStripMenuItemClick (object sender, EventArgs e) - { - (dockPanel.ActiveContent as LogWindow.LogWindow).Close(); - } - - [SupportedOSPlatform("windows")] - private void OnCloseOtherTabsToolStripMenuItemClick (object sender, EventArgs e) - { - var closeList = dockPanel.Contents - .OfType() - .Where(content => content != dockPanel.ActiveContent) - .ToList(); - - foreach (var logWindow in closeList) - { - logWindow.Close(); - } - } - - [SupportedOSPlatform("windows")] - private void OnCloseAllTabsToolStripMenuItemClick (object sender, EventArgs e) - { - CloseAllTabs(); - } - - [SupportedOSPlatform("windows")] - private void OnTabColorToolStripMenuItemClick (object sender, EventArgs e) - { - var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; - - if (logWindow.Tag is not LogWindowData data) - { - return; - } - - ColorDialog dlg = new() - { - Color = data.Color - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - data.Color = dlg.Color; - SetTabColor(logWindow, data.Color); - } - - List delList = []; - - foreach (var entry in ConfigManager.Settings.FileColors) - { - if (entry.FileName.Equals(logWindow.FileName, StringComparison.Ordinal)) - { - delList.Add(entry); - } - } - - foreach (var entry in delList) - { - _ = ConfigManager.Settings.FileColors.Remove(entry); - } - - ConfigManager.Settings.FileColors.Add(new ColorEntry(logWindow.FileName, dlg.Color)); - - while (ConfigManager.Settings.FileColors.Count > MAX_COLOR_HISTORY) - { - ConfigManager.Settings.FileColors.RemoveAt(0); - } - } - - [SupportedOSPlatform("windows")] - private void OnLogTabWindowSizeChanged (object sender, EventArgs e) - { - if (WindowState != FormWindowState.Minimized) - { - _wasMaximized = WindowState == FormWindowState.Maximized; - } - } - - [SupportedOSPlatform("windows")] - private void OnSaveProjectToolStripMenuItemClick (object sender, EventArgs e) - { - SaveFileDialog dlg = new() - { - DefaultExt = "lxj", - Filter = @"LogExpert session (*.lxj)|*.lxj" - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - var fileName = dlg.FileName; - List fileNames = []; - - lock (_logWindowList) - { - foreach (var logWindow in dockPanel.Contents.OfType()) - { - var persistenceFileName = logWindow?.SavePersistenceData(true); - if (persistenceFileName != null) - { - fileNames.Add(persistenceFileName); - } - } - } - - ProjectData projectData = new() - { - MemberList = fileNames, - TabLayoutXml = SaveLayout() - }; - ProjectPersister.SaveProjectData(fileName, projectData); - } - } - - [SupportedOSPlatform("windows")] - private void OnLoadProjectToolStripMenuItemClick (object sender, EventArgs e) - { - OpenFileDialog dlg = new() - { - DefaultExt = "lxj", - Filter = @"LogExpert sessions (*.lxj)|*.lxj" - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - var projectFileName = dlg.FileName; - LoadProject(projectFileName, true); - } - } - - [SupportedOSPlatform("windows")] - private void OnToolStripButtonBubblesClick (object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - CurrentLogWindow.ShowBookmarkBubbles = toolStripButtonBubbles.Checked; - } - } - - [SupportedOSPlatform("windows")] - private void OnCopyPathToClipboardToolStripMenuItemClick (object sender, EventArgs e) - { - var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; - Clipboard.SetText(logWindow.Title); - } - - private void OnFindInExplorerToolStripMenuItemClick (object sender, EventArgs e) - { - var logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; - - Process explorer = new(); - explorer.StartInfo.FileName = "explorer.exe"; - explorer.StartInfo.Arguments = "/e,/select," + logWindow.Title; - explorer.StartInfo.UseShellExecute = false; - explorer.Start(); - } - - private void TruncateFileToolStripMenuItem_Click (object sender, EventArgs e) - { - CurrentLogWindow?.TryToTruncate(); - } - - private void OnExportBookmarksToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ExportBookmarkList(); - } - - [SupportedOSPlatform("windows")] - private void OnHighlightGroupsComboBoxDropDownClosed (object sender, EventArgs e) - { - ApplySelectedHighlightGroup(); - } - - [SupportedOSPlatform("windows")] - private void OnHighlightGroupsComboBoxSelectedIndexChanged (object sender, EventArgs e) - { - ApplySelectedHighlightGroup(); - } - - [SupportedOSPlatform("windows")] - private void OnHighlightGroupsComboBoxMouseUp (object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - ShowHighlightSettingsDialog(); - } - } - - - private void OnConfigChanged (object sender, ConfigChangedEventArgs e) - { - if (LogExpertProxy != null) - { - NotifySettingsChanged(null, e.Flags); - } - } - - [SupportedOSPlatform("windows")] - private void OnDumpLogBufferInfoToolStripMenuItemClick (object sender, EventArgs e) - { -#if DEBUG - CurrentLogWindow?.DumpBufferInfo(); -#endif - } - - [SupportedOSPlatform("windows")] - private void OnDumpBufferDiagnosticToolStripMenuItemClick (object sender, EventArgs e) - { -#if DEBUG - CurrentLogWindow?.DumpBufferDiagnostic(); -#endif - } - - private void OnRunGCToolStripMenuItemClick (object sender, EventArgs e) - { - RunGC(); - } - - private void OnGCInfoToolStripMenuItemClick (object sender, EventArgs e) - { - DumpGCInfo(); - } - - [SupportedOSPlatform("windows")] - private void OnToolsToolStripMenuItemDropDownItemClicked (object sender, ToolStripItemClickedEventArgs e) - { - if (e.ClickedItem.Tag is ToolEntry tag) - { - ToolButtonClick(tag); - } - } - - [SupportedOSPlatform("windows")] - private void OnExternalToolsToolStripItemClicked (object sender, ToolStripItemClickedEventArgs e) - { - ToolButtonClick(e.ClickedItem.Tag as ToolEntry); - } - - [SupportedOSPlatform("windows")] - private void OnConfigureToolStripMenuItemClick (object sender, EventArgs e) - { - OpenSettings(2); - } - - private void OnThrowExceptionGUIThreadToolStripMenuItemClick (object sender, EventArgs e) - { - throw new Exception("This is a test exception thrown by the GUI thread"); - } - - private void OnThrowExceptionBackgroundThToolStripMenuItemClick (object sender, EventArgs e) - { - ExceptionFx fx = ThrowExceptionFx; - fx.BeginInvoke(null, null); - } - - private void OnThrowExceptionBackgroundThreadToolStripMenuItemClick (object sender, EventArgs e) - { - Thread thread = new(ThrowExceptionThreadFx) - { - IsBackground = true - }; - - thread.Start(); - } - - private void OnWarnToolStripMenuItemClick (object sender, EventArgs e) - { - //_logger.GetLogger().LogLevel = _logger.Level.WARN; - } - - private void OnInfoToolStripMenuItemClick (object sender, EventArgs e) - { - //_logger.Get_logger().LogLevel = _logger.Level.INFO; - } - - private void OnDebugToolStripMenuItemClick (object sender, EventArgs e) - { - //_logger.Get_logger().LogLevel = _logger.Level.DEBUG; - } - - private void OnLogLevelToolStripMenuItemClick (object sender, EventArgs e) - { - } - - private void OnLogLevelToolStripMenuItemDropDownOpening (object sender, EventArgs e) - { - //warnToolStripMenuItem.Checked = _logger.Get_logger().LogLevel == _logger.Level.WARN; - //infoToolStripMenuItem.Checked = _logger.Get_logger().LogLevel == _logger.Level.INFO; - //debugToolStripMenuItem1.Checked = _logger.Get_logger().LogLevel == _logger.Level.DEBUG; - } - - [SupportedOSPlatform("windows")] - private void OnDisableWordHighlightModeToolStripMenuItemClick (object sender, EventArgs e) - { - DebugOptions.DisableWordHighlight = disableWordHighlightModeToolStripMenuItem.Checked; - CurrentLogWindow?.RefreshAllGrids(); - } - - [SupportedOSPlatform("windows")] - private void OnMultiFileMaskToolStripMenuItemClick (object sender, EventArgs e) - { - CurrentLogWindow?.ChangeMultifileMask(); - } - - [SupportedOSPlatform("windows")] - private void OnMultiFileEnabledStripMenuItemClick (object sender, EventArgs e) - { - ToggleMultiFile(); - } - - [SupportedOSPlatform("windows")] - private void OnLockInstanceToolStripMenuItemClick (object sender, EventArgs e) - { - AbstractLogTabWindow.StaticData.CurrentLockedMainWindow = lockInstanceToolStripMenuItem.Checked ? null : this; - } - - [SupportedOSPlatform("windows")] - private void OnOptionToolStripMenuItemDropDownOpening (object sender, EventArgs e) - { - lockInstanceToolStripMenuItem.Enabled = !ConfigManager.Settings.Preferences.AllowOnlyOneInstance; - lockInstanceToolStripMenuItem.Checked = AbstractLogTabWindow.StaticData.CurrentLockedMainWindow == this; - } - - [SupportedOSPlatform("windows")] - private void OnFileToolStripMenuItemDropDownOpening (object sender, EventArgs e) - { - newFromClipboardToolStripMenuItem.Enabled = Clipboard.ContainsText(); - } - - [SupportedOSPlatform("windows")] - private void OnNewFromClipboardToolStripMenuItemClick (object sender, EventArgs e) - { - PasteFromClipboard(); - } - - [SupportedOSPlatform("windows")] - private void OnOpenURIToolStripMenuItemClick (object sender, EventArgs e) - { - OpenUriDialog dlg = new() - { - UriHistory = ConfigManager.Settings.UriHistoryList - }; - - if (DialogResult.OK == dlg.ShowDialog()) - { - if (dlg.Uri.Trim().Length > 0) - { - ConfigManager.Settings.UriHistoryList = dlg.UriHistory; - ConfigManager.Save(SettingsFlags.FileHistory); - LoadFiles([dlg.Uri], false); - } - } - } - - [SupportedOSPlatform("windows")] - private void OnColumnFinderToolStripMenuItemClick (object sender, EventArgs e) - { - if (CurrentLogWindow != null && !_skipEvents) - { - CurrentLogWindow.ToggleColumnFinder(columnFinderToolStripMenuItem.Checked, true); - } - } - - [SupportedOSPlatform("windows")] - private void OnDockPanelActiveContentChanged (object sender, EventArgs e) - { - if (dockPanel.ActiveContent is LogWindow.LogWindow window) - { - CurrentLogWindow = window; - CurrentLogWindow.LogWindowActivated(); - ConnectToolWindows(CurrentLogWindow); - } - } - - [SupportedOSPlatform("windows")] - private void OnTabRenameToolStripMenuItemClick (object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - TabRenameDialog dlg = new() - { - TabName = CurrentLogWindow.Text - }; - - if (DialogResult.OK == dlg.ShowDialog()) - { - CurrentLogWindow.Text = dlg.TabName; - } - - dlg.Dispose(); - } - } - - #endregion -} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs deleted file mode 100644 index 4a4760c9..00000000 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPrivate.cs +++ /dev/null @@ -1,1375 +0,0 @@ -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.Versioning; -using System.Security; -using System.Text; - -using LogExpert.Core.Classes; -using LogExpert.Core.Classes.Columnizer; -using LogExpert.Core.Classes.Persister; -using LogExpert.Core.Config; -using LogExpert.Core.Entities; -using LogExpert.Core.Enums; -using LogExpert.Core.EventArguments; -using LogExpert.Dialogs; -using LogExpert.PluginRegistry.FileSystem; -using LogExpert.UI.Dialogs; -using LogExpert.UI.Entities; -using LogExpert.UI.Extensions; - -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.UI.Controls.LogTabWindow; - -internal partial class LogTabWindow -{ - #region Private Methods - - /// - /// Creates a temp file with the text content of the clipboard and opens the temp file in a new tab. - /// - [SupportedOSPlatform("windows")] - private void PasteFromClipboard () - { - if (Clipboard.ContainsText()) - { - var text = Clipboard.GetText(); - var fileName = Path.GetTempFileName(); - - using (FileStream fStream = new(fileName, FileMode.Append, FileAccess.Write, FileShare.Read)) - using (StreamWriter writer = new(fStream, Encoding.Unicode)) - { - writer.Write(text); - writer.Close(); - } - - var title = "Clipboard"; - var logWindow = AddTempFileTab(fileName, title); - if (logWindow.Tag is LogWindowData data) - { - SetTooltipText(logWindow, "Pasted on " + DateTime.Now); - } - } - } - - [SupportedOSPlatform("windows")] - private void InitToolWindows () - { - InitBookmarkWindow(); - } - - [SupportedOSPlatform("windows")] - private void DestroyToolWindows () - { - DestroyBookmarkWindow(); - } - - [SupportedOSPlatform("windows")] - private void InitBookmarkWindow () - { - _bookmarkWindow = new BookmarkWindow - { - HideOnClose = true, - ShowHint = DockState.DockBottom - }; - - var setLastColumnWidth = ConfigManager.Settings.Preferences.SetLastColumnWidth; - var lastColumnWidth = ConfigManager.Settings.Preferences.LastColumnWidth; - var fontName = ConfigManager.Settings.Preferences.FontName; - var fontSize = ConfigManager.Settings.Preferences.FontSize; - - _bookmarkWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, SettingsFlags.All); - _bookmarkWindow.VisibleChanged += OnBookmarkWindowVisibleChanged; - _firstBookmarkWindowShow = true; - } - - [SupportedOSPlatform("windows")] - private void DestroyBookmarkWindow () - { - _bookmarkWindow.HideOnClose = false; - _bookmarkWindow.Close(); - } - - private void SaveLastOpenFilesList () - { - ConfigManager.Settings.LastOpenFilesList.Clear(); - foreach (DockContent content in dockPanel.Contents) - { - if (content is LogWindow.LogWindow logWin) - { - if (!logWin.IsTempFile) - { - ConfigManager.Settings.LastOpenFilesList.Add(logWin.GivenFileName); - } - } - } - } - - [SupportedOSPlatform("windows")] - private void SaveWindowPosition () - { - SuspendLayout(); - if (WindowState == FormWindowState.Normal) - { - ConfigManager.Settings.AppBounds = Bounds; - ConfigManager.Settings.IsMaximized = false; - } - else - { - ConfigManager.Settings.AppBoundsFullscreen = Bounds; - ConfigManager.Settings.IsMaximized = true; - WindowState = FormWindowState.Normal; - ConfigManager.Settings.AppBounds = Bounds; - } - - ResumeLayout(); - } - - private void SetTooltipText (LogWindow.LogWindow logWindow, string logFileName) - { - logWindow.ToolTipText = logFileName; - } - - private void FillDefaultEncodingFromSettings (EncodingOptions encodingOptions) - { - if (ConfigManager.Settings.Preferences.DefaultEncoding != null) - { - try - { - encodingOptions.DefaultEncoding = Encoding.GetEncoding(ConfigManager.Settings.Preferences.DefaultEncoding); - } - catch (ArgumentException) - { - _logger.Warn(CultureInfo.InvariantCulture, "Encoding " + ConfigManager.Settings.Preferences.DefaultEncoding + " is not a valid encoding"); - encodingOptions.DefaultEncoding = null; - } - } - } - - [SupportedOSPlatform("windows")] - private void AddFileTabs (string[] fileNames) - { - foreach (var fileName in fileNames) - { - if (!string.IsNullOrEmpty(fileName)) - { - if (fileName.EndsWith(".lxj")) - { - LoadProject(fileName, false); - } - else - { - AddFileTab(fileName, false, null, false, null); - } - } - } - - Activate(); - } - - [SupportedOSPlatform("windows")] - private void AddLogWindow (LogWindow.LogWindow logWindow, string title, bool doNotAddToPanel) - { - logWindow.CloseButton = true; - logWindow.TabPageContextMenuStrip = tabContextMenuStrip; - SetTooltipText(logWindow, title); - logWindow.DockAreas = DockAreas.Document | DockAreas.Float; - - if (!doNotAddToPanel) - { - logWindow.Show(dockPanel); - } - - LogWindowData data = new() - { - DiffSum = 0 - }; - - logWindow.Tag = data; - - lock (_logWindowList) - { - _logWindowList.Add(logWindow); - } - - logWindow.FileSizeChanged += OnFileSizeChanged; - logWindow.TailFollowed += OnTailFollowed; - logWindow.Disposed += OnLogWindowDisposed; - logWindow.FileNotFound += OnLogWindowFileNotFound; - logWindow.FileRespawned += OnLogWindowFileRespawned; - logWindow.FilterListChanged += OnLogWindowFilterListChanged; - logWindow.CurrentHighlightGroupChanged += OnLogWindowCurrentHighlightGroupChanged; - logWindow.SyncModeChanged += OnLogWindowSyncModeChanged; - - logWindow.Visible = true; - } - - [SupportedOSPlatform("windows")] - private void DisconnectEventHandlers (LogWindow.LogWindow logWindow) - { - logWindow.FileSizeChanged -= OnFileSizeChanged; - logWindow.TailFollowed -= OnTailFollowed; - logWindow.Disposed -= OnLogWindowDisposed; - logWindow.FileNotFound -= OnLogWindowFileNotFound; - logWindow.FileRespawned -= OnLogWindowFileRespawned; - logWindow.FilterListChanged -= OnLogWindowFilterListChanged; - logWindow.CurrentHighlightGroupChanged -= OnLogWindowCurrentHighlightGroupChanged; - logWindow.SyncModeChanged -= OnLogWindowSyncModeChanged; - - var data = logWindow.Tag as LogWindowData; - //data.tabPage.MouseClick -= tabPage_MouseClick; - //data.tabPage.TabDoubleClick -= tabPage_TabDoubleClick; - //data.tabPage.ContextMenuStrip = null; - //data.tabPage = null; - } - - [SupportedOSPlatform("windows")] - private void AddToFileHistory (string fileName) - { - bool FindName (string s) => s.ToUpperInvariant().Equals(fileName.ToUpperInvariant(), StringComparison.Ordinal); - - var index = ConfigManager.Settings.FileHistoryList.FindIndex(FindName); - - if (index != -1) - { - ConfigManager.Settings.FileHistoryList.RemoveAt(index); - } - - ConfigManager.Settings.FileHistoryList.Insert(0, fileName); - - while (ConfigManager.Settings.FileHistoryList.Count > MAX_FILE_HISTORY) - { - ConfigManager.Settings.FileHistoryList.RemoveAt(ConfigManager.Settings.FileHistoryList.Count - 1); - } - - ConfigManager.Save(SettingsFlags.FileHistory); - - FillHistoryMenu(); - } - - [SupportedOSPlatform("windows")] - private LogWindow.LogWindow FindWindowForFile (string fileName) - { - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - if (logWindow.FileName.ToUpperInvariant().Equals(fileName.ToUpperInvariant(), StringComparison.Ordinal)) - { - return logWindow; - } - } - } - - return null; - } - - /// - /// Checks if the file name is a settings file. If so, the contained logfile name - /// is returned. If not, the given file name is returned unchanged. - /// - /// - /// - private string FindFilenameForSettings (string fileName) - { - if (fileName.EndsWith(".lxp")) - { - var persistenceData = Persister.LoadOptionsOnly(fileName); - if (persistenceData == null) - { - return fileName; - } - - if (!string.IsNullOrEmpty(persistenceData.FileName)) - { - var fs = PluginRegistry.PluginRegistry.Instance.FindFileSystemForUri(persistenceData.FileName); - if (fs != null && !fs.GetType().Equals(typeof(LocalFileSystem))) - { - return persistenceData.FileName; - } - - // On relative paths the URI check (and therefore the file system plugin check) will fail. - // So fs == null and fs == LocalFileSystem are handled here like normal files. - if (Path.IsPathRooted(persistenceData.FileName)) - { - return persistenceData.FileName; - } - - // handle relative paths in .lxp files - var dir = Path.GetDirectoryName(fileName); - return Path.Combine(dir, persistenceData.FileName); - } - } - - return fileName; - } - - [SupportedOSPlatform("windows")] - private void FillHistoryMenu () - { - ToolStripDropDown strip = new ToolStripDropDownMenu(); - - foreach (var file in ConfigManager.Settings.FileHistoryList) - { - ToolStripItem item = new ToolStripMenuItem(file); - strip.Items.Add(item); - } - - strip.ItemClicked += OnHistoryItemClicked; - strip.MouseUp += OnStripMouseUp; - lastUsedToolStripMenuItem.DropDown = strip; - } - - [SupportedOSPlatform("windows")] - private void RemoveLogWindow (LogWindow.LogWindow logWindow) - { - lock (_logWindowList) - { - _logWindowList.Remove(logWindow); - } - - DisconnectEventHandlers(logWindow); - } - - [SupportedOSPlatform("windows")] - private void RemoveAndDisposeLogWindow (LogWindow.LogWindow logWindow, bool dontAsk) - { - if (CurrentLogWindow == logWindow) - { - ChangeCurrentLogWindow(null); - } - - lock (_logWindowList) - { - _logWindowList.Remove(logWindow); - } - - logWindow.Close(dontAsk); - } - - [SupportedOSPlatform("windows")] - private void ShowHighlightSettingsDialog () - { - HighlightDialog dlg = new(ConfigManager) - { - KeywordActionList = PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions, - Owner = this, - TopMost = TopMost, - HighlightGroupList = HighlightGroupList, - PreSelectedGroupName = groupsComboBoxHighlightGroups.Text - }; - - var res = dlg.ShowDialog(); - - if (res == DialogResult.OK) - { - HighlightGroupList = dlg.HighlightGroupList; - FillHighlightComboBox(); - ConfigManager.Settings.Preferences.HighlightGroupList = HighlightGroupList; - ConfigManager.Save(SettingsFlags.HighlightSettings); - OnHighlightSettingsChanged(); - } - } - - [SupportedOSPlatform("windows")] - private void FillHighlightComboBox () - { - var currentGroupName = groupsComboBoxHighlightGroups.Text; - groupsComboBoxHighlightGroups.Items.Clear(); - foreach (var group in HighlightGroupList) - { - groupsComboBoxHighlightGroups.Items.Add(group.GroupName); - if (group.GroupName.Equals(currentGroupName, StringComparison.Ordinal)) - { - groupsComboBoxHighlightGroups.Text = group.GroupName; - } - } - } - - [SupportedOSPlatform("windows")] - private void OpenFileDialog () - { - OpenFileDialog openFileDialog = new(); - - if (CurrentLogWindow != null) - { - FileInfo info = new(CurrentLogWindow.FileName); - openFileDialog.InitialDirectory = info.DirectoryName; - } - else - { - if (!string.IsNullOrEmpty(ConfigManager.Settings.LastDirectory)) - { - openFileDialog.InitialDirectory = ConfigManager.Settings.LastDirectory; - } - else - { - try - { - openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - } - catch (SecurityException e) - { - _logger.Warn(e, "Insufficient rights for GetFolderPath(): "); - // no initial directory if insufficient rights - } - } - } - - openFileDialog.Multiselect = true; - - if (DialogResult.OK == openFileDialog.ShowDialog(this)) - { - FileInfo info = new(openFileDialog.FileName); - if (info.Directory.Exists) - { - ConfigManager.Settings.LastDirectory = info.DirectoryName; - ConfigManager.Save(SettingsFlags.FileHistory); - } - - if (info.Exists) - { - LoadFiles(openFileDialog.FileNames, false); - } - } - } - - [SupportedOSPlatform("windows")] - private void LoadFiles (string[] names, bool invertLogic) - { - Array.Sort(names); - - if (names.Length == 1) - { - if (names[0].EndsWith(".lxj")) - { - LoadProject(names[0], true); - return; - } - - AddFileTab(names[0], false, null, false, null); - return; - } - - var option = ConfigManager.Settings.Preferences.MultiFileOption; - if (option == MultiFileOption.Ask) - { - MultiLoadRequestDialog dlg = new(); - var res = dlg.ShowDialog(); - - if (res == DialogResult.Yes) - { - option = MultiFileOption.SingleFiles; - } - else if (res == DialogResult.No) - { - option = MultiFileOption.MultiFile; - } - else - { - return; - } - } - else - { - if (invertLogic) - { - option = option == MultiFileOption.SingleFiles - ? MultiFileOption.MultiFile - : MultiFileOption.SingleFiles; - } - } - - if (option == MultiFileOption.SingleFiles) - { - AddFileTabs(names); - } - else - { - AddMultiFileTab(names); - } - } - - private void SetColumnizerHistoryEntry (string fileName, ILogLineColumnizer columnizer) - { - var entry = FindColumnizerHistoryEntry(fileName); - if (entry != null) - { - _ = ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); - - } - - ConfigManager.Settings.ColumnizerHistoryList.Add(new ColumnizerHistoryEntry(fileName, columnizer.GetName())); - - if (ConfigManager.Settings.ColumnizerHistoryList.Count > MAX_COLUMNIZER_HISTORY) - { - ConfigManager.Settings.ColumnizerHistoryList.RemoveAt(0); - } - } - - private ColumnizerHistoryEntry FindColumnizerHistoryEntry (string fileName) - { - foreach (var entry in ConfigManager.Settings.ColumnizerHistoryList) - { - if (entry.FileName.Equals(fileName, StringComparison.Ordinal)) - { - return entry; - } - } - - return null; - } - - [SupportedOSPlatform("windows")] - private void ToggleMultiFile () - { - if (CurrentLogWindow != null) - { - CurrentLogWindow.SwitchMultiFile(!CurrentLogWindow.IsMultiFile); - multiFileToolStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; - multiFileEnabledStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; - } - } - - [SupportedOSPlatform("windows")] - private void ChangeCurrentLogWindow (LogWindow.LogWindow newLogWindow) - { - if (newLogWindow == _currentLogWindow) - { - return; // do nothing if wishing to set the same window - } - - var oldLogWindow = _currentLogWindow; - _currentLogWindow = newLogWindow; - var titleName = _showInstanceNumbers ? "LogExpert #" + _instanceNumber : "LogExpert"; - - if (oldLogWindow != null) - { - oldLogWindow.StatusLineEvent -= OnStatusLineEvent; - oldLogWindow.ProgressBarUpdate -= OnProgressBarUpdate; - oldLogWindow.GuiStateUpdate -= OnGuiStateUpdate; - oldLogWindow.ColumnizerChanged -= OnColumnizerChanged; - oldLogWindow.BookmarkAdded -= OnBookmarkAdded; - oldLogWindow.BookmarkRemoved -= OnBookmarkRemoved; - oldLogWindow.BookmarkTextChanged -= OnBookmarkTextChanged; - DisconnectToolWindows(oldLogWindow); - } - - if (newLogWindow != null) - { - newLogWindow.StatusLineEvent += OnStatusLineEvent; - newLogWindow.ProgressBarUpdate += OnProgressBarUpdate; - newLogWindow.GuiStateUpdate += OnGuiStateUpdate; - newLogWindow.ColumnizerChanged += OnColumnizerChanged; - newLogWindow.BookmarkAdded += OnBookmarkAdded; - newLogWindow.BookmarkRemoved += OnBookmarkRemoved; - newLogWindow.BookmarkTextChanged += OnBookmarkTextChanged; - - Text = newLogWindow.IsTempFile - ? titleName + @" - " + newLogWindow.TempTitleName - : titleName + @" - " + newLogWindow.FileName; - - multiFileToolStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; - multiFileToolStripMenuItem.Enabled = true; - multiFileEnabledStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; - cellSelectModeToolStripMenuItem.Checked = true; - cellSelectModeToolStripMenuItem.Enabled = true; - closeFileToolStripMenuItem.Enabled = true; - searchToolStripMenuItem.Enabled = true; - filterToolStripMenuItem.Enabled = true; - goToLineToolStripMenuItem.Enabled = true; - //ConnectToolWindows(newLogWindow); - } - else - { - Text = titleName; - multiFileToolStripMenuItem.Checked = false; - multiFileEnabledStripMenuItem.Checked = false; - checkBoxFollowTail.Checked = false; - mainMenuStrip.Enabled = true; - timeshiftToolStripMenuItem.Enabled = false; - timeshiftToolStripMenuItem.Checked = false; - timeshiftMenuTextBox.Text = ""; - timeshiftMenuTextBox.Enabled = false; - multiFileToolStripMenuItem.Enabled = false; - cellSelectModeToolStripMenuItem.Checked = false; - cellSelectModeToolStripMenuItem.Enabled = false; - closeFileToolStripMenuItem.Enabled = false; - searchToolStripMenuItem.Enabled = false; - filterToolStripMenuItem.Enabled = false; - goToLineToolStripMenuItem.Enabled = false; - dragControlDateTime.Visible = false; - } - } - - private void ConnectToolWindows (LogWindow.LogWindow logWindow) - { - ConnectBookmarkWindow(logWindow); - } - - private void ConnectBookmarkWindow (LogWindow.LogWindow logWindow) - { - FileViewContext ctx = new(logWindow, logWindow); - _bookmarkWindow.SetBookmarkData(logWindow.BookmarkData); - _bookmarkWindow.SetCurrentFile(ctx); - } - - private void DisconnectToolWindows (LogWindow.LogWindow logWindow) - { - DisconnectBookmarkWindow(logWindow); - } - - private void DisconnectBookmarkWindow (LogWindow.LogWindow logWindow) - { - _bookmarkWindow.SetBookmarkData(null); - _bookmarkWindow.SetCurrentFile(null); - } - - [SupportedOSPlatform("windows")] - private void GuiStateUpdateWorker (GuiStateArgs e) - { - _skipEvents = true; - checkBoxFollowTail.Checked = e.FollowTail; - mainMenuStrip.Enabled = e.MenuEnabled; - timeshiftToolStripMenuItem.Enabled = e.TimeshiftPossible; - timeshiftToolStripMenuItem.Checked = e.TimeshiftEnabled; - timeshiftMenuTextBox.Text = e.TimeshiftText; - timeshiftMenuTextBox.Enabled = e.TimeshiftEnabled; - multiFileToolStripMenuItem.Enabled = e.MultiFileEnabled; // disabled for temp files - multiFileToolStripMenuItem.Checked = e.IsMultiFileActive; - multiFileEnabledStripMenuItem.Checked = e.IsMultiFileActive; - cellSelectModeToolStripMenuItem.Checked = e.CellSelectMode; - RefreshEncodingMenuBar(e.CurrentEncoding); - - if (e.TimeshiftPossible && ConfigManager.Settings.Preferences.TimestampControl) - { - dragControlDateTime.MinDateTime = e.MinTimestamp; - dragControlDateTime.MaxDateTime = e.MaxTimestamp; - dragControlDateTime.DateTime = e.Timestamp; - dragControlDateTime.Visible = true; - dragControlDateTime.Enabled = true; - dragControlDateTime.Refresh(); - } - else - { - dragControlDateTime.Visible = false; - dragControlDateTime.Enabled = false; - } - - toolStripButtonBubbles.Checked = e.ShowBookmarkBubbles; - groupsComboBoxHighlightGroups.Text = e.HighlightGroupName; - columnFinderToolStripMenuItem.Checked = e.ColumnFinderVisible; - - _skipEvents = false; - } - - [SupportedOSPlatform("windows")] - private void ProgressBarUpdateWorker (ProgressEventArgs e) - { - if (e.Value <= e.MaxValue && e.Value >= e.MinValue) - { - try - { - loadProgessBar.Minimum = e.MinValue; - loadProgessBar.Maximum = e.MaxValue; - loadProgessBar.Value = e.Value; - loadProgessBar.Visible = e.Visible; - } - catch (Exception ex) - { - _logger.Error(ex, "Error during ProgressBarUpdateWorker value {0}, min {1}, max {2}, visible {3}", e.Value, e.MinValue, e.MaxValue, e.Visible); - } - - Invoke(new MethodInvoker(statusStrip.Refresh)); - } - } - - [SupportedOSPlatform("windows")] - //TODO Crossthread Exception when a log file has been filtered to a new tab! - private void StatusLineEventWorker (StatusLineEventArgs e) - { - if (e != null) - { - //_logger.logDebug("StatusLineEvent: text = " + e.StatusText); - labelStatus.Text = e.StatusText; - labelStatus.Size = TextRenderer.MeasureText(labelStatus.Text, labelStatus.Font); - labelLines.Text = $" {e.LineCount} lines"; - labelLines.Size = TextRenderer.MeasureText(labelLines.Text, labelLines.Font); - labelSize.Text = Util.GetFileSizeAsText(e.FileSize); - labelSize.Size = TextRenderer.MeasureText(labelSize.Text, labelSize.Font); - labelCurrentLine.Text = $"Line: {e.CurrentLineNum}"; - labelCurrentLine.Size = TextRenderer.MeasureText(labelCurrentLine.Text, labelCurrentLine.Font); - if (statusStrip.InvokeRequired) - { - statusStrip.BeginInvoke(new MethodInvoker(statusStrip.Refresh)); - } - else - { - statusStrip.Refresh(); - } - } - } - - // tailState: 0,1,2 = on/off/off by Trigger - // syncMode: 0 = normal (no), 1 = time synced - [SupportedOSPlatform("windows")] - private Icon CreateLedIcon (int level, bool dirty, int tailState, int syncMode) - { - var iconRect = _leds[0]; - iconRect.Height = 16; // (DockPanel's damn hardcoded height) // this.leds[this.leds.Length - 1].Bottom; - iconRect.Width = iconRect.Right + 6; - Bitmap bmp = new(iconRect.Width, iconRect.Height); - var gfx = Graphics.FromImage(bmp); - - var offsetFromTop = 4; - - for (var i = 0; i < _leds.Length; ++i) - { - var ledRect = _leds[i]; - ledRect.Offset(0, offsetFromTop); - - if (level >= _leds.Length - i) - { - gfx.FillRectangle(_ledBrushes[i], ledRect); - } - else - { - gfx.FillRectangle(_offLedBrush, ledRect); - } - } - - var ledSize = 3; - var ledGap = 1; - var lastLed = _leds[^1]; - Rectangle dirtyLed = new(lastLed.Right + 2, lastLed.Bottom - ledSize, ledSize, ledSize); - Rectangle tailLed = new(dirtyLed.Location, dirtyLed.Size); - tailLed.Offset(0, -(ledSize + ledGap)); - Rectangle syncLed = new(tailLed.Location, dirtyLed.Size); - syncLed.Offset(0, -(ledSize + ledGap)); - - syncLed.Offset(0, offsetFromTop); - tailLed.Offset(0, offsetFromTop); - dirtyLed.Offset(0, offsetFromTop); - - if (dirty) - { - gfx.FillRectangle(_dirtyLedBrush, dirtyLed); - } - else - { - gfx.FillRectangle(_offLedBrush, dirtyLed); - } - - // tailMode 4 means: don't show - if (tailState < 3) - { - gfx.FillRectangle(_tailLedBrush[tailState], tailLed); - } - - if (syncMode == 1) - { - gfx.FillRectangle(_syncLedBrush, syncLed); - } - //else - //{ - // gfx.FillRectangle(this.offLedBrush, syncLed); - //} - - // see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=345656 - // GetHicon() creates an unmanaged handle which must be destroyed. The Clone() workaround creates - // a managed copy of icon. then the unmanaged win32 handle is destroyed - var iconHandle = bmp.GetHicon(); - var icon = Icon.FromHandle(iconHandle).Clone() as Icon; - NativeMethods.DestroyIcon(iconHandle); - - gfx.Dispose(); - bmp.Dispose(); - return icon; - } - - [SupportedOSPlatform("windows")] - private void CreateIcons () - { - for (var syncMode = 0; syncMode <= 1; syncMode++) // LED indicating time synced tabs - { - for (var tailMode = 0; tailMode < 4; tailMode++) - { - for (var i = 0; i < 6; ++i) - { - _ledIcons[i, 0, tailMode, syncMode] = CreateLedIcon(i, false, tailMode, syncMode); - } - - for (var i = 0; i < 6; ++i) - { - _ledIcons[i, 1, tailMode, syncMode] = CreateLedIcon(i, true, tailMode, syncMode); - } - } - } - } - - [SupportedOSPlatform("windows")] - private void FileNotFound (LogWindow.LogWindow logWin) - { - var data = logWin.Tag as LogWindowData; - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, _deadIcon); - dragControlDateTime.Visible = false; - } - - [SupportedOSPlatform("windows")] - private void FileRespawned (LogWindow.LogWindow logWin) - { - var data = logWin.Tag as LogWindowData; - var icon = GetIcon(0, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); - } - - [SupportedOSPlatform("windows")] - private void ShowLedPeak (LogWindow.LogWindow logWin) - { - var data = logWin.Tag as LogWindowData; - lock (data) - { - data.DiffSum = DIFF_MAX; - } - - var icon = GetIcon(data.DiffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); - } - - private int GetLevelFromDiff (int diff) - { - if (diff > 60) - { - diff = 60; - } - - var level = diff / 10; - if (diff > 0 && level == 0) - { - level = 2; - } - else if (level == 0) - { - level = 1; - } - - return level - 1; - } - - [SupportedOSPlatform("windows")] - private void LedThreadProc () - { - Thread.CurrentThread.Name = "LED Thread"; - while (!_shouldStop) - { - try - { - Thread.Sleep(200); - } - catch - { - return; - } - - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - var data = logWindow.Tag as LogWindowData; - if (data.DiffSum > 0) - { - data.DiffSum -= 10; - if (data.DiffSum < 0) - { - data.DiffSum = 0; - } - - var icon = GetIcon(data.DiffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); - } - } - } - } - } - - [SupportedOSPlatform("windows")] - private void SetTabIcon (LogWindow.LogWindow logWindow, Icon icon) - { - if (logWindow != null) - { - logWindow.Icon = icon; - logWindow.DockHandler.Pane?.TabStripControl.Invalidate(false); - } - } - - private Icon GetIcon (int diff, LogWindowData data) - { - var icon = - _ledIcons[ - GetLevelFromDiff(diff), data.Dirty ? 1 : 0, Preferences.ShowTailState ? data.TailState : 3, - data.SyncMode - ]; - return icon; - } - - [SupportedOSPlatform("windows")] - private void RefreshEncodingMenuBar (Encoding encoding) - { - toolStripEncodingASCIIItem.Checked = false; - toolStripEncodingANSIItem.Checked = false; - toolStripEncodingUTF8Item.Checked = false; - toolStripEncodingUTF16Item.Checked = false; - toolStripEncodingISO88591Item.Checked = false; - - if (encoding == null) - { - return; - } - - if (encoding is ASCIIEncoding) - { - toolStripEncodingASCIIItem.Checked = true; - } - else if (encoding.Equals(Encoding.Default)) - { - toolStripEncodingANSIItem.Checked = true; - } - else if (encoding is UTF8Encoding) - { - toolStripEncodingUTF8Item.Checked = true; - } - else if (encoding is UnicodeEncoding) - { - toolStripEncodingUTF16Item.Checked = true; - } - else if (encoding.Equals(Encoding.GetEncoding("iso-8859-1"))) - { - toolStripEncodingISO88591Item.Checked = true; - } - - toolStripEncodingANSIItem.Text = Encoding.Default.HeaderName; - } - - [SupportedOSPlatform("windows")] - private void OpenSettings (int tabToOpen) - { - SettingsDialog dlg = new(ConfigManager.Settings.Preferences, this, tabToOpen, ConfigManager) - { - TopMost = TopMost - }; - - if (DialogResult.OK == dlg.ShowDialog()) - { - ConfigManager.Settings.Preferences = dlg.Preferences; - ConfigManager.Save(SettingsFlags.Settings); - NotifyWindowsForChangedPrefs(SettingsFlags.Settings); - } - } - - [SupportedOSPlatform("windows")] - private void NotifyWindowsForChangedPrefs (SettingsFlags flags) - { - _logger.Info(CultureInfo.InvariantCulture, "The preferences have changed"); - ApplySettings(ConfigManager.Settings, flags); - - var setLastColumnWidth = ConfigManager.Settings.Preferences.SetLastColumnWidth; - var lastColumnWidth = ConfigManager.Settings.Preferences.LastColumnWidth; - var fontName = ConfigManager.Settings.Preferences.FontName; - var fontSize = ConfigManager.Settings.Preferences.FontSize; - - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - logWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, false, flags); - } - } - - _bookmarkWindow.PreferencesChanged(fontName, fontSize, setLastColumnWidth, lastColumnWidth, flags); - - HighlightGroupList = ConfigManager.Settings.Preferences.HighlightGroupList; - if ((flags & SettingsFlags.HighlightSettings) == SettingsFlags.HighlightSettings) - { - OnHighlightSettingsChanged(); - } - } - - [SupportedOSPlatform("windows")] - private void ApplySettings (Settings settings, SettingsFlags flags) - { - if ((flags & SettingsFlags.WindowPosition) == SettingsFlags.WindowPosition) - { - TopMost = alwaysOnTopToolStripMenuItem.Checked = settings.AlwaysOnTop; - dragControlDateTime.DragOrientation = settings.Preferences.TimestampControlDragOrientation; - hideLineColumnToolStripMenuItem.Checked = settings.HideLineColumn; - } - - if ((flags & SettingsFlags.FileHistory) == SettingsFlags.FileHistory) - { - FillHistoryMenu(); - } - - if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) - { - SetTabIcons(settings.Preferences); - } - - if ((flags & SettingsFlags.ToolSettings) == SettingsFlags.ToolSettings) - { - FillToolLauncherBar(); - } - - if ((flags & SettingsFlags.HighlightSettings) == SettingsFlags.HighlightSettings) - { - FillHighlightComboBox(); - } - } - - [SupportedOSPlatform("windows")] - private void SetTabIcons (Preferences preferences) - { - _tailLedBrush[0] = new SolidBrush(preferences.ShowTailColor); - CreateIcons(); - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - var data = logWindow.Tag as LogWindowData; - var icon = GetIcon(data.DiffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); - } - } - } - - [SupportedOSPlatform("windows")] - private void SetToolIcon (ToolEntry entry, ToolStripItem item) - { - var icon = NativeMethods.LoadIconFromExe(entry.IconFile, entry.IconIndex); - - if (icon != null) - { - item.Image = icon.ToBitmap(); - - item.DisplayStyle = item is ToolStripMenuItem - ? ToolStripItemDisplayStyle.ImageAndText - : ToolStripItemDisplayStyle.Image; - - NativeMethods.DestroyIcon(icon.Handle); - icon.Dispose(); - } - - if (!string.IsNullOrEmpty(entry.Cmd)) - { - item.ToolTipText = entry.Name; - } - } - - [SupportedOSPlatform("windows")] - private void ToolButtonClick (ToolEntry toolEntry) - { - if (string.IsNullOrEmpty(toolEntry.Cmd)) - { - //TODO TabIndex => To Enum - OpenSettings(2); - return; - } - - if (CurrentLogWindow != null) - { - var line = CurrentLogWindow.GetCurrentLine(); - var info = CurrentLogWindow.GetCurrentFileInfo(); - if (line != null && info != null) - { - ArgParser parser = new(toolEntry.Args); - var argLine = parser.BuildArgs(line, CurrentLogWindow.GetRealLineNum() + 1, info, this); - if (argLine != null) - { - StartTool(toolEntry.Cmd, argLine, toolEntry.Sysout, toolEntry.ColumnizerName, toolEntry.WorkingDir); - } - } - } - } - - [SupportedOSPlatform("windows")] - private void StartTool (string cmd, string args, bool sysoutPipe, string columnizerName, string workingDir) - { - if (string.IsNullOrEmpty(cmd)) - { - return; - } - - Process process = new(); - ProcessStartInfo startInfo = new(cmd, args); - if (!Util.IsNull(workingDir)) - { - startInfo.WorkingDirectory = workingDir; - } - - process.StartInfo = startInfo; - process.EnableRaisingEvents = true; - - if (sysoutPipe) - { - var columnizer = ColumnizerPicker.DecideColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - - _logger.Info(CultureInfo.InvariantCulture, "Starting external tool with sysout redirection: {0} {1}", cmd, args); - startInfo.UseShellExecute = false; - startInfo.RedirectStandardOutput = true; - //process.OutputDataReceived += pipe.DataReceivedEventHandler; - try - { - _ = process.Start(); - } - catch (Win32Exception e) - { - _logger.Error(e); - MessageBox.Show(e.Message); - return; - } - - SysoutPipe pipe = new(process.StandardOutput); - - var logWin = AddTempFileTab(pipe.FileName, - CurrentLogWindow.IsTempFile - ? CurrentLogWindow.TempTitleName - : Util.GetNameFromPath(CurrentLogWindow.FileName) + "->E"); - logWin.ForceColumnizer(columnizer); - - process.Exited += pipe.ProcessExitedEventHandler; - //process.BeginOutputReadLine(); - } - else - { - _logger.Info(CultureInfo.InvariantCulture, "Starting external tool: {0} {1}", cmd, args); - - try - { - startInfo.UseShellExecute = false; - _ = process.Start(); - } - catch (Exception e) - { - _logger.Error(e); - MessageBox.Show(e.Message); - } - } - } - - [SupportedOSPlatform("windows")] - private void CloseAllTabs () - { - IList closeList = []; - lock (_logWindowList) - { - foreach (DockContent content in dockPanel.Contents) - { - if (content is LogWindow.LogWindow window) - { - closeList.Add(window); - } - } - } - - foreach (var form in closeList) - { - form.Close(); - } - } - - //TODO Reimplement - private void SetTabColor (LogWindow.LogWindow logWindow, Color color) - { - //tabPage.BackLowColor = color; - //tabPage.BackLowColorDisabled = Color.FromArgb(255, - // Math.Max(0, color.R - 50), - // Math.Max(0, color.G - 50), - // Math.Max(0, color.B - 50) - // ); - } - - [SupportedOSPlatform("windows")] - private void LoadProject (string projectFileName, bool restoreLayout) - { - var projectData = ProjectPersister.LoadProjectData(projectFileName); - var hasLayoutData = projectData.TabLayoutXml != null; - - if (hasLayoutData && restoreLayout && _logWindowList.Count > 0) - { - ProjectLoadDlg dlg = new(); - if (DialogResult.Cancel != dlg.ShowDialog()) - { - switch (dlg.ProjectLoadResult) - { - case ProjectLoadDlgResult.IgnoreLayout: - hasLayoutData = false; - break; - case ProjectLoadDlgResult.CloseTabs: - CloseAllTabs(); - break; - case ProjectLoadDlgResult.NewWindow: - LogExpertProxy.NewWindow([projectFileName]); - return; - } - } - } - - if (projectData != null) - { - foreach (var fileName in projectData.MemberList) - { - if (hasLayoutData) - { - AddFileTabDeferred(fileName, false, null, true, null); - } - else - { - AddFileTab(fileName, false, null, true, null); - } - } - - if (hasLayoutData && restoreLayout) - { - // Re-creating tool (non-document) windows is needed because the DockPanel control would throw strange errors - DestroyToolWindows(); - InitToolWindows(); - RestoreLayout(projectData.TabLayoutXml); - } - } - } - - [SupportedOSPlatform("windows")] - private void ApplySelectedHighlightGroup () - { - var groupName = groupsComboBoxHighlightGroups.Text; - CurrentLogWindow?.SetCurrentHighlightGroup(groupName); - } - - [SupportedOSPlatform("windows")] - private void FillToolLauncherBar () - { - char[] labels = - [ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', - 'U', 'V', 'W', 'X', 'Y', 'Z' - ]; - toolsToolStripMenuItem.DropDownItems.Clear(); - toolsToolStripMenuItem.DropDownItems.Add(configureToolStripMenuItem); - toolsToolStripMenuItem.DropDownItems.Add(configureToolStripSeparator); - externalToolsToolStrip.Items.Clear(); - var num = 0; - externalToolsToolStrip.SuspendLayout(); - foreach (var tool in Preferences.ToolEntries) - { - if (tool.IsFavourite) - { - ToolStripButton button = new("" + labels[num % 26]) - { - Alignment = ToolStripItemAlignment.Left, - Tag = tool - }; - - SetToolIcon(tool, button); - externalToolsToolStrip.Items.Add(button); - } - - num++; - ToolStripMenuItem menuItem = new(tool.Name) - { - Tag = tool - }; - - SetToolIcon(tool, menuItem); - toolsToolStripMenuItem.DropDownItems.Add(menuItem); - } - - externalToolsToolStrip.ResumeLayout(); - - externalToolsToolStrip.Visible = num > 0; // do not show bar if no tool uses it - } - - private void RunGC () - { - _logger.Info($"Running GC. Used mem before: {GC.GetTotalMemory(false):N0}"); - GC.Collect(); - _logger.Info($"GC done. Used mem after: {GC.GetTotalMemory(true):N0}"); - } - - private void DumpGCInfo () - { - _logger.Info($"-------- GC info -----------\r\nUsed mem: {GC.GetTotalMemory(false):N0}"); - for (var i = 0; i < GC.MaxGeneration; ++i) - { - _logger.Info($"Generation {i} collect count: {GC.CollectionCount(i)}"); - } - - _logger.Info(CultureInfo.InvariantCulture, "----------------------------"); - } - - private void ThrowExceptionFx () - { - throw new Exception("This is a test exception thrown by an async delegate"); - } - - private void ThrowExceptionThreadFx () - { - throw new Exception("This is a test exception thrown by a background thread"); - } - - private string SaveLayout () - { - using MemoryStream memStream = new(2000); - using StreamReader r = new(memStream); - dockPanel.SaveAsXml(memStream, Encoding.UTF8, true); - - memStream.Seek(0, SeekOrigin.Begin); - var resultXml = r.ReadToEnd(); - - r.Close(); - - return resultXml; - } - - [SupportedOSPlatform("windows")] - private void RestoreLayout (string layoutXml) - { - using MemoryStream memStream = new(2000); - using StreamWriter w = new(memStream); - w.Write(layoutXml); - w.Flush(); - - memStream.Seek(0, SeekOrigin.Begin); - - dockPanel.LoadFromXml(memStream, DeserializeDockContent, true); - } - - [SupportedOSPlatform("windows")] - private IDockContent DeserializeDockContent (string persistString) - { - if (persistString.Equals(WindowTypes.BookmarkWindow.ToString(), StringComparison.Ordinal)) - { - return _bookmarkWindow; - } - - if (persistString.StartsWith(WindowTypes.LogWindow.ToString())) - { - var fileName = persistString[(WindowTypes.LogWindow.ToString().Length + 1)..]; - var win = FindWindowForFile(fileName); - if (win != null) - { - return win; - } - - _logger.Warn($"Layout data contains non-existing LogWindow for {fileName}"); - } - - return null; - } - - private void OnHighlightSettingsChanged () - { - HighlightSettingsChanged?.Invoke(this, EventArgs.Empty); - } - - #endregion -} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs deleted file mode 100644 index 3751f2eb..00000000 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindowPublic.cs +++ /dev/null @@ -1,364 +0,0 @@ -using System.Runtime.Versioning; -using System.Text; -using System.Text.RegularExpressions; - -using LogExpert.Core.Classes.Columnizer; -using LogExpert.Core.Classes.Filter; -using LogExpert.Core.Config; -using LogExpert.Core.Entities; -using LogExpert.Core.Interface; -using LogExpert.Dialogs; -using LogExpert.UI.Entities; -using LogExpert.UI.Extensions; - -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.UI.Controls.LogTabWindow; - -internal partial class LogTabWindow -{ - #region Public methods - - [SupportedOSPlatform("windows")] - public LogWindow.LogWindow AddTempFileTab (string fileName, string title) - { - return AddFileTab(fileName, true, title, false, null); - } - - [SupportedOSPlatform("windows")] - public LogWindow.LogWindow AddFilterTab (FilterPipe pipe, string title, ILogLineColumnizer preProcessColumnizer) - { - var logWin = AddFileTab(pipe.FileName, true, title, false, preProcessColumnizer); - if (pipe.FilterParams.SearchText.Length > 0) - { - ToolTip tip = new(components); - - tip.SetToolTip(logWin, - "Filter: \"" + pipe.FilterParams.SearchText + "\"" + - (pipe.FilterParams.IsInvert ? " (Invert match)" : "") + - (pipe.FilterParams.ColumnRestrict ? "\nColumn restrict" : "") - ); - - tip.AutomaticDelay = 10; - tip.AutoPopDelay = 5000; - var data = logWin.Tag as LogWindowData; - data.ToolTip = tip; - } - - return logWin; - } - - [SupportedOSPlatform("windows")] - public LogWindow.LogWindow AddFileTabDeferred (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer) - { - return AddFileTab(givenFileName, isTempFile, title, forcePersistenceLoading, preProcessColumnizer, true); - } - - [SupportedOSPlatform("windows")] - public LogWindow.LogWindow AddFileTab (string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer, bool doNotAddToDockPanel = false) - { - var logFileName = FindFilenameForSettings(givenFileName); - var win = FindWindowForFile(logFileName); - if (win != null) - { - if (!isTempFile) - { - AddToFileHistory(givenFileName); - } - - SelectTab(win); - return win; - } - - EncodingOptions encodingOptions = new(); - FillDefaultEncodingFromSettings(encodingOptions); - LogWindow.LogWindow logWindow = new(this, logFileName, isTempFile, forcePersistenceLoading, ConfigManager) - { - GivenFileName = givenFileName - }; - - if (preProcessColumnizer != null) - { - logWindow.ForceColumnizerForLoading(preProcessColumnizer); - } - - if (isTempFile) - { - logWindow.TempTitleName = title; - encodingOptions.Encoding = new UnicodeEncoding(false, false); - } - - AddLogWindow(logWindow, title, doNotAddToDockPanel); - if (!isTempFile) - { - AddToFileHistory(givenFileName); - } - - var data = logWindow.Tag as LogWindowData; - data.Color = _defaultTabColor; - SetTabColor(logWindow, _defaultTabColor); - //data.tabPage.BorderColor = this.defaultTabBorderColor; - if (!isTempFile) - { - foreach (var colorEntry in ConfigManager.Settings.FileColors) - { - if (colorEntry.FileName.ToUpperInvariant().Equals(logFileName.ToUpperInvariant(), StringComparison.Ordinal)) - { - data.Color = colorEntry.Color; - SetTabColor(logWindow, colorEntry.Color); - break; - } - } - } - - if (!isTempFile) - { - SetTooltipText(logWindow, logFileName); - } - - if (givenFileName.EndsWith(".lxp", StringComparison.Ordinal)) - { - logWindow.ForcedPersistenceFileName = givenFileName; - } - - // this.BeginInvoke(new LoadFileDelegate(logWindow.LoadFile), new object[] { logFileName, encoding }); - Task.Run(() => logWindow.LoadFile(logFileName, encodingOptions)); - return logWindow; - } - - [SupportedOSPlatform("windows")] - public LogWindow.LogWindow AddMultiFileTab (string[] fileNames) - { - if (fileNames.Length < 1) - { - return null; - } - - LogWindow.LogWindow logWindow = new(this, fileNames[^1], false, false, ConfigManager); - AddLogWindow(logWindow, fileNames[^1], false); - multiFileToolStripMenuItem.Checked = true; - multiFileEnabledStripMenuItem.Checked = true; - EncodingOptions encodingOptions = new(); - FillDefaultEncodingFromSettings(encodingOptions); - BeginInvoke(new LoadMultiFilesDelegate(logWindow.LoadFilesAsMulti), fileNames, encodingOptions); - AddToFileHistory(fileNames[0]); - return logWindow; - } - - [SupportedOSPlatform("windows")] - public void LoadFiles (string[] fileNames) - { - Invoke(new AddFileTabsDelegate(AddFileTabs), [fileNames]); - } - - [SupportedOSPlatform("windows")] - public void OpenSearchDialog () - { - if (CurrentLogWindow == null) - { - return; - } - - SearchDialog dlg = new(); - AddOwnedForm(dlg); - dlg.TopMost = TopMost; - SearchParams.HistoryList = ConfigManager.Settings.SearchHistoryList; - dlg.SearchParams = SearchParams; - var res = dlg.ShowDialog(); - if (res == DialogResult.OK && dlg.SearchParams != null && !string.IsNullOrWhiteSpace(dlg.SearchParams.SearchText)) - { - SearchParams = dlg.SearchParams; - SearchParams.IsFindNext = false; - CurrentLogWindow.StartSearch(); - } - } - - public ILogLineColumnizer GetColumnizerHistoryEntry (string fileName) - { - var entry = FindColumnizerHistoryEntry(fileName); - if (entry != null) - { - foreach (var columnizer in PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers) - { - if (columnizer.GetName().Equals(entry.ColumnizerName, StringComparison.Ordinal)) - { - return columnizer; - } - } - - ConfigManager.Settings.ColumnizerHistoryList.Remove(entry); // no valid name -> remove entry - } - - return null; - } - - public void SwitchTab (bool shiftPressed) - { - var index = dockPanel.Contents.IndexOf(dockPanel.ActiveContent); - if (shiftPressed) - { - index--; - if (index < 0) - { - index = dockPanel.Contents.Count - 1; - } - - if (index < 0) - { - return; - } - } - else - { - index++; - if (index >= dockPanel.Contents.Count) - { - index = 0; - } - } - - if (index < dockPanel.Contents.Count) - { - (dockPanel.Contents[index] as DockContent).Activate(); - } - } - - public void ScrollAllTabsToTimestamp (DateTime timestamp, LogWindow.LogWindow senderWindow) - { - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - if (logWindow != senderWindow) - { - if (logWindow.ScrollToTimestamp(timestamp, false, false)) - { - ShowLedPeak(logWindow); - } - } - } - } - } - - public ILogLineColumnizer FindColumnizerByFileMask (string fileName) - { - foreach (var entry in ConfigManager.Settings.Preferences.ColumnizerMaskList) - { - if (entry.Mask != null) - { - try - { - if (Regex.IsMatch(fileName, entry.Mask)) - { - var columnizer = ColumnizerPicker.FindColumnizerByName(entry.ColumnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - return columnizer; - } - } - catch (ArgumentException e) - { - _logger.Error(e, "RegEx-error while finding columnizer: "); - // occurs on invalid regex patterns - } - } - } - - return null; - } - - public HighlightGroup FindHighlightGroupByFileMask (string fileName) - { - foreach (var entry in ConfigManager.Settings.Preferences.HighlightMaskList) - { - if (entry.Mask != null) - { - try - { - if (Regex.IsMatch(fileName, entry.Mask)) - { - var group = FindHighlightGroup(entry.HighlightGroupName); - return group; - } - } - catch (ArgumentException e) - { - _logger.Error(e, "RegEx-error while finding columnizer: "); - // occurs on invalid regex patterns - } - } - } - - return null; - } - - public void SelectTab (ILogWindow logWindow) - { - logWindow.Activate(); - } - - [SupportedOSPlatform("windows")] - public void SetForeground () - { - NativeMethods.SetForegroundWindow(Handle); - if (WindowState == FormWindowState.Minimized) - { - if (_wasMaximized) - { - WindowState = FormWindowState.Maximized; - } - else - { - WindowState = FormWindowState.Normal; - } - } - } - - // called from LogWindow when follow tail was changed - [SupportedOSPlatform("windows")] - public void FollowTailChanged (LogWindow.LogWindow logWindow, bool isEnabled, bool offByTrigger) - { - if (logWindow.Tag is not LogWindowData data) - { - return; - } - - if (isEnabled) - { - data.TailState = 0; - } - else - { - data.TailState = offByTrigger ? 2 : 1; - } - - if (Preferences.ShowTailState) - { - var icon = GetIcon(data.DiffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); - } - } - - [SupportedOSPlatform("windows")] - public void NotifySettingsChanged (object sender, SettingsFlags flags) - { - if (sender != this) - { - NotifyWindowsForChangedPrefs(flags); - } - } - - public IList GetListOfOpenFiles () - { - IList list = []; - lock (_logWindowList) - { - foreach (var logWindow in _logWindowList) - { - list.Add(new WindowFileEntry(logWindow)); - } - } - - return list; - } - - #endregion -} \ No newline at end of file diff --git a/src/LogExpert.UI/LogExpert.UI.csproj b/src/LogExpert.UI/LogExpert.UI.csproj index 7e634730..eb79da96 100644 --- a/src/LogExpert.UI/LogExpert.UI.csproj +++ b/src/LogExpert.UI/LogExpert.UI.csproj @@ -24,11 +24,6 @@ - - - - - Always @@ -40,18 +35,6 @@ Form - - True - True - Resources.resx - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - From 6aacad73c4f92f8b1b31e3f206217d02f7225b09 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Sat, 21 Jun 2025 18:17:14 +0200 Subject: [PATCH 17/26] replace resources --- .../Controls/LogWindow/LogWindow.cs | 4 +-- src/LogExpert.UI/Dialogs/AboutBox.cs | 18 +++++------ .../Dialogs/LogTabWindow/LogTabWindow.cs | 2 +- .../LogTabWindow/LogTabWindow.designer.cs | 32 +++++++++---------- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index ec8f669d..eb565541 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -231,8 +231,8 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp dataGridView.EditModeMenuStrip = editModeContextMenuStrip; markEditModeToolStripMenuItem.Enabled = true; - _panelOpenButtonImage = Resources.Resources.Arrow_menu_open; - _panelCloseButtonImage = Resources.Resources.Arrow_menu_close; + _panelOpenButtonImage = Resources.Arrow_menu_open; + _panelCloseButtonImage = Resources.Arrow_menu_close; var settings = configManager.Settings; diff --git a/src/LogExpert.UI/Dialogs/AboutBox.cs b/src/LogExpert.UI/Dialogs/AboutBox.cs index 471d836f..e0f0d016 100644 --- a/src/LogExpert.UI/Dialogs/AboutBox.cs +++ b/src/LogExpert.UI/Dialogs/AboutBox.cs @@ -1,11 +1,11 @@ -using LogExpert.Core.Classes; - -using Newtonsoft.Json; - using System.Diagnostics; using System.Reflection; using System.Runtime.Versioning; +using LogExpert.Core.Classes; + +using Newtonsoft.Json; + namespace LogExpert.UI.Dialogs; [SupportedOSPlatform("windows")] @@ -19,7 +19,7 @@ internal partial class AboutBox : Form #region cTor - public AboutBox() + public AboutBox () { InitializeComponent(); @@ -38,7 +38,7 @@ public AboutBox() //Name, Version, License, Download, Source - private void LoadUsedComponents() + private void LoadUsedComponents () { var json = File.ReadAllText($"{Application.StartupPath}files\\json\\usedComponents.json"); var usedComponents = JsonConvert.DeserializeObject(json); @@ -47,9 +47,9 @@ private void LoadUsedComponents() } - private void LoadResources() + private void LoadResources () { - logoPictureBox.Image = Resources.Resources.LogLover; + logoPictureBox.Image = Resources.LogLover; } #endregion @@ -139,7 +139,7 @@ public string AssemblyCopyright #region Events handler - private void OnLinkLabelURLClicked(object sender, LinkLabelLinkClickedEventArgs e) + private void OnLinkLabelURLClicked (object sender, LinkLabelLinkClickedEventArgs e) { var target = string.Empty; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index 2eb2d0f7..d6000dcc 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -168,7 +168,7 @@ public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNu // get a list of resource names from the manifest var resNames = a.GetManifestResourceNames(); - Bitmap bmp = Resources.Resources.Deceased; + Bitmap bmp = Resources.Deceased; _deadIcon = Icon.FromHandle(bmp.GetHicon()); bmp.Dispose(); Closing += OnLogTabWindowClosing; diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs index 6dc8e85e..2b322b27 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs @@ -240,7 +240,7 @@ private void InitializeComponent() // openToolStripMenuItem // openToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - openToolStripMenuItem.Image = LogExpert.Resources.Resources.File_open; + openToolStripMenuItem.Image = LogExpert.Resources.File_open; openToolStripMenuItem.Name = "openToolStripMenuItem"; openToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.O; openToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -258,7 +258,7 @@ private void InitializeComponent() // // closeFileToolStripMenuItem // - closeFileToolStripMenuItem.Image = LogExpert.Resources.Resources.Close; + closeFileToolStripMenuItem.Image = LogExpert.Resources.Close; closeFileToolStripMenuItem.Name = "closeFileToolStripMenuItem"; closeFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F4; closeFileToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -267,7 +267,7 @@ private void InitializeComponent() // // reloadToolStripMenuItem // - reloadToolStripMenuItem.Image = LogExpert.Resources.Resources.Restart_alt; + reloadToolStripMenuItem.Image = LogExpert.Resources.Restart_alt; reloadToolStripMenuItem.Name = "reloadToolStripMenuItem"; reloadToolStripMenuItem.ShortcutKeys = Keys.F5; reloadToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -359,7 +359,7 @@ private void InitializeComponent() // // exitToolStripMenuItem // - exitToolStripMenuItem.Image = LogExpert.Resources.Resources.Exit; + exitToolStripMenuItem.Image = LogExpert.Resources.Exit; exitToolStripMenuItem.Name = "exitToolStripMenuItem"; exitToolStripMenuItem.ShortcutKeys = Keys.Alt | Keys.F4; exitToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -391,7 +391,7 @@ private void InitializeComponent() // // filterToolStripMenuItem // - filterToolStripMenuItem.Image = LogExpert.Resources.Resources.Filter; + filterToolStripMenuItem.Image = LogExpert.Resources.Filter; filterToolStripMenuItem.Name = "filterToolStripMenuItem"; filterToolStripMenuItem.ShortcutKeys = Keys.F4; filterToolStripMenuItem.Size = new System.Drawing.Size(189, 30); @@ -409,7 +409,7 @@ private void InitializeComponent() // toggleBookmarkToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; toggleBookmarkToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toggleBookmarkToolStripMenuItem.Image = LogExpert.Resources.Resources.Bookmark_add; + toggleBookmarkToolStripMenuItem.Image = LogExpert.Resources.Bookmark_add; toggleBookmarkToolStripMenuItem.Name = "toggleBookmarkToolStripMenuItem"; toggleBookmarkToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F2; toggleBookmarkToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -420,7 +420,7 @@ private void InitializeComponent() // jumpToNextToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; jumpToNextToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - jumpToNextToolStripMenuItem.Image = LogExpert.Resources.Resources.ArrowDown; + jumpToNextToolStripMenuItem.Image = LogExpert.Resources.ArrowDown; jumpToNextToolStripMenuItem.Name = "jumpToNextToolStripMenuItem"; jumpToNextToolStripMenuItem.ShortcutKeys = Keys.F2; jumpToNextToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -431,7 +431,7 @@ private void InitializeComponent() // jumpToPrevToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; jumpToPrevToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - jumpToPrevToolStripMenuItem.Image = LogExpert.Resources.Resources.ArrowUp; + jumpToPrevToolStripMenuItem.Image = LogExpert.Resources.ArrowUp; jumpToPrevToolStripMenuItem.Name = "jumpToPrevToolStripMenuItem"; jumpToPrevToolStripMenuItem.ShortcutKeys = Keys.Shift | Keys.F2; jumpToPrevToolStripMenuItem.Size = new System.Drawing.Size(253, 30); @@ -585,7 +585,7 @@ private void InitializeComponent() // // settingsToolStripMenuItem // - settingsToolStripMenuItem.Image = LogExpert.Resources.Resources.Settings; + settingsToolStripMenuItem.Image = LogExpert.Resources.Settings; settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; settingsToolStripMenuItem.Size = new System.Drawing.Size(224, 30); settingsToolStripMenuItem.Text = "Settings..."; @@ -914,7 +914,7 @@ private void InitializeComponent() // toolStripButtonOpen // toolStripButtonOpen.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonOpen.Image = LogExpert.Resources.Resources.File_open; + toolStripButtonOpen.Image = LogExpert.Resources.File_open; toolStripButtonOpen.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonOpen.Name = "toolStripButtonOpen"; toolStripButtonOpen.Size = new System.Drawing.Size(28, 28); @@ -930,7 +930,7 @@ private void InitializeComponent() // toolStripButtonSearch // toolStripButtonSearch.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonSearch.Image = LogExpert.Resources.Resources.Search; + toolStripButtonSearch.Image = LogExpert.Resources.Search; toolStripButtonSearch.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonSearch.Name = "toolStripButtonSearch"; toolStripButtonSearch.Size = new System.Drawing.Size(28, 28); @@ -941,7 +941,7 @@ private void InitializeComponent() // toolStripButtonFilter // toolStripButtonFilter.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonFilter.Image = LogExpert.Resources.Resources.Filter; + toolStripButtonFilter.Image = LogExpert.Resources.Filter; toolStripButtonFilter.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonFilter.Name = "toolStripButtonFilter"; toolStripButtonFilter.Size = new System.Drawing.Size(28, 28); @@ -958,7 +958,7 @@ private void InitializeComponent() // toolStripButtonBookmark // toolStripButtonBookmark.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonBookmark.Image = LogExpert.Resources.Resources.Bookmark_add; + toolStripButtonBookmark.Image = LogExpert.Resources.Bookmark_add; toolStripButtonBookmark.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonBookmark.Name = "toolStripButtonBookmark"; toolStripButtonBookmark.Size = new System.Drawing.Size(28, 28); @@ -969,7 +969,7 @@ private void InitializeComponent() // toolStripButtonUp // toolStripButtonUp.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonUp.Image = LogExpert.Resources.Resources.ArrowUp; + toolStripButtonUp.Image = LogExpert.Resources.ArrowUp; toolStripButtonUp.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonUp.Name = "toolStripButtonUp"; toolStripButtonUp.Size = new System.Drawing.Size(28, 28); @@ -980,7 +980,7 @@ private void InitializeComponent() // toolStripButtonDown // toolStripButtonDown.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonDown.Image = LogExpert.Resources.Resources.ArrowDown; + toolStripButtonDown.Image = LogExpert.Resources.ArrowDown; toolStripButtonDown.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonDown.Name = "toolStripButtonDown"; toolStripButtonDown.Size = new System.Drawing.Size(28, 28); @@ -997,7 +997,7 @@ private void InitializeComponent() // toolStripButtonBubbles.CheckOnClick = true; toolStripButtonBubbles.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonBubbles.Image = LogExpert.Resources.Resources.bookmark_bubbles; + toolStripButtonBubbles.Image = LogExpert.Resources.bookmark_bubbles; toolStripButtonBubbles.ImageAlign = System.Drawing.ContentAlignment.BottomCenter; toolStripButtonBubbles.ImageTransparentColor = System.Drawing.Color.Magenta; toolStripButtonBubbles.Name = "toolStripButtonBubbles"; From 8ec80fb41f7852efd5e7db5daa6d6f3f4bfae6af Mon Sep 17 00:00:00 2001 From: Hirogen Date: Sat, 21 Jun 2025 18:26:00 +0200 Subject: [PATCH 18/26] review comments --- .../Controls/LogWindow/LogWindow.cs | 19 ++++++++++--------- src/LogExpert.UI/Dialogs/BookmarkWindow.cs | 5 ++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index eb565541..f757d24f 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -985,11 +985,12 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti { if (_bookmarkProvider.IsBookmarkAtLine(lineNum)) { - Rectangle r;// = new(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); - r = e.CellBounds; - r.Inflate(-2, -2); + //This was the OLD rect, left for future Information + //(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); + var rect = e.CellBounds; + rect.Inflate(-2, -2); using var brush = new SolidBrush(BookmarkColor); - e.Graphics.FillRectangle(brush, r); + e.Graphics.FillRectangle(brush, rect); var bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); @@ -1003,7 +1004,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); using var font = new Font("Verdana", Preferences.FontSize, FontStyle.Bold); - e.Graphics.DrawString("!", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); + e.Graphics.DrawString("!", font, brush2, new RectangleF(rect.Left, rect.Top, rect.Width, rect.Height), format); } } } @@ -1018,7 +1019,7 @@ private void OnFilterGridViewCellValueNeeded (object sender, DataGridViewCellVal { if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) { - e.Value = ""; + e.Value = string.Empty; return; } @@ -1118,7 +1119,7 @@ private void OnFilterGridViewKeyDown (object sender, KeyEventArgs e) break; } case Keys.Tab when e.Modifiers == Keys.None: - dataGridView.Focus(); + _ = dataGridView.Focus(); e.Handled = true; break; } @@ -1131,7 +1132,7 @@ private void OnDataGridViewKeyDown (object sender, KeyEventArgs e) { case Keys.Tab when e.Modifiers == Keys.None: { - filterGridView.Focus(); + _ = filterGridView.Focus(); e.Handled = true; break; } @@ -1161,7 +1162,7 @@ private void OnDataGridViewCellContentDoubleClick (object sender, DataGridViewCe { if (dataGridView.CurrentCell != null) { - dataGridView.BeginEdit(false); + _ = dataGridView.BeginEdit(false); } } diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs index 5e6bad97..a78c6c49 100644 --- a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -204,8 +204,7 @@ protected override void OnPaint (PaintEventArgs e) { if (!splitContainer1.Visible) { - var r = ClientRectangle; - e.Graphics.FillRectangle(SystemBrushes.ControlLight, r); + e.Graphics.FillRectangle(SystemBrushes.ControlLight, ClientRectangle); StringFormat sf = new() { @@ -213,7 +212,7 @@ protected override void OnPaint (PaintEventArgs e) LineAlignment = StringAlignment.Center }; - e.Graphics.DrawString("No bookmarks in current file", SystemFonts.DialogFont, SystemBrushes.WindowText, r, sf); + e.Graphics.DrawString("No bookmarks in current file", SystemFonts.DialogFont, SystemBrushes.WindowText, ClientRectangle, sf); } else { From 669b7847b4eda328a0e82ce2c4c9d1792e359732 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Sat, 21 Jun 2025 18:32:20 +0200 Subject: [PATCH 19/26] update usedComponents --- src/usedPackages.json | Bin 19146 -> 13280 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/usedPackages.json b/src/usedPackages.json index 0b67f10b2fc9b9957a774a5c81d82743691baf4b..291e04bf08c1763d7c827cedc6715aab14ff5122 100644 GIT binary patch delta 106 zcmX>#mGMFPhAHfuOSopRPF9c>+5AiPnJ~XQgB3#z5V|vDGL$f6Z2oQ7$c8RB`L|*F uWCtm^$@{eUHhWnLu}uzgieNOI>?oW(xxkTcvy5{S3l}c~7eg!qhy(x?H69uO delta 1122 zcmb`GOKTHR6vxkKUTsa9H^dk+k%CI&JldwQg4md98lth9EJSpXPCIF_Z9*C`8^P>c zh#*Jzx^XRxU%*8{y0YNj$5(J8UHPBM6DjQ`TxK};-gEBxopb;9XLbLb@ae6SzuW!% zetgRK?Rzl}RB4OWNum{MVAjO9N>54Wd)@@Egu`RA*qbGVB);oim+O5m z4W3&aU(#_xgLX-#!G7nIFWwA`FWO0=i zz*VLVtcvixk4|J^WzdBtZSW75964?`Vlf7zL1A*h_#chX%8@5F*svdqRJ>;)} zqM^tiZ7fFS%*8+%Nm@uJ(M?n42w!6%1i73~3g!j$(!Jt~E>EF~eTlYFmSz>Xi@9z^ zn~~c<(CHZ Date: Sun, 22 Jun 2025 09:19:33 +0200 Subject: [PATCH 20/26] build not working --- src/LogExpert.Core/Config/Settings.cs | 2 +- src/LogExpert.Core/Entities/SearchParams.cs | 2 +- .../Controls/LogWindow/LogWindow.cs | 47 +++++++------------ .../Dialogs/LogTabWindow/LogTabWindow.cs | 1 + src/LogExpert.UI/Dialogs/SearchDialog.cs | 2 +- 5 files changed, 21 insertions(+), 33 deletions(-) diff --git a/src/LogExpert.Core/Config/Settings.cs b/src/LogExpert.Core/Config/Settings.cs index 51375e41..7ba088cf 100644 --- a/src/LogExpert.Core/Config/Settings.cs +++ b/src/LogExpert.Core/Config/Settings.cs @@ -1,7 +1,7 @@ using System.Drawing; using LogExpert.Core.Classes.Filter; -using LogExpert.Core.Entities; +using LogExpert.Entities; namespace LogExpert.Core.Config; diff --git a/src/LogExpert.Core/Entities/SearchParams.cs b/src/LogExpert.Core/Entities/SearchParams.cs index ed4b2748..2a5167db 100644 --- a/src/LogExpert.Core/Entities/SearchParams.cs +++ b/src/LogExpert.Core/Entities/SearchParams.cs @@ -1,4 +1,4 @@ -namespace LogExpert.Core.Entities; +namespace LogExpert.Entities; [Serializable] public class SearchParams diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index f757d24f..82f6f7ba 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -4,7 +4,6 @@ using System.Text; using System.Text.RegularExpressions; -using LogExpert.Classes.Filter; using LogExpert.Core.Callback; using LogExpert.Core.Classes; using LogExpert.Core.Classes.Bookmark; @@ -18,6 +17,7 @@ using LogExpert.Core.EventArguments; using LogExpert.Core.Interface; using LogExpert.Dialogs; +using LogExpert.Entities; using LogExpert.Extensions; using LogExpert.UI.Dialogs; using LogExpert.UI.Entities; @@ -3738,18 +3738,18 @@ private void SyncTimestampDisplayWorker () while (!_shouldTimestampDisplaySyncingCancel) { - _timeShiftSyncWakeupEvent.WaitOne(); + _ = _timeShiftSyncWakeupEvent.WaitOne(); if (_shouldTimestampDisplaySyncingCancel) { return; } - _timeShiftSyncWakeupEvent.Reset(); + _ = _timeShiftSyncWakeupEvent.Reset(); while (!_shouldTimestampDisplaySyncingCancel) { var signaled = _timeShiftSyncTimerEvent.WaitOne(WAIT_TIME, true); - _timeShiftSyncTimerEvent.Reset(); + _ = _timeShiftSyncTimerEvent.Reset(); if (!signaled) { break; @@ -3791,17 +3791,11 @@ private void SyncTimestampDisplayWorker () refLine = row2; var timeStamp2 = GetTimestampForLine(ref refLine, false); //TimeSpan span = TimeSpan.FromTicks(timeStamp2.Ticks - timeStamp1.Ticks); - DateTime diff; - if (timeStamp1.Ticks > timeStamp2.Ticks) - { - diff = new DateTime(timeStamp1.Ticks - timeStamp2.Ticks); - } - else - { - diff = new DateTime(timeStamp2.Ticks - timeStamp1.Ticks); - } + var diff = timeStamp1.Ticks > timeStamp2.Ticks + ? new DateTime(timeStamp1.Ticks - timeStamp2.Ticks) + : new DateTime(timeStamp2.Ticks - timeStamp1.Ticks); - StatusLineText("Time diff is " + diff.ToString("HH:mm:ss.fff")); + StatusLineText($"Time diff is {diff:HH:mm:ss.fff}"); } else { @@ -3830,14 +3824,9 @@ private void SyncFilterGridPos () } } - if (filterGridView.Rows.GetRowCount(DataGridViewElementStates.None) > 0) // exception no rows - { - filterGridView.CurrentCell = filterGridView.Rows[index].Cells[0]; - } - else - { - filterGridView.CurrentCell = null; - } + filterGridView.CurrentCell = filterGridView.Rows.GetRowCount(DataGridViewElementStates.None) > 0 + ? filterGridView.Rows[index].Cells[0] + : null; } } catch (Exception e) @@ -4008,7 +3997,7 @@ private void SelectLine (int line, bool triggerSyncCall, bool shouldScroll) if (shouldScroll) { dataGridView.CurrentCell = dataGridView.Rows[line].Cells[0]; - dataGridView.Focus(); + _ = dataGridView.Focus(); } } catch (ArgumentOutOfRangeException e) @@ -4027,7 +4016,7 @@ private void StartEditMode () { if (!dataGridView.CurrentCell.ReadOnly) { - dataGridView.BeginEdit(false); + _ = dataGridView.BeginEdit(false); if (dataGridView.EditingControl != null) { if (dataGridView.EditingControl is LogCellEditingControl editControl) @@ -4235,7 +4224,6 @@ private void FilterSearch () if (filterComboBox.Text.Length == 0) { _filterParams.SearchText = string.Empty; - _filterParams.LowerSearchText = string.Empty; _filterParams.IsRangeSearch = false; ClearFilterList(); filterSearchButton.Image = null; @@ -4253,8 +4241,7 @@ private async void FilterSearch (string text) FireCancelHandlers(); // make sure that there's no other filter running (maybe from filter restore) _filterParams.SearchText = text; - _filterParams.LowerSearchText = text.ToLowerInvariant(); - ConfigManager.Settings.FilterHistoryList.Remove(text); + _ = ConfigManager.Settings.FilterHistoryList.Remove(text); ConfigManager.Settings.FilterHistoryList.Insert(0, text); var maxHistory = ConfigManager.Settings.Preferences.MaximumFilterEntries; @@ -4266,7 +4253,7 @@ private async void FilterSearch (string text) filterComboBox.Items.Clear(); foreach (var item in ConfigManager.Settings.FilterHistoryList) { - filterComboBox.Items.Add(item); + _ = filterComboBox.Items.Add(item); } filterComboBox.Text = text; @@ -4275,7 +4262,7 @@ private async void FilterSearch (string text) _filterParams.RangeSearchText = filterRangeComboBox.Text; if (_filterParams.IsRangeSearch) { - ConfigManager.Settings.FilterRangeHistoryList.Remove(filterRangeComboBox.Text); + _ = ConfigManager.Settings.FilterRangeHistoryList.Remove(filterRangeComboBox.Text); ConfigManager.Settings.FilterRangeHistoryList.Insert(0, filterRangeComboBox.Text); if (ConfigManager.Settings.FilterRangeHistoryList.Count > maxHistory) { @@ -4285,7 +4272,7 @@ private async void FilterSearch (string text) filterRangeComboBox.Items.Clear(); foreach (var item in ConfigManager.Settings.FilterRangeHistoryList) { - filterRangeComboBox.Items.Add(item); + _ = filterRangeComboBox.Items.Add(item); } } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs index d6000dcc..b27cd020 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -17,6 +17,7 @@ using LogExpert.Core.EventArguments; using LogExpert.Core.Interface; using LogExpert.Dialogs; +using LogExpert.Entities; using LogExpert.PluginRegistry.FileSystem; using LogExpert.UI.Dialogs; using LogExpert.UI.Entities; diff --git a/src/LogExpert.UI/Dialogs/SearchDialog.cs b/src/LogExpert.UI/Dialogs/SearchDialog.cs index 9ae87f17..a12294ed 100644 --- a/src/LogExpert.UI/Dialogs/SearchDialog.cs +++ b/src/LogExpert.UI/Dialogs/SearchDialog.cs @@ -1,7 +1,7 @@ using System.Runtime.Versioning; using System.Text.RegularExpressions; -using LogExpert.Core.Entities; +using LogExpert.Entities; using LogExpert.UI.Dialogs; namespace LogExpert.Dialogs; From 2d3c361f92a0ad7c30c914deb8485c6a27f748e4 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 23 Jun 2025 12:03:15 +0200 Subject: [PATCH 21/26] optimizations for debugging --- .../Classes/Log/LogfileReader.cs | 6 +- src/LogExpert.Core/Classes/SpreadEntry.cs | 4 +- .../Controls/BufferedDataGridView.cs | 4 +- .../Controls/LogWindow/LogWindow.cs | 158 ++++++------------ .../Controls/LogWindow/PatternWindow.cs | 4 +- .../LogWindow/TimeSpreadCalculator.cs | 128 ++++++-------- .../LogWindow/TimeSpreadigControl.Designer.cs | 3 +- .../Controls/LogWindow/TimeSpreadigControl.cs | 33 ++-- .../Dialogs/LogTabWindow/HighlightDialog.cs | 13 +- src/LogExpert.UI/Entities/PaintHelper.cs | 106 +++++++++--- 10 files changed, 220 insertions(+), 239 deletions(-) diff --git a/src/LogExpert.Core/Classes/Log/LogfileReader.cs b/src/LogExpert.Core/Classes/Log/LogfileReader.cs index 445ffd1e..d7f887a4 100644 --- a/src/LogExpert.Core/Classes/Log/LogfileReader.cs +++ b/src/LogExpert.Core/Classes/Log/LogfileReader.cs @@ -1785,13 +1785,13 @@ private void DumpBufferInfos (LogBuffer buffer) #endregion - public void Dispose() + public void Dispose () { Dispose(true); GC.SuppressFinalize(this); // Suppress finalization (not needed but best practice) } - protected virtual void Dispose(bool disposing) + protected virtual void Dispose (bool disposing) { if (!_disposed) { @@ -1808,7 +1808,7 @@ protected virtual void Dispose(bool disposing) //TODO: Seems that this can be deleted. Need to verify. ~LogfileReader () { - Dispose (false); + Dispose(false); } protected virtual void OnFileSizeChanged (LogEventArgs e) diff --git a/src/LogExpert.Core/Classes/SpreadEntry.cs b/src/LogExpert.Core/Classes/SpreadEntry.cs index 090c4847..c6fce9d8 100644 --- a/src/LogExpert.Core/Classes/SpreadEntry.cs +++ b/src/LogExpert.Core/Classes/SpreadEntry.cs @@ -1,4 +1,4 @@ -namespace LogExpert.Core.Classes; +namespace LogExpert.Core.Classes; public class SpreadEntry { @@ -16,7 +16,7 @@ public class SpreadEntry #region cTor - public SpreadEntry(int lineNum, int diff, DateTime timestamp) + public SpreadEntry (int lineNum, int diff, DateTime timestamp) { LineNum = lineNum; Diff = diff; diff --git a/src/LogExpert.UI/Controls/BufferedDataGridView.cs b/src/LogExpert.UI/Controls/BufferedDataGridView.cs index 7597b2e2..563cacdd 100644 --- a/src/LogExpert.UI/Controls/BufferedDataGridView.cs +++ b/src/LogExpert.UI/Controls/BufferedDataGridView.cs @@ -291,7 +291,7 @@ private void OnControlKeyDown (object sender, KeyEventArgs e) { if (EditingControl is LogCellEditingControl editControl) { - editControl.EditingControlDataGridView.EndEdit(); + _ = editControl.EditingControlDataGridView.EndEdit(); var line = editControl.EditingControlDataGridView.CurrentCellAddress.Y; if (e.KeyCode == Keys.Up) { @@ -313,7 +313,7 @@ private void OnControlKeyDown (object sender, KeyEventArgs e) var scrollIndex = editControl.EditingControlDataGridView.HorizontalScrollingOffset; var selStart = editControl.SelectionStart; editControl.EditingControlDataGridView.CurrentCell = editControl.EditingControlDataGridView.Rows[line].Cells[col]; - editControl.EditingControlDataGridView.BeginEdit(false); + _ = editControl.EditingControlDataGridView.BeginEdit(false); editControl.SelectionStart = selStart; editControl.ScrollToCaret(); editControl.EditingControlDataGridView.HorizontalScrollingOffset = scrollIndex; diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index 82f6f7ba..e41c1b17 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -155,7 +155,7 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp CreateDefaultViewStyle(); - columnNamesLabel.Text = ""; // no filtering on columns by default + columnNamesLabel.Text = string.Empty; // no filtering on columns by default _parentLogTabWin = parent; IsTempFile = isTempFile; @@ -202,7 +202,7 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp _filterParams = new FilterParams(); foreach (var item in configManager.Settings.FilterHistoryList) { - filterComboBox.Items.Add(item); + _ = filterComboBox.Items.Add(item); } filterComboBox.DropDownHeight = filterComboBox.ItemHeight * configManager.Settings.Preferences.MaximumFilterEntriesDisplayed; @@ -264,8 +264,6 @@ public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTemp ResumeLayout(); } - - #endregion #region Delegates @@ -800,7 +798,7 @@ private void OnFileSizeChanged (object sender, LogEventArgs e) lock (_logEventArgsList) { _logEventArgsList.Add(e); - _logEventArgsEvent.Set(); + _ = _logEventArgsEvent.Set(); } } @@ -819,7 +817,7 @@ private void OnDataGridViewCellValueNeeded (object sender, DataGridViewCellValue for (var i = startCount; i < CurrentColumnizer.GetColumnCount(); i++) { var colName = CurrentColumnizer.GetColumnNames()[i]; - dataGridView.Columns.Add(PaintHelper.CreateTitleColumn(colName)); + _ = dataGridView.Columns.Add(PaintHelper.CreateTitleColumn(colName)); } } } @@ -853,7 +851,7 @@ private void OnDataGridViewCellValuePushed (object sender, DataGridViewCellValue var index = span.LastIndexOf('.'); if (index > 0) { - span = span.Substring(0, index + 4); + span = span[..(index + 4)]; } SetTimeshiftValue(span); @@ -947,8 +945,6 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti return; } - - var lineNum = _filterResultList[e.RowIndex]; var line = _logFileReader.GetLogLineWithWait(lineNum).Result; @@ -956,18 +952,19 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti { var entry = FindFirstNoWordMatchHilightEntry(line); e.Graphics.SetClip(e.CellBounds); + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { + if (e.CellStyle.SelectionForeColor != Color.White) + { + e.CellStyle.SelectionForeColor = PaintHelper.GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); + } + using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); } else { - // paint direct filter hits with different bg color - //if (this.filterParams.SpreadEnabled && this.filterHitList.Contains(lineNum)) - //{ - // bgColor = Color.FromArgb(255, 220, 220, 220); - //} e.CellStyle.BackColor = PaintHelper.GetBackColorFromHighlightEntry(entry); e.PaintBackground(e.ClipBounds, false); } @@ -978,7 +975,7 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti } else { - PaintCell(e, filterGridView, false, entry); + PaintCell(e, entry); } if (e.ColumnIndex == 0) @@ -2037,21 +2034,12 @@ private void OnFilterListBoxDrawItem (object sender, DrawItemEventArgs e) var filterParams = (FilterParams)filterListBox.Items[e.Index]; Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - Brush brush; - - if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) - { - brush = new SolidBrush(filterListBox.BackColor); - } - else - { - brush = new SolidBrush(filterParams.Color); - } + using var brush = (e.State & DrawItemState.Selected) == DrawItemState.Selected + ? new SolidBrush(filterListBox.BackColor) + : new SolidBrush(filterParams.Color); - e.Graphics.DrawString(filterParams.SearchText, e.Font, brush, - new PointF(rectangle.Left, rectangle.Top)); + e.Graphics.DrawString(filterParams.SearchText, e.Font, brush, new PointF(rectangle.Left, rectangle.Top)); e.DrawFocusRectangle(); - brush.Dispose(); } } @@ -2203,7 +2191,7 @@ private void OnColumnComboBoxKeyDown (object sender, KeyEventArgs e) if (e.KeyCode == Keys.Enter) { SelectColumn(); - dataGridView.Focus(); + _ = dataGridView.Focus(); } } @@ -2259,10 +2247,10 @@ private void OnLogWindowEnter (object sender, EventArgs e) [SupportedOSPlatform("windows")] private void OnDataGridViewRowUnshared (object sender, DataGridViewRowEventArgs e) { - if (_logger.IsTraceEnabled) - { - _logger.Trace($"Row unshared line {e.Row.Cells[1].Value}"); - } + //if (_logger.IsTraceEnabled) + //{ + // _logger.Trace($"Row unshared line {e.Row.Cells[1].Value}"); + //} } #endregion @@ -2281,6 +2269,16 @@ private void MeasureItem (object sender, MeasureItemEventArgs e) #region Private Methods + [SupportedOSPlatform("windows")] + private void CreateDefaultViewStyle () + { + + dataGridView.DefaultCellStyle = PaintHelper.GetDataGridViewCellStyle(); + filterGridView.DefaultCellStyle = PaintHelper.GetDataGridViewCellStyle(); + dataGridView.RowsDefaultCellStyle = PaintHelper.GetDataGridDefaultRowStyle(); + filterGridView.RowsDefaultCellStyle = PaintHelper.GetDataGridDefaultRowStyle(); + } + [SupportedOSPlatform("windows")] private void RegisterLogFileReaderEvents () { @@ -2306,56 +2304,6 @@ private void UnRegisterLogFileReaderEvents () } } - [SupportedOSPlatform("windows")] - private void CreateDefaultViewStyle () - { - DataGridViewCellStyle dataGridViewCellStyleMainGrid = new(); - DataGridViewCellStyle dataGridViewCellStyleFilterGrid = new(); - - dataGridViewCellStyleMainGrid.Alignment = DataGridViewContentAlignment.MiddleLeft; - dataGridViewCellStyleMainGrid.BackColor = SystemColors.Window; - dataGridViewCellStyleMainGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - dataGridViewCellStyleMainGrid.ForeColor = SystemColors.ControlText; - dataGridViewCellStyleMainGrid.SelectionBackColor = SystemColors.Highlight; - //dataGridViewCellStyleMainGrid.SelectionForeColor = SystemColors.HighlightText; - - var highlightColor = SystemColors.Highlight; - //Color is smaller than 128, means its darker - var isSelectionBackColorDark = (highlightColor.R * 0.2126) + (highlightColor.G * 0.7152) + (highlightColor.B * 0.0722) < 255 / 2; - - if (isSelectionBackColorDark) - { - dataGridViewCellStyleMainGrid.SelectionForeColor = Color.White; - } - else - { - dataGridViewCellStyleMainGrid.SelectionForeColor = Color.Black; - - } - - dataGridViewCellStyleMainGrid.WrapMode = DataGridViewTriState.False; - dataGridView.DefaultCellStyle = dataGridViewCellStyleMainGrid; - - dataGridViewCellStyleFilterGrid.Alignment = DataGridViewContentAlignment.MiddleLeft; - dataGridViewCellStyleFilterGrid.BackColor = SystemColors.Window; - dataGridViewCellStyleFilterGrid.Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - dataGridViewCellStyleFilterGrid.ForeColor = SystemColors.ControlText; - dataGridViewCellStyleFilterGrid.SelectionBackColor = SystemColors.Highlight; - //dataGridViewCellStyleFilterGrid.SelectionForeColor = SystemColors.HighlightText; - - if (isSelectionBackColorDark) - { - dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.White; - } - else - { - dataGridViewCellStyleFilterGrid.SelectionForeColor = Color.Black; - } - - dataGridViewCellStyleFilterGrid.WrapMode = DataGridViewTriState.False; - filterGridView.DefaultCellStyle = dataGridViewCellStyleFilterGrid; - } - [SupportedOSPlatform("windows")] private bool LoadPersistenceOptions () { @@ -3083,7 +3031,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) var matchingList = FindMatchingHilightEntries(line); LaunchHighlightPlugins(matchingList, i); - GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); + GetHighlightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); if (setBookmark) { SetBookmarkFx fx = SetBookmarkFromTrigger; @@ -3131,7 +3079,7 @@ private void CheckFilterAndHighlight (LogEventArgs e) { var matchingList = FindMatchingHilightEntries(line); LaunchHighlightPlugins(matchingList, i); - GetHilightActions(matchingList, out suppressLed, out stopTail, out setBookmark, + GetHighlightActions(matchingList, out suppressLed, out stopTail, out setBookmark, out bookmarkComment); if (setBookmark) { @@ -3380,12 +3328,12 @@ private void AutoResizeColumns (BufferedDataGridView gridView) } } - private void PaintCell (DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) + private void PaintCell (DataGridViewCellPaintingEventArgs e, HighlightEntry groundEntry) { - PaintHighlightedCell(e, gridView, noBackgroundFill, groundEntry); + PaintHighlightedCell(e, groundEntry); } - private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) + private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, HighlightEntry groundEntry) { var column = e.Value as IColumn; @@ -3454,14 +3402,13 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered var wordPos = valBounds.Location; Size proposedSize = new(valBounds.Width, valBounds.Height); - var r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); e.Graphics.SetClip(e.CellBounds); foreach (var matchEntry in matchList) { var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? BoldFont : NormalFont; - Brush bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty + using var bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty ? new SolidBrush(matchEntry.HighlightEntry.BackgroundColor) : null; @@ -3471,18 +3418,16 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Buffered Rectangle wordRect = new(wordPos, wordSize); var foreColor = matchEntry.HighlightEntry.ForegroundColor; - if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) + if (bgBrush != null && !matchEntry.HighlightEntry.NoBackground) { e.Graphics.FillRectangle(bgBrush, wordRect); } } TextRenderer.DrawText(e.Graphics, matchWord, font, wordRect, foreColor, flags); - wordPos.Offset(wordSize.Width, 0); - bgBrush?.Dispose(); } } @@ -3664,7 +3609,7 @@ private void GetHighlightEntryMatches (ITextValue line, IList hi } } - private void GetHilightActions (IList matchingList, out bool noLed, out bool stopTail, out bool setBookmark, out string bookmarkComment) + private void GetHighlightActions (IList matchingList, out bool noLed, out bool stopTail, out bool setBookmark, out string bookmarkComment) { noLed = stopTail = setBookmark = false; bookmarkComment = string.Empty; @@ -3724,8 +3669,8 @@ private void SyncTimestampDisplay () private void SyncTimestampDisplay (int lineNum) { _timeShiftSyncLine = lineNum; - _timeShiftSyncTimerEvent.Set(); - _timeShiftSyncWakeupEvent.Set(); + _ = _timeShiftSyncTimerEvent.Set(); + _ = _timeShiftSyncWakeupEvent.Set(); } [SupportedOSPlatform("windows")] @@ -5285,6 +5230,7 @@ private void BookmarkComment (Bookmark bookmark) { Comment = bookmark.Text }; + if (dlg.ShowDialog() == DialogResult.OK) { bookmark.Text = dlg.Comment; @@ -6432,7 +6378,7 @@ public IColumn GetCellValue (int rowIndex, int columnIndex) return Column.EmptyColumn; } - public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) + public void CellPainting (bool focused, int rowIndex, DataGridViewCellPaintingEventArgs e) { if (rowIndex < 0 || e.ColumnIndex < 0) { @@ -6449,7 +6395,12 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); + if (e.CellStyle.SelectionForeColor != Color.White) + { + e.CellStyle.SelectionForeColor = PaintHelper.GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); + } + + using var brush = PaintHelper.GetBrushForFocusedControl(focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); } else @@ -6464,15 +6415,16 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV } else { - PaintCell(e, gridView, false, entry); + PaintCell(e, entry); } if (e.ColumnIndex == 0) { if (_bookmarkProvider.IsBookmarkAtLine(rowIndex)) { - Rectangle r; // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); - r = e.CellBounds; + //keeping this comment, because it's the original code + // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); + var r = e.CellBounds; r.Inflate(-2, -2); using var brush = new SolidBrush(BookmarkColor); e.Graphics.FillRectangle(brush, r); @@ -6502,7 +6454,7 @@ public void CellPainting (BufferedDataGridView gridView, int rowIndex, DataGridV public void OnDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) { var gridView = (BufferedDataGridView)sender; - CellPainting(gridView, e.RowIndex, e); + CellPainting(gridView.Focused, e.RowIndex, e); } /// diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs index ea2fa9f8..94b5c5c4 100644 --- a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs @@ -245,7 +245,7 @@ private void OnPatternHitsDataGridViewCellPainting (object sender, DataGridViewC { var gridView = (BufferedDataGridView)sender; var rowIndex = GetLineForHitGrid(e.RowIndex); - _logWindow.CellPainting(gridView, rowIndex, e); + _logWindow.CellPainting(gridView.Focused, rowIndex, e); } } @@ -314,7 +314,7 @@ private void OnContentDataGridViewCellPainting (object sender, DataGridViewCellP var gridView = (BufferedDataGridView)sender; var rowIndex = GetLineForContentGrid(e.RowIndex); - _logWindow.CellPainting(gridView, rowIndex, e); + _logWindow.CellPainting(gridView.Focused, rowIndex, e); } private void OnContentDataGridViewCellMouseDoubleClick (object sender, DataGridViewCellMouseEventArgs e) diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs index 791e6797..9c91fce3 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs @@ -1,15 +1,11 @@ +using System.Globalization; + using LogExpert.Core.Callback; using LogExpert.Core.Classes; using LogExpert.Core.Interface; using NLog; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; - namespace LogExpert.UI.Controls.LogWindow; internal class TimeSpreadCalculator @@ -39,10 +35,8 @@ internal class TimeSpreadCalculator private DateTime _endTimestamp; private int _lineCount; private int _maxDiff; - private TimeSpan _maxSpan; private bool _shouldStop; - private CancellationTokenSource cts = new(); - + private readonly CancellationTokenSource _cts = new(); private DateTime _startTimestamp; private bool _timeMode = true; @@ -54,28 +48,20 @@ internal class TimeSpreadCalculator #region cTor - public TimeSpreadCalculator(ILogWindow logWindow) + public TimeSpreadCalculator (ILogWindow logWindow) { _logWindow = logWindow; _callback = new ColumnizerCallback(_logWindow); - Task.Run(WorkerFx, cts.Token); + _ = Task.Run(WorkerFx, _cts.Token); } #endregion - #region Delegates - - public delegate void CalcDoneEventHandler(object sender, EventArgs e); - - public delegate void StartCalcEventHandler(object sender, EventArgs e); - - #endregion - #region Events - public event CalcDoneEventHandler CalcDone; - public event StartCalcEventHandler StartCalc; + public EventHandler CalcDone; + public EventHandler StartCalc; #endregion @@ -89,8 +75,8 @@ public bool Enabled _enabled = value; if (_enabled) { - _calcEvent.Set(); - _lineCountEvent.Set(); + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); } } } @@ -103,8 +89,8 @@ public bool TimeMode _timeMode = value; if (_enabled) { - _calcEvent.Set(); - _lineCountEvent.Set(); + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); } } } @@ -129,8 +115,9 @@ public int Contrast } else { - CalcValuesViaLines(_timePerLine, _maxSpan); + _ = CalcValuesViaLines(_timePerLine); } + OnCalcDone(EventArgs.Empty); } @@ -143,30 +130,31 @@ public int Contrast #region Public methods - public void Stop() + public void Stop () { _shouldStop = true; - _lineCountEvent.Set(); - cts.Cancel(); + _ = _lineCountEvent.Set(); + + _cts.Cancel(); } - public void SetLineCount(int count) + public void SetLineCount (int count) { _lineCount = count; if (Enabled) { - _calcEvent.Set(); - _lineCountEvent.Set(); + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); } } - public void SetDisplayHeight(int height) + public void SetDisplayHeight (int height) { _displayHeight = height; if (Enabled) { - _calcEvent.Set(); - _lineCountEvent.Set(); + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); } } @@ -174,7 +162,7 @@ public void SetDisplayHeight(int height) #region Private Methods - private void WorkerFx() + private void WorkerFx () { //Thread.CurrentThread.Name = "TimeSpreadCalculator Worker"; //Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; @@ -182,7 +170,7 @@ private void WorkerFx() while (!_shouldStop) { // wait for wakeup - _lineCountEvent.WaitOne(); + _ = _lineCountEvent.WaitOne(); while (!_shouldStop) { @@ -200,17 +188,19 @@ private void WorkerFx() { DoCalc(); } + break; } _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator: signalled. no calc."); - _calcEvent.Reset(); + _ = _calcEvent.Reset(); } - _lineCountEvent.Reset(); + + _ = _lineCountEvent.Reset(); } } - private void DoCalc() + private void DoCalc () { OnStartCalc(EventArgs.Empty); _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() begin"); @@ -231,20 +221,13 @@ private void DoCalc() if (_startTimestamp != DateTime.MinValue && _endTimestamp != DateTime.MinValue) { - TimeSpan overallSpan = _endTimestamp - _startTimestamp; + var overallSpan = _endTimestamp - _startTimestamp; var overallSpanMillis = (int)(overallSpan.Ticks / TimeSpan.TicksPerMillisecond); _timePerLine = (int)Math.Round(overallSpanMillis / (double)_lineCount); - DateTime oldTime = _logWindow.GetTimestampForLineForward(ref lineNum, false); - int step; - - if (_lineCount > _displayHeight) - { - step = (int)Math.Round(_lineCount / (double)_displayHeight); - } - else - { - step = 1; - } + var oldTime = _logWindow.GetTimestampForLineForward(ref lineNum, false); + var step = _lineCount > _displayHeight + ? (int)Math.Round(_lineCount / (double)_displayHeight) + : 1; _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() collecting data for {0} lines with step size {1}", lastLineNum, step); @@ -255,10 +238,10 @@ private void DoCalc() for (var i = lineNum; i < lastLineNum; i += step) { var currLineNum = i; - DateTime time = _logWindow.GetTimestampForLineForward(ref currLineNum, false); + var time = _logWindow.GetTimestampForLineForward(ref currLineNum, false); if (time != DateTime.MinValue) { - TimeSpan span = time - oldTime; + var span = time - oldTime; maxList.Add(span); timePerLineSum += (int)(span.Ticks / TimeSpan.TicksPerMillisecond); newDiffList.Add(new SpreadEntry(i, 0, time)); @@ -270,14 +253,13 @@ private void DoCalc() if (maxList.Count > 3) { maxList.Sort(); - _maxSpan = maxList[^3]; } lock (_diffListLock) { DiffList = newDiffList; _timePerLine = (int)Math.Round(timePerLineSum / ((double)(lastLineNum + 1) / step)); - CalcValuesViaLines(_timePerLine, _maxSpan); + _ = CalcValuesViaLines(_timePerLine); OnCalcDone(EventArgs.Empty); _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() end"); } @@ -285,7 +267,7 @@ private void DoCalc() } //TODO Refactor this method - private void DoCalc_via_Time() + private void DoCalc_via_Time () { OnStartCalc(EventArgs.Empty); _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc_via_Time() begin"); @@ -304,25 +286,16 @@ private void DoCalc_via_Time() if (_startTimestamp != DateTime.MinValue && _endTimestamp != DateTime.MinValue) { - TimeSpan overallSpan = _endTimestamp - _startTimestamp; + var overallSpan = _endTimestamp - _startTimestamp; var overallSpanMillis = overallSpan.Ticks / TimeSpan.TicksPerMillisecond; //int timePerLine = (int)Math.Round((double)overallSpanMillis / (double)this.lineCount); - long step; - - if (overallSpanMillis > _displayHeight) - { - step = (long)Math.Round(overallSpanMillis / (double)_displayHeight); - } - else - { - step = 1; - } + var step = overallSpanMillis > _displayHeight ? (long)Math.Round(overallSpanMillis / (double)_displayHeight) : 1; _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc_via_Time() time range is {0} ms", overallSpanMillis); lineNum = 0; - DateTime searchTimeStamp = _startTimestamp; + var searchTimeStamp = _startTimestamp; var oldLineNum = lineNum; var loopCount = 0; var lineDiffSum = 0; @@ -395,17 +368,17 @@ private void DoCalc_via_Time() } } - private DateTime CalcValuesViaLines(int timePerLine, TimeSpan maxSpan) + private DateTime CalcValuesViaLines (int timePerLine) { - DateTime oldTime = DateTime.MinValue; + var oldTime = DateTime.MinValue; if (DiffList.Count > 0) { oldTime = DiffList[0].Timestamp; - foreach (SpreadEntry entry in DiffList) + foreach (var entry in DiffList) { - TimeSpan span = entry.Timestamp - oldTime; + var span = entry.Timestamp - oldTime; double diffFromAverage = (int)(span.Ticks / TimeSpan.TicksPerMillisecond) - timePerLine; if (diffFromAverage < 0) @@ -422,9 +395,9 @@ private DateTime CalcValuesViaLines(int timePerLine, TimeSpan maxSpan) return oldTime; } - private void CalcValuesViaTime(int maxDiff, double average) + private void CalcValuesViaTime (int maxDiff, double average) { - foreach (SpreadEntry entry in DiffList) + foreach (var entry in DiffList) { var lineDiff = entry.Diff; var diffFromAverage = entry.Diff - average; @@ -433,6 +406,7 @@ private void CalcValuesViaTime(int maxDiff, double average) { diffFromAverage = 0; } + var value = (int)(diffFromAverage / maxDiff * _contrast); entry.Value = 255 - value; @@ -440,12 +414,12 @@ private void CalcValuesViaTime(int maxDiff, double average) } } - private void OnCalcDone(EventArgs e) + private void OnCalcDone (EventArgs e) { CalcDone?.Invoke(this, e); } - private void OnStartCalc(EventArgs e) + private void OnStartCalc (EventArgs e) { StartCalc?.Invoke(this, e); } diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs index 4a0cc7fb..48595990 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs @@ -1,4 +1,4 @@ -namespace LogExpert.UI.Controls.LogWindow +namespace LogExpert.UI.Controls.LogWindow { partial class TimeSpreadingControl { @@ -17,6 +17,7 @@ protected override void Dispose(bool disposing) { components.Dispose(); } + base.Dispose(disposing); } diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs index ad0150e9..41c94c8d 100644 --- a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs @@ -12,7 +12,7 @@ namespace LogExpert.UI.Controls.LogWindow; [SupportedOSPlatform("windows")] internal partial class TimeSpreadingControl : UserControl { - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); #region Fields @@ -45,13 +45,11 @@ public TimeSpreadingControl () #region Delegates - public delegate void LineSelectedEventHandler (object sender, SelectLineEventArgs e); - #endregion #region Events - public event LineSelectedEventHandler LineSelected; + public EventHandler LineSelected; #endregion @@ -82,11 +80,10 @@ protected override void OnPaint (PaintEventArgs e) { if (DesignMode) { - Brush bgBrush = new SolidBrush(Color.FromKnownColor(KnownColor.LightSkyBlue)); + using var bgBrush = new SolidBrush(Color.FromKnownColor(KnownColor.LightSkyBlue)); var rect = ClientRectangle; rect.Inflate(0, -_edgeOffset); e.Graphics.FillRectangle(bgBrush, rect); - bgBrush.Dispose(); } else { @@ -107,7 +104,7 @@ private SpreadEntry GetEntryForMouse (MouseEventArgs e) { y = 0; } - else if (y >= ClientRectangle.Height - _edgeOffset * 3) + else if (y >= ClientRectangle.Height - (_edgeOffset * 3)) { y = list.Count - 1; } @@ -153,7 +150,7 @@ private void OnTimeSpreadCalcCalcDone (object sender, EventArgs e) { Invalidate(); var rect = ClientRectangle; - rect.Size = new Size(rect.Width, rect.Height - _edgeOffset * 3); + rect.Size = new Size(rect.Width, rect.Height - (_edgeOffset * 3)); if (rect.Height < 1) { @@ -161,10 +158,9 @@ private void OnTimeSpreadCalcCalcDone (object sender, EventArgs e) } _bitmap = new Bitmap(rect.Width, rect.Height); - var gfx = Graphics.FromImage(_bitmap); - Brush bgBrush = new SolidBrush(BackColor); + using var gfx = Graphics.FromImage(_bitmap); + using var bgBrush = new SolidBrush(BackColor); gfx.FillRectangle(bgBrush, rect); - bgBrush.Dispose(); var list = TimeSpreadCalc.DiffList; int step; @@ -199,10 +195,8 @@ private void OnTimeSpreadCalcCalcDone (object sender, EventArgs e) color = 0; } - Brush brush = new SolidBrush(Color.FromArgb(color, ForeColor)); - //Brush brush = new SolidBrush(Color.FromArgb(color, color, color, color)); + using var brush = new SolidBrush(Color.FromArgb(color, ForeColor)); gfx.FillRectangle(brush, fillRect); - brush.Dispose(); fillRect.Offset(0, _rectHeight); } } @@ -217,7 +211,7 @@ private void OnTimeSpreadCalcStartCalc (object sender, EventArgs e) { Invalidate(); var rect = ClientRectangle; - rect.Size = new Size(rect.Width, rect.Height - _edgeOffset * 3); + rect.Size = new Size(rect.Width, rect.Height - (_edgeOffset * 3)); if (rect.Height < 1) { @@ -227,8 +221,8 @@ private void OnTimeSpreadCalcStartCalc (object sender, EventArgs e) //this.bmp = new Bitmap(rect.Width, rect.Height); var gfx = Graphics.FromImage(_bitmap); - Brush bgBrush = new SolidBrush(BackColor); - Brush fgBrush = new SolidBrush(ForeColor); + using var bgBrush = new SolidBrush(BackColor); + using var fgBrush = new SolidBrush(ForeColor); //gfx.FillRectangle(bgBrush, rect); StringFormat format = new(StringFormatFlags.DirectionVertical | StringFormatFlags.NoWrap) @@ -240,9 +234,6 @@ private void OnTimeSpreadCalcStartCalc (object sender, EventArgs e) RectangleF rectf = new(rect.Left, rect.Top, rect.Width, rect.Height); gfx.DrawString("Calculating time spread view...", Font, fgBrush, rectf, format); - - bgBrush.Dispose(); - fgBrush.Dispose(); } BeginInvoke(new MethodInvoker(Refresh)); @@ -252,7 +243,7 @@ private void OnTimeSpreadingControlSizeChanged (object sender, EventArgs e) { if (TimeSpreadCalc != null) { - _displayHeight = ClientRectangle.Height - _edgeOffset * 3; + _displayHeight = ClientRectangle.Height - (_edgeOffset * 3); TimeSpreadCalc.SetDisplayHeight(_displayHeight); } } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs index fa1e3b01..88d846e0 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs @@ -412,13 +412,18 @@ private void OnHighlightListBoxDrawItem (object sender, DrawItemEventArgs e) var entry = (HighlightEntry)listBoxHighlight.Items[e.Index]; Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - if ((e.State & DrawItemState.Selected) != DrawItemState.Selected) + var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected; + + using var brush = selected + ? new SolidBrush(entry.BackgroundColor) + : new SolidBrush(entry.ForegroundColor); + + if (selected) { - e.Graphics.FillRectangle(new SolidBrush(entry.BackgroundColor), rectangle); + e.Graphics.FillRectangle(brush, rectangle); } - e.Graphics.DrawString(entry.SearchText, e.Font, new SolidBrush(entry.ForegroundColor), - new PointF(rectangle.Left, rectangle.Top)); + e.Graphics.DrawString(entry.SearchText, e.Font, brush, new PointF(rectangle.Left, rectangle.Top)); e.DrawFocusRectangle(); } diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index 0454c5cd..07401790 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -39,6 +39,11 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri if (e.State.HasFlag(DataGridViewElementStates.Selected)) { + if (e.CellStyle.SelectionForeColor != Color.White) + { + e.CellStyle.SelectionForeColor = GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); + } + using var brush = GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); } @@ -62,12 +67,12 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri var bookmark = logPaintCtx.GetBookmarkForLine(rowIndex); if (bookmark != null) { - Rectangle r; // = new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); - r = e.CellBounds; + //keep this is the old initialisation of r => new Rectangle(e.CellBounds.Left + 2, e.CellBounds.Top + 2, 6, 6); + var r = e.CellBounds; r.Inflate(-2, -2); - Brush brush = new SolidBrush(logPaintCtx.BookmarkColor); + using var brush = new SolidBrush(logPaintCtx.BookmarkColor); e.Graphics.FillRectangle(brush, r); - brush.Dispose(); + if (bookmark.Text.Length > 0) { StringFormat format = new() @@ -76,10 +81,9 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri Alignment = StringAlignment.Center }; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - var font = logPaintCtx.MonospacedFont; + using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); + using var font = logPaintCtx.MonospacedFont; e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), format); - brush2.Dispose(); } } } @@ -124,7 +128,7 @@ public static DataGridViewTextBoxColumn CreateMarkerColumn () { DataGridViewTextBoxColumn markerColumn = new() { - HeaderText = "", + HeaderText = string.Empty, AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, Resizable = DataGridViewTriState.False, DividerWidth = 1, @@ -233,6 +237,50 @@ private static void AutoResizeColumns (BufferedDataGridView gridView, bool setLa } } + /// + /// This returns Black or White based on the color that is given + /// If the color is smaller than 128 it means its a darker color and white should be the fore color, + /// if the color is bigger than 128 it means its a lighter color and black should be the fore color + /// + /// lighter or darker back color + /// White or Black based on the given back color + public static Color GetForeColorBasedOnBackColor (Color backColor) + { + var isSelectionBackColorDark = (backColor.R * 0.2126) + (backColor.G * 0.7152) + (backColor.B * 0.0722) < 255 / 2; + + return isSelectionBackColorDark ? Color.White : Color.Black; + } + + [SupportedOSPlatform("windows")] + public static DataGridViewCellStyle GetDataGridViewCellStyle () + { + return new() + { + Alignment = DataGridViewContentAlignment.MiddleLeft, + BackColor = SystemColors.Window, + Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0), + ForeColor = Color.White, + SelectionBackColor = SystemColors.Highlight, + SelectionForeColor = GetForeColorBasedOnBackColor(SystemColors.Highlight), + WrapMode = DataGridViewTriState.False + }; + } + + [SupportedOSPlatform("windows")] + public static DataGridViewCellStyle GetDataGridDefaultRowStyle () + { + return new DataGridViewCellStyle + { + Alignment = DataGridViewContentAlignment.MiddleLeft, + BackColor = SystemColors.Window, + Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0), + ForeColor = Color.Black, + SelectionBackColor = SystemColors.Highlight, + SelectionForeColor = GetForeColorBasedOnBackColor(SystemColors.Highlight), + WrapMode = DataGridViewTriState.False + }; + } + [SupportedOSPlatform("windows")] public static void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, bool setLastColumnWidht, int lastColumnWidth) { @@ -266,26 +314,38 @@ public static Rectangle BorderWidths (DataGridViewAdvancedBorderStyle advancedBo { Rectangle rect = new() { - X = advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1 + X = advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None + ? 0 + : 1 }; + if (advancedBorderStyle.Left is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) { rect.X++; } - rect.Y = advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; + rect.Y = advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None + ? 0 + : 1; + if (advancedBorderStyle.Top is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) { rect.Y++; } - rect.Width = advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; + rect.Width = advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None + ? 0 + : 1; + if (advancedBorderStyle.Right is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) { rect.Width++; } - rect.Height = advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; + rect.Height = advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None + ? 0 + : 1; + if (advancedBorderStyle.Bottom is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) { @@ -334,8 +394,8 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr { SearchText = column.FullValue, //TODO change to white if the background color is darker - ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, + ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), IsRegEx = false, IsCaseSensitive = false, IsLedSwitch = false, @@ -351,13 +411,12 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr } } - var leftPad = e.CellStyle.Padding.Left; - RectangleF rect = new(e.CellBounds.Left + leftPad, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height); var borderWidths = BorderWidths(e.AdvancedBorderStyle); var valBounds = e.CellBounds; valBounds.Offset(borderWidths.X, borderWidths.Y); valBounds.Width -= borderWidths.Right; valBounds.Height -= borderWidths.Bottom; + if (e.CellStyle.Padding != Padding.Empty) { valBounds.Offset(e.CellStyle.Padding.Left, e.CellStyle.Padding.Top); @@ -383,16 +442,15 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr var wordPos = valBounds.Location; Size proposedSize = new(valBounds.Width, valBounds.Height); - var r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); e.Graphics.SetClip(e.CellBounds); foreach (var matchEntry in matchList) { - var font = matchEntry != null && matchEntry.HighlightEntry.IsBold + using var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? logPaintCtx.BoldFont : logPaintCtx.NormalFont; - Brush bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty + using var bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty ? new SolidBrush(matchEntry.HighlightEntry.BackgroundColor) : null; @@ -428,11 +486,9 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr TextRenderer.DrawText(e.Graphics, matchWord, font, wordRect, foreColor, flags); wordPos.Offset(wordSize.Width, 0); - bgBrush?.Dispose(); } } - /// /// Builds a list of HilightMatchEntry objects. A HilightMatchEntry spans over a region that is painted with the same foreground and /// background colors. @@ -480,24 +536,26 @@ private static IList MergeHighlightMatchEntries (IList Date: Mon, 23 Jun 2025 13:07:03 +0200 Subject: [PATCH 22/26] small optimizations --- src/LogExpert.UI/Controls/LogWindow/LogWindow.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index e41c1b17..f0024bed 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -3208,11 +3208,12 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) { CurrentColumnizer = columnizer; _freezeStateMap.Clear(); + if (_logFileReader != null) { - if (CurrentColumnizer is IPreProcessColumnizer) + if (CurrentColumnizer is IPreProcessColumnizer columnizer1) { - _logFileReader.PreProcessColumnizer = (IPreProcessColumnizer)CurrentColumnizer; + _logFileReader.PreProcessColumnizer = columnizer1; } else { @@ -3237,7 +3238,7 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) // Reload when previous columnizer was PreProcess and current is not, and vice versa. // When the current columnizer is a preProcess columnizer, reload in every case. - if (CurrentColumnizer is IPreProcessColumnizer != oldColumnizerIsPreProcess || + if ((CurrentColumnizer is IPreProcessColumnizer) != oldColumnizerIsPreProcess || CurrentColumnizer is IPreProcessColumnizer) { //forcedColumnizer = currentColumnizer; // prevent Columnizer selection on SetGuiAfterReload() @@ -3390,8 +3391,7 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Highligh | TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.NoPadding | TextFormatFlags.VerticalCenter - | TextFormatFlags.TextBoxControl - ; + | TextFormatFlags.TextBoxControl; // | TextFormatFlags.VerticalCenter // | TextFormatFlags.TextBoxControl @@ -6395,9 +6395,9 @@ public void CellPainting (bool focused, int rowIndex, DataGridViewCellPaintingEv if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (e.CellStyle.SelectionForeColor != Color.White) + if (e.CellStyle.ForeColor != Color.White) { - e.CellStyle.SelectionForeColor = PaintHelper.GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); + e.CellStyle.ForeColor = PaintHelper.GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); } using var brush = PaintHelper.GetBrushForFocusedControl(focused, e.CellStyle.SelectionBackColor); @@ -6490,11 +6490,13 @@ public HighlightEntry FindHighlightEntry (ITextValue line, bool noWordMatches) { continue; } + if (CheckHighlightEntryMatch(entry, line)) { return entry; } } + return null; } } From 6b076cb1ac52336ca8f793fb380e727fc442d8aa Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 23 Jun 2025 13:17:15 +0200 Subject: [PATCH 23/26] finally fixing the wrong text color problem --- src/LogExpert.UI/Controls/LogWindow/LogWindow.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index f0024bed..ef901a46 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -3418,13 +3418,20 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Highligh Rectangle wordRect = new(wordPos, wordSize); var foreColor = matchEntry.HighlightEntry.ForegroundColor; - if (e.State.HasFlag(DataGridViewElementStates.Selected)) + if (!e.State.HasFlag(DataGridViewElementStates.Selected)) { if (bgBrush != null && !matchEntry.HighlightEntry.NoBackground) { e.Graphics.FillRectangle(bgBrush, wordRect); } } + else + { + if (foreColor.Equals(Color.Black)) + { + foreColor = Color.White; + } + } TextRenderer.DrawText(e.Graphics, matchWord, font, wordRect, foreColor, flags); wordPos.Offset(wordSize.Width, 0); From f9b7b42e455722bcabf480b956b6d6ffb3911a76 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 23 Jun 2025 13:34:27 +0200 Subject: [PATCH 24/26] wrong HighlightDialog dialog --- .../Dialogs/LogTabWindow/HighlightDialog.cs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs index 88d846e0..c48a91cd 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs @@ -6,6 +6,7 @@ using LogExpert.Core.Interface; using LogExpert.UI.Controls; using LogExpert.UI.Dialogs; +using LogExpert.UI.Entities; using NLog; @@ -412,18 +413,16 @@ private void OnHighlightListBoxDrawItem (object sender, DrawItemEventArgs e) var entry = (HighlightEntry)listBoxHighlight.Items[e.Index]; Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected; + var selected = e.State.HasFlag(DrawItemState.Selected); - using var brush = selected - ? new SolidBrush(entry.BackgroundColor) - : new SolidBrush(entry.ForegroundColor); + var forgroundColor = selected ? PaintHelper.GetForeColorBasedOnBackColor(entry.ForegroundColor) : entry.ForegroundColor; - if (selected) + if (!selected) { - e.Graphics.FillRectangle(brush, rectangle); + e.Graphics.FillRectangle(new SolidBrush(entry.BackgroundColor), rectangle); } - e.Graphics.DrawString(entry.SearchText, e.Font, brush, new PointF(rectangle.Left, rectangle.Top)); + e.Graphics.DrawString(entry.SearchText, e.Font, new SolidBrush(forgroundColor), new PointF(rectangle.Left, rectangle.Top)); e.DrawFocusRectangle(); } From 32eeda04f7a8567178b325484971df2323d0af66 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Mon, 23 Jun 2025 13:37:40 +0200 Subject: [PATCH 25/26] removed no longer needed debug code --- src/LogExpert.UI/Controls/LogWindow/LogWindow.cs | 10 ---------- .../Dialogs/LogTabWindow/HighlightDialog.cs | 5 +++-- src/LogExpert.UI/Entities/PaintHelper.cs | 5 ----- 3 files changed, 3 insertions(+), 17 deletions(-) diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index ef901a46..5496ffcc 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -955,11 +955,6 @@ private void OnFilterGridViewCellPainting (object sender, DataGridViewCellPainti if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (e.CellStyle.SelectionForeColor != Color.White) - { - e.CellStyle.SelectionForeColor = PaintHelper.GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); - } - using var brush = PaintHelper.GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); } @@ -6402,11 +6397,6 @@ public void CellPainting (bool focused, int rowIndex, DataGridViewCellPaintingEv if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (e.CellStyle.ForeColor != Color.White) - { - e.CellStyle.ForeColor = PaintHelper.GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); - } - using var brush = PaintHelper.GetBrushForFocusedControl(focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs index c48a91cd..adadc7da 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs @@ -414,8 +414,9 @@ private void OnHighlightListBoxDrawItem (object sender, DrawItemEventArgs e) Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); var selected = e.State.HasFlag(DrawItemState.Selected); - - var forgroundColor = selected ? PaintHelper.GetForeColorBasedOnBackColor(entry.ForegroundColor) : entry.ForegroundColor; + var forgroundColor = selected + ? PaintHelper.GetForeColorBasedOnBackColor(entry.ForegroundColor) + : entry.ForegroundColor; if (!selected) { diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index 07401790..acefeab5 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -39,11 +39,6 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (e.CellStyle.SelectionForeColor != Color.White) - { - e.CellStyle.SelectionForeColor = GetForeColorBasedOnBackColor(e.CellStyle.SelectionBackColor); - } - using var brush = GetBrushForFocusedControl(gridView.Focused, e.CellStyle.SelectionBackColor); e.Graphics.FillRectangle(brush, e.CellBounds); } From 5c05a5084a0e0ac3c89830e2a1f1862ca1bde024 Mon Sep 17 00:00:00 2001 From: Hirogen Date: Wed, 25 Jun 2025 17:03:20 +0200 Subject: [PATCH 26/26] review comments --- src/ColumnizerLib/ITextValue.cs | 2 +- .../Controls/LogWindow/LogWindow.cs | 22 ++--- .../Dialogs/LogTabWindow/HighlightDialog.cs | 20 +++-- src/LogExpert.UI/Entities/PaintHelper.cs | 90 +++++-------------- 4 files changed, 45 insertions(+), 89 deletions(-) diff --git a/src/ColumnizerLib/ITextValue.cs b/src/ColumnizerLib/ITextValue.cs index 80b36fe9..b072fb91 100644 --- a/src/ColumnizerLib/ITextValue.cs +++ b/src/ColumnizerLib/ITextValue.cs @@ -1,4 +1,4 @@ -namespace LogExpert; +namespace LogExpert; public interface ITextValue { diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs index 5496ffcc..0c8488a3 100644 --- a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -2267,7 +2267,6 @@ private void MeasureItem (object sender, MeasureItemEventArgs e) [SupportedOSPlatform("windows")] private void CreateDefaultViewStyle () { - dataGridView.DefaultCellStyle = PaintHelper.GetDataGridViewCellStyle(); filterGridView.DefaultCellStyle = PaintHelper.GetDataGridViewCellStyle(); dataGridView.RowsDefaultCellStyle = PaintHelper.GetDataGridDefaultRowStyle(); @@ -3206,14 +3205,9 @@ private void SetColumnizerInternal (ILogLineColumnizer columnizer) if (_logFileReader != null) { - if (CurrentColumnizer is IPreProcessColumnizer columnizer1) - { - _logFileReader.PreProcessColumnizer = columnizer1; - } - else - { - _logFileReader.PreProcessColumnizer = null; - } + _logFileReader.PreProcessColumnizer = CurrentColumnizer is IPreProcessColumnizer columnizer1 + ? columnizer1 + : null; } // always reload when choosing XML columnizers @@ -3413,18 +3407,18 @@ private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, Highligh Rectangle wordRect = new(wordPos, wordSize); var foreColor = matchEntry.HighlightEntry.ForegroundColor; - if (!e.State.HasFlag(DataGridViewElementStates.Selected)) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (bgBrush != null && !matchEntry.HighlightEntry.NoBackground) + if (foreColor.Equals(Color.Black)) { - e.Graphics.FillRectangle(bgBrush, wordRect); + foreColor = Color.White; } } else { - if (foreColor.Equals(Color.Black)) + if (bgBrush != null && !matchEntry.HighlightEntry.NoBackground) { - foreColor = Color.White; + e.Graphics.FillRectangle(bgBrush, wordRect); } } diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs index adadc7da..d772f4da 100644 --- a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs @@ -413,17 +413,23 @@ private void OnHighlightListBoxDrawItem (object sender, DrawItemEventArgs e) var entry = (HighlightEntry)listBoxHighlight.Items[e.Index]; Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - var selected = e.State.HasFlag(DrawItemState.Selected); - var forgroundColor = selected - ? PaintHelper.GetForeColorBasedOnBackColor(entry.ForegroundColor) - : entry.ForegroundColor; + SolidBrush foregroundBrush; - if (!selected) + if (e.State.HasFlag(DrawItemState.Selected)) { - e.Graphics.FillRectangle(new SolidBrush(entry.BackgroundColor), rectangle); + foregroundBrush = new SolidBrush(PaintHelper.GetForeColorBasedOnBackColor(entry.ForegroundColor)); + } + else + { + using var backgroundBrush = new SolidBrush(entry.BackgroundColor); + e.Graphics.FillRectangle(backgroundBrush, rectangle); + foregroundBrush = new SolidBrush(entry.ForegroundColor); } - e.Graphics.DrawString(entry.SearchText, e.Font, new SolidBrush(forgroundColor), new PointF(rectangle.Left, rectangle.Top)); + using (foregroundBrush) + { + e.Graphics.DrawString(entry.SearchText, e.Font, foregroundBrush, new PointF(rectangle.Left, rectangle.Top)); + } e.DrawFocusRectangle(); } diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs index acefeab5..ed0c2283 100644 --- a/src/LogExpert.UI/Entities/PaintHelper.cs +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -90,24 +90,7 @@ public static void CellPainting (ILogPaintContextUI logPaintCtx, BufferedDataGri public static Color GetBackColorFromHighlightEntry (HighlightEntry? entry) { - var bgColor = Color.White; - - if (!DebugOptions.DisableWordHighlight) - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - else - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - - return bgColor; + return entry?.BackgroundColor ?? Color.White; } [SupportedOSPlatform("windows")] @@ -305,52 +288,24 @@ public static void ApplyDataGridViewPrefs (BufferedDataGridView dataGridView, bo } [SupportedOSPlatform("windows")] - public static Rectangle BorderWidths (DataGridViewAdvancedBorderStyle advancedBorderStyle) + public static Rectangle BorderWidths (DataGridViewAdvancedBorderStyle style) { - Rectangle rect = new() - { - X = advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None - ? 0 - : 1 - }; - - if (advancedBorderStyle.Left is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.X++; - } - - rect.Y = advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None - ? 0 - : 1; - - if (advancedBorderStyle.Top is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.Y++; - } - - rect.Width = advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None - ? 0 - : 1; - - if (advancedBorderStyle.Right is DataGridViewAdvancedCellBorderStyle.OutsetDouble or DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.Width++; - } - - rect.Height = advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None - ? 0 - : 1; + return new Rectangle( + GetBorderSize(style.Left), + GetBorderSize(style.Top), + GetBorderSize(style.Right), + GetBorderSize(style.Bottom)); + } - if (advancedBorderStyle.Bottom is DataGridViewAdvancedCellBorderStyle.OutsetDouble or - DataGridViewAdvancedCellBorderStyle.InsetDouble) + [SupportedOSPlatform("windows")] + private static int GetBorderSize (DataGridViewAdvancedCellBorderStyle borderStyle) + { + return borderStyle switch { - rect.Height++; - } - - //rect.Width += this.owningColumn.DividerWidth; - //rect.Height += this.owningRow.DividerHeight; - - return rect; + DataGridViewAdvancedCellBorderStyle.None => 0, + DataGridViewAdvancedCellBorderStyle.InsetDouble or DataGridViewAdvancedCellBorderStyle.OutsetDouble => 2, + _ => 1 + }; } #endregion @@ -366,9 +321,10 @@ private static void PaintCell (ILogPaintContextUI logPaintCtx, DataGridViewCellP [SupportedOSPlatform("windows")] private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, BufferedDataGridView gridView, bool noBackgroundFill, HighlightEntry groundEntry) { + //TODO Refactor if possible since Column is ITextValue var value = e.Value ?? string.Empty; - var matchList = logPaintCtx.FindHighlightMatches(value as ILogLine); + var matchList = logPaintCtx.FindHighlightMatches(value as ITextValue); // too many entries per line seem to cause problems with the GDI while (matchList.Count > 50) { @@ -463,18 +419,18 @@ private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGr Rectangle wordRect = new(wordPos, wordSize); var foreColor = matchEntry.HighlightEntry.ForegroundColor; - if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) + if (e.State.HasFlag(DataGridViewElementStates.Selected)) { - if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) + if (foreColor.Equals(Color.Black)) { - e.Graphics.FillRectangle(bgBrush, wordRect); + foreColor = Color.White; } } else { - if (foreColor.Equals(Color.Black)) + if (!noBackgroundFill && bgBrush != null && !matchEntry.HighlightEntry.NoBackground) { - foreColor = Color.White; + e.Graphics.FillRectangle(bgBrush, wordRect); } }